text:
// Copyright 2020 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.

#include "third_party/blink/renderer/modules/direct_sockets/tcp_readable_stream_wrapper.h"

#include "base/callback_helpers.h"
#include "base/test/mock_callback.h"
#include "net/base/net_errors.h"
#include "third_party/blink/renderer/bindings/core/v8/native_value_traits_impl.h"
#include "third_party/blink/renderer/bindings/core/v8/script_promise_tester.h"
#include "third_party/blink/renderer/bindings/core/v8/v8_binding_for_testing.h"
#include "third_party/blink/renderer/bindings/core/v8/v8_iterator_result_value.h"
#include "third_party/blink/renderer/core/streams/readable_stream.h"
#include "third_party/blink/renderer/modules/direct_sockets/stream_wrapper.h"
#include "third_party/blink/renderer/platform/bindings/exception_state.h"
#include "third_party/blink/renderer/platform/heap/garbage_collected.h"
#include "third_party/blink/renderer/platform/testing/unit_test_helpers.h"

namespace blink {

namespace {

using ::testing::ElementsAre;

// The purpose of this class is to ensure that the data pipe is reset before the
// V8TestingScope is destroyed, so that the TCPReadableStreamWrapper object
// doesn't try to create a DOMException after the ScriptState has gone away.
class StreamCreator : public GarbageCollected<StreamCreator> {
 public:
  StreamCreator() = default;
  ~StreamCreator() {
    // Let the TCPReadableStreamWrapper object respond to the closure if it
    // needs to.
    test::RunPendingTasks();
  }

  // The default value of |capacity| means some sensible value selected by mojo.
  TCPReadableStreamWrapper* Create(const V8TestingScope& scope,
                                   uint32_t capacity = 0) {
    MojoCreateDataPipeOptions options;
    options.struct_size = sizeof(MojoCreateDataPipeOptions);
    options.flags = MOJO_CREATE_DATA_PIPE_FLAG_NONE;
    options.element_num_bytes = 1;
    options.capacity_num_bytes = capacity;

    mojo::ScopedDataPipeConsumerHandle data_pipe_consumer;
    MojoResult result =
        mojo::CreateDataPipe(&options, data_pipe_producer_, data_pipe_consumer);
    if (result != MOJO_RESULT_OK) {
      ADD_FAILURE() << "CreateDataPipe() returned " << result;
    }

    auto* script_state = scope.GetScriptState();
    stream_wrapper_ = MakeGarbageCollected<TCPReadableStreamWrapper>(
        script_state,
        WTF::Bind(&StreamCreator::Close, WrapWeakPersistent(this)),
        std::move(data_pipe_consumer));
    return stream_wrapper_;
  }

  void ResetPipe() { data_pipe_producer_.reset(); }

  void WriteToPipe(Vector<uint8_t> data) {
    uint32_t num_bytes = data.size();
    EXPECT_EQ(data_pipe_producer_->WriteData(data.data(), &num_bytes,
                                             MOJO_WRITE_DATA_FLAG_ALL_OR_NONE),
              MOJO_RESULT_OK);
    EXPECT_EQ(num_bytes, data.size());
  }

  // Copies the contents of a v8::Value containing a Uint8Array to a Vector.
  static Vector<uint8_t> ToVector(V8TestingScope& scope,
                                  v8::Local<v8::Value> v8value) {
    Vector<uint8_t> ret;

    NotShared<DOMUint8Array> value =
        NativeValueTraits<NotShared<DOMUint8Array>>::NativeValue(
            scope.GetIsolate(), v8value, scope.GetExceptionState());
    if (!value) {
      ADD_FAILURE() << "chunk is not an Uint8Array";
      return ret;
    }
    ret.Append(static_cast<uint8_t*>(value->Data()),
               static_cast<wtf_size_t>(value->byteLength()));
    return ret;
  }

  struct Iterator {
    bool done = false;
    Vector<uint8_t> value;
  };

  // Performs a single read from |reader|, converting the output to the
  // Iterator type. Assumes that the readable stream is not errored.
  // static Iterator Read(const V8TestingScope& scope,
  Iterator Read(V8TestingScope& scope, ReadableStreamDefaultReader* reader) {
    auto* script_state = scope.GetScriptState();
    ScriptPromise read_promise =
        reader->read(script_state, ASSERT_NO_EXCEPTION);
    ScriptPromiseTester tester(script_state, read_promise);
    tester.WaitUntilSettled();
    EXPECT_TRUE(tester.IsFulfilled());
    return IteratorFromReadResult(scope, tester.Value().V8Value());
  }

  static Iterator IteratorFromReadResult(V8TestingScope& scope,
                                         v8::Local<v8::Value> result) {
    CHECK(result->IsObject());
    Iterator ret;
    v8::Local<v8::Value> v8value;
    if (!V8UnpackIteratorResult(scope.GetScriptState(), result.As<v8::Object>(),
                                &ret.done)
             .ToLocal(&v8value)) {
      ADD_FAILURE() << "Couldn't unpack iterator";
      return ret;
    }
    if (ret.done) {
      EXPECT_TRUE(v8value->IsUndefined());
      return ret;
    }

    ret.value = ToVector(scope, v8value);
    return ret;
  }

  bool CloseCalledWith(bool error) const { return close_called_with_ == error; }

  void Trace(Visitor* visitor) const { visitor->Trace(stream_wrapper_); }

 private:
  void Close(ScriptValue exception) {
    close_called_with_ = !exception.IsEmpty();
  }

  absl::optional<bool> close_called_with_;
  mojo::ScopedDataPipeProducerHandle data_pipe_producer_;
  Member<TCPReadableStreamWrapper> stream_wrapper_;
};

TEST(TCPReadableStreamWrapperTest, Create) {
  V8TestingScope scope;

  auto* stream_creator = MakeGarbageCollected<StreamCreator>();
  auto* tcp_readable_stream_wrapper = stream_creator->Create(scope);

  EXPECT_TRUE(tcp_readable_stream_wrapper->Readable());
}

TEST(TCPReadableStreamWrapperTest, ReadArrayBuffer) {
  V8TestingScope scope;

  auto* stream_creator = MakeGarbageCollected<StreamCreator>();
  auto* tcp_readable_stream_wrapper = stream_creator->Create(scope);

  auto* script_state = scope.GetScriptState();
  auto* reader =
      tcp_readable_stream_wrapper->Readable()->GetDefaultReaderForTesting(
          script_state, ASSERT_NO_EXCEPTION);
  stream_creator->WriteToPipe({'A'});

  StreamCreator::Iterator result = stream_creator->Read(scope, reader);
  EXPECT_FALSE(result.done);
  EXPECT_THAT(result.value, ElementsAre('A'));
}

TEST(TCPReadableStreamWrapperTest, WriteToPipeWithPendingRead) {
  V8TestingScope scope;

  auto* stream_creator = MakeGarbageCollected<StreamCreator>();
  auto* tcp_readable_stream_wrapper = stream_creator->Create(scope);

  auto* script_state = scope.GetScriptState();
  auto* reader =
      tcp_readable_stream_wrapper->Readable()->GetDefaultReaderForTesting(
          script_state, ASSERT_NO_EXCEPTION);
  ScriptPromise read_promise = reader->read(script_state, ASSERT_NO_EXCEPTION);
  ScriptPromiseTester tester(script_state, read_promise);

  test::RunPendingTasks();

  stream_creator->WriteToPipe({'A'});

  tester.WaitUntilSettled();
  ASSERT_TRUE(tester.IsFulfilled());

  StreamCreator::Iterator result =
      stream_creator->IteratorFromReadResult(scope, tester.Value().V8Value());
  EXPECT_FALSE(result.done);
  EXPECT_THAT(result.value, ElementsAre('A'));
}

class TCPReadableStreamWrapperCloseTest : public testing::TestWithParam<bool> {
};

INSTANTIATE_TEST_SUITE_P(/**/,
                         TCPReadableStreamWrapperCloseTest,
                         testing::Bool());

TEST_P(TCPReadableStreamWrapperCloseTest, TriggerClose) {
  V8TestingScope scope;

  auto* stream_creator = MakeGarbageCollected<StreamCreator>();
  auto* tcp_readable_stream_wrapper = stream_creator->Create(scope);

  auto* script_state = scope.GetScriptState();
  auto* reader =
      tcp_readable_stream_wrapper->Readable()->GetDefaultReaderForTesting(
          script_state, ASSERT_NO_EXCEPTION);
  ScriptPromise read_promise = reader->read(script_state, ASSERT_NO_EXCEPTION);
  ScriptPromiseTester tester(script_state, read_promise);

  test::RunPendingTasks();
  stream_creator->WriteToPipe({'A'});

  bool graceful = GetParam();

  // 1. OnReadError(...) is called.
  tcp_readable_stream_wrapper->ErrorStream(graceful ? net::OK
                                                    : net::ERR_UNEXPECTED);

  // 2. pipe reset event arrives.
  stream_creator->ResetPipe();
  test::RunPendingTasks();

  tester.WaitUntilSettled();

  ASSERT_TRUE(tester.IsFulfilled());
  ASSERT_EQ(tcp_readable_stream_wrapper->GetState(),
            graceful ? StreamWrapper::State::kClosed
                     : StreamWrapper::State::kAborted);
}

TEST_P(TCPReadableStreamWrapperCloseTest, TriggerCloseInReverseOrder) {
  V8TestingScope scope;

  auto* stream_creator = MakeGarbageCollected<StreamCreator>();
  auto* tcp_readable_stream_wrapper = stream_creator->Create(scope);

  auto* script_state = scope.GetScriptState();
  auto* reader =
      tcp_readable_stream_wrapper->Readable()->GetDefaultReaderForTesting(
          script_state, ASSERT_NO_EXCEPTION);
  ScriptPromise read_promise = reader->read(script_state, ASSERT_NO_EXCEPTION);
  ScriptPromiseTester tester(script_state, read_promise);

  test::RunPendingTasks();
  stream_creator->WriteToPipe({'A'});

  bool graceful = GetParam();

  // 1. pipe reset event arrives.
  stream_creator->ResetPipe();
  test::RunPendingTasks();

  // 2. OnReadError(...) is called.
  tcp_readable_stream_wrapper->ErrorStream(graceful ? net::OK
                                                    : net::ERR_UNEXPECTED);
  tester.WaitUntilSettled();

  ASSERT_TRUE(stream_creator->CloseCalledWith(!graceful));

  ASSERT_TRUE(tester.IsFulfilled());
  ASSERT_EQ(tcp_readable_stream_wrapper->GetState(),
            graceful ? StreamWrapper::State::kClosed
                     : StreamWrapper::State::kAborted);
}

TEST_P(TCPReadableStreamWrapperCloseTest, ErrorCancelReset) {
  V8TestingScope scope;

  auto* stream_creator = MakeGarbageCollected<StreamCreator>();
  auto* tcp_readable_stream_wrapper = stream_creator->Create(scope);

  auto* script_state = scope.GetScriptState();

  bool graceful = GetParam();

  // 1. OnReadError(...) is called.
  tcp_readable_stream_wrapper->ErrorStream(graceful ? net::OK
                                                    : net::ERR_UNEXPECTED);

  // 2. readable.cancel() is called.
  auto tester = ScriptPromiseTester(
      script_state, tcp_readable_stream_wrapper->Readable()->cancel(
                        script_state, ASSERT_NO_EXCEPTION));
  tester.WaitUntilSettled();
  ASSERT_TRUE(tester.IsFulfilled());

  // 3. pipe reset event arrives.
  stream_creator->ResetPipe();
  test::RunPendingTasks();

  ASSERT_EQ(tcp_readable_stream_wrapper->GetState(),
            graceful ? StreamWrapper::State::kClosed
                     : StreamWrapper::State::kAborted);
}

TEST_P(TCPReadableStreamWrapperCloseTest, ResetCancelError) {
  V8TestingScope scope;

  auto* stream_creator = MakeGarbageCollected<StreamCreator>();
  auto* tcp_readable_stream_wrapper = stream_creator->Create(scope);

  auto* script_state = scope.GetScriptState();

  bool graceful = GetParam();

  // 1. pipe reset event arrives.
  stream_creator->ResetPipe();
  test::RunPendingTasks();

  // 2. readable.cancel() is called.
  auto tester = ScriptPromiseTester(
      script_state, tcp_readable_stream_wrapper->Readable()->cancel(
                        script_state, ASSERT_NO_EXCEPTION));
  tester.WaitUntilSettled();
  ASSERT_TRUE(tester.IsFulfilled());

  // 3. OnReadError(...) is called.
  tcp_readable_stream_wrapper->ErrorStream(graceful ? net::OK
                                                    : net::ERR_UNEXPECTED);

  stream_creator->ResetPipe();

  ASSERT_EQ(tcp_readable_stream_wrapper->GetState(),
            graceful ? StreamWrapper::State::kClosed
                     : StreamWrapper::State::kAborted);
}

}  // namespace

}  // namespace blink


