text:
#ifndef TALK_SESSION_PHONE_FAKEWEBRTCVOICEENGINE_H_
#define TALK_SESSION_PHONE_FAKEWEBRTCVOICEENGINE_H_

#include <list>
#include <map>
#include <vector>

#include "talk/base/basictypes.h"
#include "talk/base/stringutils.h"
#include "talk/session/phone/codec.h"
#include "talk/session/phone/fakewebrtccommon.h"
#include "talk/session/phone/voiceprocessor.h"
#include "talk/session/phone/webrtcvoe.h"

namespace cricket {

static const char kFakeDefaultDeviceName[] = "Fake Default";
static const int kFakeDefaultDeviceId = -1;
static const char kFakeDeviceName[] = "Fake Device";
#ifdef WIN32
static const int kFakeDeviceId = 0;
#else
static const int kFakeDeviceId = 1;
#endif

class FakeWebRtcVoiceEngine
    : public webrtc::VoEAudioProcessing,
      public webrtc::VoEBase, public webrtc::VoECodec, public webrtc::VoEDtmf,
      public webrtc::VoEFile, public webrtc::VoEHardware,
      public webrtc::VoEExternalMedia, public webrtc::VoENetEqStats,
      public webrtc::VoENetwork, public webrtc::VoERTP_RTCP,
      public webrtc::VoEVideoSync, public webrtc::VoEVolumeControl {
 public:
  struct Channel {
    Channel()
        : external_transport(false),
          send(false),
          playout(false),
          file(false),
          vad(false),
          fec(false),
          media_processor_registered(false),
          cn8_type(13),
          cn16_type(105),
          dtmf_type(106),
          fec_type(117),
          send_ssrc(0),
          level_header_ext_(-1) {
      memset(&send_codec, 0, sizeof(send_codec));
    }
    bool external_transport;
    bool send;
    bool playout;
    bool file;
    bool vad;
    bool fec;
    bool media_processor_registered;
    int cn8_type;
    int cn16_type;
    int dtmf_type;
    int fec_type;
    uint32 send_ssrc;
    int level_header_ext_;
    std::vector<webrtc::CodecInst> recv_codecs;
    webrtc::CodecInst send_codec;
    std::list<std::string> packets;
  };

  FakeWebRtcVoiceEngine(const cricket::AudioCodec* const* codecs,
                        int num_codecs)
      : inited_(false),
        last_channel_(-1),
        fail_create_channel_(false),
        codecs_(codecs),
        num_codecs_(num_codecs),
        ec_enabled_(false),
        ns_enabled_(false),
        ec_mode_(webrtc::kEcDefault),
        ns_mode_(webrtc::kNsDefault),
        observer_(NULL),
        playout_fail_channel_(-1),
        send_fail_channel_(-1),
        fail_start_recording_microphone_(false),
        recording_microphone_(false),
        media_processor_(NULL) {
    memset(&agc_config_, 0, sizeof(agc_config_));
  }
  ~FakeWebRtcVoiceEngine() {
    // Ought to have all been deleted by the WebRtcVoiceMediaChannel
    // destructors, but just in case ...
    for (std::map<int, Channel*>::const_iterator i = channels_.begin();
         i != channels_.end(); ++i) {
      delete i->second;
    }
  }
  bool IsExternalMediaProcessorRegistered() const {
    return media_processor_ != NULL;
  }
  bool IsInited() const { return inited_; }
  int GetLastChannel() const { return last_channel_; }
  int GetNumChannels() const { return channels_.size(); }
  bool GetPlayout(int channel) {
    return channels_[channel]->playout;
  }
  bool GetSend(int channel) {
    return channels_[channel]->send;
  }
  bool GetRecordingMicrophone() {
    return recording_microphone_;
  }
  bool GetVAD(int channel) {
    return channels_[channel]->vad;
  }
  bool GetFEC(int channel) {
    return channels_[channel]->fec;
  }
  int GetSendCNPayloadType(int channel, bool wideband) {
    return (wideband) ?
        channels_[channel]->cn16_type :
        channels_[channel]->cn8_type;
  }
  int GetSendTelephoneEventPayloadType(int channel) {
    return channels_[channel]->dtmf_type;
  }
  int GetSendFECPayloadType(int channel) {
    return channels_[channel]->fec_type;
  }
  bool CheckPacket(int channel, const void* data, size_t len) {
    bool result = !CheckNoPacket(channel);
    if (result) {
      std::string packet = channels_[channel]->packets.front();
      result = (packet == std::string(static_cast<const char*>(data), len));
      channels_[channel]->packets.pop_front();
    }
    return result;
  }
  bool CheckNoPacket(int channel) {
    return channels_[channel]->packets.empty();
  }
  void TriggerCallbackOnError(int channel_num, int err_code) {
    ASSERT(observer_ != NULL);
    observer_->CallbackOnError(channel_num, err_code);
  }
  void set_playout_fail_channel(int channel) {
    playout_fail_channel_ = channel;
  }
  void set_send_fail_channel(int channel) {
    send_fail_channel_ = channel;
  }
  void set_fail_start_recording_microphone(
      bool fail_start_recording_microphone) {
    fail_start_recording_microphone_ = fail_start_recording_microphone;
  }
  void set_fail_create_channel(bool fail_create_channel) {
    fail_create_channel_ = fail_create_channel;
  }
  void TriggerProcessPacket(MediaProcessorDirection direction) {
    webrtc::ProcessingTypes pt =
        (direction == cricket::MPD_TX) ?
            webrtc::kRecordingPerChannel : webrtc::kPlaybackPerChannel;
    if (media_processor_ != NULL) {
      media_processor_->Process(0,
                                pt,
                                NULL,
                                0,
                                0,
                                true);
    }
  }

  WEBRTC_STUB(Release, ());

  // webrtc::VoEBase
  WEBRTC_FUNC(RegisterVoiceEngineObserver, (
      webrtc::VoiceEngineObserver& observer)) {
    observer_ = &observer;
    return 0;
  }
  WEBRTC_STUB(DeRegisterVoiceEngineObserver, ());
  WEBRTC_STUB(RegisterAudioDeviceModule, (webrtc::AudioDeviceModule& adm));
  WEBRTC_STUB(DeRegisterAudioDeviceModule, ());

  WEBRTC_FUNC(Init, (webrtc::AudioDeviceModule* adm)) {
    inited_ = true;
    return 0;
  }
  WEBRTC_FUNC(Terminate, ()) {
    inited_ = false;
    return 0;
  }
  WEBRTC_STUB(MaxNumOfChannels, ());
  WEBRTC_FUNC(CreateChannel, ()) {
    if (fail_create_channel_) {
      return -1;
    }
    Channel* ch = new Channel();
    for (int i = 0; i < NumOfCodecs(); ++i) {
      webrtc::CodecInst codec;
      GetCodec(i, codec);
      ch->recv_codecs.push_back(codec);
    }
    channels_[++last_channel_] = ch;
    return last_channel_;
  }
  WEBRTC_FUNC(DeleteChannel, (int channel)) {
    WEBRTC_CHECK_CHANNEL(channel);
    delete channels_[channel];
    channels_.erase(channel);
    return 0;
  }
  WEBRTC_STUB(SetLocalReceiver, (int channel, int port, int RTCPport,
                                 const char ipaddr[64],
                                 const char multiCastAddr[64]));
  WEBRTC_STUB(GetLocalReceiver, (int channel, int& port, int& RTCPport,
                                 char ipaddr[64]));
  WEBRTC_STUB(SetSendDestination, (int channel, int port,
                                   const char ipaddr[64],
                                   int sourcePort, int RTCPport));
  WEBRTC_STUB(GetSendDestination, (int channel, int& port, char ipaddr[64],
                                   int& sourcePort, int& RTCPport));
  WEBRTC_STUB(StartReceive, (int channel));
  WEBRTC_FUNC(StartPlayout, (int channel)) {
    if (playout_fail_channel_ != channel) {
      WEBRTC_CHECK_CHANNEL(channel);
      channels_[channel]->playout = true;
      return 0;
    } else {
      // When playout_fail_channel_ == channel, fail the StartPlayout on this
      // channel.
      return -1;
    }
  }
  WEBRTC_FUNC(StartSend, (int channel)) {
    if (send_fail_channel_ != channel) {
      WEBRTC_CHECK_CHANNEL(channel);
      channels_[channel]->send = true;
      return 0;
    } else {
      // When send_fail_channel_ == channel, fail the StartSend on this
      // channel.
      return -1;
    }
  }
  WEBRTC_STUB(StopReceive, (int channel));
  WEBRTC_FUNC(StopPlayout, (int channel)) {
    WEBRTC_CHECK_CHANNEL(channel);
    channels_[channel]->playout = false;
    return 0;
  }
  WEBRTC_FUNC(StopSend, (int channel)) {
    WEBRTC_CHECK_CHANNEL(channel);
    channels_[channel]->send = false;
    return 0;
  }
  WEBRTC_STUB(GetVersion, (char version[1024]));
  WEBRTC_STUB(LastError, ());
  WEBRTC_STUB(SetOnHoldStatus, (int, bool, webrtc::OnHoldModes));
  WEBRTC_STUB(GetOnHoldStatus, (int, bool&, webrtc::OnHoldModes&));
  WEBRTC_STUB(SetNetEQPlayoutMode, (int, webrtc::NetEqModes));
  WEBRTC_STUB(GetNetEQPlayoutMode, (int, webrtc::NetEqModes&));
  WEBRTC_STUB(SetNetEQBGNMode, (int, webrtc::NetEqBgnModes));
  WEBRTC_STUB(GetNetEQBGNMode, (int, webrtc::NetEqBgnModes&));

  // webrtc::VoECodec
  WEBRTC_FUNC(NumOfCodecs, ()) {
    return num_codecs_;
  }
  WEBRTC_FUNC(GetCodec, (int index, webrtc::CodecInst& codec)) {
    if (index < 0 || index >= NumOfCodecs()) {
      return -1;
    }
    const cricket::AudioCodec& c(*codecs_[index]);
    codec.pltype = c.id;
    talk_base::strcpyn(codec.plname, sizeof(codec.plname), c.name.c_str());
    codec.plfreq = c.clockrate;
    codec.pacsize = 0;
    codec.channels = c.channels;
    codec.rate = c.bitrate;
    return 0;
  }
  WEBRTC_FUNC(SetSendCodec, (int channel, const webrtc::CodecInst& codec)) {
    WEBRTC_CHECK_CHANNEL(channel);
    channels_[channel]->send_codec = codec;
    return 0;
  }
  WEBRTC_FUNC(GetSendCodec, (int channel, webrtc::CodecInst& codec)) {
    WEBRTC_CHECK_CHANNEL(channel);
    codec = channels_[channel]->send_codec;
    return 0;
  }
  WEBRTC_STUB(GetRecCodec, (int channel, webrtc::CodecInst& codec));
  WEBRTC_STUB(SetAMREncFormat, (int channel, webrtc::AmrMode mode));
  WEBRTC_STUB(SetAMRDecFormat, (int channel, webrtc::AmrMode mode));
  WEBRTC_STUB(SetAMRWbEncFormat, (int channel, webrtc::AmrMode mode));
  WEBRTC_STUB(SetAMRWbDecFormat, (int channel, webrtc::AmrMode mode));
  WEBRTC_STUB(SetISACInitTargetRate, (int channel, int rateBps,
                                      bool useFixedFrameSize));
  WEBRTC_STUB(SetISACMaxRate, (int channel, int rateBps));
  WEBRTC_STUB(SetISACMaxPayloadSize, (int channel, int sizeBytes));
  WEBRTC_FUNC(SetRecPayloadType, (int channel,
                                  const webrtc::CodecInst& codec)) {
    WEBRTC_CHECK_CHANNEL(channel);
    Channel* ch = channels_[channel];
    if (ch->playout)
      return -1;  // Channel is in use.
    // Check if something else already has this slot.
    if (codec.pltype != -1) {
      for (std::vector<webrtc::CodecInst>::iterator it =
          ch->recv_codecs.begin(); it != ch->recv_codecs.end(); ++it) {
        if (it->pltype == codec.pltype) {
          return -1;
        }
      }
    }
    // Otherwise try to find this codec and update its payload type.
    for (std::vector<webrtc::CodecInst>::iterator it = ch->recv_codecs.begin();
         it != ch->recv_codecs.end(); ++it) {
      if (strcmp(it->plname, codec.plname) == 0 &&
          it->plfreq == codec.plfreq) {
        it->pltype = codec.pltype;
        return 0;
      }
    }
    return -1;  // not found
  }
  WEBRTC_FUNC(SetSendCNPayloadType, (int channel, int type,
                                     webrtc::PayloadFrequencies frequency)) {
    WEBRTC_CHECK_CHANNEL(channel);
    if (frequency == webrtc::kFreq8000Hz) {
      channels_[channel]->cn8_type = type;
    } else if (frequency == webrtc::kFreq16000Hz) {
      channels_[channel]->cn16_type = type;
    }
    return 0;
  }
  WEBRTC_FUNC(GetRecPayloadType, (int channel, webrtc::CodecInst& codec)) {
    WEBRTC_CHECK_CHANNEL(channel);
    Channel* ch = channels_[channel];
    for (std::vector<webrtc::CodecInst>::iterator it = ch->recv_codecs.begin();
         it != ch->recv_codecs.end(); ++it) {
      if (strcmp(it->plname, codec.plname) == 0 &&
          it->plfreq == codec.plfreq &&
          it->pltype != -1) {
        codec.pltype = it->pltype;
        return 0;
      }
    }
    return -1;  // not found
  }
  WEBRTC_FUNC(SetVADStatus, (int channel, bool enable, webrtc::VadModes mode,
                             bool disableDTX)) {
    WEBRTC_CHECK_CHANNEL(channel);
    channels_[channel]->vad = enable;
    return 0;
  }
  WEBRTC_STUB(GetVADStatus, (int channel, bool& enabled,
                             webrtc::VadModes& mode, bool& disabledDTX));

  // webrtc::VoEDtmf
  WEBRTC_STUB(SendTelephoneEvent, (int channel, int eventCode,
      bool outOfBand = true, int lengthMs = 160, int attenuationDb = 10));

  WEBRTC_FUNC(SetSendTelephoneEventPayloadType,
      (int channel, unsigned char type)) {
    channels_[channel]->dtmf_type = type;
    return 0;
  };
  WEBRTC_STUB(GetSendTelephoneEventPayloadType,
      (int channel, unsigned char& type));

  WEBRTC_STUB(SetDtmfFeedbackStatus, (bool enable, bool directFeedback));
  WEBRTC_STUB(GetDtmfFeedbackStatus, (bool& enabled, bool& directFeedback));
  WEBRTC_STUB(RegisterTelephoneEventDetection, (int channel,
      webrtc::TelephoneEventDetectionMethods detectionMethod,
      webrtc::VoETelephoneEventObserver& observer));
  WEBRTC_STUB(DeRegisterTelephoneEventDetection, (int channel));
  WEBRTC_STUB(SetDtmfPlayoutStatus, (int channel, bool enable));
  WEBRTC_STUB(GetDtmfPlayoutStatus, (int channel, bool& enabled));

  WEBRTC_STUB(PlayDtmfTone,
      (int eventCode, int lengthMs = 200, int attenuationDb = 10));
  WEBRTC_STUB(StartPlayingDtmfTone,
      (int eventCode, int attenuationDb = 10));
  WEBRTC_STUB(StopPlayingDtmfTone, ());
  WEBRTC_STUB(GetTelephoneEventDetectionStatus, (int channel,
      bool& enabled, webrtc::TelephoneEventDetectionMethods& detectionMethod));

  // webrtc::VoEFile
  WEBRTC_FUNC(StartPlayingFileLocally, (int channel, const char* fileNameUTF8,
                                        bool loop, webrtc::FileFormats format,
                                        float volumeScaling, int startPointMs,
                                        int stopPointMs)) {
    WEBRTC_CHECK_CHANNEL(channel);
    channels_[channel]->file = true;
    return 0;
  }
  WEBRTC_FUNC(StartPlayingFileLocally, (int channel, webrtc::InStream* stream,
                                        webrtc::FileFormats format,
                                        float volumeScaling, int startPointMs,
                                        int stopPointMs)) {
    WEBRTC_CHECK_CHANNEL(channel);
    channels_[channel]->file = true;
    return 0;
  }
  WEBRTC_FUNC(StopPlayingFileLocally, (int channel)) {
    WEBRTC_CHECK_CHANNEL(channel);
    channels_[channel]->file = false;
    return 0;
  }
  WEBRTC_FUNC(IsPlayingFileLocally, (int channel)) {
    WEBRTC_CHECK_CHANNEL(channel);
    return (channels_[channel]->file) ? 1 : 0;
  }
  WEBRTC_STUB(ScaleLocalFilePlayout, (int channel, float scale));
  WEBRTC_STUB(StartPlayingFileAsMicrophone, (int channel,
                                             const char* fileNameUTF8,
                                             bool loop,
                                             bool mixWithMicrophone,
                                             webrtc::FileFormats format,
                                             float volumeScaling));
  WEBRTC_STUB(StartPlayingFileAsMicrophone, (int channel,
                                             webrtc::InStream* stream,
                                             bool mixWithMicrophone,
                                             webrtc::FileFormats format,
                                             float volumeScaling));
  WEBRTC_STUB(StopPlayingFileAsMicrophone, (int channel));
  WEBRTC_STUB(IsPlayingFileAsMicrophone, (int channel));
  WEBRTC_STUB(ScaleFileAsMicrophonePlayout, (int channel, float scale));
  WEBRTC_STUB(StartRecordingPlayout, (int channel, const char* fileNameUTF8,
                                      webrtc::CodecInst* compression,
                                      int maxSizeBytes));
  WEBRTC_STUB(StartRecordingPlayout, (int channel, webrtc::OutStream* stream,
                                      webrtc::CodecInst* compression));
  WEBRTC_STUB(StopRecordingPlayout, (int channel));
  WEBRTC_FUNC(StartRecordingMicrophone, (const char* fileNameUTF8,
                                         webrtc::CodecInst* compression,
                                         int maxSizeBytes)) {
    if (fail_start_recording_microphone_) {
      return -1;
    }
    recording_microphone_ = true;
    return 0;
  }
  WEBRTC_FUNC(StartRecordingMicrophone, (webrtc::OutStream* stream,
                                         webrtc::CodecInst* compression)) {
    if (fail_start_recording_microphone_) {
      return -1;
    }
    recording_microphone_ = true;
    return 0;
  }
  WEBRTC_FUNC(StopRecordingMicrophone, ()) {
    if (!recording_microphone_) {
      return -1;
    }
    recording_microphone_ = false;
    return 0;
  }
  WEBRTC_STUB(ConvertPCMToWAV, (const char* fileNameInUTF8,
                                const char* fileNameOutUTF8));
  WEBRTC_STUB(ConvertPCMToWAV, (webrtc::InStream* streamIn,
                                webrtc::OutStream* streamOut));
  WEBRTC_STUB(ConvertWAVToPCM, (const char* fileNameInUTF8,
                                const char* fileNameOutUTF8));
  WEBRTC_STUB(ConvertWAVToPCM, (webrtc::InStream* streamIn,
                                webrtc::OutStream* streamOut));
  WEBRTC_STUB(ConvertPCMToCompressed, (const char* fileNameInUTF8,
                                       const char* fileNameOutUTF8,
                                       webrtc::CodecInst* compression));
  WEBRTC_STUB(ConvertPCMToCompressed, (webrtc::InStream* streamIn,
                                       webrtc::OutStream* streamOut,
                                       webrtc::CodecInst* compression));
  WEBRTC_STUB(ConvertCompressedToPCM, (const char* fileNameInUTF8,
                                     const char* fileNameOutUTF8));
  WEBRTC_STUB(ConvertCompressedToPCM, (webrtc::InStream* streamIn,
                                       webrtc::OutStream* streamOut));
  WEBRTC_STUB(GetFileDuration, (const char* fileNameUTF8, int& durationMs,
                                webrtc::FileFormats format));
  WEBRTC_STUB(GetPlaybackPosition, (int channel, int& positionMs));

  // webrtc::VoEHardware
  WEBRTC_STUB(GetCPULoad, (int&));
  WEBRTC_STUB(GetSystemCPULoad, (int&));
  WEBRTC_FUNC(GetNumOfRecordingDevices, (int& num)) {
    return GetNumDevices(num);
  }
  WEBRTC_FUNC(GetNumOfPlayoutDevices, (int& num)) {
    return GetNumDevices(num);
  }
  WEBRTC_FUNC(GetRecordingDeviceName, (int i, char* name, char* guid)) {
    return GetDeviceName(i, name, guid);
  }
  WEBRTC_FUNC(GetPlayoutDeviceName, (int i, char* name, char* guid)) {
    return GetDeviceName(i, name, guid);
  }
  WEBRTC_STUB(SetRecordingDevice, (int, webrtc::StereoChannel));
  WEBRTC_STUB(SetPlayoutDevice, (int));
  WEBRTC_STUB(SetAudioDeviceLayer, (webrtc::AudioLayers));
  WEBRTC_STUB(GetAudioDeviceLayer, (webrtc::AudioLayers&));
  WEBRTC_STUB(GetPlayoutDeviceStatus, (bool&));
  WEBRTC_STUB(GetRecordingDeviceStatus, (bool&));
  WEBRTC_STUB(ResetAudioDevice, ());
  WEBRTC_STUB(AudioDeviceControl, (unsigned int, unsigned int, unsigned int));
  WEBRTC_STUB(NeedMorePlayData, (short int*, int, int, int, int&));
  WEBRTC_STUB(RecordedDataIsAvailable, (short int*, int, int, int, int&));
  WEBRTC_STUB(GetDevice, (char*, unsigned int));
  WEBRTC_STUB(GetPlatform, (char*, unsigned int));
  WEBRTC_STUB(GetOS, (char*, unsigned int));
  WEBRTC_STUB(SetGrabPlayout, (bool));
  WEBRTC_STUB(SetGrabRecording, (bool));
  WEBRTC_STUB(SetLoudspeakerStatus, (bool enable));
  WEBRTC_STUB(GetLoudspeakerStatus, (bool& enabled));
  WEBRTC_STUB(EnableBuiltInAEC, (bool enable));
  virtual bool BuiltInAECIsEnabled() const { return true; }
  WEBRTC_STUB(SetSamplingRate, (int));
  WEBRTC_STUB(GetSamplingRate, (int&));

  // webrtc::VoENetEqStats
  WEBRTC_STUB(GetNetworkStatistics, (int, webrtc::NetworkStatistics&));
  WEBRTC_STUB(GetPreferredBufferSize, (int, short unsigned int&));
  WEBRTC_STUB(ResetJitterStatistics, (int));

  // webrtc::VoENetwork
  WEBRTC_FUNC(RegisterExternalTransport, (int channel,
                                          webrtc::Transport& transport)) {
    WEBRTC_CHECK_CHANNEL(channel);
    channels_[channel]->external_transport = true;
    return 0;
  }
  WEBRTC_FUNC(DeRegisterExternalTransport, (int channel)) {
    WEBRTC_CHECK_CHANNEL(channel);
    channels_[channel]->external_transport = false;
    return 0;
  }
  WEBRTC_FUNC(ReceivedRTPPacket, (int channel, const void* data,
                                  unsigned int length)) {
    WEBRTC_CHECK_CHANNEL(channel);
    if (!channels_[channel]->external_transport) return -1;
    channels_[channel]->packets.push_back(
        std::string(static_cast<const char*>(data), length));
    return 0;
  }
  WEBRTC_STUB(ReceivedRTCPPacket, (int channel, const void* data,
                                   unsigned int length));
  WEBRTC_STUB(GetSourceInfo, (int channel, int& rtpPort, int& rtcpPort,
                              char ipaddr[64]));
  WEBRTC_STUB(GetLocalIP, (char ipaddr[64], bool ipv6));
  WEBRTC_STUB(EnableIPv6, (int channel));
  // Not using WEBRTC_STUB due to bool return value
  virtual bool IPv6IsEnabled(int channel) { return true; }
  WEBRTC_STUB(SetSourceFilter, (int channel, int rtpPort, int rtcpPort,
                                const char ipaddr[64]));
  WEBRTC_STUB(GetSourceFilter, (int channel, int& rtpPort, int& rtcpPort,
                                char ipaddr[64]));
  WEBRTC_STUB(SetSendTOS, (int channel, int priority,
                           int DSCP, bool useSetSockopt));
  WEBRTC_STUB(GetSendTOS, (int channel, int& priority,
                           int& DSCP, bool& useSetSockopt));
  WEBRTC_STUB(SetSendGQoS, (int channel, bool enable, int serviceType,
                            int overrideDSCP));
  WEBRTC_STUB(GetSendGQoS, (int channel, bool& enabled, int& serviceType,
                            int& overrideDSCP));
  WEBRTC_STUB(SetPacketTimeoutNotification, (int channel, bool enable,
                                             int timeoutSeconds));
  WEBRTC_STUB(GetPacketTimeoutNotification, (int channel, bool& enable,
                                             int& timeoutSeconds));
  WEBRTC_STUB(RegisterDeadOrAliveObserver, (int channel,
      webrtc::VoEConnectionObserver& observer));
  WEBRTC_STUB(DeRegisterDeadOrAliveObserver, (int channel));
  WEBRTC_STUB(GetPeriodicDeadOrAliveStatus, (int channel, bool& enabled,
                                             int& sampleTimeSeconds));
  WEBRTC_STUB(SetPeriodicDeadOrAliveStatus, (int channel, bool enable,
                                             int sampleTimeSeconds));
  WEBRTC_STUB(SendUDPPacket, (int channel, const void* data,
                              unsigned int length, int& transmittedBytes,
                              bool useRtcpSocket));

  // webrtc::VoERTP_RTCP
  WEBRTC_STUB(RegisterRTPObserver, (int channel,
                                    webrtc::VoERTPObserver& observer));
  WEBRTC_STUB(DeRegisterRTPObserver, (int channel));
  WEBRTC_STUB(RegisterRTCPObserver, (int channel,
                                     webrtc::VoERTCPObserver& observer));
  WEBRTC_STUB(DeRegisterRTCPObserver, (int channel));
  WEBRTC_FUNC(SetLocalSSRC, (int channel, unsigned int ssrc)) {
    WEBRTC_CHECK_CHANNEL(channel);
    channels_[channel]->send_ssrc = ssrc;
    return 0;
  }
  WEBRTC_FUNC(GetLocalSSRC, (int channel, unsigned int& ssrc)) {
    WEBRTC_CHECK_CHANNEL(channel);
    ssrc = channels_[channel]->send_ssrc;
    return 0;
  }
  WEBRTC_STUB(GetRemoteSSRC, (int channel, unsigned int& ssrc));
  WEBRTC_FUNC(SetRTPAudioLevelIndicationStatus, (int channel, bool enable,
      unsigned char ID)) {
    WEBRTC_CHECK_CHANNEL(channel);
    channels_[channel]->level_header_ext_ = (enable) ? ID : -1;
    return 0;
  }
  WEBRTC_FUNC(GetRTPAudioLevelIndicationStatus, (int channel, bool& enabled,
      unsigned char& ID)) {
    WEBRTC_CHECK_CHANNEL(channel);
    enabled = (channels_[channel]->level_header_ext_ != -1);
    ID = channels_[channel]->level_header_ext_;
    return 0;
  }
  WEBRTC_STUB(GetRemoteCSRCs, (int channel, unsigned int arrCSRC[15]));
  WEBRTC_STUB(GetRemoteEnergy, (int channel, unsigned char arrEnergy[15]));
  WEBRTC_STUB(SetRTCPStatus, (int channel, bool enable));
  WEBRTC_STUB(GetRTCPStatus, (int channel, bool& enabled));
  WEBRTC_STUB(SetRTCP_CNAME, (int channel, const char cname[256]));
  WEBRTC_STUB(GetRTCP_CNAME, (int channel, char cname[256]));
  WEBRTC_STUB(GetRemoteRTCP_CNAME, (int channel, char* cname));
  WEBRTC_STUB(GetRemoteRTCPData, (int channel, unsigned int& NTPHigh,
                                  unsigned int& NTPLow,
                                  unsigned int& timestamp,
                                  unsigned int& playoutTimestamp,
                                  unsigned int* jitter,
                                  unsigned short* fractionLost));
  WEBRTC_STUB(SendApplicationDefinedRTCPPacket, (int channel,
                                                 const unsigned char subType,
                                                 unsigned int name,
                                                 const char* data,
                                                 unsigned short dataLength));
  WEBRTC_STUB(GetRTPStatistics, (int channel, unsigned int& averageJitterMs,
                                 unsigned int& maxJitterMs,
                                 unsigned int& discardedPackets));
  WEBRTC_STUB(GetRTCPStatistics, (int channel, unsigned short& fractionLost,
                                  unsigned int& cumulativeLost,
                                  unsigned int& extendedMax,
                                  unsigned int& jitterSamples, int& rttMs));
  WEBRTC_STUB(GetRTCPStatistics, (int channel, webrtc::CallStatistics& stats));
  WEBRTC_FUNC(SetFECStatus, (int channel, bool enable, int redPayloadtype)) {
    WEBRTC_CHECK_CHANNEL(channel);
    channels_[channel]->fec = enable;
    channels_[channel]->fec_type = redPayloadtype;
    return 0;
  }
  WEBRTC_FUNC(GetFECStatus, (int channel, bool& enable, int& redPayloadtype)) {
    WEBRTC_CHECK_CHANNEL(channel);
    enable = channels_[channel]->fec;
    redPayloadtype = channels_[channel]->fec_type;
    return 0;
  }
  WEBRTC_STUB(SetRTPKeepaliveStatus, (int channel, bool enable,
                                      int unknownPayloadType,
                                      int deltaTransmitTimeSeconds));
  WEBRTC_STUB(GetRTPKeepaliveStatus, (int channel, bool& enabled,
                                      int& unknownPayloadType,
                                      int& deltaTransmitTimeSeconds));
  WEBRTC_STUB(StartRTPDump, (int channel, const char* fileNameUTF8,
                             webrtc::RTPDirections direction));
  WEBRTC_STUB(StopRTPDump, (int channel, webrtc::RTPDirections direction));
  WEBRTC_STUB(RTPDumpIsActive, (int channel, webrtc::RTPDirections direction));
  WEBRTC_STUB(InsertExtraRTPPacket, (int channel, unsigned char payloadType,
                                     bool markerBit, const char* payloadData,
                                     unsigned short payloadSize));

  // webrtc::VoEVideoSync
  WEBRTC_STUB(GetPlayoutBufferSize, (int& bufferMs));
  WEBRTC_STUB(GetPlayoutTimestamp, (int channel, unsigned int& timestamp));
  WEBRTC_STUB(GetRtpRtcp, (int, webrtc::RtpRtcp*&));
  WEBRTC_STUB(SetInitTimestamp, (int channel, unsigned int timestamp));
  WEBRTC_STUB(SetInitSequenceNumber, (int channel, short sequenceNumber));
  WEBRTC_STUB(SetMinimumPlayoutDelay, (int channel, int delayMs));
  WEBRTC_STUB(GetDelayEstimate, (int channel, int& delayMs));
  WEBRTC_STUB(GetSoundcardBufferSize, (int& bufferMs));

  // webrtc::VoEVolumeControl
  WEBRTC_STUB(SetSpeakerVolume, (unsigned int));
  WEBRTC_STUB(GetSpeakerVolume, (unsigned int&));
  WEBRTC_STUB(SetSystemOutputMute, (bool));
  WEBRTC_STUB(GetSystemOutputMute, (bool&));
  WEBRTC_STUB(SetMicVolume, (unsigned int));
  WEBRTC_STUB(GetMicVolume, (unsigned int&));
  WEBRTC_STUB(SetInputMute, (int, bool));
  WEBRTC_STUB(GetInputMute, (int, bool&));
  WEBRTC_STUB(SetSystemInputMute, (bool));
  WEBRTC_STUB(GetSystemInputMute, (bool&));
  WEBRTC_STUB(GetSpeechInputLevel, (unsigned int&));
  WEBRTC_STUB(GetSpeechOutputLevel, (int, unsigned int&));
  WEBRTC_STUB(GetSpeechInputLevelFullRange, (unsigned int&));
  WEBRTC_STUB(GetSpeechOutputLevelFullRange, (int, unsigned int&));
  WEBRTC_STUB(SetChannelOutputVolumeScaling, (int, float));
  WEBRTC_STUB(GetChannelOutputVolumeScaling, (int, float&));
  WEBRTC_STUB(SetOutputVolumePan, (int, float, float));
  WEBRTC_STUB(GetOutputVolumePan, (int, float&, float&));

  // webrtc::VoEAudioProcessing
  WEBRTC_FUNC(SetNsStatus, (bool enable, webrtc::NsModes mode)) {
    ns_enabled_ = enable;
    ns_mode_ = mode;
    return 0;
  }
  WEBRTC_FUNC(GetNsStatus, (bool& enabled, webrtc::NsModes& mode)) {
    enabled = ns_enabled_;
    mode = ns_mode_;
    return 0;
  }
  WEBRTC_STUB(SetAgcStatus, (bool enable, webrtc::AgcModes mode));
  WEBRTC_STUB(GetAgcStatus, (bool& enabled, webrtc::AgcModes& mode));

  WEBRTC_FUNC(SetAgcConfig, (const webrtc::AgcConfig config)) {
    agc_config_ = config;
    return 0;
  }
  WEBRTC_FUNC(GetAgcConfig, (webrtc::AgcConfig& config)) {
    config = agc_config_;
    return 0;
  }
  WEBRTC_FUNC(SetEcStatus, (bool enable, webrtc::EcModes mode)) {
    ec_enabled_ = enable;
    ec_mode_ = mode;
    return 0;
  }
  WEBRTC_FUNC(GetEcStatus, (bool& enabled, webrtc::EcModes& mode)) {
    enabled = ec_enabled_;
    mode = ec_mode_;
    return 0;
  }
  virtual void SetDelayOffsetMs(int offset) {}
  WEBRTC_STUB(DelayOffsetMs, ());
  WEBRTC_STUB(SetAecmMode, (webrtc::AecmModes mode, bool enableCNG));
  WEBRTC_STUB(GetAecmMode, (webrtc::AecmModes& mode, bool& enabledCNG));
  WEBRTC_STUB(SetRxNsStatus, (int channel, bool enable, webrtc::NsModes mode));
  WEBRTC_STUB(GetRxNsStatus, (int channel, bool& enabled,
                              webrtc::NsModes& mode));
  WEBRTC_STUB(SetRxAgcStatus, (int channel, bool enable,
                               webrtc::AgcModes mode));
  WEBRTC_STUB(GetRxAgcStatus, (int channel, bool& enabled,
                               webrtc::AgcModes& mode));
  WEBRTC_STUB(SetRxAgcConfig, (int channel, const webrtc::AgcConfig config));
  WEBRTC_STUB(GetRxAgcConfig, (int channel, webrtc::AgcConfig& config));

  WEBRTC_STUB(RegisterRxVadObserver, (int, webrtc::VoERxVadCallback&));
  WEBRTC_STUB(DeRegisterRxVadObserver, (int channel));
  WEBRTC_STUB(VoiceActivityIndicator, (int channel));
  WEBRTC_STUB(SetEcMetricsStatus, (bool enable));
  WEBRTC_STUB(GetEcMetricsStatus, (bool& enable));
  WEBRTC_STUB(GetEchoMetrics, (int& ERL, int& ERLE, int& RERL, int& A_NLP));
  WEBRTC_STUB(GetEcDelayMetrics, (int& delay_median, int& delay_std));

  WEBRTC_STUB(StartDebugRecording, (const char* fileNameUTF8));
  WEBRTC_STUB(StopDebugRecording, ());

  WEBRTC_STUB(SetTypingDetectionStatus, (bool enable));
  WEBRTC_STUB(GetTypingDetectionStatus, (bool& enabled));
  WEBRTC_STUB(TimeSinceLastTyping, (int& seconds));
  WEBRTC_STUB(SetTypingDetectionParameters, (int timeWindow,
                                             int costPerTyping,
                                             int reportingThreshold,
                                             int penaltyDecay));
  WEBRTC_STUB(EnableHighPassFilter, (bool enable));
  bool IsHighPassFilterEnabled() { return false; }
  bool IsStereoChannelSwappingEnabled() { return false; }
  void EnableStereoChannelSwapping(bool enable) { return; }
  // webrtc::VoEExternalMedia
  WEBRTC_FUNC(RegisterExternalMediaProcessing,
              (int channel, webrtc::ProcessingTypes type,
               webrtc::VoEMediaProcess& processObject)) {
    WEBRTC_CHECK_CHANNEL(channel);
    if (channels_[channel]->media_processor_registered) {
      return -1;
    }
    channels_[channel]->media_processor_registered = true;
    media_processor_ = &processObject;
    return 0;
  }
  WEBRTC_FUNC(DeRegisterExternalMediaProcessing,
              (int channel, webrtc::ProcessingTypes type)) {
    WEBRTC_CHECK_CHANNEL(channel);
    if (!channels_[channel]->media_processor_registered) {
      return -1;
    }
    channels_[channel]->media_processor_registered = false;
    media_processor_ = NULL;
    return 0;
  }
  WEBRTC_STUB(SetExternalRecordingStatus, (bool enable));
  WEBRTC_STUB(SetExternalPlayoutStatus, (bool enable));
  WEBRTC_STUB(ExternalRecordingInsertData,
              (const WebRtc_Word16 speechData10ms[], int lengthSamples,
               int samplingFreqHz, int current_delay_ms));
  WEBRTC_STUB(ExternalPlayoutGetData,
              (WebRtc_Word16 speechData10ms[], int samplingFreqHz,
               int current_delay_ms, int& lengthSamples));

 private:
  int GetNumDevices(int& num) {
#ifdef WIN32
    num = 1;
#else
    // On non-Windows platforms VE adds a special entry for the default device,
    // so if there is one physical device then there are two entries in the
    // list.
    num = 2;
#endif
    return 0;
  }

  int GetDeviceName(int i, char* name, char* guid) {
    const char *s;
#ifdef WIN32
    if (0 == i) {
      s = kFakeDeviceName;
    } else {
      return -1;
    }
#else
    // See comment above.
    if (0 == i) {
      s = kFakeDefaultDeviceName;
    } else if (1 == i) {
      s = kFakeDeviceName;
    } else {
      return -1;
    }
#endif
    strcpy(name, s);
    guid[0] = '\0';
    return 0;
  }

  bool inited_;
  int last_channel_;
  std::map<int, Channel*> channels_;
  bool fail_create_channel_;
  const cricket::AudioCodec* const* codecs_;
  int num_codecs_;
  bool ec_enabled_;
  bool ns_enabled_;
  webrtc::EcModes ec_mode_;
  webrtc::NsModes ns_mode_;
  webrtc::AgcConfig agc_config_;
  webrtc::VoiceEngineObserver* observer_;
  int playout_fail_channel_;
  int send_fail_channel_;
  bool fail_start_recording_microphone_;
  bool recording_microphone_;
  webrtc::VoEMediaProcess* media_processor_;
};

}  // namespace cricket

