text:
export { FiltersArray_BiasesArray };

import * as Pool from "../../util/Pool.js";
import * as Recyclable from "../../util/Recyclable.js";
import * as FloatValue from "../../Unpacker/FloatValue.js";
import * as ValueDesc from "../../Unpacker/ValueDesc.js";
import * as Weights from "../../Unpacker/Weights.js";
import * as BoundsArraySet from "../BoundsArraySet.js";
import { ChannelPartInfo, FiltersBiasesPartInfo } from  "./Pointwise_ChannelPartInfo.js";

/**
 * Extract pointwise convolution filters and biases.
 *
 *
 * @member {number} weightElementOffsetBegin
 *   The position which is started (inclusive) to extract from inputWeightArray by init().
 *
 * @member {number} weightElementOffsetEnd
 *   The position which is ended to (non-inclusive) extract from inputWeightArray by init(). Where to extract next weights.
 * Only meaningful if .init() returns true.
 *
 * @member {BoundsArraySet.Pointwise} boundsArraySet
 *   The element value bounds (per channel) of this pointwise convolution.
 *
 * @member {number} outputChannelCount
 *   The output channel count of this pointwise convolutiuon.
 *     - Usually, if ( outputChannelCount == 0 ), it means no operation at all (i.e. bPointwise == bExisted == false ).
 *
 * @member {number} nPassThroughStyleId
 *   The pass-through style id (ValueDesc.PassThroughStyle.Singleton.Ids.Xxx) of this convolution. It only affect the channels
 * which need to be pass-through from input to output.
 *
 * @member {ValueDesc.Pointwise_HigherHalfDifferent} nHigherHalfDifferent
 *   - 0. If ( nHigherHalfDifferent == ValueDesc.Pointwise_HigherHalfDifferent.Singleton.Ids.NONE ), it is just a normal poitwise convolution.
 *         normal poitwise convolution.
 *
 *   - 1. If ( nHigherHalfDifferent == ValueDesc.Pointwise_HigherHalfDifferent.Singleton.Ids.HIGHER_HALF_COPY_LOWER_HALF__LOWER_HALF_PASS_THROUGH ):
 *         (i.e. bHigherHalfCopyLowerHalf_LowerHalfPassThrough),
 *         (for pointwise1 of ShuffleNetV2_ByMobileNetV1's head),
 *         the filters for the output channels between 0 and ( outputChannelCount_lowerHalf - 1 ) will just pass
 *         through the input to output. The filters for the output channels between ( outputChannelCount_lowerHalf )
 *         and ( outputChannelCount - 1 ) will just copy the input channels between 0 and ( outputChannelCount_lowerHalf - 1 ).
 *         In this case, it will always have no biases (no matter how bBias is).
 *
 *   - 2. If ( nHigherHalfDifferent == ValueDesc.Pointwise_HigherHalfDifferent.Singleton.Ids.HIGHER_HALF_COPY_LOWER_HALF ):
 *         (i.e. bHigherHalfCopyLowerHalf),
 *         (for pointwise1 of ShuffleNetV2_ByMobileNetV1's head),
 *         the filters for the output channels between ( outputChannelCount_lowerHalf ) and ( outputChannelCount - 1 ) will just copy
 *         the input channels between 0 and ( outputChannelCount_lowerHalf - 1 ).
 *
 *   - 3. If ( nHigherHalfDifferent == ValueDesc.Pointwise_HigherHalfDifferent.Singleton.Ids.HIGHER_HALF_ANOTHER_POINTWISE ):
 *         (i.e. bHigherHalfAnotherPointwise),
 *         (for pointwise2 of ShuffleNetV2_ByMobileNetV1's head),
 *         the filters for the input channels between 0 and ( inputChannelCount_lowerHalf - 1 ) are pointwise21, between
 *         ( inputChannelCount_lowerHalf ) and ( inputChannelCount - 1 ) are pointwise212. These two filters (and biases)
 *         will be extracted in sequence, but they will be combined into one larger filters (and biases). This makes these
 *         filters' (and biases') weights are arranged the same as pointwise2 of ShuffleNetV2_ByPointwise22's head. So that
 *         the same filters weights could be used in these two architectures for comparing performance and correctness.
 *
 *     - 3.1 If ( channelShuffler_outputGroupCount <= 0 ), (i.e. bHigherHalfAnotherPointwise).
 *           (Not used.)
 *
 *     - 3.2 If ( channelShuffler_outputGroupCount > 0 ), (i.e. bHigherHalfAnotherPointwiseShuffle).
 *           (for pointwise2 of ShuffleNetV2_ByMobileNetV1's head with channel shuffling)
 *           The output channels will be arranged just like applying channel shuffler on them.
 *
 *   - 4. If ( nHigherHalfDifferent == ValueDesc.Pointwise_HigherHalfDifferent.Singleton.Ids.HIGHER_HALF_PASS_THROUGH ):
 *        the filters for the output channels between ( outputChannelCount_lowerHalf )
 *        and ( outputChannelCount - 1 ) will just pass through the input to output.
 *
 *     - 4.1 If ( channelShuffler_outputGroupCount <= 0 ), (i.e. bHigherHalfPassThrough).
 *           (for pointwise1 of ShuffleNetV2_ByMobileNetV1's body/tail)
 *
 *     - 4.2 If ( channelShuffler_outputGroupCount > 0 ), (i.e. bHigherHalfPassThroughShuffle).
 *           (for pointwise2 of ShuffleNetV2_ByMobileNetV1's body/tail)
 *           The output channels will be arranged just like applying channel shuffler on them.
 *
 * @member {boolean} bHigherHalfDifferent
 *   It will be false, if ( nHigherHalfDifferent == ValueDesc.Pointwise_HigherHalfDifferent.Singleton.Ids.NONE ).
 *
 * @member {number} inputChannelCount_lowerHalf
 *   The lower half input channel count when ( bHigherHalfDifferent == true ). It is ignored when ( bHigherHalfDifferent == false ).
 *
 * @member {number} outputChannelCount_lowerHalf
 *   The lower half output channel count when ( bHigherHalfDifferent == true ). It is ignored when ( bHigherHalfDifferent == false ).
 *
 * @member {number} channelShuffler_inputGroupCount
 *   The input group count of the channel shuffler. Usually, it is used for undo previous operation's channel shuffling. If 0, the
 * inputScaleBoundsArray will be used. If positive (only 2 is supported currently), the inputScaleBoundsArray.beforeChannelShuffled
 * will be used.
 *
 * @member {number} channelShuffler_outputGroupCount
 *   The output group count of the channel shuffler. Usually, it is used when:
 *   - ( nHigherHalfDifferent == ValueDesc.Pointwise_HigherHalfDifferent.Singleton.Ids.HIGHER_HALF_ANOTHER_POINTWISE ).
 *   - ( nHigherHalfDifferent == ValueDesc.Pointwise_HigherHalfDifferent.Singleton.Ids.HIGHER_HALF_PASS_THROUGH ).
 *
 * @member {number} tensorWeightCountTotal_internal
 *   The total wieght count used in tensors. Not including Params, because they are not used in tensors. Including inferenced
 * weights, if they are used in tensors.
 *
 * @member {number[]} filtersShape
 *   The shape of the pointwise convolution filters array.
 *
 * @member {number[]} biasesShape
 *   The shape of the pointwise convolution biases array.
 *
 * @member {number[]} filtersArray
 *   The pointwise convolution filters array.
 *
 * @member {number[]} biasesArray
 *   The pointwise convolution biases array.
 *
 * @member {boolean} bInitOk
 *   If .init() success, it will be true.
 *
 */