text:
 <link href="pantheios.css" rel="stylesheet" type="text/css">

Main Page

Modules

Namespaces

Classes

Files

Related Pages

Examples

pantheios/implicit_link/fe.WindowsRegistry.WithCallback.h File Reference

Detailed Description

[C, C++] Implicitly links in the callback version of the Pantheios WindowsRegistry Stock Front-end.

#include <pantheios/pantheios.h>

#include <pantheios/implicit_link/implicit_link_base_.h>

Go to the source code of this file.

    pantheios
    Library documentation
    © Matthew Wilson &
    Synesis Software,
    2006-2011

redpajama_set_name: RedPajamaGithub


text:
using blaze::CompressedMatrix;
using blaze::DynamicVector;
using blaze::Submatrix;
using blaze::Subvector;
using custom_vector;

namespace chrono {

// Forward declarations

class ChBody;
class ChLink;
class ChPhysicsItem;
class real2;
class real3;
class real4;
class vec3;
class Ch3DOFContainer;
class ChFEAContainer;
class ChFluidContainer;
class ChMPMContainer;
class ChFLIPContainer;
class ChConstraintRigidRigid;
class ChConstraintBilateral;
class ChMaterialCompositionStrategy;

namespace collision {
class ChCBroadphase;
class ChCNarrowphaseDispatch;
class ChCAABBGenerator;
}  // namespace collision

#if BLAZE_MAJOR_VERSION == 2
typedef blaze::SparseSubmatrix<CompressedMatrix<real>> SubMatrixType;
typedef blaze::DenseSubvector<DynamicVector<real>> SubVectorType;
typedef blaze::SparseSubmatrix<const CompressedMatrix<real>> ConstSubMatrixType;
typedef blaze::DenseSubvector<const DynamicVector<real>> ConstSubVectorType;
#elif BLAZE_MAJOR_VERSION == 3
typedef blaze::Submatrix<CompressedMatrix<real>> SubMatrixType;
typedef blaze::Subvector<DynamicVector<real>> SubVectorType;
typedef blaze::Submatrix<const CompressedMatrix<real>> ConstSubMatrixType;
typedef blaze::Subvector<const DynamicVector<real>> ConstSubVectorType;
#endif

// These defines are used in the submatrix calls below to keep them concise
// They aren't names to be easy to understand, but for length
#define _num_dof_ data_manager->num_dof
#define _num_rigid_dof_ data_manager->num_rigid_bodies * 6
#define _num_shaft_dof_ data_manager->num_shafts
#define _num_motor_dof_ data_manager->num_motors
#define _num_fluid_dof_ data_manager->num_fluid_bodies * 3
#define _num_bil_ data_manager->num_bilaterals
#define _num_uni_ data_manager->num_unilaterals
#define _num_r_c_ data_manager->num_rigid_contacts
#define _num_rf_c_ data_manager->num_rigid_fluid_contacts
#define _num_fluid_ data_manager->num_fluid_bodies

// 0
//_num_rigid_dof_
//_num_shaft_dof_
//_num_motor_dof_
//_num_fluid_dof_

// 0
//_num_r_c_
// 2*_num_r_c_
// 3*_num_r_c_
//_num_bil_
//_num_rf_c_
// 2*_num_rf_c_
//_num_fluid_
// 3*_num_fluid_
#define _D_ data_manager->host_data.D
#define _M_invD_ data_manager->host_data.M_invD
#define _D_T_ data_manager->host_data.D_T
#define _E_ data_manager->host_data.E
#define _gamma_ data_manager->host_data.gamma

#define _DN_ submatrix(_D_, 0, 0, _num_rigid_dof_, 1 * _num_r_c_)
#define _DT_ submatrix(_D_, 0, _num_r_c_, _num_rigid_dof_, 2 * _num_r_c_)
#define _DS_ submatrix(_D_, 0, 3 * _num_r_c_, _num_rigid_dof_, 3 * _num_r_c_)
// D Bilateral
#define _DB_ submatrix(_D_, 0, _num_uni_, _num_rigid_dof_ + _num_shaft_dof_ + _num_motor_dof_, _num_bil_)
// D Rigid Fluid
#define _DRFN_ submatrix(_D_, 0, _num_uni_ + _num_bil_, _num_dof_, _num_rf_c_)
#define _DRFT_ submatrix(_D_, 0, _num_uni_ + _num_bil_ + _num_rf_c_, _num_dof_, 2 * _num_rf_c_)
// D fluid fluid density
#define _DFFD_                                                                                \
    submatrix(_D_, _num_rigid_dof_ + _num_shaft_dof_ + _num_motor_dof_, _num_uni_ + _num_bil_ + 3 * _num_rf_c_, \
              _num_fluid_dof_, _num_fluid_)
// D fluid fluid viscosity
#define _DFFV_                                                          \
    submatrix(_D_, _num_rigid_dof_ + _num_shaft_dof_ + _num_motor_dof_, \
              _num_uni_ + _num_bil_ + 3 * _num_rf_c_ + _num_fluid_, _num_fluid_dof_, 3 * _num_fluid_)
//======
#define _MINVDN_ submatrix(_M_invD_, 0, 0, _num_rigid_dof_, 1 * _num_r_c_)
#define _MINVDT_ submatrix(_M_invD_, 0, _num_r_c_, _num_rigid_dof_, 2 * _num_r_c_)
#define _MINVDS_ submatrix(_M_invD_, 0, 3 * _num_r_c_, _num_rigid_dof_, 3 * _num_r_c_)
// Bilateral
#define _MINVDB_ submatrix(_M_invD_, 0, _num_uni_, _num_rigid_dof_ + _num_shaft_dof_ + _num_motor_dof_, _num_bil_)
// Rigid Fluid
#define _MINVDRFN_ submatrix(_M_invD_, 0, _num_uni_ + _num_bil_, _num_dof_, _num_rf_c_)
#define _MINVDRFT_ submatrix(_M_invD_, 0, _num_uni_ + _num_bil_ + _num_rf_c_, _num_dof_, 2 * _num_rf_c_)
// Density
#define _MINVDFFD_                                                                                \
    submatrix(_M_invD_, _num_rigid_dof_ + _num_shaft_dof_ + _num_motor_dof_, _num_uni_ + _num_bil_ + 3 * _num_rf_c_, \
              _num_fluid_dof_, _num_fluid_)
// Viscosity
#define _MINVDFFV_                                                           \
    submatrix(_M_invD_, _num_rigid_dof_ + _num_shaft_dof_ + _num_motor_dof_, \
              _num_uni_ + _num_bil_ + 3 * _num_rf_c_ + _num_fluid_, _num_fluid_dof_, 3 * _num_fluid_)
//======
#define _DNT_ submatrix(_D_T_, 0, 0, _num_r_c_, _num_rigid_dof_)
#define _DTT_ submatrix(_D_T_, _num_r_c_, 0, 2 * _num_r_c_, _num_rigid_dof_)
#define _DST_ submatrix(_D_T_, 3 * _num_r_c_, 0, 3 * _num_r_c_, _num_rigid_dof_)
// Bilateral
#define _DBT_ submatrix(_D_T_, _num_uni_, 0, _num_bil_, _num_rigid_dof_ + _num_shaft_dof_ + _num_motor_dof_)
// Rigid Fluid
#define _DRFNT_ submatrix(_D_T_, _num_uni_ + _num_bil_, 0, _num_rf_c_, _num_dof_)
#define _DRFTT_ submatrix(_D_T_, _num_uni_ + _num_bil_ + _num_rf_c_, 0, 2 * _num_rf_c_, _num_dof_)
// Density
#define _DFFDT_                                                                                \
    submatrix(_D_T_, _num_uni_ + _num_bil_ + 3 * _num_rf_c_, _num_rigid_dof_ + _num_shaft_dof_ + _num_motor_dof_, \
              _num_fluid_, _num_fluid_dof_)
// Viscosity
#define _DFFVT_                                                            \
    submatrix(_D_T_, _num_uni_ + _num_bil_ + 3 * _num_rf_c_ + _num_fluid_, \
              _num_rigid_dof_ + _num_shaft_dof_ + _num_motor_dof_, 3 * _num_fluid_, _num_fluid_dof_)
//======
#define _EN_ subvector(_E_, 0, _num_r_c_)
#define _ET_ subvector(_E_, _num_r_c_, 2 * _num_r_c_)
#define _ES_ subvector(_E_, 3 * _num_r_c_, 3 * _num_r_c_)
// Bilateral
#define _EB_ subvector(_E_, _num_uni_, _num_bil_)
// Rigid Fluid
#define _ERFN_ subvector(_E_, _num_uni_ + _num_bil_, _num_rf_c_)
#define _ERFT_ subvector(_E_, _num_uni_ + _num_bil_ + _num_rf_c_, 2 * _num_rf_c_)
// Density
#define _EFFD_ subvector(_E_, _num_uni_ + _num_bil_ + 3 * _num_rf_c_, _num_fluid_)
// Viscosity
#define _EFFV_ subvector(_E_, _num_uni_ + _num_bil_ + 3 * _num_rf_c_ + _num_fluid_, 3 * _num_fluid_)

////======
//#define _GAMMAN_ subvector(_gamma_, 0, _num_r_c_)
//#define _GAMMAT_ submatrix(_gamma_, _num_r_c_, 2 * _num_r_c_)
//#define _GAMMAS_ submatrix(_gamma_, 3 * _num_r_c_, 3 * _num_r_c_)
//// Bilateral
//#define _GAMMAB_ submatrix(_gamma_, _num_uni_,  _num_bil_)
//// Rigid Fluid
//#define _GAMMARFN_ submatrix(_gamma_, _num_uni_ + _num_bil_ _num_rf_c_)
//#define _GAMMARFT_ submatrix(_gamma_, _num_uni_ + _num_bil_ + _num_rf_c_, 2 * _num_rf_c_)
//// Density
//#define _GAMMAFFD_ submatrix(_gamma_,  _num_uni_ + _num_bil_ + 3 * _num_rf_c_, _num_fluid_)
//// Viscosity
//#define _GAMMAFFV_ submatrix(_gamma_,  _num_uni_ + _num_bil_ + 3 * _num_rf_c_ + _num_fluid_,  3 * _num_fluid_)

// The maximum number of shear history contacts per smaller body (SMC)
#define max_shear 20

/// @addtogroup multicore_module
/// @{

/// Structure of arrays containing contact shape information.
struct shape_container {
    custom_vector<short2> fam_rigid;  ///< family information
    custom_vector<uint> id_rigid;     ///< ID of associated body
    custom_vector<int> typ_rigid;     ///< shape type
    custom_vector<int> local_rigid;   ///< local shape index in collision model of associated body
    custom_vector<int> start_rigid;   ///< start index in the appropriate container of dimensions
    custom_vector<int> length_rigid;  ///< usually 1, except for convex