#endif  // TALK_SESSION_PHONE_FAKEWEBRTCVOICEENGINE_H_


text:
{% extends 'base.html' %}
{% import 'publication_list_macro.html' as publist with context %}
{% import 'video_list_macro.html' as vidlist with context %}
{% import 'related_list_macro.html' as relist with context %}

{% block title %}Neural Reckoning Group{% endblock %}

{% block main %}

            Tweets by neuralreckoning

            The Neural Reckoning Group is led by
            Dan Goodman at
            Imperial College London.

            We aim to understand the brain, and intelligent behaviour more widely, via theoretical and computational
            models.

            We are particularly interested in spiking neural networks
            and the role they play in sensory processing.
            Machine learning is essential to our
            work, as we believe that only by understanding how the brain copes with messy, real-world complexity can
            we hope to understand what makes it unique.
            A key part of our work is neuroinformatics, building open source
            software packages to make our methods freely available to all.
            For a brief overview of our interests, see the selection of papers, software and organisations below.

            We maintain a short list of resources for learning computational
            neuroscience that might be useful to students and people new to the field.

Recent publications

            {{ publist.recent_publications(5) }}

Selected publications

            {{ publist.selected_publications() }}

Selected software packages

            {{ relist.card_list(software | selectattr('selected')) }}