let FiltersArray_BiasesArray = ( ParentClass = Object ) =>
  class FiltersArray_BiasesArray extends Weights.Base( ParentClass ) {

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

  /**
   */
  constructor(
    inputChannelCount, outputChannelCount, bBias, nActivationId, nPassThroughStyleId,
    nHigherHalfDifferent, inputChannelCount_lowerHalf, outputChannelCount_lowerHalf,
    channelShuffler_inputGroupCount, channelShuffler_outputGroupCount,
    ...restArgs ) {

    super( ...restArgs );

    FiltersArray_BiasesArray.setAsConstructor_self.call( this,
      inputChannelCount, outputChannelCount, bBias, nActivationId, nPassThroughStyleId,
      nHigherHalfDifferent, inputChannelCount_lowerHalf, outputChannelCount_lowerHalf,
      channelShuffler_inputGroupCount, channelShuffler_outputGroupCount );
  }

  /** @override */
  static setAsConstructor(
    inputChannelCount, outputChannelCount, bBias, nActivationId, nPassThroughStyleId,
    nHigherHalfDifferent, inputChannelCount_lowerHalf, outputChannelCount_lowerHalf,
    channelShuffler_inputGroupCount, channelShuffler_outputGroupCount,
    ...restArgs ) {

    super.setAsConstructor( ...restArgs );

    FiltersArray_BiasesArray.setAsConstructor_self.call( this,
      inputChannelCount, outputChannelCount, bBias, nActivationId, nPassThroughStyleId,
      nHigherHalfDifferent, inputChannelCount_lowerHalf, outputChannelCount_lowerHalf,
      channelShuffler_inputGroupCount, channelShuffler_outputGroupCount );

    return this;
  }

  /** @override */
  static setAsConstructor_self(
    inputChannelCount, outputChannelCount, bBias, nActivationId, nPassThroughStyleId,
    nHigherHalfDifferent, inputChannelCount_lowerHalf, outputChannelCount_lowerHalf,
    channelShuffler_inputGroupCount, channelShuffler_outputGroupCount ) {

    this.inputChannelCount = inputChannelCount;
    this.outputChannelCount = outputChannelCount;
    this.bBias = bBias;
    this.nActivationId = nActivationId;
    this.nPassThroughStyleId = nPassThroughStyleId;

    this.nHigherHalfDifferent = nHigherHalfDifferent;
    this.inputChannelCount_lowerHalf = inputChannelCount_lowerHalf;
    this.outputChannelCount_lowerHalf = outputChannelCount_lowerHalf;
    this.channelShuffler_inputGroupCount = channelShuffler_inputGroupCount;
    this.channelShuffler_outputGroupCount = channelShuffler_outputGroupCount;

    this.tensorWeightCountTotal_internal = 0;

    if ( inputChannelCount <= 0 )
      throw Error( `Pointwise.FiltersArray_BiasesArray.setAsConstructor_self(): `
        + `inputChannelCount ( ${inputChannelCount} ) must be positive integer.`
      );

    if ( this.bHigherHalfDifferent ) {
      if ( this.inputChannelCount_lowerHalf > inputChannelCount )
        throw Error( `Pointwise.FiltersArray_BiasesArray.setAsConstructor_self(): `
          + `inputChannelCount_lowerHalf ( ${inputChannelCount_lowerHalf} ) can not be larger than `
          + `inputChannelCount ( ${inputChannelCount} ).`
        );

      if ( outputChannelCount_lowerHalf > outputChannelCount )
        throw Error( `Pointwise.FiltersArray_BiasesArray.setAsConstructor_self(): `
          + `outputChannelCount_lowerHalf ( ${outputChannelCount_lowerHalf} ) can not be larger than `
          + `outputChannelCount ( ${outputChannelCount} ).`
        );

      if ( ( inputChannelCount_lowerHalf > 0 ) != ( outputChannelCount_lowerHalf > 0 ) )
        throw Error( `Pointwise.FiltersArray_BiasesArray.setAsConstructor_self(): `
          + `inputChannelCount_lowerHalf ( ${inputChannelCount_lowerHalf} ) and `
          + `outputChannelCount_lowerHalf ( ${outputChannelCount_lowerHalf} ) `
          + `should be both positive or both not.`
        );
    }
  }

  /** @override */
  disposeResources() {

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

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

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

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

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

    this.inputChannelCount_higherHalf = undefined;
    this.outputChannelCount_higherHalf = undefined;

    this.tensorWeightCountTotal_internal = undefined;

    this.channelShuffler_outputGroupCount = undefined;
    this.channelShuffler_inputGroupCount = undefined;
    this.outputChannelCount_lowerHalf = undefined;
    this.inputChannelCount_lowerHalf = undefined;

    this.nHigherHalfDifferent = undefined;

    this.nPassThroughStyleId = undefined;
    this.nActivationId = undefined;
    this.bBias = undefined;
    this.outputChannelCount = undefined;
    this.inputChannelCount = undefined;

    super.disposeResources();
  }

  /**
   * Extract pointwise filters and biases.
   *
   * The following properties will be modified:
   *   - this.weightElementOffsetBegin
   *   - this.weightElementOffsetEnd
   *   - this.tensorWeightCountTotal_internal
   *   - this.boundsArraySet
   *   - this.filtersShape
   *   - this.filtersArray
   *   - this.biasesShape     ( if ( this.bBias == true ) )
   *   - this.biasesArray     ( if ( this.bBias == true ) )
   *
   *
   * @param {number[]|Float32Array} inputWeightArray
   *   A Float32Array whose values will be interpreted as weights.
   *
   * @param {ActivationEscaping.ScaleBoundsArray} inputScaleBoundsArray
   *   The element value bounds (per channel) of input. Usually, it is The .output of the previous convolution-bias-activation value bounds
   * set of this pointwise convolution. It will be kept (not cloned) directly. So caller should not modify them.
   *
   * @return {boolean}
   *   Return true, if succeeded.
   */
  init( inputWeightArray, weightElementOffsetBegin, inputScaleBoundsArray ) {

    // Q1: Why is the inputWeightArray not a parameter of constructor?
    // A1: The reason is to avoid keeping it as this.inputWeightArray so that it could be released by memory garbage collector.
    //
    // Q2: Why is not the sourceWeights kept in this?
    // A2: So that inputWeightArray could be released.

    if ( this.inputChannelCount != inputScaleBoundsArray.length )
      throw Error( `Pointwise.FiltersArray_BiasesArray.init(): `
        + `inputChannelCount ( ${this.inputChannelCount} ) should be the same as `
        + `outputChannelCount of previous convolution-bias-activation ( ${inputScaleBoundsArray.length} ).`
      );

    if ( this.inputChannelCount != inputScaleBoundsArray.scaleArraySet.undo.length )
      throw Error( `Pointwise.FiltersArray_BiasesArray.init(): `
        + `inputChannelCount ( ${this.inputChannelCount} ) should be the same as the length of `
        + `.output.scaleArraySet.undo of previous convolution-bias-activation `
        + `( ${inputScaleBoundsArray.scaleArraySet.undo.length} ).`
      );

    // Note: Even if ( this.outputChannelCount <= 0 ), this function should work correctly as pass-through input to output.
    //

    let aFiltersBiasesPartInfoArray;
    try {

      // Calculate lower half and higher half channel count. (Even if ( bHigherHalfDifferent == false ), these are still correct.)
      {
        if ( this.inputChannelCount_lowerHalf != undefined )
          this.inputChannelCount_higherHalf = this.inputChannelCount - this.inputChannelCount_lowerHalf;
        else
          this.inputChannelCount_higherHalf = undefined;

        if ( this.outputChannelCount_lowerHalf != undefined )
          this.outputChannelCount_higherHalf = this.outputChannelCount - this.outputChannelCount_lowerHalf;
        else
          this.outputChannelCount_higherHalf = undefined;
      }

      // Determine shape of the filters, biases, channels.
      let filtersWeightCount_extracted, biasesWeightCount_extracted;

      // Set up aFiltersBiasesPartInfoArray and filtersShape and biasesShape.
      {
        switch ( this.nHigherHalfDifferent ) {
          // 3.0 Normal pointwise convolution and bias.
          case ValueDesc.Pointwise_HigherHalfDifferent.Singleton.Ids.NONE: // (0)

            // Extract all weights as specified input/output channels.
            filtersWeightCount_extracted = this.inputChannelCount * this.outputChannelCount;
            biasesWeightCount_extracted = this.outputChannelCount;

            aFiltersBiasesPartInfoArray = Recyclable.OwnerArray.Pool.get_or_create_by(
              FiltersBiasesPartInfo.Pool.get_or_create_by(
                ChannelPartInfo.Pool.get_or_create_by( 0, this.inputChannelCount, this.outputChannelCount, false )
              )
            );
            break;

          // 3.1 bHigherHalfCopyLowerHalf_LowerHalfPassThrough
          case ValueDesc.Pointwise_HigherHalfDifferent.Singleton.Ids.HIGHER_HALF_COPY_LOWER_HALF__LOWER_HALF_PASS_THROUGH: // (1)
            filtersWeightCount_extracted = biasesWeightCount_extracted = 0; // Does not extract any weights.
            aFiltersBiasesPartInfoArray = Recyclable.OwnerArray.Pool.get_or_create_by(
              FiltersBiasesPartInfo.Pool.get_or_create_by(
                ChannelPartInfo.Pool.get_or_create_by( 0, this.inputChannelCount_lowerHalf, this.outputChannelCount_lowerHalf,  true ),
                ChannelPartInfo.Pool.get_or_create_by( 0, this.inputChannelCount_lowerHalf, this.outputChannelCount_higherHalf, true )
              )
            );
            break;

          // 3.2 bHigherHalfCopyLowerHalf
          case ValueDesc.Pointwise_HigherHalfDifferent.Singleton.Ids.HIGHER_HALF_COPY_LOWER_HALF: // (2)
            filtersWeightCount_extracted = this.inputChannelCount_lowerHalf * this.outputChannelCount_lowerHalf;
            biasesWeightCount_extracted = this.outputChannelCount_lowerHalf;

            aFiltersBiasesPartInfoArray = Recyclable.OwnerArray.Pool.get_or_create_by(
              FiltersBiasesPartInfo.Pool.get_or_create_by(
                ChannelPartInfo.Pool.get_or_create_by( 0, this.inputChannelCount_lowerHalf, this.outputChannelCount_lowerHalf, false ),
                ChannelPartInfo.Pool.get_or_create_by( 0, this.inputChannelCount_lowerHalf, this.outputChannelCount_higherHalf, true )
              )
            );
            break;

          // 3.3 bHigherHalfAnotherPointwise
          case ValueDesc.Pointwise_HigherHalfDifferent.Singleton.Ids.HIGHER_HALF_ANOTHER_POINTWISE: // (3)
            filtersWeightCount_extracted =
                ( this.inputChannelCount_lowerHalf * this.outputChannelCount_lowerHalf )
              + ( this.inputChannelCount_higherHalf * this.outputChannelCount_higherHalf );

            biasesWeightCount_extracted = this.outputChannelCount;

            aFiltersBiasesPartInfoArray = Recyclable.OwnerArray.Pool.get_or_create_by(
              FiltersBiasesPartInfo.Pool.get_or_create_by(
                ChannelPartInfo.Pool.get_or_create_by(
                                                 0, this.inputChannelCount_lowerHalf, this.outputChannelCount_lowerHalf,  false )
              ),
              FiltersBiasesPartInfo.Pool.get_or_create_by(
                ChannelPartInfo.Pool.get_or_create_by(
                  this.inputChannelCount_lowerHalf, this.inputChannelCount,           this.outputChannelCount_higherHalf, false )
              )
            );
            break;

          // 3.4 bHigherHalfPassThrough
          case ValueDesc.Pointwise_HigherHalfDifferent.Singleton.Ids.HIGHER_HALF_PASS_THROUGH: // (4)
            filtersWeightCount_extracted = this.inputChannelCount_lowerHalf * this.outputChannelCount_lowerHalf;
            biasesWeightCount_extracted = this.outputChannelCount_lowerHalf;

            aFiltersBiasesPartInfoArray = Recyclable.OwnerArray.Pool.get_or_create_by(
              FiltersBiasesPartInfo.Pool.get_or_create_by(
                ChannelPartInfo.Pool.get_or_create_by(
                                                 0, this.inputChannelCount_lowerHalf, this.outputChannelCount_lowerHalf,  false ),
                ChannelPartInfo.Pool.get_or_create_by(
                  this.inputChannelCount_lowerHalf, this.inputChannelCount,           this.outputChannelCount_higherHalf,  true )
              )
            );

            // Note: If ( HIGHER_HALF_PASS_THROUGH ) with ( inputChannelCount_lowerHalf == 0 ) and ( outputChannelCount_lowerHalf == 0 ),
            // the result should be the same as AllPassThrough without using special ( outputChannelCount <= 0 ).
            break;

          default:
            throw Error(
              `Pointwise.FiltersArray_BiasesArray.init(): `
                + `nHigherHalfDifferent ( ${this.nHigherHalfDifferent} ) is unknown value.`
            );
            break;
        }

        this.filtersShape = Recyclable.Array.Pool.get_or_create_by( 1, 1, this.inputChannelCount, this.outputChannelCount );

        if ( this.bBias ) {
          this.biasesShape = Recyclable.Array.Pool.get_or_create_by( 1 );
          this.biasesShape[ 0 ] = this.outputChannelCount;
        } else {
          biasesWeightCount_extracted = 0;
        }
      }

      // Prepare result filters and biases array.
      if ( this.filtersShape )
        this.filtersArray = Recyclable.Array.Pool.get_or_create_by( tf.util.sizeFromShape( this.filtersShape ) );
      if ( this.biasesShape )
        this.biasesArray = Recyclable.Array.Pool.get_or_create_by( tf.util.sizeFromShape( this.biasesShape ) );

      // Calculate weights count of filters and biases to be extracted.
      let weightsCount_extracted = 0;
      if ( filtersWeightCount_extracted )
        weightsCount_extracted += filtersWeightCount_extracted;
      if ( biasesWeightCount_extracted )
        weightsCount_extracted += biasesWeightCount_extracted;

      // Prepare source weights to be extracted.
      if ( !super.init( inputWeightArray, weightElementOffsetBegin, weightsCount_extracted ) ) { // i.e. Weights.Base.init()
        this.bInitOk = false;
        return false;  // e.g. input array does not have enough data.
      }

      // filters and bias: weights and value bounds.
      //
      // It should be better to calculate per channel value bounds by real filter and bias value (i.e. not by an estimated value bounds).
      // This is especialy important for ActivationEscaping. Because inputDomainLinear of activation function is not wide, using looser
      // value bounds estimation has higher possibility to lost information.
      //
      // Two-rounds processing is used:
      //
      //   - In the 1st round, extracting filter and bias value from sourceWeights[]. At the same time, calculating .afterFilter and
      //       .afterBias by these extracted values combined with undoPreviousEscapingScale
      //       (i.e. inputScaleBoundsArray.scaleArraySet.undo.scales[ inChannel ]). And then,
      //       Find out .activationEscaping_ScaleArraySet, .afterActivationEscaping, .afterActivation.
      //
      //   - In the 2nd round, apply doEscapingScale (i.e. .activationEscaping_ScaleArraySet.do.scales[ outChannel ] )
      //       to filter and bias value (and also .afterFilter and .afterBias).
      //
      {
        // Round 0
        {
          // Initialize element value bounds (per channel). Determine .input and .afterUndoPreviousActivationEscaping
          this.boundsArraySet = BoundsArraySet.Pointwise.Pool.get_or_create_by(
            inputScaleBoundsArray, this.outputChannelCount, this.channelShuffler_inputGroupCount );
        }

        // Round 1
        {
          this.set_filtersArray_biasesArray_afterFilter_afterBias_apply_undoPreviousEscapingScale(
            inputWeightArray, weightElementOffsetBegin, inputScaleBoundsArray, aFiltersBiasesPartInfoArray );

          this.boundsArraySet.set_bPassThrough_all_byChannelPartInfoArray( aFiltersBiasesPartInfoArray );

          // Determine .activationEscaping_ScaleArraySet, .afterActivationEscaping, .afterActivation
          this.boundsArraySet.adjust_afterFilter_afterBias_set_output0_by_afterBias_bPassThrough_nActivationId( this.nActivationId );
        }

        // Round 2
        this.apply_doEscapingScale_to_filtersArray_biasesArray(); // Apply doEscapingScale.
      }

      // Shuffle channels.
      //
      // Pre-shuffle channels by shuffling the filters and biases.
      this.set_filters_biases_outputScaleBoundsArray_all_byInterleave_asGrouptTwo();

      {
        this.tensorWeightCountTotal_internal = 0;

        if ( this.filtersShape )
          this.tensorWeightCountTotal_internal += tf.util.sizeFromShape( this.filtersShape );

        if ( this.biasesShape )
          this.tensorWeightCountTotal_internal += tf.util.sizeFromShape( this.biasesShape );
      }

      this.bInitOk = true;
      return true;

    } finally { // Release temporary resource.
      if ( aFiltersBiasesPartInfoArray ) {
        aFiltersBiasesPartInfoArray.disposeResources_and_recycleToPool();
        aFiltersBiasesPartInfoArray = null;
      }
    }
  }

  /**
   * Extract this.filtersArray and this.biasesArray from sourceWeightArray and
   * apply inputScaleBoundsArray.scaleArraySet.undo.scales[]. Also set the .afterFilter and .afterBias.
   *
   * @param {Float32Array} sourceWeightArray
   *   A Float32Array whose values will be interpreted as weights.
   *
   * @param {ActivationEscaping.ScaleBoundsArray} inputScaleBoundsArray
   *   The element value bounds (per channel) of input. Usually, it is The .output of the previous convolution-bias-activation value bounds
   * set of this pointwise convolution. It will be kept (not cloned) directly. So caller should not modify them.
   *
   * @param {Pointwise.FiltersBiasesPartInfo[]} aFiltersBiasesPartInfoArray
   *   The input channel range array which describe lower/higher half channels index range.
   */
  set_filtersArray_biasesArray_afterFilter_afterBias_apply_undoPreviousEscapingScale(
    sourceWeightArray, weightElementOffsetBegin, inputScaleBoundsArray, aFiltersBiasesPartInfoArray ) {

    const thePassThroughStyleInfo = ValueDesc.PassThroughStyle.Singleton.getInfo_byId( this.nPassThroughStyleId );
    let tBounds = FloatValue.Bounds.Pool.get_or_create_by( 0, 0 );

    // Init
    {
      this.boundsArraySet.afterFilter.set_all_byN( 0 ); // Init .afterFilter
      this.boundsArraySet.afterBias.set_all_byN( 0 );   // Init .afterBias

      // Because biases is fetched by adding, it should be initialized to zero. (Note: The .filtersArray is fetched by assigning, so
      // it needs not be initialized.)
      //
      if ( this.biasesArray ) {
        this.biasesArray.fill( 0 );
      }
    }

    let input_scaleArraySet_undo;
    if ( this.channelShuffler_inputGroupCount > 0 ) { // Use non-channel-shuffled info of previous operation.
      input_scaleArraySet_undo = FloatValue.ScaleArray.Pool.get_or_create_by( inputScaleBoundsArray.scaleArraySet.undo.length );
      input_scaleArraySet_undo.set_all_byInterleave_asGrouptTwo_undo_byScaleArray( inputScaleBoundsArray.scaleArraySet.undo );
    } else {
      input_scaleArraySet_undo = inputScaleBoundsArray.scaleArraySet.undo; // Use channel-shuffled info of previous operation.
    }

    // Extracting weights of filters and biases. (Including extra scale.)
    let sourceIndex = weightElementOffsetBegin, filterIndex = 0, biasIndex = 0;

    let outChannelBegin = 0, outChannelEnd = 0; // [ outChannelBegin, outChannelEnd ) are output channels of the current FiltersBiasesPart.

    FiltersBiasesPartIndexLoop:
    for ( let aFiltersBiasesPartIndex = 0; aFiltersBiasesPartIndex < aFiltersBiasesPartInfoArray.length; ++aFiltersBiasesPartIndex ) {
      let aFiltersBiasesPartInfo = aFiltersBiasesPartInfoArray[ aFiltersBiasesPartIndex ];
      let inChannelPartInfoArray = aFiltersBiasesPartInfo;

      filterIndex = outChannelBegin = outChannelEnd; // Begin from the ending of the previous FiltersBiasesPart.

      { // this.filtersArray

        for ( let inChannel = 0; inChannel < this.inputChannelCount; ++inChannel ) {
          let undoPreviousEscapingScale = input_scaleArraySet_undo.scales[ inChannel ];
          let filterValuePassThrough = thePassThroughStyleInfo.filterValue * undoPreviousEscapingScale;
          let outChannel = outChannelBegin;

          InChannelPartIndexLoop:
          for ( let inChannelPartIndex = 0; inChannelPartIndex < inChannelPartInfoArray.length; ++inChannelPartIndex ) {
            let inChannelPartInfo = inChannelPartInfoArray[ inChannelPartIndex ];
            let inChannelToPartBegin = inChannel - inChannelPartInfo.inChannelBegin;

            for ( let outChannelSub = 0; outChannelSub < inChannelPartInfo.outputChannelCount; ++outChannelSub, ++outChannel ) {
              if ( outChannel >= this.outputChannelCount )
                break InChannelPartIndexLoop; // Never exceeds the total output channel count.

              // Note: The .afterUndoPreviousActivationEscaping has already been multiplied by undoPreviousEscapingScale.

              if ( ( inChannelToPartBegin >= 0 ) && ( inChannel < inChannelPartInfo.inChannelEnd ) ) {
                if ( inChannelPartInfo.bPassThrough ) { // For pass-through half channels.
                  if ( inChannelToPartBegin == outChannelSub ) { // The only one filter position (in the pass-through part) may have non-zero value.
                    this.filtersArray[ filterIndex ] = filterValuePassThrough;
                    tBounds
                      .set_byBoundsArray( this.boundsArraySet.afterUndoPreviousActivationEscaping, inChannel )
                      .multiply_byN( thePassThroughStyleInfo.filterValue );

                  } else {
                    this.filtersArray[ filterIndex ] = 0; // All other filter positions (in the pass-through part) are zero.
                    tBounds.set_byN( 0 );
                  }

                } else { // Non-pass-through half channels.
                  let sourceWeight = sourceWeightArray[ sourceIndex ];
                  ++sourceIndex;

                  this.filtersArray[ filterIndex ] = sourceWeight * undoPreviousEscapingScale;
                  tBounds
                    .set_byBoundsArray( this.boundsArraySet.afterUndoPreviousActivationEscaping, inChannel )
                    .multiply_byN( sourceWeight );
                }

                // Determine .afterFilter
                this.boundsArraySet.afterFilter.add_one_byBounds( outChannel, tBounds );

              } else {
                this.filtersArray[ filterIndex ] = 0; // All input channels which is not in range use zero filter to ignore the inputs.
              }

              ++filterIndex;

            } // outChannelSub, outChannel
          } // inChannelPartIndex

          outChannelEnd = outChannel; // Record the ending output channel index of the current FiltersBiasesPart.
          filterIndex += ( this.outputChannelCount - outChannel ) + outChannelBegin; // Jump to the outChannelBegin of the next inChannel.

        } // inChannelSub, inChannel

      } // this.filtersArray

      if ( this.biasesArray ) {
        let biasValue;
        let outChannel = outChannelBegin;

        InChannelPartIndexLoop:
        for ( let inChannelPartIndex = 0; inChannelPartIndex < inChannelPartInfoArray.length; ++inChannelPartIndex ) {
          let inChannelPartInfo = inChannelPartInfoArray[ inChannelPartIndex ];

          for ( let outChannelSub = 0; outChannelSub < inChannelPartInfo.outputChannelCount; ++outChannelSub, ++outChannel ) {
            if ( outChannel >= this.outputChannelCount )
              break InChannelPartIndexLoop; // Never exceeds the total output channel count.

            // Note: bias is not responsible for undoPreviousEscapingScale. (i.e. the filter already done it)

            if ( inChannelPartInfo.bPassThrough ) { // For pass-through half channels.
              biasValue = thePassThroughStyleInfo.biasValue;

            } else { // Non-pass-through half channels.
              biasValue = sourceWeightArray[ sourceIndex ];
              ++sourceIndex;
            }

            this.biasesArray[ biasIndex ] += biasValue; // Note: Use adding instead of assignment.

            // Determine .afterBias
            this.boundsArraySet.afterBias.add_one_byN( outChannel, biasValue ); // Shift the value bounds by the bias.

            ++biasIndex;

          } // outChannelSub, outChannel
        } // inChannelPartIndex

      } else { // ( !this.biasesArray ). No biases array to be extracted.
        // Do nothing.
      }

    } // aFiltersBiasesPartIndex

    // Combine .afterFilter to .afterBias.
    //
    // Q: Why not combine when initializing .afterBias ?
    // A: Because .afterFilter is unknown before FiltersBiasesPartInfoArray has been visited totally.
    //
    this.boundsArraySet.afterBias.add_all_byBoundsArray( this.boundsArraySet.afterFilter );

    if ( outChannelEnd != this.outputChannelCount )
      throw Error(
        `Pointwise.FiltersArray_BiasesArray.set_filtersArray_biasesArray_afterFilter_afterBias_apply_undoPreviousEscapingScale(): `
          + `aFiltersBiasesPartInfoArray[ inChannelPartInfoArray[] ] total output channel count ( ${outChannelEnd} ) `
          + `should be ( ${this.outputChannelCount} ).` );

    // Release temporary resources.
    {
      if ( this.channelShuffler_inputGroupCount > 0 ) {
        input_scaleArraySet_undo.disposeResources_and_recycleToPool();
        input_scaleArraySet_undo = null;
      }

      tBounds.disposeResources_and_recycleToPool();
      tBounds = null;
    }
  }

  /**
   * Apply this.boundsArraySet.output0.scaleArraySet.do.scales[] to this.filtersArray and this.biasesArray.
   */
  apply_doEscapingScale_to_filtersArray_biasesArray() {

    { // this.filtersArray
      let filterIndex = 0;

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

          let doEscapingScale = this.boundsArraySet.output0.scaleArraySet.do.scales[ outChannel ];
          this.filtersArray[ filterIndex ] *= doEscapingScale; // filter wieghts scaled.

          ++filterIndex;

        } // outChannel
      } // inChannel
    } // this.filtersArray

    if ( this.biasesArray ) {
      let biasIndex = 0;

      for ( let outChannel = 0; outChannel < this.outputChannelCount; ++outChannel ) {

        let doEscapingScale = this.boundsArraySet.output0.scaleArraySet.do.scales[ outChannel ];
        this.biasesArray[ biasIndex ] *= doEscapingScale; // bias wieghts scaled.

        ++biasIndex;

      } // outChannel

    } else { // ( !this.biasesArray ). No biases array to be extracted.
      // Do nothing.
    }
  }

  /**
   * Shuffle (.filtersArray, .biasesArray, .boundsArraySet) by interleaving.
   *   - Only ( outputGroupCount == 2 ) is supported.
   *   - The input channel count must be even (i.e. divisible by 2), if ( .channelShuffler_inputGroupCount > 0 ).
   *   - The output channel count must be even (i.e. divisible by 2), if ( .channelShuffler_outputGroupCount > 0 ).
   */
  set_filters_biases_outputScaleBoundsArray_all_byInterleave_asGrouptTwo() {

    // 1.Shuffle along input channels.
    if ( this.channelShuffler_inputGroupCount > 0 ) {

      if ( this.channelShuffler_inputGroupCount != 2 )
        throw Error( `Pointwise.FiltersArray_BiasesArray.set_filters_biases_outputScaleBoundsArray_all_byInterleave_asGrouptTwo(): `
          + `channelShuffler_inputGroupCount ( ${this.channelShuffler_inputGroupCount} ) only 2 is supported.`
        );

      if ( ( this.inputChannelCount % 2 ) != 0 )
        throw Error( `Pointwise.FiltersArray_BiasesArray.set_filters_biases_outputScaleBoundsArray_all_byInterleave_asGrouptTwo(): `
          + `input channel count ( ${this.inputChannelCount} ) must be even (i.e. divisible by 2).`
        );

      // Shuffle filters.
      {
        let filtersArrayShuffled = Recyclable.Array.Pool.get_or_create_by( this.filtersArray.length );

        FloatValue.ArrayInterleaver.interleave_asGrouptTwo_alongLast2ndAxis_from_to(
          this.filtersArray, filtersArrayShuffled, this.inputChannelCount, this.outputChannelCount );

        this.filtersArray.disposeResources_and_recycleToPool();
        this.filtersArray = filtersArrayShuffled;
      }

      // Because its channel shuffling is undone before filters and biases weights extracting, redo it to restore to its original order.
      this.boundsArraySet.set_afterUndoPreviousActivationEscaping_by_Interleave_asGrouptTwo();

      // Note: biases and other BoundsArraySet.afterXxx are not affected because they are along output channels (i.e. not
      //       along input channels).
    }

    // 2. Shuffle along output channels.
    if ( this.channelShuffler_outputGroupCount > 0 ) {

      if ( this.channelShuffler_outputGroupCount != 2 )
        throw Error( `Pointwise.FiltersArray_BiasesArray.set_filters_biases_outputScaleBoundsArray_all_byInterleave_asGrouptTwo(): `
          + `channelShuffler_outputGroupCount ( ${this.channelShuffler_outputGroupCount} ) only 2 is supported.`
        );

      if ( ( this.outputChannelCount % 2 ) != 0 )
        throw Error( `Pointwise.FiltersArray_BiasesArray.set_filters_biases_outputScaleBoundsArray_all_byInterleave_asGrouptTwo(): `
          + `output channel count ( ${this.outputChannelCount} ) must be even (i.e. divisible by 2).`
        );

      // Shuffle filters.
      {
        let filtersArrayShuffled = Recyclable.Array.Pool.get_or_create_by( this.filtersArray.length );

        FloatValue.ArrayInterleaver.interleave_asGrouptTwo_alongLastAxis_from_to(
          this.filtersArray, filtersArrayShuffled, this.inputChannelCount, this.outputChannelCount );

        this.filtersArray.disposeResources_and_recycleToPool();
        this.filtersArray = filtersArrayShuffled;
      }

      // Shuffle biases.
      if ( this.biasesArray ) {
        let biasesArrayShuffled = Recyclable.Array.Pool.get_or_create_by( this.biasesArray.length );

        FloatValue.ArrayInterleaver.interleave_asGrouptTwo_alongLastAxis_from_to(
          this.biasesArray, biasesArrayShuffled, this.outputChannelCount );

        this.biasesArray.disposeResources_and_recycleToPool();
        this.biasesArray = biasesArrayShuffled;
      }

      this.boundsArraySet.set_outputs_all_byInterleave_asGrouptTwo(); // Shuffle bounds array set of output.
    }
  }

  get bHigherHalfDifferent() {
    return ( this.nHigherHalfDifferent ) && ( this.nHigherHalfDifferent != ValueDesc.Pointwise_HigherHalfDifferent.Singleton.Ids.NONE );
  }

}