    custom_vector<quaternion> ObR_rigid;  ///< Shape rotation
    custom_vector<real3> ObA_rigid;       ///< Position of shape

    custom_vector<real> sphere_rigid;      ///< radius for sphere shapes
    custom_vector<real3> box_like_rigid;   ///< dimensions for box-like shapes
    custom_vector<real3> triangle_rigid;   ///< vertices of all triangle shapes (3 per shape)
    custom_vector<real2> capsule_rigid;    ///< radius and half-length for capsule shapes
    custom_vector<real4> rbox_like_rigid;  ///< dimensions and radius for rbox-like shapes
    custom_vector<real3> convex_rigid;     ///<
    custom_vector<int> tetrahedron_rigid;  ///<

    custom_vector<real3> triangle_global;
    custom_vector<real3> obj_data_A_global;
    custom_vector<quaternion> obj_data_R_global;
};

/// Structure of arrays containing simulation data.
struct host_container {
    // Collision data

    custom_vector<real3> aabb_min;  ///< List of bounding boxes minimum point
    custom_vector<real3> aabb_max;  ///< List of bounding boxes maximum point

    custom_vector<real3> aabb_min_tet;  ///< List of bounding boxes minimum point for tets
    custom_vector<real3> aabb_max_tet;  ///< List of bounding boxes maximum point for tets

    custom_vector<long long> pair_shapeIDs;     ///< Shape IDs for each shape pair (encoded in a single long long)
    custom_vector<long long> contact_shapeIDs;  ///< Shape IDs for each contact (encoded in a single long long)

    // Contact data
    custom_vector<real3> norm_rigid_rigid;
    custom_vector<real3> cpta_rigid_rigid;
    custom_vector<real3> cptb_rigid_rigid;
    custom_vector<real> dpth_rigid_rigid;
    custom_vector<real> erad_rigid_rigid;
    custom_vector<vec2> bids_rigid_rigid;

    custom_vector<real3> norm_rigid_fluid;
    custom_vector<real3> cpta_rigid_fluid;
    custom_vector<real> dpth_rigid_fluid;
    custom_vector<int> neighbor_rigid_fluid;
    custom_vector<int> c_counts_rigid_fluid;

    // each particle has a finite number of neighbors preallocated
    custom_vector<int> neighbor_3dof_3dof;
    custom_vector<int> c_counts_3dof_3dof;
    custom_vector<int> particle_indices_3dof;
    custom_vector<int> reverse_mapping_3dof;

    custom_vector<real3> norm_rigid_tet;
    custom_vector<real3> cpta_rigid_tet;
    custom_vector<real3> cptb_rigid_tet;
    custom_vector<real> dpth_rigid_tet;
    custom_vector<int> neighbor_rigid_tet;
    custom_vector<real4> face_rigid_tet;
    custom_vector<int> c_counts_rigid_tet;
    // contact with nodes
    custom_vector<real3> norm_rigid_tet_node;
    custom_vector<real3> cpta_rigid_tet_node;
    custom_vector<real> dpth_rigid_tet_node;
    custom_vector<int> neighbor_rigid_tet_node;
    custom_vector<int> c_counts_rigid_tet_node;

    custom_vector<real3> norm_marker_tet;
    custom_vector<real3> cpta_marker_tet;
    custom_vector<real3> cptb_marker_tet;
    custom_vector<real> dpth_marker_tet;
    custom_vector<int> neighbor_marker_tet;
    custom_vector<real4> face_marker_tet;
    custom_vector<int> c_counts_marker_tet;

    // Contact forces (SMC)
    // These vectors hold the contact forces and torques for each individual contact. For each contact, the force and
    // torque are given at the body origin, expressed in the absolute frame. These vectors include the force and torque
    // for each of the two bodies involved in a contact.
    custom_vector<real3> ct_force;   ///< Contact forces per contact
    custom_vector<real3> ct_torque;  ///< Contact torques per contact
    // These vectors hold the resultant contact force and torque for each body in contact, accumulating over all
    // contacts that the body is involved in. The force and torque are given at the body origin, expresed in the
    // absolute frame. for bodies that are involved in at least one contact.
    custom_vector<real3> ct_body_force;   ///< Total contact force on bodies
    custom_vector<real3> ct_body_torque;  ///< Total contact torque on these bodies

    // Contact shear history (SMC)
    custom_vector<vec3> shear_neigh;          ///< Neighbor list of contacting bodies and shapes
    custom_vector<real3> shear_disp;          ///< Accumulated shear displacement for each neighbor
    custom_vector<real> contact_relvel_init;  ///< Initial relative normal velocity manitude per contact pair
    custom_vector<real> contact_duration;     ///< Accumulated contact duration, per contact pair

    /// Mapping from all bodies in the system to bodies involved in a contact.
    /// For bodies that are currently not in contact, the mapping entry is -1.
    /// Otherwise, the mapping holds the appropriate index in the vectors above.
    custom_vector<int> ct_body_map;

    /// This vector holds the friction information (composite material) as a triplet:
    /// x - Sliding friction,
    /// y - Rolling friction,
    /// z - Spinning Friction.
    /// This is precomputed at every timestep for all contacts in parallel.
    /// Improves performance and reduces conditionals later on.
    // Used for both NSC and SMC contacts.
    custom_vector<real3> fric_rigid_rigid;

    /// Holds the cohesion value (composite material) for each contact.
    /// Similar to friction this is precomputed for all contacts in parallel.
    /// Used for NSC only.
    custom_vector<real> coh_rigid_rigid;

    /// Precomputed compliance (composite material) values for all contacts.
    /// Used for NSC only.
    custom_vector<real4> compliance_rigid_rigid;

    // Precomputed composite material quantities (SMC)
    custom_vector<real2> modulus_rigid_rigid;   ///< E_eff and G_eff
    custom_vector<real3> adhesion_rigid_rigid;  ///< adhesion_eff, adhesionMultDMT_eff, and adhesionSPerko_eff
    custom_vector<real> cr_rigid_rigid;         ///< cr_eff (effective coefficient of restitution)
    custom_vector<real4> smc_rigid_rigid;       ///< kn, kt, gn, gt

    // Object data
    custom_vector<real3> pos_rigid;
    custom_vector<quaternion> rot_rigid;
    custom_vector<char> active_rigid;
    custom_vector<char> collide_rigid;
    custom_vector<real> mass_rigid;

    // Information for 3dof nodes
    custom_vector<real3> pos_3dof;
    custom_vector<real3> sorted_pos_3dof;
    custom_vector<real3> vel_3dof;
    custom_vector<real3> sorted_vel_3dof;

    // Information for FEM nodes
    custom_vector<real3> pos_node_fea;
    custom_vector<real3> vel_node_fea;
    custom_vector<real> mass_node_fea;
    custom_vector<uvec4> tet_indices;

    custom_vector<uvec4> boundary_triangles_fea;
    custom_vector<uint> boundary_node_fea;
    custom_vector<uint> boundary_element_fea;
    custom_vector<short2> boundary_family_fea;

    /// Bilateral constraint type (all supported constraints)
    custom_vector<int> bilateral_type;

    /// Keeps track of active bilateral constraints.
    custom_vector<int> bilateral_mapping;

    // Shaft data
    custom_vector<real> shaft_rot;     ///< shaft rotation angles
    custom_vector<real> shaft_inr;     ///< shaft inverse inertias
    custom_vector<char> shaft_active;  ///< shaft active (not sleeping nor fixed) flags

    // Material properties (NSC, only for fluid-rigid and FEA-rigid contacts)
    custom_vector<float> sliding_friction;  ///< sliding coefficients of friction
    custom_vector<float> cohesion;          ///< constant cohesion forces

    /// This matrix, if used will hold D^TxM^-1xD in sparse form.
    CompressedMatrix<real> Nshur;
    /// The D Matrix hold the Jacobian for the entire system.
    CompressedMatrix<real> D;
    /// D_T is the transpose of the D matrix, note that D_T is actually computed
    /// first and D is taken as the transpose. This is due to the way that blaze
    /// handles sparse matrix allocation, it is easier to do it on a per row basis.
    CompressedMatrix<real> D_T;
    /// Mass matrix; if holding the full inertia tensor, M is block diagonal.
    CompressedMatrix<real> M;
    /// M_inv is the inverse mass matrix; if holding the full inertia tensor, M_inv is block diagonal.
    CompressedMatrix<real> M_inv;
    /// M_invD holds M_inv multiplied by D. This is done as a preprocessing step
    /// so that later, when the full matrix vector product is needed it can be
    /// performed in two steps, first R = Minv_D*x, and then D_T*R where R is just
    /// a temporary variable used here for illustrative purposes. In reality the
    /// entire operation happens inline without a temp variable.
    CompressedMatrix<real> M_invD;

    DynamicVector<real> R_full;  ///< The right hand side of the system
    DynamicVector<real> R;       ///< The rhs of the system, changes during solve
    DynamicVector<real> b;       ///< Correction terms
    DynamicVector<real> s;
    DynamicVector<real> M_invk;  ///< Result of M_inv multiplied by vector of forces
    DynamicVector<real> v;       ///< This vector holds the velocities for all objects
    DynamicVector<real> hf;      ///< This vector holds h*forces, h is time step

    /// Contact impulses. These are the unknowns solved for in the NSC formulation.
    /// Depending on the selected SolverMode, gamma is organized as follows (N is the number of rigid contacts):
    /// \li NORMAL [size(gamma) = N]\n
    ///     n1 n2 ... nN
    /// \li SLIDING [size(gamma) = 3N]\n
    ///     n1 n2 ... nN | u1 v1 u2 v2 ... uN vN
    /// \li SPINNING [size(gamma) = 6N]\n
    ///     n1 n2 ... nN | u1 v1 u2 v2 ... uN vN | tn1 tu1 tv1 tn2 tu2 tv2 ... tnN tuN tvN
    ///
    /// If there are any bilateral constraints, the corresponding impulses are stored at the end of `gamma`.
    DynamicVector<real> gamma;

    /// Compliance matrix elements.
    /// Note that E is a diagonal matrix and hence stored in a vector.
    DynamicVector<real> E;

    DynamicVector<real> Fc; ///< Contact forces (NSC)

    //========Broadphase Data========

    custom_vector<uint> bin_intersections;
    custom_vector<uint> bin_number;
    custom_vector<uint> bin_number_out;
    custom_vector<uint> bin_aabb_number;
    custom_vector<uint> bin_start_index;
    custom_vector<uint> bin_num_contact;
};

/// Global data manager for Chrono::Multicore.
class CH_MULTICORE_API ChMulticoreDataManager {
  public:
    ChMulticoreDataManager();
    ~ChMulticoreDataManager();

    host_container host_data;    ///< Structure of data arrays (state, contact, etc)
    shape_container shape_data;  ///< Structure of arrays containing contact shape information

    /// Used by the bilarerals for computing the Jacobian and other terms.
    std::shared_ptr<ChSystemDescriptor> system_descriptor;

    std::shared_ptr<Ch3DOFContainer> node_container;  ///< container of 3-DOF particles
    std::shared_ptr<Ch3DOFContainer> fea_container;   ///< container of FEA nodes

    ChConstraintRigidRigid* rigid_rigid;  ///< methods for unilateral constraints
    ChConstraintBilateral* bilateral;     ///< methods for bilateral constraints

    collision::ChCBroadphase* broadphase;            ///< methods for broad-phase collision detection
    collision::ChCNarrowphaseDispatch* narrowphase;  ///< methods for narrow-phase collision detection
    collision::ChCAABBGenerator* aabb_generator;     ///< methods for cpmputing object AABBs

