text:
// Copyright 2013 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 "webkit/browser/fileapi/file_system_operation_impl.h"

#include "base/bind.h"
#include "base/file_util.h"
#include "base/files/scoped_temp_dir.h"
#include "base/logging.h"
#include "base/memory/scoped_ptr.h"
#include "base/memory/weak_ptr.h"
#include "base/run_loop.h"
#include "base/strings/stringprintf.h"
#include "content/browser/fileapi/mock_file_change_observer.h"
#include "content/browser/quota/mock_quota_manager.h"
#include "content/browser/quota/mock_quota_manager_proxy.h"
#include "content/public/test/async_file_test_helper.h"
#include "content/public/test/sandbox_file_system_test_helper.h"
#include "testing/gtest/include/gtest/gtest.h"
#include "url/gurl.h"
#include "webkit/browser/fileapi/file_system_context.h"
#include "webkit/browser/fileapi/file_system_file_util.h"
#include "webkit/browser/fileapi/file_system_operation_context.h"
#include "webkit/browser/fileapi/file_system_operation_runner.h"
#include "webkit/browser/fileapi/sandbox_file_system_backend.h"
#include "webkit/browser/quota/quota_manager.h"
#include "webkit/browser/quota/quota_manager_proxy.h"
#include "webkit/common/blob/shareable_file_reference.h"
#include "webkit/common/fileapi/file_system_util.h"

using content::AsyncFileTestHelper;
using storage::FileSystemOperation;
using storage::FileSystemOperationContext;
using storage::FileSystemOperationRunner;
using storage::FileSystemURL;
using storage::QuotaManager;
using storage::QuotaManagerProxy;
using storage::ShareableFileReference;

