text:
#ifndef WEBRTC_MODULES_AUDIO_CODING_MAIN_SOURCE_ACM_GENERIC_CODEC_H_
#define WEBRTC_MODULES_AUDIO_CODING_MAIN_SOURCE_ACM_GENERIC_CODEC_H_

#include "acm_common_defs.h"
#include "audio_coding_module_typedefs.h"
#include "rw_lock_wrapper.h"
#include "trace.h"
#include "webrtc_neteq.h"

#define MAX_FRAME_SIZE_10MSEC 6

// forward declaration
struct WebRtcVadInst;
struct WebRtcCngEncInst;

namespace webrtc
{

// forward declaration
struct CodecInst;
class  ACMNetEQ;

class ACMGenericCodec
{
public:
    ///////////////////////////////////////////////////////////////////////////
    // Constructor of the class
    //
    ACMGenericCodec();

    ///////////////////////////////////////////////////////////////////////////
    // Destructor of the class.
    //
    virtual ~ACMGenericCodec();

    ///////////////////////////////////////////////////////////////////////////
    // ACMGenericCodec* CreateInstance();
    // The function will be used for FEC. It is not implemented yet.
    //
    virtual ACMGenericCodec* CreateInstance() = 0;

    ///////////////////////////////////////////////////////////////////////////
    // WebRtc_Word16 Encode()
    // The function is called to perform an encoding of the audio stored in
    // audio buffer. An encoding is performed only if enough audio, i.e. equal
    // to the frame-size of the codec, exist. The audio frame will be processed
    // by VAD and CN/DTX if required. There are few different cases.
    //
    // A) Neither VAD nor DTX is active; the frame is encoded by the encoder.
    //
    // B) VAD is enabled but not DTX; in this case the audio is processed by VAD
    //    and encoded by the encoder. The "*encodingType" will be either
    //    "activeNormalEncode" or "passiveNormalEncode" if frame is active or
    //    passive, respectively.
    //
    // C) DTX is enabled; if the codec has internal VAD/DTX we just encode the
    //    frame by the encoder. Otherwise, the frame is passed through VAD and
    //    if identified as passive, then it will be processed by CN/DTX. If the
    //    frame is active it will be encoded by the encoder.
    //
    // This function acquires the appropriate locks and calls EncodeSafe() for
    // the actual processing.
    //
    // Outputs:
    //   -bitStream          : a buffer where bit-stream will be written to.
    //   -bitStreamLenByte   : contains the length of the bit-stream in
    //                         bytes.
    //   -timeStamp          : contains the RTP timestamp, this is the
    //                         sampling time of the first sample encoded
    //                         (measured in number of samples).
    //   -encodingType       : contains the type of encoding applied on the
    //                         audio samples. The alternatives are
    //                         (c.f. acm_common_types.h)
    //                         -kNoEncoding:
    //                            there was not enough data to encode. or
    //                            some error has happened that we could
    //                            not do encoding.
    //                         -kActiveNormalEncoded:
    //                            the audio frame is active and encoded by
    //                            the given codec.
    //                         -kPassiveNormalEncoded:
    //                            the audio frame is passive but coded with
    //                            the given codec (NO DTX).
    //                         -kPassiveDTXWB:
    //                            The audio frame is passive and used
    //                            wide-band CN to encode.
    //                         -kPassiveDTXNB:
    //                            The audio frame is passive and used
    //                            narrow-band CN to encode.
    //
    // Return value:
    //   -1 if error is occurred, otherwise the length of the bit-stream in
    //      bytes.
    //
    WebRtc_Word16 Encode(
        WebRtc_UWord8*         bitStream,
        WebRtc_Word16*         bitStreamLenByte,
        WebRtc_UWord32*        timeStamp,
        WebRtcACMEncodingType* encodingType);

    ///////////////////////////////////////////////////////////////////////////
    // WebRtc_Word16 Decode()
    // This function is used to decode a given bit-stream, without engaging
    // NetEQ.
    //
    // This function acquires the appropriate locks and calls DecodeSafe() for
    // the actual processing. Please note that this is not functional yet.
    //
    // Inputs:
    //   -bitStream          : a buffer where bit-stream will be read.
    //   -bitStreamLenByte   : the length of the bit-stream in bytes.
    //
    // Outputs:
    //   -audio              : pointer to a buffer where the audio will written.
    //   -audioSamples       : number of audio samples out of decoding the given
    //                         bit-stream.
    //   -speechType         : speech type (for future use).
    //
    // Return value:
    //   -1 if failed to decode,
    //    0 if succeeded.
    //
    WebRtc_Word16 Decode(
        WebRtc_UWord8* bitStream,
        WebRtc_Word16  bitStreamLenByte,
        WebRtc_Word16* audio,
        WebRtc_Word16* audioSamples,
        WebRtc_Word8*  speechType);

    ///////////////////////////////////////////////////////////////////////////
    // void SplitStereoPacket()
    // This function is used to split stereo payloads in left and right channel.
    // Codecs which has stereo support has there own implementation of the
    // function.
    //
    // Input/Output:
    //   -payload             : a vector with the received payload data.
    //                          The function will reorder the data so that
    //                          first half holds the left channel data, and the
    //                          second half the right channel data.
    //   -payload_length      : length of payload in bytes. Will be changed to
    //                          twice the input in case of true stereo, where
    //                          we simply copy the data and return it both for
    //                          left channel and right channel decoding.
    virtual void SplitStereoPacket(WebRtc_UWord8* /* payload */,
                                   WebRtc_Word32* /* payload_length */) {}

    ///////////////////////////////////////////////////////////////////////////
    // bool EncoderInitialized();
    //
    // Return value:
    //   True if the encoder is successfully initialized,
    //   false otherwise.
    //
    bool EncoderInitialized();

    ///////////////////////////////////////////////////////////////////////////
    // bool DecoderInitialized();
    //
    // Return value:
    //   True if the decoder is successfully initialized,
    //   false otherwise.
    //
    bool DecoderInitialized();

    ///////////////////////////////////////////////////////////////////////////
    // WebRtc_Word16 EncoderParams()
    // It is called to get encoder parameters. It will call
    // EncoderParamsSafe() in turn.
    //
    // Output:
    //   -encParams          : a buffer where the encoder parameters is
    //                         written to. If the encoder is not
    //                         initialized this buffer is filled with
    //                         invalid values
    // Return value:
    //   -1 if the encoder is not initialized,
    //    0 otherwise.
    //
    //
    WebRtc_Word16 EncoderParams(
        WebRtcACMCodecParams *encParams);

    ///////////////////////////////////////////////////////////////////////////
    // WebRtc_Word16 DecoderParams(...)
    // It is called to get decoder parameters. It will call DecoderParamsSafe()
    // in turn.
    //
    // Output:
    //   -decParams          : a buffer where the decoder parameters is
    //                         written to. If the decoder is not initialized
    //                         this buffer is filled with invalid values
    //
    // Return value:
    //   -1 if the decoder is not initialized,
    //    0 otherwise.
    //
    //
    bool DecoderParams(
        WebRtcACMCodecParams *decParams,
        const WebRtc_UWord8  payloadType);

    ///////////////////////////////////////////////////////////////////////////
    // WebRtc_Word16 InitEncoder(...)
    // This function is called to initialize the encoder with the given
    // parameters.
    //
    // Input:
    //   -codecParams        : parameters of encoder.
    //   -forceInitialization: if false the initialization is invoked only if
    //                         the encoder is not initialized. If true the
    //                         encoder is forced to (re)initialize.
    //
    // Return value:
    //   0 if could initialize successfully,
    //  -1 if failed to initialize.
    //
    //
    WebRtc_Word16 InitEncoder(
        WebRtcACMCodecParams* codecParams,
        bool                  forceInitialization);

    ///////////////////////////////////////////////////////////////////////////
    // WebRtc_Word16 InitDecoder()
    // This function is called to initialize the decoder with the given
    // parameters. (c.f. acm_common_defs.h & common_types.h for the
    // definition of the structure)
    //
    // Input:
    //   -codecParams        : parameters of decoder.
    //   -forceInitialization: if false the initialization is invoked only
    //                         if the decoder is not initialized. If true
    //                         the encoder is forced to(re)initialize.
    //
    // Return value:
    //   0 if could initialize successfully,
    //  -1 if failed to initialize.
    //
    //
    WebRtc_Word16 InitDecoder(
        WebRtcACMCodecParams* codecParams,
        bool                 forceInitialization);

    ///////////////////////////////////////////////////////////////////////////
    // WebRtc_Word32 RegisterInNetEq(...)
    // This function is called to register the decoder in NetEq, with the given
    // payload-type.
    //
    // Inputs:
    //   -netEq              : pointer to NetEq Instance
    //   -codecInst          : instance with of the codec settings of the codec
    //
    // Return values
    //   -1 if failed to register,
    //    0 if successfully initialized.
    //
    WebRtc_Word32 RegisterInNetEq(
        ACMNetEQ*             netEq,
        const CodecInst& codecInst);

    ///////////////////////////////////////////////////////////////////////////
    // WebRtc_Word32 Add10MsData(...)
    // This function is called to add 10 ms of audio to the audio buffer of
    // the codec.
    //
    // Inputs:
    //   -timeStamp          : the timestamp of the 10 ms audio. the timestamp
    //                         is the sampling time of the
    //                         first sample measured in number of samples.
    //   -data               : a buffer that contains the audio. The codec
    //                         expects to get the audio in correct sampling
    //                         frequency
    //   -length             : the length of the audio buffer
    //   -audioChannel       : 0 for mono, 1 for stereo (not supported yet)
    //
    // Return values:
    //   -1 if failed
    //    0 otherwise.
    //
    WebRtc_Word32 Add10MsData(
        const WebRtc_UWord32 timeStamp,
        const WebRtc_Word16* data,
        const WebRtc_UWord16 length,
        const WebRtc_UWord8  audioChannel);

    ///////////////////////////////////////////////////////////////////////////
    // WebRtc_UWord32 NoMissedSamples()
    // This function returns the number of samples which are overwritten in
    // the audio buffer. The audio samples are overwritten if the input audio
    // buffer is full, but Add10MsData() is called. (We might remove this
    // function if it is not used)
    //
    // Return Value:
    //   Number of samples which are overwritten.
    //
    WebRtc_UWord32 NoMissedSamples() const;

    ///////////////////////////////////////////////////////////////////////////
    // void ResetNoMissedSamples()
    // This function resets the number of overwritten samples to zero.
    // (We might remove this function if we remove NoMissedSamples())
    //
    void ResetNoMissedSamples();

    ///////////////////////////////////////////////////////////////////////////
    // WebRtc_Word16 SetBitRate()
    // The function is called to set the encoding rate.
    //
    // Input:
    //   -bitRateBPS         : encoding rate in bits per second
    //
    // Return value:
    //   -1 if failed to set the rate, due to invalid input or given
    //      codec is not rate-adjustable.
    //    0 if the rate is adjusted successfully
    //
    WebRtc_Word16 SetBitRate(const WebRtc_Word32 bitRateBPS);

    ///////////////////////////////////////////////////////////////////////////
    // DestructEncoderInst()
    // This API is used in conferencing. It will free the memory that is pointed
    // by "ptrInst". "ptrInst" is a pointer to encoder instance, created and
    // filled up by calling EncoderInst(...).
    //
    // Inputs:
    //   -ptrInst            : pointer to an encoder instance to be deleted.
    //
    //
    void DestructEncoderInst(
        void* ptrInst);