    // These pointers are used to compute the mass matrix instead of filling a temporary data structure
    std::vector<std::shared_ptr<ChBody>>* body_list;                  ///< List of bodies
    std::vector<std::shared_ptr<ChLinkBase>>* link_list;              ///< List of bilaterals
    std::vector<std::shared_ptr<ChPhysicsItem>>* other_physics_list;  ///< List to other items

    // Indexing variables
    uint num_rigid_bodies;             ///< The number of rigid bodies in a system
    uint num_fluid_bodies;             ///< The number of fluid bodies in the system
    uint num_shafts;                   ///< The number of shafts in a system
    uint num_motors;                   ///< The number of motor links with 1 state variable
    uint num_linmotors;                ///< The number of linear speed motors
    uint num_rotmotors;                ///< The number of rotation speed motors
    uint num_dof;                      ///< The number of degrees of freedom in the system
    uint num_rigid_shapes;             ///< The number of collision models in a system
    uint num_rigid_contacts;           ///< The number of contacts between rigid bodies in a system
    uint num_rigid_fluid_contacts;     ///< The number of contacts between rigid and fluid objects
    uint num_fluid_contacts;           ///< The number of contacts between fluid objects
    uint num_unilaterals;              ///< The number of contact constraints
    uint num_bilaterals;               ///< The number of bilateral constraints
    uint num_constraints;              ///< Total number of constraints
    uint num_fea_nodes;                ///< Total number of FEM nodes
    uint num_fea_tets;                 ///< Total number of FEM nodes
    uint num_rigid_tet_contacts;       ///< The number of contacts between tetrahedron and rigid bodies
    uint num_marker_tet_contacts;      ///< The number of contacts between tetrahedron and fluid markers
    uint num_rigid_tet_node_contacts;  ///< The number of contacts between tetrahedron nodes and rigid bodies
    uint nnz_bilaterals;               ///< The number of non-zero entries in the bilateral Jacobian

    /// Flag indicating whether or not the contact forces are current (NSC only).
    bool Fc_current;
    /// Container for all timers for the system.
    ChTimerMulticore system_timer;
    /// Container for all settings for the system, collision detection, and solver.
    settings_container settings;
    /// Container for various statistics for collision detection and solver.
    measures_container measures;

    /// Material composition strategy.
    std::unique_ptr<ChMaterialCompositionStrategy> composition_strategy;

    /// User-provided callback for overriding composite material properties.
    std::shared_ptr<ChContactContainer::AddContactCallback> add_contact_callback;

    /// Output a vector (one dimensional matrix) from blaze to a file.
    int OutputBlazeVector(DynamicVector<real> src, std::string filename);
    /// Output a sparse blaze matrix to a file.
    int OutputBlazeMatrix(CompressedMatrix<real> src, std::string filename);
    /// Utility debugging function that outputs all of the data associated for a system.
    int ExportCurrentSystem(std::string output_dir);

    /// Print a sparse blaze matrix.
    void PrintMatrix(CompressedMatrix<real> src);
};

/// @} multicore_module

}  // end namespace chrono


text:
package main

import (
	"encoding/json"
	"fmt"
	"io"
	"io/ioutil"
	"net/http"
	"os"
	"path/filepath"
	"strconv"
	"text/tabwriter"
	"time"

	"github.com/bitrise-io/go-steputils/stepconf"
	"github.com/bitrise-io/go-steputils/tools"
	"github.com/bitrise-io/go-utils/colorstring"
	"github.com/bitrise-io/go-utils/log"
	"github.com/bitrise-io/go-utils/pathutil"
	"github.com/bitrise-io/go-utils/sliceutil"
	toolresults "google.golang.org/api/toolresults/v1beta3"
)

const (
	testTypeInstrumentation = "instrumentation"
	testTypeRobo            = "robo"
)

func failf(f string, v ...interface{}) {
	log.Errorf(f, v...)
	os.Exit(1)
}

func main() {
	var configs ConfigsModel
	if err := stepconf.Parse(&configs); err != nil {
		failf("Invalid input: %s", err)
	}

	if err := configs.validate(); err != nil {
		log.Errorf("Failed to parse config:")
		failf("%s", err)
	}

	fmt.Println()
	configs.print()

	log.SetEnableDebugLog(configs.VerboseLog)

	fmt.Println()
	successful := true

	log.Infof("Uploading app and test files")

	testAssets, err := uploadTestAssets(configs)
	if err != nil {
		failf("Failed to upload test assets, error: %s", err)
	}
	log.Donef("=> Files uploaded")

	fmt.Println()
	log.Infof("Starting test")

	if err = startTestRun(configs, testAssets); err != nil {
		failf("Starting test run failed, error: %s", err)
	}
	log.Donef("=> Test started")

	fmt.Println()
	log.Infof("Waiting for test results")
	{
		finished := false
		printedLogs := []string{}
		for !finished {
			url := configs.APIBaseURL + "/" + configs.AppSlug + "/" + configs.BuildSlug + "/" + configs.APIToken

			req, err := http.NewRequest("GET", url, nil)
			if err != nil {
				failf("Failed to create http request, error: %s", err)
			}

			client := &http.Client{}
			resp, err := client.Do(req)
			if err != nil || resp.StatusCode != http.StatusOK {
				resp, err = client.Do(req)
				if err != nil {
					failf("Failed to get http response, error: %s", err)
				}
			}

			body, err := ioutil.ReadAll(resp.Body)
			if err != nil {
				failf("Failed to read response body, error: %s", err)
			}

			if resp.StatusCode != http.StatusOK {
				failf("Failed to get test status, error: %s", string(body))
			}

			responseModel := &toolresults.ListStepsResponse{}

			err = json.Unmarshal(body, responseModel)
			if err != nil {
				failf("Failed to unmarshal response body, error: %s, body: %s", err, string(body))
			}

			finished = true
			testsRunning := 0
			for _, step := range responseModel.Steps {
				if step.State != "complete" {
					finished = false
					testsRunning++
				}
			}

			msg := ""
			if len(responseModel.Steps) == 0 {
				finished = false
				msg = fmt.Sprintf("- Validating")
			} else {
				msg = fmt.Sprintf("- (%d/%d) running", testsRunning, len(responseModel.Steps))
			}

			if !sliceutil.IsStringInSlice(msg, printedLogs) {
				log.Printf(msg)
				printedLogs = append(printedLogs, msg)
			}

			if finished {
				log.Donef("=> Test finished")
				fmt.Println()

				log.Infof("Test results:")
				w := tabwriter.NewWriter(os.Stdout, 0, 0, 3, ' ', 0)
				if _, err := fmt.Fprintln(w, "Model\tAPI Level\tLocale\tOrientation\tOutcome\t"); err != nil {
					failf("Failed to write in tabwriter, error: %s", err)
				}

				for _, step := range responseModel.Steps {
					dimensions := map[string]string{}
					for _, dimension := range step.DimensionValue {
						dimensions[dimension.Key] = dimension.Value
					}

					outcome := step.Outcome.Summary

					switch outcome {
					case "success":
						outcome = colorstring.Green(outcome)
					case "failure":
						successful = false
						if step.Outcome.FailureDetail != nil {
							if step.Outcome.FailureDetail.Crashed {
								outcome += "(Crashed)"
							}
							if step.Outcome.FailureDetail.NotInstalled {
								outcome += "(NotInstalled)"
							}
							if step.Outcome.FailureDetail.OtherNativeCrash {
								outcome += "(OtherNativeCrash)"
							}
							if step.Outcome.FailureDetail.TimedOut {
								outcome += "(TimedOut)"
							}
							if step.Outcome.FailureDetail.UnableToCrawl {
								outcome += "(UnableToCrawl)"
							}
						}
						outcome = colorstring.Red(outcome)
					case "inconclusive":
						successful = false
						if step.Outcome.InconclusiveDetail != nil {
							if step.Outcome.InconclusiveDetail.AbortedByUser {
								outcome += "(AbortedByUser)"
							}
							if step.Outcome.InconclusiveDetail.InfrastructureFailure {
								outcome += "(InfrastructureFailure)"
							}
						}
						outcome = colorstring.Yellow(outcome)
					case "skipped":
						successful = false
						if step.Outcome.SkippedDetail != nil {
							if step.Outcome.SkippedDetail.IncompatibleAppVersion {
								outcome += "(IncompatibleAppVersion)"
							}
							if step.Outcome.SkippedDetail.IncompatibleArchitecture {
								outcome += "(IncompatibleArchitecture)"
							}
							if step.Outcome.SkippedDetail.IncompatibleDevice {
								outcome += "(IncompatibleDevice)"
							}
						}
						outcome = colorstring.Blue(outcome)
					}

					if _, err := fmt.Fprintln(w, fmt.Sprintf("%s\t%s\t%s\t%s\t%s\t", dimensions["Model"], dimensions["Version"], dimensions["Locale"], dimensions["Orientation"], outcome)); err != nil {
						failf("Failed to write in tabwriter, error: %s", err)
					}
				}
				if err := w.Flush(); err != nil {
					log.Errorf("Failed to flush writer, error: %s", err)
				}
			}
			if !finished {
				time.Sleep(5 * time.Second)
			}
		}
	}

	if configs.DownloadTestResults {
		fmt.Println()
		log.Infof("Downloading test assets")
		{
			url := configs.APIBaseURL + "/assets/" + configs.AppSlug + "/" + configs.BuildSlug + "/" + configs.APIToken

			req, err := http.NewRequest("GET", url, nil)
			if err != nil {
				failf("Failed to create http request, error: %s", err)
			}

			client := &http.Client{}
			resp, err := client.Do(req)
			if err != nil {
				failf("Failed to get http response, error: %s", err)
			}

			if resp.StatusCode != http.StatusOK {
				failf("Failed to get http response, status code: %d", resp.StatusCode)
			}

			body, err := ioutil.ReadAll(resp.Body)
			if err != nil {
				failf("Failed to read response body, error: %s", err)
			}

			responseModel := map[string]string{}

			err = json.Unmarshal(body, &responseModel)
			if err != nil {
				failf("Failed to unmarshal response body, error: %s", err)
			}

			tempDir, err := pathutil.NormalizedOSTempDirPath("vdtesting_test_assets")
			if err != nil {
				failf("Failed to create temp dir, error: %s", err)
			}

			for fileName, fileURL := range responseModel {
				err := downloadFile(fileURL, filepath.Join(tempDir, fileName))
				if err != nil {
					failf("Failed to download file, error: %s", err)
				}
			}

			log.Donef("=> Assets downloaded")
			if err := tools.ExportEnvironmentWithEnvman("VDTESTING_DOWNLOADED_FILES_DIR", tempDir); err != nil {
				log.Warnf("Failed to export environment (VDTESTING_DOWNLOADED_FILES_DIR), error: %s", err)
			} else {
				log.Printf("The downloaded test assets path (%s) is exported to the VDTESTING_DOWNLOADED_FILES_DIR environment variable.", tempDir)
			}
		}
	}

	if !successful {
		os.Exit(1)
	}
}

func downloadFile(url string, localPath string) error {
	out, err := os.Create(localPath)
	if err != nil {
		return fmt.Errorf("Failed to open the local cache file for write: %s", err)
	}
	defer func() {
		if err := out.Close(); err != nil {
			log.Printf("Failed to close Archive download file (%s): %s", localPath, err)
		}
	}()

	resp, err := http.Get(url)
	if err != nil {
		return fmt.Errorf("Failed to create cache download request: %s", err)
	}
	defer func() {
		if err := resp.Body.Close(); err != nil {
			log.Printf("Failed to close Archive download response body: %s", err)
		}
	}()

	if resp.StatusCode != 200 {
		return fmt.Errorf("Failed to download archive - non success response code: %d", resp.StatusCode)
	}

	_, err = io.Copy(out, resp.Body)
	if err != nil {
		return fmt.Errorf("Failed to save cache content into file: %s", err)
	}

	return nil
}