Organisations

            {{ relist.card_list(organisations) }}

Latest video

See more videos here.

            {{ vidlist.video_highlight(videos) }}

{% endblock %}

redpajama_set_name: RedPajamaGithub


text:
#ifndef __PEPXML_PARSER_H__
#define __PEPXML_PARSER_H__

#ifdef __cplusplus
extern "C"
{
#endif

#include <stdio.h>
#include <stdlib.h>

#include "pepXMLStructures.h"
#include "pepXMLReaderDefs.h"
#include "pepXMLDelegates.h"

#define HEADER_BUFF_SIZE 10240		/* 10KB reading buffer as standard for the pipeline analysis header*/
#define OPT_READ_BUFF_SIZE 2048		/* 2KB reading buffer as standard for optional belayed reads */
#define SUMMARY_BUFF_SIZE 20480		/* 20KB reading buffer as standard for the run summary header*/
#define READ_BUFF_SIZE 1048576		/* 1MB reading buffer as standard */
#define INIT_SPECTRUM_COUNT 2000	/* Initial spectrum count of 2000 */

/* Parses the entire file */
void parse_msms_pipeline_analysis(pmsms_pipeline_analysis retval, FILE* finput, pipeline_analysis_flags paflags, run_summary_flags rsflags, pdelegate_list dlist);

/* Parses the analysis summary structures */
void parse_analysis_summary_structure(pmsms_pipeline_analysis retval, char* beginptr, FILE* finput, pdelegate_list dlist);

/* Parses the analysis summary structures when loaded later */
void parse_analysis_summary_structure_from_file(pmsms_pipeline_analysis retval, FILE* finput, pdelegate_list dlist);

/* Parses an individual analysis summary element */
analysis_summary parse_analysis_summary(char* content, pdelegate_type deltype);

/* Parses the dataset_derivation structures */
void parse_dataset_derivation_structure(pmsms_pipeline_analysis retval, char* beginptr, FILE* finput);

/* Parses the dataset_derivation structures from file when needed at a later stage */
void parse_dataset_derivation_structure_from_file(pmsms_pipeline_analysis retval, FILE* finput);

/* Parses the pepxml_msms_run_summary elements */
void parse_run_summary_structure(pmsms_pipeline_analysis retval, char* beginptr, FILE* finput, run_summary_flags rsflags, pdelegate_list dlist);

/* Parses a single pepxml_msms_run_summary element */
msms_run_summary parse_run_summary(char* beginptr, FILE* finput, run_summary_flags rsflags, pdelegate_list dlist);

/* Parses the pepxml_msms_run_summary elements */
void parse_sample_enzyme_structure(pmsms_run_summary retval, char* beginptr, FILE* finput);

/* Parses the pepxml_search_summary elements */
void parse_search_summary_structure(pmsms_run_summary retval, char* beginptr, FILE* finput);

/* Parses individual search_summary element */
search_summary parse_search_summary(char* beginptr, FILE* finput);

/* Parses the pepxml_analysis_timestamp structure */
void parse_analysis_timestamp_structure(pmsms_run_summary retval, char* beginptr, FILE* finput);

/* Parses individual analysis_timestamp element */
analysis_timestamp parse_analysis_timestamp(char* beginptr, FILE* finput);

/* Parses sprectum_query list */
void parse_spectrum_query_structure(pmsms_run_summary retval, char* beginptr, FILE* finput, pdelegate_list dlist);

/* Parses individual sprectum_query element */
spectrum_query parse_spectrum_query(char* beginptr, FILE* finput, pdelegate_list dlist);

/* Parses search_result_array structure */
void parse_search_result_structure(pspectrum_query retval, char* beginptr, FILE* finput, pdelegate_list dlist);

/* Parses individual search result element */
search_result parse_search_result(char* beginptr, FILE* finput, pdelegate_list dlist);

/* Parses search_hit_array structure */
void parse_search_hit_structure(psearch_result retval, char* beginptr, FILE* finput, pdelegate_list dlist);

/* Parses individual search hit element */
search_hit parse_search_hit(char* beginptr, FILE* finput, pdelegate_list dlist);

/* Parses alternative_protein_array structure */
void parse_alternative_protein_structure(psearch_hit retval, char* beginptr, FILE* finput);

/* Parses individual alternative_protein element */
alternative_protein parse_alternative_protein(char* beginptr, FILE* finput);

/* Parses modification_info_array structure */
void parse_modification_info_structure(psearch_hit retval, char* beginptr, FILE* finput);

/* Parses mod_aminoacid_mass_array structure */
void parse_mod_aminoacid_mass_structure(pmodification_info retval, char* beginptr, FILE* finput);

/* Parses individual mod_aminoacid_mass element */
mod_aminoacid_mass parse_mod_aminoacid_mass(char* beginptr, FILE* finput);

/* Parses search_score_array structure */
void parse_search_score_structure(psearch_hit retval, char* beginptr, FILE* finput);

/* Parses analysis_result_array structure */
void parse_analysis_result_structure(psearch_hit retval, char* beginptr, FILE* finput, pdelegate_list dlist);

/* Parses parameter_array structure */
void parse_parameter_structure(psearch_hit retval, char* beginptr, FILE* finput);

#ifdef __cplusplus
}
#endif

