text:
<?php
/**
 * Definition of the MeetingRequestMessageType type
 *
 * @package php-ews
 * @subpackage Types
 */

/**
 * Definition of the MeetingRequestMessageType type
 */
class EWSType_MeetingRequestMessageType extends EWSType
{
    /**
     * MeetingRequestType property
     *
     * @var EWSType_MeetingRequestTypeType
     */
    public $MeetingRequestType;

    /**
     * IntendedFreeBusyStatus property
     *
     * @var EWSType_LegacyFreeBusyType
     */
    public $IntendedFreeBusyStatus;

    /**
     * Start property
     *
     * @var EWSType_dateTime
     */
    public $Start;

    /**
     * End property
     *
     * @var EWSType_dateTime
     */
    public $End;

    /**
     * OriginalStart property
     *
     * @var EWSType_dateTime
     */
    public $OriginalStart;

    /**
     * IsAllDayEvent property
     *
     * @var boolean
     */
    public $IsAllDayEvent;

    /**
     * LegacyFreeBusyStatus property
     *
     * @var EWSType_LegacyFreeBusyType
     */
    public $LegacyFreeBusyStatus;

    /**
     * Location property
     *
     * @var string
     */
    public $Location;

    /**
     * When property
     *
     * @var string
     */
    public $When;

    /**
     * IsMeeting property
     *
     * @var boolean
     */
    public $IsMeeting;

    /**
     * IsCancelled property
     *
     * @var boolean
     */
    public $IsCancelled;

    /**
     * IsRecurring property
     *
     * @var boolean
     */
    public $IsRecurring;

    /**
     * MeetingRequestWasSent property
     *
     * @var boolean
     */
    public $MeetingRequestWasSent;

    /**
     * CalendarItemType property
     *
     * @var EWSType_CalendarItemTypeType
     */
    public $CalendarItemType;

    /**
     * MyResponseType property
     *
     * @var EWSType_ResponseTypeType
     */
    public $MyResponseType;

    /**
     * Organizer property
     *
     * @var EWSType_SingleRecipientType
     */
    public $Organizer;

    /**
     * RequiredAttendees property
     *
     * @var EWSType_NonEmptyArrayOfAttendeesType
     */
    public $RequiredAttendees;

    /**
     * OptionalAttendees property
     *
     * @var EWSType_NonEmptyArrayOfAttendeesType
     */
    public $OptionalAttendees;

    /**
     * Resources property
     *
     * @var EWSType_NonEmptyArrayOfAttendeesType
     */
    public $Resources;

    /**
     * ConflictingMeetingCount property
     *
     * @var integer
     */
    public $ConflictingMeetingCount;

    /**
     * AdjacentMeetingCount property
     *
     * @var integer
     */
    public $AdjacentMeetingCount;

    /**
     * ConflictingMeetings property
     *
     * @var EWSType_NonEmptyArrayOfAllItemsType
     */
    public $ConflictingMeetings;

    /**
     * AdjacentMeetings property
     *
     * @var EWSType_NonEmptyArrayOfAllItemsType
     */
    public $AdjacentMeetings;

    /**
     * Duration property
     *
     * @var string
     */
    public $Duration;

    /**
     * TimeZone property
     *
     * @var string
     */
    public $TimeZone;

    /**
     * AppointmentReplyTime property
     *
     * @var EWSType_dateTime
     */
    public $AppointmentReplyTime;

    /**
     * AppointmentSequenceNumber property
     *
     * @var integer
     */
    public $AppointmentSequenceNumber;

    /**
     * AppointmentState property
     *
     * @var integer
     */
    public $AppointmentState;

    /**
     * Recurrence property
     *
     * @var EWSType_RecurrenceType
     */
    public $Recurrence;

    /**
     * FirstOccurrence property
     *
     * @var EWSType_OccurrenceInfoType
     */
    public $FirstOccurrence;

    /**
     * LastOccurrence property
     *
     * @var EWSType_OccurrenceInfoType
     */
    public $LastOccurrence;

    /**
     * ModifiedOccurrences property
     *
     * @var EWSType_NonEmptyArrayOfOccurrenceInfoType
     */
    public $ModifiedOccurrences;

    /**
     * DeletedOccurrences property
     *
     * @var EWSType_NonEmptyArrayOfDeletedOccurrencesType
     */
    public $DeletedOccurrences;

    /**
     * MeetingTimeZone property
     *
     * @var EWSType_TimeZoneType
     */
    public $MeetingTimeZone;

    /**
     * ConferenceType property
     *
     * @var integer
     */
    public $ConferenceType;

    /**
     * AllowNewTimeProposal property
     *
     * @var boolean
     */
    public $AllowNewTimeProposal;

    /**
     * IsOnlineMeeting property
     *
     * @var boolean
     */
    public $IsOnlineMeeting;

    /**
     * MeetingWorkspaceUrl property
     *
     * @var string
     */
    public $MeetingWorkspaceUrl;

    /**
     * NetShowUrl property
     *
     * @var string
     */
    public $NetShowUrl;
}


text:
/* -*- Mode: C++; tab-width: 4; c-basic-offset: 4; indent-tabs-mode: nil -*- */
/*
 *     Copyright 2015 Couchbase, Inc.
 *
 *   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.
 */

#include "testapp.h"
#include "testapp_client_test.h"
#include <protocol/connection/client_mcbp_connection.h>

#include <algorithm>
#include <platform/compress.h>

class GetSetTest : public TestappClientTest {
public:
    void SetUp() {
        document.info.cas = mcbp::cas::Wildcard;
        document.info.datatype = cb::mcbp::Datatype::JSON;
        document.info.flags = 0xcaffee;
        document.info.id = name;
        const std::string content = to_string(memcached_cfg, false);
        std::copy(content.begin(), content.end(),
                  std::back_inserter(document.value));
    }

protected:
    Document document;
};

INSTANTIATE_TEST_CASE_P(TransportProtocols,
                        GetSetTest,
                        ::testing::Values(TransportProtocols::McbpPlain,
                                          TransportProtocols::McbpIpv6Plain,
                                          TransportProtocols::McbpSsl,
                                          TransportProtocols::McbpIpv6Ssl
                                         ),
                        ::testing::PrintToStringParamName());

TEST_P(GetSetTest, TestAdd) {
    MemcachedConnection& conn = getConnection();
    conn.mutate(document, 0, MutationType::Add);

    int eExistsCount = getResponseCount(PROTOCOL_BINARY_RESPONSE_KEY_EEXISTS);
    // Adding it one more time should fail
    try {
        conn.mutate(document, 0, MutationType::Add);
        FAIL() << "It should not be possible to add a document that exists";
    } catch (ConnectionError& error) {
        EXPECT_TRUE(error.isAlreadyExists()) << error.what();
        // Check that we correctly increment the status counter stat
        EXPECT_EQ(eExistsCount + 1,
                  getResponseCount(PROTOCOL_BINARY_RESPONSE_KEY_EEXISTS));
    }

    // Add with a cas should fail
    int invalCount = getResponseCount(PROTOCOL_BINARY_RESPONSE_EINVAL);
    try {
        document.info.cas = mcbp::cas::Wildcard + 1;
        conn.mutate(document, 0, MutationType::Add);
        FAIL() << "It should not be possible to add a document that exists";
    } catch (ConnectionError& error) {
        EXPECT_TRUE(error.isInvalidArguments()) << error.what();
        // Check that we correctly increment the status counter stat
        EXPECT_EQ(invalCount + 1,
                  getResponseCount(PROTOCOL_BINARY_RESPONSE_EINVAL));
    }
}

TEST_P(GetSetTest, TestReplace) {
    MemcachedConnection& conn = getConnection();

    // Replacing a nonexisting document should fail
    int eNoentCount = getResponseCount(PROTOCOL_BINARY_RESPONSE_KEY_ENOENT);
    try {
        conn.mutate(document, 0, MutationType::Replace);
        FAIL() << "It's not possible to replace a nonexisting document";
    } catch (ConnectionError& error) {
        EXPECT_TRUE(error.isNotFound()) << error.what();
        // Check that we correctly increment the status counter stat
        EXPECT_EQ(eNoentCount + 1,
                  getResponseCount(PROTOCOL_BINARY_RESPONSE_KEY_ENOENT));
    }

    conn.mutate(document, 0, MutationType::Add);
    // Replace this time should be fine!
    MutationInfo info;
    info = conn.mutate(document, 0, MutationType::Replace);

    // Replace with invalid cas should fail
    document.info.cas = info.cas + 1;

    int eExistsCount = getResponseCount(PROTOCOL_BINARY_RESPONSE_KEY_EEXISTS);
    try {
        conn.mutate(document, 0, MutationType::Replace);
        FAIL() << "replace with CAS mismatch should fail!";
    } catch (ConnectionError& error) {
        EXPECT_TRUE(error.isAlreadyExists()) << error.what();
        // Check that we correctly increment the status counter stat
        EXPECT_EQ(eExistsCount + 1,
                  getResponseCount(PROTOCOL_BINARY_RESPONSE_KEY_EEXISTS));
    }

    // Trying to replace a deleted document should also fail
    conn.remove(name, 0, 0);
    document.info.cas = 0;
    try {
        conn.mutate(document, 0, MutationType::Replace);
        FAIL() << "It's not possible to replace a nonexisting document (deleted)";
    } catch (ConnectionError& error) {
        EXPECT_TRUE(error.isNotFound()) << error.what();
    }

    // And CAS replace
    document.info.cas = 1;
    try {
        conn.mutate(document, 0, MutationType::Replace);
        FAIL() << "It's not possible to replace a nonexisting document (deleted)";
    } catch (ConnectionError& error) {
        EXPECT_TRUE(error.isNotFound()) << error.what();
    }

}

TEST_P(GetSetTest, TestReplaceWithXattr) {
    // The current code does not preserve XATTRs yet
    auto& conn = getConnection();
    conn.mutate(document, 0, MutationType::Add);
    createXattr("meta.cas", "\"${Mutation.CAS}\"", true);
    const auto mutation_cas = getXattr("meta.cas");
    EXPECT_NE("\"${Mutation.CAS}\"", mutation_cas);
    conn.mutate(document, 0, MutationType::Replace);
    // The xattr should have been preserved, and the macro should not
    // be expanded more than once..
    EXPECT_EQ(mutation_cas, getXattr("meta.cas"));
}

TEST_P(GetSetTest, TestSet) {
    MemcachedConnection& conn = getConnection();
    // Set should fail if the key doesn't exists and we're using CAS
    document.info.cas = 1;

    int eNoentCount = getResponseCount(PROTOCOL_BINARY_RESPONSE_KEY_ENOENT);
    try {
        conn.mutate(document, 0, MutationType::Set);
        FAIL() << "Set with CAS and no such doc should fail!";
    } catch (ConnectionError& error) {
        EXPECT_TRUE(error.isNotFound()) << error.what();
        EXPECT_EQ(eNoentCount + 1,
                  getResponseCount(PROTOCOL_BINARY_RESPONSE_KEY_ENOENT));
    }

    int successCount = getResponseCount(PROTOCOL_BINARY_RESPONSE_SUCCESS);
    // set should work even if a nonexisting document should fail
    document.info.cas = mcbp::cas::Wildcard;
    conn.mutate(document, 0, MutationType::Set);

    // And it should be possible to set it once more
    auto info = conn.mutate(document, 0, MutationType::Set);

    // And it should be possible to set it with a CAS
    document.info.cas = info.cas;
    info = conn.mutate(document, 0, MutationType::Set);
    // Check that we correctly increment the status counter stat
    EXPECT_EQ(successCount + statResps() + 3,
              getResponseCount(PROTOCOL_BINARY_RESPONSE_SUCCESS));

    // Replace with invalid cas should fail
    document.info.cas = info.cas + 1;

    int eExistsCount = getResponseCount(PROTOCOL_BINARY_RESPONSE_KEY_EEXISTS);

    try {
        conn.mutate(document, 0, MutationType::Replace);
        FAIL() << "set with CAS mismatch should fail!";
    } catch (ConnectionError& error) {
        EXPECT_TRUE(error.isAlreadyExists()) << error.what();
        // Check that we correctly increment the status counter stat
        EXPECT_EQ(eExistsCount + 1,
                  getResponseCount(PROTOCOL_BINARY_RESPONSE_KEY_EEXISTS));
    }
}