func uploadFile(uploadURL string, archiveFilePath string) error {
	archFile, err := os.Open(archiveFilePath)
	if err != nil {
		return fmt.Errorf("Failed to open archive file for upload (%s): %s", archiveFilePath, err)
	}
	isFileCloseRequired := true
	defer func() {
		if !isFileCloseRequired {
			return
		}
		if err := archFile.Close(); err != nil {
			log.Printf(" (!) Failed to close archive file (%s): %s", archiveFilePath, err)
		}
	}()

	fileInfo, err := archFile.Stat()
	if err != nil {
		return fmt.Errorf("Failed to get File Stats of the Archive file (%s): %s", archiveFilePath, err)
	}
	fileSize := fileInfo.Size()

	req, err := http.NewRequest("PUT", uploadURL, archFile)
	if err != nil {
		return fmt.Errorf("Failed to create upload request: %s", err)
	}

	req.Header.Add("Content-Length", strconv.FormatInt(fileSize, 10))
	req.ContentLength = fileSize

	resp, err := http.DefaultClient.Do(req)
	if err != nil {
		return fmt.Errorf("Failed to upload: %s", err)
	}
	isFileCloseRequired = false
	defer func() {
		if err := resp.Body.Close(); err != nil {
			log.Printf(" [!] Failed to close response body: %s", err)
		}
	}()

	_, err = ioutil.ReadAll(resp.Body)
	if err != nil {
		return fmt.Errorf("Failed to read response: %s", err)
	}

	if resp.StatusCode != 200 {
		return fmt.Errorf("Failed to upload file, response code was: %d", resp.StatusCode)
	}

	return nil
}


text:
require 'capistrano/all'
require 'capistrano/github/releases/version'
load File.expand_path('../../tasks/github_releases.rake', __FILE__)


text:
package org.apache.geronimo.kernel.proxy;

/**
 * @version $Rev$ $Date$
 */
public class ProxyCreationException extends RuntimeException {
    public ProxyCreationException() {
    }

    public ProxyCreationException(String message) {
        super(message);
    }

    public ProxyCreationException(String message, Throwable cause) {
        super(message, cause);
    }

    public ProxyCreationException(Throwable cause) {
        super(cause);
    }
}


text:
<?xml version="1.0"?>
<package>
  <name>slamsim</name>
  <version>0.0.2</version>
  <description>The slamsim package</description>
  <maintainer email="yukunlin@mail.ustc.edu.cn">Yu Kunlin</maintainer>
  <author email="yukunlin@mail.ustc.edu.cn">Yu Kunlin</author>
  <license>BSD 3-Clause</license>
</package>


text:
/** @file */

#include "vfsnodeunit.h"

#include "vbinaryiostream.h"
#include "vbufferedfilestream.h"
#include "vdirectiofilestream.h"
#include "vexception.h"
#include "vtextiostream.h"

// VFSNodeIterateTestCallback -----------------------------------------------------

class VFSNodeIterateTestCallback : public VDirectoryIterationCallback {
    public:

        VFSNodeIterateTestCallback() : mNodeNames() {}
        virtual ~VFSNodeIterateTestCallback() {}

        virtual bool handleNextNode(const VFSNode& node);

        VStringVector mNodeNames;
};

// VFSNodeUnit -------------------------------------------------------------

VFSNodeUnit::VFSNodeUnit(bool logOnSuccess, bool throwOnError) :
    VUnit("VFSNodeUnit", logOnSuccess, throwOnError) {
    mTextFileLines.push_back("This is line 1.");
    mTextFileLines.push_back("This is the second line.");
    mTextFileLines.push_back("This is the third and final line.");

    for (VStringVector::const_iterator i = mTextFileLines.begin(); i != mTextFileLines.end(); ++i) {
        mTextFileContents += (*i);
        mTextFileContents += VString::NATIVE_LINE_ENDING();
    }
}

void VFSNodeUnit::run() {
    // Note that we also do testing of streams and file i/o here.

    this->logStatus(VSTRING_FORMAT("getExecutable: '%s'", VFSNode::getExecutable().getPath().chars()));
    this->logStatus(VSTRING_FORMAT("getExecutableDirectory: '%s'", VFSNode::getExecutableDirectory().getPath().chars()));
    this->logStatus(VSTRING_FORMAT("USER_HOME_DIRECTORY: '%s'", VFSNode::getKnownDirectoryNode(VFSNode::USER_HOME_DIRECTORY, "com", "app").getPath().chars()));
    this->logStatus(VSTRING_FORMAT("LOG_FILES_DIRECTORY: '%s'", VFSNode::getKnownDirectoryNode(VFSNode::LOG_FILES_DIRECTORY, "com", "app").getPath().chars()));
    this->logStatus(VSTRING_FORMAT("USER_PREFERENCES_DIRECTORY: '%s'", VFSNode::getKnownDirectoryNode(VFSNode::USER_PREFERENCES_DIRECTORY, "com", "app").getPath().chars()));
    this->logStatus(VSTRING_FORMAT("CACHED_DATA_DIRECTORY: '%s'", VFSNode::getKnownDirectoryNode(VFSNode::CACHED_DATA_DIRECTORY, "com", "app").getPath().chars()));
    this->logStatus(VSTRING_FORMAT("APPLICATION_DATA_DIRECTORY: '%s'", VFSNode::getKnownDirectoryNode(VFSNode::APPLICATION_DATA_DIRECTORY, "com", "app").getPath().chars()));
    this->logStatus(VSTRING_FORMAT("CURRENT_WORKING_DIRECTORY: '%s'", VFSNode::getKnownDirectoryNode(VFSNode::CURRENT_WORKING_DIRECTORY, "com", "app").getPath().chars()));
    this->logStatus(VSTRING_FORMAT("EXECUTABLE_DIRECTORY: '%s'", VFSNode::getKnownDirectoryNode(VFSNode::EXECUTABLE_DIRECTORY, "com", "app").getPath().chars()));

    VFSNode tempDir = VFSNode::getKnownDirectoryNode(VFSNode::CACHED_DATA_DIRECTORY, "vault", "unittest");
    VString tempDirPath = tempDir.getPath();

    VFSNode testDirRoot(tempDir, "vfsnodetest_temp");
    (void) testDirRoot.rm();

    VFSNode testDirDeep(tempDir, "vfsnodetest_temp/one/two/three");
    VUNIT_ASSERT_FALSE_LABELED(testDirDeep.exists(), "initial state 1");
    testDirDeep.mkdirs();
    VUNIT_ASSERT_TRUE_LABELED(testDirDeep.exists(), "deep mkdirs");

    VFSNode testDirDeeper(testDirDeep, "four");
    VUNIT_ASSERT_FALSE_LABELED(testDirDeeper.exists(), "initial state 2");
    testDirDeeper.mkdirs();
    VUNIT_ASSERT_TRUE_LABELED(testDirDeeper.exists(), "one-deep mkdirs");

    // Now that we have created a deep directory structure, let's do some
    // file i/o streams stuff here.

    VFSNode testTextFileNode(testDirDeeper, "test_text_file.txt");

    VBufferedFileStream btfs(testTextFileNode);
    this->_testTextFileIO("starting Buffered Text IO tests", testTextFileNode, btfs);
    (void) testTextFileNode.rm();
    VUNIT_ASSERT_FALSE_LABELED(testTextFileNode.exists(), "buffered text file removed");

    VDirectIOFileStream dtfs(testTextFileNode);
    this->_testTextFileIO("starting Unbuffered Text IO tests", testTextFileNode, dtfs);
    this->_testTextFileReadAll(testTextFileNode);
    (void) testTextFileNode.rm();
    VUNIT_ASSERT_FALSE_LABELED(testTextFileNode.exists(), "unbuffered text file removed");

    VFSNode testBinaryFileNode(testDirDeeper, "test_binary_file");

    VBufferedFileStream bbfs(testBinaryFileNode);
    this->_testBinaryFileIO("starting Buffered Binary IO tests", testBinaryFileNode, bbfs);
    (void) testBinaryFileNode.rm();
    VUNIT_ASSERT_FALSE_LABELED(testBinaryFileNode.exists(), "buffered binary file removed");

    VDirectIOFileStream dbfs(testBinaryFileNode);
    this->_testBinaryFileIO("starting Unbuffered Binary IO tests", testBinaryFileNode, dbfs);
    (void) testBinaryFileNode.rm();
    VUNIT_ASSERT_FALSE_LABELED(testBinaryFileNode.exists(), "unbuffered binary file removed");

    this->_testDirectoryIteration(testDirDeeper);

    // Next, test all flavors of renaming operations.
    VFSNode copyTest1(tempDir, "vfsnodetest_temp/one/two/test1.txt");
    VBufferedFileStream sourceFileStream(copyTest1);
    sourceFileStream.openWrite();
    VTextIOStream sourceOut(sourceFileStream);
    sourceOut.writeLine("line 1");
    sourceOut.writeLine("line 2");
    sourceOut.flush();
    sourceFileStream.close();
    VUNIT_ASSERT_TRUE_LABELED(copyTest1.exists(), "test1 exists");

    VFSNode copyTest2(tempDir, "vfsnodetest_temp/one/two/test2.txt");
    copyTest1.renameToName("test2.txt");
    VUNIT_ASSERT_FALSE_LABELED(copyTest1.exists(), "test1 was renamed");
    VUNIT_ASSERT_TRUE_LABELED(copyTest2.exists(), "test2 exists");

    VFSNode copyTest3;
    copyTest2.renameToName("test3.txt", copyTest3);
    VUNIT_ASSERT_FALSE_LABELED(copyTest2.exists(), "test2 was renamed");
    VUNIT_ASSERT_TRUE_LABELED(copyTest3.getPath() == tempDirPath + "/vfsnodetest_temp/one/two/test3.txt" && copyTest3.exists(), "test3 exists");

    VFSNode copyTest4(tempDir, "vfsnodetest_temp/one/two/three/test4.txt");
    copyTest3.renameToNode(copyTest4);
    VUNIT_ASSERT_FALSE_LABELED(copyTest3.exists(), "test3 was moved and renamed");
    VUNIT_ASSERT_TRUE_LABELED(copyTest4.exists(), "test4 exists");

    copyTest4.renameToPath(tempDirPath + "/vfsnodetest_temp/one/two/test5.txt");
    VFSNode copyTest5(tempDir, "vfsnodetest_temp/one/two/test5.txt");
    VUNIT_ASSERT_FALSE_LABELED(copyTest4.exists(), "test4 was moved and renamed");
    VUNIT_ASSERT_TRUE_LABELED(copyTest5.exists(), "test5 exists");

    copyTest5.renameToName("test5.txt"); // should throw

    VFSNode dirCopyTarget(tempDir, "vfsnodetest_temp_copy");
    VFSNode::copyDirectory(testDirRoot, dirCopyTarget, true);
    // Verify that expected files now exist. Very dependent on file operations performed in tests above.
    VUNIT_ASSERT_TRUE_LABELED(VFSNode(tempDirPath + "/vfsnodetest_temp_copy/one/two/test5.txt").isFile(), "copied directory, spot check test5.txt");
    VUNIT_ASSERT_TRUE_LABELED(VFSNode(tempDirPath + "/vfsnodetest_temp_copy/one/two/three/four/iter_test_0.txt").isFile(), "copied directory, spot check iter_test_0.txt");
    VUNIT_ASSERT_TRUE_LABELED(VFSNode(tempDirPath + "/vfsnodetest_temp_copy/one/two/three/four/iter_test_1.txt").isFile(), "copied directory, spot check iter_test_1.txt");
    VUNIT_ASSERT_TRUE_LABELED(VFSNode(tempDirPath + "/vfsnodetest_temp_copy/one/two/three/four/iter_test_2.txt").isFile(), "copied directory, spot check iter_test_2.txt");
    VUNIT_ASSERT_TRUE_LABELED(VFSNode(tempDirPath + "/vfsnodetest_temp_copy/one/two/three/four/iter_test_3.txt").isFile(), "copied directory, spot check iter_test_3.txt");

    // Verify that a non-recursive copy of source into a subdirectory of itself is allowed.
    VFSNode nrcSource(tempDirPath + "/vfsnodetest_temp/one/two");
    VFSNode nrcDest(tempDirPath + "/vfsnodetest_temp/one/two/non-recursive-copy-of-two");
    VFSNode::copyDirectory(nrcSource, nrcDest, false);
    VUNIT_ASSERT_TRUE_LABELED(VFSNode(tempDirPath + "/vfsnodetest_temp/one/two/non-recursive-copy-of-two/test5.txt").isFile(), "non-recursive nested copy succeeds on child file");

    // Verify that a recursive copy of source into a subdirectory of itself yields an
    // exception (rather than an infinite loop copying until disk is full!).
    try {
        VFSNode rcSource(tempDirPath + "/vfsnodetest_temp/one/two");
        VFSNode rcDest(tempDirPath + "/vfsnodetest_temp/one/two/recursive-copy-of-two");
        VFSNode::copyDirectory(nrcSource, nrcDest, true);
        VUNIT_ASSERT_FAILURE("Recursive nested copy was improperly allowed");
    } catch (const VException& ex) {
        VUNIT_ASSERT_SUCCESS("Recursive nested copy threw an exception as expected");
    }

    // Clean up our litter.
    (void) copyTest5.rm();
    (void) dirCopyTarget.rm();
    (void) nrcDest.rm();

    // Done with exercising file i/o and streams and directory stuff. Clean up our litter.

    VString deepPath;
    testDirDeeper.getParentPath(deepPath);
    VUNIT_ASSERT_EQUAL_LABELED(deepPath, tempDirPath + "/vfsnodetest_temp/one/two/three", "get parent path");

    VString nodeName;
    testDirDeeper.getName(nodeName);
    VUNIT_ASSERT_EQUAL_LABELED(nodeName, "four", "get deep node name");

    VFSNode shallowNode("shallow");
    shallowNode.getName(nodeName);
    VUNIT_ASSERT_EQUAL_LABELED(nodeName, "shallow", "get shallow node name");

    (void) testDirRoot.rm();
    VUNIT_ASSERT_FALSE_LABELED(testDirRoot.exists(), "rm tree");

    // Test some of the path string manipulation.

    VString testPath3("one/two/three");
    VFSNode testPath3Node(testPath3);

    VString testPath2;
    testPath3Node.getParentPath(testPath2);
    VFSNode testPath2Node(testPath2);
    VUNIT_ASSERT_EQUAL_LABELED(testPath2, "one/two", "parent of level 3 path");

    VString testPath1;
    testPath2Node.getParentPath(testPath1);
    VFSNode testPath1Node(testPath1);
    VUNIT_ASSERT_EQUAL_LABELED(testPath1, "one", "parent of level 2 path");

    VString testPath0;
    testPath1Node.getParentPath(testPath0);
    VFSNode testPath0Node(testPath0);
    VUNIT_ASSERT_EQUAL_LABELED(testPath0, "", "parent of level 1 path");

    // Test oddities with DOS driver letters and mapped drives. Trailing slash on drive letter may or may be present.
#ifdef VPLATFORM_WIN
    // These tests assume that C: and C:Windows exist; some installations may use a different drive letter, in which case skip the test.
    const VString DRIVE_LETTER("C");
    const VString CHILD_NODE_NAME("Windows");
    if (VFSNode(VSTRING_FORMAT("%s:/%s", DRIVE_LETTER.chars(), CHILD_NODE_NAME.chars())).exists()) {
        this->_testWindowsDrivePaths(DRIVE_LETTER, CHILD_NODE_NAME, false, true);
        this->_testWindowsDrivePaths(DRIVE_LETTER, CHILD_NODE_NAME, true, true);
    }
#endif

    // Test assignment operator.
    VFSNode someNode("a/b/c/d");
    VFSNode copiedNode;
    copiedNode = someNode;
    VUNIT_ASSERT_EQUAL_LABELED(copiedNode.getPath(), "a/b/c/d", "assignment operator");

    /*
        Uncomment if you want to exercise this code. It's commented out for now because by its nature it
        will litter several directories with its output. (It tests the APIs that locate the various
        platform-dependent directories where log files, preference files, etc. should be written.
        So for now I've chosen not to exercise this code in this unit test.

        // Test known directory location lookup. Just write a file to each directory;
        // user will have to visually check that it was put in the right place.
        this->_writeKnownDirectoryTestFile(VFSNode::USER_HOME_DIRECTORY, "unittest-user");
        this->_writeKnownDirectoryTestFile(VFSNode::LOG_FILES_DIRECTORY, "unittest-logs");
        this->_writeKnownDirectoryTestFile(VFSNode::USER_PREFERENCES_DIRECTORY, "unittest-prefs");
        this->_writeKnownDirectoryTestFile(VFSNode::CACHED_DATA_DIRECTORY, "unittest-cache");
        this->_writeKnownDirectoryTestFile(VFSNode::APPLICATION_DATA_DIRECTORY, "unittest-appdata");
        this->_writeKnownDirectoryTestFile(VFSNode::CURRENT_WORKING_DIRECTORY, "unittest-cwd");
    */
}

