text:
namespace syncer {

class MockConnectionManager : public ServerConnectionManager {
 public:
  class MidCommitObserver {
   public:
    virtual void Observe() = 0;

   protected:
    virtual ~MidCommitObserver() {}
  };

  MockConnectionManager(syncable::Directory*,
                        CancelationSignal* signal);
  virtual ~MockConnectionManager();

  // Overridden ServerConnectionManager functions.
  virtual bool PostBufferToPath(
      PostBufferParams*,
      const std::string& path,
      const std::string& auth_token,
      ScopedServerStatusWatcher* watcher) OVERRIDE;

  // Control of commit response.
  // NOTE: Commit callback is invoked only once then reset.
  void SetMidCommitCallback(const base::Closure& callback);
  void SetMidCommitObserver(MidCommitObserver* observer);

  // Set this if you want commit to perform commit time rename. Will request
  // that the client renames all commited entries, prepending this string.
  void SetCommitTimeRename(std::string prepend);

  // Generic versions of AddUpdate functions. Tests using these function should
  // compile for both the int64 and string id based versions of the server.
  // The SyncEntity returned is only valid until the Sync is completed
  // (e.g. with SyncShare.) It allows to add further entity properties before
  // sync, using SetLastXXX() methods and/or GetMutableLastUpdate().
  sync_pb::SyncEntity* AddUpdateDirectory(
      syncable::Id id,
      syncable::Id parent_id,
      std::string name,
      int64 version,
      int64 sync_ts,
      std::string originator_cache_guid,
      std::string originator_client_item_id);
  sync_pb::SyncEntity* AddUpdateBookmark(syncable::Id id,
                                         syncable::Id parent_id,
                                         std::string name,
                                         int64 version,
                                         int64 sync_ts,
                                         std::string originator_cache_guid,
                                         std::string originator_client_item_id);
  // Versions of the AddUpdate functions that accept integer IDs.
  sync_pb::SyncEntity* AddUpdateDirectory(
      int id,
      int parent_id,
      std::string name,
      int64 version,
      int64 sync_ts,
      std::string originator_cache_guid,
      std::string originator_client_item_id);
  sync_pb::SyncEntity* AddUpdateBookmark(int id,
                                         int parent_id,
                                         std::string name,
                                         int64 version,
                                         int64 sync_ts,
                                         std::string originator_cache_guid,
                                         std::string originator_client_item_id);
  // New protocol versions of the AddUpdate functions.
  sync_pb::SyncEntity* AddUpdateDirectory(
      std::string id,
      std::string parent_id,
      std::string name,
      int64 version,
      int64 sync_ts,
      std::string originator_cache_guid,
      std::string originator_client_item_id);
  sync_pb::SyncEntity* AddUpdateBookmark(std::string id,
                                         std::string parent_id,
                                         std::string name,
                                         int64 version,
                                         int64 sync_ts,
                                         std::string originator_cache_guid,
                                         std::string originator_client_item_id);
  // Versions of the AddUpdate function that accept specifics.
  sync_pb::SyncEntity* AddUpdateSpecifics(
      int id,
      int parent_id,
      std::string name,
      int64 version,
      int64 sync_ts,
      bool is_dir,
      int64 position,
      const sync_pb::EntitySpecifics& specifics);
  sync_pb::SyncEntity* AddUpdateSpecifics(
      int id,
      int parent_id,
      std::string name,
      int64 version,
      int64 sync_ts,
      bool is_dir,
      int64 position,
      const sync_pb::EntitySpecifics& specifics,
      std::string originator_cache_guid,
      std::string originator_client_item_id);
  sync_pb::SyncEntity* SetNigori(
      int id,
      int64 version,
      int64 sync_ts,
      const sync_pb::EntitySpecifics& specifics);
  // Unique client tag variant for adding items.
  sync_pb::SyncEntity* AddUpdatePref(std::string id,
                                     std::string parent_id,
                                     std::string client_tag,
                                     int64 version,
                                     int64 sync_ts);

  // Find the last commit sent by the client, and replay it for the next get
  // updates command.  This can be used to simulate the GetUpdates that happens
  // immediately after a successful commit.
  sync_pb::SyncEntity* AddUpdateFromLastCommit();

  // Add a deleted item.  Deletion records typically contain no
  // additional information beyond the deletion, and no specifics.
  // The server may send the originator fields.
  void AddUpdateTombstone(const syncable::Id& id);

  void SetLastUpdateDeleted();
  void SetLastUpdateServerTag(const std::string& tag);
  void SetLastUpdateClientTag(const std::string& tag);
  void SetLastUpdateOriginatorFields(const std::string& client_id,
                                     const std::string& entry_id);
  void SetLastUpdatePosition(int64 position_in_parent);
  void SetNewTimestamp(int ts);
  void SetChangesRemaining(int64 count);

  // Add a new batch of updates after the current one.  Allows multiple
  // GetUpdates responses to be buffered up, since the syncer may
  // issue multiple requests during a sync cycle.
  void NextUpdateBatch();

  void FailNextPostBufferToPathCall() { countdown_to_postbuffer_fail_ = 1; }
  void FailNthPostBufferToPathCall(int n) { countdown_to_postbuffer_fail_ = n; }

  void SetKeystoreKey(const std::string& key);

  void FailNonPeriodicGetUpdates() { fail_non_periodic_get_updates_ = true; }

  // Simple inspectors.
  bool client_stuck() const { return client_stuck_; }

  // warning: These take ownership of their input.
  void SetGUClientCommand(sync_pb::ClientCommand* command);
  void SetCommitClientCommand(sync_pb::ClientCommand* command);

  void SetTransientErrorId(syncable::Id);

  const std::vector<syncable::Id>& committed_ids() const {
    return committed_ids_;
  }
  const std::vector<sync_pb::CommitMessage*>& commit_messages() const {
    return commit_messages_.get();
  }
  const std::vector<sync_pb::CommitResponse*>& commit_responses() const {
    return commit_responses_.get();
  }
  // Retrieve the last sent commit message.
  const sync_pb::CommitMessage& last_sent_commit() const;

  // Retrieve the last returned commit response.
  const sync_pb::CommitResponse& last_commit_response() const;

  // Retrieve the last request submitted to the server (regardless of type).
  const sync_pb::ClientToServerMessage& last_request() const {
    return last_request_;
  }

  void set_conflict_all_commits(bool value) {
    conflict_all_commits_ = value;
  }
  void set_next_new_id(int value) {
    next_new_id_ = value;
  }
  void set_conflict_n_commits(int value) {
    conflict_n_commits_ = value;
  }

  void set_use_legacy_bookmarks_protocol(bool value) {
    use_legacy_bookmarks_protocol_ = value;
  }