TEST_P(GetSetTest, TestGetMiss) {
    MemcachedConnection& conn = getConnection();
    int eNoentCount = getResponseCount(PROTOCOL_BINARY_RESPONSE_KEY_ENOENT);
    try {
        conn.get("TestGetMiss", 0);
        FAIL() << "Expected TestGetMiss to throw an exception";
    } catch (ConnectionError& error) {
        EXPECT_TRUE(error.isNotFound()) << error.what();
        // Check that we correctly increment the status counter stat
        EXPECT_EQ(eNoentCount + 1,
                  getResponseCount(PROTOCOL_BINARY_RESPONSE_KEY_ENOENT));
    }
}

TEST_P(GetSetTest, TestGetSuccess) {
    MemcachedConnection& conn = getConnection();
    conn.mutate(document, 0, MutationType::Set);

    int successCount = getResponseCount(PROTOCOL_BINARY_RESPONSE_SUCCESS);
    const auto stored = conn.get(name, 0);
    // Check that we correctly increment the status counter stat
    EXPECT_EQ(successCount + statResps() + 1,
              getResponseCount(PROTOCOL_BINARY_RESPONSE_SUCCESS));

    EXPECT_NE(mcbp::cas::Wildcard, stored.info.cas);
    EXPECT_EQ(cb::mcbp::Datatype::JSON, stored.info.datatype);
    EXPECT_EQ(document.info.flags, stored.info.flags);
    EXPECT_EQ(document.info.id, stored.info.id);
    EXPECT_EQ(document.value, stored.value);
}

TEST_P(GetSetTest, TestAppend) {
    MemcachedConnection& conn = getConnection();
    document.info.datatype = cb::mcbp::Datatype::Raw;
    document.value.clear();
    document.value.push_back('a');
    int successCount = getResponseCount(PROTOCOL_BINARY_RESPONSE_SUCCESS);
    conn.mutate(document, 0, MutationType::Set);
    document.value[0] = 'b';
    conn.mutate(document, 0, MutationType::Append);

    const auto stored = conn.get(name, 0);
    // Check that we correctly increment the status counter stat
    EXPECT_EQ(successCount + statResps() + 3,
              getResponseCount(PROTOCOL_BINARY_RESPONSE_SUCCESS));

    EXPECT_NE(mcbp::cas::Wildcard, stored.info.cas);
    EXPECT_EQ(cb::mcbp::Datatype::Raw, stored.info.datatype);
    EXPECT_EQ(document.info.flags, stored.info.flags);
    EXPECT_EQ(document.info.id, stored.info.id);
    document.value[0] = 'a';
    document.value.push_back('b');
    EXPECT_EQ(document.value, stored.value);
}

TEST_P(GetSetTest, TestAppendWithXattr) {
    // The current code does not preserve XATTRs
    auto& conn = getConnection();
    document.info.datatype = cb::mcbp::Datatype::Raw;
    document.value.clear();
    document.value.push_back('a');
    int sucCount = getResponseCount(PROTOCOL_BINARY_RESPONSE_SUCCESS);
    conn.mutate(document, 0, MutationType::Add);
    createXattr("meta.cas", "\"${Mutation.CAS}\"", true);
    const auto mutation_cas = getXattr("meta.cas");
    EXPECT_NE("\"${Mutation.CAS}\"", mutation_cas);

    document.value[0] = 'b';
    conn.mutate(document, 0, MutationType::Append);

    // The xattr should have been preserved, and the macro should not
    // be expanded more than once..
    EXPECT_EQ(mutation_cas, getXattr("meta.cas"));

    const auto stored = conn.get(name, 0);

    // Check that we correctly increment the status counter stat.
    // * We expect 4 * helloResps because the 3x createXattr/getXattr/getXattr
    //   connected and ran hello *and* the final getResponseCount will include
    //   the hellos for that call.
    // * We expect 6 successes for each command we ran
    // * Plus 1 more success to account for the stat call in the first
    //   getResponseCount
    EXPECT_EQ(sucCount + (helloResps() * 4) + 6 + 1,
              getResponseCount(PROTOCOL_BINARY_RESPONSE_SUCCESS));

    // And the rest of the doc should look the same
    EXPECT_NE(mcbp::cas::Wildcard, stored.info.cas);
    EXPECT_EQ(cb::mcbp::Datatype::Raw, stored.info.datatype);
    EXPECT_EQ(document.info.flags, stored.info.flags);
    EXPECT_EQ(document.info.id, stored.info.id);
    document.value[0] = 'a';
    document.value.push_back('b');
    EXPECT_EQ(document.value, stored.value);
}

TEST_P(GetSetTest, TestAppendCasSuccess) {
    MemcachedConnection& conn = getConnection();
    document.info.datatype = cb::mcbp::Datatype::Raw;
    document.value.clear();
    document.value.push_back('a');

    int successCount = getResponseCount(PROTOCOL_BINARY_RESPONSE_SUCCESS);
    const auto info = conn.mutate(document, 0, MutationType::Set);
    document.value[0] = 'b';
    document.info.cas = info.cas;
    conn.mutate(document, 0, MutationType::Append);

    const auto stored = conn.get(name, 0);
    // Check that we correctly increment the status counter stat
    EXPECT_EQ(successCount + statResps() + 3,
              getResponseCount(PROTOCOL_BINARY_RESPONSE_SUCCESS));

    EXPECT_NE(info.cas, stored.info.cas);
    EXPECT_EQ(cb::mcbp::Datatype::Raw, stored.info.datatype);
    EXPECT_EQ(document.info.flags, stored.info.flags);
    EXPECT_EQ(document.info.id, stored.info.id);
    document.value[0] = 'a';
    document.value.push_back('b');
    EXPECT_EQ(document.value, stored.value);
}

TEST_P(GetSetTest, TestAppendCasMismatch) {
    MemcachedConnection& conn = getConnection();
    document.info.datatype = cb::mcbp::Datatype::Raw;
    document.value.clear();
    document.value.push_back('a');

    const auto info = conn.mutate(document, 0, MutationType::Set);
    document.value[0] = 'b';
    document.info.cas = info.cas + 1;
    try {
        conn.mutate(document, 0, MutationType::Append);
        FAIL() << "Append with illegal CAS should fail";
    } catch (ConnectionError& error) {
        EXPECT_TRUE(error.isAlreadyExists()) << error.what();
    }

    // verify it didn't change..
    const auto stored = conn.get(name, 0);

    EXPECT_EQ(info.cas, stored.info.cas);
    EXPECT_EQ(document.info.datatype, stored.info.datatype);
    EXPECT_EQ(document.info.flags, stored.info.flags);
    EXPECT_EQ(document.info.id, stored.info.id);
    document.value[0] = 'a';
    EXPECT_EQ(document.value, stored.value);
}

TEST_P(GetSetTest, TestPrepend) {
    MemcachedConnection& conn = getConnection();
    document.info.datatype = cb::mcbp::Datatype::Raw;
    document.value.clear();
    document.value.push_back('a');

    int successCount = getResponseCount(PROTOCOL_BINARY_RESPONSE_SUCCESS);
    conn.mutate(document, 0, MutationType::Set);
    document.value[0] = 'b';
    conn.mutate(document, 0, MutationType::Prepend);

    const auto stored = conn.get(name, 0);
    // Check that we correctly increment the status counter stat
    EXPECT_EQ(successCount + statResps() + 3,
              getResponseCount(PROTOCOL_BINARY_RESPONSE_SUCCESS));

    EXPECT_NE(mcbp::cas::Wildcard, stored.info.cas);
    EXPECT_EQ(document.info.datatype, stored.info.datatype);
    EXPECT_EQ(document.info.flags, stored.info.flags);
    EXPECT_EQ(document.info.id, stored.info.id);
    document.value.push_back('a');
    EXPECT_EQ(document.value, stored.value);
}

TEST_P(GetSetTest, TestPrependWithXattr) {
    // The current code does not preserve XATTRs
    auto& conn = getConnection();
    document.info.datatype = cb::mcbp::Datatype::Raw;
    document.value.clear();
    document.value.push_back('a');

    int sucCount = getResponseCount(PROTOCOL_BINARY_RESPONSE_SUCCESS);

    conn.mutate(document, 0, MutationType::Add);
    createXattr("meta.cas", "\"${Mutation.CAS}\"", true);
    const auto mutation_cas = getXattr("meta.cas");
    EXPECT_NE("\"${Mutation.CAS}\"", mutation_cas);

    document.value[0] = 'b';
    conn.mutate(document, 0, MutationType::Prepend);

    // The xattr should have been preserved, and the macro should not
    // be expanded more than once..
    EXPECT_EQ(mutation_cas, getXattr("meta.cas"));

    const auto stored = conn.get(name, 0);

    // Check that we correctly increment the status counter stat.
    // * We expect 4 * helloResps because the 3x createXattr/getXattr/getXattr
    //   connected and ran hello *and* the final getResponseCount will include
    //   the hellos for that call.
    // * We expect 6 successes for each command we ran
    // * Plus 1 more success to account for the stat call in the first
    //   getResponseCount
    EXPECT_EQ(sucCount + (helloResps() * 4) + 6 + 1,
              getResponseCount(PROTOCOL_BINARY_RESPONSE_SUCCESS));

    // And the rest of the doc should look the same
    EXPECT_NE(mcbp::cas::Wildcard, stored.info.cas);
    EXPECT_EQ(cb::mcbp::Datatype::Raw, stored.info.datatype);
    EXPECT_EQ(document.info.flags, stored.info.flags);
    EXPECT_EQ(document.info.id, stored.info.id);
    document.value.push_back('a');
    EXPECT_EQ(document.value, stored.value);
}

TEST_P(GetSetTest, TestPrependCasSuccess) {
    MemcachedConnection& conn = getConnection();
    document.info.datatype = cb::mcbp::Datatype::Raw;
    document.value.clear();
    document.value.push_back('a');

    int successCount = getResponseCount(PROTOCOL_BINARY_RESPONSE_SUCCESS);
    const auto info = conn.mutate(document, 0, MutationType::Set);
    document.value[0] = 'b';
    document.info.cas = info.cas;
    conn.mutate(document, 0, MutationType::Prepend);

    const auto stored = conn.get(name, 0);
    // Check that we correctly increment the status counter stat
    EXPECT_EQ(successCount + statResps() + 3,
              getResponseCount(PROTOCOL_BINARY_RESPONSE_SUCCESS));

    EXPECT_NE(mcbp::cas::Wildcard, stored.info.cas);
    EXPECT_EQ(document.info.datatype, stored.info.datatype);
    EXPECT_EQ(document.info.flags, stored.info.flags);
    EXPECT_EQ(document.info.id, stored.info.id);
    document.value.push_back('a');
    EXPECT_EQ(document.value, stored.value);
}