    ///////////////////////////////////////////////////////////////////////////
    // WebRtc_Word16 AudioBuffer()
    // This is used when synchronization of codecs is required. There are cases
    // that the audio buffers of two codecs have to be synched. By calling this
    // function on can get the audio buffer and other related parameters, such
    // as timestamps...
    //
    // Output:
    //   -audioBuff          : a pointer to WebRtcACMAudioBuff where the audio
    //                         buffer of this codec will be written to.
    //
    // Return value:
    //   -1 if fails to copy the audio buffer,
    //    0 if succeeded.
    //
    WebRtc_Word16 AudioBuffer(
        WebRtcACMAudioBuff& audioBuff);

    ///////////////////////////////////////////////////////////////////////////
    // WebRtc_UWord32 EarliestTimestamp()
    // Returns the timestamp of the first 10 ms in audio buffer. This is used
    // to identify if a synchronization of two encoders is required.
    //
    // Return value:
    //   timestamp of the first 10 ms audio in the audio buffer.
    //
    WebRtc_UWord32 EarliestTimestamp() const;

    ///////////////////////////////////////////////////////////////////////////
    // WebRtc_Word16 SetAudioBuffer()
    // This function is called to set the audio buffer and the associated
    // parameters to a given value.
    //
    // Return value:
    //   -1 if fails to copy the audio buffer,
    //    0 if succeeded.
    //
    WebRtc_Word16 SetAudioBuffer(WebRtcACMAudioBuff& audioBuff);

    ///////////////////////////////////////////////////////////////////////////
    // WebRtc_Word16 SetVAD()
    // This is called to set VAD & DTX. If the codec has internal DTX that will
    // be used. If DTX is enabled and the codec does not have internal DTX,
    // WebRtc-VAD will be used to decide if the frame is active. If DTX is
    // disabled but VAD is enabled. The audio is passed through VAD to label it
    // as active or passive, but the frame is  encoded normally. However the
    // bit-stream is labeled properly so that ACM::Process() can use this
    // information. In case of failure, the previous states of the VAD & DTX
    // are kept.
    //
    // Inputs:
    //   -enableDTX          : if true DTX will be enabled otherwise the DTX is
    //                         disabled. If codec has internal DTX that will be
    //                         used, otherwise WebRtc-CNG is used. In the latter
    //                         case VAD is automatically activated.
    //   -enableVAD          : if true WebRtc-VAD is enabled, otherwise VAD is
    //                         disabled, except for the case that DTX is enabled
    //                         but codec doesn't have internal DTX. In this case
    //                         VAD is enabled regardless of the value of
    //                         "enableVAD."
    //   -mode               : this specifies the aggressiveness of VAD.
    //
    // Return value
    //   -1 if failed to set DTX & VAD as specified,
    //    0 if succeeded.
    //
    WebRtc_Word16 SetVAD(
        const bool             enableDTX = true,
        const bool             enableVAD = false,
        const ACMVADMode mode      = VADNormal);

    ///////////////////////////////////////////////////////////////////////////
    // WebRtc_Word32 ReplaceInternalDTX()
    // This is called to replace the codec internal DTX with WebRtc DTX.
    // This is only valid for G729 where the user has possibility to replace
    // AnnexB with WebRtc DTX. For other codecs this function has no effect.
    //
    // Input:
    //   -replaceInternalDTX : if true the internal DTX is replaced with WebRtc.
    //
    // Return value
    //   -1 if failed to replace internal DTX,
    //    0 if succeeded.
    //
    WebRtc_Word32 ReplaceInternalDTX(const bool replaceInternalDTX);

    ///////////////////////////////////////////////////////////////////////////
    // WebRtc_Word32 IsInternalDTXReplaced()
    // This is called to check if the codec internal DTX is replaced by WebRtc DTX.
    // This is only valid for G729 where the user has possibility to replace
    // AnnexB with WebRtc DTX. For other codecs this function has no effect.
    //
    // Output:
    //   -internalDTXReplaced    : if true the internal DTX is replaced with WebRtc.
    //
    // Return value
    //   -1 if failed to check if replace internal DTX or replacement not feasible,
    //    0 if succeeded.
    //
    WebRtc_Word32 IsInternalDTXReplaced(bool* internalDTXReplaced);

    ///////////////////////////////////////////////////////////////////////////
    // void SetNetEqDecodeLock()
    // Passes the NetEq lock to the codec.
    //
    // Input:
    //   -netEqDecodeLock    : pointer to the lock associated with NetEQ of ACM.
    //
    void SetNetEqDecodeLock(
        RWLockWrapper* netEqDecodeLock)
    {
        _netEqDecodeLock = netEqDecodeLock;
    }

    ///////////////////////////////////////////////////////////////////////////
    // bool HasInternalDTX()
    // Used to check if the codec has internal DTX.
    //
    // Return value:
    //   true if the codec has an internal DTX, e.g. G729,
    //   false otherwise.
    //
    bool HasInternalDTX() const
    {
        return _hasInternalDTX;
    }

   ///////////////////////////////////////////////////////////////////////////
    // WebRtc_Word32 GetEstimatedBandwidth()
    // Used to get decoder estimated bandwidth. Only iSAC will provide a value.
    //
    //
    // Return value:
    //   -1 if fails to get decoder estimated bandwidth,
    //    >0 estimated bandwidth in bits/sec.
    //
    WebRtc_Word32 GetEstimatedBandwidth();

    ///////////////////////////////////////////////////////////////////////////
    // WebRtc_Word32 SetEstimatedBandwidth()
    // Used to set estiamted bandwidth sent out of band from other side. Only
    // iSAC will have use for the value.
    //
    // Input:
    //       -estimatedBandwidth:    estimated bandwidth in bits/sec
    //
    // Return value:
    //   -1 if fails to set estimated bandwidth,
    //    0 on success.
    //
    WebRtc_Word32 SetEstimatedBandwidth(WebRtc_Word32 estimatedBandwidth);

    ///////////////////////////////////////////////////////////////////////////
    // WebRtc_Word32 GetRedPayload()
    // Used to get codec specific RED payload (if such is implemented).
    // Currently only done in iSAC.
    //
    // Outputs:
    //   -redPayload        : a pointer to the data for RED payload.
    //   -payloadBytes      : number of bytes in RED payload.
    //
    // Return value:
    //   -1 if fails to get codec specific RED,
    //    0 if succeeded.
    //
    WebRtc_Word32 GetRedPayload(
        WebRtc_UWord8* redPayload,
        WebRtc_Word16* payloadBytes);

    ///////////////////////////////////////////////////////////////////////////
    // WebRtc_Word16 ResetEncoder()
    // By calling this function you would re-initialize the encoder with the
    // current parameters. All the settings, e.g. VAD/DTX, frame-size... should
    // remain unchanged. (In case of iSAC we don't want to lose BWE history.)
    //
    // Return value
    //   -1 if failed,
    //    0 if succeeded.
    //
    WebRtc_Word16 ResetEncoder();

    ///////////////////////////////////////////////////////////////////////////
    // WebRtc_Word16 ResetEncoder()
    // By calling this function you would re-initialize the decoder with the
    // current parameters.
    //
    // Return value
    //   -1 if failed,
    //    0 if succeeded.
    //
    WebRtc_Word16 ResetDecoder(
        WebRtc_Word16 payloadType);

    ///////////////////////////////////////////////////////////////////////////
    // void DestructEncoder()
    // This function is called to delete the encoder instance, if possible, to
    // have a fresh start. For codecs where encoder and decoder share the same
    // instance we cannot delete the encoder and instead we will initialize the
    // encoder. We also delete VAD and DTX if they have been created.
    //
    void DestructEncoder();

    ///////////////////////////////////////////////////////////////////////////
    // void DestructDecoder()
    // This function is called to delete the decoder instance, if possible, to
    // have a fresh start. For codecs where encoder and decoder share the same
    // instance we cannot delete the encoder and instead we will initialize the
    // decoder. Before deleting decoder instance it has to be removed from the
    // NetEq list.
    //
    void DestructDecoder();

    ///////////////////////////////////////////////////////////////////////////
    // WebRtc_Word16 SamplesLeftToEncode()
    // Returns the number of samples required to be able to do encoding.
    //
    // Return value:
    //   Number of samples.
    //
    WebRtc_Word16 SamplesLeftToEncode();

    ///////////////////////////////////////////////////////////////////////////
    // WebRtc_UWord32 LastEncodedTimestamp()
    // Returns the timestamp of the last frame it encoded.
    //
    // Return value:
    //   Timestamp.
    //
    WebRtc_UWord32 LastEncodedTimestamp() const;

    ///////////////////////////////////////////////////////////////////////////
    // SetUniqueID()
    // Set a unique ID for the codec to be used for tracing and debuging
    //
    // Input
    //   -id                 : A number to identify the codec.
    //
    void SetUniqueID(
        const WebRtc_UWord32 id);

    ///////////////////////////////////////////////////////////////////////////
    // IsAudioBufferFresh()
    // Specifies if ever audio is injected to this codec.
    //
    // Return value
    //   -true; no audio is feed into this codec
    //   -false; audio has already been  fed to the codec.
    //
    bool IsAudioBufferFresh() const;

    ///////////////////////////////////////////////////////////////////////////
    // UpdateDecoderSampFreq()
    // For most of the codecs this function does nothing. It must be
    // implemented for those codecs that one codec instance serves as the
    // decoder for different flavers of the codec. One example is iSAC. there,
    // iSAC 16 kHz and iSAC 32 kHz are treated as two different codecs with
    // different payload types, however, there is only one iSAC instance to
    // decode. The reason for that is we would like to decode and encode with
    // the same codec instance for bandwidth estimator to work.
    //
    // Each time that we receive a new payload type, we call this funtion to
    // prepare the decoder associated with the new payload. Normally, decoders
    // doesn't have to do anything. For iSAC the decoder has to change it's
    // sampling rate. The input parameter specifies the current flaver of the
    // codec in codec database. For instance, if we just got a SWB payload then
    // the input parameter is ACMCodecDB::isacswb.
    //
    // Input:
    //   -codecId            : the ID of the codec associated with the
    //                         payload type that we just received.
    //
    // Return value:
    //    0 if succeeded in updating the decoder.
    //   -1 if failed to update.
    //
    virtual WebRtc_Word16 UpdateDecoderSampFreq(
        WebRtc_Word16 /* codecId */)
    {
        return 0;
    }

    ///////////////////////////////////////////////////////////////////////////
    // UpdateEncoderSampFreq()
    // Call this function to update the encoder sampling frequency. This
    // is for codecs where one payload-name supports several encoder sampling
    // frequencies. Otherwise, to change the sampling frequency we need to
    // register new codec. ACM will consider that as registration of a new
    // codec, not a change in parameter. For iSAC, switching from WB to SWB
    // is treated as a change in parameter. Therefore, we need this function.
    //
    // Input:
    //   -encoderSampFreqHz  : encoder sampling frequency.
    //
    // Return value:
    //   -1 if failed, or if this is meaningless for the given codec.
    //    0 if succeeded.
    //
    virtual WebRtc_Word16 UpdateEncoderSampFreq(
        WebRtc_UWord16 encoderSampFreqHz);

    ///////////////////////////////////////////////////////////////////////////
    // EncoderSampFreq()
    // Get the sampling frequency that the encoder (WebRtc wrapper) expects.
    //
    // Output:
    //   -sampFreqHz         : sampling frequency, in Hertz, which the encoder
    //                         should be fed with.
    //
    // Return value:
    //   -1 if failed to output sampling rate.
    //    0 if the sample rate is returned successfully.
    //
    virtual WebRtc_Word16 EncoderSampFreq(
        WebRtc_UWord16& sampFreqHz);

