text:
#include <algorithm>  // max

#include "testing/gtest/include/gtest/gtest.h"

#include "webrtc/call.h"
#include "webrtc/common_video/interface/i420_video_frame.h"
#include "webrtc/frame_callback.h"
#include "webrtc/modules/rtp_rtcp/interface/rtp_header_parser.h"
#include "webrtc/modules/rtp_rtcp/interface/rtp_rtcp.h"
#include "webrtc/modules/rtp_rtcp/source/rtcp_sender.h"
#include "webrtc/modules/rtp_rtcp/source/rtcp_utility.h"
#include "webrtc/system_wrappers/interface/critical_section_wrapper.h"
#include "webrtc/system_wrappers/interface/event_wrapper.h"
#include "webrtc/system_wrappers/interface/scoped_ptr.h"
#include "webrtc/system_wrappers/interface/sleep.h"
#include "webrtc/system_wrappers/interface/thread_wrapper.h"
#include "webrtc/test/direct_transport.h"
#include "webrtc/test/configurable_frame_size_encoder.h"
#include "webrtc/test/encoder_settings.h"
#include "webrtc/test/fake_encoder.h"
#include "webrtc/test/frame_generator_capturer.h"
#include "webrtc/test/null_transport.h"
#include "webrtc/test/rtp_rtcp_observer.h"
#include "webrtc/test/testsupport/perf_test.h"
#include "webrtc/video/transport_adapter.h"
#include "webrtc/video_send_stream.h"

namespace webrtc {

enum VideoFormat { kGeneric, kVP8, };

class VideoSendStreamTest : public ::testing::Test {
 public:
  VideoSendStreamTest()
      : send_stream_(NULL), fake_encoder_(Clock::GetRealTimeClock()) {}

 protected:
  void RunSendTest(Call* call,
                   const VideoSendStream::Config& config,
                   test::RtpRtcpObserver* observer) {
    send_stream_ = call->CreateVideoSendStream(config);
    scoped_ptr<test::FrameGeneratorCapturer> frame_generator_capturer(
        test::FrameGeneratorCapturer::Create(
            send_stream_->Input(), 320, 240, 30, Clock::GetRealTimeClock()));
    send_stream_->StartSending();
    frame_generator_capturer->Start();

    EXPECT_EQ(kEventSignaled, observer->Wait());

    observer->StopSending();
    frame_generator_capturer->Stop();
    send_stream_->StopSending();
    call->DestroyVideoSendStream(send_stream_);
  }

  VideoSendStream::Config GetSendTestConfig(Call* call, size_t num_streams) {
    assert(num_streams <= kNumSendSsrcs);
    VideoSendStream::Config config = call->GetDefaultSendConfig();
    config.encoder_settings = test::CreateEncoderSettings(
        &fake_encoder_, "FAKE", kFakeSendPayloadType, num_streams);
    config.encoder_settings.encoder = &fake_encoder_;
    config.encoder_settings.payload_type = kFakeSendPayloadType;
    for (size_t i = 0; i < num_streams; ++i)
      config.rtp.ssrcs.push_back(kSendSsrcs[i]);
    config.pacing = true;
    return config;
  }

  void TestNackRetransmission(uint32_t retransmit_ssrc,
                              uint8_t retransmit_payload_type,
                              bool enable_pacing);

  void TestPacketFragmentationSize(VideoFormat format, bool with_fec);

  void SendsSetSsrcs(size_t num_ssrcs, bool send_single_ssrc_first);

  enum { kNumSendSsrcs = 3 };
  static const uint8_t kSendPayloadType;
  static const uint8_t kSendRtxPayloadType;
  static const uint8_t kFakeSendPayloadType;
  static const uint32_t kSendSsrc;
  static const uint32_t kSendRtxSsrc;
  static const uint32_t kSendSsrcs[kNumSendSsrcs];

  VideoSendStream* send_stream_;
  test::FakeEncoder fake_encoder_;
};

const uint8_t VideoSendStreamTest::kSendPayloadType = 100;
const uint8_t VideoSendStreamTest::kFakeSendPayloadType = 125;
const uint8_t VideoSendStreamTest::kSendRtxPayloadType = 98;
const uint32_t VideoSendStreamTest::kSendRtxSsrc = 0xBADCAFE;
const uint32_t VideoSendStreamTest::kSendSsrcs[kNumSendSsrcs] = {
    0xC0FFED, 0xC0FFEE, 0xC0FFEF};
const uint32_t VideoSendStreamTest::kSendSsrc =
    VideoSendStreamTest::kSendSsrcs[0];

void VideoSendStreamTest::SendsSetSsrcs(size_t num_ssrcs,
                                        bool send_single_ssrc_first) {
  class SendSsrcObserver : public test::RtpRtcpObserver {
   public:
    SendSsrcObserver(const uint32_t* ssrcs,
                     size_t num_ssrcs,
                     bool send_single_ssrc_first)
        : RtpRtcpObserver(30 * 1000),
          ssrcs_to_observe_(num_ssrcs),
          expect_single_ssrc_(send_single_ssrc_first) {
      for (size_t i = 0; i < num_ssrcs; ++i)
        valid_ssrcs_[ssrcs[i]] = true;
    }

    virtual Action OnSendRtp(const uint8_t* packet, size_t length) OVERRIDE {
      RTPHeader header;
      EXPECT_TRUE(parser_->Parse(packet, static_cast<int>(length), &header));

      // TODO(pbos): Reenable this part of the test when #1695 is resolved and
      //             all SSRCs are allocated on startup. This test was observed
      //             to fail on TSan as the codec gets set before the SSRCs are
      //             set up and some frames are sent on a random-generated SSRC
      //             before the correct SSRC gets set.
      // EXPECT_TRUE(valid_ssrcs_[header.ssrc])
      //    << "Received unknown SSRC: " << header.ssrc;
      //
      // if (!valid_ssrcs_[header.ssrc])
      //  observation_complete_->Set();

      if (!is_observed_[header.ssrc]) {
        is_observed_[header.ssrc] = true;
        --ssrcs_to_observe_;
        if (expect_single_ssrc_) {
          expect_single_ssrc_ = false;
          observation_complete_->Set();
        }
      }

      if (ssrcs_to_observe_ == 0)
        observation_complete_->Set();

      return SEND_PACKET;
    }

   private:
    std::map<uint32_t, bool> valid_ssrcs_;
    std::map<uint32_t, bool> is_observed_;
    size_t ssrcs_to_observe_;
    bool expect_single_ssrc_;
  } observer(kSendSsrcs, num_ssrcs, send_single_ssrc_first);

  Call::Config call_config(observer.SendTransport());
  scoped_ptr<Call> call(Call::Create(call_config));

  VideoSendStream::Config send_config =
      GetSendTestConfig(call.get(), num_ssrcs);

  if (num_ssrcs > 1) {
    // Set low simulcast bitrates to not have to wait for bandwidth ramp-up.
    std::vector<VideoStream>* streams = &send_config.encoder_settings.streams;
    for (size_t i = 0; i < streams->size(); ++i) {
      (*streams)[i].min_bitrate_bps = 10000;
      (*streams)[i].target_bitrate_bps = 10000;
      (*streams)[i].max_bitrate_bps = 10000;
    }
  }

  std::vector<VideoStream> all_streams = send_config.encoder_settings.streams;
  if (send_single_ssrc_first)
    send_config.encoder_settings.streams.resize(1);

  send_stream_ = call->CreateVideoSendStream(send_config);
  scoped_ptr<test::FrameGeneratorCapturer> frame_generator_capturer(
      test::FrameGeneratorCapturer::Create(
          send_stream_->Input(), 320, 240, 30, Clock::GetRealTimeClock()));
  send_stream_->StartSending();
  frame_generator_capturer->Start();

  EXPECT_EQ(kEventSignaled, observer.Wait())
      << "Timed out while waiting for "
      << (send_single_ssrc_first ? "first SSRC." : "SSRCs.");

  if (send_single_ssrc_first) {
    // Set full simulcast and continue with the rest of the SSRCs.
    send_stream_->ReconfigureVideoEncoder(all_streams, NULL);
    EXPECT_EQ(kEventSignaled, observer.Wait())
        << "Timed out while waiting on additional SSRCs.";
  }

  observer.StopSending();
  frame_generator_capturer->Stop();
  send_stream_->StopSending();
  call->DestroyVideoSendStream(send_stream_);
}

TEST_F(VideoSendStreamTest, CanStartStartedStream) {
  test::NullTransport transport;
  Call::Config call_config(&transport);
  scoped_ptr<Call> call(Call::Create(call_config));

  VideoSendStream::Config config = GetSendTestConfig(call.get(), 1);
  VideoSendStream* stream = call->CreateVideoSendStream(config);
  stream->StartSending();
  stream->StartSending();
  call->DestroyVideoSendStream(stream);
}

TEST_F(VideoSendStreamTest, CanStopStoppedStream) {
  test::NullTransport transport;
  Call::Config call_config(&transport);
  scoped_ptr<Call> call(Call::Create(call_config));

  VideoSendStream::Config config = GetSendTestConfig(call.get(), 1);
  VideoSendStream* stream = call->CreateVideoSendStream(config);
  stream->StopSending();
  stream->StopSending();
  call->DestroyVideoSendStream(stream);
}

TEST_F(VideoSendStreamTest, SendsSetSsrc) { SendsSetSsrcs(1, false); }

TEST_F(VideoSendStreamTest, DISABLED_SendsSetSimulcastSsrcs) {
  SendsSetSsrcs(kNumSendSsrcs, false);
}

TEST_F(VideoSendStreamTest, DISABLED_CanSwitchToUseAllSsrcs) {
  SendsSetSsrcs(kNumSendSsrcs, true);
}

TEST_F(VideoSendStreamTest, SupportsCName) {
  static std::string kCName = "PjQatC14dGfbVwGPUOA9IH7RlsFDbWl4AhXEiDsBizo=";
  class CNameObserver : public test::RtpRtcpObserver {
   public:
    CNameObserver() : RtpRtcpObserver(30 * 1000) {}

    virtual Action OnSendRtcp(const uint8_t* packet, size_t length) OVERRIDE {
      RTCPUtility::RTCPParserV2 parser(packet, length, true);
      EXPECT_TRUE(parser.IsValid());

      RTCPUtility::RTCPPacketTypes packet_type = parser.Begin();
      while (packet_type != RTCPUtility::kRtcpNotValidCode) {
        if (packet_type == RTCPUtility::kRtcpSdesChunkCode) {
          EXPECT_EQ(parser.Packet().CName.CName, kCName);
          observation_complete_->Set();
        }

        packet_type = parser.Iterate();
      }

      return SEND_PACKET;
    }
  } observer;

  Call::Config call_config(observer.SendTransport());
  scoped_ptr<Call> call(Call::Create(call_config));

  VideoSendStream::Config send_config = GetSendTestConfig(call.get(), 1);
  send_config.rtp.c_name = kCName;

  RunSendTest(call.get(), send_config, &observer);
}

TEST_F(VideoSendStreamTest, SupportsAbsoluteSendTime) {
  static const uint8_t kAbsSendTimeExtensionId = 13;
  class AbsoluteSendTimeObserver : public test::RtpRtcpObserver {
   public:
    AbsoluteSendTimeObserver() : RtpRtcpObserver(30 * 1000) {
      EXPECT_TRUE(parser_->RegisterRtpHeaderExtension(
          kRtpExtensionAbsoluteSendTime, kAbsSendTimeExtensionId));
    }

    virtual Action OnSendRtp(const uint8_t* packet, size_t length) OVERRIDE {
      RTPHeader header;
      EXPECT_TRUE(parser_->Parse(packet, static_cast<int>(length), &header));

      EXPECT_FALSE(header.extension.hasTransmissionTimeOffset);
      EXPECT_TRUE(header.extension.hasAbsoluteSendTime);
      EXPECT_EQ(header.extension.transmissionTimeOffset, 0);
      EXPECT_GT(header.extension.absoluteSendTime, 0u);
      observation_complete_->Set();

      return SEND_PACKET;
    }
  } observer;

  Call::Config call_config(observer.SendTransport());
  scoped_ptr<Call> call(Call::Create(call_config));

  VideoSendStream::Config send_config = GetSendTestConfig(call.get(), 1);
  send_config.rtp.extensions.push_back(
      RtpExtension(RtpExtension::kAbsSendTime, kAbsSendTimeExtensionId));

  RunSendTest(call.get(), send_config, &observer);
}

TEST_F(VideoSendStreamTest, SupportsTransmissionTimeOffset) {
  static const uint8_t kTOffsetExtensionId = 13;
  class DelayedEncoder : public test::FakeEncoder {
   public:
    explicit DelayedEncoder(Clock* clock) : test::FakeEncoder(clock) {}
    virtual int32_t Encode(const I420VideoFrame& input_image,
                           const CodecSpecificInfo* codec_specific_info,
                           const std::vector<VideoFrameType>* frame_types)
        OVERRIDE {
      // A delay needs to be introduced to assure that we get a timestamp
      // offset.
      SleepMs(5);
      return FakeEncoder::Encode(input_image, codec_specific_info, frame_types);
    }
  } encoder(Clock::GetRealTimeClock());

  class TransmissionTimeOffsetObserver : public test::RtpRtcpObserver {
   public:
    TransmissionTimeOffsetObserver() : RtpRtcpObserver(30 * 1000) {
      EXPECT_TRUE(parser_->RegisterRtpHeaderExtension(
          kRtpExtensionTransmissionTimeOffset, kTOffsetExtensionId));
    }

    virtual Action OnSendRtp(const uint8_t* packet, size_t length) OVERRIDE {
      RTPHeader header;
      EXPECT_TRUE(parser_->Parse(packet, static_cast<int>(length), &header));

      EXPECT_TRUE(header.extension.hasTransmissionTimeOffset);
      EXPECT_FALSE(header.extension.hasAbsoluteSendTime);
      EXPECT_GT(header.extension.transmissionTimeOffset, 0);
      EXPECT_EQ(header.extension.absoluteSendTime, 0u);
      observation_complete_->Set();

      return SEND_PACKET;
    }
  } observer;

  Call::Config call_config(observer.SendTransport());
  scoped_ptr<Call> call(Call::Create(call_config));

  VideoSendStream::Config send_config = GetSendTestConfig(call.get(), 1);
  send_config.encoder_settings.encoder = &encoder;
  send_config.rtp.extensions.push_back(
      RtpExtension(RtpExtension::kTOffset, kTOffsetExtensionId));

  RunSendTest(call.get(), send_config, &observer);
}

class FakeReceiveStatistics : public NullReceiveStatistics {
 public:
  FakeReceiveStatistics(uint32_t send_ssrc,
                        uint32_t last_sequence_number,
                        uint32_t cumulative_lost,
                        uint8_t fraction_lost)
      : lossy_stats_(new LossyStatistician(last_sequence_number,
                                           cumulative_lost,
                                           fraction_lost)) {
    stats_map_[send_ssrc] = lossy_stats_.get();
  }