TEST_P(GetSetTest, TestPerpendCasMismatch) {
    MemcachedConnection& conn = getConnection();
    document.info.datatype = cb::mcbp::Datatype::Raw;
    document.value.clear();
    document.value.push_back('a');

    const auto info = conn.mutate(document, 0, MutationType::Set);
    document.value[0] = 'b';
    document.info.cas = info.cas + 1;
    try {
        conn.mutate(document, 0, MutationType::Prepend);
        FAIL() << "Prepend with illegal CAS should fail";
    } catch (ConnectionError& error) {
        EXPECT_TRUE(error.isAlreadyExists()) << error.what();
    }
    const auto stored = conn.get(name, 0);

    EXPECT_NE(mcbp::cas::Wildcard, stored.info.cas);
    EXPECT_EQ(document.info.datatype, stored.info.datatype);
    EXPECT_EQ(document.info.flags, stored.info.flags);
    EXPECT_EQ(document.info.id, stored.info.id);
    document.value[0] = 'a';
    EXPECT_EQ(document.value, stored.value);
}

TEST_P(GetSetTest, TestIllegalVbucket) {
    auto& conn = getConnection();
    conn.authenticate("@admin", "password", "PLAIN");
    // A memcached bucket only use vbucket 0
    conn.createBucket("bucket", "", BucketType::Memcached);
    conn.selectBucket("bucket");

    try {
        conn.get("TestGetInvalidVbucket", 1);
        FAIL() << "Expected fetch of item in illegal vbucket to throw an exception";
    } catch (ConnectionError& error) {
        EXPECT_TRUE(error.isNotMyVbucket()) << error.what();
    }

    conn.deleteBucket("bucket");
    conn.reconnect();
}

static void compress_vector(const std::vector<char>& input,
                            std::vector<uint8_t>& output) {
    cb::compression::Buffer compressed;
    EXPECT_TRUE(cb::compression::deflate(cb::compression::Algorithm::Snappy,
                                         input.data(), input.size(),
                                         compressed));
    EXPECT_GT(input.size(), compressed.len);
    output.resize(compressed.len);
    memcpy(output.data(), compressed.data.get(), compressed.len);
}

TEST_P(GetSetTest, TestAppendCompressedSource) {
    TESTAPP_SKIP_IF_NO_COMPRESSION();
    MemcachedConnection& conn = getConnection();
    document.info.datatype = cb::mcbp::Datatype::Snappy;

    std::vector<char> input(1024);
    std::fill(input.begin(), input.end(), 'a');
    compress_vector(input, document.value);

    int successCount = getResponseCount(PROTOCOL_BINARY_RESPONSE_SUCCESS);
    conn.mutate(document, 0, MutationType::Set);
    document.value.resize(input.size());
    std::fill(document.value.begin(), document.value.end(), 'b');
    document.info.datatype = cb::mcbp::Datatype::Raw;

    conn.mutate(document, 0, MutationType::Append);
    const auto stored = conn.get(name, 0);
    // Check that we correctly increment the status counter stat
    EXPECT_EQ(successCount + statResps() + 3,
              getResponseCount(PROTOCOL_BINARY_RESPONSE_SUCCESS));

    EXPECT_EQ(cb::mcbp::Datatype::Raw, stored.info.datatype);
    EXPECT_EQ(document.info.flags, stored.info.flags);
    EXPECT_EQ(document.info.id, stored.info.id);

    std::vector<uint8_t> expected(input.size() * 2);
    memset(expected.data(), 'a', input.size());
    memset(expected.data() + input.size(), 'b', input.size());
    EXPECT_EQ(expected, stored.value);
}

TEST_P(GetSetTest, TestAppendCompressedData) {
    TESTAPP_SKIP_IF_NO_COMPRESSION();
    MemcachedConnection& conn = getConnection();
    document.info.datatype = cb::mcbp::Datatype::Raw;
    document.value.resize(1024);
    std::fill(document.value.begin(), document.value.end(), 'a');

    int successCount = getResponseCount(PROTOCOL_BINARY_RESPONSE_SUCCESS);

    conn.mutate(document, 0, MutationType::Set);

    std::vector<char> input(1024);
    std::fill(input.begin(), input.end(), 'b');
    compress_vector(input, document.value);
    document.info.datatype = cb::mcbp::Datatype::Snappy;
    conn.mutate(document, 0, MutationType::Append);

    const auto stored = conn.get(name, 0);

    // Check that we correctly increment the status counter stat
    EXPECT_EQ(successCount + statResps() + 3,
              getResponseCount(PROTOCOL_BINARY_RESPONSE_SUCCESS));

    EXPECT_EQ(cb::mcbp::Datatype::Raw, stored.info.datatype);
    EXPECT_EQ(document.info.flags, stored.info.flags);
    EXPECT_EQ(document.info.id, stored.info.id);

    std::vector<uint8_t> expected(input.size() * 2);
    memset(expected.data(), 'a', input.size());
    memset(expected.data() + input.size(), 'b', input.size());

    ASSERT_EQ(2048, stored.value.size());

    EXPECT_EQ(expected, stored.value);
}

TEST_P(GetSetTest, TestAppendCompressedSourceAndData) {
    TESTAPP_SKIP_IF_NO_COMPRESSION();
    MemcachedConnection& conn = getConnection();
    document.info.datatype = cb::mcbp::Datatype::Snappy;

    std::vector<char> input(1024);
    std::fill(input.begin(), input.end(), 'a');
    compress_vector(input, document.value);

    int successCount = getResponseCount(PROTOCOL_BINARY_RESPONSE_SUCCESS);
    conn.mutate(document, 0, MutationType::Set);

    std::vector<char> append(1024);
    std::fill(append.begin(), append.end(), 'b');
    compress_vector(append, document.value);
    conn.mutate(document, 0, MutationType::Append);
    const auto stored = conn.get(name, 0);

    // Check that we correctly increment the status counter stat
    EXPECT_EQ(successCount + statResps() + 3,
              getResponseCount(PROTOCOL_BINARY_RESPONSE_SUCCESS));

    EXPECT_EQ(cb::mcbp::Datatype::Raw, stored.info.datatype);
    EXPECT_EQ(document.info.flags, stored.info.flags);
    EXPECT_EQ(document.info.id, stored.info.id);

    std::vector<uint8_t> expected(input.size() + append.size());
    memset(expected.data(), 'a', input.size());
    memset(expected.data() + input.size(), 'b', append.size());
    EXPECT_EQ(expected, stored.value);
}

TEST_P(GetSetTest, TestPrependCompressedSource) {
    TESTAPP_SKIP_IF_NO_COMPRESSION();
    MemcachedConnection& conn = getConnection();
    document.info.datatype = cb::mcbp::Datatype::Snappy;

    std::vector<char> input(1024);
    std::fill(input.begin(), input.end(), 'a');
    compress_vector(input, document.value);

    int successCount = getResponseCount(PROTOCOL_BINARY_RESPONSE_SUCCESS);
    conn.mutate(document, 0, MutationType::Set);
    document.value.resize(input.size());
    std::fill(document.value.begin(), document.value.end(), 'b');
    document.info.datatype = cb::mcbp::Datatype::Raw;

    conn.mutate(document, 0, MutationType::Prepend);
    const auto stored = conn.get(name, 0);

    // Check that we correctly increment the status counter stat
    EXPECT_EQ(successCount + statResps() + 3,
              getResponseCount(PROTOCOL_BINARY_RESPONSE_SUCCESS));

    EXPECT_EQ(cb::mcbp::Datatype::Raw, stored.info.datatype);
    EXPECT_EQ(document.info.flags, stored.info.flags);
    EXPECT_EQ(document.info.id, stored.info.id);

    std::vector<uint8_t> expected(input.size() * 2);
    memset(expected.data(), 'b', input.size());
    memset(expected.data() + input.size(), 'a', input.size());
    EXPECT_EQ(expected, stored.value);
}

TEST_P(GetSetTest, TestPrependCompressedData) {
    TESTAPP_SKIP_IF_NO_COMPRESSION();
    MemcachedConnection& conn = getConnection();
    document.info.datatype = cb::mcbp::Datatype::Raw;
    document.value.resize(1024);
    std::fill(document.value.begin(), document.value.end(), 'a');

    int successCount = getResponseCount(PROTOCOL_BINARY_RESPONSE_SUCCESS);
    conn.mutate(document, 0, MutationType::Set);

    std::vector<char> input(1024);
    std::fill(input.begin(), input.end(), 'b');
    compress_vector(input, document.value);
    document.info.datatype = cb::mcbp::Datatype::Snappy;
    conn.mutate(document, 0, MutationType::Prepend);

    const auto stored = conn.get(name, 0);

    // Check that we correctly increment the status counter stat
    EXPECT_EQ(successCount + statResps() + 3,
              getResponseCount(PROTOCOL_BINARY_RESPONSE_SUCCESS));

    EXPECT_EQ(cb::mcbp::Datatype::Raw, stored.info.datatype);
    EXPECT_EQ(document.info.flags, stored.info.flags);
    EXPECT_EQ(document.info.id, stored.info.id);

    std::vector<uint8_t> expected(input.size() * 2);
    memset(expected.data(), 'b', input.size());
    memset(expected.data() + input.size(), 'a', input.size());
    EXPECT_EQ(expected, stored.value);
}

TEST_P(GetSetTest, TestPrepepndCompressedSourceAndData) {
    TESTAPP_SKIP_IF_NO_COMPRESSION();
    MemcachedConnection& conn = getConnection();
    document.info.datatype = cb::mcbp::Datatype::Snappy;

    std::vector<char> input(1024);
    std::fill(input.begin(), input.end(), 'a');
    compress_vector(input, document.value);

    int successCount = getResponseCount(PROTOCOL_BINARY_RESPONSE_SUCCESS);
    conn.mutate(document, 0, MutationType::Set);

    std::vector<char> append(1024);
    std::fill(append.begin(), append.end(), 'b');
    compress_vector(append, document.value);
    conn.mutate(document, 0, MutationType::Prepend);
    const auto stored = conn.get(name, 0);

    // Check that we correctly increment the status counter stat
    EXPECT_EQ(successCount + statResps() + 3,
              getResponseCount(PROTOCOL_BINARY_RESPONSE_SUCCESS));

    EXPECT_EQ(cb::mcbp::Datatype::Raw, stored.info.datatype);
    EXPECT_EQ(document.info.flags, stored.info.flags);
    EXPECT_EQ(document.info.id, stored.info.id);

    std::vector<uint8_t> expected(input.size() + append.size());
    memset(expected.data(), 'b', input.size());
    memset(expected.data() + input.size(), 'a', append.size());
    EXPECT_EQ(expected, stored.value);
}

redpajama_set_name: RedPajamaGithub


text:
package source

import (
	"encoding/json"
	"fmt"
	"os/exec"
)

type simpleSource struct {
	args    []string
	command string
	rawData []byte
}