  void set_store_birthday(std::string new_birthday) {
    // Multiple threads can set store_birthday_ in our tests, need to lock it to
    // ensure atomic read/writes and avoid race conditions.
    base::AutoLock lock(store_birthday_lock_);
    store_birthday_ = new_birthday;
  }

  // Retrieve the number of GetUpdates requests that the mock server has
  // seen since the last time this function was called.  Can be used to
  // verify that a GetUpdates actually did or did not happen after running
  // the syncer.
  int GetAndClearNumGetUpdatesRequests() {
    int result = num_get_updates_requests_;
    num_get_updates_requests_ = 0;
    return result;
  }

  // Expect that GetUpdates will request exactly the types indicated in
  // the bitset.
  void ExpectGetUpdatesRequestTypes(ModelTypeSet expected_filter) {
    expected_filter_ = expected_filter;
  }

  void SetServerReachable();

  void SetServerNotReachable();

  // Updates our internal state as if we had attempted a connection.  Does not
  // send notifications as a real connection attempt would.  This is useful in
  // cases where we're mocking out most of the code that performs network
  // requests.
  void UpdateConnectionStatus();

  void SetServerStatus(HttpResponse::ServerConnectionCode server_status);

  // Return by copy to be thread-safe.
  const std::string store_birthday() {
    base::AutoLock lock(store_birthday_lock_);
    return store_birthday_;
  }

  // Explicitly indicate that we will not be fetching some updates.
  void ClearUpdatesQueue() {
    update_queue_.clear();
  }

  // Locate the most recent update message for purpose of alteration.
  sync_pb::SyncEntity* GetMutableLastUpdate();

 private:
  sync_pb::SyncEntity* AddUpdateFull(syncable::Id id, syncable::Id parentid,
                                     std::string name, int64 version,
                                     int64 sync_ts,
                                     bool is_dir);
  sync_pb::SyncEntity* AddUpdateFull(std::string id,
                                     std::string parentid, std::string name,
                                     int64 version, int64 sync_ts,
                                     bool is_dir);
  sync_pb::SyncEntity* AddUpdateMeta(std::string id, std::string parentid,
                                    std::string name, int64 version,
                                    int64 sync_ts);

  // Functions to handle the various types of server request.
  void ProcessGetUpdates(sync_pb::ClientToServerMessage* csm,
                         sync_pb::ClientToServerResponse* response);
  void ProcessCommit(sync_pb::ClientToServerMessage* csm,
                     sync_pb::ClientToServerResponse* response_buffer);
  void ProcessClearData(sync_pb::ClientToServerMessage* csm,
                        sync_pb::ClientToServerResponse* response);
  void AddDefaultBookmarkData(sync_pb::SyncEntity* entity, bool is_folder);

  // Determine if one entry in a commit should be rejected with a conflict.
  bool ShouldConflictThisCommit();

  // Determine if the given item's commit request should be refused with
  // a TRANSIENT_ERROR response.
  bool ShouldTransientErrorThisId(syncable::Id id);

  // Generate a numeric position_in_parent value.  We use a global counter
  // that only decreases; this simulates new objects always being added to the
  // front of the ordering.
  int64 GeneratePositionInParent() {
    return next_position_in_parent_--;
  }

  // Get a mutable update response which will eventually be returned to the
  // client.
  sync_pb::GetUpdatesResponse* GetUpdateResponse();
  void ApplyToken();

  // Determine whether an progress marker array (like that sent in
  // GetUpdates.from_progress_marker) indicates that a particular ModelType
  // should be included.
  bool IsModelTypePresentInSpecifics(
      const google::protobuf::RepeatedPtrField<
          sync_pb::DataTypeProgressMarker>& filter,
      ModelType value);

  sync_pb::DataTypeProgressMarker const* GetProgressMarkerForType(
      const google::protobuf::RepeatedPtrField<
          sync_pb::DataTypeProgressMarker>& filter,
      ModelType value);

  // When false, we pretend to have network connectivity issues.
  bool server_reachable_;

  // All IDs that have been committed.
  std::vector<syncable::Id> committed_ids_;

  // List of IDs which should return a transient error.
  std::vector<syncable::Id> transient_error_ids_;

  // Control of when/if we return conflicts.
  bool conflict_all_commits_;
  int conflict_n_commits_;

  // Commit messages we've sent, and responses we've returned.
  ScopedVector<sync_pb::CommitMessage> commit_messages_;
  ScopedVector<sync_pb::CommitResponse> commit_responses_;

  // The next id the mock will return to a commit.
  int next_new_id_;

  // The store birthday we send to the client.
  std::string store_birthday_;
  base::Lock store_birthday_lock_;
  bool store_birthday_sent_;
  bool client_stuck_;
  std::string commit_time_rename_prepended_string_;

  // On each PostBufferToPath() call, we decrement this counter.  The call fails
  // iff we hit zero at that call.
  int countdown_to_postbuffer_fail_;

  // Our directory.  Used only to ensure that we are not holding the transaction
  // lock when performing network I/O.  Can be NULL if the test author is
  // confident this can't happen.
  syncable::Directory* directory_;

  // The updates we'll return to the next request.
  std::list<sync_pb::GetUpdatesResponse> update_queue_;
  base::Closure mid_commit_callback_;
  MidCommitObserver* mid_commit_observer_;

  // The keystore key we return for a GetUpdates with need_encryption_key set.
  std::string keystore_key_;

  // The AUTHENTICATE response we'll return for auth requests.
  sync_pb::AuthenticateResponse auth_response_;
  // What we use to determine if we should return SUCCESS or BAD_AUTH_TOKEN.
  std::string valid_auth_token_;

  // Whether we are faking a server mandating clients to throttle requests.
  // Protected by |response_code_override_lock_|.
  bool throttling_;

  // Whether we are failing all requests by returning
  // ClientToServerResponse::AUTH_INVALID.
  // Protected by |response_code_override_lock_|.
  bool fail_with_auth_invalid_;

  base::Lock response_code_override_lock_;

  // True if we are only accepting GetUpdatesCallerInfo::PERIODIC requests.
  bool fail_non_periodic_get_updates_;

  scoped_ptr<sync_pb::ClientCommand> gu_client_command_;
  scoped_ptr<sync_pb::ClientCommand> commit_client_command_;

  // The next value to use for the position_in_parent property.
  int64 next_position_in_parent_;

  // The default is to use the newer sync_pb::BookmarkSpecifics-style protocol.
  // If this option is set to true, then the MockConnectionManager will
  // use the older sync_pb::SyncEntity_BookmarkData-style protocol.
  bool use_legacy_bookmarks_protocol_;

  ModelTypeSet expected_filter_;

  int num_get_updates_requests_;

  std::string next_token_;

  sync_pb::ClientToServerMessage last_request_;

  DISALLOW_COPY_AND_ASSIGN(MockConnectionManager);
};

}  // namespace syncer