  virtual StatisticianMap GetActiveStatisticians() const OVERRIDE {
    return stats_map_;
  }

  virtual StreamStatistician* GetStatistician(uint32_t ssrc) const OVERRIDE {
    return lossy_stats_.get();
  }

 private:
  class LossyStatistician : public StreamStatistician {
   public:
    LossyStatistician(uint32_t extended_max_sequence_number,
                      uint32_t cumulative_lost,
                      uint8_t fraction_lost) {
      stats_.fraction_lost = fraction_lost;
      stats_.cumulative_lost = cumulative_lost;
      stats_.extended_max_sequence_number = extended_max_sequence_number;
    }
    virtual bool GetStatistics(RtcpStatistics* statistics,
                               bool reset) OVERRIDE {
      *statistics = stats_;
      return true;
    }
    virtual void GetDataCounters(uint32_t* bytes_received,
                                 uint32_t* packets_received) const OVERRIDE {
      *bytes_received = 0;
      *packets_received = 0;
    }
    virtual uint32_t BitrateReceived() const OVERRIDE { return 0; }
    virtual void ResetStatistics() OVERRIDE {}
    virtual bool IsRetransmitOfOldPacket(const RTPHeader& header,
                                         int min_rtt) const OVERRIDE {
      return false;
    }

    virtual bool IsPacketInOrder(uint16_t sequence_number) const OVERRIDE {
      return true;
    }

    RtcpStatistics stats_;
  };