namespace content {

namespace {

const int kFileOperationStatusNotSet = 1;

void AssertFileErrorEq(const tracked_objects::Location& from_here,
                       base::File::Error expected,
                       base::File::Error actual) {
  ASSERT_EQ(expected, actual) << from_here.ToString();
}

}  // namespace

// Test class for FileSystemOperationImpl.
class FileSystemOperationImplTest
    : public testing::Test {
 public:
  FileSystemOperationImplTest()
      : status_(kFileOperationStatusNotSet),
        weak_factory_(this) {}

 protected:
  virtual void SetUp() OVERRIDE {
    EXPECT_TRUE(base_.CreateUniqueTempDir());
    change_observers_ =
        storage::MockFileChangeObserver::CreateList(&change_observer_);

    base::FilePath base_dir = base_.path().AppendASCII("filesystem");
    quota_manager_ =
        new MockQuotaManager(false /* is_incognito */,
                                    base_dir,
                                    base::MessageLoopProxy::current().get(),
                                    base::MessageLoopProxy::current().get(),
                                    NULL /* special storage policy */);
    quota_manager_proxy_ = new MockQuotaManagerProxy(
        quota_manager(), base::MessageLoopProxy::current().get());
    sandbox_file_system_.SetUp(base_dir, quota_manager_proxy_.get());
    sandbox_file_system_.AddFileChangeObserver(&change_observer_);
  }

  virtual void TearDown() OVERRIDE {
    // Let the client go away before dropping a ref of the quota manager proxy.
    quota_manager_proxy()->SimulateQuotaManagerDestroyed();
    quota_manager_ = NULL;
    quota_manager_proxy_ = NULL;
    sandbox_file_system_.TearDown();
  }

  FileSystemOperationRunner* operation_runner() {
    return sandbox_file_system_.operation_runner();
  }

  int status() const { return status_; }
  const base::File::Info& info() const { return info_; }
  const base::FilePath& path() const { return path_; }
  const std::vector<storage::DirectoryEntry>& entries() const {
    return entries_;
  }

  const ShareableFileReference* shareable_file_ref() const {
    return shareable_file_ref_.get();
  }

  MockQuotaManager* quota_manager() {
    return static_cast<MockQuotaManager*>(quota_manager_.get());
  }

  MockQuotaManagerProxy* quota_manager_proxy() {
    return static_cast<MockQuotaManagerProxy*>(
        quota_manager_proxy_.get());
  }

  storage::FileSystemFileUtil* file_util() {
    return sandbox_file_system_.file_util();
  }

  storage::MockFileChangeObserver* change_observer() {
    return &change_observer_;
  }

  scoped_ptr<FileSystemOperationContext> NewContext() {
    FileSystemOperationContext* context =
        sandbox_file_system_.NewOperationContext();
    // Grant enough quota for all test cases.
    context->set_allowed_bytes_growth(1000000);
    return make_scoped_ptr(context);
  }

  FileSystemURL URLForPath(const std::string& path) const {
    return sandbox_file_system_.CreateURLFromUTF8(path);
  }

  base::FilePath PlatformPath(const std::string& path) {
    return sandbox_file_system_.GetLocalPath(
        base::FilePath::FromUTF8Unsafe(path));
  }

  bool FileExists(const std::string& path) {
    return AsyncFileTestHelper::FileExists(
        sandbox_file_system_.file_system_context(), URLForPath(path),
        AsyncFileTestHelper::kDontCheckSize);
  }

  bool DirectoryExists(const std::string& path) {
    return AsyncFileTestHelper::DirectoryExists(
        sandbox_file_system_.file_system_context(), URLForPath(path));
  }

  FileSystemURL CreateFile(const std::string& path) {
    FileSystemURL url = URLForPath(path);
    bool created = false;
    EXPECT_EQ(base::File::FILE_OK,
              file_util()->EnsureFileExists(NewContext().get(),
                                            url, &created));
    EXPECT_TRUE(created);
    return url;
  }

  FileSystemURL CreateDirectory(const std::string& path) {
    FileSystemURL url = URLForPath(path);
    EXPECT_EQ(base::File::FILE_OK,
              file_util()->CreateDirectory(NewContext().get(), url,
                                           false /* exclusive */, true));
    return url;
  }

  int64 GetFileSize(const std::string& path) {
    base::File::Info info;
    EXPECT_TRUE(base::GetFileInfo(PlatformPath(path), &info));
    return info.size;
  }

  // Callbacks for recording test results.
  FileSystemOperation::StatusCallback RecordStatusCallback() {
    return base::Bind(&FileSystemOperationImplTest::DidFinish,
                      weak_factory_.GetWeakPtr());
  }

  FileSystemOperation::ReadDirectoryCallback
  RecordReadDirectoryCallback() {
    return base::Bind(&FileSystemOperationImplTest::DidReadDirectory,
                      weak_factory_.GetWeakPtr());
  }

  FileSystemOperation::GetMetadataCallback RecordMetadataCallback() {
    return base::Bind(&FileSystemOperationImplTest::DidGetMetadata,
                      weak_factory_.GetWeakPtr());
  }

  FileSystemOperation::SnapshotFileCallback RecordSnapshotFileCallback() {
    return base::Bind(&FileSystemOperationImplTest::DidCreateSnapshotFile,
                      weak_factory_.GetWeakPtr());
  }

  void DidFinish(base::File::Error status) {
    status_ = status;
  }

  void DidReadDirectory(base::File::Error status,
                        const std::vector<storage::DirectoryEntry>& entries,
                        bool /* has_more */) {
    entries_ = entries;
    status_ = status;
  }

  void DidGetMetadata(base::File::Error status,
                      const base::File::Info& info) {
    info_ = info;
    status_ = status;
  }

  void DidCreateSnapshotFile(
      base::File::Error status,
      const base::File::Info& info,
      const base::FilePath& platform_path,
      const scoped_refptr<ShareableFileReference>& shareable_file_ref) {
    info_ = info;
    path_ = platform_path;
    status_ = status;
    shareable_file_ref_ = shareable_file_ref;
  }

  int64 GetDataSizeOnDisk() {
    return sandbox_file_system_.ComputeCurrentOriginUsage() -
        sandbox_file_system_.ComputeCurrentDirectoryDatabaseUsage();
  }

  void GetUsageAndQuota(int64* usage, int64* quota) {
    storage::QuotaStatusCode status =
        AsyncFileTestHelper::GetUsageAndQuota(quota_manager_.get(),
                                              sandbox_file_system_.origin(),
                                              sandbox_file_system_.type(),
                                              usage,
                                              quota);
    base::RunLoop().RunUntilIdle();
    ASSERT_EQ(storage::kQuotaStatusOk, status);
  }

  int64 ComputePathCost(const FileSystemURL& url) {
    int64 base_usage;
    GetUsageAndQuota(&base_usage, NULL);

    AsyncFileTestHelper::CreateFile(
        sandbox_file_system_.file_system_context(), url);
    operation_runner()->Remove(url, false /* recursive */,
                               base::Bind(&AssertFileErrorEq, FROM_HERE,
                                          base::File::FILE_OK));
    base::RunLoop().RunUntilIdle();
    change_observer()->ResetCount();

    int64 total_usage;
    GetUsageAndQuota(&total_usage, NULL);
    return total_usage - base_usage;
  }

  void GrantQuotaForCurrentUsage() {
    int64 usage;
    GetUsageAndQuota(&usage, NULL);
    quota_manager()->SetQuota(sandbox_file_system_.origin(),
                              sandbox_file_system_.storage_type(),
                              usage);
  }

  int64 GetUsage() {
    int64 usage = 0;
    GetUsageAndQuota(&usage, NULL);
    return usage;
  }

  void AddQuota(int64 quota_delta) {
    int64 quota;
    GetUsageAndQuota(NULL, &quota);
    quota_manager()->SetQuota(sandbox_file_system_.origin(),
                              sandbox_file_system_.storage_type(),
                              quota + quota_delta);
  }

 private:
  base::MessageLoop message_loop_;
  scoped_refptr<QuotaManager> quota_manager_;
  scoped_refptr<QuotaManagerProxy> quota_manager_proxy_;

  // Common temp base for nondestructive uses.
  base::ScopedTempDir base_;

  SandboxFileSystemTestHelper sandbox_file_system_;

  // For post-operation status.
  int status_;
  base::File::Info info_;
  base::FilePath path_;
  std::vector<storage::DirectoryEntry> entries_;
  scoped_refptr<ShareableFileReference> shareable_file_ref_;

  storage::MockFileChangeObserver change_observer_;
  storage::ChangeObserverList change_observers_;

  base::WeakPtrFactory<FileSystemOperationImplTest> weak_factory_;

  DISALLOW_COPY_AND_ASSIGN(FileSystemOperationImplTest);
};

TEST_F(FileSystemOperationImplTest, TestMoveFailureSrcDoesntExist) {
  change_observer()->ResetCount();
  operation_runner()->Move(URLForPath("a"), URLForPath("b"),
                           FileSystemOperation::OPTION_NONE,
                           RecordStatusCallback());
  base::RunLoop().RunUntilIdle();
  EXPECT_EQ(base::File::FILE_ERROR_NOT_FOUND, status());
  EXPECT_TRUE(change_observer()->HasNoChange());
}

TEST_F(FileSystemOperationImplTest, TestMoveFailureContainsPath) {
  FileSystemURL src_dir(CreateDirectory("src"));
  FileSystemURL dest_dir(CreateDirectory("src/dest"));

  operation_runner()->Move(src_dir, dest_dir,
                           FileSystemOperation::OPTION_NONE,
                           RecordStatusCallback());
  base::RunLoop().RunUntilIdle();
  EXPECT_EQ(base::File::FILE_ERROR_INVALID_OPERATION, status());
  EXPECT_TRUE(change_observer()->HasNoChange());
}

TEST_F(FileSystemOperationImplTest, TestMoveFailureSrcDirExistsDestFile) {
  // Src exists and is dir. Dest is a file.
  FileSystemURL src_dir(CreateDirectory("src"));
  FileSystemURL dest_dir(CreateDirectory("dest"));
  FileSystemURL dest_file(CreateFile("dest/file"));

  operation_runner()->Move(src_dir, dest_file,
                           FileSystemOperation::OPTION_NONE,
                           RecordStatusCallback());
  base::RunLoop().RunUntilIdle();
  EXPECT_EQ(base::File::FILE_ERROR_INVALID_OPERATION, status());
  EXPECT_TRUE(change_observer()->HasNoChange());
}

TEST_F(FileSystemOperationImplTest,
       TestMoveFailureSrcFileExistsDestNonEmptyDir) {
  // Src exists and is a directory. Dest is a non-empty directory.
  FileSystemURL src_dir(CreateDirectory("src"));
  FileSystemURL dest_dir(CreateDirectory("dest"));
  FileSystemURL dest_file(CreateFile("dest/file"));

  operation_runner()->Move(src_dir, dest_dir,
                           FileSystemOperation::OPTION_NONE,
                           RecordStatusCallback());
  base::RunLoop().RunUntilIdle();
  EXPECT_EQ(base::File::FILE_ERROR_NOT_EMPTY, status());
  EXPECT_TRUE(change_observer()->HasNoChange());
}

TEST_F(FileSystemOperationImplTest, TestMoveFailureSrcFileExistsDestDir) {
  // Src exists and is a file. Dest is a directory.
  FileSystemURL src_dir(CreateDirectory("src"));
  FileSystemURL src_file(CreateFile("src/file"));
  FileSystemURL dest_dir(CreateDirectory("dest"));

  operation_runner()->Move(src_file, dest_dir,
                           FileSystemOperation::OPTION_NONE,
                           RecordStatusCallback());
  base::RunLoop().RunUntilIdle();
  EXPECT_EQ(base::File::FILE_ERROR_INVALID_OPERATION, status());
  EXPECT_TRUE(change_observer()->HasNoChange());
}

TEST_F(FileSystemOperationImplTest, TestMoveFailureDestParentDoesntExist) {
  // Dest. parent path does not exist.
  FileSystemURL src_dir(CreateDirectory("src"));
  operation_runner()->Move(src_dir, URLForPath("nonexistent/deset"),
                           FileSystemOperation::OPTION_NONE,
                           RecordStatusCallback());
  base::RunLoop().RunUntilIdle();
  EXPECT_EQ(base::File::FILE_ERROR_NOT_FOUND, status());
  EXPECT_TRUE(change_observer()->HasNoChange());
}

TEST_F(FileSystemOperationImplTest, TestMoveSuccessSrcFileAndOverwrite) {
  FileSystemURL src_file(CreateFile("src"));
  FileSystemURL dest_file(CreateFile("dest"));

  operation_runner()->Move(src_file, dest_file,
                           FileSystemOperation::OPTION_NONE,
                           RecordStatusCallback());
  base::RunLoop().RunUntilIdle();
  EXPECT_EQ(base::File::FILE_OK, status());
  EXPECT_TRUE(FileExists("dest"));

  EXPECT_EQ(1, change_observer()->get_and_reset_modify_file_count());
  EXPECT_EQ(1, change_observer()->get_and_reset_remove_file_count());
  EXPECT_TRUE(change_observer()->HasNoChange());

  EXPECT_EQ(1, quota_manager_proxy()->notify_storage_accessed_count());
}

TEST_F(FileSystemOperationImplTest, TestMoveSuccessSrcFileAndNew) {
  FileSystemURL src_file(CreateFile("src"));

  operation_runner()->Move(src_file, URLForPath("new"),
                           FileSystemOperation::OPTION_NONE,
                           RecordStatusCallback());
  base::RunLoop().RunUntilIdle();
  EXPECT_EQ(base::File::FILE_OK, status());
  EXPECT_TRUE(FileExists("new"));

  EXPECT_EQ(1, change_observer()->get_and_reset_create_file_from_count());
  EXPECT_EQ(1, change_observer()->get_and_reset_remove_file_count());
  EXPECT_TRUE(change_observer()->HasNoChange());
}

TEST_F(FileSystemOperationImplTest, TestMoveSuccessSrcDirAndOverwrite) {
  FileSystemURL src_dir(CreateDirectory("src"));
  FileSystemURL dest_dir(CreateDirectory("dest"));

  operation_runner()->Move(src_dir, dest_dir,
                           FileSystemOperation::OPTION_NONE,
                           RecordStatusCallback());
  base::RunLoop().RunUntilIdle();
  EXPECT_EQ(base::File::FILE_OK, status());
  EXPECT_FALSE(DirectoryExists("src"));

  EXPECT_EQ(1, change_observer()->get_and_reset_create_directory_count());
  EXPECT_EQ(2, change_observer()->get_and_reset_remove_directory_count());
  EXPECT_TRUE(change_observer()->HasNoChange());

  // Make sure we've overwritten but not moved the source under the |dest_dir|.
  EXPECT_TRUE(DirectoryExists("dest"));
  EXPECT_FALSE(DirectoryExists("dest/src"));
}

TEST_F(FileSystemOperationImplTest, TestMoveSuccessSrcDirAndNew) {
  FileSystemURL src_dir(CreateDirectory("src"));
  FileSystemURL dest_dir(CreateDirectory("dest"));

  operation_runner()->Move(src_dir, URLForPath("dest/new"),
                           FileSystemOperation::OPTION_NONE,
                           RecordStatusCallback());
  base::RunLoop().RunUntilIdle();
  EXPECT_EQ(base::File::FILE_OK, status());
  EXPECT_FALSE(DirectoryExists("src"));
  EXPECT_TRUE(DirectoryExists("dest/new"));

  EXPECT_EQ(1, change_observer()->get_and_reset_remove_directory_count());
  EXPECT_EQ(1, change_observer()->get_and_reset_create_directory_count());
  EXPECT_TRUE(change_observer()->HasNoChange());
}

TEST_F(FileSystemOperationImplTest, TestMoveSuccessSrcDirRecursive) {
  FileSystemURL src_dir(CreateDirectory("src"));
  CreateDirectory("src/dir");
  CreateFile("src/dir/sub");

  FileSystemURL dest_dir(CreateDirectory("dest"));

  operation_runner()->Move(src_dir, dest_dir,
                           FileSystemOperation::OPTION_NONE,
                           RecordStatusCallback());
  base::RunLoop().RunUntilIdle();
  EXPECT_EQ(base::File::FILE_OK, status());
  EXPECT_TRUE(DirectoryExists("dest/dir"));
  EXPECT_TRUE(FileExists("dest/dir/sub"));

  EXPECT_EQ(3, change_observer()->get_and_reset_remove_directory_count());
  EXPECT_EQ(2, change_observer()->get_and_reset_create_directory_count());
  EXPECT_EQ(1, change_observer()->get_and_reset_remove_file_count());
  EXPECT_EQ(1, change_observer()->get_and_reset_create_file_from_count());
  EXPECT_TRUE(change_observer()->HasNoChange());
}

TEST_F(FileSystemOperationImplTest, TestMoveSuccessSamePath) {
  FileSystemURL src_dir(CreateDirectory("src"));
  CreateDirectory("src/dir");
  CreateFile("src/dir/sub");

  operation_runner()->Move(src_dir, src_dir,
                           FileSystemOperation::OPTION_NONE,
                           RecordStatusCallback());
  base::RunLoop().RunUntilIdle();
  EXPECT_EQ(base::File::FILE_OK, status());
  EXPECT_TRUE(DirectoryExists("src/dir"));
  EXPECT_TRUE(FileExists("src/dir/sub"));

  EXPECT_EQ(0, change_observer()->get_and_reset_remove_directory_count());
  EXPECT_EQ(0, change_observer()->get_and_reset_create_directory_count());
  EXPECT_EQ(0, change_observer()->get_and_reset_remove_file_count());
  EXPECT_EQ(0, change_observer()->get_and_reset_create_file_from_count());
  EXPECT_TRUE(change_observer()->HasNoChange());
}

TEST_F(FileSystemOperationImplTest, TestCopyFailureSrcDoesntExist) {
  operation_runner()->Copy(URLForPath("a"), URLForPath("b"),
                           FileSystemOperation::OPTION_NONE,
                           FileSystemOperationRunner::CopyProgressCallback(),
                           RecordStatusCallback());
  base::RunLoop().RunUntilIdle();
  EXPECT_EQ(base::File::FILE_ERROR_NOT_FOUND, status());
  EXPECT_TRUE(change_observer()->HasNoChange());
}

TEST_F(FileSystemOperationImplTest, TestCopyFailureContainsPath) {
  FileSystemURL src_dir(CreateDirectory("src"));
  FileSystemURL dest_dir(CreateDirectory("src/dir"));

  operation_runner()->Copy(src_dir, dest_dir,
                           FileSystemOperation::OPTION_NONE,
                           FileSystemOperationRunner::CopyProgressCallback(),
                           RecordStatusCallback());
  base::RunLoop().RunUntilIdle();
  EXPECT_EQ(base::File::FILE_ERROR_INVALID_OPERATION, status());
  EXPECT_TRUE(change_observer()->HasNoChange());
}

TEST_F(FileSystemOperationImplTest, TestCopyFailureSrcDirExistsDestFile) {
  // Src exists and is dir. Dest is a file.
  FileSystemURL src_dir(CreateDirectory("src"));
  FileSystemURL dest_dir(CreateDirectory("dest"));
  FileSystemURL dest_file(CreateFile("dest/file"));

  operation_runner()->Copy(src_dir, dest_file,
                           FileSystemOperation::OPTION_NONE,
                           FileSystemOperationRunner::CopyProgressCallback(),
                           RecordStatusCallback());
  base::RunLoop().RunUntilIdle();
  EXPECT_EQ(base::File::FILE_ERROR_INVALID_OPERATION, status());
  EXPECT_TRUE(change_observer()->HasNoChange());
}

TEST_F(FileSystemOperationImplTest,
       TestCopyFailureSrcFileExistsDestNonEmptyDir) {
  // Src exists and is a directory. Dest is a non-empty directory.
  FileSystemURL src_dir(CreateDirectory("src"));
  FileSystemURL dest_dir(CreateDirectory("dest"));
  FileSystemURL dest_file(CreateFile("dest/file"));

  operation_runner()->Copy(src_dir, dest_dir,
                           FileSystemOperation::OPTION_NONE,
                           FileSystemOperationRunner::CopyProgressCallback(),
                           RecordStatusCallback());
  base::RunLoop().RunUntilIdle();
  EXPECT_EQ(base::File::FILE_ERROR_NOT_EMPTY, status());
  EXPECT_TRUE(change_observer()->HasNoChange());
}

TEST_F(FileSystemOperationImplTest, TestCopyFailureSrcFileExistsDestDir) {
  // Src exists and is a file. Dest is a directory.
  FileSystemURL src_file(CreateFile("src"));
  FileSystemURL dest_dir(CreateDirectory("dest"));

  operation_runner()->Copy(src_file, dest_dir,
                           FileSystemOperation::OPTION_NONE,
                           FileSystemOperationRunner::CopyProgressCallback(),
                           RecordStatusCallback());
  base::RunLoop().RunUntilIdle();
  EXPECT_EQ(base::File::FILE_ERROR_INVALID_OPERATION, status());
  EXPECT_TRUE(change_observer()->HasNoChange());
}

TEST_F(FileSystemOperationImplTest, TestCopyFailureDestParentDoesntExist) {
  // Dest. parent path does not exist.
  FileSystemURL src_dir(CreateDirectory("src"));

  operation_runner()->Copy(src_dir, URLForPath("nonexistent/dest"),
                           FileSystemOperation::OPTION_NONE,
                           FileSystemOperationRunner::CopyProgressCallback(),
                           RecordStatusCallback());
  base::RunLoop().RunUntilIdle();
  EXPECT_EQ(base::File::FILE_ERROR_NOT_FOUND, status());
  EXPECT_TRUE(change_observer()->HasNoChange());
}

TEST_F(FileSystemOperationImplTest, TestCopyFailureByQuota) {
  FileSystemURL src_dir(CreateDirectory("src"));
  FileSystemURL src_file(CreateFile("src/file"));
  FileSystemURL dest_dir(CreateDirectory("dest"));
  operation_runner()->Truncate(src_file, 6, RecordStatusCallback());
  base::RunLoop().RunUntilIdle();
  EXPECT_EQ(base::File::FILE_OK, status());
  EXPECT_EQ(6, GetFileSize("src/file"));

  FileSystemURL dest_file(URLForPath("dest/file"));
  int64 dest_path_cost = ComputePathCost(dest_file);
  GrantQuotaForCurrentUsage();
  AddQuota(6 + dest_path_cost - 1);

  operation_runner()->Copy(src_file, dest_file,
                           FileSystemOperation::OPTION_NONE,
                           FileSystemOperationRunner::CopyProgressCallback(),
                           RecordStatusCallback());
  base::RunLoop().RunUntilIdle();
  EXPECT_EQ(base::File::FILE_ERROR_NO_SPACE, status());
  EXPECT_FALSE(FileExists("dest/file"));
}

TEST_F(FileSystemOperationImplTest, TestCopySuccessSrcFileAndOverwrite) {
  FileSystemURL src_file(CreateFile("src"));
  FileSystemURL dest_file(CreateFile("dest"));

  operation_runner()->Copy(src_file, dest_file,
                           FileSystemOperation::OPTION_NONE,
                           FileSystemOperationRunner::CopyProgressCallback(),
                           RecordStatusCallback());
  base::RunLoop().RunUntilIdle();
  EXPECT_EQ(base::File::FILE_OK, status());
  EXPECT_TRUE(FileExists("dest"));
  EXPECT_EQ(2, quota_manager_proxy()->notify_storage_accessed_count());

  EXPECT_EQ(1, change_observer()->get_and_reset_modify_file_count());
  EXPECT_TRUE(change_observer()->HasNoChange());
}

TEST_F(FileSystemOperationImplTest, TestCopySuccessSrcFileAndNew) {
  FileSystemURL src_file(CreateFile("src"));

  operation_runner()->Copy(src_file, URLForPath("new"),
                           FileSystemOperation::OPTION_NONE,
                           FileSystemOperationRunner::CopyProgressCallback(),
                           RecordStatusCallback());
  base::RunLoop().RunUntilIdle();
  EXPECT_EQ(base::File::FILE_OK, status());
  EXPECT_TRUE(FileExists("new"));
  EXPECT_EQ(2, quota_manager_proxy()->notify_storage_accessed_count());

  EXPECT_EQ(1, change_observer()->get_and_reset_create_file_from_count());
  EXPECT_TRUE(change_observer()->HasNoChange());
}

TEST_F(FileSystemOperationImplTest, TestCopySuccessSrcDirAndOverwrite) {
  FileSystemURL src_dir(CreateDirectory("src"));
  FileSystemURL dest_dir(CreateDirectory("dest"));

  operation_runner()->Copy(src_dir, dest_dir,
                           FileSystemOperation::OPTION_NONE,
                           FileSystemOperationRunner::CopyProgressCallback(),
                           RecordStatusCallback());
  base::RunLoop().RunUntilIdle();
  EXPECT_EQ(base::File::FILE_OK, status());

  // Make sure we've overwritten but not copied the source under the |dest_dir|.
  EXPECT_TRUE(DirectoryExists("dest"));
  EXPECT_FALSE(DirectoryExists("dest/src"));
  EXPECT_GE(quota_manager_proxy()->notify_storage_accessed_count(), 3);

  EXPECT_EQ(1, change_observer()->get_and_reset_remove_directory_count());
  EXPECT_EQ(1, change_observer()->get_and_reset_create_directory_count());
  EXPECT_TRUE(change_observer()->HasNoChange());
}

TEST_F(FileSystemOperationImplTest, TestCopySuccessSrcDirAndNew) {
  FileSystemURL src_dir(CreateDirectory("src"));
  FileSystemURL dest_dir_new(URLForPath("dest"));

  operation_runner()->Copy(src_dir, dest_dir_new,
                           FileSystemOperation::OPTION_NONE,
                           FileSystemOperationRunner::CopyProgressCallback(),
                           RecordStatusCallback());
  base::RunLoop().RunUntilIdle();
  EXPECT_EQ(base::File::FILE_OK, status());
  EXPECT_TRUE(DirectoryExists("dest"));
  EXPECT_GE(quota_manager_proxy()->notify_storage_accessed_count(), 2);

  EXPECT_EQ(1, change_observer()->get_and_reset_create_directory_count());
  EXPECT_TRUE(change_observer()->HasNoChange());
}

TEST_F(FileSystemOperationImplTest, TestCopySuccessSrcDirRecursive) {
  FileSystemURL src_dir(CreateDirectory("src"));
  CreateDirectory("src/dir");
  CreateFile("src/dir/sub");

  FileSystemURL dest_dir(CreateDirectory("dest"));

  operation_runner()->Copy(src_dir, dest_dir,
                           FileSystemOperation::OPTION_NONE,
                           FileSystemOperationRunner::CopyProgressCallback(),
                           RecordStatusCallback());
  base::RunLoop().RunUntilIdle();

  EXPECT_EQ(base::File::FILE_OK, status());
  EXPECT_TRUE(DirectoryExists("dest/dir"));
  EXPECT_TRUE(FileExists("dest/dir/sub"));

  // For recursive copy we may record multiple read access.
  EXPECT_GE(quota_manager_proxy()->notify_storage_accessed_count(), 1);

  EXPECT_EQ(2, change_observer()->get_and_reset_create_directory_count());
  EXPECT_EQ(1, change_observer()->get_and_reset_remove_directory_count());
  EXPECT_EQ(1, change_observer()->get_and_reset_create_file_from_count());
  EXPECT_TRUE(change_observer()->HasNoChange());
}

TEST_F(FileSystemOperationImplTest, TestCopySuccessSamePath) {
  FileSystemURL src_dir(CreateDirectory("src"));
  CreateDirectory("src/dir");
  CreateFile("src/dir/sub");

  operation_runner()->Copy(src_dir, src_dir,
                           FileSystemOperation::OPTION_NONE,
                           FileSystemOperationRunner::CopyProgressCallback(),
                           RecordStatusCallback());
  base::RunLoop().RunUntilIdle();

  EXPECT_EQ(base::File::FILE_OK, status());
  EXPECT_TRUE(DirectoryExists("src/dir"));
  EXPECT_TRUE(FileExists("src/dir/sub"));

  EXPECT_EQ(0, change_observer()->get_and_reset_create_directory_count());
  EXPECT_EQ(0, change_observer()->get_and_reset_remove_file_count());
  EXPECT_EQ(0, change_observer()->get_and_reset_create_file_from_count());
  EXPECT_TRUE(change_observer()->HasNoChange());
}

TEST_F(FileSystemOperationImplTest, TestCopyInForeignFileSuccess) {
  base::FilePath src_local_disk_file_path;
  base::CreateTemporaryFile(&src_local_disk_file_path);
  const char test_data[] = "foo";
  int data_size = ARRAYSIZE_UNSAFE(test_data);
  base::WriteFile(src_local_disk_file_path, test_data, data_size);

  FileSystemURL dest_dir(CreateDirectory("dest"));

  int64 before_usage;
  GetUsageAndQuota(&before_usage, NULL);

  // Check that the file copied and corresponding usage increased.
  operation_runner()->CopyInForeignFile(src_local_disk_file_path,
                                        URLForPath("dest/file"),
                                        RecordStatusCallback());
  base::RunLoop().RunUntilIdle();

  EXPECT_EQ(1, change_observer()->create_file_count());
  EXPECT_EQ(base::File::FILE_OK, status());
  EXPECT_TRUE(FileExists("dest/file"));
  int64 after_usage;
  GetUsageAndQuota(&after_usage, NULL);
  EXPECT_GT(after_usage, before_usage);

  // Compare contents of src and copied file.
  char buffer[100];
  EXPECT_EQ(data_size, base::ReadFile(PlatformPath("dest/file"),
                                      buffer, data_size));
  for (int i = 0; i < data_size; ++i)
    EXPECT_EQ(test_data[i], buffer[i]);
}

TEST_F(FileSystemOperationImplTest, TestCopyInForeignFileFailureByQuota) {
  base::FilePath src_local_disk_file_path;
  base::CreateTemporaryFile(&src_local_disk_file_path);
  const char test_data[] = "foo";
  base::WriteFile(src_local_disk_file_path, test_data,
                       ARRAYSIZE_UNSAFE(test_data));

  FileSystemURL dest_dir(CreateDirectory("dest"));

  GrantQuotaForCurrentUsage();
  operation_runner()->CopyInForeignFile(src_local_disk_file_path,
                                        URLForPath("dest/file"),
                                        RecordStatusCallback());
  base::RunLoop().RunUntilIdle();

  EXPECT_FALSE(FileExists("dest/file"));
  EXPECT_EQ(0, change_observer()->create_file_count());
  EXPECT_EQ(base::File::FILE_ERROR_NO_SPACE, status());
}

TEST_F(FileSystemOperationImplTest, TestCreateFileFailure) {
  // Already existing file and exclusive true.
  FileSystemURL file(CreateFile("file"));
  operation_runner()->CreateFile(file, true, RecordStatusCallback());
  base::RunLoop().RunUntilIdle();
  EXPECT_EQ(base::File::FILE_ERROR_EXISTS, status());
  EXPECT_TRUE(change_observer()->HasNoChange());
}

TEST_F(FileSystemOperationImplTest, TestCreateFileSuccessFileExists) {
  // Already existing file and exclusive false.
  FileSystemURL file(CreateFile("file"));
  operation_runner()->CreateFile(file, false, RecordStatusCallback());
  base::RunLoop().RunUntilIdle();
  EXPECT_EQ(base::File::FILE_OK, status());
  EXPECT_TRUE(FileExists("file"));

  // The file was already there; did nothing.
  EXPECT_TRUE(change_observer()->HasNoChange());
}

TEST_F(FileSystemOperationImplTest, TestCreateFileSuccessExclusive) {
  // File doesn't exist but exclusive is true.
  operation_runner()->CreateFile(URLForPath("new"), true,
                                 RecordStatusCallback());
  base::RunLoop().RunUntilIdle();
  EXPECT_EQ(base::File::FILE_OK, status());
  EXPECT_TRUE(FileExists("new"));
  EXPECT_EQ(1, change_observer()->get_and_reset_create_file_count());
}

TEST_F(FileSystemOperationImplTest, TestCreateFileSuccessFileDoesntExist) {
  // Non existing file.
  operation_runner()->CreateFile(URLForPath("nonexistent"), false,
                                 RecordStatusCallback());
  base::RunLoop().RunUntilIdle();
  EXPECT_EQ(base::File::FILE_OK, status());
  EXPECT_EQ(1, change_observer()->get_and_reset_create_file_count());
}

TEST_F(FileSystemOperationImplTest,
       TestCreateDirFailureDestParentDoesntExist) {
  // Dest. parent path does not exist.
  operation_runner()->CreateDirectory(
      URLForPath("nonexistent/dir"), false, false,
      RecordStatusCallback());
  base::RunLoop().RunUntilIdle();
  EXPECT_EQ(base::File::FILE_ERROR_NOT_FOUND, status());
  EXPECT_TRUE(change_observer()->HasNoChange());
}

TEST_F(FileSystemOperationImplTest, TestCreateDirFailureDirExists) {
  // Exclusive and dir existing at path.
  FileSystemURL dir(CreateDirectory("dir"));
  operation_runner()->CreateDirectory(dir, true, false,
                                      RecordStatusCallback());
  base::RunLoop().RunUntilIdle();
  EXPECT_EQ(base::File::FILE_ERROR_EXISTS, status());
  EXPECT_TRUE(change_observer()->HasNoChange());
}

TEST_F(FileSystemOperationImplTest, TestCreateDirFailureFileExists) {
  // Exclusive true and file existing at path.
  FileSystemURL file(CreateFile("file"));
  operation_runner()->CreateDirectory(file, true, false,
                                      RecordStatusCallback());
  base::RunLoop().RunUntilIdle();
  EXPECT_EQ(base::File::FILE_ERROR_EXISTS, status());
  EXPECT_TRUE(change_observer()->HasNoChange());
}

TEST_F(FileSystemOperationImplTest, TestCreateDirSuccess) {
  // Dir exists and exclusive is false.
  FileSystemURL dir(CreateDirectory("dir"));
  operation_runner()->CreateDirectory(dir, false, false,
                                      RecordStatusCallback());
  base::RunLoop().RunUntilIdle();
  EXPECT_EQ(base::File::FILE_OK, status());
  EXPECT_TRUE(change_observer()->HasNoChange());

  // Dir doesn't exist.
  operation_runner()->CreateDirectory(URLForPath("new"), false, false,
                                      RecordStatusCallback());
  base::RunLoop().RunUntilIdle();
  EXPECT_EQ(base::File::FILE_OK, status());
  EXPECT_TRUE(DirectoryExists("new"));
  EXPECT_EQ(1, change_observer()->get_and_reset_create_directory_count());
}

TEST_F(FileSystemOperationImplTest, TestCreateDirSuccessExclusive) {
  // Dir doesn't exist.
  operation_runner()->CreateDirectory(URLForPath("new"), true, false,
                                      RecordStatusCallback());
  base::RunLoop().RunUntilIdle();
  EXPECT_EQ(base::File::FILE_OK, status());
  EXPECT_TRUE(DirectoryExists("new"));
  EXPECT_EQ(1, change_observer()->get_and_reset_create_directory_count());
  EXPECT_TRUE(change_observer()->HasNoChange());
}

TEST_F(FileSystemOperationImplTest, TestExistsAndMetadataFailure) {
  operation_runner()->GetMetadata(URLForPath("nonexistent"),
                                  RecordMetadataCallback());
  base::RunLoop().RunUntilIdle();
  EXPECT_EQ(base::File::FILE_ERROR_NOT_FOUND, status());

  operation_runner()->FileExists(URLForPath("nonexistent"),
                                 RecordStatusCallback());
  base::RunLoop().RunUntilIdle();
  EXPECT_EQ(base::File::FILE_ERROR_NOT_FOUND, status());

  operation_runner()->DirectoryExists(URLForPath("nonexistent"),
                                      RecordStatusCallback());
  base::RunLoop().RunUntilIdle();
  EXPECT_EQ(base::File::FILE_ERROR_NOT_FOUND, status());
  EXPECT_TRUE(change_observer()->HasNoChange());
}

TEST_F(FileSystemOperationImplTest, TestExistsAndMetadataSuccess) {
  FileSystemURL dir(CreateDirectory("dir"));
  FileSystemURL file(CreateFile("dir/file"));
  int read_access = 0;

  operation_runner()->DirectoryExists(dir, RecordStatusCallback());
  base::RunLoop().RunUntilIdle();
  EXPECT_EQ(base::File::FILE_OK, status());
  ++read_access;

  operation_runner()->GetMetadata(dir, RecordMetadataCallback());
  base::RunLoop().RunUntilIdle();
  EXPECT_EQ(base::File::FILE_OK, status());
  EXPECT_TRUE(info().is_directory);
  ++read_access;

  operation_runner()->FileExists(file, RecordStatusCallback());
  base::RunLoop().RunUntilIdle();
  EXPECT_EQ(base::File::FILE_OK, status());
  ++read_access;

  operation_runner()->GetMetadata(file, RecordMetadataCallback());
  base::RunLoop().RunUntilIdle();
  EXPECT_EQ(base::File::FILE_OK, status());
  EXPECT_FALSE(info().is_directory);
  ++read_access;

  EXPECT_EQ(read_access,
            quota_manager_proxy()->notify_storage_accessed_count());
  EXPECT_TRUE(change_observer()->HasNoChange());
}

TEST_F(FileSystemOperationImplTest, TestTypeMismatchErrors) {
  FileSystemURL dir(CreateDirectory("dir"));
  operation_runner()->FileExists(dir, RecordStatusCallback());
  base::RunLoop().RunUntilIdle();
  EXPECT_EQ(base::File::FILE_ERROR_NOT_A_FILE, status());

  FileSystemURL file(CreateFile("file"));
  operation_runner()->DirectoryExists(file, RecordStatusCallback());
  base::RunLoop().RunUntilIdle();
  EXPECT_EQ(base::File::FILE_ERROR_NOT_A_DIRECTORY, status());
}

TEST_F(FileSystemOperationImplTest, TestReadDirFailure) {
  // Path doesn't exist
  operation_runner()->ReadDirectory(URLForPath("nonexistent"),
                                    RecordReadDirectoryCallback());
  base::RunLoop().RunUntilIdle();
  EXPECT_EQ(base::File::FILE_ERROR_NOT_FOUND, status());

  // File exists.
  FileSystemURL file(CreateFile("file"));
  operation_runner()->ReadDirectory(file, RecordReadDirectoryCallback());
  base::RunLoop().RunUntilIdle();
  EXPECT_EQ(base::File::FILE_ERROR_NOT_A_DIRECTORY, status());
  EXPECT_TRUE(change_observer()->HasNoChange());
}

TEST_F(FileSystemOperationImplTest, TestReadDirSuccess) {
  //      parent_dir
  //       |       |
  //  child_dir  child_file
  // Verify reading parent_dir.
  FileSystemURL parent_dir(CreateDirectory("dir"));
  FileSystemURL child_dir(CreateDirectory("dir/child_dir"));
  FileSystemURL child_file(CreateFile("dir/child_file"));

  operation_runner()->ReadDirectory(parent_dir, RecordReadDirectoryCallback());
  base::RunLoop().RunUntilIdle();
  EXPECT_EQ(base::File::FILE_OK, status());
  EXPECT_EQ(2u, entries().size());

  for (size_t i = 0; i < entries().size(); ++i) {
    if (entries()[i].is_directory)
      EXPECT_EQ(FILE_PATH_LITERAL("child_dir"), entries()[i].name);
    else
      EXPECT_EQ(FILE_PATH_LITERAL("child_file"), entries()[i].name);
  }
  EXPECT_EQ(1, quota_manager_proxy()->notify_storage_accessed_count());
  EXPECT_TRUE(change_observer()->HasNoChange());
}

TEST_F(FileSystemOperationImplTest, TestRemoveFailure) {
  // Path doesn't exist.
  operation_runner()->Remove(URLForPath("nonexistent"), false /* recursive */,
                             RecordStatusCallback());
  base::RunLoop().RunUntilIdle();
  EXPECT_EQ(base::File::FILE_ERROR_NOT_FOUND, status());

  // It's an error to try to remove a non-empty directory if recursive flag
  // is false.
  //      parent_dir
  //       |       |
  //  child_dir  child_file
  // Verify deleting parent_dir.
  FileSystemURL parent_dir(CreateDirectory("dir"));
  FileSystemURL child_dir(CreateDirectory("dir/child_dir"));
  FileSystemURL child_file(CreateFile("dir/child_file"));

  operation_runner()->Remove(parent_dir, false /* recursive */,
                             RecordStatusCallback());
  base::RunLoop().RunUntilIdle();
  EXPECT_EQ(base::File::FILE_ERROR_NOT_EMPTY, status());
  EXPECT_TRUE(change_observer()->HasNoChange());
}

TEST_F(FileSystemOperationImplTest, TestRemoveSuccess) {
  FileSystemURL empty_dir(CreateDirectory("empty_dir"));
  EXPECT_TRUE(DirectoryExists("empty_dir"));
  operation_runner()->Remove(empty_dir, false /* recursive */,
                             RecordStatusCallback());
  base::RunLoop().RunUntilIdle();
  EXPECT_EQ(base::File::FILE_OK, status());
  EXPECT_FALSE(DirectoryExists("empty_dir"));

  EXPECT_EQ(1, change_observer()->get_and_reset_remove_directory_count());
  EXPECT_TRUE(change_observer()->HasNoChange());
}

TEST_F(FileSystemOperationImplTest, TestRemoveSuccessRecursive) {
  // Removing a non-empty directory with recursive flag == true should be ok.
  //      parent_dir
  //       |       |
  //  child_dir  child_files
  //       |
  //  child_files
  //
  // Verify deleting parent_dir.
  FileSystemURL parent_dir(CreateDirectory("dir"));
  for (int i = 0; i < 8; ++i)
    CreateFile(base::StringPrintf("dir/file-%d", i));
  FileSystemURL child_dir(CreateDirectory("dir/child_dir"));
  for (int i = 0; i < 8; ++i)
    CreateFile(base::StringPrintf("dir/child_dir/file-%d", i));

  operation_runner()->Remove(parent_dir, true /* recursive */,
                             RecordStatusCallback());
  base::RunLoop().RunUntilIdle();
  EXPECT_EQ(base::File::FILE_OK, status());
  EXPECT_FALSE(DirectoryExists("parent_dir"));

  EXPECT_EQ(2, change_observer()->get_and_reset_remove_directory_count());
  EXPECT_EQ(16, change_observer()->get_and_reset_remove_file_count());
  EXPECT_TRUE(change_observer()->HasNoChange());
}

TEST_F(FileSystemOperationImplTest, TestTruncate) {
  FileSystemURL file(CreateFile("file"));
  base::FilePath platform_path = PlatformPath("file");

  char test_data[] = "test data";
  int data_size = static_cast<int>(sizeof(test_data));
  EXPECT_EQ(data_size,
            base::WriteFile(platform_path, test_data, data_size));

  // Check that its length is the size of the data written.
  operation_runner()->GetMetadata(file, RecordMetadataCallback());
  base::RunLoop().RunUntilIdle();
  EXPECT_EQ(base::File::FILE_OK, status());
  EXPECT_FALSE(info().is_directory);
  EXPECT_EQ(data_size, info().size);

  // Extend the file by truncating it.
  int length = 17;
  operation_runner()->Truncate(file, length, RecordStatusCallback());
  base::RunLoop().RunUntilIdle();
  EXPECT_EQ(base::File::FILE_OK, status());

  EXPECT_EQ(1, change_observer()->get_and_reset_modify_file_count());
  EXPECT_TRUE(change_observer()->HasNoChange());

  // Check that its length is now 17 and that it's all zeroes after the test
  // data.
  EXPECT_EQ(length, GetFileSize("file"));
  char data[100];
  EXPECT_EQ(length, base::ReadFile(platform_path, data, length));
  for (int i = 0; i < length; ++i) {
    if (i < static_cast<int>(sizeof(test_data)))
      EXPECT_EQ(test_data[i], data[i]);
    else
      EXPECT_EQ(0, data[i]);
  }

  // Shorten the file by truncating it.
  length = 3;
  operation_runner()->Truncate(file, length, RecordStatusCallback());
  base::RunLoop().RunUntilIdle();
  EXPECT_EQ(base::File::FILE_OK, status());

  EXPECT_EQ(1, change_observer()->get_and_reset_modify_file_count());
  EXPECT_TRUE(change_observer()->HasNoChange());

  // Check that its length is now 3 and that it contains only bits of test data.
  EXPECT_EQ(length, GetFileSize("file"));
  EXPECT_EQ(length, base::ReadFile(platform_path, data, length));
  for (int i = 0; i < length; ++i)
    EXPECT_EQ(test_data[i], data[i]);

  // Truncate is not a 'read' access.  (Here expected access count is 1
  // since we made 1 read access for GetMetadata.)
  EXPECT_EQ(1, quota_manager_proxy()->notify_storage_accessed_count());
}

TEST_F(FileSystemOperationImplTest, TestTruncateFailureByQuota) {
  FileSystemURL dir(CreateDirectory("dir"));
  FileSystemURL file(CreateFile("dir/file"));

  GrantQuotaForCurrentUsage();
  AddQuota(10);

  operation_runner()->Truncate(file, 10, RecordStatusCallback());
  base::RunLoop().RunUntilIdle();
  EXPECT_EQ(base::File::FILE_OK, status());
  EXPECT_EQ(1, change_observer()->get_and_reset_modify_file_count());
  EXPECT_TRUE(change_observer()->HasNoChange());

  EXPECT_EQ(10, GetFileSize("dir/file"));

  operation_runner()->Truncate(file, 11, RecordStatusCallback());
  base::RunLoop().RunUntilIdle();
  EXPECT_EQ(base::File::FILE_ERROR_NO_SPACE, status());
  EXPECT_TRUE(change_observer()->HasNoChange());

  EXPECT_EQ(10, GetFileSize("dir/file"));
}

TEST_F(FileSystemOperationImplTest, TestTouchFile) {
  FileSystemURL file(CreateFile("file"));
  base::FilePath platform_path = PlatformPath("file");

  base::File::Info info;
  EXPECT_TRUE(base::GetFileInfo(platform_path, &info));
  EXPECT_FALSE(info.is_directory);
  EXPECT_EQ(0, info.size);
  const base::Time last_modified = info.last_modified;
  const base::Time last_accessed = info.last_accessed;

  const base::Time new_modified_time = base::Time::UnixEpoch();
  const base::Time new_accessed_time = new_modified_time +
      base::TimeDelta::FromHours(77);
  ASSERT_NE(last_modified, new_modified_time);
  ASSERT_NE(last_accessed, new_accessed_time);

  operation_runner()->TouchFile(file, new_accessed_time, new_modified_time,
                                RecordStatusCallback());
  base::RunLoop().RunUntilIdle();
  EXPECT_EQ(base::File::FILE_OK, status());
  EXPECT_TRUE(change_observer()->HasNoChange());

  EXPECT_TRUE(base::GetFileInfo(platform_path, &info));
  // We compare as time_t here to lower our resolution, to avoid false
  // negatives caused by conversion to the local filesystem's native
  // representation and back.
  EXPECT_EQ(new_modified_time.ToTimeT(), info.last_modified.ToTimeT());
  EXPECT_EQ(new_accessed_time.ToTimeT(), info.last_accessed.ToTimeT());
}

TEST_F(FileSystemOperationImplTest, TestCreateSnapshotFile) {
  FileSystemURL dir(CreateDirectory("dir"));

  // Create a file for the testing.
  operation_runner()->DirectoryExists(dir, RecordStatusCallback());
  FileSystemURL file(CreateFile("dir/file"));
  operation_runner()->FileExists(file, RecordStatusCallback());
  base::RunLoop().RunUntilIdle();
  EXPECT_EQ(base::File::FILE_OK, status());

  // See if we can get a 'snapshot' file info for the file.
  // Since FileSystemOperationImpl assumes the file exists in the local
  // directory it should just returns the same metadata and platform_path
  // as the file itself.
  operation_runner()->CreateSnapshotFile(file, RecordSnapshotFileCallback());
  base::RunLoop().RunUntilIdle();
  EXPECT_EQ(base::File::FILE_OK, status());
  EXPECT_FALSE(info().is_directory);
  EXPECT_EQ(PlatformPath("dir/file"), path());
  EXPECT_TRUE(change_observer()->HasNoChange());

  // The FileSystemOpration implementation does not create a
  // shareable file reference.
  EXPECT_EQ(NULL, shareable_file_ref());
}

TEST_F(FileSystemOperationImplTest,
       TestMoveSuccessSrcDirRecursiveWithQuota) {
  FileSystemURL src(CreateDirectory("src"));
  int src_path_cost = GetUsage();

  FileSystemURL dest(CreateDirectory("dest"));
  FileSystemURL child_file1(CreateFile("src/file1"));
  FileSystemURL child_file2(CreateFile("src/file2"));
  FileSystemURL child_dir(CreateDirectory("src/dir"));
  FileSystemURL grandchild_file1(CreateFile("src/dir/file1"));
  FileSystemURL grandchild_file2(CreateFile("src/dir/file2"));

  int total_path_cost = GetUsage();
  EXPECT_EQ(0, GetDataSizeOnDisk());

  operation_runner()->Truncate(
      child_file1, 5000,
      base::Bind(&AssertFileErrorEq, FROM_HERE, base::File::FILE_OK));
  operation_runner()->Truncate(
      child_file2, 400,
      base::Bind(&AssertFileErrorEq, FROM_HERE, base::File::FILE_OK));
  operation_runner()->Truncate(
      grandchild_file1, 30,
      base::Bind(&AssertFileErrorEq, FROM_HERE, base::File::FILE_OK));
  operation_runner()->Truncate(
      grandchild_file2, 2,
      base::Bind(&AssertFileErrorEq, FROM_HERE, base::File::FILE_OK));
  base::RunLoop().RunUntilIdle();

  const int64 all_file_size = 5000 + 400 + 30 + 2;
  EXPECT_EQ(all_file_size, GetDataSizeOnDisk());
  EXPECT_EQ(all_file_size + total_path_cost, GetUsage());

  operation_runner()->Move(
      src, dest, FileSystemOperation::OPTION_NONE,
      base::Bind(&AssertFileErrorEq, FROM_HERE, base::File::FILE_OK));
  base::RunLoop().RunUntilIdle();

  EXPECT_FALSE(DirectoryExists("src/dir"));
  EXPECT_FALSE(FileExists("src/dir/file2"));
  EXPECT_TRUE(DirectoryExists("dest/dir"));
  EXPECT_TRUE(FileExists("dest/dir/file2"));

  EXPECT_EQ(all_file_size, GetDataSizeOnDisk());
  EXPECT_EQ(all_file_size + total_path_cost - src_path_cost,
            GetUsage());
}

TEST_F(FileSystemOperationImplTest,
       TestCopySuccessSrcDirRecursiveWithQuota) {
  FileSystemURL src(CreateDirectory("src"));
  FileSystemURL dest1(CreateDirectory("dest1"));
  FileSystemURL dest2(CreateDirectory("dest2"));

  int64 usage = GetUsage();
  FileSystemURL child_file1(CreateFile("src/file1"));
  FileSystemURL child_file2(CreateFile("src/file2"));
  FileSystemURL child_dir(CreateDirectory("src/dir"));
  int64 child_path_cost = GetUsage() - usage;
  usage += child_path_cost;

  FileSystemURL grandchild_file1(CreateFile("src/dir/file1"));
  FileSystemURL grandchild_file2(CreateFile("src/dir/file2"));
  int64 total_path_cost = GetUsage();
  int64 grandchild_path_cost = total_path_cost - usage;

  EXPECT_EQ(0, GetDataSizeOnDisk());

  operation_runner()->Truncate(
      child_file1, 8000,
      base::Bind(&AssertFileErrorEq, FROM_HERE, base::File::FILE_OK));
  operation_runner()->Truncate(
      child_file2, 700,
      base::Bind(&AssertFileErrorEq, FROM_HERE, base::File::FILE_OK));
  operation_runner()->Truncate(
      grandchild_file1, 60,
      base::Bind(&AssertFileErrorEq, FROM_HERE, base::File::FILE_OK));
  operation_runner()->Truncate(
      grandchild_file2, 5,
      base::Bind(&AssertFileErrorEq, FROM_HERE, base::File::FILE_OK));
  base::RunLoop().RunUntilIdle();

  const int64 child_file_size = 8000 + 700;
  const int64 grandchild_file_size = 60 + 5;
  const int64 all_file_size = child_file_size + grandchild_file_size;
  int64 expected_usage = all_file_size + total_path_cost;

  usage = GetUsage();
  EXPECT_EQ(all_file_size, GetDataSizeOnDisk());
  EXPECT_EQ(expected_usage, usage);

  // Copy src to dest1.
  operation_runner()->Copy(
      src, dest1, FileSystemOperation::OPTION_NONE,
      FileSystemOperationRunner::CopyProgressCallback(),
      base::Bind(&AssertFileErrorEq, FROM_HERE, base::File::FILE_OK));
  base::RunLoop().RunUntilIdle();

  expected_usage += all_file_size + child_path_cost + grandchild_path_cost;
  EXPECT_TRUE(DirectoryExists("src/dir"));
  EXPECT_TRUE(FileExists("src/dir/file2"));
  EXPECT_TRUE(DirectoryExists("dest1/dir"));
  EXPECT_TRUE(FileExists("dest1/dir/file2"));

  EXPECT_EQ(2 * all_file_size, GetDataSizeOnDisk());
  EXPECT_EQ(expected_usage, GetUsage());

  // Copy src/dir to dest2.
  operation_runner()->Copy(
      child_dir, dest2, FileSystemOperation::OPTION_NONE,
      FileSystemOperationRunner::CopyProgressCallback(),
      base::Bind(&AssertFileErrorEq, FROM_HERE, base::File::FILE_OK));
  base::RunLoop().RunUntilIdle();

  expected_usage += grandchild_file_size + grandchild_path_cost;
  usage = GetUsage();
  EXPECT_EQ(2 * child_file_size + 3 * grandchild_file_size,
            GetDataSizeOnDisk());
  EXPECT_EQ(expected_usage, usage);
}

}  // namespace content