void VFSNodeUnit::_testTextFileIO(const VString& seriesLabel, VFSNode& node, VAbstractFileStream& fileStream) {
    // This output line is just to mark which kind of file i/o we're doing:
    this->logStatus(seriesLabel);

    VTextIOStream io(fileStream);
    fileStream.openWrite();

    for (VStringVector::const_iterator i = mTextFileLines.begin(); i != mTextFileLines.end(); ++i)
        io.writeLine(*i);

    io.flush();

    fileStream.close();

    VUNIT_ASSERT_TRUE_LABELED(node.size() != 0, "non-empty file");
    VUNIT_ASSERT_TRUE_LABELED(node.isFile(), "is file");
    VUNIT_ASSERT_FALSE_LABELED(node.isDirectory(), "is not directory");

    fileStream.openReadOnly();

    VString line;
    int lineNumber = 1;
    for (VStringVector::const_iterator i = mTextFileLines.begin(); i != mTextFileLines.end(); ++i) {
        io.readLine(line);
        VUNIT_ASSERT_EQUAL_LABELED(line, *i, VSTRING_FORMAT("Line %d match", lineNumber));
        ++lineNumber;
    }

    try {
        // We should not be able to read any more lines.
        io.readLine(line);
        // If we get here, there's junk past the proper end of the file.
        VUNIT_ASSERT_FAILURE("EOF mark position");
    } catch (const VEOFException& /*ex*/) {
        VUNIT_ASSERT_SUCCESS("EOF mark position");
    } catch (...) {
        VUNIT_ASSERT_FAILURE("EOF mark position (unexpected exception type)");
    }

    fileStream.close();
}

void VFSNodeUnit::_testTextFileReadAll(VFSNode& node) {
    VString contents;
    node.readAll(contents);
    VUNIT_ASSERT_EQUAL_LABELED(contents, mTextFileContents, "VFSNode::readAll() to VString");

    VStringVector lines;
    node.readAll(lines);
    VUNIT_ASSERT_EQUAL_LABELED((int) lines.size(), (int) mTextFileLines.size(), "VFSNode::readAll() to VStringVector, count");

    int lineNumber = 1;
    for (size_t i = 0; i < lines.size(); ++i) {
        VUNIT_ASSERT_EQUAL_LABELED(lines[i], mTextFileLines[i], VSTRING_FORMAT("VFSNode::readAll() to VStringVector, line %d match", lineNumber));
        ++lineNumber;
    }
}

void VFSNodeUnit::_testBinaryFileIO(const VString& seriesLabel, VFSNode& node, VAbstractFileStream& fileStream) {
    // This output line is just to mark which kind of file i/o we're doing:
    this->logStatus(seriesLabel);

    VBinaryIOStream io(fileStream);

    fileStream.openWrite();

    io.writeS8(1);
    io.writeU8(2);
    io.writeS16(3);
    io.writeU16(4);
    io.writeS32(5L);
    io.writeU32(6L);
    io.writeS64(CONST_S64(7));
    io.writeU64(CONST_U64(8));
    io.writeFloat(9.9f);
    io.writeDouble(3.1415926);
    io.writeBool(true);
    io.writeString("hello");
    io.flush();

    fileStream.close();

    VUNIT_ASSERT_TRUE_LABELED(node.size() != 0, "non-empty file");
    VUNIT_ASSERT_TRUE_LABELED(node.isFile(), "is file");
    VUNIT_ASSERT_FALSE_LABELED(node.isDirectory(), "is not directory");

    fileStream.openReadOnly();

    VUNIT_ASSERT_TRUE_LABELED(io.readS8() == 1, "S8 match");
    VUNIT_ASSERT_TRUE_LABELED(io.readU8() == 2, "U8 match");
    VUNIT_ASSERT_TRUE_LABELED(io.readS16() == 3, "S16 match");
    VUNIT_ASSERT_TRUE_LABELED(io.readU16() == 4, "U16 match");
    VUNIT_ASSERT_TRUE_LABELED(io.readS32() == 5L, "S32 match");
    VUNIT_ASSERT_TRUE_LABELED(io.readU32() == 6L, "U32 match");
    VUNIT_ASSERT_TRUE_LABELED(io.readS64() == CONST_S64(7), "S64 match");
    VUNIT_ASSERT_TRUE_LABELED(io.readU64() == CONST_U64(8), "U64 match");
    VUNIT_ASSERT_TRUE_LABELED(io.readFloat() == 9.9f, "Float match");
    VUNIT_ASSERT_TRUE_LABELED(io.readDouble() == 3.1415926, "Double match");
    VUNIT_ASSERT_TRUE_LABELED(io.readBool() == true, "Bool match");
    VUNIT_ASSERT_TRUE_LABELED(io.readString() == "hello", "String match");
    try {
        // We should not be able to read any more data.
        (void) io.readU8();
        // If we get here, there's junk past the proper end of the file.
        VUNIT_ASSERT_FAILURE("EOF mark position");
    } catch (const VEOFException& /*ex*/) {
        VUNIT_ASSERT_SUCCESS("EOF mark position");
    } catch (...) {
        VUNIT_ASSERT_FAILURE("EOF mark position (unexpected exception type)");
    }

    fileStream.close();
}