#endif


text:
package ch.chrigu.datastructures.demo.instances;

import ch.chrigu.datastructures.demo.types.CollectionType;
import ch.chrigu.datastructures.demo.instances.options.CollectionOptions;
import ch.chrigu.datastructures.demo.types.CollectionTypes;
import javafx.collections.FXCollections;
import javafx.collections.ObservableList;

/**
 * Maintains a list of created collections. On these, actions can be performed.
 *
 * Created by Christoph Huber on 02.01.2015.
 */
public class CollectionInstances {

    private ObservableList<CollectionInstance<Integer>> collectionInstances;

    public CollectionInstances() {
        this.collectionInstances = FXCollections.observableArrayList();
        add(CollectionTypes.LINKED_LIST);
        add(CollectionTypes.ARRAY_LIST);
        add(CollectionTypes.HASH_SET);
        add(CollectionTypes.TREE_SET);
        add(CollectionTypes.LINKED_HASH_SET);
        add(CollectionTypes.ARRAY_LIST, new CollectionOptions().synchronizedCollection());
        add(CollectionTypes.ARRAY_LIST, new CollectionOptions().capacity(10000));
    }

    public void add(CollectionType<Integer> collectionType, CollectionOptions collectionOptions) {
        collectionInstances.add(new CollectionInstance<>(collectionType, collectionOptions));
    }
    private void add(CollectionType<Integer> collectionType) {
        collectionInstances.add(new CollectionInstance<>(collectionType));
    }

    public ObservableList<CollectionInstance<Integer>> getInstances() {
        return collectionInstances;
    }
}


text:
Article 480
----
Le mandataire peut être toute personne physique choisie par le mandant ou une
personne morale inscrite sur la liste des mandataires judiciaires à la
protection des majeurs prévue à l'article L. 471-2 du code de l'action sociale
et des familles.

Le mandataire doit, pendant toute l'exécution du mandat, jouir de la capacité
civile et remplir les conditions prévues pour les charges tutélaires par
l'article 395 et les deux derniers alinéas de l'article 445 du présent code.

Il ne peut, pendant cette exécution, être déchargé de ses fonctions qu'avec
l'autorisation du juge des tutelles.


text:
"""Tests for array_ops."""
from __future__ import absolute_import
from __future__ import division
from __future__ import print_function

import math

import numpy as np
import tensorflow as tf

from tensorflow.python.framework import dtypes
from tensorflow.python.framework import errors
from tensorflow.python.framework import tensor_shape
from tensorflow.python.framework import test_util
from tensorflow.python.ops import array_ops
from tensorflow.python.platform import googletest

class BooleanMaskTest(test_util.TensorFlowTestCase):

  def CheckVersusNumpy(self, ndims_mask, arr_shape, make_mask=None):
    """Check equivalence between boolean_mask and numpy masking."""
    if make_mask is None:
      make_mask = lambda shape: np.random.randint(0, 2, size=shape).astype(bool)
    arr = np.random.rand(*arr_shape)
    mask = make_mask(arr_shape[: ndims_mask])
    masked_arr = arr[mask]
    with self.test_session():
      masked_tensor = array_ops.boolean_mask(arr, mask)
      np.testing.assert_allclose(
          masked_arr,
          masked_tensor.eval(),
          err_msg="masked_arr:\n%s\n\nmasked_tensor:\n%s" % (
              masked_arr, masked_tensor.eval()))
      masked_tensor.get_shape().assert_is_compatible_with(masked_arr.shape)
      self.assertSequenceEqual(
          masked_tensor.get_shape()[1:].as_list(),
          masked_arr.shape[1:],
          msg="shape information lost %s -> %s" % (
              masked_arr.shape, masked_tensor.get_shape()))

  def testOneDimensionalMask(self):
    # Do 1d separately because it's the only easy one to debug!
    ndims_mask = 1
    for ndims_arr in range(ndims_mask, ndims_mask + 3):
      for _ in range(3):
        arr_shape = np.random.randint(1, 5, size=ndims_arr)
        self.CheckVersusNumpy(ndims_mask, arr_shape)

  def testMultiDimensionalMask(self):
    for ndims_mask in range(1, 4):
      for ndims_arr in range(ndims_mask, ndims_mask + 3):
        for _ in range(3):
          arr_shape = np.random.randint(1, 5, size=ndims_arr)
          self.CheckVersusNumpy(ndims_mask, arr_shape)

  def testEmptyOutput(self):
    make_mask = lambda shape: np.zeros(shape, dtype=bool)
    for ndims_mask in range(1, 4):
      for ndims_arr in range(ndims_mask, ndims_mask + 3):
        for _ in range(3):
          arr_shape = np.random.randint(1, 5, size=ndims_arr)
          self.CheckVersusNumpy(ndims_mask, arr_shape, make_mask=make_mask)

  def testWorksWithDimensionsEqualToNoneDuringGraphBuild(self):
    # The rank of the mask tensor must be specified. This is explained
    # in the docstring as well.
    with self.test_session() as sess:
      ph_tensor = array_ops.placeholder(dtypes.int32, shape=None)
      ph_mask = array_ops.placeholder(dtypes.bool, shape=[None])

      arr = np.array([[1, 2], [3, 4]])
      mask = np.array([False, True])

      masked_tensor = sess.run(
          array_ops.boolean_mask(ph_tensor, ph_mask),
          feed_dict={ph_tensor: arr, ph_mask: mask})
      np.testing.assert_allclose(masked_tensor, arr[mask])

  def testMaskDimensionsSetToNoneRaises(self):
    # The rank of the mask tensor must be specified. This is explained
    # in the docstring as well.
    with self.test_session():
      tensor = array_ops.placeholder(dtypes.int32, shape=[None, 2])
      mask = array_ops.placeholder(dtypes.bool, shape=None)
      with self.assertRaisesRegexp(ValueError, "dimensions must be specified"):
        array_ops.boolean_mask(tensor, mask)

  def testMaskHasMoreDimsThanTensorRaises(self):
    mask = [[True, True], [False, False]]
    tensor = [1, 2, 3, 4]
    with self.test_session():
      with self.assertRaisesRegexp(ValueError, "incompatible"):
        array_ops.boolean_mask(tensor, mask).eval()

  def testMaskIsScalarRaises(self):
    mask = True
    tensor = 1
    with self.test_session():
      with self.assertRaisesRegexp(ValueError, "mask.*scalar"):
        array_ops.boolean_mask(tensor, mask).eval()

  def testMaskShapeDifferentThanFirstPartOfTensorShapeRaises(self):
    mask = [True, True, True]
    tensor = [[1, 2], [3, 4]]
    with self.test_session():
      with self.assertRaisesRegexp(ValueError, "incompatible"):
        array_ops.boolean_mask(tensor, mask).eval()