text:
// Copyright (c) Microsoft Corporation. All rights reserved.
// Licensed under the MIT License.
// Code generated by Microsoft (R) AutoRest Code Generator.

package com.azure.resourcemanager.keyvault.generated;

import com.azure.core.util.Context;

/** Samples for ManagedHsms GetByResourceGroup. */
public final class ManagedHsmsGetByResourceGroupSamples {
    /*
     * x-ms-original-file: specification/keyvault/resource-manager/Microsoft.KeyVault/stable/2021-10-01/examples/ManagedHsm_Get.json
     */
    /**
     * Sample code: Retrieve a managed HSM Pool.
     *
     * @param azure The entry point for accessing resource management APIs in Azure.
     */
    public static void retrieveAManagedHSMPool(com.azure.resourcemanager.AzureResourceManager azure) {
        azure
            .vaults()
            .manager()
            .serviceClient()
            .getManagedHsms()
            .getByResourceGroupWithResponse("hsm-group", "hsm1", Context.NONE);
    }
}

redpajama_set_name: RedPajamaGithub


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

  <meta http-equiv="content-type" content="text/html; charset=UTF-8">
  <title>Returns the matched part of a multibyte regular expression</title>

mb_ereg_search_pos

mb_ereg_search_setpos

Multibyte String Functions