// New creates simple source as external program output.
// It takes command name and its arguments as parameters.
// It return pointer to new source object ready to execute.
func New(cmd string, args []string) *simpleSource {
	return &simpleSource{command: cmd, args: args}
}

// Run executes source command and gathers its output in internal structure.
// It returns nil in case of success and returns error if command execution failed.
func (ss *simpleSource) Run() error {

	out, err := exec.Command(ss.command, ss.args...).Output()
	if err != nil {
		return err
	}

	ss.rawData = out
	return nil
}

// Raw returns output of executed command in raw format (as is)
func (ss *simpleSource) Raw() []byte {
	return ss.rawData
}

// OutputMap translates json document data from command execution to a map.
// It returns map literals with its values, possibly nested maps and slices
func (ss *simpleSource) OutputMap() map[string]interface{} {
	var jsonMap map[string]interface{}
	if err := json.Unmarshal(ss.rawData, &jsonMap); err != nil {
		fmt.Println(err)
		return nil
	}
	return jsonMap
}


text:
package uploader

import (
	"fmt"
	"strconv"
	"strings"

	"github.com/pkg/errors"
)

type httpRange struct {
	start int64
	end   int64
}

func parseRangeHeader(rangeHeader string) (r *httpRange, err error) {
	keyval := strings.Split(rangeHeader, "=")
	if len(keyval) != 2 {
		err = errors.Errorf("invalid range header, expected \"key=val\", got \"%s\"", rangeHeader)
		return
	}
	val := keyval[1]

	startEnd := strings.Split(val, "-")
	if len(startEnd) != 2 {
		err = errors.Errorf("invalid range header, expected \"start-end\", got \"%s\"", val)
		return
	}

	start, err := strconv.ParseInt(startEnd[0], 10, 64)
	if err != nil {
		return
	}

	end, err := strconv.ParseInt(startEnd[1], 10, 64)
	if err != nil {
		return
	}

	r = &httpRange{start, end + 1}
	return
}

func (r *httpRange) String() string {
	return fmt.Sprintf("bytes=%d-%d", r.start, r.end-1)
}


text:
:mod:`signals`
==============

.. module:: king_phisher.server.signals
   :synopsis:

This module contains the signals which are used by the server to dispatch
events. Additional signal details regarding how these signals are used is
available in the :ref:`server-signals-label` documentation.

Functions
---------

.. autofunction:: send_safe

Signals
-------

.. autodata:: campaign_alert
   :annotation:

.. autodata:: credentials_received
   :annotation:

.. autodata:: db_initialized
   :annotation:

.. autodata:: db_session_deleted
   :annotation:

.. autodata:: db_session_inserted
   :annotation:

.. autodata:: db_session_updated
   :annotation:

.. autodata:: db_table_delete
   :annotation:

.. autodata:: db_table_insert
   :annotation:

.. autodata:: db_table_update
   :annotation:

.. autodata:: email_opened
   :annotation:

.. autodata:: request_handle
   :annotation:

.. autodata:: request_received
   :annotation:

.. autodata:: response_sent
   :annotation:

.. autodata:: rpc_method_call
   :annotation:

.. autodata:: rpc_method_called
   :annotation:

.. autodata:: rpc_user_logged_in
   :annotation:

.. autodata:: rpc_user_logged_out
   :annotation:

.. autodata:: server_initialized
   :annotation:

.. autodata:: visit_received
   :annotation:


text:
class PaddleInputP2 :
	public InputComponent
{
public:
	void update(sf::Event& event, sf::RenderWindow& window, sf::Shape& shape, GameEntity& gameEntity) override;
	PaddleInputP2();
	~PaddleInputP2();
};

#endif // PADDLE_INPUT_P2_H


text:
/* vi: set sw=4 ts=4: */
/*
 * Utility routines.
 *
 * Copyright (C) 1999-2004 by Erik Andersen <andersen@codepoet.org>
 *
 * Licensed under GPLv2 or later, see file LICENSE in this source tree.
 */

#include "libbb.h"

/* Find block device /dev/XXX which contains specified file
 * We handle /dev/dir/dir/dir too, at a cost of ~80 more bytes code */

/* Do not reallocate all this stuff on each recursion */
enum { DEVNAME_MAX = 256 };
struct arena {
	struct stat st;
	dev_t dev;
	/* Was PATH_MAX, but we recurse _/dev_. We can assume
	 * people are not crazy enough to have mega-deep tree there */
	char devpath[DEVNAME_MAX];
};

static char *find_block_device_in_dir(struct arena *ap)
{
	DIR *dir;
	struct dirent *entry;
	char *retpath = NULL;
	int len, rem;

	len = strlen(ap->devpath);
	rem = DEVNAME_MAX-2 - len;
	if (rem <= 0)
		return NULL;

	dir = opendir(ap->devpath);
	if (!dir)
		return NULL;

	ap->devpath[len++] = '/';

	while ((entry = readdir(dir)) != NULL) {
		safe_strncpy(ap->devpath + len, entry->d_name, rem);
		/* lstat: do not follow links */
		if (lstat(ap->devpath, &ap->st) != 0)
			continue;
		if (S_ISBLK(ap->st.st_mode) && ap->st.st_rdev == ap->dev) {
			retpath = xstrdup(ap->devpath);
			break;
		}
		if (S_ISDIR(ap->st.st_mode)) {
			/* Do not recurse for '.' and '..' */
			if (DOT_OR_DOTDOT(entry->d_name))
				continue;
			retpath = find_block_device_in_dir(ap);
			if (retpath)
				break;
		}
	}
	closedir(dir);

	return retpath;
}

char* FAST_FUNC find_block_device(const char *path)
{
	struct arena a;

	if (stat(path, &a.st) != 0)
		return NULL;
	a.dev = S_ISBLK(a.st.st_mode) ? a.st.st_rdev : a.st.st_dev;
	strcpy(a.devpath, "/dev");
	return find_block_device_in_dir(&a);
}


text:
// Copyright (c) 2012 The Chromium Authors. All rights reserved.
// Use of this source code is governed by a BSD-style license that can be
// found in the LICENSE file.

// <if expr="is_ios">
import 'chrome://resources/js/ios/web_ui.js';
// </if>

import 'chrome://resources/js/action_link.js';
import './strings.m.js';
import {addWebUIListener} from 'chrome://resources/js/cr.m.js';
import {loadTimeData} from 'chrome://resources/js/load_time_data.m.js';
import {$, appendParam} from 'chrome://resources/js/util.m.js';

/* Id for tracking automatic refresh of crash list.  */
let refreshCrashListId = undefined;

/**
 * Requests the list of crashes from the backend.
 */
function requestCrashes() {
  chrome.send('requestCrashList');
}

/**
 * Callback from backend with the list of crashes. Builds the UI.
 * @param {!{enabled: boolean,
 *           dynamicBackend: boolean,
 *           manualUploads: boolean,
 *           crashes: !Array,
 *           version: string,
 *           os: string,
 *           isGoogleAccount: boolean,
 *           }} result
 */
function updateCrashList({
  enabled,
  dynamicBackend,
  manualUploads,
  crashes,
  version,
  os,
  isGoogleAccount
}) {
  $('crashesCount').textContent = loadTimeData.getStringF(
      'crashCountFormat', crashes.length.toLocaleString());

  const crashList = $('crashList');

  $('disabledMode').hidden = enabled;
  $('crashUploadStatus').hidden = !enabled || !dynamicBackend;

  const template = crashList.getElementsByTagName('template')[0];

  // Clear any previous list.
  crashList.querySelectorAll('.crash-row').forEach((elm) => elm.remove());

  const productName = loadTimeData.getString('shortProductName');

  for (let i = 0; i < crashes.length; i++) {
    const crash = crashes[i];
    if (crash.local_id === '') {
      crash.local_id = productName;
    }

    const crashRow = template.content.cloneNode(true);
    if (crash.state !== 'uploaded') {
      crashRow.querySelector('.crash-row').classList.add('not-uploaded');
    }

    const uploaded = crash.state === 'uploaded';

    // Some clients do not distinguish between capture time and upload time,
    // so use the latter if the former is not available.
    crashRow.querySelector('.capture-time').textContent =
        loadTimeData.getStringF(
            'crashCaptureTimeFormat',
            crash.capture_time || crash.upload_time || '');
    crashRow.querySelector('.local-id .value').textContent = crash.local_id;

    let stateText = '';
    switch (crash.state) {
      case 'not_uploaded':
        stateText = loadTimeData.getString('crashStatusNotUploaded');
        break;
      case 'pending':
        stateText = loadTimeData.getString('crashStatusPending');
        break;
      case 'pending_user_requested':
        stateText = loadTimeData.getString('crashStatusPendingUserRequested');
        break;
      case 'uploaded':
        stateText = loadTimeData.getString('crashStatusUploaded');
        break;
      default:
        continue;  // Unknown state.
    }
    crashRow.querySelector('.status .value').textContent = stateText;

    const uploadId = crashRow.querySelector('.upload-id');
    const uploadTime = crashRow.querySelector('.upload-time');
    const sendNowButton = crashRow.querySelector('.send-now');
    const fileBugButton = crashRow.querySelector('.file-bug');
    if (uploaded) {
      const uploadIdValue = uploadId.querySelector('.value');
      if (isGoogleAccount) {
        const crashLink = document.createElement('a');
        crashLink.href = `https://goto.google.com/crash/${crash.id}`;
        crashLink.target = '_blank';
        crashLink.textContent = crash.id;
        uploadIdValue.appendChild(crashLink);
      } else {
        uploadIdValue.textContent = crash.id;
      }

      uploadTime.querySelector('.value').textContent = crash.upload_time;

      sendNowButton.remove();
      fileBugButton.onclick = () => fileBug(crash.id, os, version);
    } else {
      uploadId.remove();
      uploadTime.remove();
      fileBugButton.remove();
      // Do not allow crash submission if the Chromium build does not support
      // it, or if the user already requested it.
      if (!manualUploads || crash.state === 'pending_user_requested') {
        sendNowButton.remove();
      }
      sendNowButton.onclick = (e) => {
        e.target.disabled = true;
        chrome.send('requestSingleCrashUpload', [crash.local_id]);
      };
    }

    const fileSize = crashRow.querySelector('.file-size');
    if (crash.file_size === '') {
      fileSize.remove();
    } else {
      fileSize.querySelector('.value').textContent = crash.file_size;
    }

    crashList.appendChild(crashRow);
  }

  $('noCrashes').hidden = crashes.length !== 0;
}

/**
 * Opens a new tab/window to report the crash to crbug.
 * @param {string} The crash report ID.
 * @param {string} The OS name.
 * @param {string} The product version.
 */
function fileBug(crashId, os, version) {
  const commentLines = [
    'IMPORTANT: Your crash has already been automatically reported ' +
    'to our crash system. Please file this bug only if you can provide ' +
    'more information about it.',
    '',
    '',
    'Chrome Version: ' + version,
    'Operating System: ' + os,
    '',
    'URL (if applicable) where crash occurred:',
    '',
    'Can you reproduce this crash?',
    '',
    'What steps will reproduce this crash? (If it\'s not ' +
    'reproducible, what were you doing just before the crash?)',
    '1.', '2.', '3.',
    '',
    '****DO NOT CHANGE BELOW THIS LINE****',
    'Crash ID: crash/' + crashId
  ];
  const params = {
    template: 'Crash Report',
    comment: commentLines.join('\n'),
    // TODO(scottmg): Use add_labels to add 'User-Submitted' rather than
    // duplicating the template's labels (the first two) once
    // https://bugs.chromium.org/p/monorail/issues/detail?id=1488 is done.
    labels: 'Restrict-View-EditIssue,Stability-Crash,User-Submitted,Pri-3,Type-Bug',
  };
  let href = 'https://bugs.chromium.org/p/chromium/issues/entry';
  for (const param in params) {
    href = appendParam(href, param, params[param]);
  }

  window.open(href);
}