#endif  // SYNC_TEST_ENGINE_MOCK_CONNECTION_MANAGER_H_


text:
package org.apache.flink.table.data.columnar.vector.heap;

import org.apache.flink.annotation.Internal;
import org.apache.flink.table.data.columnar.vector.writable.WritableShortVector;

import java.util.Arrays;

/** This class represents a nullable short column vector. */
@Internal
public class HeapShortVector extends AbstractHeapVector implements WritableShortVector {

    private static final long serialVersionUID = -8278486456144676292L;

    public short[] vector;

    /**
     * Don't use this except for testing purposes.
     *
     * @param len the number of rows
     */
    public HeapShortVector(int len) {
        super(len);
        vector = new short[len];
    }

    @Override
    public short getShort(int i) {
        if (dictionary == null) {
            return vector[i];
        } else {
            return (short) dictionary.decodeToInt(dictionaryIds.vector[i]);
        }
    }

    @Override
    public void setShort(int i, short value) {
        vector[i] = value;
    }

    @Override
    public void fill(short value) {
        Arrays.fill(vector, value);
    }
}

redpajama_set_name: RedPajamaGithub


text:
A few shell scripts to facilitate docker use in local development

Docker is a very powerful tool in clustering and deployment, but when comes to local development, testing docker image may not necessarily be handy, especially with boot2docker on Windows or MacOS.

### docker-init.sh
docker-init will modify boot2docker image in VirtualBox and add a mountpoint to current path. The mountpoint name is visible in .boot2docker-path file.

This enables docker to attach current path as a volume, hence any changes to the files are immediately visible to docker container.

### docker-build.sh
docker-build is a simple script to clean, build and push docker containers.
```
docker-build.sh -p my-container
```
will build docker container based on Dockerfile in current path and push it with system timestamp as version number.

### docker-start.sh
docker-start.sh shows an example of using these scripts together with Dockerfile to set up an Apache/PHP/Mysql development environment.

### docker-entry.sh
When developing NodeJS applications, you want to see the changes without rebuilding the docker container (then you have to wait for the build, restart the container with all linked containers etc). docker-entry.sh will automatically restart the NodeJS application when it sees .restart file in its path.

For example, in Dockerfile,
```
CMD docker-entry.sh node app.js
```
will start the nodejs app when you run the container.
```
docker run -v //MOUNT_POINT_12345:/app -d my-container
```
Once you made changes to app.js and want to restart the application, simply create an empty file named .restart, and it will trigger a restart without the need to rebuild the container.
```
touch .restart
```


text:
// Copyright 2000-2019 JetBrains s.r.o. Use of this source code is governed by the Apache 2.0 license that can be found in the LICENSE file.
package org.jetbrains.plugins.github.api.data;

//region issues api model
/*
{
  "url": "https://api.github.com/repos/iasemenov/testing/issues/6",
  "repository_url": "https://api.github.com/repos/iasemenov/testing",
  "labels_url": "https://api.github.com/repos/iasemenov/testing/issues/6/labels{/name}",
  "comments_url": "https://api.github.com/repos/iasemenov/testing/issues/6/comments",
  "events_url": "https://api.github.com/repos/iasemenov/testing/issues/6/events",
  "html_url": "https://github.com/iasemenov/testing/issues/6",
  "id": 343648850,
  "node_id": "MDU6SXNzdWUzNDM2NDg4NTA=",
  "number": 6,
  "title": "test3",
  "user": {
    "login": "iasemenov",
    "id": 33097396,
    "node_id": "MDQ6VXNlcjMzMDk3Mzk2",
    "avatar_url": "https://avatars2.githubusercontent.com/u/33097396?v=4",
    "gravatar_id": "",
    "url": "https://api.github.com/users/iasemenov",
    "html_url": "https://github.com/iasemenov",
    "followers_url": "https://api.github.com/users/iasemenov/followers",
    "following_url": "https://api.github.com/users/iasemenov/following{/other_user}",
    "gists_url": "https://api.github.com/users/iasemenov/gists{/gist_id}",
    "starred_url": "https://api.github.com/users/iasemenov/starred{/owner}{/repo}",
    "subscriptions_url": "https://api.github.com/users/iasemenov/subscriptions",
    "organizations_url": "https://api.github.com/users/iasemenov/orgs",
    "repos_url": "https://api.github.com/users/iasemenov/repos",
    "events_url": "https://api.github.com/users/iasemenov/events{/privacy}",
    "received_events_url": "https://api.github.com/users/iasemenov/received_events",
    "type": "User",
    "site_admin": false
  },
  "labels": [],
  "state": "closed",
  "locked": false,
  "assignee": {
    "login": "iasemenov",
    "id": 33097396,
    "node_id": "MDQ6VXNlcjMzMDk3Mzk2",
    "avatar_url": "https://avatars2.githubusercontent.com/u/33097396?v=4",
    "gravatar_id": "",
    "url": "https://api.github.com/users/iasemenov",
    "html_url": "https://github.com/iasemenov",
    "followers_url": "https://api.github.com/users/iasemenov/followers",
    "following_url": "https://api.github.com/users/iasemenov/following{/other_user}",
    "gists_url": "https://api.github.com/users/iasemenov/gists{/gist_id}",
    "starred_url": "https://api.github.com/users/iasemenov/starred{/owner}{/repo}",
    "subscriptions_url": "https://api.github.com/users/iasemenov/subscriptions",
    "organizations_url": "https://api.github.com/users/iasemenov/orgs",
    "repos_url": "https://api.github.com/users/iasemenov/repos",
    "events_url": "https://api.github.com/users/iasemenov/events{/privacy}",
    "received_events_url": "https://api.github.com/users/iasemenov/received_events",
    "type": "User",
    "site_admin": false
  },
  "assignees": [
    {
      "login": "iasemenov",
      "id": 33097396,
      "node_id": "MDQ6VXNlcjMzMDk3Mzk2",
      "avatar_url": "https://avatars2.githubusercontent.com/u/33097396?v=4",
      "gravatar_id": "",
      "url": "https://api.github.com/users/iasemenov",
      "html_url": "https://github.com/iasemenov",
      "followers_url": "https://api.github.com/users/iasemenov/followers",
      "following_url": "https://api.github.com/users/iasemenov/following{/other_user}",
      "gists_url": "https://api.github.com/users/iasemenov/gists{/gist_id}",
      "starred_url": "https://api.github.com/users/iasemenov/starred{/owner}{/repo}",
      "subscriptions_url": "https://api.github.com/users/iasemenov/subscriptions",
      "organizations_url": "https://api.github.com/users/iasemenov/orgs",
      "repos_url": "https://api.github.com/users/iasemenov/repos",
      "events_url": "https://api.github.com/users/iasemenov/events{/privacy}",
      "received_events_url": "https://api.github.com/users/iasemenov/received_events",
      "type": "User",
      "site_admin": false
    }
  ],
  "milestone": null,
  "comments": 0,
  "created_at": "2018-07-23T14:07:48Z",
  "updated_at": "2018-07-23T17:05:21Z",
  "closed_at": "2018-07-23T17:05:21Z",
  "author_association": "OWNER",
  "body": "",
  "closed_by": {
    "login": "iasemenov",
    "id": 33097396,
    "node_id": "MDQ6VXNlcjMzMDk3Mzk2",
    "avatar_url": "https://avatars2.githubusercontent.com/u/33097396?v=4",
    "gravatar_id": "",
    "url": "https://api.github.com/users/iasemenov",
    "html_url": "https://github.com/iasemenov",
    "followers_url": "https://api.github.com/users/iasemenov/followers",
    "following_url": "https://api.github.com/users/iasemenov/following{/other_user}",
    "gists_url": "https://api.github.com/users/iasemenov/gists{/gist_id}",
    "starred_url": "https://api.github.com/users/iasemenov/starred{/owner}{/repo}",
    "subscriptions_url": "https://api.github.com/users/iasemenov/subscriptions",
    "organizations_url": "https://api.github.com/users/iasemenov/orgs",
    "repos_url": "https://api.github.com/users/iasemenov/repos",
    "events_url": "https://api.github.com/users/iasemenov/events{/privacy}",
    "received_events_url": "https://api.github.com/users/iasemenov/received_events",
    "type": "User",
    "site_admin": false
  }
}*/
//endregion
@SuppressWarnings("UnusedDeclaration")
public class GithubIssue extends GithubIssueBase {
  private GithubUser closedBy;
}