class OperatorShapeTest(test_util.TensorFlowTestCase):

  def testExpandScalar(self):
    scalar = "hello"
    scalar_expanded = array_ops.expand_dims(scalar, [0])
    self.assertEqual(scalar_expanded.get_shape(), (1,))

  def testSqueeze(self):
    scalar = "hello"
    scalar_squeezed = array_ops.squeeze(scalar, ())
    self.assertEqual(scalar_squeezed.get_shape(), ())

class ReverseTest(test_util.TensorFlowTestCase):

  def testReverse0DimAuto(self):
    x_np = 4
    for use_gpu in [False, True]:
      with self.test_session(use_gpu=use_gpu):
        x_tf = array_ops.reverse(x_np, []).eval()
        self.assertAllEqual(x_tf, x_np)

  def testReverse1DimAuto(self):
    x_np = [1, 4, 9]

    for use_gpu in [False, True]:
      with self.test_session(use_gpu=use_gpu):
        x_tf = array_ops.reverse(x_np, [True]).eval()
        self.assertAllEqual(x_tf, np.asarray(x_np)[::-1])

  def testUnknownDims(self):
    data_t = tf.placeholder(tf.float32)
    dims_known_t = tf.placeholder(tf.bool, shape=[3])
    reverse_known_t = tf.reverse(data_t, dims_known_t)
    self.assertEqual(3, reverse_known_t.get_shape().ndims)

    dims_unknown_t = tf.placeholder(tf.bool)
    reverse_unknown_t = tf.reverse(data_t, dims_unknown_t)
    self.assertIs(None, reverse_unknown_t.get_shape().ndims)

    data_2d_t = tf.placeholder(tf.float32, shape=[None, None])
    dims_2d_t = tf.placeholder(tf.bool, shape=[2])
    reverse_2d_t = tf.reverse(data_2d_t, dims_2d_t)
    self.assertEqual(2, reverse_2d_t.get_shape().ndims)

    dims_3d_t = tf.placeholder(tf.bool, shape=[3])
    with self.assertRaisesRegexp(ValueError, "must have rank 3"):
      tf.reverse(data_2d_t, dims_3d_t)

class MeshgridTest(test_util.TensorFlowTestCase):

  def _compare(self, n, np_dtype, use_gpu):
    inputs = []
    for i in range(n):
      x = np.linspace(-10, 10, 5).astype(np_dtype)
      if np_dtype in (np.complex64, np.complex128):
        x += 1j
      inputs.append(x)

    numpy_out = np.meshgrid(*inputs)
    with self.test_session(use_gpu=use_gpu):
      tf_out = array_ops.meshgrid(*inputs)
      for X, _X in zip(numpy_out, tf_out):
        self.assertAllEqual(X, _X.eval())

  def testCompare(self):
    for t in (np.float16, np.float32, np.float64, np.int32, np.int64,
            np.complex64, np.complex128):
      # Don't test the one-dimensional case, as
      # old numpy versions don't support it
      self._compare(2, t, False)
      self._compare(3, t, False)
      self._compare(4, t, False)
      self._compare(5, t, False)

    # Test for inputs with rank not equal to 1
    x = [[1, 1], [1, 1]]
    with self.assertRaisesRegexp(errors.InvalidArgumentError,
                                 "needs to have rank 1"):
      with self.test_session():
        X, _ = array_ops.meshgrid(x, x)
        X.eval()

class StridedSliceChecker(object):
  """Check a given tensor against the numpy result."""

  REF_TENSOR = np.arange(1, 19, dtype=np.int32).reshape(3, 2, 3)
  REF_TENSOR_ALIGNED = np.arange(1, 97, dtype=np.int32).reshape(3, 4, 8)

  def __init__(self, test, x):
    self.test = test
    self.x = tf.constant(x)
    self.x_np = np.array(x)

  def __getitem__(self, spec):
    # TODO(aselle): When NewSliceHelper is installed, we can switch this back
    # op = self.x[spec]
    op = array_ops._NewSliceHelper(self.x, spec)

    tensor = op.eval()
    self.test.assertAllEqual(self.x_np[spec], tensor)
    self.test.assertAllEqual(tensor.shape, op.get_shape())
    return tensor

class StridedSliceTest(test_util.TensorFlowTestCase):
  """Test the strided slice operation with variants of slices."""

  def testBasicSlice(self):
    for use_gpu in [False, True]:
      with self.test_session(use_gpu=use_gpu):
        checker = StridedSliceChecker(self, StridedSliceChecker.REF_TENSOR)
        _ = checker[:, :, :]
        # Various ways of representing identity slice
        _ = checker[:, :, :]
        _ = checker[::, ::, ::]
        _ = checker[::1, ::1, ::1]
        # Not zero slice
        _ = checker[::1, ::5, ::2]
        # Reverse in each dimension independently
        _ = checker[::-1, :, :]
        _ = checker[:, ::-1, :]
        _ = checker[:, :, ::-1]
        ## negative index tests i.e. n-2 in first component
        _ = checker[-2::-1, :, ::1]
        # negative index tests i.e. n-2 in first component, and non unit stride
        _ = checker[-2::-1, :, ::2]

  def testDegenerateSlices(self):
    for use_gpu in [False, True]:
      with self.test_session(use_gpu=use_gpu):
        checker = StridedSliceChecker(self, StridedSliceChecker.REF_TENSOR)
        # degenerate by offering a forward interval with a negative stride
        _ = checker[0:-1:-1, :, :]
        # degenerate with a reverse interval with a positive stride
        _ = checker[-1:0, :, :]
        # empty interval in every dimension
        _ = checker[-1:0, 2:2, 2:3:-1]

  def testEllipse(self):
    for use_gpu in [False, True]:
      with self.test_session(use_gpu=use_gpu):
        raw = [[[[[1, 2], [3, 4], [5, 6]]], [[[7, 8], [9, 10], [11, 12]]]]]
        checker = StridedSliceChecker(self, raw)

        _ = checker[0:]
        # implicit ellipse
        _ = checker[0:, ...]
        # ellipsis alone
        _ = checker[...]
        # ellipsis at end
        _ = checker[0:1, ...]
        # ellipsis at begin
        _ = checker[..., 0:1]
        # ellipsis at middle
        _ = checker[0:1, ..., 0:1]
        # multiple ellipsis not allowed
        with self.assertRaisesRegexp(ValueError,
                                     "Multiple ellipses not allowed"):
          _ = checker[..., :, ...].eval()

  def testShrink(self):
    for use_gpu in [False, True]:
      with self.test_session(use_gpu=use_gpu):
        raw = [[[[[1, 2, 4, 5], [5, 6, 7, 8], [9, 10, 11, 12]]],
                [[[13, 14, 15, 16], [17, 18, 19, 20], [21, 22, 23, 24]]]]]
        checker = StridedSliceChecker(self, raw)
        _ = checker[:, :, :, :, 3]
        _ = checker[..., 3]
        _ = checker[:, 0]
        _ = checker[:, :, 0]

  def testExpand(self):
    for use_gpu in [False, True]:
      with self.test_session(use_gpu=use_gpu):
        raw = [[[[[1, 2, 4, 5], [5, 6, 7, 8], [9, 10, 11, 12]]],
                [[[13, 14, 15, 16], [17, 18, 19, 20], [21, 22, 23, 24]]]]]
        checker = StridedSliceChecker(self, raw)
        # new axis (followed by implicit ellipsis)
        _ = checker[np.newaxis]
        # newaxis after ellipse
        _ = checker[..., np.newaxis]
        # newaxis in between ellipse and explicit range
        _ = checker[..., np.newaxis, :]
        _ = checker[:, ..., np.newaxis, :, :]
        # Reverse final dimension with new axis
        _ = checker[:, :, np.newaxis, :, 2::-1]
        # Ellipse in middle of two newaxis
        _ = checker[np.newaxis, ..., np.newaxis]

  def testOptimizedCases(self):
    for use_gpu in [False, True]:
      with self.test_session(use_gpu=use_gpu):
        checker = StridedSliceChecker(self,
                                      StridedSliceChecker.REF_TENSOR_ALIGNED)
        # Identity
        _ = checker[:]
        # Identity
        _ = checker[...]
        # Identity
        _ = checker[np.newaxis, ..., np.newaxis]
        # First axis slice
        _ = checker[1:]
        # First axis slice
        _ = checker[np.newaxis, 1:]

class StridedSliceShapeChecker(object):

  def __init__(self, x):
    self.x = x

  def __getitem__(self, spec):
    # TODO(aselle): When NewSliceHelper is installed, we can switch this back
    # op = self.x[spec]
    op = array_ops._NewSliceHelper(self.x, spec)
    return op.get_shape()

class StridedSliceShapeTest(test_util.TensorFlowTestCase):
  """Test the shape inference of StridedSliceShapes."""

  def testUnknown(self):
    with self.test_session(use_gpu=False):
      uncertain_tensor = tf.placeholder(tf.float32)
      a = StridedSliceShapeChecker(uncertain_tensor)
      a_slice_shape = a[...]
      self.assertAllEqual(a_slice_shape.ndims, None)

  def tensorShapeEqual(self, x, y):
    self.assertTrue(x is not None and y is not None or x is None and y is None)
    self.assertEqual(x.as_list(), y.as_list())

  def testTensorShapeUncertain(self):
    for use_gpu in [False, True]:
      with self.test_session(use_gpu=use_gpu):
        uncertain_tensor = tf.placeholder(tf.float32, shape=(5, None, 7))
        a = StridedSliceShapeChecker(uncertain_tensor)
        self.tensorShapeEqual(a[3:5], tensor_shape.TensorShape([2, None, 7]))
        self.tensorShapeEqual(a[3:5, :, 4], tensor_shape.TensorShape([2, None]))
        self.tensorShapeEqual(a[3:5, 3:4, 4],
                              tensor_shape.TensorShape([2, None]))
        self.tensorShapeEqual(a[3:5, :, 5:10],
                              tensor_shape.TensorShape([2, None, 2]))
        self.tensorShapeEqual(a[3:5, :, 50:3],
                              tensor_shape.TensorShape([2, None, 0]))
        self.tensorShapeEqual(a[3:5, :, tf.newaxis, 50:3,],
                              tensor_shape.TensorShape([2, None, 1, 0]))
        self.tensorShapeEqual(a[1:5:2, :, tf.newaxis, 50:3,],
                              tensor_shape.TensorShape([2, None, 1, 0]))
        self.tensorShapeEqual(a[:5:3, :, tf.newaxis, 50:3,],
                              tensor_shape.TensorShape([2, None, 1, 0]))
        self.tensorShapeEqual(a[:2:3, :, tf.newaxis, 50:3,],
                              tensor_shape.TensorShape([1, None, 1, 0]))
        self.tensorShapeEqual(a[::-1, :, tf.newaxis, ::-2],
                              tensor_shape.TensorShape([5, None, 1, 4]))

if __name__ == "__main__":
  googletest.main()


text:
/**
 * @private
 */