  scoped_ptr<LossyStatistician> lossy_stats_;
  StatisticianMap stats_map_;
};

TEST_F(VideoSendStreamTest, SwapsI420VideoFrames) {
  static const size_t kWidth = 320;
  static const size_t kHeight = 240;

  test::NullTransport transport;
  Call::Config call_config(&transport);
  scoped_ptr<Call> call(Call::Create(call_config));

  VideoSendStream::Config send_config = GetSendTestConfig(call.get(), 1);
  VideoSendStream* video_send_stream = call->CreateVideoSendStream(send_config);
  video_send_stream->StartSending();

  I420VideoFrame frame;
  frame.CreateEmptyFrame(
      kWidth, kHeight, kWidth, (kWidth + 1) / 2, (kWidth + 1) / 2);
  uint8_t* old_y_buffer = frame.buffer(kYPlane);

  video_send_stream->Input()->SwapFrame(&frame);

  EXPECT_NE(frame.buffer(kYPlane), old_y_buffer);

  call->DestroyVideoSendStream(video_send_stream);
}

TEST_F(VideoSendStreamTest, SupportsFec) {
  static const int kRedPayloadType = 118;
  static const int kUlpfecPayloadType = 119;
  class FecObserver : public test::RtpRtcpObserver {
   public:
    FecObserver()
        : RtpRtcpObserver(30 * 1000),
          transport_adapter_(SendTransport()),
          send_count_(0),
          received_media_(false),
          received_fec_(false) {
      transport_adapter_.Enable();
    }

    virtual Action OnSendRtp(const uint8_t* packet, size_t length) OVERRIDE {
      RTPHeader header;
      EXPECT_TRUE(parser_->Parse(packet, static_cast<int>(length), &header));

      // Send lossy receive reports to trigger FEC enabling.
      if (send_count_++ % 2 != 0) {
        // Receive statistics reporting having lost 50% of the packets.
        FakeReceiveStatistics lossy_receive_stats(
            kSendSsrc, header.sequenceNumber, send_count_ / 2, 127);
        RTCPSender rtcp_sender(
            0, false, Clock::GetRealTimeClock(), &lossy_receive_stats);
        EXPECT_EQ(0, rtcp_sender.RegisterSendTransport(&transport_adapter_));

        rtcp_sender.SetRTCPStatus(kRtcpNonCompound);
        rtcp_sender.SetRemoteSSRC(kSendSsrc);

        RTCPSender::FeedbackState feedback_state;

        EXPECT_EQ(0, rtcp_sender.SendRTCP(feedback_state, kRtcpRr));
      }

      EXPECT_EQ(kRedPayloadType, header.payloadType);

      uint8_t encapsulated_payload_type = packet[header.headerLength];

      if (encapsulated_payload_type == kUlpfecPayloadType) {
        received_fec_ = true;
      } else {
        received_media_ = true;
      }

      if (received_media_ && received_fec_)
        observation_complete_->Set();

      return SEND_PACKET;
    }

   private:
    internal::TransportAdapter transport_adapter_;
    int send_count_;
    bool received_media_;
    bool received_fec_;
  } observer;

  Call::Config call_config(observer.SendTransport());
  scoped_ptr<Call> call(Call::Create(call_config));

  observer.SetReceivers(call->Receiver(), NULL);

  VideoSendStream::Config send_config = GetSendTestConfig(call.get(), 1);
  send_config.rtp.fec.red_payload_type = kRedPayloadType;
  send_config.rtp.fec.ulpfec_payload_type = kUlpfecPayloadType;

  RunSendTest(call.get(), send_config, &observer);
}

void VideoSendStreamTest::TestNackRetransmission(
    uint32_t retransmit_ssrc,
    uint8_t retransmit_payload_type,
    bool enable_pacing) {
  class NackObserver : public test::RtpRtcpObserver {
   public:
    explicit NackObserver(uint32_t retransmit_ssrc,
                          uint8_t retransmit_payload_type)
        : RtpRtcpObserver(30 * 1000),
          transport_adapter_(SendTransport()),
          send_count_(0),
          retransmit_ssrc_(retransmit_ssrc),
          retransmit_payload_type_(retransmit_payload_type),
          nacked_sequence_number_(-1) {
      transport_adapter_.Enable();
    }

    virtual Action OnSendRtp(const uint8_t* packet, size_t length) OVERRIDE {
      RTPHeader header;
      EXPECT_TRUE(parser_->Parse(packet, static_cast<int>(length), &header));

      // Nack second packet after receiving the third one.
      if (++send_count_ == 3) {
        uint16_t nack_sequence_number = header.sequenceNumber - 1;
        nacked_sequence_number_ = nack_sequence_number;
        NullReceiveStatistics null_stats;
        RTCPSender rtcp_sender(
            0, false, Clock::GetRealTimeClock(), &null_stats);
        EXPECT_EQ(0, rtcp_sender.RegisterSendTransport(&transport_adapter_));

        rtcp_sender.SetRTCPStatus(kRtcpNonCompound);
        rtcp_sender.SetRemoteSSRC(kSendSsrc);

        RTCPSender::FeedbackState feedback_state;

        EXPECT_EQ(0,
                  rtcp_sender.SendRTCP(
                      feedback_state, kRtcpNack, 1, &nack_sequence_number));
      }

      uint16_t sequence_number = header.sequenceNumber;

      if (header.ssrc == retransmit_ssrc_ && retransmit_ssrc_ != kSendSsrc) {
        // Not kSendSsrc, assume correct RTX packet. Extract sequence number.
        const uint8_t* rtx_header = packet + header.headerLength;
        sequence_number = (rtx_header[0] << 8) + rtx_header[1];
      }

      if (sequence_number == nacked_sequence_number_) {
        EXPECT_EQ(retransmit_ssrc_, header.ssrc);
        EXPECT_EQ(retransmit_payload_type_, header.payloadType);
        observation_complete_->Set();
      }

      return SEND_PACKET;
    }

   private:
    internal::TransportAdapter transport_adapter_;
    int send_count_;
    uint32_t retransmit_ssrc_;
    uint8_t retransmit_payload_type_;
    int nacked_sequence_number_;
  } observer(retransmit_ssrc, retransmit_payload_type);

  Call::Config call_config(observer.SendTransport());
  scoped_ptr<Call> call(Call::Create(call_config));
  observer.SetReceivers(call->Receiver(), NULL);

  VideoSendStream::Config send_config = GetSendTestConfig(call.get(), 1);
  send_config.rtp.nack.rtp_history_ms = 1000;
  send_config.rtp.rtx.payload_type = retransmit_payload_type;
  send_config.pacing = enable_pacing;
  if (retransmit_ssrc != kSendSsrc)
    send_config.rtp.rtx.ssrcs.push_back(retransmit_ssrc);

  RunSendTest(call.get(), send_config, &observer);
}

TEST_F(VideoSendStreamTest, RetransmitsNack) {
  // Normal NACKs should use the send SSRC.
  TestNackRetransmission(kSendSsrc, kFakeSendPayloadType, false);
}

TEST_F(VideoSendStreamTest, RetransmitsNackOverRtx) {
  // NACKs over RTX should use a separate SSRC.
  TestNackRetransmission(kSendRtxSsrc, kSendRtxPayloadType, false);
}

TEST_F(VideoSendStreamTest, RetransmitsNackOverRtxWithPacing) {
  // NACKs over RTX should use a separate SSRC.
  TestNackRetransmission(kSendRtxSsrc, kSendRtxPayloadType, true);
}

void VideoSendStreamTest::TestPacketFragmentationSize(VideoFormat format,
                                                      bool with_fec) {
  static const int kRedPayloadType = 118;
  static const int kUlpfecPayloadType = 119;
  // Observer that verifies that the expected number of packets and bytes
  // arrive for each frame size, from start_size to stop_size.
  class FrameFragmentationObserver : public test::RtpRtcpObserver,
                                     public EncodedFrameObserver {
   public:
    FrameFragmentationObserver(uint32_t max_packet_size,
                               uint32_t start_size,
                               uint32_t stop_size,
                               test::ConfigurableFrameSizeEncoder* encoder,
                               bool test_generic_packetization,
                               bool use_fec)
        : RtpRtcpObserver(120 * 1000),  // Timeout after two minutes.
          transport_adapter_(SendTransport()),
          encoder_(encoder),
          max_packet_size_(max_packet_size),
          stop_size_(stop_size),
          test_generic_packetization_(test_generic_packetization),
          use_fec_(use_fec),
          packet_count_(0),
          accumulated_size_(0),
          accumulated_payload_(0),
          fec_packet_received_(false),
          current_size_rtp_(start_size),
          current_size_frame_(start_size) {
      // Fragmentation required, this test doesn't make sense without it.
      assert(stop_size > max_packet_size);
      transport_adapter_.Enable();
    }

    virtual Action OnSendRtp(const uint8_t* packet, size_t size) OVERRIDE {
      uint32_t length = static_cast<int>(size);
      RTPHeader header;
      EXPECT_TRUE(parser_->Parse(packet, length, &header));

      EXPECT_LE(length, max_packet_size_);

      if (use_fec_) {
        uint8_t payload_type = packet[header.headerLength];
        bool is_fec = header.payloadType == kRedPayloadType &&
                      payload_type == kUlpfecPayloadType;
        if (is_fec) {
          fec_packet_received_ = true;
          return SEND_PACKET;
        }
      }

      accumulated_size_ += length;

      if (use_fec_)
        TriggerLossReport(header);

      if (test_generic_packetization_) {
        uint32_t overhead = header.headerLength + header.paddingLength +
                          (1 /* Generic header */);
        if (use_fec_)
          overhead += 1;  // RED for FEC header.
        accumulated_payload_ += length - overhead;
      }

      // Marker bit set indicates last packet of a frame.
      if (header.markerBit) {
        if (use_fec_ && accumulated_payload_ == current_size_rtp_ - 1) {
          // With FEC enabled, frame size is incremented asynchronously, so
          // "old" frames one byte too small may arrive. Accept, but don't
          // increase expected frame size.
          accumulated_size_ = 0;
          accumulated_payload_ = 0;
          return SEND_PACKET;
        }

        EXPECT_GE(accumulated_size_, current_size_rtp_);
        if (test_generic_packetization_) {
          EXPECT_EQ(current_size_rtp_, accumulated_payload_);
        }

        // Last packet of frame; reset counters.
        accumulated_size_ = 0;
        accumulated_payload_ = 0;
        if (current_size_rtp_ == stop_size_) {
          // Done! (Don't increase size again, might arrive more @ stop_size).
          observation_complete_->Set();
        } else {
          // Increase next expected frame size. If testing with FEC, make sure
          // a FEC packet has been received for this frame size before
          // proceeding, to make sure that redundancy packets don't exceed
          // size limit.
          if (!use_fec_) {
            ++current_size_rtp_;
          } else if (fec_packet_received_) {
            fec_packet_received_ = false;
            ++current_size_rtp_;
            ++current_size_frame_;
          }
        }
      }

      return SEND_PACKET;
    }

    void TriggerLossReport(const RTPHeader& header) {
      // Send lossy receive reports to trigger FEC enabling.
      if (packet_count_++ % 2 != 0) {
        // Receive statistics reporting having lost 50% of the packets.
        FakeReceiveStatistics lossy_receive_stats(
            kSendSsrc, header.sequenceNumber, packet_count_ / 2, 127);
        RTCPSender rtcp_sender(
            0, false, Clock::GetRealTimeClock(), &lossy_receive_stats);
        EXPECT_EQ(0, rtcp_sender.RegisterSendTransport(&transport_adapter_));

        rtcp_sender.SetRTCPStatus(kRtcpNonCompound);
        rtcp_sender.SetRemoteSSRC(kSendSsrc);

        RTCPSender::FeedbackState feedback_state;

        EXPECT_EQ(0, rtcp_sender.SendRTCP(feedback_state, kRtcpRr));
      }
    }

    virtual void EncodedFrameCallback(const EncodedFrame& encoded_frame) {
      // Increase frame size for next encoded frame, in the context of the
      // encoder thread.
      if (!use_fec_ &&
          current_size_frame_.Value() < static_cast<int32_t>(stop_size_)) {
        ++current_size_frame_;
      }
      encoder_->SetFrameSize(current_size_frame_.Value());
    }

   private:
    internal::TransportAdapter transport_adapter_;
    test::ConfigurableFrameSizeEncoder* const encoder_;

    const uint32_t max_packet_size_;
    const uint32_t stop_size_;
    const bool test_generic_packetization_;
    const bool use_fec_;

    uint32_t packet_count_;
    uint32_t accumulated_size_;
    uint32_t accumulated_payload_;
    bool fec_packet_received_;

    uint32_t current_size_rtp_;
    Atomic32 current_size_frame_;
  };

  // Use a fake encoder to output a frame of every size in the range [90, 290],
  // for each size making sure that the exact number of payload bytes received
  // is correct and that packets are fragmented to respect max packet size.
  static const uint32_t kMaxPacketSize = 128;
  static const uint32_t start = 90;
  static const uint32_t stop = 290;

  // Don't auto increment if FEC is used; continue sending frame size until
  // a FEC packet has been received.
  test::ConfigurableFrameSizeEncoder encoder(stop);
  encoder.SetFrameSize(start);

  FrameFragmentationObserver observer(
      kMaxPacketSize, start, stop, &encoder, format == kGeneric, with_fec);
  Call::Config call_config(observer.SendTransport());
  scoped_ptr<Call> call(Call::Create(call_config));

  observer.SetReceivers(call->Receiver(), NULL);

  VideoSendStream::Config send_config = GetSendTestConfig(call.get(), 1);
  if (with_fec) {
    send_config.rtp.fec.red_payload_type = kRedPayloadType;
    send_config.rtp.fec.ulpfec_payload_type = kUlpfecPayloadType;
  }

  if (format == kVP8)
    send_config.encoder_settings.payload_name = "VP8";

  send_config.pacing = false;
  send_config.encoder_settings.encoder = &encoder;
  send_config.rtp.max_packet_size = kMaxPacketSize;
  send_config.post_encode_callback = &observer;

  // Add an extension header, to make the RTP header larger than the base
  // length of 12 bytes.
  static const uint8_t kAbsSendTimeExtensionId = 13;
  send_config.rtp.extensions.push_back(
      RtpExtension(RtpExtension::kAbsSendTime, kAbsSendTimeExtensionId));

  RunSendTest(call.get(), send_config, &observer);
}

// TODO(sprang): Is there any way of speeding up these tests?
TEST_F(VideoSendStreamTest, FragmentsGenericAccordingToMaxPacketSize) {
  TestPacketFragmentationSize(kGeneric, false);
}

TEST_F(VideoSendStreamTest, FragmentsGenericAccordingToMaxPacketSizeWithFec) {
  TestPacketFragmentationSize(kGeneric, true);
}

TEST_F(VideoSendStreamTest, FragmentsVp8AccordingToMaxPacketSize) {
  TestPacketFragmentationSize(kVP8, false);
}

TEST_F(VideoSendStreamTest, FragmentsVp8AccordingToMaxPacketSizeWithFec) {
  TestPacketFragmentationSize(kVP8, true);
}

// The test will go through a number of phases.
// 1. Start sending packets.
// 2. As soon as the RTP stream has been detected, signal a low REMB value to
//    suspend the stream.
// 3. Wait until |kSuspendTimeFrames| have been captured without seeing any RTP
//    packets.
// 4. Signal a high REMB and then wait for the RTP stream to start again.
//    When the stream is detected again, and the stats show that the stream
//    is no longer suspended, the test ends.
TEST_F(VideoSendStreamTest, SuspendBelowMinBitrate) {
  static const int kSuspendTimeFrames = 60;  // Suspend for 2 seconds @ 30 fps.

  class RembObserver : public test::RtpRtcpObserver, public I420FrameCallback {
   public:
    RembObserver(VideoSendStream** send_stream_ptr)
        : RtpRtcpObserver(30 * 1000),  // Timeout after 30 seconds.
          transport_adapter_(&transport_),
          clock_(Clock::GetRealTimeClock()),
          test_state_(kBeforeSuspend),
          rtp_count_(0),
          last_sequence_number_(0),
          suspended_frame_count_(0),
          low_remb_bps_(0),
          high_remb_bps_(0),
          crit_sect_(CriticalSectionWrapper::CreateCriticalSection()),
          send_stream_ptr_(send_stream_ptr) {
      transport_adapter_.Enable();
    }

    void SetReceiver(PacketReceiver* receiver) {
      transport_.SetReceiver(receiver);
    }

    virtual Action OnSendRtcp(const uint8_t* packet, size_t length) OVERRIDE {
      // Receive statistics reporting having lost 0% of the packets.
      // This is needed for the send-side bitrate controller to work properly.
      CriticalSectionScoped lock(crit_sect_.get());
      SendRtcpFeedback(0);  // REMB is only sent if value is > 0.
      return SEND_PACKET;
    }

    virtual Action OnSendRtp(const uint8_t* packet, size_t length) OVERRIDE {
      CriticalSectionScoped lock(crit_sect_.get());
      ++rtp_count_;
      RTPHeader header;
      EXPECT_TRUE(parser_->Parse(packet, static_cast<int>(length), &header));
      last_sequence_number_ = header.sequenceNumber;

      if (test_state_ == kBeforeSuspend) {
        // The stream has started. Try to suspend it.
        SendRtcpFeedback(low_remb_bps_);
        test_state_ = kDuringSuspend;
      } else if (test_state_ == kDuringSuspend) {
        if (header.paddingLength == 0) {
          // Received non-padding packet during suspension period. Reset the
          // counter.
          suspended_frame_count_ = 0;
        }
      } else if (test_state_ == kWaitingForPacket) {
        if (header.paddingLength == 0) {
          // Non-padding packet observed. Test is almost complete. Will just
          // have to wait for the stats to change.
          test_state_ = kWaitingForStats;
        }
      } else if (test_state_ == kWaitingForStats) {
        assert(*send_stream_ptr_);
        VideoSendStream::Stats stats = (*send_stream_ptr_)->GetStats();
        if (stats.suspended == false) {
          // Stats flipped to false. Test is complete.
          observation_complete_->Set();
        }
      }

      return SEND_PACKET;
    }

    // This method implements the I420FrameCallback.
    void FrameCallback(I420VideoFrame* video_frame) OVERRIDE {
      CriticalSectionScoped lock(crit_sect_.get());
      if (test_state_ == kDuringSuspend &&
          ++suspended_frame_count_ > kSuspendTimeFrames) {
        assert(*send_stream_ptr_);
        VideoSendStream::Stats stats = (*send_stream_ptr_)->GetStats();
        EXPECT_TRUE(stats.suspended);
        SendRtcpFeedback(high_remb_bps_);
        test_state_ = kWaitingForPacket;
      }
    }

    void set_low_remb_bps(int value) { low_remb_bps_ = value; }

    void set_high_remb_bps(int value) { high_remb_bps_ = value; }

    void Stop() { transport_.StopSending(); }

   private:
    enum TestState {
      kBeforeSuspend,
      kDuringSuspend,
      kWaitingForPacket,
      kWaitingForStats
    };

    virtual void SendRtcpFeedback(int remb_value) {
      FakeReceiveStatistics receive_stats(
          kSendSsrc, last_sequence_number_, rtp_count_, 0);
      RTCPSender rtcp_sender(0, false, clock_, &receive_stats);
      EXPECT_EQ(0, rtcp_sender.RegisterSendTransport(&transport_adapter_));

      rtcp_sender.SetRTCPStatus(kRtcpNonCompound);
      rtcp_sender.SetRemoteSSRC(kSendSsrc);
      if (remb_value > 0) {
        rtcp_sender.SetREMBStatus(true);
        rtcp_sender.SetREMBData(remb_value, 0, NULL);
      }
      RTCPSender::FeedbackState feedback_state;
      EXPECT_EQ(0, rtcp_sender.SendRTCP(feedback_state, kRtcpRr));
    }

    internal::TransportAdapter transport_adapter_;
    test::DirectTransport transport_;
    Clock* clock_;
    TestState test_state_;
    int rtp_count_;
    int last_sequence_number_;
    int suspended_frame_count_;
    int low_remb_bps_;
    int high_remb_bps_;
    scoped_ptr<CriticalSectionWrapper> crit_sect_;
    VideoSendStream** send_stream_ptr_;
  } observer(&send_stream_);
  // Note that |send_stream_| is created in RunSendTest(), called below. This
  // is why a pointer to |send_stream_| must be provided here.

  Call::Config call_config(observer.SendTransport());
  scoped_ptr<Call> call(Call::Create(call_config));
  observer.SetReceiver(call->Receiver());

  VideoSendStream::Config send_config = GetSendTestConfig(call.get(), 1);
  send_config.rtp.nack.rtp_history_ms = 1000;
  send_config.pre_encode_callback = &observer;
  send_config.suspend_below_min_bitrate = true;
  int min_bitrate_bps = send_config.encoder_settings.streams[0].min_bitrate_bps;
  observer.set_low_remb_bps(min_bitrate_bps - 10000);
  int threshold_window = std::max(min_bitrate_bps / 10, 10000);
  ASSERT_GT(send_config.encoder_settings.streams[0].max_bitrate_bps,
            min_bitrate_bps + threshold_window + 5000);
  observer.set_high_remb_bps(min_bitrate_bps + threshold_window + 5000);

  RunSendTest(call.get(), send_config, &observer);
  observer.Stop();
}

TEST_F(VideoSendStreamTest, NoPaddingWhenVideoIsMuted) {
  class PacketObserver : public test::RtpRtcpObserver {
   public:
    PacketObserver()
        : RtpRtcpObserver(30 * 1000),  // Timeout after 30 seconds.
          clock_(Clock::GetRealTimeClock()),
          last_packet_time_ms_(-1),
          transport_adapter_(ReceiveTransport()),
          capturer_(NULL),
          crit_sect_(CriticalSectionWrapper::CreateCriticalSection()) {
      transport_adapter_.Enable();
    }

    void SetCapturer(test::FrameGeneratorCapturer* capturer) {
      capturer_ = capturer;
    }

    virtual Action OnSendRtp(const uint8_t* packet, size_t length) OVERRIDE {
      CriticalSectionScoped lock(crit_sect_.get());
      last_packet_time_ms_ = clock_->TimeInMilliseconds();
      capturer_->Stop();
      return SEND_PACKET;
    }

    virtual Action OnSendRtcp(const uint8_t* packet, size_t length) OVERRIDE {
      CriticalSectionScoped lock(crit_sect_.get());
      const int kVideoMutedThresholdMs = 10000;
      if (last_packet_time_ms_ > 0 &&
          clock_->TimeInMilliseconds() - last_packet_time_ms_ >
              kVideoMutedThresholdMs)
        observation_complete_->Set();
      // Receive statistics reporting having lost 50% of the packets.
      FakeReceiveStatistics receive_stats(kSendSsrcs[0], 1, 1, 0);
      RTCPSender rtcp_sender(
          0, false, Clock::GetRealTimeClock(), &receive_stats);
      EXPECT_EQ(0, rtcp_sender.RegisterSendTransport(&transport_adapter_));

      rtcp_sender.SetRTCPStatus(kRtcpNonCompound);
      rtcp_sender.SetRemoteSSRC(kSendSsrcs[0]);

      RTCPSender::FeedbackState feedback_state;

      EXPECT_EQ(0, rtcp_sender.SendRTCP(feedback_state, kRtcpRr));
      return SEND_PACKET;
    }

   private:
    Clock* clock_;
    int64_t last_packet_time_ms_;
    internal::TransportAdapter transport_adapter_;
    test::FrameGeneratorCapturer* capturer_;
    scoped_ptr<CriticalSectionWrapper> crit_sect_;
  } observer;

  Call::Config call_config(observer.SendTransport());
  scoped_ptr<Call> call(Call::Create(call_config));
  observer.SetReceivers(call->Receiver(), call->Receiver());

  VideoSendStream::Config send_config = GetSendTestConfig(call.get(), 3);

  send_stream_ = call->CreateVideoSendStream(send_config);
  scoped_ptr<test::FrameGeneratorCapturer> frame_generator_capturer(
      test::FrameGeneratorCapturer::Create(
          send_stream_->Input(), 320, 240, 30, Clock::GetRealTimeClock()));
  observer.SetCapturer(frame_generator_capturer.get());
  send_stream_->StartSending();
  frame_generator_capturer->Start();

  EXPECT_EQ(kEventSignaled, observer.Wait())
      << "Timed out while waiting for RTP packets to stop being sent.";

  observer.StopSending();
  frame_generator_capturer->Stop();
  send_stream_->StopSending();
  call->DestroyVideoSendStream(send_stream_);
}

TEST_F(VideoSendStreamTest, ProducesStats) {
  static const std::string kCName =
      "PjQatC14dGfbVwGPUOA9IH7RlsFDbWl4AhXEiDsBizo=";
  static const uint32_t kTimeoutMs = 30 * 1000;
  class StatsObserver : public test::RtpRtcpObserver {
   public:
    StatsObserver()
        : RtpRtcpObserver(kTimeoutMs),
          stream_(NULL),
          event_(EventWrapper::Create()) {}

    virtual Action OnSendRtcp(const uint8_t* packet, size_t length) OVERRIDE {
      event_->Set();

      return SEND_PACKET;
    }

    bool WaitForFilledStats() {
      Clock* clock = Clock::GetRealTimeClock();
      int64_t now = clock->TimeInMilliseconds();
      int64_t stop_time = now + kTimeoutMs;
      while (now < stop_time) {
        int64_t time_left = stop_time - now;
        if (time_left > 0 && event_->Wait(time_left) == kEventSignaled &&
            CheckStats()) {
          return true;
        }
        now = clock->TimeInMilliseconds();
      }
      return false;
    }

    bool CheckStats() {
      VideoSendStream::Stats stats = stream_->GetStats();
      // Check that all applicable data sources have been used.
      if (stats.input_frame_rate > 0 && stats.encode_frame_rate > 0 &&
          stats.avg_delay_ms > 0 && stats.c_name == kCName &&
          !stats.substreams.empty()) {
        uint32_t ssrc = stats.substreams.begin()->first;
        EXPECT_NE(
            config_.rtp.ssrcs.end(),
            std::find(
                config_.rtp.ssrcs.begin(), config_.rtp.ssrcs.end(), ssrc));
        // Check for data populated by various sources. RTCP excluded as this
        // data is received from remote side. Tested in call tests instead.
        const StreamStats& entry = stats.substreams[ssrc];
        if (entry.key_frames > 0u && entry.bitrate_bps > 0 &&
            entry.rtp_stats.packets > 0u) {
          return true;
        }
      }
      return false;
    }

    void SetConfig(const VideoSendStream::Config& config) { config_ = config; }

    void SetSendStream(VideoSendStream* stream) { stream_ = stream; }

    VideoSendStream* stream_;
    VideoSendStream::Config config_;
    scoped_ptr<EventWrapper> event_;
  } observer;

  Call::Config call_config(observer.SendTransport());
  scoped_ptr<Call> call(Call::Create(call_config));

  VideoSendStream::Config send_config = GetSendTestConfig(call.get(), 1);
  send_config.rtp.c_name = kCName;
  observer.SetConfig(send_config);

  send_stream_ = call->CreateVideoSendStream(send_config);
  observer.SetSendStream(send_stream_);
  scoped_ptr<test::FrameGeneratorCapturer> frame_generator_capturer(
      test::FrameGeneratorCapturer::Create(
          send_stream_->Input(), 320, 240, 30, Clock::GetRealTimeClock()));
  send_stream_->StartSending();
  frame_generator_capturer->Start();

  EXPECT_TRUE(observer.WaitForFilledStats())
      << "Timed out waiting for filled statistics.";

  observer.StopSending();
  frame_generator_capturer->Stop();
  send_stream_->StopSending();
  call->DestroyVideoSendStream(send_stream_);
}

// This test first observes "high" bitrate use at which point it sends a REMB to
// indicate that it should be lowered significantly. The test then observes that
// the bitrate observed is sinking well below the min-transmit-bitrate threshold
// to verify that the min-transmit bitrate respects incoming REMB.
TEST_F(VideoSendStreamTest, MinTransmitBitrateRespectsRemb) {
  static const int kMinTransmitBitrateBps = 400000;
  static const int kHighBitrateBps = 200000;
  static const int kRembBitrateBps = 80000;
  static const int kRembRespectedBitrateBps = 100000;
  class BitrateObserver: public test::RtpRtcpObserver, public PacketReceiver {
   public:
    BitrateObserver()
        : RtpRtcpObserver(30 * 1000),
          feedback_transport_(ReceiveTransport()),
          send_stream_(NULL),
          bitrate_capped_(false) {
      RtpRtcp::Configuration config;
      feedback_transport_.Enable();
      config.outgoing_transport = &feedback_transport_;
      rtp_rtcp_.reset(RtpRtcp::CreateRtpRtcp(config));
      rtp_rtcp_->SetREMBStatus(true);
      rtp_rtcp_->SetRTCPStatus(kRtcpNonCompound);
    }

    void SetSendStream(VideoSendStream* send_stream) {
      send_stream_ = send_stream;
    }

   private:
    virtual bool DeliverPacket(const uint8_t* packet, size_t length) {
      if (RtpHeaderParser::IsRtcp(packet, static_cast<int>(length)))
        return true;

      RTPHeader header;
      if (!parser_->Parse(packet, static_cast<int>(length), &header))
        return true;
      assert(send_stream_ != NULL);
      VideoSendStream::Stats stats = send_stream_->GetStats();
      if (!stats.substreams.empty()) {
        EXPECT_EQ(1u, stats.substreams.size());
        int bitrate_bps = stats.substreams.begin()->second.bitrate_bps;
        test::PrintResult(
            "bitrate_stats_",
            "min_transmit_bitrate_low_remb",
            "bitrate_bps",
            static_cast<size_t>(bitrate_bps),
            "bps",
            false);
        if (bitrate_bps > kHighBitrateBps) {
          rtp_rtcp_->SetREMBData(kRembBitrateBps, 1, &header.ssrc);
          rtp_rtcp_->Process();
          bitrate_capped_ = true;
        } else if (bitrate_capped_ &&
                   bitrate_bps < kRembRespectedBitrateBps) {
          observation_complete_->Set();
        }
      }
      return true;
    }

    scoped_ptr<RtpRtcp> rtp_rtcp_;
    internal::TransportAdapter feedback_transport_;
    VideoSendStream* send_stream_;
    bool bitrate_capped_;
  } observer;

  Call::Config call_config(observer.SendTransport());
  scoped_ptr<Call> call(Call::Create(call_config));
  observer.SetReceivers(&observer, call->Receiver());

  VideoSendStream::Config send_config = GetSendTestConfig(call.get(), 1);
  send_config.rtp.min_transmit_bitrate_bps = kMinTransmitBitrateBps;
  send_stream_ = call->CreateVideoSendStream(send_config);
  observer.SetSendStream(send_stream_);

  scoped_ptr<test::FrameGeneratorCapturer> frame_generator_capturer(
      test::FrameGeneratorCapturer::Create(
          send_stream_->Input(), 320, 240, 30, Clock::GetRealTimeClock()));
  send_stream_->StartSending();
  frame_generator_capturer->Start();

  EXPECT_EQ(kEventSignaled, observer.Wait())
      << "Timeout while waiting for low bitrate stats after REMB.";

  observer.StopSending();
  frame_generator_capturer->Stop();
  send_stream_->StopSending();
  call->DestroyVideoSendStream(send_stream_);
}

}  // namespace webrtc