/**
 * Request crashes get uploaded in the background.
 */
function requestCrashUpload() {
  // Don't need locking with this call because the system crash reporter
  // has locking built into itself.
  chrome.send('requestCrashUpload');

  // Trigger a refresh in 5 seconds.  Clear any previous requests.
  clearTimeout(refreshCrashListId);
  refreshCrashListId = setTimeout(requestCrashes, 5000);
}

/**
 * Toggles hiding/showing the developer details of a crash report, depending
 * on the value of the check box.
 * @param {Event} The DOM event for onclick.
 */
function toggleDevDetails(e) {
  $('crashList').classList.toggle('showing-dev-details', e.target.checked);
}

document.addEventListener('DOMContentLoaded', function() {
  addWebUIListener('update-crash-list', updateCrashList);
  $('uploadCrashes').onclick = requestCrashUpload;
  $('showDevDetails').onclick = toggleDevDetails;
  requestCrashes();
});


text:
@implementation DiscoverModel
- (instancetype)initWithDictionary:(NSDictionary *)dic{
    self = [super init];
    if (self) {
        self.title = dic[@"title"];
        self.image = dic[@"image"];
        self.activityId = dic[@"id"];
        self.type = dic[@"type"];
    }
    return self;
}

@end


text:
using System;
using System.Collections.Generic;
using System.Collections.Immutable;
using System.Linq;
using System.Threading;
using System.Threading.Tasks;
using Microsoft.CodeAnalysis.CodeFixes;
using Microsoft.CodeAnalysis.CodeFixes.Suppression;
using Microsoft.CodeAnalysis.Diagnostics;
using Microsoft.CodeAnalysis.Editor.UnitTests.Workspaces;
using Microsoft.CodeAnalysis.Host.Mef;
using Microsoft.CodeAnalysis.SolutionCrawler;
using Microsoft.CodeAnalysis.Text;
using Roslyn.Utilities;
using Xunit;

namespace Microsoft.CodeAnalysis.Editor.UnitTests.CodeFixes
{
    public class CodeFixServiceTests
    {
        [Fact]
        public void TestGetFirstDiagnosticWithFixAsync()
        {
            var diagnosticService = new TestDiagnosticAnalyzerService(DiagnosticExtensions.GetCompilerDiagnosticAnalyzersMap());

            var fixers = CreateFixers();
            var fixService = new CodeFixService(
                    diagnosticService, fixers, SpecializedCollections.EmptyEnumerable<Lazy<ISuppressionFixProvider, CodeChangeProviderMetadata>>());

            var code = @"
    a
";

            using (var workspace =
                CSharpWorkspaceFactory.CreateWorkspaceFromFile(code))
            {
                var incrementalAnalzyer = (IIncrementalAnalyzerProvider)diagnosticService;

                // register diagnostic engine to solution crawler
                var analyzer = incrementalAnalzyer.CreateIncrementalAnalyzer(workspace);

                var reference = new MockAnalyzerReference();
                var project = workspace.CurrentSolution.Projects.Single().AddAnalyzerReference(reference);
                var document = project.Documents.Single();
                var unused = fixService.GetFirstDiagnosticWithFixAsync(document, TextSpan.FromBounds(0, 0), CancellationToken.None).Result;

                var fixer1 = fixers.Single().Value as MockFixer;
                var fixer2 = reference.Fixer as MockFixer;

                // check to make sure both of them are called.
                Assert.True(fixer1.Called);
                Assert.True(fixer2.Called);
            }
        }

        private IEnumerable<Lazy<CodeFixProvider, CodeChangeProviderMetadata>> CreateFixers()
        {
            return SpecializedCollections.SingletonEnumerable(
                new Lazy<CodeFixProvider, CodeChangeProviderMetadata>(() => new MockFixer(), new CodeChangeProviderMetadata("Test", languages: LanguageNames.CSharp)));
        }

        private class MockFixer : CodeFixProvider
        {
            public const string Id = "MyDiagnostic";
            public bool Called = false;

            public sealed override ImmutableArray<string> FixableDiagnosticIds
            {
                get { return ImmutableArray.Create(Id); }
            }

            public sealed override Task RegisterCodeFixesAsync(CodeFixContext context)
            {
                Called = true;
                return SpecializedTasks.EmptyTask;
            }
        }

        private class MockAnalyzerReference : AnalyzerReference, ICodeFixProviderFactory
        {
            public readonly MockFixer Fixer = new MockFixer();
            public readonly MockDiagnosticAnalyzer Analyzer = new MockDiagnosticAnalyzer();

            public override string Display
            {
                get
                {
                    return "MockAnalyzerReference";
                }
            }

            public override string FullPath
            {
                get
                {
                    return string.Empty;
                }
            }

            public override ImmutableArray<DiagnosticAnalyzer> GetAnalyzers(string language)
            {
                return ImmutableArray.Create<DiagnosticAnalyzer>(Analyzer);
            }

            public override ImmutableArray<DiagnosticAnalyzer> GetAnalyzersForAllLanguages()
            {
                return ImmutableArray<DiagnosticAnalyzer>.Empty;
            }

            public ImmutableArray<CodeFixProvider> GetFixers()
            {
                return ImmutableArray.Create<CodeFixProvider>(Fixer);
            }

            public class MockDiagnosticAnalyzer : DiagnosticAnalyzer
            {
                private DiagnosticDescriptor _descriptor = new DiagnosticDescriptor(MockFixer.Id, "MockDiagnostic", "MockDiagnostic", "InternalCategory", DiagnosticSeverity.Warning, isEnabledByDefault: true);

                public override ImmutableArray<DiagnosticDescriptor> SupportedDiagnostics
                {
                    get
                    {
                        return ImmutableArray.Create(_descriptor);
                    }
                }

                public override void Initialize(AnalysisContext context)
                {
                    context.RegisterSyntaxTreeAction(c =>
                    {
                        c.ReportDiagnostic(Diagnostic.Create(_descriptor, c.Tree.GetLocation(TextSpan.FromBounds(0, 0))));
                    });
                }
            }
        }
    }
}


text:
import logging
from datetime import datetime

def decor_info_ajuda(func):
	def wrapper(*args, **kwargs):
		try:
			func(*args, **kwargs)
		except BaseException:
			args[0].bot.sendMessage(
				args[0].chat_id,
				'Por favor, inicie uma conversa comigo e tente novamente.'
			)
	return wrapper

def log(func):
	day_date_hour = datetime.now().strftime('%c')

	def wrapper(*args, **kwargs):
		if args[0].msg.get('data'):
			func(*args, **kwargs)
		else:
			func(*args, **kwargs)
			if args[0].msg['text'].startswith('/start'):
				logging.basicConfig(
					filename='.tmp/users_register.log',
					filemode='w',
					level=logging.INFO
				)
				logging.info("log [{}]".format(day_date_hour))
				logging.info(" | Username: {} | ID: {} | Comando usado: {}\n".format(
					args[0].user, args[0].UserID, args[0].msg['text'].split(' ')[0])
				)
				print("@{} Iniciou o Bot - Dados salvos!".format(args[0].user))
			elif(args[0].msg['text'].startswith('/') and args[0].msg['text'] != '/start'):
				logging.basicConfig(
					filename='.tmp/log.log',
					filemode='w',
					level=logging.INFO
				)
				logging.info("log [{}]".format(day_date_hour))
				logging.info(" | Username: {} | ID: {} | Comando usado: {}\n".format(
					args[0].user, args[0].UserID, args[0].msg['text'].split(' ')[0])
				)
				print("@{} Usou o Bot - Dados salvos!".format(args[0].user))
	return wrapper

def admin(func):
	def wrapper(*args, **kwargs):
		if args[0].msg.get('data'):
			if args[0].get_admin_list(query=True):
				func(*args, **kwargs)
		elif args[0].get_admin_list():
			func(*args, **kwargs)
	return wrapper


text:
package com.google.javascript.refactoring.examples;

import com.google.javascript.refactoring.testing.RefasterJsTestCase;
import org.junit.Test;
import org.junit.runner.RunWith;
import org.junit.runners.JUnit4;

@RunWith(JUnit4.class)
public class StringIndexOfToIncludesTest {

  /** Path of the directory containing test inputs and expected outputs. */
  private static final String TESTDATA_DIR =
      "test/"
          + "com/google/javascript/refactoring/examples/testdata";

  /** The RefasterJs template to use. */
  private static final String STRING_INDEXOF_TO_INCLUDES_TEMPLATE =
      "com/google/javascript/refactoring/examples/refasterjs/string_indexof_to_includes.js";

  @Test
  public void test_refactorings() throws Exception {
    RefasterJsTestCase.builder()
        .setTemplatePath(STRING_INDEXOF_TO_INCLUDES_TEMPLATE)
        .setInputPath(TESTDATA_DIR + "/string_indexof_to_includes_in.js")
        .addExpectedOutputPath(TESTDATA_DIR + "/string_indexof_to_includes_out.js")
        .addAdditionalSourcePath(TESTDATA_DIR + "/goog_base.js")
        .test();
  }
}


text:
<component name="ProjectDictionaryState">
  <dictionary name="devuser">
    <words>
      <w>goodstype</w>
    </words>
  </dictionary>
</component>


text:
package com.anuragkapur.leetcode;

import org.junit.Test;

import static org.junit.Assert.*;

/**
 * @author anuragkapur
 */
public class ZigZagConversionTest {

    ZigZagConversion zigZagConversion = new ZigZagConversion();

    @Test
    public void testConvert0() throws Exception {
        assertEquals("PAYPALISHIRING", zigZagConversion.convert("PAYPALISHIRING", 1));
        assertEquals("", zigZagConversion.convert("", 4));
        assertEquals(null, zigZagConversion.convert(null, 4));
    }

    @Test
    public void testConvert1() throws Exception {
        assertEquals("PAHNAPLSIIGYIR", zigZagConversion.convert("PAYPALISHIRING", 3));
    }
}


text:
using Kirinji.LightWands;
using Kirinji.LinqToObservableCollection.Impl;
using Kirinji.LinqToObservableCollection.Impl.Producers;
using Kirinji.LinqToObservableCollection.SimpleNotifyCollectionChangedEvents;
using Kirinji.LinqToObservableCollection.SlimNotifyCollectionChangedEvents;
using Kirinji.LinqToObservableCollection.SlimSimpleNotifyCollectionChangedEvents;
using Kirinji.LinqToObservableCollection.Support;
using System;
using System.Collections.Generic;
using System.Collections.ObjectModel;
using System.Collections.Specialized;
using System.Diagnostics.Contracts;
using System.Linq;
using System.Reactive.Disposables;
using System.Reactive.Linq;
using System.Text;
using System.Threading;
using System.Threading.Tasks;