text:
package helloworld.structural.bridge;

/**
 * @author yihua.huang@dianping.com
 */
public class JavaHelloWorldImpl implements HelloWorldImpl {
    @Override
    public String generate() {
        return "Hello Java!";
    }
}

redpajama_set_name: RedPajamaGithub


text:
        <meta http-equiv="Content-Type" content="text/html; charset=utf-8" />
        <title>W28739_text</title>
        <link rel="stylesheet" type="text/css" href="style.css" />

                «

    <p class="styleSans18.0000<enum PANGO_WEIGHT_NORMAL of type PangoWeight><enum PANGO_STYLE_NORMAL of type PangoStyle>">#5 Energy Services

    <p class="styleSans10.0000<enum PANGO_WEIGHT_NORMAL of type PangoWeight><enum PANGO_STYLE_NORMAL of type PangoStyle>">October 7, 2014

    <p class="styleSans9.0000<enum PANGO_WEIGHT_NORMAL of type PangoWeight><enum PANGO_STYLE_NORMAL of type PangoStyle>">North Dakota Industrial Commission Oil & Gas Division
600 North Boulevard Ave Department 405
Bismarck, North Dakota 58505

    <p class="styleSans11.0000<enum PANGO_WEIGHT_NORMAL of type PangoWeight><enum PANGO_STYLE_NORMAL of type PangoStyle>">RE: FOG Resources, Inc. Parshall 86-2928H A'Iountrai] County, ND Rig: Stoncham #17

    <p class="styleSans9.0000<enum PANGO_WEIGHT_NORMAL of type PangoWeight><enum PANGO_STYLE_NORMAL of type PangoStyle>">Dear North Dakota Industrial Commission:

    <p class="styleSans10.0000<enum PANGO_WEIGHT_NORMAL of type PangoWeight><enum PANGO_STYLE_NORMAL of type PangoStyle>">Please find enclosed the original certified Rate Gyro Surveys run from Surface to a depth of 1,900' MD. on the above mentioned well.