var WebSocketHixie76FrameCodecHandler = (function () /*extends WebSocketHandlerAdapter*/ {
    ;;;var CLASS_NAME = "WebSocketHixie76FrameCodecHandler";
    ;;;var LOG = Logger.getLogger(CLASS_NAME);

    var WebSocketHixie76FrameCodecHandler = function () {
        ;;;LOG.finest(CLASS_NAME, "<init>");
    };

    var $prototype = WebSocketHixie76FrameCodecHandler.prototype = new WebSocketHandlerAdapter();
    $prototype.processConnect = function (channel, uri, protocol) {
        this._nextHandler.processConnect(channel, uri, protocol);
    }

    $prototype.processBinaryMessage = function (channel, data) {
        if (data.constructor == $rootModule.ByteBuffer) { //bytebuffer
            var bytes = data.array.slice(data.position, data.limit);
            this._nextHandler.processTextMessage(channel, Charset.UTF8.encodeByteArray(bytes));
        } else if (data.byteLength) { //arraybuffer
            this._nextHandler.processTextMessage(channel, Charset.UTF8.encodeArrayBuffer(data));
        } else if (data.size) { //blob, send data in callback function
            var $this = this;
            var cb = function (result) {
                $this._nextHandler.processBinaryMessage(channel, Charset.UTF8.encodeByteArray(result));
            };
            BlobUtils.asNumberArray(cb, data);
        } else {
            throw new Error("Invalid type for send");
        }
    }
    $prototype.setNextHandler = function (nextHandler) {
        this._nextHandler = nextHandler;
        var $this = this;
        var listener = new WebSocketHandlerListener(this);
        //KG-9437 temp work around, always fire binaryMessageReceived
        listener.textMessageReceived = function (channel, text) {
            //conver UTF8 string to Bytebuffer
            $this._listener.binaryMessageReceived(channel, $rootModule.ByteBuffer.wrap(Charset.UTF8.toByteArray(text)));
        }

        listener.binaryMessageReceived = function (channel, buf) {
            throw new Error("draft76 won't receive binary frame");
        }
        nextHandler.setListener(listener);
    }

    $prototype.setListener = function (listener) {
        this._listener = listener;
    }

    return WebSocketHixie76FrameCodecHandler;
})()


text:
"""Library for computing the parallization and routing for streaming queries.

The client computes the keyranges to parallelize over
based on the desired parallization and shard count.
Please note that the shard count maybe greater than equal
to actual shards. It is suggested to keep this value
at the upsharded count in case a resharding event is planned.
These keyranges can then be used to derived the routing
information. The routing information object is supposed to
be opaque to the client but VTGate uses it to route queries.
It is also used to compute the associated where clause to be added
to the query, wich is needed to prevent returning duplicate result
from two parallelized queries running over the same shard.

API usage -

task_map = vtrouting.create_parallel_task_keyrange_map(num_tasks, shard_count)
keyrange_list = task_map.keyrange_list

for db_keyrange in keyrange_list:
  vt_routing_info = vtrouting.create_vt_routing_info(db_keyrange, 'ruser')

During query construction -

where_clause, bind_vars = vt_routing_info.update_where_clause(
           where_clause, bind_vars)
"""

from vtdb import dbexceptions
from vtdb import keyrange
from vtdb import keyrange_constants
from vtdb import topology

class TaskKeyrangeMap(object):
  """Class for computing keyranges for parallel tasks.

  Attributes:
   num_tasks: number of parallel queries.
  """

  def __init__(self, num_tasks):
    self.num_tasks = num_tasks
    self.keyrange_list = []
    self.compute_kr_list()

  def compute_kr_list(self):
    """compute the keyrange list for parallel queries.
    """
    kr_chunks = []
    # we only support 256 shards for now
    min_key_hex = int('00', base=16)
    max_key_hex = int('100', base=16)
    kr = min_key_hex
    span = (max_key_hex - min_key_hex)/self.num_tasks
    kr_chunks.append('')
    for i in xrange(self.num_tasks):
      kr += span
      kr_chunks.append('%.2x' % kr)
    kr_chunks[-1] = ''
    for i in xrange(len(kr_chunks) - 1):
      start = kr_chunks[i]
      end = kr_chunks[i+1]
      kr = keyrange.KeyRange((start, end,))
      self.keyrange_list.append(str(kr))

class VTRoutingInfo(object):
  """Class to encompass the keyrange and compute the where clause with the same.

  Attributes:
    db_keyrange: the keyrange to route the query to.
    extra_where_clause: where clause with the sharding key for the keyspace.
    extra_bind_vars: bind var dictionary with the sharding key for the keyspace.
  """

  def __init__(self, db_keyrange, where_clause, bind_vars):
    self.db_keyrange = db_keyrange
    self.extra_where_clause = where_clause
    self.extra_bind_vars = bind_vars

  def update_where_clause(self, where_clause, bind_vars):
    """Updates the existing where clause of the query with the routing info.

    Args:
      where_clause: the where_clause of the query being constructed.
      bind_vars: bind_vars of the query being constructed.

    Returns:
      updated where_clause and bind_vars with the sharding key
      of the keyspace and the db_keyrange.
      Example -
      Assuming sharding key of keyspace 'test_keyspace' is
      'keyspace_id'.
      returned_where_clause = where_clause AND keyspace_id <= <db_keyrange>
      returned_bind_vars = {'keyspace_id': <db_keyrange>}
    """
    if self.extra_where_clause:
      if where_clause:
        where_clause += ' AND ' + self.extra_where_clause
      else:
        where_clause = self.extra_where_clause
    if self.extra_bind_vars:
      bind_vars.update(self.extra_bind_vars)
    return where_clause, bind_vars

def create_parallel_task_keyrange_map(num_tasks, shard_count):
  """Compute the task map for a streaming query.

  Args:
    num_tasks: desired parallelization of queries.
    shard_count: configurable global shard count for keyspace.
    This can be greater than actual shards and should be set to
    the desired upsharded value before a resharding event.
    This is so that the keyrange->shard map for an inflight
    query is always unique.

  Returns:
    TaskKeyrangeMap object
  """
  if num_tasks % shard_count != 0:
    raise dbexceptions.ProgrammingError(
        'tasks %d should be multiple of shard_count %d' % (num_tasks,
                                                           shard_count))
  return TaskKeyrangeMap(num_tasks)

def create_vt_routing_info(key_range, keyspace_name):
  """Creates VTRoutingInfo object for the given key_range in keyspace.

  Args:
    key_range: keyrange for query routing.
    keyspace_name: target keyspace for the query. This is used to derive
    sharding column type and column name information for the where clause.

  Returns:
    VTRoutingInfo object.
  """
  col_name, col_type = topology.get_sharding_col(keyspace_name)
  if not col_name or col_type == keyrange_constants.KIT_UNSET:
    return VTRoutingInfo(key_range, '', {})
  where_clause, bind_vars = _create_where_clause_for_keyrange(key_range,
                                                              col_name,
                                                              col_type)
  return VTRoutingInfo(key_range, where_clause, bind_vars)

def _true_int_kr_value(kr_value):
  """This returns the true value of keyrange for comparison with keyspace_id.

  We abbreviate the keyranges for ease of use.
  To obtain true value for comparison with keyspace id,
  create true hex value for that keyrange by right padding and conversion.
  Args:
    kr_value: short keyranges as used by vitess.
  Returns:
    complete hex value of keyrange.
  """
  if kr_value == '':
    return None
  kr_value += (16-len(kr_value))*'0'
  if not kr_value.startswith('0x'):
    kr_value = '0x' + kr_value
  return int(kr_value, base=16)

def _create_where_clause_for_keyrange(
    key_range, keyspace_col_name='keyspace_id',
    keyspace_col_type=keyrange_constants.KIT_UINT64):
  """Compute the where clause and bind_vars for a given keyrange.

  Args:
    key_range: keyrange for the query.
    keyspace_col_name: keyspace column name of keyspace.
    keyspace_col_type: keyspace column type of keyspace.
  Returns:
    where clause for the keyrange.
  """

  if isinstance(key_range, str):
    # If the key_range is for unsharded db, there is no
    # where clause to add to or bind_vars to add to.
    if key_range == keyrange_constants.NON_PARTIAL_KEYRANGE:
      return '', {}
    key_range = key_range.split('-')

  if (not isinstance(key_range, tuple) and not isinstance(key_range, list) or
      len(key_range) != 2):
    raise dbexceptions.ProgrammingError(
        'key_range must be list or tuple or \'-\' separated str %s' % key_range)

  if keyspace_col_type == keyrange_constants.KIT_UINT64:
    return _create_where_clause_for_int_keyspace(key_range, keyspace_col_name)
  elif keyspace_col_type == keyrange_constants.KIT_BYTES:
    return _create_where_clause_for_str_keyspace(key_range, keyspace_col_name)
  else:
    raise dbexceptions.ProgrammingError(
        'Illegal type for keyspace_col_type %d' % keyspace_col_type)

def _create_where_clause_for_str_keyspace(key_range, keyspace_col_name):
  """This creates the where clause and bind_vars if keyspace_id col is a str.

  The comparison is done using mysql hex function and byte level comparison
  with the key_range values.

  Args:
    key_range: keyrange for the query.
    keyspace_col_name: keyspace column name for the keyspace.

  Returns:
    This returns the where clause when the keyspace column type is string.
  """
  kr_min = key_range[0].strip()
  kr_max = key_range[1].strip()

  where_clause = ''
  bind_vars = {}
  i = 0
  if kr_min != keyrange_constants.MIN_KEY:
    bind_name = '%s%d' % (keyspace_col_name, i)
    where_clause = 'hex(%s) >= ' % keyspace_col_name + '%(' + bind_name + ')s'
    i += 1
    bind_vars[bind_name] = kr_min
  if kr_max != keyrange_constants.MAX_KEY:
    if where_clause:
      where_clause += ' AND '
    bind_name = '%s%d' % (keyspace_col_name, i)
    where_clause += 'hex(%s) < ' % keyspace_col_name + '%(' + bind_name + ')s'
    bind_vars[bind_name] = kr_max
  return where_clause, bind_vars

def _create_where_clause_for_int_keyspace(key_range, keyspace_col_name):
  """This creates the where clause and bind_vars if keyspace_id col is a int.

  The comparison is done using numeric comparison on the int values hence
  the true 64-bit int values are generated for the key_range in the bind_vars.

  Args:
    key_range: keyrange for the query.
    keyspace_col_name: keyspace column name for the keyspace.

  Returns:
    This returns the where clause when the keyspace column type is uint64.
  """
  kr_min = _true_int_kr_value(key_range[0])
  kr_max = _true_int_kr_value(key_range[1])

  where_clause = ''
  bind_vars = {}
  i = 0
  if kr_min is not None:
    bind_name = '%s%d' % (keyspace_col_name, i)
    where_clause = '%s >= ' % keyspace_col_name + '%(' + bind_name + ')s'
    i += 1
    bind_vars[bind_name] = kr_min
  if kr_max is not None:
    if where_clause:
      where_clause += ' AND '
    bind_name = '%s%d' % (keyspace_col_name, i)
    where_clause += '%s < ' % keyspace_col_name + '%(' + bind_name + ')s'
    bind_vars[bind_name] = kr_max
  return where_clause, bind_vars


text:
{% extends "index.html" %}
{% set title = 'BKK Pool League: Login' %}

{% block content %}
<form id="login-form" action="/login" method="POST"  autocomplete="off">

Please enter your email and password

			Email: <input type="email" id="email" name="email">

			Password: <input type="password" id="password" name="password">

			<input type="submit" id="submit" name="login" value="login">

	<input type="hidden" name="h" value="{{ h }}">
</form>
 {% endblock %}


text:
namespace Infrastructure.Tests.Data.Domain.Mapping
{
    public class OrderMapping : EntityMappingBase<Order>
    {
        public OrderMapping()
        {
            HasKey(x => x.Id);

            Property(x => x.OrderDate);
            Property(x => x.CustomerId);

            HasRequired<Customer>(x => x.Customer)
                .WithMany(y => y.Orders)
                .HasForeignKey(o => o.CustomerId);

            ToTable("Order");
        }
    }
}


text:
'use strict';

import convert from 'koa-convert';

import cors from 'kcors';
import createLogger from 'concurrency-logger';
import helmet from "koa-helmet";
import bodyparser from "koa-bodyparser";

import sessionMiddleware from './session';

/**
 * A JS function that applies each middleware to passed in app
 *
 * Used middlewares:
 * - Concurrency Logger
 * - Session based on MongoDB
 * - CORS
 * - Security headers
 * - HTTP request auto body parsing
 *
 * @param  {Koa} app
 */
export default function middlewares(app) {
  app.use(createLogger({
    timestamp: true,
  }));
  app.use(convert(sessionMiddleware));
  app.use(cors());
  app.use(helmet());
  app.use(bodyparser());
}


text:
JGProgressHUD
---------------

An elegant and simple progress HUD for iOS and tvOS.

Overview
---------------