    ///////////////////////////////////////////////////////////////////////////
    // WebRtc_Word32 ConfigISACBandwidthEstimator()
    // Call this function to configure the bandwidth estimator of ISAC.
    // During the adaptation of bit-rate, iSAC atomatically adjusts the
    // frame-size (either 30 or 60 ms) to save on RTP header. The initial
    // frame-size can be specified by the first argument. The configuration also
    // regards the initial estimate of bandwidths. The estimator starts from
    // this point and converges to the actual bottleneck. This is given by the
    // second parameter. Furthermore, it is also possible to control the
    // adaptation of frame-size. This is specified by the last parameter.
    //
    // Input:
    //   -initFrameSizeMsec  : initial frame-size in milisecods. For iSAC-wb
    //                         30 ms and 60 ms (default) are acceptable values,
    //                         and for iSAC-swb 30 ms is the only acceptable
    //                         value. Zero indiates default value.
    //   -initRateBitPerSec  : initial estimate of the bandwidth. Values
    //                         between 10000 and 58000 are acceptable.
    //   -enforceFrameSize   : if true, the frame-size will not be adapted.
    //
    // Return value:
    //   -1 if failed to configure the bandwidth estimator,
    //    0 if the configuration was successfully applied.
    //
    virtual WebRtc_Word32 ConfigISACBandwidthEstimator(
        const WebRtc_UWord8  initFrameSizeMsec,
        const WebRtc_UWord16 initRateBitPerSec,
        const bool           enforceFrameSize);

    ///////////////////////////////////////////////////////////////////////////
    // SetISACMaxPayloadSize()
    // Set the maximum payload size of iSAC packets. No iSAC payload,
    // regardless of its frame-size, may exceed the given limit. For
    // an iSAC payload of size B bits and frame-size T sec we have;
    // (B < maxPayloadLenBytes * 8) and (B/T < maxRateBitPerSec), c.f.
    // SetISACMaxRate().
    //
    // Input:
    //   -maxPayloadLenBytes : maximum payload size in bytes.
    //
    // Return value:
    //   -1 if failed to set the maximm  payload-size.
    //    0 if the given linit is seet successfully.
    //
    virtual WebRtc_Word32 SetISACMaxPayloadSize(
        const WebRtc_UWord16 maxPayloadLenBytes);

    ///////////////////////////////////////////////////////////////////////////
    // SetISACMaxRate()
    // Set the maximum instantaneous rate of iSAC. For a payload of B bits
    // with a frame-size of T sec the instantaneous rate is B/T bist per
    // second. Therefore, (B/T < maxRateBitPerSec) and
    // (B < maxPayloadLenBytes * 8) are always satisfied for iSAC payloads,
    // c.f SetISACMaxPayloadSize().
    //
    // Input:
    //   -maxRateBitPerSec   : maximum instantaneous bit-rate given in bits/sec.
    //
    // Return value:
    //   -1 if failed to set the maximum rate.
    //    0 if the maximum rate is set successfully.
    //
    virtual WebRtc_Word32 SetISACMaxRate(
        const WebRtc_UWord32 maxRateBitPerSec);

    ///////////////////////////////////////////////////////////////////////////
    // SaveDecoderParamS()
    // Save the parameters of decoder.
    //
    // Input:
    //   -codecParams        : pointer to a struct where the parameters of
    //                         decoder is stored in.
    //
    void SaveDecoderParam(
        const WebRtcACMCodecParams* codecParams);

    WebRtc_Word32 FrameSize()
    {
        return _frameLenSmpl;
    }

    void SetIsMaster(bool isMaster);

    ///////////////////////////////////////////////////////////////////////////
    // REDPayloadISAC()
    // This is an iSAC-specific function. The function is called to get RED
    // paylaod from a default-encoder.
    //
    // Inputs:
    //   -isacRate           : the target rate of the main payload. A RED
    //                         paylaod is generated according to the rate of
    //                         main paylaod. Note that we are not specifying the
    //                         rate of RED payload, but the main payload.
    //   -isacBwEstimate     : bandwidth information should be inserted in
    //                         RED payload.
    //
    // Output:
    //   -payload            : pointer to a buffer where the RED paylaod will
    //                         written to.
    //   -paylaodLenBytes    : a place-holder to write the length of the RED
    //                         payload in Bytes.
    //
    // Return value:
    //   -1 if an error occures, otherwise the length of the payload (in Bytes)
    //   is returned.
    //
    //
    virtual WebRtc_Word16 REDPayloadISAC(
        const WebRtc_Word32 isacRate,
        const WebRtc_Word16 isacBwEstimate,
        WebRtc_UWord8*      payload,
        WebRtc_Word16*      payloadLenBytes);

    ///////////////////////////////////////////////////////////////////////////
    // IsTrueStereoCodec()
    // Call to see if current encoder is a true stereo codec. This function
    // should be overwritten for codecs which are true stereo codecs
    // Return value:
    //   -true  if stereo codec
    //   -false if not stereo codec.
    //
    virtual bool IsTrueStereoCodec() {
      return false;
    }

protected:
    ///////////////////////////////////////////////////////////////////////////
    // All the functions with FunctionNameSafe(...) contain the actual
    // implementation of FunctionName(...). FunctionName() acquires an
    // appropriate lock and calls FunctionNameSafe() to do the actual work.
    // Therefore, for the description of functionality, input/output arguments
    // and return value we refer to FunctionName()
    //

    ///////////////////////////////////////////////////////////////////////////
    // See Encode() for the description of function, input(s)/output(s) and
    // return value.
    //
    WebRtc_Word16 EncodeSafe(
        WebRtc_UWord8*         bitStream,
        WebRtc_Word16*         bitStreamLenByte,
        WebRtc_UWord32*        timeStamp,
        WebRtcACMEncodingType* encodingType);

    ///////////////////////////////////////////////////////////////////////////
    // See Decode() for the description of function, input(s)/output(s) and
    // return value.
    //
    virtual WebRtc_Word16 DecodeSafe(
        WebRtc_UWord8* bitStream,
        WebRtc_Word16  bitStreamLenByte,
        WebRtc_Word16* audio,
        WebRtc_Word16* audioSamples,
        WebRtc_Word8*  speechType) = 0;

    ///////////////////////////////////////////////////////////////////////////
    // See Add10MsSafe() for the description of function, input(s)/output(s)
    // and return value.
    //
    virtual WebRtc_Word32 Add10MsDataSafe(
        const WebRtc_UWord32 timeStamp,
        const WebRtc_Word16* data,
        const WebRtc_UWord16 length,
        const WebRtc_UWord8  audioChannel);

    ///////////////////////////////////////////////////////////////////////////
    // See RegisterInNetEq() for the description of function,
    // input(s)/output(s) and  return value.
    //
    virtual WebRtc_Word32 CodecDef(
        WebRtcNetEQ_CodecDef& codecDef,
        const CodecInst&  codecInst) = 0;

    ///////////////////////////////////////////////////////////////////////////
    // See EncoderParam() for the description of function, input(s)/output(s)
    // and return value.
    //
    WebRtc_Word16 EncoderParamsSafe(
        WebRtcACMCodecParams *encParams);

    ///////////////////////////////////////////////////////////////////////////
    // See DecoderParam for the description of function, input(s)/output(s)
    // and return value.
    //
    // Note:
    // Any Class where a single instance handle several flavers of the
    // same codec, therefore, several payload types are associated with
    // the same instance have to implement this function.
    //
    // Currently only iSAC is implementing it. A single iSAC instance is
    // used for decoding both WB & SWB stream. At one moment both WB & SWB
    // can be registered as receive codec. Hence two payloads are associated
    // with a single codec instance.
    //
    virtual bool  DecoderParamsSafe(
        WebRtcACMCodecParams *decParams,
        const WebRtc_UWord8  payloadType);

    ///////////////////////////////////////////////////////////////////////////
    // See ResetEncoder() for the description of function, input(s)/output(s)
    // and return value.
    //
    WebRtc_Word16 ResetEncoderSafe();

    ///////////////////////////////////////////////////////////////////////////
    // See InitEncoder() for the description of function, input(s)/output(s)
    // and return value.
    //
    WebRtc_Word16 InitEncoderSafe(
        WebRtcACMCodecParams *codecParams,
        bool                 forceInitialization);

    ///////////////////////////////////////////////////////////////////////////
    // See InitDecoder() for the description of function, input(s)/output(s)
    // and return value.
    //
    WebRtc_Word16 InitDecoderSafe(
        WebRtcACMCodecParams *codecParams,
        bool                 forceInitialization);

    ///////////////////////////////////////////////////////////////////////////
    // See ResetDecoder() for the description of function, input(s)/output(s)
    // and return value.
    //
    WebRtc_Word16 ResetDecoderSafe(
        WebRtc_Word16 payloadType);

    ///////////////////////////////////////////////////////////////////////////
    // See DestructEncoder() for the description of function,
    // input(s)/output(s) and return value.
    //
    virtual void DestructEncoderSafe() = 0;

    ///////////////////////////////////////////////////////////////////////////
    // See DestructDecoder() for the description of function,
    // input(s)/output(s) and return value.
    //
    virtual void DestructDecoderSafe() = 0;

    ///////////////////////////////////////////////////////////////////////////
    // See SetBitRate() for the description of function, input(s)/output(s)
    // and return value.
    //
    // Any codec that can change the bit-rate has to implement this.
    //
    virtual WebRtc_Word16 SetBitRateSafe(
        const WebRtc_Word32 bitRateBPS);

    ///////////////////////////////////////////////////////////////////////////
    // See GetEstimatedBandwidth() for the description of function, input(s)/output(s)
    // and return value.
    //
    virtual WebRtc_Word32 GetEstimatedBandwidthSafe();

    ///////////////////////////////////////////////////////////////////////////
    // See SetEstimatedBandwidth() for the description of function, input(s)/output(s)
    // and return value.
    //
    virtual WebRtc_Word32 SetEstimatedBandwidthSafe(WebRtc_Word32 estimatedBandwidth);

    ///////////////////////////////////////////////////////////////////////////
    // See GetRedPayload() for the description of function, input(s)/output(s)
    // and return value.
    //
    virtual WebRtc_Word32 GetRedPayloadSafe(
        WebRtc_UWord8* redPayload,
        WebRtc_Word16* payloadBytes);

    ///////////////////////////////////////////////////////////////////////////
    // See SetVAD() for the description of function, input(s)/output(s) and
    // return value.
    //
    WebRtc_Word16 SetVADSafe(
        const bool       enableDTX = true,
        const bool       enableVAD = false,
        const ACMVADMode mode      = VADNormal);

    ///////////////////////////////////////////////////////////////////////////
    // See ReplaceInternalDTX() for the description of function, input and
    // return value.
    //
    virtual WebRtc_Word32 ReplaceInternalDTXSafe(
        const bool replaceInternalDTX);

    ///////////////////////////////////////////////////////////////////////////
    // See IsInternalDTXReplaced() for the description of function, input and
    // return value.
    //
    virtual WebRtc_Word32 IsInternalDTXReplacedSafe(
        bool* internalDTXReplaced);

    ///////////////////////////////////////////////////////////////////////////
    // WebRtc_Word16 CreateEncoder()
    // Creates the encoder instance.
    //
    // Return value:
    //   -1 if failed,
    //    0 if succeeded.
    //
    WebRtc_Word16 CreateEncoder();