text:
package com.twitter.finagle.netty3

import com.twitter.io.Buf
import org.junit.runner.RunWith
import org.scalatest.FunSuite
import org.scalatest.junit.JUnitRunner
import org.jboss.netty.buffer.ChannelBuffers
import org.scalatest.prop.GeneratorDrivenPropertyChecks

@RunWith(classOf[JUnitRunner])
class ChannelBufferBufTest
  extends FunSuite
  with GeneratorDrivenPropertyChecks {

  test("ChannelBufferBuf.slice: slices according to the underlying ChannelBuffer") {
    val cb = ChannelBuffers.buffer(128)
    cb.writeBytes(Array[Byte](1,2,3,4,5,6,7,8,9))
    assert(cb.readByte() == 1)
    val buf = ChannelBufferBuf.Owned(cb)
    assert(buf.length == 8)
    assert(buf.slice(2,4) == Buf.ByteArray.Owned(Array[Byte](4,5)))
    assert(buf == Buf.ByteArray.Owned(Array[Byte](2,3,4,5,6,7,8,9)))
  }

  test("ChannelBufferBuf.slice: truncates on out-of-bounds indices") {
    val cb = ChannelBuffers.buffer(128)
    cb.writeBytes(Array[Byte](1,2,3,4,5,6,7,8,9))
    val buf = ChannelBufferBuf.Owned(cb)
    buf.slice(1, Int.MaxValue)
  }

  test("ChannelBufferBuf.Shared.apply") {
    val bytes = Array[Byte](1,2,3,4,5,6,7,8,9)
    val cb = ChannelBuffers.wrappedBuffer(bytes)
    val buf = ChannelBufferBuf.Shared(cb)
    bytes(0) = 0.toByte
    assert(buf == Buf.ByteArray.Owned(Array[Byte](1,2,3,4,5,6,7,8,9)))
    cb.clear()
    assert(buf == Buf.ByteArray.Owned(Array[Byte](1,2,3,4,5,6,7,8,9)))
  }

  test("ChannelBufferBuf.Direct.apply") {
    val bytes = Array[Byte](1,2,3,4,5,6,7,8,9)
    val cb = ChannelBuffers.wrappedBuffer(bytes)
    val buf = ChannelBufferBuf.Owned(cb)
    bytes(0) = 0.toByte
    assert(buf == Buf.ByteArray.Owned(Array[Byte](0,2,3,4,5,6,7,8,9)))
    cb.clear()
    assert(buf.length == 0)
  }

  test("ChannelBufferBuf.Shared.unapply") {
    val cb0 = ChannelBuffers.buffer(128)
    cb0.writeBytes(Array[Byte](1,2,3,4,5,6,7,8,9))
    val ChannelBufferBuf.Shared(cb1) = ChannelBufferBuf.Owned(cb0)
    cb0.clear()
    assert(cb1.readableBytes() == 9)
  }

  test("ChannelBufferBuf.Direct.unapply") {
    val cb0 = ChannelBuffers.buffer(128)
    cb0.writeBytes(Array[Byte](1,2,3,4,5,6,7,8,9))
    val ChannelBufferBuf.Owned(cb1) = ChannelBufferBuf.Owned(cb0)
    cb0.clear()
    assert(cb1.readableBytes() == 0)
  }

  test("ChannelBufferBuf.coerce(ChannelBufferBuf)") {
    val cb = ChannelBuffers.wrappedBuffer(Array[Byte](1,2,3,4,5,6,7,8,9))
    val orig = ChannelBufferBuf.Owned(cb)
    val coerced = ChannelBufferBuf.coerce(orig)
    assert(coerced eq orig)
  }

  test("ChannelBufferBuf.coerce(ByteArray)") {
    val orig = Buf.ByteArray.Owned(Array[Byte](1,2,3,4,5,6,7,8,9))
    val coerced = ChannelBufferBuf.coerce(orig)
    assert(coerced == orig)
  }

  test("ByteArray.coerce(ChannelBufferBuf)") {
    val orig = ChannelBufferBuf.Owned(
      ChannelBuffers.wrappedBuffer(Array[Byte](1,2,3,4,5,6,7,8,9), 2, 4))
    val coerced = Buf.ByteArray.coerce(orig)
    assert(coerced == orig)
    val Buf.ByteArray.Owned(bytes, begin, end) = coerced
    assert(bytes.length == 9)
    assert(begin == 2)
    assert(end == 6)
  }

  test("get(Int)") {
    val out = new Array[Byte](1)
    forAll { bytes: Array[Byte] =>
      whenever(bytes.length >= 2) {
        val cb = ChannelBuffers.wrappedBuffer(bytes)
        cb.readByte()
        val buf = new ChannelBufferBuf(cb)

        // compare slice/write to get
        buf.slice(0, 1).write(out, 0)
        assert(out(0) == buf.get(0))

        buf.slice(buf.length - 1, buf.length).write(out, 0)
        assert(out(0) == buf.get(buf.length - 1))
      }
    }
  }

  test("get(Int) over the length") {
    forAll { bytes: Array[Byte] =>
      val cb = ChannelBuffers.wrappedBuffer(bytes)
      val buf = new ChannelBufferBuf(cb)
      intercept[IndexOutOfBoundsException] {
        buf.get(buf.length)
      }
    }
  }

  test("write(ByteBuffer)") {
    withBufferOfExcessSize(0)
  }

  test("write(ByteBuffer) when dest has greater capacity than necessary") {
    withBufferOfExcessSize(1)
  }

  private def withBufferOfExcessSize(excess: Int) {
    forAll { bytes: Array[Byte] =>
      val buf = new ChannelBufferBuf(ChannelBuffers.wrappedBuffer(bytes))
      val out = java.nio.ByteBuffer.allocate(bytes.length + excess)
      buf.write(out)
      assert(out.remaining == excess)
      out.flip()
      assert(new ChannelBufferBuf(ChannelBuffers.wrappedBuffer(out)) == buf)
    }
  }

  test("write(ByteBuffer) validates output ByteBuffer is large enough") {
    forAll { bytes: Array[Byte] =>
      whenever (bytes.length > 0) {
        val buf = new ChannelBufferBuf(ChannelBuffers.wrappedBuffer(bytes))
        val out = java.nio.ByteBuffer.allocate(bytes.length - 1)
        val clonedIndexes = out.duplicate()
        val ex = intercept[IllegalArgumentException] {
          buf.write(out)
        }
        assert(ex.getMessage.startsWith("Output too small"))
        // Make sure the indexes of the output buffer were not modified
        assert(out == clonedIndexes)
      }
    }
  }

  test("write(ByteBuffer) with existing data") {
    forAll { bytes: Array[Byte] =>
      val buf = new ChannelBufferBuf(ChannelBuffers.wrappedBuffer(bytes))
      val out = java.nio.ByteBuffer.allocate(bytes.length + 1)
      out.put(1.toByte)
      buf.write(out)
      assert(out.remaining == 0)
      out.flip()
      assert(out.get() == 1)
      assert(new ChannelBufferBuf(ChannelBuffers.wrappedBuffer(out)) == buf)
    }
  }

  test("process returns -1 when fully processed") {
    forAll { bytes: Array[Byte] =>
      val cb = ChannelBuffers.wrappedBuffer(bytes)
      val buf = new ChannelBufferBuf(cb)

      var n = 0
      val processor = new Buf.Processor {
        def apply(byte: Byte): Boolean = {
          n += 1
          true
        }
      }
      assert(-1 == buf.process(processor))
      assert(buf.length == n)
    }
  }

  test("process returns index where processing stopped") {
    val processor = new Buf.Processor {
      def apply(byte: Byte): Boolean = false
    }
    forAll { bytes: Array[Byte] =>
      val cb = ChannelBuffers.wrappedBuffer(bytes)
      val buf = new ChannelBufferBuf(cb)
      assert(buf.process(processor) == (if (buf.isEmpty) -1 else 0))

      def maxThree() = new Buf.Processor {
        private[this] var n = 0
        def apply(byte: Byte): Boolean = {
          n += 1
          n <= 3
        }
      }

      if (bytes.length <= 3) {
        assert(-1 == buf.process(maxThree()))
      } else {
        assert(3 == buf.process(maxThree()))
        if (bytes.length > 10) {
          assert(4 == buf.process(1, 5, maxThree()))
          assert(5 == buf.process(2, 9, maxThree()))
          assert(-1 == buf.process(0, 3, maxThree()))
        }
      }
    }
  }

  test("process handles empty inputs") {
    val processor = new Buf.Processor {
      def apply(byte: Byte): Boolean = false
    }
    forAll { bytes: Array[Byte] =>
      val buf = new ChannelBufferBuf(ChannelBuffers.wrappedBuffer(bytes))
      assert(-1 == buf.process(1, 0, processor))
      assert(-1 == buf.process(buf.length, buf.length + 1, processor))
    }
  }

  test("process handles large until") {
    val processor = new Buf.Processor {
      def apply(byte: Byte): Boolean = true
    }
    forAll { bytes: Array[Byte] =>
      val buf = new ChannelBufferBuf(ChannelBuffers.wrappedBuffer(bytes))
      assert(-1 == buf.process(0, buf.length, processor))
      assert(-1 == buf.process(0, buf.length + 1, processor))
    }
  }

}