__The ultimate progress HUD for iOS and tvOS is here: JGProgressHUD!__

- Plug and play: Simple integration, easy to use, few lines of code required.
- Easily customizable (custom animations, indicator views and more).
- Uses `UIVisualEffectView` and `UIMotionEffect` for a native look.
- Uses AutoLayout to provide a fully dynamic layout.
- Detects and repositions when keyboard appears/disappears.
- Well documented and maintained.
- Voice Over/`UIAccessibility` support.
- Backward compatibility to iOS 8.
- Can be used with Swift and Objective C.
- And most importantly, it looks good!

Download the source code and open the Examples project to try JGProgressHUD and see all of its features in action!

[![GitHub release](https://img.shields.io/github/release/JonasGessner/JGProgressHUD.svg)](https://github.com/JonasGessner/JGProgressHUD/releases)
[![GitHub license](https://img.shields.io/github/license/JonasGessner/JGProgressHUD.svg)](https://github.com/JonasGessner/JGProgressHUD/blob/master/LICENSE.txt)
[![CocoaPods](https://img.shields.io/cocoapods/v/JGProgressHUD.svg)](https://cocoapods.org/pods/JGProgressHUD)
[![Carthage compatible](https://img.shields.io/badge/Carthage-compatible-4BC51D.svg?style=flat)](https://github.com/Carthage/Carthage)

Examples
--------------

#### Showing indeterminate progress:

Objective C:

```objc
JGProgressHUD *HUD = [JGProgressHUD progressHUDWithStyle:JGProgressHUDStyleDark];
HUD.textLabel.text = @"Loading";
[HUD showInView:self.view];
[HUD dismissAfterDelay:3.0];
```

Swift:

```swift
let hud = JGProgressHUD(style: .dark)
hud.textLabel.text = "Loading"
hud.show(in: self.view)
hud.dismiss(afterDelay: 3.0)
```

This displays a dark HUD with an activity indicator and the title "Loading". The HUD is presented with a fade animation and is dismissed after 3 seconds with a fade animation.

#### Showing an error message:

```objc
JGProgressHUD *HUD = [JGProgressHUD progressHUDWithStyle:JGProgressHUDStyleDark];
HUD.textLabel.text = @"Error";
HUD.indicatorView = [[JGProgressHUDErrorIndicatorView alloc] init]; //JGProgressHUDSuccessIndicatorView is also available
[HUD showInView:self.view];
[HUD dismissAfterDelay:3.0];
```

#### Showing determinate progress:

```objc
JGProgressHUD *HUD = [JGProgressHUD progressHUDWithStyle:JGProgressHUDStyleDark];
HUD.indicatorView = [[JGProgressHUDPieIndicatorView alloc] init]; //Or JGProgressHUDRingIndicatorView
HUD.progress = 0.5f;
[HUD showInView:self.view];
[HUD dismissAfterDelay:3.0];
```

__Important:__ You should always show `JGProgressHUD` in a `UIViewController` view.

Download the source code and open the Examples project to explore more use cases for JGProgressHUD.

Customization
-----------
### Styles:
JGProgressHUD can be displayed in 3 styles:

- __Extra Light__
- __Light__
- __Dark__

### Indicator Views:
By default a HUD will display an indeterminate progress indicator. The indicator view can be completely hidden by setting the `indicatorView` property to `nil`. These indicator views are available by default:

- __Indeterminate progress indicator__
- __Pie progress indicator__
- __Ring progress indicator__
- __Success indicator__
- __Error indicator__
- __Image indicator__

Custom indicator views can be created by subclassing `JGProgressHUDIndicatorView`.

### Animations:
By default a HUD will use a fade animation. Several parameters can be altered such as animation duration or animation curve. A HUD can be displayed without animation and different animations can be used. These animations are available by default:

- __Fade__
- __Zoom and Fade__

Custom animations can be created by subclassing `JGProgressHUDAnimation`.

To dim the content behind the HUD set your dim color as `backgroundColor` of your `JGProgressHUD` instance.

Installation
--------------
### CocoaPods:
In your `Podfile` add:

```
pod 'JGProgressHUD'
```

### Carthage:
In your `Cartfile` add:

```
github "JonasGessner/JGProgressHUD"
```

### Manual Installation (Framework):

1. Drag the `JGProgressHUD.xcodeproj` file into your Xcode project.
2. Add `JGProgressHUD.framework` to "Embedded Binaries" in the "General" tab of your target.

Then import the module where you want to use it:

```objc
@import JGProgressHUD;
```

Swift:

```swift
import JGProgressHUD
```

See the Examples project for an example implementation of JGProgressHUD as framework.

Requirements
------------

- Base SDK of iOS/tvOS 11 or higher.
- Deployment target of iOS/tvOS 8.0 or higher.

JGProgressHUD can also be used by projects written in Swift. See Installation for details.

Documentation
----------------
Detailed documentation can be found on CocoaDocs.

Each method is well documented, making it easy to quickly get a great overview of JGProgressHUD. To start, see JGProgressHUD.h.

License
---------
MIT License.

© 2014-2017, Jonas Gessner.

Credits
----------
Created and maintained by Jonas Gessner, © 2014-2017.


text:
product: material-ui
title: Componente React Avaliação
components: Rating
githubLabel: 'component: rating'
waiAria: 'https://www.w3.org/WAI/tutorials/forms/custom-controls/#a-star-rating'
---

# Rating

Avaliações fornecem informações sobre as opiniões e experiências dos outros e permitem que o usuário envie sua própria avaliação.

{{"component": "modules/components/ComponentLinkHeader.js"}}

## Avaliação básica

{{"demo": "BasicRating.js"}}

## Avaliação precisa

A avaliação pode exibir qualquer número flutuante com a propriedade `value`. Use a propriedade `precision` para definir a alteração mínima do valor de incremento permitida.

{{"demo": "HalfRating.js"}}

## Feedback ao passar o mouse

Você pode exibir um rótulo ao passar o mouse para ajudar os usuários a escolher o valor de avaliação correto. A demonstração usa a propriedade `onChangeActive`.

{{"demo": "HoverRating.js"}}

## Tamanhos

Para avaliações maiores ou menores use a propriedade `size`.

{{"demo": "RatingSize.js"}}

## Avaliação customizada

Aqui estão alguns exemplos de customização do componente. You can learn more about this in the [overrides documentation page](/material-ui/customization/how-to-customize/).

{{"demo": "CustomizedRating.js"}}

## Radio group

The rating is implemented with a radio group, set `highlightSelectedOnly` to restore the natural behavior.

{{"demo": "RadioGroupRating.js"}}

## Acessibilidade

([WAI tutorial](https://www.w3.org/WAI/tutorials/forms/custom-controls/#a-star-rating))

A acessibilidade neste componente conta com:

- Um grupo de botões de opção com seus campos visualmente ocultos. Ele contém seis botões de opção, um para cada estrela e outro para 0 estrelas, que é marcado por padrão. Certifique-se de fornecer um valor para a propriedade `name` que é exclusivo para o formulário pai.
- Labels for the radio buttons containing actual text ("1 Star", "2 Stars", …). Certifique-se de fornecer uma função adequada para a propriedade `getLabelText` quando a página estiver em um idioma diferente de inglês. You can use the [included locales](https://mui.com/material-ui/guides/localization/), or provide your own.
- Uma aparência visualmente distinta para os ícones de avaliação. Por padrão, o componente de avaliação usa uma diferença de cor e forma (ícones preenchidos e vazios) para indicar o valor. No caso de você usar cor como a única forma de indicar o valor, a informação também deve ser apresentada como texto, como nesta demonstração. Isto é importante para corresponder a [success Criterion 1.4.1](https://www.w3.org/TR/WCAG21/#use-of-color) do WCAG2.1.

{{"demo": "TextRating.js"}}

### ARIA

A avaliação de somente leitura tem uma regra de "img" e um aria-label que descreve a avaliação exibida.

### Teclado

Devido ao componente avaliação usar botões de opção, a interação do teclado segue o comportamento nativo do navegador. A tecla tab irá focar a avaliação atual e as teclas do cursor controlam a avaliação selecionada.

A avaliação de somente leitura não é focável.


text:
<!DOCTYPE HTML PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN" "http://www.w3.org/TR/html4/loose.dtd">

<META http-equiv="Content-Type" content="text/html; charset=ISO-8859-1">
<TITLE>
org.apache.commons.logging Class Hierarchy (SLF4J 1.5.2 API)
</TITLE>

<LINK REL ="stylesheet" TYPE="text/css" HREF="../../../../stylesheet.css" TITLE="Style">

      Overview
      Package
      Class
      Use
    Tree
      Deprecated
      Index
      Help

 PREV
 NEXT

  FRAMES
 NO FRAMES

  All Classes

Hierarchy For Package org.apache.commons.logging

Package Hierarchies:
All Packages

Class Hierarchy

java.lang.Object

org.apache.commons.logging.LogFactory
java.lang.Throwable (implements java.io.Serializable)

java.lang.Exception

java.lang.RuntimeException

org.apache.commons.logging.LogConfigurationException

Interface Hierarchy

org.apache.commons.logging.Log

      Overview
      Package
      Class
      Use
    Tree
      Deprecated
      Index
      Help

 PREV
 NEXT

  FRAMES
 NO FRAMES

  All Classes

Copyright © 2005-2008 QOS.ch. All Rights Reserved.


text:
typedef enum{
	VERTEX_SHDR=0x0,
	GEOMETRY_SHDR=0x1
}SHDR_type;

typedef enum{
	RESULT_POSITION = 0x0,
	RESULT_COLOR = 0x2,
	RESULT_TEXCOORD0 = 0x3,
	RESULT_TEXCOORD1 = 0x5,
	RESULT_TEXCOORD2 = 0x6
}SHDR_outType;

typedef struct{
	u32 codeSize;
	u32* codeData;
	u32 opdescSize;
	u32* opcdescData;
}DVLP_s;

typedef struct{
	u32 header;
	u32 data[4];
}DVLE_constEntry_s;

typedef struct{
	u16 type;
	u16 regID;
	u32 header;
}DVLE_outEntry_s;

typedef struct{
	u32 symbolOffset;
	u16 startReg;
	u16 endReg;
}DVLE_uniformEntry_s;

typedef struct{
	SHDR_type type;
	u32 mainOffset, endmainOffset;
	u32 constTableSize;
	DVLE_constEntry_s* constTableData;
	u32 outTableSize;
	DVLE_outEntry_s* outTableData;
	u32 uniformTableSize;
	DVLE_uniformEntry_s* uniformTableData;
	char* symbolTableData;
}DVLE_s;

typedef struct{
	u32 numDVLE;
	DVLP_s DVLP;
	DVLE_s* DVLE;
}DVLB_s;

DVLB_s* SHDR_ParseSHBIN(u32* shbinData, u32 shbinSize);
void SHDR_UseProgram(DVLB_s* dvlb, u8 id);
void SHDR_FreeDVLB(DVLB_s* dvlb);
s8 SHDR_GetUniformRegister(DVLB_s* dvlb, char* name, u8 programID);

void DVLP_SendCode(DVLP_s* dvlp);
void DVLP_SendOpDesc(DVLP_s* dvlp);

void DVLE_SendOutmap(DVLE_s* dvle);
void DVLE_SendConstants(DVLE_s* dvle);

#endif


text:
<!DOCTYPE html>

    <meta http-equiv="Content-Type" content="text/html; charset=UTF-8">
    {common_head}

                <input id="btn_create" class="btn2" value="新建试题分类" title="" type="button"/>
                <input id="btn_all_exam_question" class="btn2" value="管理全部试题"  type="button"/>

            全
            编辑
            状态

            名称
            排序
            管理试题

        <icms id="exam_question_class_list" type="list">
            <item>
                <![CDATA[

                            <input class="doc_input"
                                                                                type="checkbox"
                                                                                name="doc_input"
                                                                                value="{f_ExamQuestionClassId}"/>

                            {f_State}

                                {f_ExamQuestionClassName}
                                [新增子分类]

                            {f_Sort}

                                管理试题

                {child}
                ]]>
            </item>
            <child>
                <![CDATA[

                            <input class="doc_input" type="checkbox" name="docinput" value="{f_ExamQuestionClassId}" />

                            {f_State}

                            {f_ExamQuestionClassName}
                                [新增三级分类]

                            {f_Sort}

                                管理试题

                {third}
                ]]>
            </child>
            <third>
                <![CDATA[

                            <input class="doc_input" type="checkbox" name="docinput" value="{f_ExamQuestionClassId}" />

                            {f_State}

                            {f_ExamQuestionClassName}

                            {f_Sort}

                                管理试题

                ]]>
            </third>
        </icms>

{pager_button}


text:
// Copyright Keith D Gregory
//
// Licensed under the Apache License, Version 2.0 (the "License");
// you may not use this file except in compliance with the License.
// You may obtain a copy of the License at
//
//     http://www.apache.org/licenses/LICENSE-2.0
//
// Unless required by applicable law or agreed to in writing, software
// distributed under the License is distributed on an "AS IS" BASIS,
// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
// See the License for the specific language governing permissions and
// limitations under the License.

package com.kdgregory.pomutil.cleaner.transform;

import java.util.ArrayList;
import java.util.LinkedHashMap;
import java.util.List;
import java.util.Map;

import org.w3c.dom.Document;
import org.w3c.dom.Element;

import net.sf.practicalxml.DomUtil;
import net.sf.practicalxml.ParseUtil;

import com.kdgregory.pomutil.cleaner.CommandLine;
import com.kdgregory.pomutil.util.PomWrapper;
import com.kdgregory.pomutil.util.Utils;

/**
 *  Organizes the POM according to the prototype. Disabled by default.
 */
public class OrganizePom
extends AbstractTransformer
{

//----------------------------------------------------------------------------
//  Instance variables and constructors
//----------------------------------------------------------------------------

    private boolean enabled;

    /**
     *  Base constructor.
     */
    public OrganizePom(PomWrapper pom, CommandLine args)
    {
        super(pom, args);
        enabled = args.isOptionEnabled(CommandLine.Options.ORGANIZE_POM);
    }

//----------------------------------------------------------------------------
//  Transformer
//----------------------------------------------------------------------------

    @Override
    public void transform()
    {
        if (!enabled)
            return;

        String[] expectedElements = loadPrototype();

        Element root = pom.getDom().getDocumentElement();
        Map<String,Element> children = selectElements(root);
        Utils.reconstruct(root, children, expectedElements);
    }

//----------------------------------------------------------------------------
//  Implementation
//----------------------------------------------------------------------------

    private String[] loadPrototype()
    {
        List<String> result = new ArrayList<String>();
        Document proto = ParseUtil.parseFromClasspath("proto-pom.xml");
        for (Element elem : DomUtil.getChildren(proto.getDocumentElement()))
        {
            result.add(DomUtil.getLocalName(elem));
        }
        return result.toArray(new String[result.size()]);
    }

    private Map<String,Element> selectElements(Element root)
    {
        Map<String,Element> result = new LinkedHashMap<String,Element>();
        for (Element elem : DomUtil.getChildren(root))
        {
            result.put(DomUtil.getLocalName(elem), elem);
        }
        return result;
    }
}


text:
% Author: Carl Doersch (cdoersch at cs dot cmu dot edu)
%
% change the current working directory-struct that dswork is using.
% dspath can be an absolute or relative path.  For example, if the
% ds currently contains (where '-' means a field):
%
% ds - struct1
%    - struct2 - field1
%              - field2
%
% Then dscd('ds.struct2') will result in a ds that looks like:
%
% ds - field1
%    - field2
%
% and so a call to ds.field1 will succeed.  You can no longer access
% ds.struct1 directly; you must either use dscd('.ds'), or use functions
% that recognize absolute paths.

function dscd(dspath)
  global ds;
  targ=dsabspath(dspath);
  targ=targ(4:end);
  rootpath=['ds.sys.root' targ];
  varpath=dsfindvar(dspath);
  if(dsfield(varpath))
    if(~eval(['isstruct(' varpath ')']))
      throw MException('ds:cantcd','Cannot cd into fieldi ' dspath ' that is not a struct');
    end
  else
    eval([rootpath '=struct();']);
  end
  if(dsfield(ds,'conf'))
    newconf=ds.conf;
  end

  %try
    if(dsfield(ds,'sys'))
      sys=ds.sys;
      ds2=rmfield(ds,'sys');
    else
      sys=struct();
      ds2=ds;
    end
    if(~dsfield(sys,'currpath'))
      sys.currpath='';
    end
    eval(['sys.root' sys.currpath '=ds2;']);
    if(~dsfield(sys,['root' targ]))
      %if(dsfield(sys,['savestate' sys.currpath]))
      eval(['sys.root' targ '=struct();']);
      %else
      %  throw MException('ds:cantcd','Cannot cd into fieldi ' dspath ' that does not exist.');
      %end
    end
    eval(['ds2=sys.root' targ ';']);
    eval(['sys.root' targ '=struct();']);
    %if(~dsfield(['sys.savestate' targ])) %don't actually want to create a savestate, or we'll think we have it on disk
    %  eval(['sys.savestate' targ '=struct();']);
    %end
    sys.currpath=targ;
    ds2.sys=sys;
    ds=ds2;
  %catch someexception
  %  ex=MException('dswork:cantcd','cannot cd')
  %  ex=addCause(ex,someexception);
  %  throw(ex);
  %end
  if(~dsfield(ds,'conf')&&exist('newconf','var'))
    ds.conf=newconf;
  end
end


text:
<?php

namespace Coyote\Services\Stream\Render;

class Block extends Render
{
    /**
     * @return mixed
     */
    protected function excerpt()
    {
        return array_get($this->stream, 'object.content');
    }

    /**
     * @return string
     */
    protected function object()
    {
        return parent::object() . ': ' . array_get($this->stream, 'object.displayName');
    }
}


text:
<?php

use React\Filesystem\Factory;
use React\Filesystem\Node\FileInterface;

require 'vendor/autoload.php';

Factory::create()->detect(__FILE__ . '.copy')->then(static function (FileInterface $file) {
    return $file->putContents(file_get_contents(__FILE__));
})->then(static function ($result): void {
    var_export([$result]);
})->done();


text:
require_relative '../spec_helper'
require 'rr'

describe RR::EpisodeList do
  before do
    @source ||= File.read( 'specs/data/episodes.html' )
    @episodes = RR::EpisodeList.new( {source: @source} )
  end

  it "should iterate over episodes" do
    @episodes.each do |ep|
      ep.number.wont_be_nil
    end
  end

  it "should get an episode by index" do
    @episodes[1].title.must_equal "002 RR Virtual Machines, Concurrency, and the Future of Ruby"
  end
end


text:
---
uid: SolidEdgeAssembly.AssemblyGroups.Count
summary:
remarks:
---


text:
from django.db import models

from projects.models import Participant

class Tracking(models.Model):
    participant = models.ForeignKey(
        Participant, verbose_name='Participante del Proyecto')
    day = models.DateField(verbose_name='Día')
    hours = models.SmallIntegerField(null=True, blank=True,
                                     verbose_name='Horas invertidas')
    notes =  models.TextField(
        null=True, blank=True, verbose_name='Notas o comentarios')

    def __str__(self):
        s = [
            str(self.participant),
            ' - ',
            str(self.date),
            ' - ',
            str(self.hours)
        ]
        return ''.join(s)


text:
import 'index.css';
import React from 'react';
import ReactDOM from 'react-dom';

import { Provider } from 'react-redux';
import { configureStore } from 'store';
import { Router, Route, Switch } from 'react-router-dom'
import { history, AuthorizedRoute, UnauthorizedRoute } from 'routing';
import { authMethods } from 'modules/auth';

// route components
import App from 'containers/App';
import {Login, Signup} from 'containers/Auth';
import Dashboard from 'containers/Dashboard';
import Home from 'containers/Home';

const store = configureStore();

const render = () => ReactDOM.render(
    (
        <Provider store={store}>
            <Router history={history}>
                <App>
                    <Switch>
                        <Route exact path="/" component={Home} />
                        <UnauthorizedRoute path="/login" component={Login} />
                        <UnauthorizedRoute path="/signup" component={Signup} />
                        <AuthorizedRoute path="/dashboard" component={Dashboard} />
                    </Switch>
                </App>
            </Router>
        </Provider>
    ),
    document.getElementById('root')
);

// Dispatch auth state (i.e. check firebase auth state) before rendering.
// If a user refreshes the browser while on an AuthorizedRoute they'll be already
// logged in and the route will render without redirects
authMethods.dispatchAuthState(store.dispatch)
.then(render)


text:
using System.Collections.Generic;
using Azure.Core;
using Azure.ResourceManager.Automation;

namespace Azure.ResourceManager.Automation.Models
{
    /// <summary> The response model for the list hybrid runbook workers. </summary>
    internal partial class HybridRunbookWorkersListResult
    {
        /// <summary> Initializes a new instance of HybridRunbookWorkersListResult. </summary>
        internal HybridRunbookWorkersListResult()
        {
            Value = new ChangeTrackingList<HybridRunbookWorkerData>();
        }

        /// <summary> Initializes a new instance of HybridRunbookWorkersListResult. </summary>
        /// <param name="value"> Gets or sets a list of hybrid runbook workers. </param>
        /// <param name="nextLink"> Gets or sets the next link. </param>
        internal HybridRunbookWorkersListResult(IReadOnlyList<HybridRunbookWorkerData> value, string nextLink)
        {
            Value = value;
            NextLink = nextLink;
        }

        /// <summary> Gets or sets a list of hybrid runbook workers. </summary>
        public IReadOnlyList<HybridRunbookWorkerData> Value { get; }
        /// <summary> Gets or sets the next link. </summary>
        public string NextLink { get; }
    }
}


text:
package lucene4ir.indexer;

import lucene4ir.Lucene4IRConstants;
import lucene4ir.utils.TokenAnalyzerMaker;
import org.apache.commons.compress.compressors.z.ZCompressorInputStream;

import org.apache.lucene.analysis.Analyzer;
import org.apache.lucene.document.Document;
import org.apache.lucene.index.IndexWriter;
import org.apache.lucene.index.IndexWriterConfig;
import org.apache.lucene.store.Directory;
import org.apache.lucene.store.FSDirectory;

import java.io.*;
import java.nio.file.Paths;
import java.util.zip.GZIPInputStream;

/**
 * Created by leifos on 21/08/2016.
 * Edited by kojayboy on 16/08/2017.
 * Edited by Leifos 10/9/2017
 * Added extra method openDocumentFile that can handle different input file types
 * i.e. compressed (gz, etc) and creates the appropriate input reader
 * probably should re-factor class to provide a templated method with the BufferredReader to process for each file
 * and not the file itself.
 */
public class DocumentIndexer {

    protected boolean indexPositions;
    public IndexWriter writer;
    public Analyzer analyzer;

    public DocumentIndexer(){};

    public DocumentIndexer(String indexPath, String tokenFilterFile, boolean positional){
        writer = null;
        analyzer = Lucene4IRConstants.ANALYZER;
        indexPositions=positional;

        if (tokenFilterFile != null){
            TokenAnalyzerMaker tam = new TokenAnalyzerMaker();
            analyzer = tam.createAnalyzer(tokenFilterFile);
        }
        createWriter(indexPath);
    }

    public void createWriter(String indexPath){
        /*
        The indexPath specifies where to create the index
         */

        // I am can imagine that there are lots of ways to create indexers -
        // We could add in some parameters to customize its creation

        try {
            Directory dir = FSDirectory.open(Paths.get(indexPath));
            System.out.println("Indexing to directory '" + indexPath + "'...");

            IndexWriterConfig iwc = new IndexWriterConfig(analyzer);
            iwc.setOpenMode(IndexWriterConfig.OpenMode.CREATE);
            writer = new IndexWriter(dir, iwc);

        } catch (IOException e){
            e.printStackTrace();
            System.exit(1);
        }
    }

    public void addDocumentToIndex(Document doc){
        try {
            writer.addDocument(doc);
        } catch (IOException e){
            e.printStackTrace();
            System.exit(1);
        }
    }

    public void indexDocumentsFromFile(String filename){
        /* to be implemented in sub classess*/
    };

    protected BufferedReader openDocumentFile(String filename){
        BufferedReader br = null;
        try {
            if(filename.endsWith(".gz")) {
                InputStream fileStream = new FileInputStream(filename);
                InputStream gzipStream = new GZIPInputStream(fileStream);
                Reader decoder = new InputStreamReader(gzipStream, "UTF-8");
                br = new BufferedReader(decoder);
            }
            else
            {
                // For the weirdness that is TREC collections.
                if (filename.endsWith(".Z") || filename.endsWith(".0Z") || filename.endsWith(".1Z") || filename.endsWith(".2Z")) {
                    InputStream fileStream = new FileInputStream(filename);
                    //InputStream zipStream = new ZCompressorInputStream(fileStream);
                    ZCompressorInputStream zipStream = new ZCompressorInputStream(fileStream);
                    Reader decoder = new InputStreamReader(zipStream, "UTF-8");
                    br = new BufferedReader(decoder);
                }
                else
                    br = new BufferedReader(new FileReader(filename));
            }

        } catch (Exception e){
            e.printStackTrace();
            System.exit(1);
        }
        return br;
    }

    public void finished(){
        try {
            if (writer != null){
                writer.close();
            }
        } catch (IOException e){
            e.printStackTrace();
            System.exit(1);
        }
    }

}