    ///////////////////////////////////////////////////////////////////////////
    // WebRtc_Word16 CreateDecoder()
    // Creates the decoder instance.
    //
    // Return value:
    //   -1 if failed,
    //    0 if succeeded.
    //
    WebRtc_Word16 CreateDecoder();

    ///////////////////////////////////////////////////////////////////////////
    // WebRtc_Word16 EnableVAD();
    // Enables VAD with the given mode. The VAD instance will be created if
    // it does not exists.
    //
    // Input:
    //   -mode               : VAD mode c.f. audio_coding_module_typedefs.h for
    //                         the options.
    //
    // Return value:
    //   -1 if failed,
    //    0 if succeeded.
    //
    WebRtc_Word16 EnableVAD(ACMVADMode mode);

    ///////////////////////////////////////////////////////////////////////////
    // WebRtc_Word16 DisableVAD()
    // Disables VAD.
    //
    // Return value:
    //   -1 if failed,
    //    0 if succeeded.
    //
    WebRtc_Word16 DisableVAD();

    ///////////////////////////////////////////////////////////////////////////
    // WebRtc_Word16 EnableDTX()
    // Enables DTX. This method should be overwritten for codecs which have
    // internal DTX.
    //
    // Return value:
    //   -1 if failed,
    //    0 if succeeded.
    //
    virtual WebRtc_Word16 EnableDTX();

    ///////////////////////////////////////////////////////////////////////////
    // WebRtc_Word16 DisableDTX()
    // Disables usage of DTX. This method should be overwritten for codecs which
    // have internal DTX.
    //
    // Return value:
    //   -1 if failed,
    //    0 if succeeded.
    //
    virtual WebRtc_Word16 DisableDTX();

    ///////////////////////////////////////////////////////////////////////////
    // WebRtc_Word16 InternalEncode()
    // This is a codec-specific function called in EncodeSafe() to actually
    // encode a frame of audio.
    //
    // Outputs:
    //   -bitStream          : pointer to a buffer where the bit-stream is
    //                         written to.
    //   -bitStreamLenByte   : the length of the bit-stream in bytes,
    //                         a negative value indicates error.
    //
    // Return value:
    //   -1 if failed,
    //   otherwise the length of the bit-stream is returned.
    //
    virtual WebRtc_Word16 InternalEncode(
        WebRtc_UWord8* bitStream,
        WebRtc_Word16* bitStreamLenByte) = 0;

    ///////////////////////////////////////////////////////////////////////////
    // WebRtc_Word16 InternalInitEncoder()
    // This is a codec-specific function called in InitEncoderSafe(), it has to
    // do all codec-specific operation to initialize the encoder given the
    // encoder parameters.
    //
    // Input:
    //   -codecParams        : pointer to a structure that contains parameters to
    //                         initialize encoder.
    //                         Set codecParam->CodecInst.rate to -1 for
    //                         iSAC to operate in adaptive mode.
    //                         (to do: if frame-length is -1 frame-length will be
    //                         automatically adjusted, otherwise, given
    //                         frame-length is forced)
    //
    // Return value:
    //   -1 if failed,
    //    0 if succeeded.
    //
    virtual WebRtc_Word16 InternalInitEncoder(
        WebRtcACMCodecParams *codecParams) = 0;

    ///////////////////////////////////////////////////////////////////////////
    // WebRtc_Word16 InternalInitDecoder()
    // This is a codec-specific function called in InitDecoderSafe(), it has to
    // do all codec-specific operation to initialize the decoder given the
    // decoder parameters.
    //
    // Input:
    //   -codecParams        : pointer to a structure that contains parameters to
    //                         initialize encoder.
    //
    // Return value:
    //   -1 if failed,
    //    0 if succeeded.
    //
    virtual WebRtc_Word16 InternalInitDecoder(
        WebRtcACMCodecParams *codecParams) = 0;

    ///////////////////////////////////////////////////////////////////////////
    // void IncreaseNoMissedSamples()
    // This method is called to increase the number of samples that are
    // overwritten in the audio buffer.
    //
    // Input:
    //   -noSamples          : the number of overwritten samples is incremented
    //                         by this value.
    //
    void IncreaseNoMissedSamples(
        const WebRtc_Word16 noSamples);

    ///////////////////////////////////////////////////////////////////////////
    // WebRtc_Word16 InternalCreateEncoder()
    // This is a codec-specific method called in CreateEncoderSafe() it is
    // supposed to perform all codec-specific operations to create encoder
    // instance.
    //
    // Return value:
    //   -1 if failed,
    //    0 if succeeded.
    //
    virtual WebRtc_Word16 InternalCreateEncoder() = 0;

    ///////////////////////////////////////////////////////////////////////////
    // WebRtc_Word16 InternalCreateDecoder()
    // This is a codec-specific method called in CreateDecoderSafe() it is
    // supposed to perform all codec-specific operations to create decoder
    // instance.
    //
    // Return value:
    //   -1 if failed,
    //    0 if succeeded.
    //
    virtual WebRtc_Word16 InternalCreateDecoder() = 0;

    ///////////////////////////////////////////////////////////////////////////
    // void InternalDestructEncoderInst()
    // This is a codec-specific method, used in conferencing, called from
    // DestructEncoderInst(). The input argument is pointer to encoder instance
    // (codec instance for codecs that encoder and decoder share the same
    // instance). This method is called to free the memory that "ptrInst" is
    // pointing to.
    //
    // Input:
    //   -ptrInst            : pointer to encoder instance.
    //
    // Return value:
    //   -1 if failed,
    //    0 if succeeded.
    //
    virtual void InternalDestructEncoderInst(
        void* ptrInst) = 0;

    ///////////////////////////////////////////////////////////////////////////
    // WebRtc_Word16 InternalResetEncoder()
    // This method is called to reset the states of encoder. However, the
    // current parameters, e.g. frame-length, should remain as they are. For
    // most of the codecs a re-initialization of the encoder is what needs to
    // be down. But for iSAC we like to keep the BWE history so we cannot
    // re-initialize. As soon as such an API is implemented in iSAC this method
    // has to be overwritten in ACMISAC class.
    //
    // Return value:
    //   -1 if failed,
    //    0 if succeeded.
    //
    virtual WebRtc_Word16 InternalResetEncoder();

    ///////////////////////////////////////////////////////////////////////////
    // WebRtc_Word16 ProcessFrameVADDTX()
    // This function is called when a full frame of audio is available. It will
    // break the audio frame into blocks such that each block could be processed
    // by VAD & CN/DTX. If a frame is divided into two blocks then there are two
    // cases. First, the first block is active, the second block will not be
    // processed by CN/DTX but only by VAD and return to caller with
    // '*samplesProcessed' set to zero. There, the audio frame will be encoded
    // by the encoder. Second, the first block is inactive and is processed by
    // CN/DTX, then we stop processing the next block and return to the caller
    // which is EncodeSafe(), with "*samplesProcessed" equal to the number of
    // samples in first block.
    //
    // Output:
    //   -bitStream          : pointer to a buffer where DTX frame, if
    //                         generated, will be written to.
    //   -bitStreamLenByte   : contains the length of bit-stream in bytes, if
    //                         generated. Zero if no bit-stream is generated.
    //   -noSamplesProcessed : contains no of samples that actually CN has
    //                         processed. Those samples processed by CN will not
    //                         be encoded by the encoder, obviously. If
    //                         contains zero, it means that the frame has been
    //                         identified as active by VAD. Note that
    //                         "*noSamplesProcessed" might be non-zero but
    //                         "*bitStreamLenByte" be zero.
    //
    // Return value:
    //   -1 if failed,
    //    0 if succeeded.
    //
    WebRtc_Word16 ProcessFrameVADDTX(
        WebRtc_UWord8* bitStream,
        WebRtc_Word16* bitStreamLenByte,
        WebRtc_Word16* samplesProcessed);

    ///////////////////////////////////////////////////////////////////////////
    // CanChangeEncodingParam()
    // Check if the codec parameters can be changed. In conferencing normally
    // codec parametrs cannot be changed. The exception is bit-rate of isac.
    //
    // return value:
    //   -true  if codec parameters are allowed to change.
    //   -flase otherwise.
    //
    virtual bool CanChangeEncodingParam(CodecInst& codecInst);

    ///////////////////////////////////////////////////////////////////////////
    // CurrentRate()
    // Call to get the current encoding rate of the encoder. This function
    // should be overwritten for codecs whic automatically change their
    // target rate. One example is iSAC. The output of the function is the
    // current target rate.
    //
    // Output:
    //   -rateBitPerSec      : the current target rate of the codec.
    //
    virtual void CurrentRate(
        WebRtc_Word32& /* rateBitPerSec */)
    {
        return;
    }

    virtual void SaveDecoderParamSafe(
        const WebRtcACMCodecParams* codecParams);

    // &_inAudio[_inAudioIxWrite] always point to where new audio can be
    // written to
    WebRtc_Word16         _inAudioIxWrite;

    // &_inAudio[_inAudioIxRead] points to where audio has to be read from
    WebRtc_Word16         _inAudioIxRead;

    WebRtc_Word16         _inTimestampIxWrite;

    // Where the audio is stored before encoding,
    // To save memory the following buffer can be allocated
    // dynamically for 80ms depending on the sampling frequency
    // of the codec.
    WebRtc_Word16*        _inAudio;
    WebRtc_UWord32*       _inTimestamp;

    WebRtc_Word16         _frameLenSmpl;
    WebRtc_UWord16        _noChannels;

    // This will point to a static database of the supported codecs
    WebRtc_Word16         _codecID;

    // This will account for the No of samples  were not encoded
    // the case is rare, either samples are missed due to overwite
    // at input buffer or due to encoding error
    WebRtc_UWord32        _noMissedSamples;

    // True if the encoder instance created
    bool                  _encoderExist;
    bool                  _decoderExist;
    // True if the ecncoder instance initialized
    bool                  _encoderInitialized;
    bool                  _decoderInitialized;

    bool                  _registeredInNetEq;

    // VAD/DTX
    bool                  _hasInternalDTX;
    WebRtcVadInst*        _ptrVADInst;
    bool                  _vadEnabled;
    ACMVADMode            _vadMode;
    WebRtc_Word16         _vadLabel[MAX_FRAME_SIZE_10MSEC];
    bool                  _dtxEnabled;
    WebRtcCngEncInst*     _ptrDTXInst;
    WebRtc_UWord8         _numLPCParams;
    bool                  _sentCNPrevious;
    bool                  _isMaster;

    WebRtcACMCodecParams  _encoderParams;
    WebRtcACMCodecParams  _decoderParams;

    // Used as a global lock for all avaiable decoders
    // so that no decoder is used when NetEQ decodes.
    RWLockWrapper*        _netEqDecodeLock;
    // Used to lock wrapper internal data
    // such as buffers and state variables.
    RWLockWrapper&        _codecWrapperLock;

    WebRtc_UWord32        _lastEncodedTimestamp;
    WebRtc_UWord32        _lastTimestamp;
    bool                  _isAudioBuffFresh;
    WebRtc_UWord32        _uniqueID;
};

} // namespace webrt

#endif  // WEBRTC_MODULES_AUDIO_CODING_MAIN_SOURCE_ACM_GENERIC_CODEC_H_


text:
import vtk
from vtk.test import Testing
from vtk.util.misc import vtkGetDataRoot
VTK_DATA_ROOT = vtkGetDataRoot()

sphere = vtk.vtkSphereSource()

# make two copies of the shape and distort them a little
transform1 = vtk.vtkTransform()
transform1.Translate(0.2, 0.1, 0.3)
transform1.Scale(1.3, 1.1, 0.8)