namespace Kirinji.LinqToObservableCollection.Support
{
    internal static partial class Extensions
    {
        public static void ApplyChangeEvent<T>(this MultiValuesObservableCollection<T> collection, INotifyCollectionChangedEvent<T> e)
        {
            Contract.Requires<ArgumentNullException>(collection != null);
            Contract.Requires<ArgumentNullException>(e != null);

            switch (e.Action)
            {
                case NotifyCollectionChangedEventAction.InitialState:
                    {
                        collection.Clear();
                        if (e.InitialState.Items != null)
                        {
                            collection.AddRange(e.InitialState.Items);
                        }
                        return;
                    }
                case NotifyCollectionChangedEventAction.Add:
                    {
                        int insertingIndex = e.Added.StartingIndex;
                        if (insertingIndex <= -1)
                        {
                            collection.AddRange(e.Added.Items);
                        }
                        else
                        {
                            try
                            {
                                collection.Insert(insertingIndex, e.Added.Items);
                            }
                            catch (IndexOutOfRangeException)
                            {
                                throw new InvalidInformationException<T>(InvalidInformationExceptionType.InvalidIndex, e);
                            }
                            catch (ArgumentOutOfRangeException)
                            {
                                throw new InvalidInformationException<T>(InvalidInformationExceptionType.InvalidIndex, e);
                            }
                        }
                        return;
                    }
                case NotifyCollectionChangedEventAction.Move:
                    {
                        try
                        {
                            collection.Move(e.Moved.OldStartingIndex, e.Moved.NewStartingIndex, e.Moved.Items.Count);
                        }
                        catch (IndexOutOfRangeException)
                        {
                            throw new InvalidInformationException<T>(InvalidInformationExceptionType.InvalidIndex, e);
                        }
                        catch (ArgumentOutOfRangeException)
                        {
                            throw new InvalidInformationException<T>(InvalidInformationExceptionType.InvalidIndex, e);
                        }

                        return;
                    }
                case NotifyCollectionChangedEventAction.Remove:
                    {
                        if (e.Removed.StartingIndex <= -1)
                        {
                            try
                            {
                                collection.RemoveAt(collection.Count - e.Removed.Items.Count, e.Removed.Items.Count);
                            }
                            catch (IndexOutOfRangeException)
                            {
                                throw new InvalidInformationException<T>(InvalidInformationExceptionType.InvalidIndex, e);
                            }
                            catch (ArgumentOutOfRangeException)
                            {
                                throw new InvalidInformationException<T>(InvalidInformationExceptionType.InvalidIndex, e);
                            }
                        }
                        else
                        {
                            try
                            {
                                collection.RemoveAt(e.Removed.StartingIndex, e.Removed.Items.Count);
                            }
                            catch (IndexOutOfRangeException)
                            {
                                throw new InvalidInformationException<T>(InvalidInformationExceptionType.InvalidIndex, e);
                            }
                            catch (ArgumentOutOfRangeException)
                            {
                                throw new InvalidInformationException<T>(InvalidInformationExceptionType.InvalidIndex, e);
                            }
                        }
                        return;
                    }
                case NotifyCollectionChangedEventAction.Replace:
                    {
                        try
                        {
                            collection.Replace(e.Replaced.StartingIndex, e.Replaced.OldItems.Count, e.Replaced.NewItems);
                        }
                        catch (IndexOutOfRangeException)
                        {
                            throw new InvalidInformationException<T>(InvalidInformationExceptionType.InvalidIndex, e);
                        }
                        catch (ArgumentOutOfRangeException)
                        {
                            throw new InvalidInformationException<T>(InvalidInformationExceptionType.InvalidIndex, e);
                        }
                        return;
                    }
                case NotifyCollectionChangedEventAction.Reset:
                    {
                        if (e.Reset.Items != null)
                        {
                            collection.Reset(e.Reset.Items);
                        }
                        else
                        {
                            collection.Clear();
                        }

                        return;
                    }
            }
        }

        // returns infomation-filled events
        public static IReadOnlyList<INotifyCollectionChangedEvent<T>> ApplyChangeEvent<T>(this IList<T> collection, INotifyCollectionChangedEvent<T> e, bool checkRemovingItemsEquality = false, IEqualityComparer<T> removingItemsEqualityComparer = null)
        {
            Contract.Requires<ArgumentNullException>(collection != null);
            Contract.Requires<ArgumentNullException>(e != null);
            Contract.Ensures(Contract.Result<IReadOnlyList<INotifyCollectionChangedEvent<T>>>() != null);
            Contract.Ensures(Contract.ForAll(Contract.Result<IReadOnlyList<INotifyCollectionChangedEvent<T>>>(), x => x != null));

            var removingItemsEqualityComparerNotNull = removingItemsEqualityComparer ?? EqualityComparer<T>.Default;

            // filter to ensure (Old|New)Items.Count >= 1
            INotifyCollectionChangedEvent<T> filteredEvent;
            switch (e.Action)
            {
                case NotifyCollectionChangedEventAction.InitialState:
                    filteredEvent = e;
                    break;
                case NotifyCollectionChangedEventAction.Add:
                    if (e.Added.Items.Count == 0)
                    {
                        return new INotifyCollectionChangedEvent<T>[0];
                    }
                    filteredEvent = e;
                    break;
                case NotifyCollectionChangedEventAction.Remove:
                    if (e.Removed.Items.Count == 0)
                    {
                        return new INotifyCollectionChangedEvent<T>[0];
                    }
                    filteredEvent = e;
                    break;
                case NotifyCollectionChangedEventAction.Move:
                    if (e.Moved.Items.Count == 0)
                    {
                        return new INotifyCollectionChangedEvent<T>[0];
                    }
                    filteredEvent = e;
                    break;
                case NotifyCollectionChangedEventAction.Replace:
                    if (e.Replaced.OldItems.Count == 0 && e.Replaced.NewItems.Count == 0)
                    {
                        return new INotifyCollectionChangedEvent<T>[0];
                    }
                    else if (e.Replaced.OldItems.Count == 0)
                    {
                        filteredEvent = NotifyCollectionChangedEvent.CreateAddedEvent(e.Replaced.NewItems, e.Replaced.StartingIndex);
                    }
                    else if (e.Replaced.NewItems.Count == 0)
                    {
                        filteredEvent = NotifyCollectionChangedEvent.CreateRemovedEvent(e.Replaced.OldItems, e.Replaced.StartingIndex);
                    }
                    else
                    {
                        filteredEvent = e;
                    }
                    break;
                case NotifyCollectionChangedEventAction.Reset:
                    filteredEvent = e;
                    break;
                default:
                    throw Exceptions.UnpredictableSwitchCasePattern;
            }

            switch (filteredEvent.Action)
            {
                case NotifyCollectionChangedEventAction.InitialState:
                    {
                        collection.Clear();
                        if (filteredEvent.InitialState.Items != null)
                        {
                            collection.AddRange(filteredEvent.InitialState.Items);
                        }
                        return new[] { filteredEvent }.ToReadOnly();
                    }
                case NotifyCollectionChangedEventAction.Add:
                    {
                        int insertingIndex = filteredEvent.Added.StartingIndex < 0 ? collection.Count : filteredEvent.Added.StartingIndex;
                        try
                        {
                            collection.InsertRange(insertingIndex, filteredEvent.Added.Items);
                        }
                        catch (IndexOutOfRangeException)
                        {
                            throw new InvalidInformationException<T>(InvalidInformationExceptionType.InvalidIndex, filteredEvent);
                        }
                        catch (ArgumentOutOfRangeException)
                        {
                            throw new InvalidInformationException<T>(InvalidInformationExceptionType.InvalidIndex, filteredEvent);
                        }
                        return new[] { NotifyCollectionChangedEvent.CreateAddedEvent(filteredEvent.Added.Items, insertingIndex) }.ToReadOnly();
                    }
                case NotifyCollectionChangedEventAction.Move:
                    {
                        if (e.Moved.OldStartingIndex == e.Moved.NewStartingIndex && !checkRemovingItemsEquality)
                        {
                            return new INotifyCollectionChangedEvent<T>[0];
                        }

                        ReadOnlyCollection<T> movedItems;
                        try
                        {
                            movedItems = collection.MoveRange(filteredEvent.Moved.OldStartingIndex, filteredEvent.Moved.NewStartingIndex, filteredEvent.Moved.Items.Count);
                        }
                        catch (IndexOutOfRangeException)
                        {
                            throw new InvalidInformationException<T>(InvalidInformationExceptionType.InvalidIndex, filteredEvent);
                        }
                        catch (ArgumentOutOfRangeException)
                        {
                            throw new InvalidInformationException<T>(InvalidInformationExceptionType.InvalidIndex, filteredEvent);
                        }

                        if (checkRemovingItemsEquality)
                        {
                            if (!movedItems.SequenceEqual(filteredEvent.Moved.Items, removingItemsEqualityComparerNotNull))
                            {
                                throw new InvalidInformationException<T>(InvalidInformationExceptionType.InvalidItem, filteredEvent);
                            }
                        }

                        if (e.Moved.OldStartingIndex == e.Moved.NewStartingIndex)
                        {
                            return new INotifyCollectionChangedEvent<T>[0];
                        }
                        else
                        {
                            return new[] { filteredEvent }.ToReadOnly();
                        }
                    }
                case NotifyCollectionChangedEventAction.Remove:
                    {
                        if (filteredEvent.Removed.StartingIndex <= -1)
                        {
                            IEnumerable<IRemoved<T>> removed;
                            try
                            {
                                removed = FindAndRemove(collection, filteredEvent.Removed.Items, removingItemsEqualityComparerNotNull);
                            }
                            catch (IndexOutOfRangeException)
                            {
                                throw new InvalidInformationException<T>(InvalidInformationExceptionType.InvalidIndex, filteredEvent);
                            }
                            catch (ArgumentOutOfRangeException)
                            {
                                throw new InvalidInformationException<T>(InvalidInformationExceptionType.InvalidIndex, filteredEvent);
                            }

                            return removed
                                .Select(r => NotifyCollectionChangedEvent.ToEvent(r))
                                .ToArray()
                                .ToReadOnly();
                        }
                        else
                        {
                            ReadOnlyCollection<T> removedItems;
                            try
                            {
                                removedItems = collection.RemoveAtRange(filteredEvent.Removed.StartingIndex, filteredEvent.Removed.Items.Count);
                            }
                            catch (IndexOutOfRangeException)
                            {
                                throw new InvalidInformationException<T>(InvalidInformationExceptionType.InvalidIndex, filteredEvent);
                            }
                            catch (ArgumentOutOfRangeException)
                            {
                                throw new InvalidInformationException<T>(InvalidInformationExceptionType.InvalidIndex, filteredEvent);
                            }

                            if (checkRemovingItemsEquality)
                            {
                                if (!removedItems.SequenceEqual(filteredEvent.Removed.Items, removingItemsEqualityComparerNotNull))
                                {
                                    throw new InvalidInformationException<T>(InvalidInformationExceptionType.InvalidItem, filteredEvent);
                                }
                            }
                            return new[] { filteredEvent }.ToReadOnly();
                        }
                    }
                case NotifyCollectionChangedEventAction.Replace:
                    {
                        if (filteredEvent.Replaced.StartingIndex < 0)
                        {
                            IReadOnlyList<IRemoved<T>> removed;
                            try
                            {
                                removed = FindAndRemove(collection, filteredEvent.Replaced.OldItems, removingItemsEqualityComparerNotNull).ToArray();
                            }
                            catch (IndexOutOfRangeException)
                            {
                                throw new InvalidInformationException<T>(InvalidInformationExceptionType.InvalidIndex, filteredEvent);
                            }
                            catch (ArgumentOutOfRangeException)
                            {
                                throw new InvalidInformationException<T>(InvalidInformationExceptionType.InvalidIndex, filteredEvent);
                            }

                            if (removed.Count >= 2)
                            {
                                throw new InvalidInformationException<T>(InvalidInformationExceptionType.InvalidItem, filteredEvent);
                            }

                            try
                            {
                                collection.InsertRange(removed.Single().StartingIndex, filteredEvent.Replaced.NewItems);
                            }
                            catch (IndexOutOfRangeException)
                            {
                                throw new InvalidInformationException<T>(InvalidInformationExceptionType.InvalidIndex, filteredEvent);
                            }
                            catch (ArgumentOutOfRangeException)
                            {
                                throw new InvalidInformationException<T>(InvalidInformationExceptionType.InvalidIndex, filteredEvent);
                            }

                            var replaced = NotifyCollectionChangedEvent.CreateReplacedEvent(filteredEvent.Replaced.OldItems, filteredEvent.Replaced.NewItems, removed.Single().StartingIndex);
                            return new[] { replaced }.ToReadOnly();
                        }
                        else
                        {
                            ReadOnlyCollection<T> removedItems;
                            try
                            {
                                removedItems = collection.RemoveAtRange(filteredEvent.Replaced.StartingIndex, filteredEvent.Replaced.OldItems.Count);
                            }
                            catch (IndexOutOfRangeException)
                            {
                                throw new InvalidInformationException<T>(InvalidInformationExceptionType.InvalidIndex, filteredEvent);
                            }
                            catch (ArgumentOutOfRangeException)
                            {
                                throw new InvalidInformationException<T>(InvalidInformationExceptionType.InvalidIndex, filteredEvent);
                            }

                            if (checkRemovingItemsEquality)
                            {
                                if (!removedItems.SequenceEqual(filteredEvent.Replaced.OldItems, removingItemsEqualityComparerNotNull))
                                {
                                    throw new InvalidInformationException<T>(InvalidInformationExceptionType.InvalidItem, filteredEvent);
                                }
                            }
                            try
                            {
                                collection.InsertRange(filteredEvent.Replaced.StartingIndex, filteredEvent.Replaced.NewItems);
                            }
                            catch (IndexOutOfRangeException)
                            {
                                throw new InvalidInformationException<T>(InvalidInformationExceptionType.InvalidIndex, filteredEvent);
                            }
                            catch (ArgumentOutOfRangeException)
                            {
                                throw new InvalidInformationException<T>(InvalidInformationExceptionType.InvalidIndex, filteredEvent);
                            }

                            return new[] { filteredEvent }.ToReadOnly();
                        }
                    }
                case NotifyCollectionChangedEventAction.Reset:
                    {
                        collection.Clear();
                        collection.AddRange(filteredEvent.Reset.Items);

                        return new[] { filteredEvent }.ToReadOnly();
                    }
                default:
                    throw Exceptions.UnpredictableSwitchCasePattern;
            }
        }