void VFSNodeUnit::_testDirectoryIteration(const VFSNode& dir) {
    const int NUM_FILES_TO_CREATE = 5;
    const int NUM_FILES_TO_CHECK = NUM_FILES_TO_CREATE + 3; // we'll verify we don't have these extras

    // Test directory listing, iteration, find.
    // Create 5 files in the deep directory, then test that we can find them.
    for (int i = 0; i < NUM_FILES_TO_CREATE; ++i) {
        VString testIterFileName(VSTRING_ARGS("iter_test_%d.txt", i));
        VFSNode testIterFileNode;
        dir.getChildNode(testIterFileName, testIterFileNode);
        VBufferedFileStream testIterStream(testIterFileNode);
        testIterStream.openWrite();
        VTextIOStream out(testIterStream);
        out.writeLine(testIterFileName);
    }

    {
        // find() test
        VFSNode testIterNode;
        for (int i = 0; i < NUM_FILES_TO_CHECK; ++i) {
            VString testIterFileName(VSTRING_ARGS("iter_test_%d.txt", i));
            if (i < NUM_FILES_TO_CREATE)
                VUNIT_ASSERT_TRUE_LABELED(dir.find(testIterFileName, testIterNode), VSTRING_FORMAT("find() found #%d", i)); // this file should exist
            else
                VUNIT_ASSERT_FALSE_LABELED(dir.find(testIterFileName, testIterNode), VSTRING_FORMAT("find() did not find #%d", i)); // this file should not exist
        }
    }

    // There is no guarantee that the list() and iterate() methods will return the directory
    // listing in any particular order. We either need to sort them ourself, or verify without
    // regard to order. Here, we'll sort the returned string list, since we know that our
    // file names are sortable because they are single-digit-number-based strings, e.g. "iter_test_3.txt".
    // Note that the result of sorting is ultimately dependent on strcmp().

    {
        // list() names test
        int index = 0;
        VStringVector fileNames;
        dir.list(fileNames);
        std::sort(fileNames.begin(), fileNames.end());
        VUNIT_ASSERT_EQUAL_LABELED(static_cast<int>(fileNames.size()), NUM_FILES_TO_CREATE, "list names size");
        for (VStringVector::const_iterator i = fileNames.begin(); i != fileNames.end(); ++i, ++index) {
            VString testIterFileName(VSTRING_ARGS("iter_test_%d.txt", index));
            VUNIT_ASSERT_EQUAL_LABELED(*i, testIterFileName, VSTRING_FORMAT("list names #%d", index));
        }
    }

    {
        // list() nodes test
        int index = 0;
        VFSNodeVector fileNodes;
        dir.list(fileNodes);
        std::sort(fileNodes.begin(), fileNodes.end());
        VUNIT_ASSERT_EQUAL_LABELED(static_cast<int>(fileNodes.size()), NUM_FILES_TO_CREATE, "list nodes size");
        for (VFSNodeVector::const_iterator i = fileNodes.begin(); i != fileNodes.end(); ++i, ++index) {
            VString testIterFileName(VSTRING_ARGS("iter_test_%d.txt", index));
            VString nodeFileName;
            i->getName(nodeFileName);
            VUNIT_ASSERT_EQUAL_LABELED(nodeFileName, testIterFileName, VSTRING_FORMAT("list nodes #%d", index));
        }
    }

    {
        // iterate() test
        int index = 0;
        VFSNodeIterateTestCallback callback;
        dir.iterate(callback);
        std::sort(callback.mNodeNames.begin(), callback.mNodeNames.end());
        VUNIT_ASSERT_EQUAL_LABELED(static_cast<int>(callback.mNodeNames.size()), NUM_FILES_TO_CREATE, "iterate size");
        for (VStringVector::const_iterator i = callback.mNodeNames.begin(); i != callback.mNodeNames.end(); ++i, ++index) {
            VString testIterFileName(VSTRING_ARGS("iter_test_%d.txt", index));
            VUNIT_ASSERT_EQUAL_LABELED(*i, testIterFileName, VSTRING_FORMAT("iterate nodes #%d", index));
        }
    }

}

bool VFSNodeIterateTestCallback::handleNextNode(const VFSNode& node) {
    VString nodeName;
    node.getName(nodeName);
    mNodeNames.push_back(nodeName);
    return true;
}

void VFSNodeUnit::_writeKnownDirectoryTestFile(VFSNode::KnownDirectoryIdentifier id, const VString& fileName) {
    VFSNode folder = VFSNode::getKnownDirectoryNode(id, "BombayDigital", "unittest-temp");

    VFSNode fileNode;
    folder.getChildNode(fileName, fileNode);

    VBufferedFileStream fs(fileNode);
    fs.openWrite();

    VTextIOStream out(fs);

    VInstant now;
    out.writeLine(now.getLocalString());
    out.flush();

    this->logStatus(VSTRING_FORMAT("Wrote to file '%s'.", fileNode.getPath().chars()));
}

void VFSNodeUnit::_testWindowsDrivePaths(const VString& driveLetter, const VString& childNodeName, bool adornedWithSlash, bool childIsDirectory) {
    VString driveLetterNodeName(VSTRING_ARGS("%s:", driveLetter.chars()));
    VString adornedDriveLetterPath(VSTRING_ARGS("%s:%s", driveLetter.chars(), (adornedWithSlash ? VFSNode::PATH_SEPARATOR_CHARS : "")));

    VFSNode driveLetterNode(adornedDriveLetterPath);
    this->logStatus(VSTRING_FORMAT("Testing '%s'...", adornedDriveLetterPath.chars()));
    VUNIT_ASSERT_EQUAL_LABELED(driveLetterNode.getName(), driveLetterNodeName, "drive letter node name");
    VUNIT_ASSERT_EQUAL_LABELED(driveLetterNode.getParentPath(), "", "drive letter node parent path");
    VUNIT_ASSERT_EQUAL_LABELED(driveLetterNode.isDirectory(), true, "drive letter node is dir"); // this test assumes that drive C: exists; not true in some installations
    VUNIT_ASSERT_EQUAL_LABELED(driveLetterNode.isFile(), false, "drive letter node is not file");

    VString adornedChildNodePath(VSTRING_ARGS("%s:%s%s", driveLetter.chars(), (adornedWithSlash ? VFSNode::PATH_SEPARATOR_CHARS : ""), childNodeName.chars()));
    VFSNode childNode(driveLetterNode, childNodeName);
    this->logStatus(VSTRING_FORMAT("Testing '%s'...", adornedChildNodePath.chars()));
    VUNIT_ASSERT_EQUAL_LABELED(childNode.getName(), childNodeName, "drive letter child node name");
    VUNIT_ASSERT_EQUAL_LABELED(childNode.getParentPath(), driveLetterNodeName, "drive letter child node parent path");
    VUNIT_ASSERT_EQUAL_LABELED(childNode.isDirectory(), childIsDirectory, "drive letter child node is/not dir check"); // this test assumes that C:Windows dir exists; not true in some installations
    VUNIT_ASSERT_EQUAL_LABELED(childNode.isFile(), !childIsDirectory, "drive letter child node is/not file check");

    VString childFileName("child.txt");
    VString expectedChildPath(VSTRING_ARGS("%s:%c%s", driveLetter.chars(), VFSNode::PATH_SEPARATOR_CHAR, childFileName.chars()));
    VFSNode childFileNode(driveLetterNode, childFileName);
    this->logStatus(VSTRING_FORMAT("Testing '%s + %s'...", adornedDriveLetterPath.chars(), childFileName.chars()));
    VUNIT_ASSERT_EQUAL_LABELED(childFileNode.getName(), childFileName, "drive letter child file node name");
    VUNIT_ASSERT_EQUAL_LABELED(childFileNode.getParentPath(), driveLetterNodeName, "drive letter child file node parent path");
    VUNIT_ASSERT_EQUAL_LABELED(childFileNode.getPath(), expectedChildPath, "drive letter child file node path");
}


text:
package codeu.chat.client.core;

import java.util.ArrayList;
import java.util.Collection;

import codeu.chat.common.User;

public class Context extends codeu.chat.contexts.Context {

  private View view;
  private Controller controller;

  public Context(View view, Controller controller) {
    super(view, controller);
    this.view = view;
    this.controller = controller;
  }

  @Override
  public UserContext create(String name) {
    final User user = controller.newUser(name);
    return user == null ?
        null :
        new UserContext(user, view, controller);
  }

  @Override
  public Iterable<codeu.chat.contexts.UserContext> allUsers() {
    final Collection<codeu.chat.contexts.UserContext> users = new ArrayList<>();
    for (final User user : view.getUsers()) {
      users.add(new UserContext(user, view, controller));
    }
    return users;
  }

}


text:
#ifndef FUSION_IMAGE_GENERATOR_H
#define FUSION_IMAGE_GENERATOR_H

#include <Fusion/StdDefs.h>

#include <Fusion/Resource/Image.h>

#include <CGMath/Variant.h>

#include <Base/MT/Task.h>

NAMESPACE_BEGIN

/*==============================================================================
  CLASS ImageGenerator
==============================================================================*/
class ImageGenerator:
   public Task
{
public:

   /*----- static methods -----*/

   static void initialize();

   /*----- methods -----*/

   ImageGenerator(
      const           String&  path,
      const            Table*  args,
      const            Vec2i&  size,
      const Bitmap::PixelType  type        = Bitmap::BYTE,
      const               int  numChannels = 4 );
   //Add ctor with arguments Table.
   virtual ~ImageGenerator();

   virtual void execute();

   inline Image*  image() const { return _result.ptr(); }

protected:

   /*----- methods -----*/

   /*----- data members -----*/

   String             _path;
   RCP<const Table>   _args;

   Vec2i              _size;
   Bitmap::PixelType  _type;
   int                _chan;

   RCP<Image>         _result;

private:
}; //class ImageGenerator

NAMESPACE_END

#endif //FUSION_IMAGE_GENERATOR_H


text:
package br.com.six2six.fixturefactory.function;

import java.util.Arrays;
import java.util.List;

import br.com.six2six.fixturefactory.Fixture;
import br.com.six2six.fixturefactory.ObjectFactory;
import br.com.six2six.fixturefactory.processor.Processor;

public class FixtureFunction implements AtomicFunction, RelationFunction {

	private Class<?> clazz;

	private List<String> labels;

	private Integer quantity;

	public FixtureFunction(Class<?> clazz, String label) {
		this.clazz = clazz;
		this.labels = Arrays.asList(label);
	}

	public FixtureFunction(Class<?> clazz, String label, Integer quantity) {
		this(clazz, Arrays.asList(label), quantity);
	}

	public FixtureFunction(Class<?> clazz, List<String> labels, Integer quantity) {
		this.clazz = clazz;
		this.labels = labels;
		this.quantity = quantity;
	}

	@Override
	public <T> T generateValue() {
		return generate(Fixture.from(clazz));
	}

	@Override
	public <T> T generateValue(Processor processor) {
		return generate(Fixture.from(clazz).uses(processor));
	}

	@Override
	public <T> T generateValue(Object owner) {
		return generate(new ObjectFactory(Fixture.of(clazz), owner));
	}

	@Override
	public <T> T generateValue(Object owner, Processor processor) {
	    return generate(Fixture.from(clazz).uses(processor));
	}

	@SuppressWarnings("unchecked")
	private <T> T generate(ObjectFactory objectFactory) {
		if(quantity != null) {
			return gimmeWithQuantity(objectFactory);
		} else {
			return (T) objectFactory.gimme(getLabel());
		}
	}

	@SuppressWarnings("unchecked")
	private <T> T gimmeWithQuantity(ObjectFactory objectFactory) {
		if(labels.size() == 1) {
			return (T) objectFactory.gimme(quantity, getLabel());
		} else {
			return (T) objectFactory.gimme(quantity, labels);
		}
	}

	private String getLabel() {
		return labels.get(0);
	}
}


text:
HANDLE_IGET_X(OP_IGET_OBJECT_VOLATILE,  "-object-volatile", ObjectVolatile, _AS_OBJECT)
OP_END


text:
package org.slc.sli.headerfooter.service;

import com.liferay.portal.kernel.exception.PortalException;
import com.liferay.portal.kernel.exception.SystemException;
import com.liferay.portal.kernel.transaction.Isolation;
import com.liferay.portal.kernel.transaction.Propagation;
import com.liferay.portal.kernel.transaction.Transactional;
import com.liferay.portal.service.PersistedModelLocalService;

/**
 * The interface for the header footer local service.
 *
 *

 * This is a local service. Methods of this service will not have security checks based on the propagated JAAS credentials because this service can only be accessed from within the same VM.
 *

 *
 * @author manoj
 * @see HeaderFooterLocalServiceUtil
 * @see org.slc.sli.headerfooter.service.base.HeaderFooterLocalServiceBaseImpl
 * @see org.slc.sli.headerfooter.service.impl.HeaderFooterLocalServiceImpl
 * @generated
 */
@Transactional(isolation = Isolation.PORTAL, rollbackFor =  {
	PortalException.class, SystemException.class})
public interface HeaderFooterLocalService extends PersistedModelLocalService {
	/*
	 * NOTE FOR DEVELOPERS:
	 *
	 * Never modify or reference this interface directly. Always use {@link HeaderFooterLocalServiceUtil} to access the header footer local service. Add custom service methods to {@link org.slc.sli.headerfooter.service.impl.HeaderFooterLocalServiceImpl} and rerun ServiceBuilder to automatically copy the method declarations to this interface.
	 */