text:
namespace MassTransit.AutomatonymousIntegration.Tests
{
    using System;
    using System.Collections.Generic;
    using System.Data.Common;
    using System.Threading;
    using System.Threading.Tasks;
    using NHibernate;
    using NHibernate.Engine;
    using NHibernate.Metadata;
    using NHibernate.Stat;

    class SingleConnectionSessionFactory :
        ISessionFactory
    {
        readonly ISessionFactory _inner;
        readonly DbConnection _liveConnection;

        public SingleConnectionSessionFactory(ISessionFactory inner, DbConnection liveConnection)
        {
            _inner = inner;
            _liveConnection = liveConnection;
        }

        public void Dispose() => _inner.Dispose();

        public ISession OpenSession(DbConnection conn) => _inner.WithOptions().Connection(_liveConnection).OpenSession();

        public Task CloseAsync(CancellationToken cancellationToken = new CancellationToken()) =>
            _inner.CloseAsync(cancellationToken);

        public Task EvictAsync(Type persistentClass, CancellationToken cancellationToken = new CancellationToken()) =>
            _inner.EvictAsync(persistentClass, cancellationToken);

        public Task EvictAsync(Type persistentClass, object id, CancellationToken cancellationToken = new CancellationToken()) =>
            _inner.EvictAsync(persistentClass, id, cancellationToken);

        public Task EvictEntityAsync(string entityName, CancellationToken cancellationToken = new CancellationToken()) =>
            _inner.EvictEntityAsync(entityName, cancellationToken);

        public Task EvictEntityAsync(string entityName, object id, CancellationToken cancellationToken = new CancellationToken()) =>
            _inner.EvictEntityAsync(entityName, id, cancellationToken);

        public Task EvictCollectionAsync(string roleName, CancellationToken cancellationToken = new CancellationToken()) =>
            _inner.EvictCollectionAsync(roleName, cancellationToken);

        public Task EvictCollectionAsync(string roleName, object id, CancellationToken cancellationToken = new CancellationToken()) =>
            _inner.EvictCollectionAsync(roleName, id, cancellationToken);

        public Task EvictQueriesAsync(CancellationToken cancellationToken = new CancellationToken()) =>
            _inner.EvictQueriesAsync(cancellationToken);

        public Task EvictQueriesAsync(string cacheRegion, CancellationToken cancellationToken = new CancellationToken()) =>
            _inner.EvictQueriesAsync(cacheRegion, cancellationToken);

        public ISessionBuilder WithOptions() => _inner.WithOptions();

        public ISession OpenSession(IInterceptor sessionLocalInterceptor) =>
            _inner.WithOptions().Connection(_liveConnection).Interceptor(sessionLocalInterceptor).OpenSession();

        public ISession OpenSession(DbConnection conn, IInterceptor sessionLocalInterceptor) =>
            _inner.WithOptions().Connection(_liveConnection).Interceptor(sessionLocalInterceptor).OpenSession();

        public ISession OpenSession() => _inner.WithOptions().Connection(_liveConnection).OpenSession();

        public IStatelessSessionBuilder WithStatelessOptions()
        {
            throw new NotImplementedException();
        }

        public IClassMetadata GetClassMetadata(Type persistentClass) =>
            _inner.GetClassMetadata(persistentClass);

        public IClassMetadata GetClassMetadata(string entityName) =>
            _inner.GetClassMetadata(entityName);

        public ICollectionMetadata GetCollectionMetadata(string roleName) =>
            _inner.GetCollectionMetadata(roleName);

        public IDictionary<string, IClassMetadata> GetAllClassMetadata() =>
            _inner.GetAllClassMetadata();

        public IDictionary<string, ICollectionMetadata> GetAllCollectionMetadata() =>
            _inner.GetAllCollectionMetadata();

        public void Close() => _inner.Close();

        public void Evict(Type persistentClass) => _inner.Evict(persistentClass);

        public void Evict(Type persistentClass, object id) => _inner.Evict(persistentClass, id);

        public void EvictEntity(string entityName) => _inner.EvictEntity(entityName);

        public void EvictEntity(string entityName, object id) => _inner.EvictEntity(entityName, id);

        public void EvictCollection(string roleName) => _inner.EvictCollection(roleName);

        public void EvictCollection(string roleName, object id) => _inner.EvictCollection(roleName, id);

        public void EvictQueries() => _inner.EvictQueries();

        public void EvictQueries(string cacheRegion) => _inner.EvictQueries(cacheRegion);

        public IStatelessSession OpenStatelessSession() => _inner.OpenStatelessSession();

        public IStatelessSession OpenStatelessSession(DbConnection connection) =>
            _inner.OpenStatelessSession(connection);

        public FilterDefinition GetFilterDefinition(string filterName) =>
            _inner.GetFilterDefinition(filterName);

        public ISession GetCurrentSession() => _inner.GetCurrentSession();

        public IStatistics Statistics => _inner.Statistics;

        public bool IsClosed => _inner.IsClosed;

        public ICollection<string> DefinedFilterNames => _inner.DefinedFilterNames;
    }
}