        public static void ApplySlimChangeEvent<T>(this MultiValuesObservableCollection<T> collection, SlimNotifyCollectionChangedEvent<T> e)
        {
            Contract.Requires<ArgumentNullException>(collection != null);
            Contract.Requires<ArgumentNullException>(e != null);

            switch (e.Action)
            {
                case NotifyCollectionChangedEventAction.InitialState:
                    {
                        collection.Clear();
                        collection.AddRange(e.InitialState.Items);
                        return;
                    }
                case NotifyCollectionChangedEventAction.Add:
                    {
                        try
                        {
                            collection.Insert(e.Added.StartingIndex, e.Added.Items);
                        }
                        catch (IndexOutOfRangeException)
                        {
                            throw new InvalidInformationException<T>(InvalidInformationExceptionType.InvalidIndex);
                        }
                        catch (ArgumentOutOfRangeException)
                        {
                            throw new InvalidInformationException<T>(InvalidInformationExceptionType.InvalidIndex);
                        }

                        return;
                    }
                case NotifyCollectionChangedEventAction.Move:
                    {
                        try
                        {
                            collection.Move(e.Moved.OldStartingIndex, e.Moved.NewStartingIndex, e.Moved.ItemsCount);
                        }
                        catch (IndexOutOfRangeException)
                        {
                            throw new InvalidInformationException<T>(InvalidInformationExceptionType.InvalidIndex);
                        }
                        catch (ArgumentOutOfRangeException)
                        {
                            throw new InvalidInformationException<T>(InvalidInformationExceptionType.InvalidIndex);
                        }

                        return;
                    }
                case NotifyCollectionChangedEventAction.Remove:
                    {
                        try
                        {
                            collection.RemoveAt(e.Removed.StartingIndex, e.Removed.ItemsCount);
                        }
                        catch (IndexOutOfRangeException)
                        {
                            throw new InvalidInformationException<T>(InvalidInformationExceptionType.InvalidIndex);
                        }
                        catch (ArgumentOutOfRangeException)
                        {
                            throw new InvalidInformationException<T>(InvalidInformationExceptionType.InvalidIndex);

                        }
                        return;
                    }
                case NotifyCollectionChangedEventAction.Replace:
                    {
                        try
                        {
                            collection.Replace(e.Replaced.StartingIndex, e.Replaced.OldItemsCount, e.Replaced.NewItems);
                        }
                        catch (IndexOutOfRangeException)
                        {
                            throw new InvalidInformationException<T>(InvalidInformationExceptionType.InvalidIndex);
                        }
                        catch (ArgumentOutOfRangeException)
                        {
                            throw new InvalidInformationException<T>(InvalidInformationExceptionType.InvalidIndex);
                        }
                        return;
                    }
                case NotifyCollectionChangedEventAction.Reset:
                    {
                        collection.Reset(e.Reset.Items);

                        return;
                    }
            }
        }

        public static void ApplySlimChangeEvent<T>(this IList<T> collection, SlimNotifyCollectionChangedEvent<T> e)
        {
            Contract.Requires<ArgumentNullException>(collection != null);
            Contract.Requires<ArgumentNullException>(e != null);

            switch (e.Action)
            {
                case NotifyCollectionChangedEventAction.InitialState:
                    {
                        collection.Clear();
                        collection.AddRange(e.InitialState.Items);
                        return;
                    }
                case NotifyCollectionChangedEventAction.Add:
                    {
                        try
                        {
                            collection.InsertRange(e.Added.StartingIndex, e.Added.Items);
                        }
                        catch (IndexOutOfRangeException)
                        {
                            throw new InvalidInformationException<T>(InvalidInformationExceptionType.InvalidIndex);
                        }
                        catch (ArgumentOutOfRangeException)
                        {
                            throw new InvalidInformationException<T>(InvalidInformationExceptionType.InvalidIndex);
                        }

                        return;
                    }
                case NotifyCollectionChangedEventAction.Move:
                    {
                        try
                        {
                            collection.MoveRange(e.Moved.OldStartingIndex, e.Moved.NewStartingIndex, e.Moved.ItemsCount);
                        }
                        catch (IndexOutOfRangeException)
                        {
                            throw new InvalidInformationException<T>(InvalidInformationExceptionType.InvalidIndex);
                        }
                        catch (ArgumentOutOfRangeException)
                        {
                            throw new InvalidInformationException<T>(InvalidInformationExceptionType.InvalidIndex);
                        }

                        return;
                    }
                case NotifyCollectionChangedEventAction.Remove:
                    {
                        try
                        {
                            collection.RemoveAtRange(e.Removed.StartingIndex, e.Removed.ItemsCount);
                        }
                        catch (IndexOutOfRangeException)
                        {
                            throw new InvalidInformationException<T>(InvalidInformationExceptionType.InvalidIndex);
                        }
                        catch (ArgumentOutOfRangeException)
                        {
                            throw new InvalidInformationException<T>(InvalidInformationExceptionType.InvalidIndex);

                        }
                        return;
                    }
                case NotifyCollectionChangedEventAction.Replace:
                    {
                        try
                        {
                            collection.RemoveAtRange(e.Replaced.StartingIndex, e.Replaced.OldItemsCount);
                            collection.InsertRange(e.Replaced.StartingIndex, e.Replaced.NewItems);
                        }
                        catch (IndexOutOfRangeException)
                        {
                            throw new InvalidInformationException<T>(InvalidInformationExceptionType.InvalidIndex);
                        }
                        catch (ArgumentOutOfRangeException)
                        {
                            throw new InvalidInformationException<T>(InvalidInformationExceptionType.InvalidIndex);
                        }
                        return;
                    }
                case NotifyCollectionChangedEventAction.Reset:
                    {
                        collection.Clear();
                        collection.AddRange(e.Reset.Items);

                        return;
                    }
            }
        }

        public static SimpleNotifyCollectionChangedEvent<T> ApplySimpleChangeEvent<T>(this IList<Tagged<T>> collection, SimpleNotifyCollectionChangedEvent<T> e, bool checkRemovingItemsEquality = false)
        {
            Contract.Requires<ArgumentNullException>(collection != null);
            Contract.Requires<ArgumentNullException>(e != null);
            Contract.Ensures(Contract.Result<SimpleNotifyCollectionChangedEvent<T>>() != null);

            switch (e.Action)
            {
                case SimpleNotifyCollectionChangedEventAction.InitialState:
                    {
                        collection.Clear();
                        collection.AddRange(e.InitialStateOrReset);

                        return e;
                    }
                case SimpleNotifyCollectionChangedEventAction.AddOrRemove:
                    {
                        var result = new List<AddedOrRemovedUnit<T>>();

                        foreach (var i in e.AddedOrRemoved)
                        {
                            if (i.Type == AddOrRemoveUnitType.Add)
                            {
                                try
                                {
                                    collection.Insert(i.Index, i.Item);
                                }
                                catch (IndexOutOfRangeException)
                                {
                                    throw new InvalidInformationException<T>(InvalidInformationExceptionType.InvalidIndex, e);
                                }
                                catch (ArgumentOutOfRangeException)
                                {
                                    throw new InvalidInformationException<T>(InvalidInformationExceptionType.InvalidIndex, e);
                                }
                                result.Add(i);
                            }
                            else
                            {
                                Tagged<T> removing;
                                try
                                {
                                    removing = collection[i.Index];
                                }
                                catch (IndexOutOfRangeException)
                                {
                                    throw new InvalidInformationException<T>(InvalidInformationExceptionType.InvalidIndex, e);
                                }
                                catch (ArgumentOutOfRangeException)
                                {
                                    throw new InvalidInformationException<T>(InvalidInformationExceptionType.InvalidIndex, e);
                                }

                                if (checkRemovingItemsEquality && !Object.Equals(removing.Item, i.Item.Item))
                                {
                                    throw new InvalidInformationException<T>(InvalidInformationExceptionType.InvalidItem, e);
                                }

                                collection.RemoveAt(i.Index);

                                if (i.Item == null)
                                {
                                    result.Add(new AddedOrRemovedUnit<T>(AddOrRemoveUnitType.Remove, removing, i.Index));
                                }
                                else
                                {
                                    result.Add(i);
                                }

                            }
                        }

                        return SimpleNotifyCollectionChangedEvent<T>.CreateAddOrRemove(result.ToReadOnly());
                    }
                case SimpleNotifyCollectionChangedEventAction.Reset:
                    {
                        collection.Clear();
                        collection.AddRange(e.InitialStateOrReset);

                        return e;
                    }
                default:
                    throw Exceptions.UnpredictableSwitchCasePattern;
            }
        }