text:
package com.planet_ink.coffee_mud.Abilities.Properties;
import com.planet_ink.coffee_mud.core.interfaces.*;
import com.planet_ink.coffee_mud.core.*;
import com.planet_ink.coffee_mud.core.collections.*;
import com.planet_ink.coffee_mud.Abilities.interfaces.*;
import com.planet_ink.coffee_mud.Areas.interfaces.*;
import com.planet_ink.coffee_mud.Behaviors.interfaces.*;
import com.planet_ink.coffee_mud.CharClasses.interfaces.*;
import com.planet_ink.coffee_mud.Commands.interfaces.*;
import com.planet_ink.coffee_mud.Common.interfaces.*;
import com.planet_ink.coffee_mud.Exits.interfaces.*;
import com.planet_ink.coffee_mud.Items.interfaces.*;
import com.planet_ink.coffee_mud.Libraries.interfaces.*;
import com.planet_ink.coffee_mud.Locales.interfaces.*;
import com.planet_ink.coffee_mud.MOBS.interfaces.*;
import com.planet_ink.coffee_mud.Races.interfaces.*;

import java.util.*;

public class Prop_ReqTattoo extends Property implements TriggeredAffect
{
	@Override
	public String ID()
	{
		return "Prop_ReqTattoo";
	}