text:
include_recipe_relative 'emacs'

node.default['admin_users'] = node.admin_essentials.admin_users

package 'zsh'

# add all members of groups in admin_groups to admin list
node.admin_essentials.admin_groups.each do |admin_group|
  group_members = node[:etc][:group][admin_group][:members]
  node.default['admin_users'] += group_members
end

# add SUDO_USER to admin list if there were no other admins specified
sudo_user = ENV['SUDO_USER']
if sudo_user && node.default['admin_users'].empty?
  node.default['admin_users'] << sudo_user
end

# always set admin preferences for root
node.default['admin_users'] << "root"
node.default['admin_users'].uniq!

node.default['admin_users'].each do |username|
  admin = node[:etc][:passwd][username]

  user username do
    shell '/bin/zsh'
  end

  template "#{admin[:dir]}/.zshrc.local" do
    source 'zshrc.local.erb'
    action :create_if_missing
    owner admin[:uid]
    group admin[:gid]
  end

  # silence zsh-newuser-install
  file "#{admin[:dir]}/.zshrc" do
    action :create_if_missing
    owner admin[:uid]
    group admin[:gid]
  end

  directory "#{admin[:dir]}/.ssh" do
    owner admin[:uid]
    group admin[:gid]
  end

  cookbook_file "#{admin[:dir]}/.ssh/config" do
    source 'ssh-config'
    action :create_if_missing
    owner admin[:uid]
    group admin[:gid]
  end

  directory "#{admin[:dir]}/.config" do
    owner admin[:uid]
    group admin[:gid]
  end

  directory "#{admin[:dir]}/.config/mc" do
    owner admin[:uid]
    group admin[:gid]
  end

  cookbook_file "#{admin[:dir]}/.config/mc/ini" do
    source 'mc-ini'
    owner admin[:uid]
    group admin[:gid]
  end
end

# make sudo preserve $EDITOR
directory '/etc/sudoers.d'
file '/etc/sudoers.d/env_keep-editor' do
  content %Q(Defaults env_keep += "EDITOR"\n)
  mode '0440'
end


text:
package redido

import (
	"io"
	"net"
	"sync"
	"time"

	"github.com/garyburd/redigo/redis"
)

// Conn iterface exposes Do and Close. It's a subset of redigo.Conn interface.
type Conn interface {
	// Do sends a command to the server and returns the received reply.
	Do(commandName string, args ...interface{}) (reply interface{}, err error)

	// Close closes the connection.
	Close() error
}

// ConnFactory is a function returning new connections
type ConnFactory func() (Conn, error)

// Doer does the Do, reconnecting when necessary
type Doer struct {
	newConn ConnFactory
	c       Conn
	lock    sync.Mutex
}

// New returns new Doer which will use passed connection factory to estabilish
// new connections.
func New(cf ConnFactory) *Doer {
	return &Doer{newConn: cf}
}

// NewDialTimeout will dial using redis.DialTimeout with passed parameters.
// No connections is being estabilished by calling this function.
func NewDialTimeout(network, address string, connectTimeout, readTimeout, writeTimeout time.Duration) *Doer {
	return New(func() (Conn, error) {
		return redis.DialTimeout(network, address, connectTimeout, readTimeout, writeTimeout)
	})
}

// Do does the command with arguments. Retries on network error.
func (d *Doer) Do(cmd string, args ...interface{}) (reply interface{}, err error) {
	for n := 0; n < 5; n++ {
		reply, err = d.do(cmd, args...)
		if d.c != nil {
			return
		}
		time.Sleep(time.Duration(n) * time.Second)
	}
	return
}

// do does the command with arguments without any retries.
// Connections will be estabilished if doesn't exist.
func (d *Doer) do(cmd string, args ...interface{}) (resp interface{}, err error) {
	d.lock.Lock()
	defer d.lock.Unlock()

	if d.c == nil {
		d.c, err = d.newConn()
		if err != nil {
			return
		}
	}
	r, err := d.c.Do(cmd, args...)
	if _, ok := err.(net.Error); ok || err == io.EOF {
		d.Close()
	}
	return r, err
}

// Close closes the underlying connection.
func (d *Doer) Close() {
	if d.c != nil {
		d.c.Close()
		d.c = nil
	}
}