        public static void ApplySimpleChangeEventWithoutTag<T>(this IList<T> collection, SimpleNotifyCollectionChangedEvent<T> e)
        {
            Contract.Requires<ArgumentNullException>(collection != null);
            Contract.Requires<ArgumentNullException>(e != null);

            switch (e.Action)
            {
                case SimpleNotifyCollectionChangedEventAction.InitialState:
                    {
                        collection.Clear();
                        collection.AddRange(e.InitialStateOrReset.Select(tagged => tagged.Item));

                        return;
                    }
                case SimpleNotifyCollectionChangedEventAction.AddOrRemove:
                    {
                        foreach (var i in e.AddedOrRemoved)
                        {
                            if (i.Type == AddOrRemoveUnitType.Add)
                            {
                                try
                                {
                                    collection.Insert(i.Index, i.Item.Item);
                                }
                                catch (IndexOutOfRangeException)
                                {
                                    throw new InvalidInformationException<T>(InvalidInformationExceptionType.InvalidIndex, e);
                                }
                                catch (ArgumentOutOfRangeException)
                                {
                                    throw new InvalidInformationException<T>(InvalidInformationExceptionType.InvalidIndex, e);
                                }
                            }
                            else
                            {
                                try
                                {
                                    collection.RemoveAt(i.Index);
                                }
                                catch (IndexOutOfRangeException)
                                {
                                    throw new InvalidInformationException<T>(InvalidInformationExceptionType.InvalidIndex, e);
                                }
                                catch (ArgumentOutOfRangeException)
                                {
                                    throw new InvalidInformationException<T>(InvalidInformationExceptionType.InvalidIndex, e);
                                }
                            }
                        }

                        return;
                    }
                case SimpleNotifyCollectionChangedEventAction.Reset:
                    {
                        collection.Clear();
                        collection.AddRange(e.InitialStateOrReset.Select(tagged => tagged.Item));

                        return;
                    }
                default:
                    throw Exceptions.UnpredictableSwitchCasePattern;
            }
        }

        public static void ApplySlimSimpleChangeEvent<T>(this IList<Tagged<T>> collection, SlimSimpleNotifyCollectionChangedEvent<T> e)
        {
            Contract.Requires<ArgumentNullException>(collection != null);
            Contract.Requires<ArgumentNullException>(e != null);

            switch (e.Action)
            {
                case SlimSimpleNotifyCollectionChangedEventAction.InitialState:
                    {
                        collection.Clear();
                        collection.AddRange(e.InitialStateOrReset);

                        return;
                    }
                case SlimSimpleNotifyCollectionChangedEventAction.AddOrRemove:
                    {
                        foreach (var i in e.AddedOrRemoved)
                        {
                            if (i.Type == SlimAddOrRemoveUnitType.Add)
                            {
                                try
                                {
                                    collection.Insert(i.Index, i.Item);
                                }
                                catch (IndexOutOfRangeException)
                                {
                                    throw new InvalidInformationException<T>(InvalidInformationExceptionType.InvalidIndex);
                                }
                                catch (ArgumentOutOfRangeException)
                                {
                                    throw new InvalidInformationException<T>(InvalidInformationExceptionType.InvalidIndex);
                                }
                            }
                            else
                            {
                                try
                                {
                                    collection.RemoveAt(i.Index);
                                }
                                catch (IndexOutOfRangeException)
                                {
                                    throw new InvalidInformationException<T>(InvalidInformationExceptionType.InvalidIndex);
                                }
                                catch (ArgumentOutOfRangeException)
                                {
                                    throw new InvalidInformationException<T>(InvalidInformationExceptionType.InvalidIndex);
                                }
                            }
                        }

                        return;
                    }
                case SlimSimpleNotifyCollectionChangedEventAction.Reset:
                    {
                        collection.Clear();
                        collection.AddRange(e.InitialStateOrReset);

                        return;
                    }
                default:
                    throw Exceptions.UnpredictableSwitchCasePattern;
            }
        }

        public static void ApplySlimSimpleChangeEventWithoutTag<T>(this IList<T> collection, SlimSimpleNotifyCollectionChangedEvent<T> e)
        {
            Contract.Requires<ArgumentNullException>(collection != null);
            Contract.Requires<ArgumentNullException>(e != null);

            switch (e.Action)
            {
                case SlimSimpleNotifyCollectionChangedEventAction.InitialState:
                    {
                        collection.Clear();
                        collection.AddRange(e.InitialStateOrReset.Select(tagged => tagged.Item));

                        return;
                    }
                case SlimSimpleNotifyCollectionChangedEventAction.AddOrRemove:
                    {
                        foreach (var i in e.AddedOrRemoved)
                        {
                            if (i.Type == SlimAddOrRemoveUnitType.Add)
                            {
                                try
                                {
                                    collection.Insert(i.Index, i.Item.Item);
                                }
                                catch (IndexOutOfRangeException)
                                {
                                    throw new InvalidInformationException<T>(InvalidInformationExceptionType.InvalidIndex);
                                }
                                catch (ArgumentOutOfRangeException)
                                {
                                    throw new InvalidInformationException<T>(InvalidInformationExceptionType.InvalidIndex);
                                }
                            }
                            else
                            {
                                try
                                {
                                    collection.RemoveAt(i.Index);
                                }
                                catch (IndexOutOfRangeException)
                                {
                                    throw new InvalidInformationException<T>(InvalidInformationExceptionType.InvalidIndex);
                                }
                                catch (ArgumentOutOfRangeException)
                                {
                                    throw new InvalidInformationException<T>(InvalidInformationExceptionType.InvalidIndex);
                                }
                            }
                        }

                        return;
                    }
                case SlimSimpleNotifyCollectionChangedEventAction.Reset:
                    {
                        collection.Clear();
                        collection.AddRange(e.InitialStateOrReset.Select(tagged => tagged.Item));

                        return;
                    }
                default:
                    throw Exceptions.UnpredictableSwitchCasePattern;
            }
        }

        public static IEnumerable<IRemoved<T>> FindAndRemove<T>(IList<T> collection, IEnumerable<T> removingItems, IEqualityComparer<T> comparer = null)
        {
            Contract.Requires<ArgumentNullException>(collection != null);
            Contract.Requires<ArgumentNullException>(removingItems != null);
            Contract.Ensures(Contract.Result<IEnumerable<IRemoved<T>>>() != null);

            var comparerNotNull = comparer ?? EqualityComparer<T>.Default;
            var collectionBackup = collection.ToArray();

            var removingIndexesAndItems = new List<Tuple<int, T>>();
            foreach (var ri in removingItems)
            {
                var removingIndex = collection.FirstIndex(item => comparerNotNull.Equals(ri, item));
                if (removingIndex == null)
                {
                    collection.Clear();
                    collection.AddRange(collectionBackup);
                    throw new InvalidOperationException();
                }
                var removeingItem = collection[removingIndex.Value];
                collection.RemoveAt(removingIndex.Value);
                removingIndexesAndItems.Add(Tuple.Create(removingIndex.Value, removeingItem));
            }

            var itemsQueue = new List<T>();
            int lastIndex = -1;
            foreach (var tuple in removingIndexesAndItems)
            {
                if (lastIndex == tuple.Item1)
                {
                    itemsQueue.Add(tuple.Item2);
                }
                else if (lastIndex < 0)
                {
                    lastIndex = tuple.Item1;
                    itemsQueue.Add(tuple.Item2);
                }
                else
                {
                    yield return NotifyCollectionChangedEvent.CreateRemoved(itemsQueue.ToArray().ToReadOnly(), lastIndex);
                    itemsQueue.Clear();
                    itemsQueue.Add(tuple.Item2);
                    lastIndex = tuple.Item1;
                }
            }

            if (lastIndex >= 0)
            {
                yield return NotifyCollectionChangedEvent.CreateRemoved(itemsQueue.ToArray().ToReadOnly(), lastIndex);
            }
        }
    }
}


text:
class ProjectsController < ApplicationController

	before_filter :may_create_projects_required,
		:only => [:new,:create]
	before_filter :may_read_projects_required,
		:only => [:show,:index]
	before_filter :may_update_projects_required,
		:only => [:edit,:update]
	before_filter :may_destroy_projects_required,
		:only => :destroy

	before_filter :valid_id_required,
		:only => [:show,:edit,:update,:destroy]

	def index
		@projects = Project.order('position')
	end

	def new
		@project = Project.new
	end

	def create
		@project = Project.new(project_params)
		@project.save!
		flash[:notice] = 'Success!'
		redirect_to @project
	rescue ActiveRecord::RecordNotSaved, ActiveRecord::RecordInvalid
		flash.now[:error] = "There was a problem creating " <<
			"the project"
		render :action => "new"
	end

	def update
		@project.update_attributes!(project_params)
		flash[:notice] = 'Success!'
		redirect_to projects_path
	rescue ActiveRecord::RecordNotSaved, ActiveRecord::RecordInvalid
		flash.now[:error] = "There was a problem updating " <<
			"the project"
		render :action => "edit"
	end

	def destroy
		@project.destroy
		redirect_to projects_path
	end

protected

	def valid_id_required
		if( !params[:id].blank? && Project.exists?(params[:id]) )
			@project = Project.find(params[:id])
		else
			access_denied("Valid id required!", projects_path)
		end
	end

	def project_params
		params.require(:project).permit(:key,:label,:description)
	end

end


text:
cob="$1"

git clone https://github.com/ray-project/ray.git ray
pushd ray || true
git checkout "$cob"

bash ./ci/travis/install-bazel.sh
BAZEL_PATH=$HOME/bin/bazel

# Run all test cases, but with a forced num_gpus=1 (--test_env=RLLIB_NUM_GPUS=1).
$BAZEL_PATH test --config=ci $(./scripts/bazel_export_options) --build_tests_only --test_tag_filters=examples_A,examples_B --test_env=RAY_USE_MULTIPROCESSING_CPU_COUNT=1 --test_env=RLLIB_NUM_GPUS=1 rllib/...
$BAZEL_PATH test --config=ci $(./scripts/bazel_export_options) --build_tests_only --test_tag_filters=examples_C,examples_D --test_env=RAY_USE_MULTIPROCESSING_CPU_COUNT=1 --test_env=RLLIB_NUM_GPUS=1 rllib/...
$BAZEL_PATH test --config=ci $(./scripts/bazel_export_options) --build_tests_only --test_tag_filters=examples_E,examples_F,examples_G,examples_H,examples_I,examples_J,examples_K,examples_L,examples_M,examples_N,examples_O,examples_P --test_env=RAY_USE_MULTIPROCESSING_CPU_COUNT=1 --test_env=RLLIB_NUM_GPUS=1  rllib/...
$BAZEL_PATH test --config=ci $(./scripts/bazel_export_options) --build_tests_only --test_tag_filters=examples_Q,examples_R,examples_S,examples_T,examples_U,examples_V,examples_W,examples_X,examples_Y,examples_Z --test_env=RAY_USE_MULTIPROCESSING_CPU_COUNT=1 --test_env=RLLIB_NUM_GPUS=1 rllib/...

popd || true