transform2 = vtk.vtkTransform()
transform2.Translate(0.3, 0.7, 0.1)
transform2.Scale(1.0, 0.1, 1.8)

transformer1 = vtk.vtkTransformPolyDataFilter()
transformer1.SetInputConnection(sphere.GetOutputPort())
transformer1.SetTransform(transform1)

transformer2 = vtk.vtkTransformPolyDataFilter()
transformer2.SetInputConnection(sphere.GetOutputPort())
transformer2.SetTransform(transform2)

# map these three shapes into the first renderer
map1a = vtk.vtkPolyDataMapper()
map1a.SetInputConnection(sphere.GetOutputPort())
Actor1a = vtk.vtkActor()
Actor1a.SetMapper(map1a)
Actor1a.GetProperty().SetDiffuseColor(1.0000, 0.3882, 0.2784)
map1b = vtk.vtkPolyDataMapper()
map1b.SetInputConnection(transformer1.GetOutputPort())
Actor1b = vtk.vtkActor()
Actor1b.SetMapper(map1b)
Actor1b.GetProperty().SetDiffuseColor(0.3882, 1.0000, 0.2784)
map1c = vtk.vtkPolyDataMapper()
map1c.SetInputConnection(transformer2.GetOutputPort())
Actor1c = vtk.vtkActor()
Actor1c.SetMapper(map1c)
Actor1c.GetProperty().SetDiffuseColor(0.3882, 0.2784, 1.0000)

# align the shapes using Procrustes (using SetModeToRigidBody)
group = vtk.vtkMultiBlockDataGroupFilter()
group.AddInputConnection(sphere.GetOutputPort())
group.AddInputConnection(transformer1.GetOutputPort())
group.AddInputConnection(transformer2.GetOutputPort())

procrustes1 = vtk.vtkProcrustesAlignmentFilter()
procrustes1.SetInputConnection(group.GetOutputPort())
procrustes1.GetLandmarkTransform().SetModeToRigidBody()
procrustes1.Update()

# map the aligned shapes into the second renderer
map2a = vtk.vtkPolyDataMapper()
map2a.SetInputData(procrustes1.GetOutput().GetBlock(0))

Actor2a = vtk.vtkActor()
Actor2a.SetMapper(map2a)
Actor2a.GetProperty().SetDiffuseColor(1.0000, 0.3882, 0.2784)

map2b = vtk.vtkPolyDataMapper()
map2b.SetInputData(procrustes1.GetOutput().GetBlock(1))

Actor2b = vtk.vtkActor()
Actor2b.SetMapper(map2b)
Actor2b.GetProperty().SetDiffuseColor(0.3882, 1.0000, 0.2784)

map2c = vtk.vtkPolyDataMapper()
map2c.SetInputData(procrustes1.GetOutput().GetBlock(2))

Actor2c = vtk.vtkActor()
Actor2c.SetMapper(map2c)
Actor2c.GetProperty().SetDiffuseColor(0.3882, 0.2784, 1.0000)

# align the shapes using Procrustes (using SetModeToSimilarity (default))
procrustes2 = vtk.vtkProcrustesAlignmentFilter()
procrustes2.SetInputConnection(group.GetOutputPort())
procrustes2.Update()

# map the aligned shapes into the third renderer
map3a = vtk.vtkPolyDataMapper()
map3a.SetInputData(procrustes2.GetOutput().GetBlock(0))

Actor3a = vtk.vtkActor()
Actor3a.SetMapper(map3a)
Actor3a.GetProperty().SetDiffuseColor(1.0000, 0.3882, 0.2784)

map3b = vtk.vtkPolyDataMapper()
map3b.SetInputData(procrustes2.GetOutput().GetBlock(1))

Actor3b = vtk.vtkActor()
Actor3b.SetMapper(map3b)
Actor3b.GetProperty().SetDiffuseColor(0.3882, 1.0000, 0.2784)

map3c = vtk.vtkPolyDataMapper()
map3c.SetInputData(procrustes2.GetOutput().GetBlock(2))

Actor3c = vtk.vtkActor()
Actor3c.SetMapper(map3c)
Actor3c.GetProperty().SetDiffuseColor(0.3882, 0.2784, 1.0000)

# Create the RenderWindow and its three Renderers
ren1 = vtk.vtkRenderer()
ren2 = vtk.vtkRenderer()
ren3 = vtk.vtkRenderer()

renWin = vtk.vtkRenderWindow()
renWin.AddRenderer(ren1)
renWin.AddRenderer(ren2)
renWin.AddRenderer(ren3)

renWin.SetSize(300, 100)

iren = vtk.vtkRenderWindowInteractor()
iren.SetRenderWindow(renWin)

# Add the actors to the renderer
ren1.AddActor(Actor1a)
ren1.AddActor(Actor1b)
ren1.AddActor(Actor1c)
ren2.AddActor(Actor2a)
ren2.AddActor(Actor2b)
ren2.AddActor(Actor2c)
ren3.AddActor(Actor3a)
ren3.AddActor(Actor3b)
ren3.AddActor(Actor3c)

# set the properties of the renderers
ren1.SetBackground(1, 1, 1)
ren1.SetViewport(0.0, 0.0, 0.33, 1.0)
ren1.ResetCamera()

ren1.GetActiveCamera().SetPosition(1, -1, 0)
ren1.ResetCamera()

ren2.SetBackground(1, 1, 1)
ren2.SetViewport(0.33, 0.0, 0.66, 1.0)
ren2.ResetCamera()

ren2.GetActiveCamera().SetPosition(1, -1, 0)
ren2.ResetCamera()

ren3.SetBackground(1, 1, 1)
ren3.SetViewport(0.66, 0.0, 1.0, 1.0)
ren3.ResetCamera()

ren3.GetActiveCamera().SetPosition(1, -1, 0)
ren3.ResetCamera()

renWin.Render()

iren.Initialize()
#iren.Start()

redpajama_set_name: RedPajamaGithub


text:
<?php

include_once("./libs/global.conf.php");