text:
import React from 'react';
import BaseComponent from './baseComponent';
import PersonInfo from './personInfo';
import ScrollTop from './scrollTop';
import { default as apiUrl } from '../util/constant';
import { ajax } from '../../../util/spaUtil';

class MainPhoto extends BaseComponent {

  constructor(props) {
    super(props);
    this._bind('showInfo', 'hideInfo');

    this.state = {
      isShowInfo: false,
      photos: [],
      person: null,
      page: 0,
      isLoading: false,
      isLoadFinished: false
    }
  }

  componentDidMount() {
    let url = apiUrl.photoList;
    let loadList = () => {
      let page = this.state.page;
      if (!this.state.isLoading) {
        this.setState({
          isLoading: true
        });
        ajax.load(url + page, function(data) {
          if (data.status == 'success') {
            this.setState({
              photos: this.state.photos.concat(data.data),
              page: page + 1,
              isLoadFinished: page == data.pageCount - 1,
              isLoading: false
            });
          } else {
            this.setState({
              isLoadFinished: true,
              isLoading: false
            });
          }
        }.bind(this), function() {
          this.setState({
            isLoadFinished: true
          });
        }.bind(this));
      }
    };

    let handleScroll = () => {
      let isLoadFinished = this.state.isLoadFinished;
      if (isLoadFinished) {
        window.removeEventListener('scroll', handleScroll);
      } else {
        let scrollTop = document.body.scrollTop;
        let inHeight = window.innerHeight;
        let offsetHeight = document.body.scrollHeight;
        if (scrollTop + inHeight + 40 > offsetHeight) loadList();
      }
    };

    loadList();
    window.addEventListener('scroll', handleScroll);
  }

  showInfo(person, e) {
    e.preventDefault();
    this.setState({
      isShowInfo: true,
      person: person
    });
  }

  hideInfo() {
    this.setState({
      isShowInfo: false
    })
  }

  render() {
    let state = this.state;

    return (

        <ScrollTop />
        {
          state.isShowInfo ? <PersonInfo person={state.person} hideInfo={this.hideInfo} /> :

              {
                state.photos.map((item, index) =>
                  <li key={index} style={{marginRight: `${index%2==0?2:0}%`}}>
                     this.showInfo(item, e)}>

                      {item.title}

                )
              }

        }

    );
  }

}

export default MainPhoto;


text:
<?php
    namespace Thin;

    class Db
    {
        public static function connexion()
        {
            $args = func_get_args();

            $class = '\\Thin\\Db\\' . ucfirst(
                Inflector::lower(
                    Arrays::first($args)
                )
            );

            array_shift($args);

            return call_user_func_array([$class, 'instance'], $args);
        }

        public static function __callStatic($method, $args)
        {
            $toArgs = [];

            array_push($toArgs, $method);

            if (count($args)) {
                foreach ($args as $arg) {
                    array_push($toArgs, $arg);
                }
            }

            return call_user_func_array(['\\Thin\\Db', 'connexion'], $toArgs);
        }
    }


text:
Rational Synergy/Change scripts

The perl folder contains an example PM which has a few methods that proivde some useful synegry functions.  It's main aim though is to show how to use the CSAPI to dump CR attachments.

The CLI folder has a demo script which shows you how to do the same thing from the Linux CLI.  It does NOT use the CSAPI, but uses the CLI synergy interface.

In the end, most of my heavy-lifting was done from the CLI end, as it's more completley implemented, or was at the time.

(c) KC 2009


text:
import sys
from github_org import GithubOrganizationManager as OrgMgr
from getopt import getopt, GetoptError

#
# Helper functions
#

def usage():
    print ("Usage: %s [OPTION]... [USERS_CSV]\n"
           "  -h  --help         Print this help message and exit\n"
           "  -c  --config=FILE  Read configuration from the specified file"
           "\n") % sys.argv[0]

#
# Parse command line
#
config_file = 'ghorg.conf'

try:
    opts, args = getopt(sys.argv[1:],
                        "hc:",
                        ['help', 'config='])
except GetoptError as err:
    print str(err)  # will print something like "option -a not recognized"
    usage()
    sys.exit(2)

for opt, opt_arg in opts:
    if opt in ('-h', '--help'):
        usage()
        sys.exit(0)
    if opt in ('-c', '--config'):
        config_file = opt_arg
    else:
        assert False, "unhandled option: %s" % opt

if len(args) > 0:
    user_file = args[0]

#
# Script proper
#

mgr = OrgMgr(config_file)

for repo in mgr._organization.get_repos():
    print repo.name


text:
package Paws::EC2::PurchaseReservedInstancesOfferingResult;
  use Moose;
  has ReservedInstancesId => (is => 'ro', isa => 'Str', request_name => 'reservedInstancesId', traits => ['NameInRequest',]);

  has _request_id => (is => 'ro', isa => 'Str');
1;

### main pod documentation begin ###

=head1 NAME

Paws::EC2::PurchaseReservedInstancesOfferingResult

=head1 ATTRIBUTES

=head2 ReservedInstancesId => Str

The IDs of the purchased Reserved Instances.

=head2 _request_id => Str

=cut


text:
/* %%%%%%%%%%%%%%%%%%%% (c) William Landi 1991 %%%%%%%%%%%%%%%%%%%%%%%%%%%% */
/* Permission to use this code is granted as long as the copyright */
/* notice remains in place. */
/* ============================ op_tab.h =================================== */

/* ---------------- Possible formats for instructions.                       */
enum formats {ONE,TWO,THREE_FOUR,PSEUDO,NOT_FOUND};

/* ---------------- Possible operand types --------------------------------- */
enum operands
     {NONE,REG,REG_REG,MEM,REG_NUM,NUM,PSEUDO_LOC,PSEUDO_NOLOC,PSEUDO_ADDR};

/* ---------------- Structure of the operator table                          */
struct OP_ENTRY {
  char *MNEMONIC;                /* Name of the operator                     */
  enum formats FORMAT;           /* FORMAT of this operator                  */
  char *OPCODE;                  /* OPCODE for this operator                 */
  enum operands OPERAND;         /* Number and type of operands              */
  int FUNCTION;                  /* Function to execute is PASS1. Pseudo     */
                                 /* operators only.                          */
};

/* ---------------------------- LOOK_UP_OP --------------------------------- */
/* 1 parameter:                                                              */
/*    1) char OP[];                 Name of the OPerator to find.            */
/* Find operator in the table. Return the entry if it is found, else return  */
/* the not found entry. Uses BINARY SEARCH.                                  */
extern struct OP_ENTRY *LOOK_UP_OP();


text:
// $Header: $
package au.edu.uwa.csse.dyerd01.ipd.strategies;

import au.edu.uwa.csse.dyerd01.ipd.framework.Action;
import au.edu.uwa.csse.dyerd01.ipd.framework.GameHistory;
import org.apache.log4j.Logger;