PHP Manual

mb_ereg_search_regs

(PHP 4 >= 4.2.0, PHP 5)

mb_ereg_search_regs — Returns the matched part of a multibyte regular expression

Description

   array mb_ereg_search_regs
    ([ string $pattern
   [, string $option = "ms"
  ]] )

   Returns the matched part of a multibyte regular expression.

Parameters

pattern

       The search pattern.

option

       The search option.

Return Values

   mb_ereg_search_regs() executes the multibyte
   regular expression match, and if there are some matched part, it
   returns an array including substring of matched part as first
   element, the first grouped part with brackets as second element,
   the second grouped part as third element, and so on.
   It returns FALSE on error.

Notes

Note:
The internal encoding or the
character encoding specified by mb_regex_encoding()
will be used as the character encoding for this function.

See Also

mb_regex_encoding() - Set/Get character encoding for multibyte regex

mb_ereg_search_init() - Setup string and regular expression for a multibyte regular expression match

mb_ereg_search_pos

mb_ereg_search_setpos

Multibyte String Functions

PHP Manual


text:
var menudata={children:[
{text:"Main Page",url:"index.html"},
{text:"Packages",url:"namespaces.html",children:[
{text:"Packages",url:"namespaces.html"},
{text:"Package Functions",url:"namespacemembers.html",children:[
{text:"All",url:"namespacemembers.html"},
{text:"Enumerations",url:"namespacemembers_enum.html"}]}]},
{text:"Classes",url:"annotated.html",children:[
{text:"Class List",url:"annotated.html"},
{text:"Class Index",url:"classes.html"},
{text:"Class Hierarchy",url:"hierarchy.html"},
{text:"Class Members",url:"functions.html",children:[
{text:"All",url:"functions.html",children:[
{text:"a",url:"functions.html#index_a"},
{text:"c",url:"functions.html#index_c"},
{text:"d",url:"functions.html#index_d"},
{text:"f",url:"functions.html#index_f"},
{text:"g",url:"functions.html#index_g"},
{text:"i",url:"functions.html#index_i"},
{text:"k",url:"functions.html#index_k"},
{text:"m",url:"functions.html#index_m"},
{text:"n",url:"functions.html#index_n"},
{text:"o",url:"functions.html#index_o"},
{text:"p",url:"functions.html#index_p"},
{text:"r",url:"functions.html#index_r"},
{text:"s",url:"functions.html#index_s"},
{text:"t",url:"functions.html#index_t"},
{text:"v",url:"functions.html#index_v"},
{text:"w",url:"functions.html#index_w"}]},
{text:"Functions",url:"functions_func.html"},
{text:"Variables",url:"functions_vars.html"},
{text:"Enumerations",url:"functions_enum.html"},
{text:"Properties",url:"functions_prop.html"},
{text:"Events",url:"functions_evnt.html"}]}]}]}