If I can be of any further assistance, please do not hesitate to call me at 936-442-2567.

    <p class="styleSans10.0000<enum PANGO_WEIGHT_NORMAL of type PangoWeight><enum PANGO_STYLE_NORMAL of type PangoStyle>">Sincerely,

    <p class="styleSans10.0000<enum PANGO_WEIGHT_NORMAL of type PangoWeight><enum PANGO_STYLE_NORMAL of type PangoStyle>">Crystal Verino MS Survey

    <p class="styleSans7.0000<enum PANGO_WEIGHT_NORMAL of type PangoWeight><enum PANGO_STYLE_NORMAL of type PangoStyle>">742 W. White Ave Grand Junction, Colorado 81501
970257.1911 (office) 970.257.1947(fax) www.msenergyserviceslcom

    <p class="styleSans12000<enum PANGO_WEIGHT_NORMAL of type PangoWeight><enum PANGO_STYLE_NORMAL of type PangoStyle>">M5


text:
package org.apache.spark.deploy.security

import org.apache.hadoop.conf.Configuration
import org.apache.hadoop.fs.FileSystem
import org.apache.hadoop.security.Credentials

import org.apache.spark.SparkConf
import org.apache.spark.internal.Logging

/**
 * Manages all the registered HadoopDelegationTokenProviders and offer APIs for other modules to
 * obtain delegation tokens and their renewal time. By default [[HadoopFSDelegationTokenProvider]],
 * [[HiveDelegationTokenProvider]] and [[HBaseDelegationTokenProvider]] will be loaded in if not
 * explicitly disabled.
 *
 * Also, each HadoopDelegationTokenProvider is controlled by
 * spark.security.credentials.{service}.enabled, and will not be loaded if this config is set to
 * false.  For example, Hive's delegation token provider [[HiveDelegationTokenProvider]] can be
 * enabled/disabled by the configuration spark.security.credentials.hive.enabled.
 *
 * @param sparkConf Spark configuration
 * @param hadoopConf Hadoop configuration
 * @param fileSystems Delegation tokens will be fetched for these Hadoop filesystems.
 */
private[spark] class HadoopDelegationTokenManager(
    sparkConf: SparkConf,
    hadoopConf: Configuration,
    fileSystems: Configuration => Set[FileSystem])
  extends Logging {

  private val deprecatedProviderEnabledConfigs = List(
    "spark.yarn.security.tokens.%s.enabled",
    "spark.yarn.security.credentials.%s.enabled")
  private val providerEnabledConfig = "spark.security.credentials.%s.enabled"

  // Maintain all the registered delegation token providers
  private val delegationTokenProviders = getDelegationTokenProviders
  logDebug(s"Using the following delegation token providers: " +
    s"${delegationTokenProviders.keys.mkString(", ")}.")

  /** Construct a [[HadoopDelegationTokenManager]] for the default Hadoop filesystem */
  def this(sparkConf: SparkConf, hadoopConf: Configuration) = {
    this(
      sparkConf,
      hadoopConf,
      hadoopConf => Set(FileSystem.get(hadoopConf).getHomeDirectory.getFileSystem(hadoopConf)))
  }

  private def getDelegationTokenProviders: Map[String, HadoopDelegationTokenProvider] = {
    val providers = List(new HadoopFSDelegationTokenProvider(fileSystems),
      new HiveDelegationTokenProvider,
      new HBaseDelegationTokenProvider)

    // Filter out providers for which spark.security.credentials.{service}.enabled is false.
    providers
      .filter { p => isServiceEnabled(p.serviceName) }
      .map { p => (p.serviceName, p) }
      .toMap
  }

  def isServiceEnabled(serviceName: String): Boolean = {
    val key = providerEnabledConfig.format(serviceName)

    deprecatedProviderEnabledConfigs.foreach { pattern =>
      val deprecatedKey = pattern.format(serviceName)
      if (sparkConf.contains(deprecatedKey)) {
        logWarning(s"${deprecatedKey} is deprecated.  Please use ${key} instead.")
      }
    }

    val isEnabledDeprecated = deprecatedProviderEnabledConfigs.forall { pattern =>
      sparkConf
        .getOption(pattern.format(serviceName))
        .map(_.toBoolean)
        .getOrElse(true)
    }

    sparkConf
      .getOption(key)
      .map(_.toBoolean)
      .getOrElse(isEnabledDeprecated)
  }

  /**
   * Get delegation token provider for the specified service.
   */
  def getServiceDelegationTokenProvider(service: String): Option[HadoopDelegationTokenProvider] = {
    delegationTokenProviders.get(service)
  }

  /**
   * Writes delegation tokens to creds.  Delegation tokens are fetched from all registered
   * providers.
   *
   * @return Time after which the fetched delegation tokens should be renewed.
   */
  def obtainDelegationTokens(
      hadoopConf: Configuration,
      creds: Credentials): Long = {
    delegationTokenProviders.values.flatMap { provider =>
      if (provider.delegationTokensRequired(hadoopConf)) {
        provider.obtainDelegationTokens(hadoopConf, creds)
      } else {
        logDebug(s"Service ${provider.serviceName} does not require a token." +
          s" Check your configuration to see if security is disabled or not.")
        None
      }
    }.foldLeft(Long.MaxValue)(math.min)
  }
}


text:
%**************************************************************************
% Reads all images from a directory into a cell array.  The cell array is
% then saved back to the directory as a images.mat file (overwriting any
% pre-existing file of the same name).
%
% @param   directory   The directory to read all the images from.
%
%**************************************************************************
% Code is written by author based upon noted references (if given), using
% The MathWorks MATLAB function signature (if applicable) for convenience
% only.
%
% If you have any questions, comments, or find bugs, please feel free to
% email me at geoff.hayes74@gmail.com.
%
% Geoff Hayes 2014
%**************************************************************************
function read_images(directory)

    % verify that the directory is valid
    if isdir(directory)

        % grab all files from this directory
        files = dir(directory);

        % find the number of files in the directory
        numimgs = length(files);

        % intialize the cell array of images
        images = cell(numimgs,1);

        % read all files
        k = 0;
        for i=1:numimgs

            % append the file name to the directory
            filesrc = fullfile(directory,files(i).name);

            % only read into the workspace those images that have a certain
            % extension
            [~, ~, ext] = fileparts(filename);

            switch ext
                case {'jpg','gif','bmp','tif','png'}
                    k=k+1;
                    images{k}=imread(filesrc);
                otherwise
                    % do nothing
            end
        end

        % remove those empty elements in the cell array (if any exist)
        if k~=numimgs
            images = images(1:k);
        end

        % save the cell array to the same directory
        save(fullfile(directory,'images.mat'),'images');

    end
end


text:
/*
 *
 * LogoLoader
 *
 */

import React, { PropTypes } from 'react';
import { connect } from 'react-redux';
import { Link } from 'react-router';
import LoadingIndicator from 'components/LoadingIndicator'
import LogoImage from 'images/kc-white-500.svg'
import Error from 'components/Error'
import './style.scss'

export class LogoLoader extends React.Component { // eslint-disable-line react/prefer-stateless-function
  render() {
    const { loading, error } = this.props
    return (

        {loading ?
          <LoadingIndicator/>
        :
          <Link to="/"></Link>
        }
        {error && <Error message={error} /> }

    );
  }
}

LogoLoader.propTypes = {

};

const mapStateToProps = (state) => {
  return {
    loading: state.posts.loading,
    error: state.posts.error,
  }
}

export default connect(mapStateToProps)(LogoLoader);


text:
megaApp
===========