/**
 * An implementation of the GRADUAL strategy for playing the Iterated Prisoner's Dilemma,
 * as described by Beaufils, Delahaye and Mathieu.
 * @author Daniel Dyer
 */
public class HarshGradual extends Gradual
{
    private static final Logger logger = Logger.getLogger(HarshGradual.class);

    @Override
    public String getName()
    {
        return "HarshGradual";
    }

    @Override
    public Action getNextMove(GameHistory history)
    {
        int historyLength = history.getHistoryLength();
        if (mode != MODE_RECONCILLIATION
            && historyLength > 0
            && history.getOpponentActionForIteration(this, historyLength - 1) == Action.DEFECT)
        {
            mode = MODE_PUNISHMENT;
            defectionCount++;
            modeDuration = defectionCount;
            logger.debug("Gradual punishment triggered (duration: " + modeDuration + ").");
        }

        if (mode == MODE_PUNISHMENT)
        {
            logger.debug("In punishment mode.");
            if (modeDuration > 0)
            {
                logger.debug("Defecting...");
                modeDuration--;
                return Action.DEFECT;
            }
            else
            {
                logger.debug("Switched to reconcilliation.");
                mode = MODE_RECONCILLIATION;
                modeDuration = 2;
            }
        }
        if (mode == MODE_RECONCILLIATION && modeDuration <= 1)
        {
            mode = MODE_NORMAL;
        }
        modeDuration--;
        return Action.COOPERATE;
    }
}


text:
using System;
using System.Diagnostics;
using System.Linq;
using Examine;
using Examine.SearchCriteria;
using Merchello.Core.Models;
using Merchello.Core.Services;
using Merchello.Examine.Providers;
using Merchello.Tests.Base.DataMakers;
using Merchello.Tests.IntegrationTests.Services;
using Merchello.Tests.IntegrationTests.TestHelpers;
using NUnit.Framework;

namespace Merchello.Tests.IntegrationTests.Examine
{
    [TestFixture]
    public class ProductProviderTests : DatabaseIntegrationTestBase
    {
        private const int ProductCount = 2;
        private IProductService _productService;

        [SetUp]
        public void Init()
        {
            _productService = PreTestDataWorker.ProductService;
        }

        /// <summary>
        /// Test to verify that the product index can be rebuilt
        /// </summary>
        [Test]
        public void Can_Rebuild_Product_Index()
        {
            //// Arrange
            PreTestDataWorker.DeleteAllProducts();
            var products = MockProductDataMaker.MockProductCollectionForInserting(ProductCount);
            _productService.Save(products);

            //// Act
            var timer = new Stopwatch();
            timer.Start();
            ExamineManager.Instance.IndexProviderCollection["MerchelloProductIndexer"].RebuildIndex();
            timer.Stop();
            Console.Write("Time to index: " + timer.Elapsed.ToString());

            //// Assert
            var searcher = ExamineManager.Instance.SearchProviderCollection["MerchelloProductSearcher"];

            var criteria = searcher.CreateSearchCriteria(Merchello.Examine.IndexTypes.ProductVariant);
            criteria.Field("allDocs", "1");
            var results = searcher.Search(criteria);

            Assert.AreEqual(products.Count(), results.Count());

        }

        /// <summary>
        /// Test verifies that a new product can be added to an existing index
        /// </summary>
        [Test]
        public void Can_Add_A_New_Product_To_The_Index()
        {
            PreTestDataWorker.DeleteAllProducts();

            //// Arrange
            var provider = (ProductIndexer) ExamineManager.Instance.IndexProviderCollection["MerchelloProductIndexer"];
            provider.RebuildIndex();

            var searcher = ExamineManager.Instance.SearchProviderCollection["MerchelloProductSearcher"];

            var productVariantService = PreTestDataWorker.ProductVariantService;

            //// Act
            var product = MockProductDataMaker.MockProductCollectionForInserting(1).First();
            product.ProductOptions.Add(new ProductOption("Color"));
            product.ProductOptions.First(x => x.Name == "Color").Choices.Add(new ProductAttribute("Blue", "Blue"));
            product.ProductOptions.First(x => x.Name == "Color").Choices.Add(new ProductAttribute("Red", "Red"));
            product.ProductOptions.First(x => x.Name == "Color").Choices.Add(new ProductAttribute("Green", "Green"));
            product.ProductOptions.Add(new ProductOption("Size"));
            product.ProductOptions.First(x => x.Name == "Size").Choices.Add(new ProductAttribute("Small", "Sm"));
            product.ProductOptions.First(x => x.Name == "Size").Choices.Add(new ProductAttribute("Medium", "Med"));
            product.ProductOptions.First(x => x.Name == "Size").Choices.Add(new ProductAttribute("Large", "Lg"));
            product.ProductOptions.First(x => x.Name == "Size").Choices.Add(new ProductAttribute("X-Large", "XL"));
            product.Height = 11M;
            product.Width = 11M;
            product.Length = 11M;
            product.CostOfGoods = 15M;
            product.OnSale = true;
            product.SalePrice = 18M;
            product.Manufacturer = "Merchello";
            _productService.Save(product);

            provider.AddProductToIndex(product);

            //// Assert
            var criteria = searcher.CreateSearchCriteria("productvariant", BooleanOperation.And);
            criteria.Field("productKey", product.Key.ToString()).And().Field("master", "true");

            ISearchResults results = searcher.Search(criteria);

            Assert.IsTrue(results.Count() == 1);
            var result = results.First();
            Assert.NotNull(result.Fields["productOptions"]);
            Assert.AreEqual("Merchello", result.Fields["manufacturer"]);
            provider.RebuildIndex();

        }

        /// <summary>
        /// Test verifies that a product can be deleted from the index
        /// </summary>
        [Test]
        public void Can_Remove_A_Product_From_The_Index()
        {
            //// Arrange
            var provider = (ProductIndexer)ExamineManager.Instance.IndexProviderCollection["MerchelloProductIndexer"];

            var searcher = ExamineManager.Instance.SearchProviderCollection["MerchelloProductSearcher"];
            var criteria = searcher.CreateSearchCriteria(Merchello.Examine.IndexTypes.ProductVariant);
            criteria.Field("allDocs", "1");
            var results = searcher.Search(criteria);

            var providerKey = results.Select(x => x.Fields["productKey"]).FirstOrDefault();
            Assert.IsNotNullOrEmpty(providerKey);

            var key = new Guid(providerKey);

            var product = _productService.GetByKey(key);

            //// Act
            provider.DeleteProductFromIndex(product);

            //// Assert
            criteria = searcher.CreateSearchCriteria("productvariant", BooleanOperation.And);
            criteria.Field("productKey", product.Key.ToString()).And().Field("master", "true");

            results = searcher.Search(criteria);

            Assert.IsFalse(results.Any());

        }
    }
}