	@Override
	public String name()
	{
		return "Tattoo Limitations";
	}

	@Override
	protected int canAffectCode()
	{
		return Ability.CAN_ROOMS|Ability.CAN_AREAS|Ability.CAN_EXITS|Ability.CAN_ITEMS;
	}

	private String themsg="";

	@Override
	public long flags()
	{
		return Ability.FLAG_ZAPPER;
	}

	@Override
	public String accountForYourself()
	{
		return "Ownership restricted as follows: "+CMLib.masking().maskDesc(text());
	}

	@Override
	public int triggerMask()
	{
		return TriggeredAffect.TRIGGER_ENTER;
	}

	@Override
	public String text()
	{
		return themsg+";"+super.text();
	}

	@Override
	public void setMiscText(final String newText)
	{
		themsg="";
		final int x=newText.indexOf(';');
		if(x<0)
			super.setMiscText(newText);
		else
		if(newText.substring(0,x).indexOf('+')>=0)
			super.setMiscText(newText);
		else
		if(newText.substring(0,x).indexOf('-')>=0)
			super.setMiscText(newText);
		else
		{
			themsg=newText.substring(0,x).trim();
			super.setMiscText(newText.substring(x+1));
		}
	}

	public Vector<String> getMask(final boolean[] flags)
	{
		final Vector<String> V=CMParms.parse(miscText.toUpperCase());
		String s=null;
		for(int v=V.size()-1;v>=1;v--)
		{
			s=V.elementAt(v);
			if(s.startsWith("NOFOL"))
			{
				flags[0]=true;
				V.removeElementAt(v);
			}
			else
			if(s.startsWith("NOSNEAK"))
			{
				flags[1]=true;
				V.removeElementAt(v);
			}
			else
			if("+-".indexOf(s.charAt(0))<0)
			{
				V.removeElementAt(v);
				V.setElementAt((V.elementAt(v-1))+" "+s,v-1);
			}
		}
		return V;
	}

	public boolean passesMuster(final Vector<String> mask, final boolean[] flags, final MOB mob)
	{
		if(mob==null)
			return false;
		if(CMLib.flags().isATrackingMonster(mob))
			return true;
		if(CMLib.flags().isSneaking(mob)&&(flags[1]))
			return true;
		int allFlag=0;
		String s=null;
		for(int v=0;v<mask.size();v++)
		{
			s=mask.elementAt(v);
			if(s.equals("+ALL"))
				allFlag=1;
			else
			if(s.equals("+NONE"))
				allFlag=0;
			else
			if(s.equals("-ALL"))
				allFlag=-1;
			else
			if(s.startsWith("+")||s.startsWith("-"))
			{
				final char c=s.charAt(0);
				final String tattooName;
				if((c=='+')||(c=='-'))
					tattooName = s.substring(1);
				else
					tattooName = s;
				final boolean found;
				if(tattooName.toLowerCase().startsWith("account ")
				&&(mob.playerStats()!=null)
				&&(mob.playerStats().getAccount()!=null))
					found=mob.playerStats().getAccount().findTattoo(tattooName.substring(8).trim())!=null;
				else
					found=mob.findTattoo(tattooName)!=null;
				switch(allFlag)
				{
				case 0: // +NONE -- HAS/LACKS ALL
					if(c=='-')
					{
						if(found)
							return false;
					}
					else
					if(!found)
						return false;
					break;
				case 1: // +ALL -- LACKS ANY
					if(c!='+') // ----------------
					{
						if(!found)
							return true;
					}
					else
					if(found)
						return true;
					break;
				case -1: // -ALL -- HAS ANY
					if(c!='-') // ++++++++++++++++++++
					{
						if(found)
							return true;
					}
					else
					if(found)
						return false;
					break;
				}
			}
		}
		if(allFlag<0) return false; // if not returned, does not have any of them
		if(allFlag==0) return true; // none were missing, so its all good.
		if(allFlag>0) return true; // all were missing, so its all good.
		return true;
	}

	@Override
	public boolean okMessage(final Environmental myHost, final CMMsg msg)
	{
		if((affected!=null)
		&&(msg.target()!=null)
		&&(!CMLib.flags().isFalling(msg.source()))
		&&((msg.amITarget(affected))||(msg.tool()==affected)||(affected instanceof Area)))
		{
			if(((msg.target() instanceof Room)&&(msg.targetMinor()==CMMsg.TYP_ENTER))
			||((msg.target() instanceof Item)&&((msg.targetMinor()==CMMsg.TYP_GET)||(msg.targetMinor()==CMMsg.TYP_SIT))))
			{
				final boolean[] flags=new boolean[2];
				final Vector<String> V=getMask(flags);
				final HashSet<MOB> H=new HashSet<MOB>();
				if(flags[0])
					H.add(msg.source());
				else
				{
					msg.source().getGroupMembers(H);
					final HashSet<MOB> H2=new XHashSet<MOB>(H);
					for(final Iterator<MOB> e=H2.iterator();e.hasNext();)
						e.next().getRideBuddies(H);
				}
				for(final Iterator<MOB> e=H.iterator();e.hasNext();)
				{
					final MOB E=e.next();
					if(passesMuster(V,flags,E))
						return super.okMessage(myHost,msg);
				}
				if(msg.target() instanceof Room)
					msg.source().tell(themsg.length()==0?L("You have not been granted authorization to go that way."):themsg);
				else
				if(msg.source().location()!=null)
					msg.source().location().show(msg.source(),null,affected,CMMsg.MSG_OK_ACTION,themsg.length()==0?L("<O-NAME> flashes and flies out of <S-HIS-HER> hands!"):themsg);
				return false;
			}
		}
		return super.okMessage(myHost,msg);
	}
}

redpajama_set_name: RedPajamaGithub