[![Build Status](https://travis-ci.org/BachelorProjektAI-HSFulda/megaApp.svg?branch=development)](https://travis-ci.org/BachelorProjektAI-HSFulda/megaApp)

Super Mega Cordova und Electron app

Currently only the Ionic mobile part is setup and can be used for development.

## Setup Dev Environment and Run

- Install the dependencies Cordova and Android SDK
- Assign ANDROID_HOME to your android sdk location
- Make sure to have tools and platform-tools in the path
- Accept the License Agreement of the Android SDK
- Make sure to have Node 6.x or 7.x at least

- `npm install`
- `npm install -g ionic cordova`
- `ionic serve`

With the command `npm run install-clean` it's possible to install a fresh npm installation. This is handy when switching between branches with different node_modules and configurations or when new node_modules are introduced.

**Note**: Only verified on webkit based browsers.

### Run Android Build

- `android update sdk --no-ui --filter build-tools-25.2.5,android-25,extra-android-m2repository,platform-tools-25.0.3`
- `ionic platform add android`
- `ionic build android`

### Visual Studio Setup

- Install plugin Tools for Apache Cordova
- Install plugin Ionic2 Templates
- Install plugin Ionic Pack
- Import the Project
- Configure Android Run-Environment

Further Information in the Docs of Ionic https://taco.visualstudio.com/en-us/docs/tutorial-ionic/

**Remember to always put into the .gitignore file all build files, temp files and everything others won't need or that will be generated.**


text:
package gov.healthit.chpl;

import static com.google.common.base.Predicates.or;
import static springfox.documentation.builders.PathSelectors.regex;

import javax.servlet.ServletContext;

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.context.EnvironmentAware;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
import org.springframework.context.annotation.PropertySource;
import org.springframework.core.env.Environment;

import com.google.common.base.Predicate;

import springfox.documentation.PathProvider;
import springfox.documentation.service.ApiInfo;
import springfox.documentation.service.ApiListingReference;
import springfox.documentation.spi.DocumentationType;
import springfox.documentation.spring.web.paths.RelativePathProvider;
import springfox.documentation.spring.web.plugins.Docket;
import springfox.documentation.swagger2.annotations.EnableSwagger2;

@Configuration
@PropertySource("classpath:environment.properties")
@EnableSwagger2
public class SwaggerConfig implements EnvironmentAware {

	@Autowired ServletContext context;
	@Autowired private Environment env;

	@Override
    public void setEnvironment(final Environment environment) {
        this.env = environment;
    }

    @Bean
    public Docket customDocket(){
       return new Docket(DocumentationType.SWAGGER_2)
    		   .apiInfo(apiInfo())
    		   .pathProvider(pathProvider())
               .select()
               .paths(this.paths())
               .build();
    }

    private ApiInfo apiInfo() {
    	return new ApiInfo("CHPL", "Certified Health IT Product Listing", "0.4.0",
    			"http://terms/of/service.url", "CHPL@ainq.com",
    			"License Text", "https://github.com/chpladmin/chpl-api/blob/staging/LICENSE");
    }

    private PathProvider pathProvider() {
    	return new AbsolutePathProvider(context);
    }

    @SuppressWarnings("unchecked")
    private Predicate<String> paths() {
      return or(
    		  regex("/acbs.*"),
    		  regex("/activity.*"),
    		  regex("/announcements.*"),
    		  regex("/atls.*"),
    		  regex("/auth.*"),
    		  regex("/certified_products.*"),
    		  regex("/certified_product_details.*"),
    		  regex("/corrective_action_plan.*"),
    		  regex("/data/.*"),
    		  regex("/download.*"),
    		  regex("/key.*"),
    		  regex("/products.*"),
    		  regex("/search.*"),
    		  regex("/surveillance.*"),
    		  regex("/users.*"),
    		  regex("/developers.*"),
    		  regex("/versions.*")

    		 );
    }

    private class AbsolutePathProvider extends RelativePathProvider {
    	public AbsolutePathProvider(ServletContext context) {
    		super(context);
    	}

    	@Override
    	public String getApplicationBasePath() {
    		return env.getProperty("basePath");
    	}
    }
}


text:
"""Functions for spatial filtering, a.k.a beamforming."""

import dataclasses
from typing import Optional, Tuple
import tensorflow.compat.v1 as tf

from . import filtering_projections
from . import shaper
from . import signal_transformer
from . import signal_util

def _smart_shape(t):
  return [d or tf.shape(t)[i] for i, d in enumerate(t.shape.as_list())]

def _complex_to_realimag(matrix: tf.Tensor) -> tf.Tensor:
  matrix_real = tf.real(matrix)
  matrix_imag = tf.imag(matrix)
  return tf.concat([
      tf.concat([matrix_real, -matrix_imag], axis=-1),
      tf.concat([matrix_imag, matrix_real], axis=-1)
  ], axis=-2)

def _hermitian_matrix_solve(matrix: tf.Tensor, rhs: tf.Tensor,
                            method='default') -> tf.Tensor:
  """Matrix_solve using various methods."""
  if method == 'cholesky':
    if matrix.dtype == tf.float32:
      return tf.cholesky_solve(tf.cholesky(matrix), rhs)
    else:
      matrix_realimag = _complex_to_realimag(matrix)
      n = matrix.shape[-1]
      rhs_realimag = tf.concat([tf.real(rhs), tf.imag(rhs)], axis=-2)
      lhs_realimag = tf.cholesky_solve(tf.cholesky(matrix_realimag),
                                       rhs_realimag)
      return tf.complex(lhs_realimag[..., :n, :], lhs_realimag[..., n:, :])
  elif method == 'ls':
    return tf.matrix_solve_ls(matrix, rhs)
  elif method == 'default':
    return tf.matrix_solve(matrix, rhs)
  else:
    raise ValueError(f'Unknown matrix solve method {method}.')

def _add_diagonal_matrix(ryy: tf.Tensor, diagload: float = 1e-3,
                         epsilon: float = 1e-8,
                         use_diagonal_of: Optional[tf.Tensor] = None,
                         ) -> tf.Tensor:
  """Regularize matrix usually before taking its inverse.

  Update ryy matrix with ryy += diagload * diag(matrix) + epsilon * I
  where matrix is either equal to ryy or another matrix given by
  use_diagonal_of parameter and I is the identity matrix and diag(.) is the
  diagonal matrix obtained from its argument.

  Args:
    ryy: A [..., mic, mic] complex64/float32 tensor, covariance matrix.
    diagload: A float32 value.
    epsilon: A float32 value.
    use_diagonal_of: None or another tensor [..., mic, mic] whose diagonal
      is used. If None, diagonal of ryy is used.

  Returns:
    [..., mic, mic] tensor, ryy + diagload * diag(use_diagonal_of) + epsilon*I.
  """

  mic = signal_util.static_or_dynamic_dim_size(ryy, -1)
  if use_diagonal_of is None:
    use_diagonal_of = ryy

  # The eps_identity cannot not be too small and too large relative to ryy, it
  # also needs to deal with the case when ryy is zero. Note that 1e-8 is the
  # default lower bound on signal variance and per T-F unit power.
  diagonal_matrix = (diagload * use_diagonal_of + epsilon) * tf.eye(
      mic, dtype=ryy.dtype)
  return ryy + diagonal_matrix

def _get_beamformer_from_covariances(y_cov: tf.Tensor,
                                     t_cov: tf.Tensor,
                                     diagload: float = 1e-3,
                                     epsilon: float = 1e-8,
                                     refmic: int = 0,
                                     beamformer_type: str = 'wiener'
                                     ) -> tf.Tensor:
  """Calculates beamformers from full covariance estimates.

  Typically mixture signal covariance is estimated from the mixture signal and
  the target covariance is estimated using a mask-based covariance estimation.

  Args:
    y_cov: Mixture signal covariance of shape [..., mic, mic].
    t_cov: Source signal covariance estimate of shape [..., mic, mic, source].
    diagload: diagonal loading factor.
    epsilon: data-independent stabilizer for diagonal loading.
    refmic: Reference mic.
    beamformer_type: 'wiener' or 'mvdr' or 'mpdr'.
  Returns:
    beamformers w of shape [..., mic, source].
  """
  y_cov_rank = tf.get_static_value(tf.rank(y_cov))
  # Last two dimensions in y_cov are (mic, mic) and the rest are variable.
  start = y_cov_rank - 2
  prefix = list(range(start))
  if y_cov_rank < 2:
    raise ValueError('Unsupported y_cov rank {}'.format(y_cov_rank))
  if beamformer_type == 'wiener':
    # Multi-channel wiener filter calculates the beamformer using the
    # formula \phi_{yy}^{-1} \phi_{xx} e_{ref} where \phi_{yy} is the
    # spatial covariance matrix for the mixture signal and \phi_{xx} is the
    # same for the target source signal. e_{ref} is a unit vector with a
    # 1 in the location of the reference mic. We calculate this using
    # matrix_solve where the right hand side includes column vectors for each
    # source, so that we find the beamformers for all sources at once.
    w = _hermitian_matrix_solve(_add_diagonal_matrix(y_cov, diagload, epsilon),
                                t_cov[..., refmic, :])
  elif beamformer_type.startswith('mvdr'):
    # We use mu=0.0. In theory mu=1.0 is equivalent to MCWF but in practice
    # seems to be worse in terms of SNR.
    mu = 0.0
    # Our version of MVDR beamformer is obtained by the formula:
    # (1.0/trace(\phi_{nn}^{-1}) \phi_xx) \phi_{nn}^{-1} \phi_xx e_{ref}
    # where \phi_{nn} is the spatial covariance for all sources except the
    # target source and \phi{xx} is the spatial covariance of the target source.
    # Since we need the trace of the matrix for the denominator, we find the
    # \phi_{nn}^{-1}) \phi_xx matrix first using matrix_solve separately
    # for each source since each source has a different \phi_{nn} unlike MCWF.
    # Then we obtain the trace and multiply the matrix with the e_{ref} which
    # corresponds to picking the `ref` column from the matrix.
    # Since we need to do a different matrix_solve for each source,
    # we need to include the source dimension into batch dimensions unlike MCWF.
    t_cov = tf.transpose(t_cov, prefix + [start + 2, start, start + 1])
    # t_cov has shape [..., source, mic, mic].
    # Find non-target covariance for each source.
    nt_cov = tf.reduce_sum(t_cov, axis=-3, keepdims=True) - t_cov
    y_cov = tf.expand_dims(y_cov, axis=-3)
    nt_inv_t_matrix = _hermitian_matrix_solve(
        _add_diagonal_matrix(nt_cov, diagload=1e-2, epsilon=epsilon,
                             use_diagonal_of=y_cov),
        t_cov)
    scale = tf.reciprocal(mu + tf.linalg.trace(nt_inv_t_matrix) + 1e-8)
    scale = tf.expand_dims(scale, -1)
    # nt_inv_t_matrix has shape [..., source, mic, mic].
    w = scale * nt_inv_t_matrix[..., refmic]
    # w has shape [..., source, mic].
    w = tf.transpose(w, prefix + [start + 1, start])
    # w has shape [..., mic, source].
  elif beamformer_type == 'mpdr':
    # MPDR beamformer is obtained by the formula:
    # (1.0/trace(\phi_{yy}^{-1}) \phi_xx) \phi_{yy}^{-1} \phi_xx e_{ref}
    # where \phi_{yy} is the spatial covariance of the mixture and
    # \phi{xx} is the spatial covariance of the target source.
    # Since we need the trace of the matrix for the denominator, we find the
    # \phi_{yy}^{-1}) \phi_xx matrix first.
    # Then we obtain the trace and multiply the matrix with the e_{ref} which
    # corresponds to picking the `ref` column from the matrix.
    # Since we need to do a different matrix_solve for each source,
    # we need to include the source dimension into batch dimensions unlike MCWF.
    t_cov = tf.transpose(t_cov, prefix + [start + 2, start, start + 1])
    # t_cov has shape [..., source, mic, mic].
    y_cov = tf.expand_dims(y_cov, axis=-3)
    y_cov = tf.broadcast_to(y_cov, tf.shape(t_cov))
    # This finds the whole (mic x mic) matrix of phi_yy^{-1} phi_xx for
    # each (..., source) where x is the target and y is the mixed.
    y_inv_t_matrix = _hermitian_matrix_solve(
        _add_diagonal_matrix(y_cov, diagload, epsilon), t_cov)
    scale = tf.reciprocal(tf.linalg.trace(y_inv_t_matrix) + 1e-8)
    scale = tf.cast(tf.expand_dims(scale, -1), dtype=y_cov.dtype)
    # nt_inv_t_matrix has shape [..., source, mic, mic].
    w = scale * y_inv_t_matrix[..., refmic]
    # w has shape [..., source, mic].
    w = tf.transpose(w, prefix + [start + 1, start])
    # w has shape [..., mic, source].
  else:
    raise ValueError('Unknown beamformer type {}.'.format(beamformer_type))
  return w

def _estimate_time_invariant_covariances(y: tf.Tensor,
                                         t: tf.Tensor,
                                         use_complex_mask: bool = False,
                                         refmic: int = 0,
                                         ) -> Tuple[tf.Tensor, tf.Tensor]:
  """Find time-invariant covariance matrices from masks.

  The inputs are the mixture signal and source estimates.
  Args:
    y: Mixture signal with shape [batch, mic, frame, bin].
    t: Source estimates at reference mic [batch, source, frame, bin].
    use_complex_mask: If True, use a complex mask.
    refmic: Reference microphone index.
  Returns:
    y_ti_cov: time-invariant spatial covariance matrix for mixture signal of
      shape [batch, bin, mic, mic].
    t_ti_cov: time-invariant spatial covariance matrix for source signals of
      shape [batch, bin, mic, mic, source].
  """
  tensor_shaper = shaper.Shaper()
  tensor_shaper.register_axes(y, ['batch', 'mic', 'frame', 'bin'])
  y = tensor_shaper.change(y,
                           ['batch', 'mic', 'frame', 'bin'],
                           ['batch', 'frame', 'bin', 'mic', 1])
  t = tensor_shaper.change(t,
                           ['batch', 'source', 'frame', 'bin'],
                           ['batch', 'frame', 'bin', 'source'])
  y_outprod = tf.matmul(y, y, adjoint_b=True)
  tensor_shaper.register_axes(y_outprod,
                              ['batch', 'frame', 'bin', 'mic', 'mic'])
  y_ti_cov = tf.reduce_mean(y_outprod, axis=1)
  tensor_shaper.register_axes(y_ti_cov, ['batch', 'bin', 'mic', 'mic'])
  t_power = tf.square(tf.abs(t))

  if use_complex_mask:
    y_refmic = y[:, :, :, refmic:refmic+1, 0]
    y_refmic_power = tf.square(tf.abs(y_refmic))
    power_limit = 1e-8
    est_masks = tf.where(
        tf.logical_and(y_refmic_power > power_limit,
                       t_power < y_refmic_power * 3.0),
        t / (y_refmic + power_limit), tf.zeros_like(t))
    est_masks = tf.conj(est_masks)
  else:
    # Derive an estimated Wiener-like mask from estimated target powers.
    power_offset = 1e-8
    t_power += power_offset
    est_masks = t_power / tf.reduce_sum(t_power, axis=-1, keepdims=True)

  est_masks = tf.cast(est_masks, dtype=y_outprod.dtype)
  est_masks = tensor_shaper.change(est_masks,
                                   ['batch', 'frame', 'bin', 'source'],
                                   ['batch', 'frame', 'bin', 1, 1, 'source'])

  masked_y_outprod = tf.expand_dims(y_outprod, axis=-1) * est_masks
  tensor_shaper.register_axes(masked_y_outprod,
                              ['batch', 'frame', 'bin', 'mic', 'mic', 'source'])

  t_ti_cov = tf.reduce_mean(masked_y_outprod, axis=1)
  tensor_shaper.register_axes(t_ti_cov,
                              ['batch', 'bin', 'mic', 'mic', 'source'])

  return y_ti_cov, t_ti_cov

def time_invariant_multichannel_filtering(
    y: tf.Tensor,
    t: tf.Tensor,
    use_complex_mask: bool = False,
    beamformer_type: str = 'wiener',
    refmic: int = 0,
    diagload: float = 1e-3,
    epsilon: float = 1e-8,
    )-> Tuple[tf.Tensor, tf.Tensor]:
  """Computes a multi-channel Wiener filter from time-invariant covariances.

  Args:
    y: [batch, mic, frame, bin], complex64, mixture spectrogram.
    t: [batch, source, frame, bin], complex64, estimated spectrogram.
    use_complex_mask: If True, use a complex mask.
    beamformer_type: A string describing beamformer type. 'wiener', 'mvdr'
      or 'mpdr'.
    refmic: index of the reference mic.
    diagload: A float32 value, diagonal loading for the matrix inversion in
      beamforming.
    epsilon: A float32 value, data-independent stabilizer for diagonal loading.

  Returns:
    bf_y: [batch, source, frame, bin], complex64, beamformed spectrogram.
    w_H: [batch, bin, source, mic], complex64, beamformer coefficients.
  """
  tensor_shaper = shaper.Shaper()
  tensor_shaper.register_axes(y, ['batch', 'mic', 'frame', 'bin'])
  with tf.name_scope(None, 'time_invariant_multichannel_wiener_filter'):
    # This method uses the spatial covariance of the mixture and target.
    # In this method we estimate the spatial covariances of the noisy and
    # target signals by applying the same mask to all channels of the noisy
    # signal.
    # In the future, when we support multi-channel targets, then this
    # approximation will no longer be needed, and we can directly compute the
    # target spatial covariances.

    y_ti_cov, t_ti_cov = _estimate_time_invariant_covariances(
        y, t, use_complex_mask, refmic)
    tensor_shaper.register_axes(y_ti_cov, ['batch', 'bin', 'mic', 'mic'])
    tensor_shaper.register_axes(t_ti_cov,
                                ['batch', 'bin', 'mic', 'mic', 'source'])
    w = _get_beamformer_from_covariances(
        y_ti_cov, t_ti_cov, diagload=diagload, epsilon=epsilon, refmic=refmic,
        beamformer_type=beamformer_type)
    w_h = tf.conj(tensor_shaper.change(w,
                                       ['batch', 'bin', 'mic', 'source'],
                                       ['batch', 'bin', 'source', 'mic']))
    y = tensor_shaper.change(y,
                             ['batch', 'mic', 'frame', 'bin'],
                             ['batch', 'bin', 'mic', 'frame'])
    w_h_y = tf.matmul(w_h, y)
    bf_y = tensor_shaper.change(w_h_y,
                                ['batch', 'bin', 'source', 'frame'],
                                ['batch', 'source', 'frame', 'bin'])
  return bf_y, w_h

def _maybe_expand_context(y: tf.Tensor, frame_context_length: int,
                          frame_context_type: str,
                          refmic: int) -> tf.Tensor:
  """Expands context into mics dimension of the input.

  Args:
    y: [batch, mic, frame, bin]
    frame_context_length:
    frame_context_type:
    refmic: Reference microphone.
  Returns:
    expanded_y: [batch, mic * frame_context_length, frame, bin]
    refmic: Updated refmic.
  """
  if frame_context_length > 1:
    tensor_shaper = shaper.Shaper()
    tensor_shaper.register_axes(y, ['batch', 'mic', 'frame', 'bin'])
    # If frame_context_length > 1, we pad mic axis of y with its contextual
    # frame values.
    # New mics axis is going to be mics * frame_context_length size and
    # refmic will change.
    if frame_context_type == 'causal':
      y = tf.pad(y, [(0, 0), (0, 0), (frame_context_length-1, 0), (0, 0)])
      # Center frame is the last one in the causal context case.
      center_frame_index = frame_context_length - 1
    elif frame_context_type == 'centered':
      pad_end = (frame_context_length - 1) // 2
      pad_begin = frame_context_length - 1 - pad_end
      y = tf.pad(y, [(0, 0), (0, 0), (pad_begin, pad_end), (0, 0)])
      # Center frame has the index pad_begin in the centered context case.
      center_frame_index = pad_begin
    else:
      raise ValueError('Unknown frame context type '
                       '{}'.format(frame_context_type))
    y = tf.signal.frame(y, frame_context_length, 1, axis=2)
    y = tensor_shaper.change(y,
                             ['batch', 'mic', 'frame', 'context', 'bin'],
                             ['batch', ('mic', 'context'), 'frame', 'bin'])
    # New refmic index is given by:
    #   np.ravel_multi_index([refmic, center_frame_index],
    #                        [mics, frame_context_length])
    refmic = refmic * frame_context_length + center_frame_index

    return y, refmic
  else:
    return y, refmic

def compute_multichannel_filter(y: tf.Tensor, t: tf.Tensor,
                                use_complex_mask: bool = False,
                                frame_context_length: int = 1,
                                frame_context_type: str = 'causal',
                                beamformer_type: str = 'wiener',
                                refmic: int = 0,
                                block_size_in_frames: int = -1,
                                diagload: float = 1e-3,
                                epsilon: float = 1e-8
                                ) -> Tuple[tf.Tensor, tf.Tensor]:
  """Computes a multi-channel Wiener filter from spectrogram-like inputs.

  Args:
    y: [batch, mic, frame, bin], complex64/float32, mixture spectrogram.
    t: [batch, source, frame, bin], complex64/float32, estimated spectrogram.
    use_complex_mask: If True, use a complex mask.
    frame_context_length: An integer value to specify the number of
      contextual frames used in beamforming.
    frame_context_type: 'causal' or 'centered'.
    beamformer_type: A string describing beamformer type. 'wiener', 'mvdr'
      or 'mpdr'.
    refmic: index of the reference mic.
    block_size_in_frames: an int32 value, block size in frames.
    diagload: float32, diagonal loading value for the matrix inversion in
      beamforming. Note that this value is likely dependent on the energy level
      of the input mixture. The default value has been tuned based on the
      assumption that the time-domain RMS normalization is performed, and the
      covariance matrices are always divided by the number of frames.
    epsilon: A float32 value, data-independent stabilizer for diagonal loading.

  Returns:
    [batch, source, frame, bin], complex64/float32, beamformed y.
    [batch, bin, source, mic], complex64/float32, beamformer weights.
  """

  y = tf.convert_to_tensor(y, name='y')
  t = tf.convert_to_tensor(t, name='t')
  tensor_shaper = shaper.Shaper()
  tensor_shaper.register_axes(y, ['batch', 'mic', 'frame', 'bin'])
  tensor_shaper.register_axes(t, ['batch', 'source', 'frame', 'bin'])

  batch = tensor_shaper.axis_sizes['batch']
  n_frames = tensor_shaper.axis_sizes['frame']
  # Expand context into microphones axis and update reference microphone index.
  y, refmic = _maybe_expand_context(y, frame_context_length, frame_context_type,
                                    refmic)
  # y now has shape [batch, mic*context, frame, bin]

  if block_size_in_frames < 0:
    n_frames_in_block = n_frames
    perform_blocking = False
  else:
    assert block_size_in_frames > 0
    if tf.is_tensor(n_frames):
      n_frames_in_block = tf.minimum(n_frames, block_size_in_frames)
    else:
      n_frames_in_block = min(n_frames, block_size_in_frames)
    perform_blocking = True

  if perform_blocking:
    # This window is used before and after beamforming.
    overlap_window = tf.cast(tf.signal.vorbis_window(n_frames_in_block),
                             dtype=y.dtype)

    def extract_blocks(tensor):
      """Extract overlapping blocks from signals."""
      half_size = n_frames_in_block // 2
      tensor = tf.pad(tensor, [(0, 0), (0, 0), (half_size, 0), (0, 0)])
      tensor = tf.signal.frame(tensor, n_frames_in_block, half_size,
                               pad_end=True, axis=-2)
      local_shaper = shaper.Shaper()
      tensor = local_shaper.change(
          tensor,
          ['batch', 'chan', 'block', 'frame', 'bin'],
          [('batch', 'block'), 'chan', 'frame', 'bin'])
      window_reshaped = tf.reshape(overlap_window, [1, 1, n_frames_in_block, 1])
      tensor *= window_reshaped
      return tensor

    y = extract_blocks(y)
    # y has shape [n_blocks*batch, mic, n_frames_in_block, bin].
    t = extract_blocks(t)
    # t has shape [n_blocks*batch, source, n_frames_in_block, bin].

  bf_y, beamformer_weights = time_invariant_multichannel_filtering(
      y, t, use_complex_mask=use_complex_mask,
      beamformer_type=beamformer_type, refmic=refmic, diagload=diagload,
      epsilon=epsilon)
  # bf_y has shape [n_blocks*batch, source, n_frames_in_block, bin].
  # or bf_y has shape [batch, source, frame, bin].
  # beamformer_weights has shape [batch, bin, source, mic]

  if perform_blocking:
    block_shaper = shaper.Shaper()
    block_shaper.register_axes(bf_y,
                               ['block_and_batch', 'source',
                                'frame_in_block', 'bin'])
    half_size = n_frames_in_block // 2
    n_blocks = tf.shape(bf_y)[0] / batch
    # Overlap add overlapping blocks.
    tensor_shape = tf.concat([[n_blocks, batch], tf.shape(bf_y)[1:]], axis=0)
    bf_y = tf.reshape(bf_y, tensor_shape)
    block_shaper.register_axes(
        bf_y, ['block', 'batch', 'source', 'frame_in_block', 'bin'])
    # bf_y has shape [n_blocks, batch, source, block_size, bin].
    bf_y = block_shaper.change(
        bf_y, ['block', 'batch', 'source', 'frame_in_block', 'bin'],
        ['batch', 'source', 'bin', 'block', 'frame_in_block'])
    window_reshaped = tf.reshape(overlap_window,
                                 [1, 1, 1, 1, n_frames_in_block])
    # Window the beamformed signal, so that we end up applying window squared.
    bf_y *= window_reshaped
    # Overlap-add windowed overlapping blocks.
    bf_y = tf.signal.overlap_and_add(bf_y, half_size)
    # bf_y has shape [batch, source, bin, frame_padded]
    bf_y = bf_y[..., half_size:half_size + n_frames]
    block_shaper.register_axes(
        bf_y, ['batch', 'source', 'bin', 'frame'])
    bf_y = block_shaper.change(bf_y,
                               ['batch', 'source', 'bin', 'frame'],
                               ['batch', 'source', 'frame', 'bin'])

  return bf_y, beamformer_weights

def compute_multichannel_filter_from_signals(y: tf.Tensor, t: tf.Tensor,
                                             refmic: int = 0,
                                             sample_rate: float = 16000.,
                                             ws: float = 0.064,
                                             hs: float = 0.032,
                                             frame_context_length: int = 1,
                                             frame_context_type: str = 'causal',
                                             beamformer_type: str = 'wiener',
                                             block_size_in_seconds: int = -1,
                                             use_complex_mask: bool = False,
                                             diagload: float = 1e-3,
                                             epsilon: float = 1e-8
                                             ) -> tf.Tensor:
  """Computes a multichannel Wiener filter to estimate a target t from y.

  Args:
    y: [batch, mic, time], float32, mixture waveform.
    t: [batch, source, time], float32, estimated waveform.
    refmic: Index of the reference mic.
    sample_rate: Sampling rate of audio in Hz.
    ws: Window size in seconds.
    hs: Hop size in seconds.
    frame_context_length: An integer value to specify the number of
      contextual frames used in beamforming.
    frame_context_type: 'causal' or 'centered'.
    beamformer_type: A string describing beamformer type. 'wiener', 'mvdr'
      or 'mpdr'.
    block_size_in_seconds: block size in seconds.
    use_complex_mask: If True, use a complex mask.
    diagload: float32, diagonal loading value for the matrix inversion in
      beamforming. Note that this value is likely dependent on the energy level
      of the input mixture. The default value has been tuned based on the
      assumption that the time-domain RMS normalization is performed, and the
      covariance matrices are always divided by the number of frames.
    epsilon: A float32 value, data-independent stabilizer for diagonal loading.

  Returns:
    [batch, source, time], float32, beamformed waveform y.
  """

  noisy_length = signal_util.static_or_dynamic_dim_size(y, -1)

  # Compute transforms.
  transformer = signal_transformer.SignalTransformer(
      sample_rate=sample_rate,
      window_time_seconds=ws,
      hop_time_seconds=hs,
      magnitude_offset=1e-8,
      zeropad_beginning=True,
  )
  y_spectrograms = transformer.forward(y)
  t_spectrograms = transformer.forward(t)

  block_size_in_frames = int(round(block_size_in_seconds / hs))

  # Perform beamforming.
  beamformed_spectrograms, _ = compute_multichannel_filter(
      y_spectrograms, t_spectrograms,
      frame_context_length=frame_context_length,
      frame_context_type=frame_context_type,
      beamformer_type=beamformer_type,
      refmic=refmic,
      block_size_in_frames=block_size_in_frames,
      use_complex_mask=use_complex_mask,
      diagload=diagload,
      epsilon=epsilon)

  # Reconstruct time-domain signals.
  beamformed_waveforms = transformer.inverse(
      beamformed_spectrograms)[..., :noisy_length]

  return beamformed_waveforms

@dataclasses.dataclass(frozen=True)
class BeamformerParams(object):
  """Dataclass for estimating and applying an LTI beamformer.

  The parameters are related to how to transform a time-domain signal to STFT
  domain and in what manner to estimate an LTI beamformer from that. A subset
  of the parameters (namely the first 5 hyper-parameters) are required when
  applying the estimated beamformer to another time-domain signal since we
  need to know how to transform the time domain signal to the STFT domain and
  how much frame context we would like to use.

  Attributes:
    sample_rate: Sample rate.
    ws: Window size for STFT in seconds.
    hs: Hop size for STFT in seconds.
    frame_context_length: Length of context in frames.
    frame_context_type: 'centered' or 'causal'.
    refmic: Reference microphone.
    beamformer_type: 'wiener', 'mvdr' or 'mpdr'.
    use_complex_mask: If True, use a complex mask. If False, we use a real mask
      which is a Wiener-like mask. If False, the target sources should
      include all sources in the mixture, not only some of them, otherwise the
      beamformer will be incorrect.
    diagload: float32, diagonal loading value for the matrix inversion in
      beamforming. Note that this value is likely dependent on the energy level
      of the input mixture. The default value has been tuned based on the
      assumption that the time-domain RMS normalization is performed, and the
      covariance matrices are always divided by the number of frames.
    epsilon: A float32 value, data-independent stabilizer for diagonal loading.
  """
  sample_rate: float = 16000.
  ws: float = 0.064
  hs: float = 0.032
  frame_context_length: int = 1
  frame_context_type: str = 'causal'
  refmic: int = 0
  beamformer_type: str = 'wiener'
  use_complex_mask: bool = True
  diagload: float = 1e-3
  epsilon: float = 1e-8

def compute_lti_beamformer_from_signals(
    y: tf.Tensor,
    t: tf.Tensor,
    beamformer_params: BeamformerParams = BeamformerParams(),
    ) -> Tuple[tf.Tensor, tf.Tensor]:
  """Computes a beamformer to estimate target(s) t from multi-channel y.

  Note that when beamformer_params.use_complex_mask=False, we assume that the
  source dimension in the target t tensor contains sources that approximately
  sum to the mixture waveform at the reference microphone, so that we can
  calculate a Wiener-like mask using those target sources. If this is not true,
  that is if t does not include all sources but only one of them or some of
  them, we should set beamformer_parems.use_complex_mask=True.

  Args:
    y: [batch, mic, time], float32, mixture waveform.
    t: [batch, source, time], float32, estimated waveform.
    beamformer_params: Beamformer parameters needed to apply the beamformer
      to time domain signals.

  Returns:
    [batch, bin, source, mic]: multichannel multiframe beamformer coefficients.
      Note that the mic axis also includes contextual frames if
      frame_context_length > 1 and real-imaginary parts if concat_real_imag is
      True. If concat_real_imag is True, source dimension is 2*source including
      real and imaginary for each source.
    [batch, source, time], float32, beamformed waveform y.
  """

  noisy_length = signal_util.static_or_dynamic_dim_size(y, -1)

  # Compute transforms.
  transformer = signal_transformer.SignalTransformer(
      sample_rate=beamformer_params.sample_rate,
      window_time_seconds=beamformer_params.ws,
      hop_time_seconds=beamformer_params.hs,
      magnitude_offset=1e-8,
      zeropad_beginning=True,
  )
  y_spectrograms = transformer.forward(y)
  t_spectrograms = transformer.forward(t)

  # Perform beamforming.
  beamformed_spectrograms, beamformer_weights = compute_multichannel_filter(
      y_spectrograms, t_spectrograms,
      frame_context_length=beamformer_params.frame_context_length,
      frame_context_type=beamformer_params.frame_context_type,
      beamformer_type=beamformer_params.beamformer_type,
      refmic=beamformer_params.refmic,
      block_size_in_frames=-1,
      use_complex_mask=beamformer_params.use_complex_mask,
      diagload=beamformer_params.diagload,
      epsilon=beamformer_params.epsilon)

  # Reconstruct time-domain signals through inverse STFT.
  beamformed_waveforms = transformer.inverse(
      beamformed_spectrograms)[..., :noisy_length]

  return beamformer_weights, beamformed_waveforms

def apply_lti_beamformer_to_signal(
    y: tf.Tensor,
    beamformer_weights: tf.Tensor,
    beamformer_params: BeamformerParams = BeamformerParams(),
    ) -> tf.Tensor:

  """Applies a beamformer to signal(s) in y.

  Args:
    y: [batch, mic, time], float32, multi-channel input waveform.
    beamformer_weights: [batch, bin, source, mic_and_context],
      float32/complex64, beamformer coefficients. Batch dimensions should
      broadcast with the tensor y.
    beamformer_params: Beamformer hyper parameters required to apply to a
      new signal.

  Returns:
    [batch, source, time], float32, beamformed waveforms.
  """
  input_length = signal_util.static_or_dynamic_dim_size(y, -1)
  transformer = signal_transformer.SignalTransformer(
      sample_rate=beamformer_params.sample_rate,
      window_time_seconds=beamformer_params.ws,
      hop_time_seconds=beamformer_params.hs,
      magnitude_offset=1e-8,
      zeropad_beginning=True,
  )
  y_stft = transformer.forward(y)

  y_stft, _ = _maybe_expand_context(y_stft,
                                    beamformer_params.frame_context_length,
                                    beamformer_params.frame_context_type,
                                    beamformer_params.refmic)
  tensor_shaper = shaper.Shaper()
  tensor_shaper.register_axes(y_stft, ['batch', 'mic_context', 'frame', 'bin'])
  y_stft = tensor_shaper.change(y_stft,
                                ['batch', 'mic_context', 'frame', 'bin'],
                                ['batch', 'bin', 'mic_context', 'frame'])
  beamformed_stft = tf.matmul(beamformer_weights, y_stft)
  beamformed_stft = tensor_shaper.change(beamformed_stft,
                                         ['batch', 'bin', 'source', 'frame'],
                                         ['batch', 'source', 'frame', 'bin'])

  # Reconstruct time-domain signals through inverse STFT.
  beamformed_waveforms = transformer.inverse(
      beamformed_stft)[..., :input_length]

  return beamformed_waveforms

def find_equivalent_time_domain_beamformer(
    beamformer_stft: tf.Tensor,
    beamformer_params: BeamformerParams = BeamformerParams(),
    filter_len: Optional[int] = None,
    filter_support_start: Optional[int] = None,
    random_seed: int = 0,
    ) -> Tuple[tf.Tensor, int]:
  """Finds an equivalent time domain beamformer to an STFT domain one.

  To get the exact same filter, use the same random_seed each time.

  Args:
    beamformer_stft: An STFT domain beamformer with shape
      [batch, bin, source, mic_and_context] and dtype tf.complex64.
    beamformer_params: Beamformer parameters.
    filter_len: Filter length in samples. If None, it is calculated
      automatically.
    filter_support_start: Filter support start index. If None, it is calculated
      automatically.
    random_seed: Random seed to use for generating WGN input.
  Returns:
    beamformer_time_domain: A beamformer [batch, source, mic, filter_len] of
      dtype tf.float32.
    filter_support_start: The starting sample index of the time domain
      filter. A value of 0 implies a causal filter, a value of -5 means the
      filter is non-causal where its values start from index -5.
  """
  # bf weights dimensions are [batch, bin, source, mic_and_context]
  bf_shape = _smart_shape(beamformer_stft)
  batch_size = bf_shape[0]
  num_sources = bf_shape[2]
  mics = bf_shape[-1] // beamformer_params.frame_context_length
  new_shape = bf_shape[:-1] + [mics, beamformer_params.frame_context_length]
  # new_shape is [batch, bin, source, mic, context]
  beamformer_weights_expanded = tf.reshape(beamformer_stft, new_shape)
  frame_shift_samples = int(round(
      beamformer_params.hs * beamformer_params.sample_rate))
  frame_length_samples = int(round(
      beamformer_params.ws * beamformer_params.sample_rate))
  # Time-domain filter should have a length that increases with frame context
  # length with a minimum length of two frame lengths long.
  if filter_len is None:
    filter_len = ((beamformer_params.frame_context_length - 1) *
                  frame_shift_samples + 2 * frame_length_samples)
  # An STFT domain filter will have a lookahead which is equal to the
  # frame length.
  if filter_support_start is None:
    if beamformer_params.frame_context_type == 'causal':
      filter_support_start = -frame_length_samples
    elif beamformer_params.frame_context_type == 'centered':
      filter_support_start = (
          -frame_length_samples - (
              ((beamformer_params.frame_context_length - 1) // 2) *
              frame_shift_samples))

  time_domain_filters = []
  tf.set_random_seed(random_seed)
  for i in range(mics):
    # We use a single mic beamformer and have the context axis behave as
    # mics_and_context axis for beamforming a single mic input.
    bf_weights_for_mic_i = beamformer_weights_expanded[:, :, :, i, :]
    # The strategy is to filter a random signal with STFT domain filter and then
    # find an equivalent LTI time-domain filter that would yield a close result.
    # Note: We can use a more carefully designed input signal here, but using a
    # WGN random signal works OK.
    input_signal_length = filter_len * frame_shift_samples
    # We have a single mic input signal which is WGN.
    x = tf.random.normal([batch_size, 1, input_signal_length])
    y = apply_lti_beamformer_to_signal(x, bf_weights_for_mic_i,
                                       beamformer_params=beamformer_params)
    # The output y has shape [batch, source, time].
    for source in range(num_sources):
      _, time_domain_filter = filtering_projections.filter_in_time_domain(
          x, y[:, source:source+1, :],
          filter_support_start=filter_support_start, filter_len=filter_len,
          solver='default')
      time_domain_filters.append(time_domain_filter)

  beamformer_time_domain = tf.concat(time_domain_filters, axis=-2)
  # beamformer_time_domain has shape [batch, mics*sources, filter_len].
  beamformer_time_domain = tf.reshape(
      beamformer_time_domain, [batch_size, mics, num_sources, filter_len])
  beamformer_time_domain = tf.transpose(
      beamformer_time_domain, (0, 2, 1, 3))  # [batch, source, mic, filter_len]
  return beamformer_time_domain, filter_support_start

def apply_time_domain_beamformer(input_signal: tf.Tensor,
                                 beamformer_time_domain: tf.Tensor,
                                 filter_support_start: int = 0
                                 ) -> tf.Tensor:
  """Applies a time domain beamformer to signal.

  Args:
    input_signal: Input signal with shape (batch, mic, signal_length).
    beamformer_time_domain: Beamformer with shape
      (batch, source, mic, filter_length).
    filter_support_start: The starting sample index of the time domain
      filter. A value of 0 implies a causal filter, a value of -5 means the
      filter is non-causal where its values start from index -5.
  Returns:
    output_signal: Output beamformed signal with shape
      (batch, source, signal_length).
  """
  num_sources = _smart_shape(beamformer_time_domain)[1]
  bf_outputs = []
  for source in range(num_sources):
    filtered_output = filtering_projections.perform_filtering(
        input_signal, beamformer_time_domain[:, source],
        filter_support_start=filter_support_start)
    bf_output = tf.reduce_sum(filtered_output, axis=-2, keepdims=True)
    bf_outputs.append(bf_output)
  return tf.concat(bf_outputs, axis=-2)


text:
#ifndef TENSORFLOW_LITE_MICRO_SIMPLE_MEMORY_ALLOCATOR_H_
#define TENSORFLOW_LITE_MICRO_SIMPLE_MEMORY_ALLOCATOR_H_

#include <cstddef>
#include <cstdint>

#include "tensorflow/lite/c/common.h"
#include "tensorflow/lite/core/api/error_reporter.h"
#include "tensorflow/lite/micro/compatibility.h"

namespace tflite {

// TODO(petewarden): This allocator never frees up or reuses  any memory, even
// though we have enough information about lifetimes of the tensors to do so.
// This makes it pretty wasteful, so we should use a more intelligent method.
class SimpleMemoryAllocator {
 public:
  // TODO(b/157615197): Cleanup constructors/destructor and use factory
  // functions.
  SimpleMemoryAllocator(ErrorReporter* error_reporter, uint8_t* buffer_head,
                        uint8_t* buffer_tail);
  SimpleMemoryAllocator(ErrorReporter* error_reporter, uint8_t* buffer,
                        size_t buffer_size);
  virtual ~SimpleMemoryAllocator();

  // Creates a new SimpleMemoryAllocator from a given buffer head and size.
  static SimpleMemoryAllocator* Create(ErrorReporter* error_reporter,
                                       uint8_t* buffer_head,
                                       size_t buffer_size);

  // Ensure that the head (lowest address and moving upwards) memory allocation
  // is at least a given size. This function will only increase the head size if
  // the passed in value is larger than the current head size. Calls to this
  // method will also invalidate all temporary allocation values. This call will
  // fail if a chain of allocations through AllocateTemp() have not been cleaned
  // up with a call to ResetTempAllocations().
  virtual TfLiteStatus EnsureHeadSize(size_t size, size_t alignment);

  // Allocates memory starting at the tail of the arena (highest address and
  // moving downwards).
  virtual uint8_t* AllocateFromTail(size_t size, size_t alignment);

  // Allocates a temporary buffer from the head of the arena (lowest address and
  // moving upwards) but does not update the actual head allocation size or
  // position. The returned buffer is guaranteed until either
  // ResetTempAllocations() is called or another call to AllocateFromHead().
  // Repeat calls to this function will create a chain of temp allocations. All
  // calls to AllocateTemp() must end with a call to ResetTempAllocations(). If
  // AllocateFromHead() is called before a call to ResetTempAllocations(), it
  // will fail with an error message.
  virtual uint8_t* AllocateTemp(size_t size, size_t alignment);

  // Resets a chain of temporary allocations back to the current head of the
  // arena (lowest address).
  virtual void ResetTempAllocations();

  uint8_t* GetHead() const;
  uint8_t* GetBufferHead() const;
  uint8_t* GetTail() const;

  size_t GetHeadUsedBytes() const;
  size_t GetTailUsedBytes() const;

  // Returns the number of bytes available with a given alignment.
  size_t GetAvailableMemory(size_t alignment) const;

  size_t GetUsedBytes() const;

 private:
  size_t GetBufferSize() const;

  ErrorReporter* error_reporter_;
  uint8_t* buffer_head_;
  uint8_t* buffer_tail_;
  uint8_t* head_;
  uint8_t* tail_;
  uint8_t* temp_;

  TF_LITE_REMOVE_VIRTUAL_DELETE
};

}  // namespace tflite

#endif  // TENSORFLOW_LITE_MICRO_SIMPLE_MEMORY_ALLOCATOR_H_


text:
package com.teodoradobreva.mongodb.service;

import java.util.List;

import com.sun.jersey.api.core.InjectParam;
import com.teodoradobreva.mongodb.dao.UsersDao;
import com.teodoradobreva.mongodb.model.User;

public class UsersServiceImpl implements UsersService {

	private UsersDao usersDao;

	@InjectParam
	public void setUsersDao(UsersDao usersDao) {
		this.usersDao = usersDao;
	}

	@Override
	public User getUserByUsername(String username) {
		return usersDao.getUserByUsername(username);
	}

	@Override
	public List<User> getUsersNotFollowed(User user) {
		return usersDao.getUsersNotFollowed(user);
	}

	@Override
	public List<User> getUsersFollowed(User userFrom) {
		return usersDao.getUsersFollowed(userFrom);
	}

	@Override
	public void follow(User follower, User toFollow) {
		usersDao.follow(follower, toFollow);
	}

	@Override
	public void unfollow(User follower, User followed) {
		usersDao.unfollow(follower, followed);
	}

}


text:
<?php

namespace app\commands;

use Yii;
use yii\console\Controller;

class RbacController extends Controller
{
    public function actionInit()
    {
        $auth = Yii::$app->authManager;

        $auth->removeAllPermissions();
        $auth->removeAllRoles();
        $auth->removeAllRules();

        $user = $auth->createRole('user');
        $auth->add($user);

        $admin = $auth->createRole('admin');
        $auth->add($admin);

        $auth->assign($admin, 1);
    }
}


text:
""" Tokenization class for Funnel Transformer."""

from typing import List, Optional

from ...utils import logging
from ..bert.tokenization_bert import BertTokenizer

logger = logging.get_logger(__name__)

VOCAB_FILES_NAMES = {"vocab_file": "vocab.txt"}

_model_names = [
    "small",
    "small-base",
    "medium",
    "medium-base",
    "intermediate",
    "intermediate-base",
    "large",
    "large-base",
    "xlarge",
    "xlarge-base",
]

PRETRAINED_VOCAB_FILES_MAP = {
    "vocab_file": {
        "funnel-transformer/small": "https://huggingface.co/funnel-transformer/small/resolve/main/vocab.txt",
        "funnel-transformer/small-base": "https://huggingface.co/funnel-transformer/small-base/resolve/main/vocab.txt",
        "funnel-transformer/medium": "https://huggingface.co/funnel-transformer/medium/resolve/main/vocab.txt",
        "funnel-transformer/medium-base": "https://huggingface.co/funnel-transformer/medium-base/resolve/main/vocab.txt",
        "funnel-transformer/intermediate": "https://huggingface.co/funnel-transformer/intermediate/resolve/main/vocab.txt",
        "funnel-transformer/intermediate-base": "https://huggingface.co/funnel-transformer/intermediate-base/resolve/main/vocab.txt",
        "funnel-transformer/large": "https://huggingface.co/funnel-transformer/large/resolve/main/vocab.txt",
        "funnel-transformer/large-base": "https://huggingface.co/funnel-transformer/large-base/resolve/main/vocab.txt",
        "funnel-transformer/xlarge": "https://huggingface.co/funnel-transformer/xlarge/resolve/main/vocab.txt",
        "funnel-transformer/xlarge-base": "https://huggingface.co/funnel-transformer/xlarge-base/resolve/main/vocab.txt",
    }
}
PRETRAINED_POSITIONAL_EMBEDDINGS_SIZES = {f"funnel-transformer/{name}": 512 for name in _model_names}
PRETRAINED_INIT_CONFIGURATION = {f"funnel-transformer/{name}": {"do_lower_case": True} for name in _model_names}

class FunnelTokenizer(BertTokenizer):
    r"""
    Construct a Funnel Transformer tokenizer.

    :class:`~transformers.FunnelTokenizer` is identical to :class:`~transformers.BertTokenizer` and runs end-to-end
    tokenization: punctuation splitting and wordpiece.

    Refer to superclass :class:`~transformers.BertTokenizer` for usage examples and documentation concerning
    parameters.
    """

    vocab_files_names = VOCAB_FILES_NAMES
    pretrained_vocab_files_map = PRETRAINED_VOCAB_FILES_MAP
    max_model_input_sizes = PRETRAINED_POSITIONAL_EMBEDDINGS_SIZES
    pretrained_init_configuration = PRETRAINED_INIT_CONFIGURATION
    cls_token_type_id: int = 2

    def __init__(
        self,
        vocab_file,
        do_lower_case=True,
        do_basic_tokenize=True,
        never_split=None,
        unk_token="<unk>",
        sep_token="<sep>",
        pad_token="<pad>",
        cls_token="<cls>",
        mask_token="<mask>",
        bos_token="<s>",
        eos_token="</s>",
        tokenize_chinese_chars=True,
        strip_accents=None,
        **kwargs
    ):
        super().__init__(
            vocab_file,
            do_lower_case=do_lower_case,
            do_basic_tokenize=do_basic_tokenize,
            never_split=never_split,
            unk_token=unk_token,
            sep_token=sep_token,
            pad_token=pad_token,
            cls_token=cls_token,
            mask_token=mask_token,
            bos_token=bos_token,
            eos_token=eos_token,
            tokenize_chinese_chars=tokenize_chinese_chars,
            strip_accents=strip_accents,
            **kwargs,
        )

    def create_token_type_ids_from_sequences(
        self, token_ids_0: List[int], token_ids_1: Optional[List[int]] = None
    ) -> List[int]:
        """
        Create a mask from the two sequences passed to be used in a sequence-pair classification task. A Funnel
        Transformer sequence pair mask has the following format:

        ::

            2 0 0 0 0 0 0 0 0 0 0 1 1 1 1 1 1 1 1 1
            | first sequence    | second sequence |

        If :obj:`token_ids_1` is :obj:`None`, this method only returns the first portion of the mask (0s).

        Args:
            token_ids_0 (:obj:`List[int]`):
                List of IDs.
            token_ids_1 (:obj:`List[int]`, `optional`):
                Optional second list of IDs for sequence pairs.

        Returns:
            :obj:`List[int]`: List of `token type IDs <../glossary.html#token-type-ids>`_ according to the given
            sequence(s).
        """
        sep = [self.sep_token_id]
        cls = [self.cls_token_id]
        if token_ids_1 is None:
            return len(cls) * [self.cls_token_type_id] + len(token_ids_0 + sep) * [0]
        return len(cls) * [self.cls_token_type_id] + len(token_ids_0 + sep) * [0] + len(token_ids_1 + sep) * [1]


text:
<?php

namespace {

from('Hoa')

/**
 * \Hoa\Socket\Exception
 */
-> import('Socket.Exception');

}

namespace Hoa\Socket {

/**
 * Class \Hoa\Socket\Transport.
 *
 * Basic transports manipulation.
 *
 * @author     Ivan Enderlin <ivan.enderlin@hoa-project.net>
 * @copyright  Copyright © 2007-2012 Ivan Enderlin.
 * @license    New BSD License
 */

class Transport {

    /**
     * Get all enable transports.
     *
     * @access  public
     * @return  array
     */
    public static function get ( ) {

        static $_ = null;

        if(null === $_)
            $_ = stream_get_transports();

        return $_;
    }

    /**
     * Check if a transport exists.
     *
     * @access  public
     * @param   string  $transport    Transport to check.
     * @return  bool
     */
    public static function exists ( $transport ) {

        return in_array(strtolower($transport), self::get());
    }
}

}


text:
from django.utils.functional import cached_property
from django.shortcuts import render

from .models import Story

# Look to the Home app for the primary view.