text:
Grokking Rust With Data Structure Implementations
====

These are exercises inspired by Gankro's book
[Learning Rust With Entirely Too Many Linked
Lists](http://cglab.ca/~abeinges/blah/too-many-lists/book/) and were done after
looking away from the book for a few days.

* `mutable_linked_list` takes a different approach to a safe implementation of
  the mutable singly-linked list that caused me much pain and learning when
  dealing with mutable iterators.

* `immutable_linked_list` ended up being almost an exact replica.

* `mutable_doubly_linked_list` uses owned `next` pointers and unsafe `prev`
  pointers but after a subtle oversight caught by the tests, it was refactored
  so that the unsafe reverse-traversing code has almost the identical structure
  as the safe forward-traversing code.

License
====
Copyright 2015 Ashish Myles.

Distributed under the terms of both the MIT license and the Apache License
(Version 2.0) license. See [LICENSE-MIT](LICENSE-MIT) and the
[LICENSE-APACHE](LICENSE-APACHE) for details.


text:
<!doctype html>

    <title>Page Not Found</title>
    <meta charset="utf-8"/>
    <meta name="viewport" content="width=device-width, initial-scale=1"/>
    <meta name="robots" content="nofollow"/>
    <link rel="stylesheet" type="text/css" href="errors.css"/>

Connection Refused

Your request has been denied.


text:
namespace crashpad {

//! \brief Ensures that a range, composed of a base and a size, does not
//!     overflow the pointer type of the process it describes a range in.
//!
//! This class checks bases of type WinVMAddress and sizes of type WinVMSize
//! against a process whose pointer type is either 32 or 64 bits wide.
//!
//! Aside from varying the overall range on the basis of a process' pointer type
//! width, this class functions very similarly to CheckedRange.
using CheckedWinAddressRange =
    internal::CheckedAddressRangeGeneric<WinVMAddress, WinVMSize>;

}  // namespace crashpad

#endif  // CRASHPAD_UTIL_WIN_CHECKED_WIN_ADDRESS_RANGE_H_


text:
(function () {
  'use strict';

  /**
   * @ngdoc factory
   * @name horizon.app.core.workflow.factory:horizon.app.core.workflow.factory
   * @module horizon.app.core.workflow
   * @kind function
   * @description
   *
   * Injected dependencies:
   * - workflow {@link horizon.framework.util.workflow.service:workflow `workflow`}
   * - dashboardWorkflowDecorator {@link horizon.app.core.workflow.factory
   *    :horizon.app.core.workflow.decorator `dashboardWorkflowDecorator`}
   *
   * @example
   * ```
   * var workflow = workflowService({
   *   title: gettext('Create Volume'),
   *   btnText: { finish: gettext('Create Volume') },
   *   steps: [{
   *     title: gettext('Step 1'),
   *     templateUrl: basePath + 'steps/create-volume/step1.html',
   *     helpUrl: basePath + 'steps/create-volume/step1.help.html',
   *     formName: 'step1Form'
   *   },{
   *     title: gettext('Step 2'),
   *     templateUrl: basePath + 'steps/create-volume/step2.html',
   *     helpUrl: basePath + 'steps/create-volume/step2.help.html',
   *     formName: 'step2Form',
   *     requiredServiceTypes: ['network']
   *   },{
   *     title: gettext('Step 3'),
   *     templateUrl: basePath + 'steps/create-volume/step3.html',
   *     helpUrl: basePath + 'steps/create-volume/step3.help.html',
   *     formName: 'step3Form',
   *     policy: { rules: [['compute', 'os_compute_api:os-scheduler-hints:discoverable']] }
   *   }]
   * });
   * ```
   * For each step, the requiredServiceTypes property specifies the service types that must
   * be available in the service catalog for the step to be displayed. The policy property
   * specifies the policy check that must pass in order for the step to be displayed.
   *
   * @param {Object} The input workflow specification object
   * @returns {Object} The decorated workflow specification object, the same
   * reference to the input spec object.
   *
   */
  angular
    .module('horizon.app.core.workflow')
    .factory('horizon.app.core.workflow.factory', dashboardWorkflow);

  dashboardWorkflow.$inject = [
    'horizon.framework.util.workflow.service',
    'horizon.app.core.workflow.decorator'
  ];

  /////////////

  function dashboardWorkflow(workflow, dashboardWorkflowDecorator) {
    var decorators = [dashboardWorkflowDecorator];
    return function (spec) {
      return workflow(spec, decorators);
    };
  }

})();


text:
import { NgModule, ModuleWithProviders } from '@angular/core';
import { CommonModule } from '@angular/common';
import { FormsModule } from '@angular/forms';
import { RouterModule } from '@angular/router';
import { provideLazyMapsAPILoaderConfig, AgmCoreModule } from 'angular2-google-maps/core';
import { Ng2PageScrollModule } from 'ng2-page-scroll';

import { NavbarComponent } from './navbar/index';
import { FooterComponent } from './footer/index';
import { StarViewComponent } from './star-view/index';
import { PlacesService } from './places/index';
import { GlobalEventsService } from './global-events/index';
import { CroppedImageComponent } from './cropped-image/index';
import { PhonePipe } from './phone/index';

/**
 * Do not specify providers for modules that might be imported by a lazy loaded module.
 */

@NgModule({
  imports: [
    CommonModule,
    RouterModule,
    AgmCoreModule.forRoot(),
    Ng2PageScrollModule
  ],
  declarations: [
    NavbarComponent,
    FooterComponent,
    StarViewComponent,
    CroppedImageComponent,
    PhonePipe
  ],
  exports: [
    CommonModule,
    FormsModule,
    RouterModule,
    NavbarComponent,
    FooterComponent,
    StarViewComponent,
    CroppedImageComponent,
    PhonePipe
  ]
})
export class SharedModule {
  static forRoot(): ModuleWithProviders {
    return {
      ngModule: SharedModule,
      providers: [
        PlacesService,
        GlobalEventsService,
        provideLazyMapsAPILoaderConfig({
          apiKey: 'AIzaSyBE1Bb86PEGx-11LahjWCZS2cFOWMpNseI',
          libraries: ['places']
        })
      ]
    };
  }
}


text:
<?php

/**
 * Mageflow_Connect_Model_Api2_System_Cron_Rest_Admin_V1
 *
 * @category   MFX
 * @package    Mageflow_Connect
 * @subpackage Model
 * @author     Prototypely Ltd, Estonia <info@prototypely.com>
 * @copyright  Copyright © 2017 Prototypely Ltd, Estonia (http://prototypely.com)
 * @license MIT Copyright (c) 2017 Prototypely Ltd
 * @link       http://mageflow.com/
 */
class Mageflow_Connect_Model_Api2_System_Cron_Rest_Admin_V1
    extends Mageflow_Connect_Model_Api2_Abstract
{
    /**
     * resource type
     *
     * @var string
     */
    protected $_resourceType = 'system_cron';

    /**
     * Returns array with system info
     *
     * @return array
     */
    public function _retrieve()
    {
        $out = array();
        $this->log($this->getRequest()->getParams());
        /**
         * @var Mage_Core_Model_Config_Element $cronJobs
         */
        $cronJobs = Mage::app()->getConfig()->getNode('crontab/jobs');

        /**
         * @var Mage_Core_Model_Config_Element $job
         */
        foreach ($cronJobs->children() as $name => $job) {
            $data = get_object_vars($job->children());
            if (isset($data['name'])) {
                $data['name'] = $name;
            } else {

            }
            if (isset($data['run']) && is_object($data['run'])) {
                $run = $data['run']->asArray();
                $run = $run['model'];
            } else {
                $run = '';
            }
            if (isset($data['schedule']) && is_object($data['schedule'])) {
                $schedule = $data['schedule']->asArray();
                $schedule = $schedule['cron_expr'];
            } else {
                $schedule = '';
            }

            $out[]
                = array(
                'name' => $name,
                'run' => $run,
                'schedule' => $schedule,
            );
        }
        return $out;
    }

    /**
     * retrieve collection
     *
     * @return array
     */
    public function _retrieveCollection()
    {
        return $this->_retrieve();
    }

}


text:
import functools

import futurist

def call_functions_parallel(*worker_defs):
    """Call specified functions in parallel.

    :param *worker_defs: Each positional argument can be either of
        a function to be called or a tuple which consists of a function,
        a list of positional arguments) and keyword arguments (optional).
        If you need to pass arguments, you need to pass a tuple.
        Example usages are like:
           call_functions_parallel(func1, func2, func3)
           call_functions_parallel(func1, (func2, [1, 2]))
           call_functions_parallel((func1, [], {'a': 1}),
                                   (func2, [], {'a': 2, 'b': 10}))
    :returns: a tuple of values returned from individual functions.
        None is returned if a corresponding function does not return.
        It is better to return values other than None from individual
        functions.
    """
    # TODO(amotoki): Needs to figure out what max_workers can be specified.
    # According to e0ne, the apache default configuration in devstack  allows
    # only 10 threads. What happens if max_worker=11 is specified?
    max_workers = len(worker_defs)
    # Prepare a list with enough length.
    futures = [None] * len(worker_defs)
    with futurist.ThreadPoolExecutor(max_workers=max_workers) as e:
        for index, func_def in enumerate(worker_defs):
            if callable(func_def):
                func_def = [func_def]
            args = func_def[1] if len(func_def) > 1 else []
            kwargs = func_def[2] if len(func_def) > 2 else {}
            func = functools.partial(func_def[0], *args, **kwargs)
            futures[index] = e.submit(fn=func)

    return tuple(f.result() for f in futures)


text:
Ext.define('Datanium.view.FieldToolBar', {
	extend : 'Ext.toolbar.Toolbar',
	alias : 'widget.fieldtb',
	initComponent : function() {
		Ext.apply(this, {
			items : []
		});
		this.callParent();
	}

});


text:
import { OnDestroy, Pipe, PipeTransform } from '@angular/core';
import { SkyAppLocaleInfo, SkyAppLocaleProvider } from '@skyux/i18n';

import { Subject } from 'rxjs';
import { takeUntil } from 'rxjs/operators';

import { SkyDateFormatUtility } from './date-format-utility';

/**
 * Formats date values according to locale rules.
 * @example
 * ```markup
 * {{ myDate | skyDate }}
 * {{ myDate | skyDate:'medium' }}
 * {{ myDate | skyDate:'medium':'en-CA' }}
 * ```
 */
@Pipe({
  name: 'skyDate',
  pure: false,
})
export class SkyDatePipe implements OnDestroy, PipeTransform {
  #defaultFormat = 'short';

  #format: string | undefined;

  #defaultLocale = 'en-US';

  #locale: string | undefined;

  #value: any;

  #formattedValue: string | undefined;

  #ngUnsubscribe = new Subject<void>();

  constructor(private localeProvider: SkyAppLocaleProvider) {
    this.localeProvider
      .getLocaleInfo()
      .pipe(takeUntil(this.#ngUnsubscribe))
      .subscribe((localeInfo: SkyAppLocaleInfo) => {
        this.#defaultLocale = localeInfo.locale;
        this.updateFormattedValue();
      });
  }

  public ngOnDestroy(): void {
    this.#ngUnsubscribe.next();
    this.#ngUnsubscribe.complete();
  }

  /**
   * Transforms a date value using locale and format rules.
   * @param value Specifies the date value to transform.
   * @param format Specifies the format to apply to the transform. The format string is
   * constructed by a series of symbols that represent date-time values. The symbols are
   * identical to [Angular's `DatePipe`](https://angular.io/api/common/DatePipe#pre-defined-format-options) format options.
   * @param locale Specifies the locale code to use in the transform.
   */
  public transform(value: any, format?: string, locale?: string): string {
    this.#value = value;
    this.#format = format;
    this.#locale = locale;

    this.updateFormattedValue();

    return this.#formattedValue ?? '';
  }

  private updateFormattedValue(): void {
    const locale = this.#locale || this.#defaultLocale;
    const format = this.#format || this.#defaultFormat;

    this.#formattedValue = SkyDateFormatUtility.format(
      locale,
      this.#value,
      format
    );
  }
}


text:
package de.danoeh.antennapod.activity;

import android.content.res.TypedArray;
import android.graphics.Color;
import android.os.Build;
import android.os.Bundle;
import android.support.v7.app.AppCompatActivity;
import android.util.Log;
import android.view.MenuItem;
import android.view.View;
import android.webkit.WebSettings;
import android.webkit.WebView;
import android.webkit.WebViewClient;
import android.widget.LinearLayout;

import org.apache.commons.io.IOUtils;

import java.io.IOException;
import java.io.InputStream;
import java.nio.charset.Charset;

import de.danoeh.antennapod.R;
import de.danoeh.antennapod.core.preferences.UserPreferences;
import rx.Single;
import rx.Subscription;
import rx.android.schedulers.AndroidSchedulers;
import rx.schedulers.Schedulers;

/**
 * Displays the 'about' screen
 */
public class AboutActivity extends AppCompatActivity {

    private static final String TAG = AboutActivity.class.getSimpleName();

    private WebView webView;
    private LinearLayout webViewContainer;
    private Subscription subscription;

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        setTheme(UserPreferences.getTheme());
        super.onCreate(savedInstanceState);
        getSupportActionBar().setDisplayShowHomeEnabled(true);
        setContentView(R.layout.about);
        webViewContainer = (LinearLayout) findViewById(R.id.webViewContainer);
        webView = (WebView) findViewById(R.id.webViewAbout);
        webView.getSettings().setCacheMode(WebSettings.LOAD_NO_CACHE);
        if (UserPreferences.getTheme() == R.style.Theme_AntennaPod_Dark) {
            if (Build.VERSION.SDK_INT <= Build.VERSION_CODES.ICE_CREAM_SANDWICH_MR1) {
                webView.setLayerType(View.LAYER_TYPE_SOFTWARE, null);
            }
            webView.setBackgroundColor(Color.TRANSPARENT);
        }
        webView.setWebViewClient(new WebViewClient() {

            @Override
            public boolean shouldOverrideUrlLoading(WebView view, String url) {
                if (!url.startsWith("http")) {
                    url = url.replace("file:///android_asset/", "");
                    loadAsset(url);
                    return true;
                }
                return false;
            }

        });
        loadAsset("about.html");
    }

    private void loadAsset(String filename) {
        subscription = Single.create(subscriber -> {
            InputStream input = null;
            try {
                TypedArray res = AboutActivity.this.getTheme().obtainStyledAttributes(
                        new int[] { R.attr.about_screen_font_color, R.attr.about_screen_background,
                        R.attr.about_screen_card_background, R.attr.about_screen_card_border});
                String fontColor = String.format("#%06X", 0xFFFFFF & res.getColor(0, 0));
                String backgroundColor = String.format("#%06X", 0xFFFFFF & res.getColor(1, 0));
                String cardBackground = String.format("#%06X", 0xFFFFFF & res.getColor(2, 0));
                String cardBorder = String.format("#%06X", 0xFFFFFF & res.getColor(3, 0));
                res.recycle();
                input = getAssets().open(filename);
                String webViewData = IOUtils.toString(input, Charset.defaultCharset());
                if (!webViewData.startsWith("<!DOCTYPE html>")) {
                    webViewData = webViewData.replace("%", "%");
                    webViewData =
                            "<!DOCTYPE html>" +
                            "" +
                            "" +
                            "    <meta http-equiv=\"Content-Type\" content=\"text/html;charset=UTF-8\">" +
                            "    " +
                            "
" + webViewData + "
";
                    webViewData = webViewData.replace("\n", "
");
                }
                webViewData = webViewData.replace("@fontcolor@", fontColor);
                webViewData = webViewData.replace("@background@", backgroundColor);
                webViewData = webViewData.replace("@card_background@", cardBackground);
                webViewData = webViewData.replace("@card_border@", cardBorder);
                subscriber.onSuccess(webViewData);
            } catch (IOException e) {
                Log.e(TAG, Log.getStackTraceString(e));
                subscriber.onError(e);
            } finally {
                IOUtils.closeQuietly(input);
            }
        })
                .subscribeOn(Schedulers.newThread())
                .observeOn(AndroidSchedulers.mainThread())
                .subscribe(
                        webViewData ->
                                webView.loadDataWithBaseURL("file:///android_asset/", webViewData.toString(), "text/html", "utf-8", "file:///android_asset/" + filename.toString()),
                        error -> Log.e(TAG, Log.getStackTraceString(error))
                );
    }

    @Override
    public void onBackPressed() {
        if (webView.canGoBack()) {
            webView.goBack();
        } else {
            super.onBackPressed();
        }
    }

    @Override
    public boolean onOptionsItemSelected(MenuItem item) {
        if (item.getItemId() == android.R.id.home) {
            onBackPressed();
            return true;
        } else {
            return super.onOptionsItemSelected(item);
        }
    }

    @Override
    protected void onDestroy() {
        super.onDestroy();
        if(subscription != null) {
            subscription.unsubscribe();
        }
        if (webViewContainer != null && webView != null) {
            webViewContainer.removeAllViews();
            webView.destroy();
        }
    }
}


text:
// Copyright (C) 2010 by Yan Huang <yhuang@virginia.edu>

package org.factcenter.fastgc.Cipher;

import java.math.BigInteger;
import java.security.MessageDigest;

public final class Cipher {
	private static final int unitLength = 160; // SHA-1 has 160-bit output.

	private static final BigInteger mask = BigInteger.ONE.shiftLeft(80)
			.subtract(BigInteger.ONE);

	/**
	 * Instance of sha1 message digest. Note that this can't be
	 * a static variable because it isn't thread-safe.
	 */
	private MessageDigest sha1;

	public Cipher() {
		try {
			sha1 = MessageDigest.getInstance("SHA-1");
		} catch (Exception e) {
			e.printStackTrace();
			System.exit(1);
		}
	}

	/**
	 * Compute an Yao Garbling, assuming H is a random oracle.
	 * @param keyL
	 * @param keyR
	 * @param wireSerialNo should be unique for every wire.
	 * @param plaintext
	 * @return H(keyL, keyR, wireSerialNo) XOR plaintext
	 */
	public BigInteger encrypt(BigInteger keyL, BigInteger keyR, int wireSerialNo,
			BigInteger plaintext) {
		BigInteger ret = getPadding(keyL, keyR, wireSerialNo);
		ret = ret.xor(plaintext);

		return ret;
	}

	public BigInteger decrypt(BigInteger keyL, BigInteger keyR, int wireSerialNo,
			BigInteger ciphertext) {
		BigInteger ret = getPadding(keyL, keyR, wireSerialNo);
		ret = ret.xor(ciphertext);

		return ret;
	}

	// this padding generation function is dedicated for encrypting garbled
	// tables.
	private BigInteger getPadding(BigInteger keyL, BigInteger keyR, int wireSerialNo) {
		sha1.update(keyL.toByteArray());
		sha1.update(keyR.toByteArray());
		sha1.update(BigInteger.valueOf(wireSerialNo).toByteArray());
		return (new BigInteger(sha1.digest())).and(mask);
	}

	public BigInteger encrypt(BigInteger key, BigInteger msg,
			int msgLength) {
		return msg.xor(getPaddingOfLength(key, msgLength));
	}

	public BigInteger decrypt(BigInteger key, BigInteger cph,
			int cphLength) {
		return cph.xor(getPaddingOfLength(key, cphLength));
	}

	private BigInteger getPaddingOfLength(BigInteger key, int padLength) {
		sha1.update(key.toByteArray());
		BigInteger pad = BigInteger.ZERO;
		byte[] tmp = new byte[unitLength / 8];
		for (int i = 0; i < padLength / unitLength; i++) {
			System.arraycopy(sha1.digest(), 0, tmp, 0, unitLength / 8);
			pad = pad.shiftLeft(unitLength).xor(new BigInteger(1, tmp));
			sha1.update(tmp);
		}
		System.arraycopy(sha1.digest(), 0, tmp, 0, unitLength / 8);
		pad = pad.shiftLeft(padLength % unitLength).xor(
				(new BigInteger(1, tmp)).shiftRight(unitLength
						- (padLength % unitLength)));
		return pad;
	}

	public BigInteger encrypt(int j, BigInteger key, BigInteger msg,
			int msgLength) {
		return msg.xor(getPaddingOfLength(j, key, msgLength));
	}

	public BigInteger decrypt(int j, BigInteger key, BigInteger cph,
			int cphLength) {
		return cph.xor(getPaddingOfLength(j, key, cphLength));
	}

	private BigInteger getPaddingOfLength(int j, BigInteger key,
			int padLength) {
		sha1.update(BigInteger.valueOf(j).toByteArray());
		sha1.update(key.toByteArray());
		BigInteger pad = BigInteger.ZERO;
		byte[] tmp = new byte[unitLength / 8];
		for (int i = 0; i < padLength / unitLength; i++) {
			System.arraycopy(sha1.digest(), 0, tmp, 0, unitLength / 8);
			pad = pad.shiftLeft(unitLength).xor(new BigInteger(1, tmp));
			sha1.update(tmp);
		}
		System.arraycopy(sha1.digest(), 0, tmp, 0, unitLength / 8);
		pad = pad.shiftLeft(padLength % unitLength).xor(
				(new BigInteger(1, tmp)).shiftRight(unitLength
						- (padLength % unitLength)));
		return pad;
	}
}


text:
var events = require('events');

// Create an eventEmitter object
var eventEmitter = new events.EventEmitter();

// Create an event handler as follows
var connectHandler = function connected() {
   console.log('connection succesful.');

   // Fire the data_received event
   eventEmitter.emit('data_received');
}

// Bind the connection event with the handler
eventEmitter.on('connection', connectHandler);

// Bind the data_received event with the anonymous function
eventEmitter.on('data_received', function(){
   console.log('data received succesfully.');
});

// Fire the connection event
eventEmitter.emit('connection');

console.log("Program Ended.");


text:
<?php
	//Get list Province
	function createQueryProvince(){
		$query = "SELECT gid, name_2 FROM vnm_adm2";

		return $query;
	}

	function getResultProvince(){
		include($_SERVER['DOCUMENT_ROOT'] . '/catAnhVeTinh/dbConnect.php');
		$rs = pg_query($db, createQueryProvince()) or die("Cannot execute query: $query\n");

		$result = array();
		//Store in an array
		while ($row = pg_fetch_row($rs)){
			$result[$row[0]] = $row[1];
		}
		pg_close($db);
		return $result;
	}
?>


text:
package wimf.ingest;

import com.fasterxml.jackson.annotation.JsonCreator;
import com.fasterxml.jackson.annotation.JsonProperty;
import com.google.common.collect.ImmutableList;

import java.time.LocalDateTime;
import java.time.ZoneOffset;
import java.util.Date;

/**
 * Immutable value representing a Restaurant Inspection result from New York open data
 */
final public class RestaurantInspection {

    public static wimf.domain.RestaurantInspection asModel(final RestaurantInspection ri) {
        return new wimf.domain.RestaurantInspection(
                ri.businessName,
                ri.boro,
                ri.grade,
                ri.inspectionDate,
                ri.businessID,
                ri.cuisine,
                ri.violationCode,
                ri.violationDescription,
                ri.score,
                ri.inspectionType
        );
    }

    @JsonCreator
    public static RestaurantInspection of(
            @JsonProperty("camis") final String businessID,
            @JsonProperty("dba") final String businessName,
            @JsonProperty("cuisine_description") final String cuisine,
            @JsonProperty("violation_code") final String violationCode,
            @JsonProperty("violation_description") final String violationDescription,
            @JsonProperty("grade") final String grade,
            @JsonProperty("boro") final String boro,
            @JsonProperty("building") final String building,
            @JsonProperty("street") final String street,
            @JsonProperty("zipcode") final String zipCode,
            @JsonProperty("phone") final String phone,
            @JsonProperty("score") final int score,
            @JsonProperty("inspection_date") final Date date,
            @JsonProperty("inspection_type") final String inspectionType) {

        final LocalDateTime inspectionDate =
                LocalDateTime.ofInstant(date.toInstant(), ZoneOffset.systemDefault());

        return new RestaurantInspection(
                businessID,
                businessName,
                cuisine,
                violationCode,
                violationDescription,
                grade,
                boro,
                building,
                street,
                zipCode,
                phone,
                score,
                inspectionDate,
                inspectionType);
    }

    public static RestaurantInspection of(
            final String businessID,
            final String businessName,
            final String cuisine,
            final String violationCode,
            final String violationDescription,
            final String grade,
            final String boro,
            final String building,
            final String street,
            final String zipCode,
            final String phone,
            final int score,
            final LocalDateTime inspectionDate,
            final String inspectionType) {

        return new RestaurantInspection(
                businessID,
                businessName,
                cuisine,
                violationCode,
                violationDescription,
                grade,
                boro,
                building,
                street,
                zipCode,
                phone,
                score,
                inspectionDate,
                inspectionType);
    }

    public final String businessID;
    public final String businessName;
    public final String cuisine;
    public final String violationCode;
    public final String violationDescription;
    public final String grade;
    public final String boro;
    public final String building;
    public final String street;
    public final String zipCode;
    public final String phone;
    public final int score;
    public final LocalDateTime inspectionDate;
    public final String inspectionType;

    private RestaurantInspection(
            final String businessID,
            final String businessName,
            final String cuisine,
            final String violationCode,
            final String violationDescription,
            final String grade,
            final String boro,
            final String building,
            final String street,
            final String zipCode,
            final String phone,
            final int score,
            final LocalDateTime inspectionDate,
            final String inspectionType) {

        this.businessID = businessID;
        this.businessName = businessName;
        this.cuisine = cuisine;
        this.violationCode = violationCode;
        this.violationDescription = violationDescription;
        this.grade = grade;
        this.boro = boro;
        this.building = building;
        this.street = street;
        this.zipCode = zipCode;
        this.phone = phone;
        this.score = score;
        this.inspectionDate = inspectionDate;
        this.inspectionType = inspectionType;
    }
}


text:
int main(int argc, char* argv[])
{

  // Получаем текущую локаль CRT (если нужно потом восстановить)
  char* crtLocale = setlocale(LC_ALL, NULL);
  setlocale(LC_ALL, ".1251");

  // Run
  testing::InitGoogleTest(&argc, argv);
  //testing::GTEST_FLAG(print_time) = true;
  int result = RUN_ALL_TESTS();
  setlocale(LC_ALL, crtLocale);
  //system("pause");
  return result;
}


text:
<resources xmlns:android="http://schemas.android.com/apk/res/android">

    <!--
        Base application theme, dependent on API level. This theme is replaced
        by AppBaseTheme from res/values-vXX/styles.xml on newer devices.
    -->
    <style name="AppBaseTheme" parent="android:Theme.Light">
        <!--
            Theme customizations available in newer API levels can go in
            res/values-vXX/styles.xml, while customizations related to
            backward-compatibility can go here.
        -->
    </style>

    <!-- Application theme. -->
    <style name="AppTheme" parent="AppBaseTheme">
        <!-- All customizations that are NOT specific to a particular API-level can go here. -->
    </style>

    <style name="TabButton">
        <item name="android:layout_width">0dp</item>
        <item name="android:layout_height">40dp</item>
        <item name="android:layout_weight">1</item>
        <item name="android:textColor">#333333</item>
        <item name="android:textSize">14sp</item>
        <item name="android:textStyle">bold</item>
    </style>

    <style name="OKLoginText">
        <item name="android:textSize">16sp</item>
        <item name="android:textStyle">bold</item>
        <item name="android:typeface">sans</item>
        <item name="android:textColor">@android:color/black</item>
    </style>

    <style name="OKLoginButton">
    	<item name="android:paddingBottom">12dip</item>
        <item name="android:paddingTop">12dip</item>
        <item name="android:shadowDx">0</item>
        <item name="android:shadowDy">2</item>
        <item name="android:shadowRadius">0.1</item>
        <item name="android:textStyle">bold</item>
        <item name="android:textSize">14sp</item>
    </style>

    <style name="OKLoginButtonSmall">
    	<item name="android:paddingBottom">0dip</item>
        <item name="android:paddingTop">0dip</item>
        <item name="android:paddingLeft">8dip</item>
        <item name="android:paddingRight">8dip</item>
        <item name="android:shadowDx">0</item>
        <item name="android:shadowDy">2</item>
        <item name="android:shadowRadius">0.1</item>
        <item name="android:textStyle">bold</item>
        <item name="android:textSize">14sp</item>
    </style>

    <style name="OKHeadingText" parent="@style/OKLoginText">
        <item name="android:textSize">20sp</item>
    </style>

    <style name="OKSmallLightGrayText">
        <item name="android:textSize">14sp</item>
        <item name="android:textColor">@color/io_openkit_gray</item>
        <item name="android:typeface">sans</item>
    </style>

  <style name="Theme.Transparent" parent="android:Theme">
    <item name="android:windowIsTranslucent">true</item>
    <item name="android:windowBackground">@android:color/transparent</item>
    <item name="android:windowContentOverlay">@null</item>
    <item name="android:windowNoTitle">true</item>
    <item name="android:windowIsFloating">true</item>
    <item name="android:backgroundDimEnabled">true</item>
  </style>

</resources>


text:
This document describes our Github workflow.

## Creating issues

1. Decide if issue is bug related, a feature request or something else. Pick the appropriate template.
2. Fill in the relevant sections of the template.
3. (Optional) Assign it to someone.
4. Add the appropriate labels. Bug reports already have the `bug` label, but more might be appropriate.
5. Add it to the `Samfundet` project.
6. (Optional) Add it to a milestone if it's part of some greater goal.

## Doing the Lord's Good Work

1. Choose an issue.
2. Assign youself to the issue so that everybody knows who does what.
3. Branch out from `master`. Give the branch a descriptive name. Use dashes (`-`) between words.
4. Do the lord's good work.
5. When finished, consider rebasing – It's nice, but not critical. Push your branch to our repository.
6. When Travis is happy, make a pull request. In the description of the pull request, reference the issue you're working on. For example, you can write `Fixes #xxx` where `xxx` is the number of the issue you're working on. For more information about Github issue/PR keyworrds, check out [this](https://help.github.com/en/articles/closing-issues-using-keywords) article. You'll get auto-completion when writing `#` before entering the number. When adding that to the description, it will automatically close the issue when the pull request is merged into our default branch, which is `master`.
7. Every PR needs at least one accepted review. This is to make sure that everything that gets deployed is looked at by at least two pairs of eyes. Assign someone who's available.
8. Merge your PR into `master`.
9. When appropriate, this will be deployed; ideally first to our beta site, and then to prorduction.


text:
package gaml

import (
	"bytes"
	"net/http"
	"net/url"
	"os"
	"testing"
)

const test_dir = "./test"
const simple_gaml_fn = "simple.gaml"
const simple_html_fn = "simple.html"

func TestLoadFile(t *testing.T) {
	var fsl Loader
	var err error

	if fsl, err = NewFileSystemLoader(test_dir + "/"); err != nil {
		t.Errorf("couldn't create fileSystemLoader: %s", err)
	}

	if _, err = fsl.Load(1); err == nil {
		t.Errorf("rats! expected error")
	}

	if _, err = fsl.Load(simple_gaml_fn); err != nil {
		t.Errorf("couldn't load: %s: %s", simple_gaml_fn, err)
	}

	if fsl, err = NewFileSystemLoader(test_dir); err != nil {
		t.Errorf("couldn't create fileSystemLoader: %s", err)
	}

	if _, err = fsl.Load(1); err == nil {
		t.Errorf("rats! expected error")
	}

	if _, err = fsl.Load(simple_gaml_fn); err != nil {
		t.Errorf("couldn't load: %s: %s", simple_gaml_fn, err)
	}
	if fsl, err = NewFileSystemLoader("blsadfasdf"); err == nil {
		t.Errorf("rats! expected error for non existing dir ...  ")
	}
}

func readFile(t *testing.T, fn string) ([]byte, error) {
	file, err := os.Open(fn)
	if err != nil {
		return nil, err
	}
	defer file.Close()
	data := make([]byte, 1024)
	if count, err2 := file.Read(data); err2 != nil {
		return nil, err2
	} else {
		return data[:count], nil
	}
	// dead code
	return nil, nil
}

func TestHttp(t *testing.T) {
	renderer := &Renderer{IndentSpace, true}
	if httpHandler, err := NewGamlHandlerWithRenderer(test_dir, renderer); err != nil {
		t.Errorf("couldn't create HamlHandler: %s", err)
	} else {
		writer := &TestResponseWriter{bytes.NewBufferString(""), nil, 0}
		request := http.Request{}
		request.URL, _ = url.Parse("http://localhost/simple.html")
		if expected, err2 := readFile(t, test_dir+"/"+simple_html_fn); err2 != nil {
			t.Errorf("couldn't load result: %s", err2)
		} else {
			httpHandler.ServeHTTP(writer, &request)
			if !bytes.Equal(writer.b.Bytes(), expected) {
				t.Errorf("unexpected result. got: >%s< expected: >%s<", writer.b.Bytes(), expected)
			}
		}
		writer.h = nil
		request.URL, _ = url.Parse("http://localhost/index.html")
		httpHandler.ServeHTTP(writer, &request)
		if 301 != writer.s {
			t.Errorf("incorrect status: %d", writer.s)
		}
		if "./" != writer.h["Location"][0] {
			t.Errorf("incorrect redirect: %s", writer.h["Location"][0])
		}

		// shouldn't redirect
		writer.h = nil
		request.URL, _ = url.Parse("http://localhost/")
		httpHandler.ServeHTTP(writer, &request)
		if 404 != writer.s {
			t.Errorf("incorrect status: %d", writer.s)
		}
		if nil != writer.h["Location"] {
			t.Errorf("redirect but shouldn't: %s", writer.h["Location"][0])
		}
	}
}

type TestResponseWriter struct {
	b *bytes.Buffer
	h http.Header
	s int
}

func (t *TestResponseWriter) Header() http.Header {
	if t.h == nil {
		t.h = make(map[string][]string)
	}
	return t.h
}

func (t *TestResponseWriter) Write(bytes []byte) (int, error) {
	return t.b.Write(bytes)
}
func (t *TestResponseWriter) WriteHeader(i int) {
	t.s = i
}


text:
package de.tub.cit.slist.bdos.metadata;

import java.util.Arrays;

public class ClassMetadata {
	/** total length of object. intended redundancy. */
	private final long				length;
	private final FieldMetadata[]	fields;

	public ClassMetadata(final long length, final FieldMetadata[] fields) {
		super();
		this.length = length;
		this.fields = fields;
	}

	/**
	 * Sets the {@link FieldMetadata#getSerializedOffset() serializedOffset} of each {@link FieldMetadata} child.
	 */
	public void calcSerializedOffsets() {
		long offset = 0;
		for (final FieldMetadata field : fields) {
			field.setSerializedOffset(offset);
			offset += field.getLength();
		}
	}

	/**
	 * @return total length of all fields
	 */
	public long getLength() {
		return length;
	}

	public FieldMetadata[] getFields() {
		return fields;
	}

	@Override
	public String toString() {
		return "ClassMetadata [length=" + length + ", fields=" + Arrays.toString(fields) + "]";
	}

}


text:
<?xml version="1.0" encoding="iso-8859-1"?>
<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd">

			<title>Docs for page Logger.php</title>
			<link rel="stylesheet" href="../media/stylesheet.css" />

/Logger.php

Description

					Description |
							Classes
			|									Constants

Licensed to the Apache Software Foundation (ASF) under one or more  contributor license agreements. See the NOTICE file distributed with  this work for additional information regarding copyright ownership.

The ASF licenses this file to You under the Apache License, Version 2.0  (the "License"); you may not use this file except in compliance with  the License. You may obtain a copy of the License at

http://www.apache.org/licenses/LICENSE-2.0

Unless required by applicable law or agreed to in writing, software  distributed under the License is distributed on an "AS IS" BASIS,  WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.  See the License for the specific language governing permissions and  limitations under the License.

Classes

			Description |
			Classes
			|										Constants

					Class
					Description

						Logger

											This is the central class in the log4j package. Most logging operations,  except configuration, are done through this class.

Constants

			Description |
							Classes
				|									Constants

			LOG4PHP_DIR = dirname(__FILE__)
			(line 29)

LOG4PHP_DIR points to the log4php root directory.

If not defined it will be set automatically when the first package classfile  is included

		Documentation generated on Fri, 27 Nov 2009 07:44:45 +0100 by phpDocumentor 1.4.3


text:
package org.fujion.highcharts;

import org.fujion.annotation.Option;

import java.util.ArrayList;
import java.util.List;

/**
 * Options for sunburst plot.
 * <p>
 * A sunburst displays hierarchical data, where a level in the hierarchy is represented by a circle.
 * The center represents the root node of the tree. The visualization bears a resemblance to both
 * tree map and pie charts.
 */
public class PlotSunburst extends PlotOptions {

    /**
     * When enabled the user can click on a point which is a parent and zoom in on its children.
     * Defaults to false.
     */
    @Option
    public Boolean allowDrillToNode;

    /**
     * The center of the sunburst chart relative to the plot area. Can be percentages or pixel
     * values. Defaults to undefined.
     */
    @Option
    public List<String> center = new ArrayList<>();

    /**
     * Used together with the levels and allowDrillToNode options. When set to false the first level
     * visible when drilling is considered to be level one. Otherwise the level will be the same as
     * the tree structure. Defaults to true.
     */
    @Option
    public Boolean levelIsConstant;

    /**
     * Set options on specific levels. Takes precedence over series options, but not point options.
     */
    @Option
    public final List<LevelOptions> levels = new ArrayList<>();

    /**
     * How to interpret levelSize.value. percentage gives a width relative to result of outer radius
     * minus inner radius. pixels gives the ring a fixed width in pixels. weight takes the remaining
     * width after percentage and pixels, and distributes it accross all "weighted" levels. The
     * value relative to the sum of all weights determines the width. Defaults to weight.
     */
    @Option("levelSize.unit")
    public String levelSize_unit;

    /**
     * The value used for calculating the width of the ring. Its' affect is determined by
     * levelSize.unit. Defaults to 1.
     */
    @Option("levelSize.value")
    public Double levelSize_value;

    /**
     * Which point to use as a root in the visualization. Defaults to undefined.
     */
    @Option
    public String rootId;

    /**
     * If a point is sliced, moved out from the center, how many pixels should it be moved?.
     * Defaults to 10.
     */
    @Option
    public Integer slicedOffset;

    /**
     * The start angle of the pie slices in degrees where 0 is top and 90 right. Defaults to 0.
     */
    @Option
    public Double startAngle;
}


text:
const lib = require('./lib.js');
const config = require('../json/config.json');

module.exports = {
    isLive: function (twitch, channel, callback){
        'use strict';
        lib.request({
            url: `https://api.twitch.tv/kraken/streams/${channel}`,
            headers: {
                'Client-ID': config.twitch.clientId
            }
        }, function (err, res, data){
            if (!err & res.statusCode === 200){
                data = JSON.parse(data);
                if (data.stream !== null || undefined){
                    callback(true);
                } else {
                    callback(false);
                }
            }
        });
    }
};


text:
package com.dianping.cat.report.page.transaction.service;

import java.util.Date;

import org.unidal.lookup.annotation.Inject;

import com.dianping.cat.consumer.transaction.TransactionAnalyzer;
import com.dianping.cat.consumer.transaction.model.entity.TransactionReport;
import com.dianping.cat.helper.TimeHelper;
import com.dianping.cat.report.service.BaseHistoricalModelService;
import com.dianping.cat.report.service.ModelRequest;

public class HistoricalTransactionService extends BaseHistoricalModelService<TransactionReport> {

	@Inject
	private TransactionReportService m_reportService;

	public HistoricalTransactionService() {
		super(TransactionAnalyzer.ID);
	}

	@Override
	protected TransactionReport buildModel(ModelRequest request) throws Exception {
		String domain = request.getDomain();
		long date = request.getStartTime();
		TransactionReport report = getReportFromDatabase(date, domain);

		return report;
	}

	private TransactionReport getReportFromDatabase(long timestamp, String domain) throws Exception {
		return m_reportService.queryReport(domain, new Date(timestamp), new Date(timestamp + TimeHelper.ONE_HOUR));
	}

}


text:
using System;
using System.Security.Cryptography;

namespace BeIT.MemCached
{
	/// <summary>
	/// Fowler-Noll-Vo hash, variant 1, 32-bit version.
	/// http://www.isthe.com/chongo/tech/comp/fnv/
	/// </summary>
	public class FNV1_32 : HashAlgorithm
	{
		private static readonly uint FNV_prime = 16777619;
		private static readonly uint offset_basis = 2166136261;

		protected uint hash;

		public FNV1_32() {
			HashSizeValue = 32;
		}

		public override void Initialize() {
			hash = offset_basis;
		}

		protected override void HashCore(byte[] array, int ibStart, int cbSize) {
			int length = ibStart + cbSize;
			for (int i = ibStart; i < length; i++) {
				hash = (hash * FNV_prime)^array[i];
			}
		}

		protected override byte[] HashFinal() {
			return BitConverter.GetBytes(hash);
		}
	}

	/// <summary>
	/// Fowler-Noll-Vo hash, variant 1a, 32-bit version.
	/// http://www.isthe.com/chongo/tech/comp/fnv/
	/// </summary>
	public class FNV1a_32 : HashAlgorithm
	{
		private static readonly uint FNV_prime = 16777619;
		private static readonly uint offset_basis = 2166136261;

		protected uint hash;

		public FNV1a_32() {
			HashSizeValue = 32;
		}

		public override void Initialize() {
			hash = offset_basis;
		}

		protected override void HashCore(byte[] array, int ibStart, int cbSize) {
			int length = ibStart + cbSize;
			for (int i = ibStart; i < length; i++) {
				hash = (hash^array[i]) * FNV_prime;
			}
		}

		protected override byte[] HashFinal() {
			return BitConverter.GetBytes(hash);
		}
	}

	/// <summary>
	/// Modified Fowler-Noll-Vo hash, 32-bit version.
	/// http://home.comcast.net/~bretm/hash/6.html
	/// </summary>
	public class ModifiedFNV1_32 : FNV1_32
	{
		protected override byte[] HashFinal() {
			hash += hash << 13;
			hash ^= hash >> 7;
			hash += hash << 3;
			hash ^= hash >> 17;
			hash += hash << 5;
			return BitConverter.GetBytes(hash);
		}
	}
}