	/**
	* Adds the header footer to the database. Also notifies the appropriate model listeners.
	*
	* @param headerFooter the header footer
	* @return the header footer that was added
	* @throws SystemException if a system exception occurred
	*/
	public org.slc.sli.headerfooter.model.HeaderFooter addHeaderFooter(
		org.slc.sli.headerfooter.model.HeaderFooter headerFooter)
		throws com.liferay.portal.kernel.exception.SystemException;

	/**
	* Creates a new header footer with the primary key. Does not add the header footer to the database.
	*
	* @param id the primary key for the new header footer
	* @return the new header footer
	*/
	public org.slc.sli.headerfooter.model.HeaderFooter createHeaderFooter(
		long id);

	/**
	* Deletes the header footer with the primary key from the database. Also notifies the appropriate model listeners.
	*
	* @param id the primary key of the header footer
	* @throws PortalException if a header footer with the primary key could not be found
	* @throws SystemException if a system exception occurred
	*/
	public void deleteHeaderFooter(long id)
		throws com.liferay.portal.kernel.exception.PortalException,
			com.liferay.portal.kernel.exception.SystemException;

	/**
	* Deletes the header footer from the database. Also notifies the appropriate model listeners.
	*
	* @param headerFooter the header footer
	* @throws SystemException if a system exception occurred
	*/
	public void deleteHeaderFooter(
		org.slc.sli.headerfooter.model.HeaderFooter headerFooter)
		throws com.liferay.portal.kernel.exception.SystemException;

	/**
	* Performs a dynamic query on the database and returns the matching rows.
	*
	* @param dynamicQuery the dynamic query
	* @return the matching rows
	* @throws SystemException if a system exception occurred
	*/
	@SuppressWarnings("rawtypes")
	public java.util.List dynamicQuery(
		com.liferay.portal.kernel.dao.orm.DynamicQuery dynamicQuery)
		throws com.liferay.portal.kernel.exception.SystemException;

	/**
	* Performs a dynamic query on the database and returns a range of the matching rows.
	*
	*

	* Useful when paginating results. Returns a maximum of end - start instances. start and end are not primary keys, they are indexes in the result set. Thus, 0 refers to the first result in the set. Setting both start and end to {@link com.liferay.portal.kernel.dao.orm.QueryUtil#ALL_POS} will return the full result set.
	*

	*
	* @param dynamicQuery the dynamic query
	* @param start the lower bound of the range of model instances
	* @param end the upper bound of the range of model instances (not inclusive)
	* @return the range of matching rows
	* @throws SystemException if a system exception occurred
	*/
	@SuppressWarnings("rawtypes")
	public java.util.List dynamicQuery(
		com.liferay.portal.kernel.dao.orm.DynamicQuery dynamicQuery, int start,
		int end) throws com.liferay.portal.kernel.exception.SystemException;

	/**
	* Performs a dynamic query on the database and returns an ordered range of the matching rows.
	*
	*

	* Useful when paginating results. Returns a maximum of end - start instances. start and end are not primary keys, they are indexes in the result set. Thus, 0 refers to the first result in the set. Setting both start and end to {@link com.liferay.portal.kernel.dao.orm.QueryUtil#ALL_POS} will return the full result set.
	*

	*
	* @param dynamicQuery the dynamic query
	* @param start the lower bound of the range of model instances
	* @param end the upper bound of the range of model instances (not inclusive)
	* @param orderByComparator the comparator to order the results by (optionally null)
	* @return the ordered range of matching rows
	* @throws SystemException if a system exception occurred
	*/
	@SuppressWarnings("rawtypes")
	public java.util.List dynamicQuery(
		com.liferay.portal.kernel.dao.orm.DynamicQuery dynamicQuery, int start,
		int end,
		com.liferay.portal.kernel.util.OrderByComparator orderByComparator)
		throws com.liferay.portal.kernel.exception.SystemException;

	/**
	* Returns the number of rows that match the dynamic query.
	*
	* @param dynamicQuery the dynamic query
	* @return the number of rows that match the dynamic query
	* @throws SystemException if a system exception occurred
	*/
	public long dynamicQueryCount(
		com.liferay.portal.kernel.dao.orm.DynamicQuery dynamicQuery)
		throws com.liferay.portal.kernel.exception.SystemException;

	@Transactional(propagation = Propagation.SUPPORTS, readOnly = true)
	public org.slc.sli.headerfooter.model.HeaderFooter fetchHeaderFooter(
		long id) throws com.liferay.portal.kernel.exception.SystemException;

	/**
	* Returns the header footer with the primary key.
	*
	* @param id the primary key of the header footer
	* @return the header footer
	* @throws PortalException if a header footer with the primary key could not be found
	* @throws SystemException if a system exception occurred
	*/
	@Transactional(propagation = Propagation.SUPPORTS, readOnly = true)
	public org.slc.sli.headerfooter.model.HeaderFooter getHeaderFooter(long id)
		throws com.liferay.portal.kernel.exception.PortalException,
			com.liferay.portal.kernel.exception.SystemException;

	@Transactional(propagation = Propagation.SUPPORTS, readOnly = true)
	public com.liferay.portal.model.PersistedModel getPersistedModel(
		java.io.Serializable primaryKeyObj)
		throws com.liferay.portal.kernel.exception.PortalException,
			com.liferay.portal.kernel.exception.SystemException;

	/**
	* Returns a range of all the header footers.
	*
	*

	* Useful when paginating results. Returns a maximum of end - start instances. start and end are not primary keys, they are indexes in the result set. Thus, 0 refers to the first result in the set. Setting both start and end to {@link com.liferay.portal.kernel.dao.orm.QueryUtil#ALL_POS} will return the full result set.
	*

	*
	* @param start the lower bound of the range of header footers
	* @param end the upper bound of the range of header footers (not inclusive)
	* @return the range of header footers
	* @throws SystemException if a system exception occurred
	*/
	@Transactional(propagation = Propagation.SUPPORTS, readOnly = true)
	public java.util.List<org.slc.sli.headerfooter.model.HeaderFooter> getHeaderFooters(
		int start, int end)
		throws com.liferay.portal.kernel.exception.SystemException;

	/**
	* Returns the number of header footers.
	*
	* @return the number of header footers
	* @throws SystemException if a system exception occurred
	*/
	@Transactional(propagation = Propagation.SUPPORTS, readOnly = true)
	public int getHeaderFootersCount()
		throws com.liferay.portal.kernel.exception.SystemException;

	/**
	* Updates the header footer in the database or adds it if it does not yet exist. Also notifies the appropriate model listeners.
	*
	* @param headerFooter the header footer
	* @return the header footer that was updated
	* @throws SystemException if a system exception occurred
	*/
	public org.slc.sli.headerfooter.model.HeaderFooter updateHeaderFooter(
		org.slc.sli.headerfooter.model.HeaderFooter headerFooter)
		throws com.liferay.portal.kernel.exception.SystemException;

	/**
	* Updates the header footer in the database or adds it if it does not yet exist. Also notifies the appropriate model listeners.
	*
	* @param headerFooter the header footer
	* @param merge whether to merge the header footer with the current session. See {@link com.liferay.portal.service.persistence.BatchSession#update(com.liferay.portal.kernel.dao.orm.Session, com.liferay.portal.model.BaseModel, boolean)} for an explanation.
	* @return the header footer that was updated
	* @throws SystemException if a system exception occurred
	*/
	public org.slc.sli.headerfooter.model.HeaderFooter updateHeaderFooter(
		org.slc.sli.headerfooter.model.HeaderFooter headerFooter, boolean merge)
		throws com.liferay.portal.kernel.exception.SystemException;

	/**
	* Returns the Spring bean ID for this bean.
	*
	* @return the Spring bean ID for this bean
	*/
	public java.lang.String getBeanIdentifier();

	/**
	* Sets the Spring bean ID for this bean.
	*
	* @param beanIdentifier the Spring bean ID for this bean
	*/
	public void setBeanIdentifier(java.lang.String beanIdentifier);

	public org.slc.sli.headerfooter.model.HeaderFooter addHeader(
		java.lang.String headerData)
		throws com.liferay.portal.kernel.exception.PortalException,
			com.liferay.portal.kernel.exception.SystemException;

	public org.slc.sli.headerfooter.model.HeaderFooter editHeader(long id,
		java.lang.String headerData)
		throws com.liferay.portal.kernel.exception.PortalException,
			com.liferay.portal.kernel.exception.SystemException;

	@Transactional(propagation = Propagation.SUPPORTS, readOnly = true)
	public org.slc.sli.headerfooter.model.HeaderFooter getCurrentHeader()
		throws com.liferay.portal.kernel.exception.SystemException;

	@Transactional(propagation = Propagation.SUPPORTS, readOnly = true)
	public java.lang.String getHeader(java.lang.String token,
		java.lang.String currUrl)
		throws com.liferay.portal.kernel.exception.SystemException;

	@Transactional(propagation = Propagation.SUPPORTS, readOnly = true)
	public java.lang.String getHeader(boolean isAdmin)
		throws com.liferay.portal.kernel.exception.SystemException;

	public org.slc.sli.headerfooter.model.HeaderFooter addFooter(
		java.lang.String footerData)
		throws com.liferay.portal.kernel.exception.PortalException,
			com.liferay.portal.kernel.exception.SystemException;

	public org.slc.sli.headerfooter.model.HeaderFooter editFooter(long id,
		java.lang.String footerData)
		throws com.liferay.portal.kernel.exception.PortalException,
			com.liferay.portal.kernel.exception.SystemException;

	@Transactional(propagation = Propagation.SUPPORTS, readOnly = true)
	public org.slc.sli.headerfooter.model.HeaderFooter getCurrentFooter()
		throws com.liferay.portal.kernel.exception.SystemException;

	@Transactional(propagation = Propagation.SUPPORTS, readOnly = true)
	public java.lang.String getFooter(boolean isAdmin)
		throws com.liferay.portal.kernel.exception.SystemException;

	@Transactional(propagation = Propagation.SUPPORTS, readOnly = true)
	public java.lang.String getFooter(java.lang.String token)
		throws com.liferay.portal.kernel.exception.SystemException;
}


text:
"""Thumbnail directive for reStructuredText."""

import os

from docutils.parsers.rst import directives
from docutils.parsers.rst.directives.images import Image, Figure

from nikola.plugin_categories import RestExtension

class Plugin(RestExtension):
    """Plugin for thumbnail directive."""

    name = "rest_thumbnail"

    def set_site(self, site):
        """Set Nikola site."""
        self.site = site
        directives.register_directive('thumbnail', Thumbnail)
        return super(Plugin, self).set_site(site)

class Thumbnail(Figure):
    """Thumbnail directive for reST."""

    def align(argument):
        """Return thumbnail alignment."""
        return directives.choice(argument, Image.align_values)

    def figwidth_value(argument):
        """Return figure width."""
        if argument.lower() == 'image':
            return 'image'
        else:
            return directives.length_or_percentage_or_unitless(argument, 'px')

    option_spec = Image.option_spec.copy()
    option_spec['figwidth'] = figwidth_value
    option_spec['figclass'] = directives.class_option
    has_content = True

    def run(self):
        """Run the thumbnail directive."""
        uri = directives.uri(self.arguments[0])
        if uri.endswith('.svg'):
            # the ? at the end makes docutil output an <img> instead of an object for the svg, which lightboxes may require
            self.arguments[0] = '.thumbnail'.join(os.path.splitext(uri)) + '?'
        else:
            self.arguments[0] = '.thumbnail'.join(os.path.splitext(uri))
        self.options['target'] = uri
        if self.content:
            (node,) = Figure.run(self)
        else:
            (node,) = Image.run(self)
        return [node]