text:
Manage links between client and servers to allow client to wait until linked servers are ready.
Very useful for installations involving multiple servers that should start in a particular sequence.
Linked [Docker](http://www.docker.com) containers is a very typical use case for this.

- [Installation](#installation)
- [Usage](#usage)
- [Server link status](#server-link-status)
- [Server link path](#server-link-path)
- [Server link retry options](#server-retry-options)
- [Link to external servers](#external-server-links)
- [Server link errors]($server-link-errors)
- [API reference](#api-reference)

## Installation ##

```
$ npm install server-link
```

## Usage ##

For internal servers, simply setup link support on server that client depends on:

```javascript
// == Server application ==
var express = require('express');
var app = express();
...
// Setup link support
require('server-link')(app);

// Perform normal server init and startup
app.route(...), app.use(...) etc
app.listen(....)
```

Now client can wait until linked server is ready:

```javascript
// == Client application ==
require('server-link').wait('http://localhost:3000').then(function() {
  // Linked server is ready
})
.catch(function(err) {
  // Connection with linked server failed
});
```
Provide a custom linker function to link with external servers you do not control. Server-link will handle all retries and timeouts.
```javascript
// == Client application ==
require('server-link').wait('http://localhost:3000', function(host) {
  // Handle your own server connection
  // The linker function and return values are explained below
  return my_server_connection(host);
}).then(function() {
  // Linked server is ready
})
.catch(function(err) {
  // Connection with linked server failed
});
```
Client can wait for multiple servers. The returned promise isn't resolved until all linked servers are ready:

```javascript
// == Client application ==
require('server-link').wait([
  'http://www.someserver.com:3000',
  'http://www.anotherserver.com:4000'
])
.then(function() {
  // All linked servers are ready
})
.catch(function(err) {
  // Connection with one or more linked servers failed
});
```
## Server link status ##
By default, server is assumed to be ready as soon as it starts listening on a socket and routing incoming requests. This behavior can be changed by providing a link status during setup as follows:

```javascript
// == Server application ==
var express = require('express');
var app = express();
var link = require('server-link')(app, 'starting');
```
Now the server won't report itself as ready until the link status is manually changed from 'starting' to 'online' based on your server specific conditions:
```javascript
// == Server application ==
link.status = 'online';
```
Server-link supports the following link status values:
- `'offline'`: The linked server is not responding to link requests
- `'starting'`: The linked server is starting up but not yet ready
- `'online'`: The linked server is ready for incoming requests
- `'error'`: The linked server is not ready due to an internal error
- `'invalid'`: The linked server sends invalid response to link requests

Assigning any other value to `link.status` will result in an error exception. The client will wait until the server reports status 'online'. As long as status 'offline' or 'starting' is reported, the client will continue to poll the server periodically until max number of retries is reached, based on the specified retry options (see below). When status 'error' or 'invalid' is reported, the client will abort the wait immediately and report a link failure.

The client can poll the current link status at any time:
```javascript
// == Client application ==
require('server-link').get('http://someserver.com:300').then(function(status) {
  console.log('link status=' + status);
});
```
## Server link path ##
By default, link status requests are routed through path `'/serverlink'` on the server. A custom path can be used as long as both the client and server are setup with the same path as follows:
```javascript
// == Server application ==
require('server-link')(app, '', '/custom/link/path');
```
```javascript
// == Client application ==
require('server-link').wait('http://someserver.com:3000', '/custom/link/path');
```
Please note that server URL should not contain any path or trailing '/' and custom path should start with '/'.

## Server link retry options ##
Server-link uses NPM package [retry](https://www.npmjs.com/package/retry) to perform retries during waits by the client until the linked server is ready. Retry options can be specified in the wait call and are passed on directly to this package:
```javascript
// == Client application ==
require('server-link').wait('http://someserver.com:3000', {
  retries: 2,       // Max nbr of times to retry (default 10)
  factor: 1,        // Exponential factor (default 2)
  minTimeout: 500,  // Time to wait before first retry (default 1000ms)
  maxTimeout: 500,  // Max time to wait between retries (default infinity)
  randomize: true   // Randomize wait time with factor between 1-2 (default false)
);
```
Please see the [retry](https://www.npmjs.com/package/retry) package for option details.

## Link to external servers ##
If you don't own the server that you're linking to, you're most likely not able to install link support on it as described above. Instead, a custom linker function can be provided in the wait call to handle your own server connection and translate it to a status value that server-link will understand and process accordingly, just like links with internal servers:
```javascript
// == Client application ==
require('server-link').wait([
  'http://www.internal.com:3000',
  'http://www.external.com:4000'
], function(host, index) {
    // Return nothing for internal server (index 0) to have
    // server-link handle the default connection instead
    if (index == 1) {
      // Perform custom connection and return a server-link status
      return connect_my_db(host).then(function(ready) {
        return ready ? 'online' : 'starting';
      })
      .catch(function() {
        return 'error';
      });
    }
})
.then(function() {
  // All linked servers are ready
})
.catch(function(err) {
  // Connection with one or more linked servers failed
});
```
The linker function is called for each host specified in the list. If the function returns nothing, server-link assumes it is an internal server with link support enabled and it will handle the connection instead. If the function returns a promise or a link status, server-link will succeed, fail or retry based on the status just as with any internal servers.

## Server link errors ##
Attempts by the client to wait for a linked server could result in the returned promise to be rejected with various errors. In addition to the typical network related errors, server-link my also report one of the following error instances:
- err.code = 'LINKNOTREADY' - Max wait time/retries reached before server reported status 'online'
err.number = Number of times client tried to poll the server before failure

- err.code = 'LINKINVALID' - Server sent invalid response to link status requests
err.number = Number of times client tried to poll the server before failure

- err.code = 'LINKERROR' - Server reported an internal error
err.number = Number of times client tried to poll the server before failure

- err.code = 'LINKSNOTREADY' - Wait for multiple servers failed for one or more servers
err.links = Array with an entry for each server the client is waiting for. The entry will contain an error instance as specified above if a link with the corresponding server failed.

## API reference ##
```javascript
var serverLink = require('server-link');
```
**serverLink(app, [status], [path])**
Enables link support on the server
`app` specifies the express() application for the server
`status` indicates the initial server status (default 'online')
`path` is path on the server where link status requests are routed to (default '/serverlink')
Returns a serverLink instance for this app. Use property *instance*.status to get & set current server status

**serverLink.wait(hosts, [path], [options], [linker])**
Waits until specified linked server(s) is/are ready.
`hosts` is either a string containing the host URL for a single linked server or an array of strings to wait for multiple servers. A host URL should only contain the base server URL with optional protocol and port but without path or trailing '/'.
`path` is path on the server(s) where link status request are routed to (default '/serverlink')
`options` are server retry options while waiting until ready. See [server link retry options](#server-link-retry-options) above for details.
`linker` is a function (see below) that will be called for each host in the list to handle the connection with external servers
Returns a promise that is resolved when all specified servers are ready or rejected as soon as one ore more server links failed.

**linker(host, index, number)**
Called for each host specified in the call to `serverlink.wait` to handle the server connection
`host` is the URL of the host to connect to
`index` in the index in the list of hosts specified in `serverlink.wait`
`number` is the retry count for this connection
Returns a link status string or a promise that will resolve/reject a link status.
Use `this.hosts`, `this.path` and `this.options` in the linker function to access the arguments passed to the `serverlink.wait` call.

**serverLink.get(host, [path])**
`host` specifies the host URL for the linked server. The URLshould only contain the base server URL with optional protocol and port but without path or trailing '/'.
`path` is path on the server where link status requests are routed to (default '/serverlink')
Returns a promise that is resolved with the current link status for specified server.


text:
<?php

namespace QR\Printers;

use QR\Matrix;

interface PrinterInterface {
    public function printMatrix(Matrix $matrix);
}


text:
package org.apache.sling.installer.factories.configuration.impl;

import java.io.IOException;
import java.util.Dictionary;

import org.apache.sling.installer.api.tasks.InstallTask;
import org.apache.sling.installer.api.tasks.TaskResourceGroup;
import org.osgi.framework.Constants;
import org.osgi.framework.InvalidSyntaxException;
import org.osgi.service.cm.Configuration;
import org.osgi.service.cm.ConfigurationAdmin;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;

/**
 * Base class for configuration-related tasks
 */
abstract class AbstractConfigTask extends InstallTask {

    /** Configuration PID */
    protected final String configPid;

    /** Factory PID or null */
    protected final String factoryPid;

    /** Alias factory pid or null. */
    protected String aliasPid;

    /** Configuration admin. */
    private final ConfigurationAdmin configAdmin;

    private final Logger logger = LoggerFactory.getLogger(this.getClass());

    AbstractConfigTask(final TaskResourceGroup r, final ConfigurationAdmin configAdmin) {
        super(r);
        this.configAdmin = configAdmin;
        this.configPid = (String)getResource().getAttribute(Constants.SERVICE_PID);
        this.factoryPid = (String)getResource().getAttribute(ConfigurationAdmin.SERVICE_FACTORYPID);
        if ( r.getAlias() != null ) {
            this.aliasPid = r.getAlias().substring(this.factoryPid.length() + 1);
        } else {
            this.aliasPid = null;
        }
    }

    protected Logger getLogger() {
        return this.logger;
    }

    /**
     * Get the configuration admin - if available
     */
    protected ConfigurationAdmin getConfigurationAdmin() {
        return this.configAdmin;
    }

    protected String getCompositePid() {
        return (factoryPid == null ? "" : factoryPid + ".") + configPid;
    }

    protected String getCompositeAliasPid() {
        if ( this.aliasPid == null || this.factoryPid == null ) {
            return null;
        }
        final String alias = factoryPid + "." + this.aliasPid;
        final int pos = this.getResource().getEntityId().indexOf(':');
        if ( this.getResource().getEntityId().substring(pos + 1).equals(alias) ) {
            return null;
        }
        return alias;
    }

    protected Dictionary<String, Object> getDictionary() {
        return this.getResource().getDictionary();
    }

    protected Configuration getConfiguration()
    throws IOException, InvalidSyntaxException {
        return ConfigUtil.getConfiguration(this.configAdmin, this.factoryPid, (this.factoryPid != null && this.aliasPid != null ? this.aliasPid : this.configPid));
    }

    protected Configuration createConfiguration(final String location)
    throws IOException, InvalidSyntaxException {
        return ConfigUtil.createConfiguration(this.configAdmin, this.factoryPid, (this.factoryPid != null && this.aliasPid != null ? this.aliasPid : this.configPid), location);
    }
}


text:
<?php

namespace luya\admin\apis;

use luya\admin\ngrest\base\Api;

/**
 * Proxy Machine Controller.
 *
 * File has been created with `crud/create` command on LUYA version 1.0.0-dev.
 */
class ProxyMachineController extends Api
{
    /**
     * @var string The path to the model which is the provider for the rules and fields.
     */
    public $modelClass = 'luya\admin\models\ProxyMachine';
}


text:
"""Data storage helper for ZHA."""
from __future__ import annotations

from collections import OrderedDict
from collections.abc import MutableMapping
import datetime
import time
from typing import cast

import attr

from homeassistant.core import HomeAssistant, callback
from homeassistant.loader import bind_hass

from .typing import ZhaDeviceType

DATA_REGISTRY = "zha_storage"

STORAGE_KEY = "zha.storage"
STORAGE_VERSION = 1
SAVE_DELAY = 10
TOMBSTONE_LIFETIME = datetime.timedelta(days=60).total_seconds()

@attr.s(slots=True, frozen=True)
class ZhaDeviceEntry:
    """Zha Device storage Entry."""

    name: str | None = attr.ib(default=None)
    ieee: str | None = attr.ib(default=None)
    last_seen: float | None = attr.ib(default=None)

class ZhaStorage:
    """Class to hold a registry of zha devices."""

    def __init__(self, hass: HomeAssistant) -> None:
        """Initialize the zha device storage."""
        self.hass: HomeAssistant = hass
        self.devices: MutableMapping[str, ZhaDeviceEntry] = {}
        self._store = hass.helpers.storage.Store(STORAGE_VERSION, STORAGE_KEY)

    @callback
    def async_create_device(self, device: ZhaDeviceType) -> ZhaDeviceEntry:
        """Create a new ZhaDeviceEntry."""
        device_entry: ZhaDeviceEntry = ZhaDeviceEntry(
            name=device.name, ieee=str(device.ieee), last_seen=device.last_seen
        )
        self.devices[device_entry.ieee] = device_entry
        self.async_schedule_save()
        return device_entry

    @callback
    def async_get_or_create_device(self, device: ZhaDeviceType) -> ZhaDeviceEntry:
        """Create a new ZhaDeviceEntry."""
        ieee_str: str = str(device.ieee)
        if ieee_str in self.devices:
            return self.devices[ieee_str]
        return self.async_create_device(device)

    @callback
    def async_create_or_update_device(self, device: ZhaDeviceType) -> ZhaDeviceEntry:
        """Create or update a ZhaDeviceEntry."""
        if str(device.ieee) in self.devices:
            return self.async_update_device(device)
        return self.async_create_device(device)

    @callback
    def async_delete_device(self, device: ZhaDeviceType) -> None:
        """Delete ZhaDeviceEntry."""
        ieee_str: str = str(device.ieee)
        if ieee_str in self.devices:
            del self.devices[ieee_str]
            self.async_schedule_save()

    @callback
    def async_update_device(self, device: ZhaDeviceType) -> ZhaDeviceEntry:
        """Update name of ZhaDeviceEntry."""
        ieee_str: str = str(device.ieee)
        old = self.devices[ieee_str]

        if old is not None and device.last_seen is None:
            return

        changes = {}
        changes["last_seen"] = device.last_seen

        new = self.devices[ieee_str] = attr.evolve(old, **changes)
        self.async_schedule_save()
        return new

    async def async_load(self) -> None:
        """Load the registry of zha device entries."""
        data = await self._store.async_load()

        devices: OrderedDict[str, ZhaDeviceEntry] = OrderedDict()

        if data is not None:
            for device in data["devices"]:
                devices[device["ieee"]] = ZhaDeviceEntry(
                    name=device["name"],
                    ieee=device["ieee"],
                    last_seen=device.get("last_seen"),
                )

        self.devices = devices

    @callback
    def async_schedule_save(self) -> None:
        """Schedule saving the registry of zha devices."""
        self._store.async_delay_save(self._data_to_save, SAVE_DELAY)

    async def async_save(self) -> None:
        """Save the registry of zha devices."""
        await self._store.async_save(self._data_to_save())

    @callback
    def _data_to_save(self) -> dict:
        """Return data for the registry of zha devices to store in a file."""
        data = {}

        data["devices"] = [
            {"name": entry.name, "ieee": entry.ieee, "last_seen": entry.last_seen}
            for entry in self.devices.values()
            if entry.last_seen and (time.time() - entry.last_seen) < TOMBSTONE_LIFETIME
        ]

        return data

@bind_hass
async def async_get_registry(hass: HomeAssistant) -> ZhaStorage:
    """Return zha device storage instance."""
    task = hass.data.get(DATA_REGISTRY)

    if task is None:

        async def _load_reg() -> ZhaStorage:
            registry = ZhaStorage(hass)
            await registry.async_load()
            return registry

        task = hass.data[DATA_REGISTRY] = hass.async_create_task(_load_reg())

    return cast(ZhaStorage, await task)


text:
using KaVE.JetBrains.Annotations;

namespace KaVE.Commons.Model.SSTs.Expressions.Simple
{
    public interface IConstantValueExpression : ISimpleExpression
    {
        [CanBeNull]
        string Value { get; }
    }
}


text:
'use strict';

// Config HTTP Error Handling
angular.module('users')
.directive('fileModel', ['$parse', function ($parse) {
    return {
        restrict: 'A',
        link: function(scope, element, attrs) {
            var model = $parse(attrs.fileModel);
            var modelSetter = model.assign;

            element.bind('change', function(){
                scope.$apply(function(){
                    modelSetter(scope, element[0].files[0]);
                });
            });
        }
    };
}])
.service('fileUpload', ['$http', function ($http) {
    this.uploadFileToUrl = function(file, uploadUrl){
        var fd = new FormData();
        fd.append('file', file);
        console.log("headers");
        $http.post(uploadUrl, fd, {
            transformRequest: angular.identity,
            headers: {'Content-Type': undefined}
        })
        .success(function(){
        })
        .error(function(){
        });
    }
}])
.config(['$httpProvider',
	function($httpProvider) {
		// Set the httpProvider "not authorized" interceptor
		$httpProvider.interceptors.push(['$q', '$location', 'Authentication',
			function($q, $location, Authentication) {
				return {
					responseError: function(rejection) {
						switch (rejection.status) {
							case 401:
								// Deauthenticate the global user
								Authentication.user = null;

								// Redirect to signin page
								$location.path('signin');
								break;
							case 403:
								// Add unauthorized behaviour
								break;
						}

						return $q.reject(rejection);
					}
				};
			}
		]);
	}])
  .filter('millSecondsToDays', function() {
      return function(millseconds) {
        var seconds = Math.floor(millseconds / 1000);
        var days = Math.floor(seconds / 86400);
        var timeString = '';
        if(days > 0) timeString += (days > 1) ? (days + " days ") : (days + " day ")
        else timeString = '< 1 day.';
        return timeString;
      }
    }
);


text:
@import Foundation;

@interface FakeObject : NSObject
@property (nonatomic, copy) NSString *observableProperty;
@property (nonatomic, copy) NSString *observableProperty2;
@property (nonatomic, copy) NSString *observableProperty3;
@property (nonatomic, strong) NSMutableArray *observableArray;

@property (nonatomic, assign) NSUInteger calledSomeAction;
- (void)someAction;
@end


text:
Changelog
==============================

v4
----------------------

* Layout model attribute can now be 255 in length

v3
----------------------

* Added urls to pageimages
* If an pageimage has a url it will link to that instead of the larger image

v2
----------------------

* Version bumped to 2 because version numbers are arbitrary.
* Massive documentation overhaul.
* Added in support for custom layouts.
* Applicable notices for Fancybox license requirements have been added to the documentation..

v0.1.1
----------------------

* Fancybox is now used by default on thumbnails to provide lightbox functionality.

v0.1.0
----------------------

* The initial release.


text:
namespace jam
{
  class Scene;

  class Instance final
  {
    Instance(const Instance&) = delete;
    void operator =(const Instance&) = delete;

  public:

    Instance();

    ~Instance();

    void operator ()();

    bool sendRequest(const std::string& url, std::string& res);

    bool sendPutRequest(const std::string& url, const std::string& body);

  public:

    // Globals
    ConfigManager config;
    sf::RenderWindow window;
    std::unique_ptr<Scene> currentScene;
    ResourceManager resourceManager;
    std::map<sf::String, int> highscores;

  public:

    sf::Clock m_clock;
  };
}


text:
function SensitivityAnalysis(cores, pathToSave, mainTestEM, cellType, param, values, dt, step_save,...
                       Imax, Istep, Idur, CL, nCLs, Cai_ind)

matlabpool(cores)

[SUCCESS,MESSAGE] = mkdir(pathToSave);

if(SUCCESS==0)
    error([pathToSave ' directory can''t be created: ' MESSAGE])
end

if(isempty(dir([pathToSave '/base'])))
    mkdir([pathToSave '/base'])
    mkdir([pathToSave '/base/data'])
    mkdir([pathToSave '/base/post'])
    createRunTestEM([pathToSave '/base'],mainTestEM)
end

Param_str = cell(length(param));

[conduction, IThreshold, Istim] = calculateIThreshold(pathToSave, cellType, Imax, Istep, Idur, dt, step_save)

simulateSteadyState(pathToSave,cellType,param,values,CL,nCLs,Cai_ind,Idur,dt,step_save);
% simulateAPDRateAdaptation(pathToSave, cellType, param, values, [1000 600], [100 100], Idur, dt, step_save)

matlabpool close;


text:
module HaxParse.AST where

import Data.ByteString.Lazy
import Data.IntMap
import Data.Word
import HaxParse.AST.TH

data Move = Nop | Move [Direction] | Kick | MoveKick [Direction] deriving (Eq, Show)

data Direction = Up | Left | Down | Right deriving (Eq, Show)

data Action = Action { actPlayerId   :: Key
                     , actFrameCount :: Word32
                     , actEvent      :: Event
                     } deriving (Eq, Show)

data Side = Red | Blue | Spec deriving (Eq, Show)

data Event = NewPlayer { npId      :: Key
                       , npName    :: ByteString
                       , npAdmin   :: Bool
                       , npCountry :: ByteString
                       }
           | Departure { dId    :: Word32
                       , kicked :: Bool
                       , banned :: Bool
                       , reason :: Maybe ByteString
                       }
           | ChangeAvatar ByteString
           | Chat ByteString
           | StartMatch
           | StopMatch
           | TeamChange Word32 Side
           | DiscMove Move
           | PingBroadcast [(Word32, Word8)]
           | TimeUpdate deriving (Eq, Show)

makeIsFns ''Event

data Stadium = Classic | Easy | Small | Big
             | Rounded | Hockey | BigHockey | BigEasy
             | BigRounded | Huge | Custom
             deriving (Bounded, Eq, Enum, Ord, Show)

data Color = Color String deriving (Eq, Show)

data Mask = Mask [String] deriving (Eq, Show)

data Disc = Disc { discId       :: Word32
                 , pos          :: (Double, Double)
                 , speed        :: (Double, Double)
                 , radius       :: Double
                 , bCoefficient :: Double
                 , invMass      :: Double
                 , damping      :: Double
                 , color        :: Color
                 , mask         :: Mask
                 , group        :: Mask
                 } deriving (Eq, Show)

data Room = Room { roomName     :: ByteString
                 , locked       :: Bool
                 , scoreLimit   :: Word8
                 , timeLimit    :: Word8
                 , rules        :: Word32
                 , kickoffTaken :: Bool
                 , kickoffSide  :: Side
                 , ballCoords   :: (Double, Double)
                 , redScore     :: Word32
                 , blueScore    :: Word32
                 , timer        :: Double
                 , pauseTimer   :: Word8
                 , stadium      :: Stadium
                 } deriving (Eq, Show)

data Player = Player { name     :: ByteString
                     , initial  :: Bool
                     , admin    :: Bool
                     , team     :: Side
                     , number   :: Word8
                     , avatar   :: ByteString
                     , input    :: Word32
                     , autoKick :: Bool
                     , desync   :: Bool
                     , country  :: ByteString
                     , handicap :: Word16
                     , pDiscId  :: Word32
                     } deriving (Eq, Show)

data Replay = Replay { version    :: Word32
                     , frameCount :: Word32
                     , firstFrame :: Word32
                     , room       :: Room
                     , inProgress :: Bool
                     , discs      :: [Disc]
                     , players    :: IntMap Player
                     , events     :: [Action]
                     } deriving (Eq, Show)


text:
<!DOCTYPE html>

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

<title>README - Crowdfunding</title>

<link type="text/css" media="screen" href="./rdoc.css" rel="stylesheet">

    Home
    Classes
    Methods

  <form action="#" method="get" accept-charset="utf-8">

      <input type="text" name="search" placeholder="Search" id="search-field"
             title="Type to search, Up and Down to navigate, Enter to load">

  </form>

Pages

README

Class and Module Index

Crowdfunding

Crowdfunding::Engine

Crowdfunding

Instantly add simple crowdfunding to your Ruby on Rails application with
PayPal Payments Standard.

This project is still in development. Do not use, especially in a
production application.

Testing PayPal

To test PayPal in your local development environment, you'll need to have
tunnelling enabled to ensure PayPal's IPN can send the notification to your
computer. Setup is very simple.

Install the localtunnel gem: gem install localtunnel

On the first run you will need to send localtunnel your public key like so:
localtunnel -k ~/.ssh/id_rsa.pub 3000

Configure the engine with the URL localtunnel gives you

Done. Now you can repeat these steps whenever you're using app in your
development environment by just running: localtunnel 3000

[Validate]

Generated by RDoc 3.12.

Generated with the Darkfish Rdoc Generator 3.


text:
DELETE FROM LDAP_CONFIGS
WHERE
SYSTEM_NAME = ?
;


text:
package org.dspace.content;

import org.dspace.content.authority.Choices;

/**
 * Simple data structure-like class representing a Dublin Core value. It has an
 * element, qualifier, value and language.
 *
 * @author Robert Tansley
 * @author Martin Hald
 * @version $Revision$
 */
@Deprecated
public class DCValue
{
    /** The DC element */
    public String element;

    /** The DC qualifier, or null if unqualified */
    public String qualifier;

    /** The value of the field */
    public String value;

    /** The language of the field, may be null */
    public String language;

    /** The schema name of the metadata element */
    public String schema;

    /** Authority control key */
    public String authority = null;

    /** Authority control confidence  */
    public int confidence = Choices.CF_UNSET;

    @Override
    public boolean equals(Object o)
    {
        if (this == o) return true;
        if (o == null || getClass() != o.getClass()) return false;

        DCValue dcValue = (DCValue) o;

        if (confidence != dcValue.confidence) return false;
        if (authority != null ? !authority.equals(dcValue.authority) : dcValue.authority != null) return false;
        if (element != null ? !element.equals(dcValue.element) : dcValue.element != null) return false;
        if (language != null ? !language.equals(dcValue.language) : dcValue.language != null) return false;
        if (qualifier != null ? !qualifier.equals(dcValue.qualifier) : dcValue.qualifier != null) return false;
        if (schema != null ? !schema.equals(dcValue.schema) : dcValue.schema != null) return false;
        if (value != null ? !value.equals(dcValue.value) : dcValue.value != null) return false;

        return true;
    }

    @Override
    public int hashCode()
    {
        int result = element != null ? element.hashCode() : 0;
        result = 31 * result + (qualifier != null ? qualifier.hashCode() : 0);
        result = 31 * result + (value != null ? value.hashCode() : 0);
        result = 31 * result + (language != null ? language.hashCode() : 0);
        result = 31 * result + (schema != null ? schema.hashCode() : 0);
        result = 31 * result + (authority != null ? authority.hashCode() : 0);
        result = 31 * result + confidence;
        return result;
    }
}


text:
/**
 *
 */
package com.chahyadis.restfull.service;

import java.util.List;

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import com.chahyadis.restfull.model.MAddress;
import com.chahyadis.restfull.repository.MAddressRepository;

/**
 * @author SXCHAH
 *
 */
@Service
public final class MAddressServiceImpl implements MAddressService {
	private MAddressRepository addressRepository;

	@Autowired
	public MAddressServiceImpl(MAddressRepository addressRepository) {
		this.addressRepository = addressRepository;
	}

	public List<MAddress> findByAddressLike(String address) {
		return addressRepository.findByAddressLike(address);
	}

	public void deleteById(String id) {
		addressRepository.delete(id);
	}

	public MAddress findById(String id) {
		return addressRepository.findOne(id);
	}

	public MAddress save(MAddress address) {
		return addressRepository.save(address);

	}

}


text:
<!DOCTYPE html>

    <meta charset="utf-8"/>
    <meta http-equiv="X-UA-Compatible" content="IE=edge"/>
    <title>Purifier</title>

    <meta content="width=device-width, initial-scale=1, maximum-scale=1, user-scalable=no" name="viewport"/>

    <link rel="stylesheet" href="/css/bootstrap.min.css"/>

    <link rel="stylesheet" href="https://cdnjs.cloudflare.com/ajax/libs/font-awesome/4.5.0/css/font-awesome.min.css"/>

    <link rel="stylesheet" href="https://cdnjs.cloudflare.com/ajax/libs/ionicons/2.0.1/css/ionicons.min.css"/>

    <link rel="stylesheet" href="/css/AdminLTE.min.css"/>

    <link rel="stylesheet" href="/css/blue.css"/>

        Purifier

Sign in to start your session

        <form action="" method="post">

                <input type="email" id="id" class="form-control" placeholder="Email"> </input>

                <input type="password" id="pw" class="form-control" placeholder="Password"> </input>

                            <input type="checkbox"> Remember Me </input>

                    <button type="button" class="btn btn-primary btn-block btn-flat" onClick="login()">Sign In</button>

        </form>

        Register a new membership


text:
<?php
/**
 * Contains \jamesiarmes\PhpEws\Response\GetStreamingEventsResponseMessageType.
 */

namespace jamesiarmes\PhpEws\Response;

/**
 * Represents the status and result of a single GetStreamingEvents operation
 * request.
 *
 * @package php-ews\Response
 */
class GetStreamingEventsResponseMessageType extends ResponseMessageType
{
    /**
     * Provides a text description of the status of a streaming subscription.
     *
     * @since Exchange 2010 SP1
     *
     * @var string
     *
     * @see \jamesiarmes\PhpEws\Enumeration\ConnectionStatusType
     */
    public $ConnectionStatus;

    /**
     * Contains a list of subscription IDs that are invalid.
     *
     * @since Exchange 2010 SP1
     *
     * @var \jamesiarmes\PhpEws\ArrayType\NonEmptyArrayOfSubscriptionIdsType
     */
    public $ErrorSubscriptionIds;

    /**
     * Contains a list of information about the subscription and the events that
     * have occurred since the last notification.
     *
     * @since Exchange 2010 SP1
     *
     * @var \jamesiarmes\PhpEws\ArrayType\NonEmptyArrayOfNotificationsType
     */
    public $Notifications;
}


text:
import { NgModule } from "@angular/core";
import { DemoTemplateModule } from '../../template/demo-template/demo-template';
import { DocTemplateModule } from '../../template/doc-template/doc-template';
import { DocFooterTemplateModule } from '../../template/doc-footer-template/doc-footer-template';
import { DemoNavigationModule } from '../../template/demo-navigation/demo-navigation';
import { JigsawMarkdownModule } from "../../../libs/markdown/markdown";
import { AdjustFontColorAllDemoComponent } from "./demo.component";
import {
    JigsawButtonModule,
    JigsawHeaderModule,
    JigsawInputModule,
    JigsawTagModule,
    JigsawColorSelectModule,
} from "jigsaw/public_api";
import { CommonModule } from "@angular/common";
import { AdjustFontColorDemoComponent } from "./basic/demo.component";

@NgModule({
    declarations: [
        AdjustFontColorAllDemoComponent,
        AdjustFontColorDemoComponent,
    ],
    imports: [
        DemoTemplateModule,
        DocTemplateModule,
        DocFooterTemplateModule,
        DemoNavigationModule,
        JigsawMarkdownModule,
        JigsawButtonModule,
        JigsawHeaderModule,
        JigsawInputModule,
        JigsawTagModule,
        JigsawColorSelectModule,
        CommonModule,
    ],
})
export class AdjustFontColorDemoModule { }


text:
<!DOCTYPE HTML>

	<title>Awards | KCL Tech Society</title>
	<meta charset="utf-8" />
	<meta name="viewport" content="width=device-width, initial-scale=1, user-scalable=no" />

	<meta http-equiv="Content-Type" content="text/html; charset=utf-8">
	<meta property="og:title" content="Gallery | KCL Tech Society" />
	<meta property="og:url" content="http://kcltech.com/gallery.html" />
	<meta property="og:type" content="website" />
	<meta property="og:image" content="./thumbnail.jpg" />
	<meta property="og:description" content="King's College London Tech Society is run by and made for people who are passionate about tech entrepreneurship and building interesting products. We bring together students with different skill sets from various disciplines to create an innovative and supportive community of likeminded people."
	/>

	<meta name="title" content="Awards | KCL Tech Society">
	<meta name="description" content="King's College London Tech Society is run by and made for people who are passionate about tech entrepreneurship and building interesting products. We bring together students with different skill sets from various disciplines to create an innovative and supportive community of likeminded people.">
	<meta name="keywords" content="kcl, king's college london, technology, society, activity group, college, university, hackathon, events, social, kcltech, apple, google, microsoft, uk, europe">
	<meta name="author" content="KCL Tech Society, Clarence Ji">
	<meta name="robots" content="index, follow">

	<link rel="stylesheet" href="assets/css/main.css" />
	<link rel="stylesheet" href="css/kcltech.css" />
	<link rel="stylesheet" href="css/kcltech_device.css" />

About

Events

Gallery

Team

Awards

Partners

Contact

About

Events

Gallery

Team

Awards

Partners

Contact

Activity Group of the Year

KCLSU Awards 2014-2015

				"This award will go to the activity group that has contributed the most to the KCLSU community, having gone above and beyond the efforts of other groups to provide for their members and others.
				"

Best New Society

KCLSU Awards 2013-2014

				"Awarded to the members of an activity group ratified during the course of the current or previous academic year that have done the most to develop and establish the activity group, and brought it to a good level of success within its first
				year.
				"

Exceptional Contribution Award

KCL Department of Informatics

				"Awarded by the Department of Informatics to a group that has made an exceptional contribution to the academic progress of their fellow students at the end of the academic years, nominated by their fellow students.
				"

		<button style="margin-top: 3em; margin-bottom: 5em;" onClick="location.href='mlhprize/'" value="Go to Past Events">MLH EU Spring 2015 Season Winner</button>


text:
package it.polito.ai.polibox.service.notification.message;

import it.polito.ai.polibox.persistency.model.Device;
import it.polito.ai.polibox.persistency.model.User;

public class DeviceRinominato extends AbstractMessage{

	public DeviceRinominato(User u, Device d) {
		this.u=u;
		this.o=d;
		this.code=315;
	}

	@Override
	protected String messageGenerator() {
		String s="";
		s+="device "+((Device)o).getDevice_name()+" rinominato";
		return s;
	}

}


text:
module HtmlSelectorsHelpers
  # Maps a name to a selector. Used primarily by the
  #
  #   When /^(.+) within (.+)$/ do |step, scope|
  #
  # step definitions in web_steps.rb
  #
  def selector_for(locator)
    case locator

    when /the "([^"]+)" accordion section/
      [:xpath, Bermuda::XPath.accordion_content($1)]
    when /the "([^"]+)" dialog/
      [:xpath, Bermuda::XPath.dialog($1)]
    when /the "([^"]+)" tab/
      [:xpath, Bermuda::XPath.tab_content($1)]

    else
      raise "Can't find mapping from \"#{locator}\" to a selector.\n" +
        "Now, go and add a mapping in #{__FILE__}"
    end
  end
end

World(HtmlSelectorsHelpers)


text:
import {createStore, applyMiddleware, compose} from 'redux'
import middleware from './middleware'
import reducers from './reducers'

const initialState = {}

const store = compose(
  applyMiddleware.apply(null, middleware)
)(createStore)(reducers, initialState)

// Enable Webpack hot module replacement for middleware and reducers.
if (module.hot) {
  module.hot.accept('./middleware', () => {
    const nextRootReducer = require('./middleware')
    store.replaceReducer(nextRootReducer)
  })
  module.hot.accept('./reducers', () => {
    const nextRootReducer = require('./reducers')
    store.replaceReducer(nextRootReducer)
  })
}

export default store


text:
@interface Help : UIViewController

@end