if(isset($_POST['submit'])){

    //Lets search the databse for the user name and password
    //Choose some sort of password encryption, I choose sha256
    //Password function (Not In all versions of MySQL).
    $usr = $_POST['username'];
    //$pas = hash('sha256', mysql_real_escape_string($_POST['password']));
    $pas = $_POST['password'];
    $query = $dbc -> query("SELECT * FROM Admins
        WHERE Username='$usr' AND
        Password='$pas'
        LIMIT 1");

    $results = $query -> fetch_array();

    if(empty($results)){
        header("Location: mainpage.php");
        exit;
    }else{
        session_start();
        $_SESSION['username'] = $results -> Username;
        $_SESSION['logged'] = TRUE;
        header("Location: admin_index.html"); // Modify to go to the page you would like
        exit;
    }
}else{    //If the form button wasn't submitted go to the index page, or login page
    header("Location: mainpage.php");
    exit;
}
?>


text:
using CodeTorch.Core;
using CodeTorch.Core.Commands;
using CodeTorch.Core.Messages;
using System;
using System.Linq;

namespace CodeTorch.Web.ActionCommands
{
    public class InvokeSearchMessageActionCommand : IActionCommandStrategy
    {
        public Templates.BasePage Page { get; set; }

        public ActionCommand Command { get; set; }

        InvokeSearchMessageCommand Me = null;

        public bool ExecuteCommand()
        {
            bool success = true;

            log4net.ILog log = log4net.LogManager.GetLogger(System.Reflection.MethodBase.GetCurrentMethod().DeclaringType);

            try
            {
                PerformSearchMessage search = new PerformSearchMessage();

                Page.MessageBus.Publish(search);

            }
            catch (Exception ex)
            {
                success = false;
                Page.DisplayErrorAlert(ex);

                log.Error(ex);
            }

            return success;

        }

    }
}


text:
A common way of authenticating to a remote machine over SSH is to use _keys_.

By adding your *public* key to a remote host, you can then ssh without
a password. This is convenient and secure.

To have your personal SSH key added to the vagrant VM follow these steps.

1. Add your your SSH *public* key to this directory

`user.pub`
```
ssh-rsa AAAAB3NzaC1yc2EAAAABIwAAAQEA6NF8iallvQVp22WDkTkyrtvp9eWW6A8YVr+kz4TjGYe7gHzIw+niNltGEFHzD8+v1I2YJ6oXevct1YeS0o9HZyN1Q9qgCgzUFtdOKLv6IedplqoPkcmF0aYet2PkEDo3MlTBckFXPITAMzF8dJSIFo9D8HfdOV0IAdx4O7PtixWKn5y2hMNG0zQPyUecp4pzC6kivAIhyfHilFR61RGL+GPXQ2MWZWFYbAGjyiYJnAmCP3NOTd0jMZEnDkbUvxhMmBYSdETk1rRgm+R4LOzFUGaHqHDLKLX+FIPKcF96hrucXzcWyLbIbEgE98OHlnVYCzRdK8jlqm8tehUc9c9WhQ== vagrant insecure public key
```

2. Update the `inventory.yml` to include the path to the key.

```
admin_keys: ["./admin_keys/user.pub"]
```

3. Re-run the provisioning steps

```
ansible-playbook site.yml
```

## WARNING

You should only ever include your SSH *public* key, not your _private_ key. If
you see a line like the following you are using the wrong key.

```
-----BEGIN RSA PRIVATE KEY-----
```


text:
package libcore.java.util.zip;

import junit.framework.Test;
import junit.framework.TestSuite;

public class SmallTests extends TestSuite {

  private static final Class<?>[] smallTestClasses = new Class[] {
    DeflaterInputStreamTest.class,
    DeflaterOutputStreamTest.class,
    DeflaterTest.class,
    GZIPInputStreamTest.class,
    GZIPOutputStreamTest.class,
    InflaterTest.class,
    OldAndroidChecksumTest.class,
    OldAndroidDeflateTest.class,
    OldAndroidGZIPStreamTest.class,
    OldAndroidZipStreamTest.class,
    OldDataFormatExceptionTest.class,
    ZipEntryTest.class,
    ZipFileTest.class,
    ZipInputStreamTest.class,
    ZipOutputStreamTest.class
  };

  public static Test suite() {
    return new TestSuite(smallTestClasses);
  }
}


text:
<?php

/* CriveroPruebaBundle:Default:inicio.html.twig */
class __TwigTemplate_4d576b7d7712eb16a66fce1239fb845dc0f92ac09641619cc1a2555c3b829192 extends Twig_Template
{
    public function __construct(Twig_Environment $env)
    {
        parent::__construct($env);

        // line 1
        try {
            $this->parent = $this->env->loadTemplate("::base.html.twig");
        } catch (Twig_Error_Loader $e) {
            $e->setTemplateFile($this->getTemplateName());
            $e->setTemplateLine(1);

            throw $e;
        }

        $this->blocks = array(
            'title' => array($this, 'block_title'),
            'stylesheets' => array($this, 'block_stylesheets'),
            'body' => array($this, 'block_body'),
            'javascripts' => array($this, 'block_javascripts'),
        );
    }

    protected function doGetParent(array $context)
    {
        return "::base.html.twig";
    }

    protected function doDisplay(array $context, array $blocks = array())
    {
        $this->parent->display($context, array_merge($this->blocks, $blocks));
    }

    // line 3
    public function block_title($context, array $blocks = array())
    {
        echo "Bienvenido!";
    }

    // line 4
    public function block_stylesheets($context, array $blocks = array())
    {
        // line 5
        echo "    ";
        $this->displayParentBlock("stylesheets", $context, $blocks);
        echo "
    <link href=\"";
        // line 6
        echo twig_escape_filter($this->env, $this->env->getExtension('assets')->getAssetUrl("css/slider.css"), "html", null, true);
        echo "\" type=\"text/css\" rel=\"stylesheet\">
";
    }

    // line 9
    public function block_body($context, array $blocks = array())
    {
        // line 10
        echo "

Nuestras instalaciones

fefbewfkefefiehefiefe ijfejfiojiojieofjioo fefbewfkefefiehefiefe ijfejfiojiojieofjioofefbewfkefefiehefiefe ijfejfiojiojieofjioo
                    fefbewfkefefiehefiefe ijfejfiojiojieofjioofefbewfkefefiehefiefe ijfejfiojiojieofjioofefbewfkefefiehefiefe ijfejfiojiojieofjioofefbewfkefefiehefiefe ijfejfiojiojieofjioo
                    fefbewfkefefiehefiefe ijfejfiojiojieofjioofefbewfkefefiehefiefe ijfejfiojiojieofjioofefbewfkefefiehefiefe ijfejfiojiojieofjioo

                    ";
        // line 21
        $context['_parent'] = (array) $context;
        $context['_seq'] = twig_ensure_traversable((isset($context["publicaciones"]) ? $context["publicaciones"] : $this->getContext($context, "publicaciones")));
        foreach ($context['_seq'] as $context["_key"] => $context["publicacion"]) {
            // line 22
            echo "

                            ";
            // line 23
            if ((twig_length_filter($this->env, (isset($context["publicaciones"]) ? $context["publicaciones"] : $this->getContext($context, "publicaciones"))) > 1)) {
                // line 24
                echo "                                env, $this->env->getExtension('assets')->getAssetUrl(("images/" . $this->getAttribute($context["publicacion"], "imagen", array()))), "html", null, true);
                echo "\" title=";
                echo twig_escape_filter($this->env, $this->getAttribute($context["publicacion"], "titulo", array()), "html", null, true);
                echo ">
                            ";
            } else {
                // line 26
                echo "                                env, $this->env->getExtension('assets')->getAssetUrl(("images/" . $this->getAttribute($context["publicacion"], "imagen", array()))), "html", null, true);
                echo "\" style=\"max-width: 91%\" title=";
                echo twig_escape_filter($this->env, $this->getAttribute($context["publicacion"], "titulo", array()), "html", null, true);
                echo " >
                            ";
            }
            // line 28
            echo "

                    ";
        }
        $_parent = $context['_parent'];
        unset($context['_seq'], $context['_iterated'], $context['_key'], $context['publicacion'], $context['_parent'], $context['loop']);
        $context = array_intersect_key($context, $_parent) + $_parent;
        // line 30
        echo "

                    ";
        // line 37
        $context['_parent'] = (array) $context;
        $context['_seq'] = twig_ensure_traversable((isset($context["publicaciones"]) ? $context["publicaciones"] : $this->getContext($context, "publicaciones")));
        foreach ($context['_seq'] as $context["_key"] => $context["publicacion"]) {
            // line 38
            echo "

                            ";
            // line 39
            if ((twig_length_filter($this->env, (isset($context["publicaciones"]) ? $context["publicaciones"] : $this->getContext($context, "publicaciones"))) > 1)) {
                // line 40
                echo "                                env, $this->env->getExtension('assets')->getAssetUrl(("images/" . $this->getAttribute($context["publicacion"], "imagen", array()))), "html", null, true);
                echo "\" title=";
                echo twig_escape_filter($this->env, $this->getAttribute($context["publicacion"], "titulo", array()), "html", null, true);
                echo ">
                            ";
            } else {
                // line 42
                echo "                                env, $this->env->getExtension('assets')->getAssetUrl(("images/" . $this->getAttribute($context["publicacion"], "imagen", array()))), "html", null, true);
                echo "\" style=\"max-width: 91%\" title=";
                echo twig_escape_filter($this->env, $this->getAttribute($context["publicacion"], "titulo", array()), "html", null, true);
                echo " >
                            ";
            }
            // line 44
            echo "

                    ";
        }
        $_parent = $context['_parent'];
        unset($context['_seq'], $context['_iterated'], $context['_key'], $context['publicacion'], $context['_parent'], $context['loop']);
        $context = array_intersect_key($context, $_parent) + $_parent;
        // line 46
        echo "

Nuestras instalaciones

fefbewfkefefiehefiefe ijfejfiojiojieofjioo fefbewfkefefiehefiefe ijfejfiojiojieofjioofefbewfkefefiehefiefe ijfejfiojiojieofjioo
                    fefbewfkefefiehefiefe ijfejfiojiojieofjioofefbewfkefefiehefiefe ijfejfiojiojieofjioofefbewfkefefiehefiefe ijfejfiojiojieofjioofefbewfkefefiehefiefe ijfejfiojiojieofjioo
                    fefbewfkefefiehefiefe ijfejfiojiojieofjioofefbewfkefefiehefiefe ijfejfiojiojieofjioofefbewfkefefiehefiefe ijfejfiojiojieofjioo

";
    }

    // line 59
    public function block_javascripts($context, array $blocks = array())
    {
        // line 60
        echo "    ";
        $this->displayParentBlock("javascripts", $context, $blocks);
        echo "

    ";
        // line 62
        if ((twig_length_filter($this->env, (isset($context["publicaciones"]) ? $context["publicaciones"] : $this->getContext($context, "publicaciones"))) > 1)) {
            // line 63
            echo "
    ";
        }
    }

    public function getTemplateName()
    {
        return "CriveroPruebaBundle:Default:inicio.html.twig";
    }

    public function isTraitable()
    {
        return false;
    }

    public function getDebugInfo()
    {
        return array (  178 => 63,  176 => 62,  172 => 61,  167 => 60,  164 => 59,  148 => 46,  141 => 44,  133 => 42,  125 => 40,  123 => 39,  120 => 38,  116 => 37,  107 => 30,  100 => 28,  92 => 26,  84 => 24,  82 => 23,  79 => 22,  75 => 21,  62 => 10,  59 => 9,  53 => 6,  48 => 5,  45 => 4,  39 => 3,  11 => 1,);
    }
}


text:
<?php

/**
 * BaseDmError
 *
 * This class has been auto-generated by the Doctrine ORM Framework
 *
 * @property string $php_class
 * @property string $name
 * @property string $description
 * @property string $module
 * @property string $action
 * @property string $uri
 * @property string $env
 *
 * @method string  getPhpClass()    Returns the current record's "php_class" value
 * @method string  getName()        Returns the current record's "name" value
 * @method string  getDescription() Returns the current record's "description" value
 * @method string  getModule()      Returns the current record's "module" value
 * @method string  getAction()      Returns the current record's "action" value
 * @method string  getUri()         Returns the current record's "uri" value
 * @method string  getEnv()         Returns the current record's "env" value
 * @method DmError setPhpClass()    Sets the current record's "php_class" value
 * @method DmError setName()        Sets the current record's "name" value
 * @method DmError setDescription() Sets the current record's "description" value
 * @method DmError setModule()      Sets the current record's "module" value
 * @method DmError setAction()      Sets the current record's "action" value
 * @method DmError setUri()         Sets the current record's "uri" value
 * @method DmError setEnv()         Sets the current record's "env" value
 *
 * @package    retest
 * @subpackage model
 * @author     Your name here
 * @version    SVN: $Id: Builder.php 7490 2010-03-29 19:53:27Z jwage $
 */
abstract class BaseDmError extends myDoctrineRecord
{
    public function setTableDefinition()
    {
        $this->setTableName('dm_error');
        $this->hasColumn('php_class', 'string', 127, array(
             'type' => 'string',
             'notnull' => true,
             'length' => 127,
             ));
        $this->hasColumn('name', 'string', 255, array(
             'type' => 'string',
             'notnull' => true,
             'length' => 255,
             ));
        $this->hasColumn('description', 'string', 60000, array(
             'type' => 'string',
             'length' => 60000,
             ));
        $this->hasColumn('module', 'string', 127, array(
             'type' => 'string',
             'notnull' => false,
             'length' => 127,
             ));
        $this->hasColumn('action', 'string', 127, array(
             'type' => 'string',
             'notnull' => false,
             'length' => 127,
             ));
        $this->hasColumn('uri', 'string', 255, array(
             'type' => 'string',
             'notnull' => true,
             'length' => 255,
             ));
        $this->hasColumn('env', 'string', 63, array(
             'type' => 'string',
             'notnull' => true,
             'length' => 63,
             ));
    }

    public function setUp()
    {
        parent::setUp();
        $timestampable0 = new Doctrine_Template_Timestampable(array(
             'updated' =>
             array(
              'disabled' => true,
             ),
             ));
        $this->actAs($timestampable0);
    }
}


text:
CREATE TABLE `flags` (
    `id` int(11) unsigned AUTO_INCREMENT NOT NULL PRIMARY KEY,
    `addon_id` int(11) unsigned NOT NULL UNIQUE,
    `created` datetime NOT NULL,
    `modified` datetime NOT NULL,
    `adult_content` int(1) unsigned NOT NULL DEFAULT '0',
    `child_content` int(1) unsigned NOT NULL DEFAULT '0'
) ENGINE=InnoDB CHARACTER SET utf8 COLLATE utf8_general_ci;

ALTER TABLE `flags` ADD CONSTRAINT `addon_id_refs_id_12bf23e` FOREIGN KEY (`addon_id`) REFERENCES `addons` (`id`);

CREATE INDEX `flags_2c4ada64` ON `flags` (`adult_content`);
CREATE INDEX `flags_5462cd52` ON `flags` (`child_content`);


text:
require File.expand_path(File.dirname(__FILE__) + '/../../test_config.rb')

describe "Qiankun::Wuye::AreasHelper" do
  setup do
    helpers = Class.new
    helpers.extend Qiankun::Wuye::AreasHelper
    [helpers.foo]
  end

  asserts("#foo"){ topic.first }.nil
end


text:
NSString *const kMDWampSerializationMsgpack = @"MDWampSerializationMsgpack";
NSString *const kMDWampSerializationJSON    = @"MDWampSerializationJSON";
NSString *const kMDWampErrorDomain          = @"it.mogui.MDWamp";

NSString *const MDWampOption_exclude_me         = @"exclude_me";
NSString *const MDWampOption_disclose_me        = @"disclose_me";
NSString *const MDWampOption_acknowledge        = @"acknowledge";
NSString *const MDWampOption_receive_progress   = @"receive_progress";
NSString *const MDWampOption_progress           = @"progress";
NSString *const MDWampOption_exclude            = @"exclude";
NSString *const MDWampOption_eligible           = @"eligible";
NSString *const MDWampOption_match              = @"match";


text:
using Yak.Common;

namespace Yak.Nerves
{
    public class LoggingYakNerves : IYakNerves
    {
        private readonly ILog log;

        public LoggingYakNerves(ILog log)
        {
            this.log = log;
        }

        public void SetPin(Pin pin, bool high)
        {
            var message = string.Format("SET PIN {0} TO {1}", pin, high ? "ON" : "OFF");
            this.log.Info(message);
        }

        public void Initialize()
        {
        }

        public void TearDown()
        {
        }
    }
}


text:
1.0.0-RC2 (2015-09-10)

* Fix bug with duplicating ObjectIdentities in case when several permissions are granted to the same object

1.0.0-RC1 (2015-09-03)

Initial release


text:
using UnityEngine;

namespace com.lizitt
{
    /// <summary>
    /// Represents a pointer to a specific renderer material index.
    /// (A renderer/material index pair.)
    /// </summary>
    [System.Serializable]
    public class RendererMaterialPtr
    {
        [SerializeField]
        [Tooltip("The renderer the material index applies to, or null for 'unspecified'.")]
        private Renderer m_Renderer = null;

        [SerializeField]
        [Tooltip("The index of the material in the render's material array, or -1 for"
            + " 'unspecified'.")]
        private int m_MaterialIndex = -1;

        /// <summary>
        /// Constructor.
        /// </summary>
        /// <remarks>
        /// <para>
        /// The constructor will accept a null renderer to allow for flexibility.  If
        /// <paramref name="renderer "/>is null, <paramref name="materialIndex"/> will
        /// be forced to -1.
        /// </para>
        /// </remarks>
        /// <param name="renderer">The target renderer.</param>
        /// <param name="materialIndex">
        /// The index of the material in the renderer's material array, or -1 for 'undefined'.
        /// </param>
        public RendererMaterialPtr(Renderer renderer = null, int materialIndex = -1)
        {
            Set(renderer, materialIndex);
        }

        /// <summary>
        /// True if the pointer is fully defined. (Points to a material.)
        /// </summary>
        /// <remarks>
        /// <para>
        /// Because the number of materials in a render is not expected to change, and the cost
        /// of getting a material count, the material index is only validated when it is set.
        /// </para>
        /// </remarks>
        public bool IsDefined
        {
            get { return m_Renderer && m_MaterialIndex >= 0; }
        }

        /// <summary>
        /// The renderer <see cref="MaterialIndex"/> applies to.
        /// </summary>
        /// <remarks>
        /// <para>
        /// A value of null means 'undefined.'
        /// </para>
        /// </remarks>
        public Renderer Renderer
        {
            get { return m_Renderer; }
        }

        /// <summary>
        /// The index of the material in the render's material array, or -1 for 'undefined'.
        /// </summary>
        /// <para>
        /// <para>
        /// Because the number of materials in a render is not expected to change, and the cost
        /// of getting a material count, the material index is only validated when it is set.
        /// </para>
        /// </para>
        public int MaterialIndex
        {
            get { return m_MaterialIndex; }
        }

        /// <summary>
        /// The shared material assigned to the pointer's index, or null if the pointer is
        /// 'undefined'.
        /// </summary>
        public Material SharedMaterial
        {
            get
            {
                if (IsDefined)
                {
                    var mats = m_Renderer.sharedMaterials;
                    if (m_MaterialIndex < mats.Length)  // Check is needed so editors don't get stuck in exceptions.
                        return mats[m_MaterialIndex];
                }

                return null;
            }
        }

        /// <summary>
        /// Sets the renderer and material index.
        /// </summary>
        /// <remarks>
        /// <para>
        /// A <paramref name="renderer"/> value of null represents an 'undefined' state and will
        /// force <paramref name="materialIndex"/> to -1.
        /// </para>
        /// </remarks>
        /// <param name="renderer">
        /// The renderer the material index applies to, or null for 'undefined'.
        /// </param>
        /// <param name="materialIndex">
        /// The index of the material in the render's material array, or -1 for 'undefined'.
        /// </param>
        public void Set(Renderer renderer, int materialIndex)
        {
            if (!renderer)
            {
                m_Renderer = null;
                m_MaterialIndex = -1;
                return;
            }

            if (materialIndex != -1)
            {
                if (materialIndex < 0 || materialIndex >= renderer.sharedMaterials.Length)
                {
                    Debug.LogError("Material index is out of range.");
                    materialIndex = -1;
                }
            }

            m_Renderer = renderer;
            m_MaterialIndex = materialIndex;
        }

        /// <summary>
        /// Applies the material as a shared material to the defined renderer and material index.
        /// </summary>
        /// <remarks>
        /// <para>
        /// A null material will be ignored, so it is not possible to use the method to apply
        /// a null material.
        /// </para>
        /// <para>
        /// If <see cref="IsDefined"/> is false, no action will be taken.  (This is not
        /// considered an error.)
        /// </para>
        /// </remarks>
        /// <param name="material">The material to apply.</param>
        /// <returns>
        /// True if the material was applied, or false if no change was made.
        /// </returns>
        public bool ApplySharedMaterial(Material material)
        {
            return ApplySharedMaterial(material, m_Renderer, m_MaterialIndex);
        }

        /// <summary>
        /// Applies the material as a shared material to the renderer at the specified index.
        /// </summary>
        /// <remarks>
        /// <para>
        /// The only invalid parameter value is a material index that is out of range and
        /// not -1.  A null material, null renderer, or -1 index means that no
        /// change will occur.
        /// </para>
        /// <para>
        /// It is not possible to use the method to apply a null material.
        /// </para>
        /// </remarks>
        /// <param name="material">The material to apply. (Required)</param>
        /// <param name="renderer">The renderer to apply to the material to.</param>
        /// <param name="materialIndex">The material index to assign the material to.</param>
        /// <returns>
        /// True if the material was applied, or false if no change was made.
        /// </returns>
        public static bool ApplySharedMaterial(Material material, Renderer renderer, int materialIndex)
        {
            if (!material || !renderer || materialIndex == -1)
                // This is OK.  It just means that there is no override to apply.
                return false;

            var mats = renderer.sharedMaterials;
            mats[materialIndex] = material;
            renderer.sharedMaterials = mats;

            return true;
        }
    }
}


text:
#region Using directives

using System;
using System.Collections.Generic;
using System.Text;

#endregion

namespace %namespace%
{
	class %className%
	{
		static void Main(string[] args)
		{
			Console.WriteLine("Hello");

		}
	}
}


text:
{% extends "helpers/layout.html" %}
{% block title %}Create Course{% endblock %}
{% block body %}
    {% from "helpers/_formhelpers.html" import render_field %}
    <form method="post" action="">
        <dl>
            {{ render_field(form.name) }}
            {{ render_field(form.ident) }}
            {{ render_field(form.section) }}
            {{ render_field(form.description) }}
            {{ form.hidden_tag() }}
        </dl>
        <input type="submit" value="Create">
    </form>

{% endblock %}


text:
<?php
namespace Alaxos\Lib;

use Cake\Utility\Security;

/**
 *
 * @author   Nicolas Rod <nico@alaxos.com>
 * @license  http://www.opensource.org/licenses/mit-license.php The MIT License
 * @link     http://www.alaxos.ch
 */
class SecurityTool
{
    private static $token_salt = 'Get me if you can !';

    public static function get_valid_fieldnames()
    {
        $today_fieldname     = SecurityTool::get_today_fieldname();
        $yesterday_fieldname = SecurityTool::get_yesterday_fieldname();

        return array($today_fieldname, $yesterday_fieldname);
    }

    public static function get_today_fieldname($salt = null)
    {
        return Security::hash($salt . date('d.M.Y', time()), null, true);
    }

    public static function get_yesterday_fieldname($salt = null)
    {
        return Security::hash($salt . date('d.M.Y', strtotime(date('Y-m-d')) - 1), null, true);
    }

    public static function get_today_token($salt = null)
    {
        return Security::hash($salt . SecurityTool::$token_salt . date('d.M.Y', time()), null, true);
    }

    public static function get_yesterday_token($salt = null)
    {
        return Security::hash($salt . SecurityTool::$token_salt . date('d.M.Y', strtotime(date('Y-m-d')) - 1), null, true);
    }
}


text:
namespace System.Web.UI.WebControls {

    using System;
    using System.Collections;
    using System.ComponentModel;
    using System.Collections.Specialized;
    using System.Drawing;
    using System.Web;
    using System.Web.UI;
    using System.Web.UI.WebControls.Adapters;

    /// <devdoc>
    ///    <para>Creates a control that allows the user to select a single item from a
    ///       drop-down list.</para>
    /// </devdoc>
    [
    SupportsEventValidation,
    ValidationProperty("SelectedItem")
    ]
    public class DropDownList : ListControl, IPostBackDataHandler {

        /// <devdoc>
        /// <para>Initializes a new instance of the <see cref='System.Web.UI.WebControls.DropDownList'/> class.</para>
        /// </devdoc>
        public DropDownList() {
        }

        /// <devdoc>
        ///    <para>[To be supplied.]</para>
        /// </devdoc>
        [
        Browsable(false)
        ]
        public override Color BorderColor {
            get {
                return base.BorderColor;
            }
            set {
                base.BorderColor = value;
            }
        }

        /// <devdoc>
        ///    <para>[To be supplied.]</para>
        /// </devdoc>
        [
        Browsable(false)
        ]
        public override BorderStyle BorderStyle {
            get {
                return base.BorderStyle;
            }
            set {
                base.BorderStyle = value;
            }
        }

        /// <devdoc>
        ///    <para>[To be supplied.]</para>
        /// </devdoc>
        [
        Browsable(false)
        ]
        public override Unit BorderWidth {
            get {
                return base.BorderWidth;
            }
            set {
                base.BorderWidth = value;
            }
        }

        public override bool SupportsDisabledAttribute {
            get {
                return true;
            }
        }

        /// <devdoc>
        ///    <para>Gets or sets the index of the item selected by the user
        ///       from the <see cref='System.Web.UI.WebControls.DropDownList'/>
        ///       control.</para>
        /// </devdoc>
        [
        WebCategory("Behavior"),
        DefaultValue(0),
        WebSysDescription(SR.WebControl_SelectedIndex),
        DesignerSerializationVisibility(DesignerSerializationVisibility.Hidden)
        ]
        public override int SelectedIndex {
            get {
                int selectedIndex = base.SelectedIndex;
                if (selectedIndex < 0 && Items.Count > 0) {
                    Items[0].Selected = true;
                    selectedIndex = 0;
                }
                return selectedIndex;
            }
            set {
                base.SelectedIndex = value;
            }
        }

        internal override ArrayList SelectedIndicesInternal {
            get {
                int sideEffect = SelectedIndex;
                return base.SelectedIndicesInternal;
            }
        }

        protected override void AddAttributesToRender(HtmlTextWriter writer) {
            string uniqueID = UniqueID;
            if (uniqueID != null) {
                writer.AddAttribute(HtmlTextWriterAttribute.Name, uniqueID);
            }

            base.AddAttributesToRender(writer);
        }

        protected override ControlCollection CreateControlCollection() {
            return new EmptyControlCollection(this);
        }

        /// <internalonly/>
        /// <devdoc>
        /// <para>Process posted data for the <see cref='System.Web.UI.WebControls.DropDownList'/> control.</para>
        /// </devdoc>
        bool IPostBackDataHandler.LoadPostData(String postDataKey, NameValueCollection postCollection) {
            return LoadPostData(postDataKey, postCollection);
        }

        /// <internalonly/>
        /// <devdoc>
        /// <para>Process posted data for the <see cref='System.Web.UI.WebControls.DropDownList'/> control.</para>
        /// </devdoc>
        protected virtual bool LoadPostData(String postDataKey, NameValueCollection postCollection) {

            // When a DropDownList is disabled, then there is no postback data for it.
            // Since DropDownList doesn't call RegisterRequiresPostBack, this method will
            // never be called, so we don't need to worry about ignoring empty postback data.

            string [] selectedItems = postCollection.GetValues(postDataKey);

            EnsureDataBound();
            if (selectedItems != null) {

                ValidateEvent(postDataKey, selectedItems[0]);

                int n = Items.FindByValueInternal(selectedItems[0], false);

                if (SelectedIndex != n) {
                    SetPostDataSelection(n);
                    return true;
                }
            }

            return false;
        }

        /// <internalonly/>
        /// <devdoc>
        /// <para>Raises events for the <see cref='System.Web.UI.WebControls.DropDownList'/> control on post back.</para>
        /// </devdoc>
        void IPostBackDataHandler.RaisePostDataChangedEvent() {
            RaisePostDataChangedEvent();
        }

        /// <internalonly/>
        /// <devdoc>
        /// <para>Raises events for the <see cref='System.Web.UI.WebControls.DropDownList'/> control on post back.</para>
        /// </devdoc>
        protected virtual void RaisePostDataChangedEvent() {
            if (AutoPostBack && !Page.IsPostBackEventControlRegistered) {
                // VSWhidbey 204824
                Page.AutoPostBackControl = this;

                if (CausesValidation) {
                    Page.Validate(ValidationGroup);
                }
            }
            OnSelectedIndexChanged(EventArgs.Empty);
        }

        protected internal override void VerifyMultiSelect() {
            throw new HttpException(SR.GetString(SR.Cant_Multiselect, "DropDownList"));
        }
    }
}


text:
package com.siyeh.igtest.style.unnecessary_final_on_local_variable_or_parameter;

public class UnnecessaryFinalOnLocalVariableOrParameter {
  class XX {
    XX(Object o) {}

    void foo(final Object o) {
      new XX(o) {};
    }

    void m(final Object o) {
      new XX(null) {
        Object b = o;
      };
    }
  }
}


text:
package io.flinkspector.core.quantify

import io.flinkspector.core.CoreSpec
import org.apache.flink.api.java.tuple.{Tuple2 => Fluple2, Tuple3 => Fluple3}

class TupleMapSpec extends CoreSpec {

  "The tuple map" should "map a tuple" in {
    val tmap = new TupleMap[Fluple2[String, Int]](
      Fluple2.of("test", 2), Array("key", "value")
    )

    tmap.getKeys should contain only("key", "value")
    tmap.get[String]("key") shouldBe "test"
    tmap.get[Int]("value") shouldBe 2
  }

  it should "partially map a tuple" in {
    val tmap = new TupleMap[Fluple2[String, Int]](
      Fluple2.of("test", 2), Array("key")
    )

    tmap.get[String]("key") shouldBe "test"
    an[IllegalArgumentException] shouldBe thrownBy(tmap.get[Integer]("value"))
  }

  it should "map a tuple with placeholder" in {
    val tmap = new TupleMap[Fluple2[String, Int]](
      Fluple2.of("test", 2), Array(null, "value")
    )

    tmap.get[Integer]("value") shouldBe 2

    an[IllegalArgumentException] shouldBe thrownBy(tmap.get[String](null))
  }

  it should "accept multiple placeholders" in {
    var tmap = new TupleMap[Fluple3[String, Int, Int]](
      Fluple3.of("test", 1, 2), Array(null, "value", null)
    )

    tmap.get[Int]("value") shouldBe 1

    tmap = new TupleMap[Fluple3[String, Int, Int]](
      Fluple3.of("test", 1, 2), Array(null, null, "value")
    )

    tmap.get[Int]("value") shouldBe 2
  }

  it should "not accept too many keys" in {
    an[IllegalArgumentException] shouldBe thrownBy {
      new TupleMap[Fluple3[String, Int, Int]](
        Fluple3.of("test", 1, 2), Array("key", "value", null, "v2")
      )
    }
  }
}


text:
//------------------------------------------------------------------------------
// <auto-generated>
//     This code was generated by a tool.
//     Runtime Version:4.0.30319.42000
//
//     Changes to this file may cause incorrect behavior and will be lost if
//     the code is regenerated.
// </auto-generated>
//------------------------------------------------------------------------------

namespace vitasa {
    using System;
    using System.Reflection;

    [System.CodeDom.Compiler.GeneratedCodeAttribute("System.Resources.Tools.StronglyTypedResourceBuilder", "4.0.0.0")]
    [System.Diagnostics.DebuggerNonUserCodeAttribute()]
    [System.Runtime.CompilerServices.CompilerGeneratedAttribute()]
    internal class AppResourcesEs {

        private static System.Resources.ResourceManager resourceMan;

        private static System.Globalization.CultureInfo resourceCulture;

        [System.Diagnostics.CodeAnalysis.SuppressMessageAttribute("Microsoft.Performance", "CA1811:AvoidUncalledPrivateCode")]
        internal AppResourcesEs() {
        }

        [System.ComponentModel.EditorBrowsableAttribute(System.ComponentModel.EditorBrowsableState.Advanced)]
        internal static System.Resources.ResourceManager ResourceManager {
            get {
                if (object.Equals(null, resourceMan)) {
                    System.Resources.ResourceManager temp = new System.Resources.ResourceManager("vitasa.AppResourcesEs", typeof(AppResourcesEs).Assembly);
                    resourceMan = temp;
                }
                return resourceMan;
            }
        }

        [System.ComponentModel.EditorBrowsableAttribute(System.ComponentModel.EditorBrowsableState.Advanced)]
        internal static System.Globalization.CultureInfo Culture {
            get {
                return resourceCulture;
            }
            set {
                resourceCulture = value;
            }
        }
    }
}


text:
require 'spec_helper'
require 'helpers/unit_spec_helper'

describe Puppet::Type.type(:gce_httphealthcheck) do
  let(:params) { [:name,
                  :description,
                  :check_interval,
                  :timeout,
                  :healthy_threshold,
                  :host,
                  :port,
                  :request_path,
                  :unhealthy_threshold] }
  let(:create_params) { {:name => 'name'} }

  it_behaves_like "a resource with expected parameters"
  it_behaves_like "it has a validated name"
end


text:
/*
 / _____)             _              | |
( (____  _____ ____ _| |_ _____  ____| |__
 \____ \| ___ |    (_   _) ___ |/ ___)  _ \
 _____) ) ____| | | || |_| ____( (___| | | |
(______/|_____)_|_|_| \__)_____)\____)_| |_|
    (C)2013 Semtech

Description: SX1272 driver specific target board functions implementation

License: Revised BSD License, see LICENSE.TXT file include in the project

Maintainer: Miguel Luis and Gregory Cristian
*/
 /*******************************************************************************
  * @file    sx1272mb2das.c
  * @author  MCD Application Team
  * @version V1.0.2
  * @date    27-February-2017
  * @brief   driver sx1272 board ( sx1272mb2das )
  ******************************************************************************
  * @attention
  *
  *
© COPYRIGHT(c) 2017 STMicroelectronics

  *
  * Redistribution and use in source and binary forms, with or without modification,
  * are permitted provided that the following conditions are met:
  *   1. Redistributions of source code must retain the above copyright notice,
  *      this list of conditions and the following disclaimer.
  *   2. Redistributions in binary form must reproduce the above copyright notice,
  *      this list of conditions and the following disclaimer in the documentation
  *      and/or other materials provided with the distribution.
  *   3. Neither the name of STMicroelectronics nor the names of its contributors
  *      may be used to endorse or promote products derived from this software
  *      without specific prior written permission.
  *
  * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS"
  * AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE
  * IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE
  * DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT HOLDER OR CONTRIBUTORS BE LIABLE
  * FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL
  * DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR
  * SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER
  * CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY,
  * OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE
  * OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
  *
  ******************************************************************************
  */
/* Define to prevent recursive inclusion -------------------------------------*/
#ifndef __SX1272MB2DAS__
#define __SX1272MB2DAS__

#ifdef __cplusplus
 extern "C" {
#endif

/* Includes ------------------------------------------------------------------*/
/* Exported types ------------------------------------------------------------*/
/* Exported constants --------------------------------------------------------*/

#define BOARD_WAKEUP_TIME  0 // no TCXO
/*!
 * \brief Radio hardware registers initialization definition
 *
 * \remark Can be automatically generated by the SX1272 GUI (not yet implemented)
 */
#define RADIO_INIT_REGISTERS_VALUE                \
{                                                 \
    { MODEM_FSK , REG_LNA                , 0x23 },\
    { MODEM_FSK , REG_RXCONFIG           , 0x1E },\
    { MODEM_FSK , REG_RSSICONFIG         , 0xD2 },\
    { MODEM_FSK , REG_AFCFEI             , 0x01 },\
    { MODEM_FSK , REG_PREAMBLEDETECT     , 0xAA },\
    { MODEM_FSK , REG_OSC                , 0x07 },\
    { MODEM_FSK , REG_SYNCCONFIG         , 0x12 },\
    { MODEM_FSK , REG_SYNCVALUE1         , 0xC1 },\
    { MODEM_FSK , REG_SYNCVALUE2         , 0x94 },\
    { MODEM_FSK , REG_SYNCVALUE3         , 0xC1 },\
    { MODEM_FSK , REG_PACKETCONFIG1      , 0xD8 },\
    { MODEM_FSK , REG_FIFOTHRESH         , 0x8F },\
    { MODEM_FSK , REG_IMAGECAL           , 0x02 },\
    { MODEM_FSK , REG_DIOMAPPING1        , 0x00 },\
    { MODEM_FSK , REG_DIOMAPPING2        , 0x30 },\
    { MODEM_LORA, REG_LR_DETECTOPTIMIZE  , 0x43 },\
    { MODEM_LORA, REG_LR_PAYLOADMAXLENGTH, 0x40 },\
}                                                 \

/* Exported functions ------------------------------------------------------- */

/*!
 * \brief Initializes the radio I/Os pins interface
 */
void SX1272IoInit( void );

/*!
 * \brief Initializes DIO IRQ handlers
 *
 * \param [IN] irqHandlers Array containing the IRQ callback functions
 */
void SX1272IoIrqInit( DioIrqHandler **irqHandlers );

/*!
 * \brief De-initializes the radio I/Os pins interface.
 *
 * \remark Useful when going in MCU lowpower modes
 */
void SX1272IoDeInit( void );

/*!
 * \brief Sets the radio output power.
 *
 * \param [IN] power Sets the RF output power
 */
void SX1272SetRfTxPower( int8_t power );

/*!
 * \brief Gets the board PA selection configuration
 *
 * \param [IN] channel Channel frequency in Hz
 * \retval PaSelect RegPaConfig PaSelect value
 */
uint8_t SX1272GetPaSelect( uint32_t channel );

/*!
 * \brief Set the RF Switch I/Os pins in Low Power mode
 *
 * \param [IN] status enable or disable
 */
void SX1272SetAntSwLowPower( bool status );

/*!
 * \brief Initializes the RF Switch I/Os pins interface
 */
void SX1272AntSwInit( void );

/*!
 * \brief De-initializes the RF Switch I/Os pins interface
 *
 * \remark Needed to decrease the power consumption in MCU lowpower modes
 */
void SX1272AntSwDeInit( void );

/*!
 * \brief Controls the antenna switch if necessary.
 *
 * \remark see errata note
 *
 * \param [IN] opMode Current radio operating mode
 */
void SX1272SetAntSw( uint8_t opMode );

/*!
 * \brief Checks if the given RF frequency is supported by the hardware
 *
 * \param [IN] frequency RF frequency to be checked
 * \retval isSupported [true: supported, false: unsupported]
 */
bool SX1272CheckRfFrequency( uint32_t frequency );

/*!
 * Radio hardware and global parameters
 */
extern SX1272_t SX1272;

#ifdef __cplusplus
}
#endif

#endif /* __SX1272MB2DAS__ */

/************************ (C) COPYRIGHT STMicroelectronics *****END OF FILE****/