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

#include "chrome/browser/ash/policy/core/user_cloud_policy_store_ash.h"

#include <stdint.h>

#include <map>
#include <memory>
#include <string>

#include "base/bind.h"
#include "base/files/file_util.h"
#include "base/files/scoped_temp_dir.h"
#include "base/memory/weak_ptr.h"
#include "base/run_loop.h"
#include "base/task/single_thread_task_runner.h"
#include "base/test/task_environment.h"
#include "chromeos/ash/components/cryptohome/cryptohome_parameters.h"
#include "chromeos/ash/components/dbus/cryptohome/account_identifier_operators.h"
#include "chromeos/ash/components/dbus/session_manager/fake_session_manager_client.h"
#include "chromeos/ash/components/dbus/userdataauth/fake_cryptohome_misc_client.h"
#include "chromeos/ash/components/dbus/userdataauth/userdataauth_client.h"
#include "chromeos/components/onc/onc_test_utils.h"
#include "components/policy/core/common/cloud/cloud_policy_constants.h"
#include "components/policy/core/common/cloud/mock_cloud_policy_store.h"
#include "components/policy/core/common/cloud/test/policy_builder.h"
#include "components/policy/core/common/policy_types.h"
#include "components/policy/policy_constants.h"
#include "components/policy/proto/cloud_policy.pb.h"
#include "crypto/rsa_private_key.h"
#include "testing/gmock/include/gmock/gmock.h"
#include "testing/gtest/include/gtest/gtest.h"

namespace em = enterprise_management;

using RetrievePolicyResponseType =
    ash::SessionManagerClient::RetrievePolicyResponseType;

using testing::_;
using testing::AllOf;
using testing::Eq;
using testing::InvokeWithoutArgs;
using testing::Mock;
using testing::Property;
using testing::Return;
using testing::SaveArg;
using testing::SetArgPointee;

namespace policy {

namespace {

const char kDefaultHomepage[] = "http://chromium.org";

base::FilePath GetUserPolicyKeyFile(
    const base::FilePath& user_policy_dir,
    const cryptohome::AccountIdentifier& cryptohome_id) {
  const std::string sanitized_username =
      ash::UserDataAuthClient::GetStubSanitizedUsername(cryptohome_id);
  return user_policy_dir.AppendASCII(sanitized_username)
      .AppendASCII("policy.pub");
}

bool StoreUserPolicyKey(const base::FilePath& user_policy_dir,
                        const cryptohome::AccountIdentifier& cryptohome_id,
                        const std::string& public_key) {
  base::FilePath user_policy_key_file =
      GetUserPolicyKeyFile(user_policy_dir, cryptohome_id);
  if (!base::CreateDirectory(user_policy_key_file.DirName()))
    return false;
  return base::WriteFile(user_policy_key_file, public_key);
}

// For detailed test for UserCloudPolicyStoreAsh, this supports
// public key file update emulation.
class FakeSessionManagerClient : public ash::FakeSessionManagerClient {
 public:
  explicit FakeSessionManagerClient(const base::FilePath& user_policy_dir)
      : user_policy_dir_(user_policy_dir) {}

  FakeSessionManagerClient(const FakeSessionManagerClient&) = delete;
  FakeSessionManagerClient& operator=(const FakeSessionManagerClient&) = delete;

  // SessionManagerClient override:
  void StorePolicyForUser(const cryptohome::AccountIdentifier& cryptohome_id,
                          const std::string& policy_blob,
                          chromeos::VoidDBusMethodCallback callback) override {
    ash::FakeSessionManagerClient::StorePolicyForUser(
        cryptohome_id, policy_blob,
        base::BindOnce(&FakeSessionManagerClient::OnStorePolicyForUser,
                       weak_ptr_factory_.GetWeakPtr(), cryptohome_id,
                       std::move(callback)));
  }

  void set_user_public_key(const cryptohome::AccountIdentifier& cryptohome_id,
                           const std::string& public_key) {
    public_key_map_[cryptohome_id] = public_key;
  }

 private:
  void OnStorePolicyForUser(const cryptohome::AccountIdentifier& cryptohome_id,
                            chromeos::VoidDBusMethodCallback callback,
                            bool result) {
    if (result) {
      auto iter = public_key_map_.find(cryptohome_id);
      if (iter != public_key_map_.end())
        StoreUserPolicyKey(user_policy_dir_, cryptohome_id, iter->second);
    }
    std::move(callback).Run(result);
  }

  const base::FilePath user_policy_dir_;
  std::map<cryptohome::AccountIdentifier, std::string> public_key_map_;

  base::WeakPtrFactory<FakeSessionManagerClient> weak_ptr_factory_{this};
};

class UserCloudPolicyStoreAshTest : public testing::Test {
 public:
  UserCloudPolicyStoreAshTest(const UserCloudPolicyStoreAshTest&) = delete;
  UserCloudPolicyStoreAshTest& operator=(const UserCloudPolicyStoreAshTest&) =
      delete;

 protected:
  UserCloudPolicyStoreAshTest()
      : task_environment_(
            base::test::SingleThreadTaskEnvironment::MainThreadType::UI) {}

  void SetUp() override {
    ASSERT_TRUE(tmp_dir_.CreateUniqueTempDir());
    session_manager_client_ =
        std::make_unique<FakeSessionManagerClient>(user_policy_dir());
    store_ = std::make_unique<UserCloudPolicyStoreAsh>(
        &cryptohome_misc_client_, session_manager_client_.get(),
        base::SingleThreadTaskRunner::GetCurrentDefault(), account_id_,
        user_policy_dir(), false /* is_active_directory */);
    store_->AddObserver(&observer_);

    // Install the initial public key, so that by default the validation of
    // the stored/loaded policy blob succeeds.
    std::string public_key = policy_.GetPublicSigningKeyAsString();
    ASSERT_FALSE(public_key.empty());
    ASSERT_TRUE(
        StoreUserPolicyKey(user_policy_dir(), cryptohome_id_, public_key));

    policy_.payload().mutable_homepagelocation()->set_value(kDefaultHomepage);
    policy_.Build();
  }

  void TearDown() override {
    store_->RemoveObserver(&observer_);
    store_.reset();
  }

  // Install an expectation on |observer_| for an error code.
  // This method should be called after a store->Store()/Load() call has been
  // initiated. The expected OnStoreError call will be initiated asynchronously
  // from this run_loop's iteration.
  void RunLoopAndExpectError(CloudPolicyStore::Status error) {
    base::RunLoop run_loop;
    EXPECT_CALL(observer_, OnStoreError(AllOf(
                               Eq(store_.get()),
                               Property(&CloudPolicyStore::status, Eq(error)))))
        .WillOnce(InvokeWithoutArgs(&run_loop, &base::RunLoop::Quit));
    run_loop.Run();
    Mock::VerifyAndClearExpectations(&observer_);
  }

  // Install an expectation on |observer_| for a successful load operation.
  // This method should be called after a store->Store()/Load() call has been
  // initiated. The expected OnStoreLoaded call will be initiated asynchronously
  // from this run_loop's iteration.
  void RunLoopAndExpectLoaded() {
    base::RunLoop run_loop;
    EXPECT_CALL(observer_, OnStoreLoaded(store_.get()))
        .WillOnce(InvokeWithoutArgs(&run_loop, &base::RunLoop::Quit));
    run_loop.Run();
    Mock::VerifyAndClearExpectations(&observer_);
  }

  // Triggers a store_->Load() operation, handles the expected call to
  // |session_manager_client_| and sends |response|.
  void PerformPolicyLoad(const std::string& response) {
    // Issue a load command.
    session_manager_client_->set_user_policy(cryptohome_id_, response);
    store_->Load();
  }

  // Verifies that store_->policy_map() has the HomepageLocation entry with
  // the |expected_value|.
  void VerifyPolicyMap(const char* expected_value) {
    EXPECT_EQ(1U, store_->policy_map().size());
    const PolicyMap::Entry* entry =
        store_->policy_map().Get(key::kHomepageLocation);
    ASSERT_TRUE(entry);
    EXPECT_EQ(base::Value(expected_value),
              *entry->value(base::Value::Type::STRING));
  }

  // Stores the current |policy_| and verifies that it is published.
  // If |previous_value| is set then a previously existing policy with that
  // value will be expected; otherwise no previous policy is expected.
  // If |new_value| is set then a new policy with that value is expected after
  // storing the |policy_| blob.
  void PerformStorePolicy(const char* previous_value, const char* new_value) {
    const CloudPolicyStore::Status initial_status = store_->status();

    store_->Store(policy_.policy());

    // The new policy shouldn't be present yet.
    PolicyMap previous_policy;
    EXPECT_EQ(previous_value != nullptr, store_->policy() != nullptr);
    if (previous_value) {
      previous_policy.Set(key::kHomepageLocation, POLICY_LEVEL_MANDATORY,
                          POLICY_SCOPE_USER, POLICY_SOURCE_CLOUD,
                          base::Value(previous_value), nullptr);
    }
    EXPECT_TRUE(previous_policy.Equals(store_->policy_map()));
    EXPECT_EQ(initial_status, store_->status());

    RunLoopAndExpectLoaded();
    ASSERT_TRUE(store_->policy());
    EXPECT_EQ(policy_.policy_data().SerializeAsString(),
              store_->policy()->SerializeAsString());
    VerifyPolicyMap(new_value);
    EXPECT_EQ(CloudPolicyStore::STATUS_OK, store_->status());
  }

  void VerifyStoreHasValidationError() {
    EXPECT_FALSE(store_->policy());
    EXPECT_TRUE(store_->policy_map().empty());
    EXPECT_EQ(CloudPolicyStore::STATUS_VALIDATION_ERROR, store_->status());
  }

  base::FilePath user_policy_dir() {
    return tmp_dir_.GetPath().AppendASCII("var_run_user_policy");
  }

  base::FilePath user_policy_key_file() {
    return GetUserPolicyKeyFile(user_policy_dir(), cryptohome_id_);
  }

  base::test::SingleThreadTaskEnvironment task_environment_;
  ash::FakeCryptohomeMiscClient cryptohome_misc_client_;
  std::unique_ptr<FakeSessionManagerClient> session_manager_client_;
  UserPolicyBuilder policy_;
  MockCloudPolicyStoreObserver observer_;
  std::unique_ptr<UserCloudPolicyStoreAsh> store_;
  const AccountId account_id_ =
      AccountId::FromUserEmail(PolicyBuilder::kFakeUsername);
  const cryptohome::AccountIdentifier cryptohome_id_ =
      cryptohome::CreateAccountIdentifierFromAccountId(account_id_);

 private:
  base::ScopedTempDir tmp_dir_;
};

TEST_F(UserCloudPolicyStoreAshTest, InitialStore) {
  // Start without any public key to trigger the initial key checks.
  ASSERT_TRUE(base::DeleteFile(user_policy_key_file()));

  // Make the policy blob contain a new public key.
  policy_.SetDefaultNewSigningKey();
  policy_.Build();
  std::string new_public_key = policy_.GetPublicNewSigningKeyAsString();
  ASSERT_FALSE(new_public_key.empty());
  session_manager_client_->set_user_public_key(cryptohome_id_, new_public_key);
  ASSERT_NO_FATAL_FAILURE(PerformStorePolicy(nullptr, kDefaultHomepage));
  EXPECT_EQ(new_public_key, store_->policy_signature_public_key());
}

TEST_F(UserCloudPolicyStoreAshTest, InitialStoreValidationFail) {
  // Start without any public key to trigger the initial key checks.
  ASSERT_TRUE(base::DeleteFile(user_policy_key_file()));
  // Make the policy blob contain a new public key.
  policy_.SetDefaultSigningKey();
  policy_.Build();
  *policy_.policy().mutable_new_public_key_verification_signature_deprecated() =
      "garbage";

  store_->Store(policy_.policy());
  RunLoopAndExpectError(CloudPolicyStore::STATUS_VALIDATION_ERROR);

  EXPECT_EQ(CloudPolicyStore::STATUS_VALIDATION_ERROR, store_->status());
  EXPECT_EQ(std::string(), store_->policy_signature_public_key());
}

TEST_F(UserCloudPolicyStoreAshTest, InitialStoreMissingSignatureFailure) {
  // Start without any public key to trigger the initial key checks.
  ASSERT_TRUE(base::DeleteFile(user_policy_key_file()));
  // Make the policy blob contain a new public key.
  policy_.SetDefaultSigningKey();
  policy_.Build();
  policy_.policy().clear_new_public_key_verification_signature_deprecated();

  store_->Store(policy_.policy());
  RunLoopAndExpectError(CloudPolicyStore::STATUS_VALIDATION_ERROR);

  EXPECT_EQ(CloudPolicyStore::STATUS_VALIDATION_ERROR, store_->status());
  EXPECT_EQ(std::string(), store_->policy_signature_public_key());
}

TEST_F(UserCloudPolicyStoreAshTest, StoreWithExistingKey) {
  ASSERT_NO_FATAL_FAILURE(PerformStorePolicy(nullptr, kDefaultHomepage));
  EXPECT_EQ(policy_.GetPublicSigningKeyAsString(),
            store_->policy_signature_public_key());
}

TEST_F(UserCloudPolicyStoreAshTest, StoreWithRotation) {
  // Make the policy blob contain a new public key.
  policy_.SetDefaultNewSigningKey();
  policy_.Build();
  std::string new_public_key = policy_.GetPublicNewSigningKeyAsString();
  ASSERT_FALSE(new_public_key.empty());
  session_manager_client_->set_user_public_key(cryptohome_id_, new_public_key);
  ASSERT_NO_FATAL_FAILURE(PerformStorePolicy(nullptr, kDefaultHomepage));
  EXPECT_EQ(new_public_key, store_->policy_signature_public_key());
}

TEST_F(UserCloudPolicyStoreAshTest, StoreWithRotationMissingSignatureError) {
  // Make the policy blob contain a new public key.
  policy_.SetDefaultNewSigningKey();
  policy_.Build();
  policy_.policy().clear_new_public_key_verification_signature_deprecated();

  store_->Store(policy_.policy());
  RunLoopAndExpectError(CloudPolicyStore::STATUS_VALIDATION_ERROR);

  EXPECT_EQ(CloudPolicyStore::STATUS_VALIDATION_ERROR, store_->status());
  EXPECT_EQ(std::string(), store_->policy_signature_public_key());
}

TEST_F(UserCloudPolicyStoreAshTest, StoreWithRotationValidationError) {
  // Make the policy blob contain a new public key.
  policy_.SetDefaultNewSigningKey();
  policy_.Build();
  *policy_.policy().mutable_new_public_key_verification_signature_deprecated() =
      "garbage";

  store_->Store(policy_.policy());
  RunLoopAndExpectError(CloudPolicyStore::STATUS_VALIDATION_ERROR);

  EXPECT_EQ(CloudPolicyStore::STATUS_VALIDATION_ERROR, store_->status());
  EXPECT_EQ(std::string(), store_->policy_signature_public_key());
}

TEST_F(UserCloudPolicyStoreAshTest, StoreFail) {
  // Let store policy fail.
  session_manager_client_->ForceStorePolicyFailure(true);

  store_->Store(policy_.policy());
  RunLoopAndExpectError(CloudPolicyStore::STATUS_STORE_ERROR);

  EXPECT_FALSE(store_->policy());
  EXPECT_TRUE(store_->policy_map().empty());
  EXPECT_EQ(CloudPolicyStore::STATUS_STORE_ERROR, store_->status());
  EXPECT_EQ(std::string(), store_->policy_signature_public_key());
}

TEST_F(UserCloudPolicyStoreAshTest, StoreValidationError) {
  policy_.policy_data().clear_policy_type();
  policy_.Build();

  store_->Store(policy_.policy());
  RunLoopAndExpectError(CloudPolicyStore::STATUS_VALIDATION_ERROR);

  EXPECT_EQ(CloudPolicyStore::STATUS_VALIDATION_ERROR, store_->status());
  EXPECT_EQ(std::string(), store_->policy_signature_public_key());
}

TEST_F(UserCloudPolicyStoreAshTest, StoreValueValidationError) {
  std::string onc_policy = chromeos::onc::test_utils::ReadTestData(
      "toplevel_with_unknown_fields.onc");
  policy_.payload().mutable_opennetworkconfiguration()->set_value(onc_policy);
  policy_.Build();

  store_->Store(policy_.policy());
  RunLoopAndExpectLoaded();

  const CloudPolicyValidatorBase::ValidationResult* validation_result =
      store_->validation_result();
  EXPECT_EQ(CloudPolicyStore::STATUS_OK, store_->status());
  ASSERT_TRUE(validation_result);
  EXPECT_EQ(CloudPolicyValidatorBase::VALIDATION_OK, validation_result->status);
  EXPECT_EQ(3u, validation_result->value_validation_issues.size());
  EXPECT_EQ(policy_.policy_data().policy_token(),
            validation_result->policy_token);
  EXPECT_EQ(policy_.policy().policy_data_signature(),
            validation_result->policy_data_signature);
}

TEST_F(UserCloudPolicyStoreAshTest, StoreWithoutPolicyKey) {
  // Make the dbus call to cryptohome fail.
  cryptohome_misc_client_.SetServiceIsAvailable(false);

  store_->Store(policy_.policy());
  RunLoopAndExpectError(CloudPolicyStore::STATUS_VALIDATION_ERROR);

  EXPECT_EQ(CloudPolicyStore::STATUS_VALIDATION_ERROR, store_->status());
  EXPECT_EQ(std::string(), store_->policy_signature_public_key());
}

TEST_F(UserCloudPolicyStoreAshTest, StoreWithInvalidSignature) {
  // Break the signature.
  policy_.policy().mutable_policy_data_signature()->append("garbage");

  store_->Store(policy_.policy());
  RunLoopAndExpectError(CloudPolicyStore::STATUS_VALIDATION_ERROR);

  EXPECT_EQ(CloudPolicyStore::STATUS_VALIDATION_ERROR, store_->status());
  EXPECT_EQ(std::string(), store_->policy_signature_public_key());
}

TEST_F(UserCloudPolicyStoreAshTest, MultipleStoresWithRotation) {
  // Store initial policy signed with the initial public key.
  ASSERT_NO_FATAL_FAILURE(PerformStorePolicy(nullptr, kDefaultHomepage));
  const std::string initial_public_key = policy_.GetPublicSigningKeyAsString();
  EXPECT_EQ(initial_public_key, store_->policy_signature_public_key());

  // Try storing an invalid policy signed with the new public key.
  policy_.SetDefaultNewSigningKey();
  policy_.policy_data().clear_policy_type();
  policy_.Build();

  // Store policy
  store_->Store(policy_.policy());
  RunLoopAndExpectError(CloudPolicyStore::STATUS_VALIDATION_ERROR);

  // Still the initial public key is exposed.
  EXPECT_EQ(initial_public_key, store_->policy_signature_public_key());

  // Store the correct policy signed with the new public key.
  policy_.policy_data().set_policy_type(dm_protocol::kChromeUserPolicyType);
  policy_.Build();
  std::string new_public_key = policy_.GetPublicNewSigningKeyAsString();
  ASSERT_FALSE(new_public_key.empty());
  session_manager_client_->set_user_public_key(cryptohome_id_, new_public_key);
  ASSERT_NO_FATAL_FAILURE(
      PerformStorePolicy(kDefaultHomepage, kDefaultHomepage));
  EXPECT_EQ(policy_.GetPublicNewSigningKeyAsString(),
            store_->policy_signature_public_key());
}

TEST_F(UserCloudPolicyStoreAshTest, Load) {
  ASSERT_NO_FATAL_FAILURE(PerformPolicyLoad(policy_.GetBlob()));
  RunLoopAndExpectLoaded();

  // Verify that the policy has been loaded.
  ASSERT_TRUE(store_->policy());
  EXPECT_EQ(policy_.policy_data().SerializeAsString(),
            store_->policy()->SerializeAsString());
  VerifyPolicyMap(kDefaultHomepage);
  EXPECT_EQ(CloudPolicyStore::STATUS_OK, store_->status());
  EXPECT_EQ(policy_.GetPublicSigningKeyAsString(),
            store_->policy_signature_public_key());
}

TEST_F(UserCloudPolicyStoreAshTest, LoadNoPolicy) {
  ASSERT_NO_FATAL_FAILURE(PerformPolicyLoad(""));
  RunLoopAndExpectLoaded();

  // Verify no policy has been installed.
  EXPECT_FALSE(store_->policy());
  EXPECT_TRUE(store_->policy_map().empty());
  EXPECT_EQ(CloudPolicyStore::STATUS_OK, store_->status());
  EXPECT_EQ(std::string(), store_->policy_signature_public_key());
}

TEST_F(UserCloudPolicyStoreAshTest, LoadInvalidPolicy) {
  ASSERT_NO_FATAL_FAILURE(PerformPolicyLoad("invalid"));
  RunLoopAndExpectError(CloudPolicyStore::STATUS_PARSE_ERROR);

  // Verify no policy has been installed.
  EXPECT_FALSE(store_->policy());
  EXPECT_TRUE(store_->policy_map().empty());
  EXPECT_EQ(CloudPolicyStore::STATUS_PARSE_ERROR, store_->status());
  EXPECT_EQ(std::string(), store_->policy_signature_public_key());
}

TEST_F(UserCloudPolicyStoreAshTest, LoadValidationError) {
  policy_.policy_data().clear_policy_type();
  policy_.Build();

  ASSERT_NO_FATAL_FAILURE(PerformPolicyLoad(policy_.GetBlob()));
  RunLoopAndExpectError(CloudPolicyStore::STATUS_VALIDATION_ERROR);
  VerifyStoreHasValidationError();
  EXPECT_EQ(std::string(), store_->policy_signature_public_key());
}

TEST_F(UserCloudPolicyStoreAshTest, LoadNoKey) {
  // The loaded policy can't be verified without the public key.
  ASSERT_TRUE(base::DeleteFile(user_policy_key_file()));
  ASSERT_NO_FATAL_FAILURE(PerformPolicyLoad(policy_.GetBlob()));
  RunLoopAndExpectError(CloudPolicyStore::STATUS_VALIDATION_ERROR);
  VerifyStoreHasValidationError();
  EXPECT_EQ(std::string(), store_->policy_signature_public_key());
}

TEST_F(UserCloudPolicyStoreAshTest, LoadInvalidSignature) {
  // Break the signature.
  policy_.policy().mutable_policy_data_signature()->append("garbage");
  ASSERT_NO_FATAL_FAILURE(PerformPolicyLoad(policy_.GetBlob()));
  RunLoopAndExpectError(CloudPolicyStore::STATUS_VALIDATION_ERROR);
  VerifyStoreHasValidationError();
  EXPECT_EQ(std::string(), store_->policy_signature_public_key());
}

TEST_F(UserCloudPolicyStoreAshTest, LoadImmediately) {
  session_manager_client_->set_user_policy(cryptohome_id_, policy_.GetBlob());

  EXPECT_FALSE(store_->policy());

  EXPECT_CALL(observer_, OnStoreLoaded(store_.get()));
  store_->LoadImmediately();
  // Note: verify that the |observer_| got notified synchronously, without
  // having to spin the current loop. TearDown() will flush the loop so this
  // must be done within the test.
  Mock::VerifyAndClearExpectations(&observer_);

  // The policy should become available without having to spin any loops.
  ASSERT_TRUE(store_->policy());
  EXPECT_EQ(policy_.policy_data().SerializeAsString(),
            store_->policy()->SerializeAsString());
  VerifyPolicyMap(kDefaultHomepage);
  EXPECT_EQ(CloudPolicyStore::STATUS_OK, store_->status());
  EXPECT_EQ(policy_.GetPublicSigningKeyAsString(),
            store_->policy_signature_public_key());
}

TEST_F(UserCloudPolicyStoreAshTest, LoadImmediatelyNoPolicy) {
  EXPECT_FALSE(store_->policy());

  EXPECT_CALL(observer_, OnStoreLoaded(store_.get()));
  store_->LoadImmediately();
  Mock::VerifyAndClearExpectations(&observer_);

  EXPECT_FALSE(store_->policy());
  EXPECT_TRUE(store_->policy_map().empty());
  EXPECT_EQ(CloudPolicyStore::STATUS_OK, store_->status());
  EXPECT_EQ(std::string(), store_->policy_signature_public_key());
}

TEST_F(UserCloudPolicyStoreAshTest, LoadImmediatelyInvalidBlob) {
  session_manager_client_->set_user_policy(cryptohome_id_, "le blob");

  EXPECT_FALSE(store_->policy());

  EXPECT_CALL(observer_, OnStoreError(store_.get()));
  store_->LoadImmediately();
  Mock::VerifyAndClearExpectations(&observer_);

  EXPECT_FALSE(store_->policy());
  EXPECT_TRUE(store_->policy_map().empty());
  EXPECT_EQ(CloudPolicyStore::STATUS_PARSE_ERROR, store_->status());
  EXPECT_EQ(std::string(), store_->policy_signature_public_key());
}

TEST_F(UserCloudPolicyStoreAshTest, LoadImmediatelyDBusFailure) {
  session_manager_client_->set_user_policy(cryptohome_id_, policy_.GetBlob());

  // Make the dbus call to cryptohome fail.
  cryptohome_misc_client_.SetServiceIsAvailable(false);

  EXPECT_FALSE(store_->policy());

  EXPECT_CALL(observer_, OnStoreError(store_.get()));
  store_->LoadImmediately();
  Mock::VerifyAndClearExpectations(&observer_);

  EXPECT_FALSE(store_->policy());
  EXPECT_TRUE(store_->policy_map().empty());
  EXPECT_EQ(CloudPolicyStore::STATUS_LOAD_ERROR, store_->status());
  EXPECT_EQ(std::string(), store_->policy_signature_public_key());
}

TEST_F(UserCloudPolicyStoreAshTest, LoadImmediatelyNoUserPolicyKey) {
  session_manager_client_->set_user_policy(cryptohome_id_, policy_.GetBlob());

  // Ensure no policy data.
  ASSERT_TRUE(base::DeleteFile(user_policy_key_file()));
  EXPECT_FALSE(store_->policy());

  EXPECT_CALL(observer_, OnStoreError(store_.get()));
  store_->LoadImmediately();
  Mock::VerifyAndClearExpectations(&observer_);

  EXPECT_FALSE(store_->policy());
  EXPECT_TRUE(store_->policy_map().empty());
  EXPECT_EQ(CloudPolicyStore::STATUS_VALIDATION_ERROR, store_->status());
  EXPECT_EQ(std::string(), store_->policy_signature_public_key());
}

}  // namespace

}  // namespace policy


text:
namespace boost {

namespace archive {
namespace detail {
    template<class Archive, class T>
    class iserializer;
    template<class Archive, class T>
    class oserializer;
} // namespace detail
} // namespace archive

namespace serialization {

// forward declarations
template<class Archive, class T>
inline void serialize_adl(Archive &, T &, const unsigned int);
namespace detail {
    template<class Archive, class T>
    struct member_saver;
    template<class Archive, class T>
    struct member_loader;
} // namespace detail

// use an "accessor class so that we can use:
// "friend class boost::serialization::access;"
// in any serialized class to permit clean, safe access to private class members
// by the serialization system

class access {
public:
    // grant access to "real" serialization defaults
#ifdef BOOST_NO_MEMBER_TEMPLATE_FRIENDS
public:
#else
    template<class Archive, class T>
    friend struct detail::member_saver;
    template<class Archive, class T>
    friend struct detail::member_loader;
    template<class Archive, class T>
    friend class archive::detail::iserializer;
    template<class Archive, class T>
    friend class archive::detail::oserializer;
    template<class Archive, class T>
    friend inline void serialize(
        Archive & ar,
        T & t,
        const unsigned int file_version
    );
    template<class Archive, class T>
    friend inline void save_construct_data(
        Archive & ar,
        const T * t,
        const unsigned int file_version
    );
    template<class Archive, class T>
    friend inline void load_construct_data(
        Archive & ar,
        T * t,
        const unsigned int file_version
    );
#endif

    // pass calls to users's class implementation
    template<class Archive, class T>
    static void member_save(
        Archive & ar,
        //const T & t,
        T & t,
        const unsigned int file_version
    ){
        t.save(ar, file_version);
    }
    template<class Archive, class T>
    static void member_load(
        Archive & ar,
        T & t,
        const unsigned int file_version
    ){
        t.load(ar, file_version);
    }
    template<class Archive, class T>
    static void serialize(
        Archive & ar,
        T & t,
        const unsigned int file_version
    ){
        // note: if you get a compile time error here with a
        // message something like:
        // cannot convert parameter 1 from <file type 1> to <file type 2 &>
        // a likely possible cause is that the class T contains a
        // serialize function - but that serialize function isn't
        // a template and corresponds to a file type different than
        // the class Archive.  To resolve this, don't include an
        // archive type other than that for which the serialization
        // function is defined!!!
        t.serialize(ar, file_version);
    }
    template<class T>
    static void destroy( const T * t) // const appropriate here?
    {
        // the const business is an MSVC 6.0 hack that should be
        // benign on everything else
        delete const_cast<T *>(t);
    }
    template<class T>
    static void construct(T * t){
        // default is inplace invocation of default constructor
        // Note the :: before the placement new. Required if the
        // class doesn't have a class-specific placement new defined.
        ::new(t)T;
    }
    template<class T, class U>
    static T & cast_reference(U & u){
        return static_cast<T &>(u);
    }
    template<class T, class U>
    static T * cast_pointer(U * u){
        return static_cast<T *>(u);
    }
};

} // namespace serialization
} // namespace boost

#endif // BOOST_SERIALIZATION_ACCESS_HPP

redpajama_set_name: RedPajamaGithub


text:
var _ = require('lodash');

module.exports = function (subspace) {
  return {
    addShip: renderHandler('addShip'),
    orbitShip: require('./effects/orbit_ship')(),
    fireWeapons: require('./effects/fire_weapons'),
    fireChangeBomb: require('./effects/fire_change_bomb'),
    revealPlanet: require('./effects/reveal_planet'),
    addPlanet: require('./effects/add_planet')(),
    lookAt: renderHandler('lookAt'),
    follow: require('./effects/follow')(),
    commitDetails: require('./effects/commit_details'),
    chase: require('./effects/chase')(),
    repoDetails: require('./effects/repo_details'),
    nextCommit: function () {
      subspace.emit('nextCommit');
    }
  };
};

function renderHandler (name) {
  return function (animation, renderer) {
    var next = _.last(arguments),
        args = _(arguments).rest(2).without(next).value();

    renderer[name].apply(renderer, args);
    next();
  };
}


text:
Volume

Ringtone

<input data-dojo-type="dojox.mobile.Slider" value="0" min="0" max="20" step="0.1" type="range" style="width:90%;">

Media

<input data-dojo-type="dojox.mobile.Slider" value="0" min="0" max="20" step="0.1" type="range" style="width:90%;">

Alarm

<input data-dojo-type="dojox.mobile.Slider" value="0" min="0" max="20" step="0.1" type="range" style="width:90%;">
<button data-dojo-type="dojox.mobile.Button" class="mblSimpleDialogButton2l" onclick="hide('dlg_volume')">OK</button>
<button data-dojo-type="dojox.mobile.Button" class="mblSimpleDialogButton2r" onclick="hide('dlg_volume')">Cancel</button>


text:
To find out about recent outages, past [maintenance periods](/daily-maintenance/) or possible server errors, we have
created dynamic uptime charts.
The current stacked bar chart shows the uptime of the Albion servers from the last 24 hours grouped by the hour.
The times are displayed in server time, which is UTC. Don't forget to convert them to your local timezone.

AlbionStatus is usually tracking the server status once every minute. In case AlbionStatus could not retrieve the
Albion server status, e.g. because AlbionStatus itself is in maintenance mode, the minutes are shown as
*not tracked* in the uptime chart below.


text:
package kafka.common

/**
 * Indicates that the partition id is not between 0 and numPartitions-1
 */
class InvalidPartitionException(message: String) extends RuntimeException(message) {
  def this() = this(null)
}


text:
var path = require('path');
var webpack = require('webpack');
var HtmlWebPackPlugin = require('html-webpack-plugin');
var merge = require('webpack-merge');
var pkg = require('./package.json');
var Clean = require('clean-webpack-plugin');

var autoprefixer = require('autoprefixer');

var TARGET = process.env.npm_lifecycle_event;

var ROOT_PATH = path.resolve(__dirname);
var APP_PATH = path.resolve(ROOT_PATH, 'app');
var BUILD_PATH = path.resolve(ROOT_PATH, 'build');

process.env.BABEL_ENV = TARGET;

var common = {
    entry: APP_PATH,
    output: {
        path: BUILD_PATH,
        filename: 'bundle.js'
    },
    resolve: {
        extensions: ['', '.js', '.jsx']
    },
    module: {
        loaders: [
            {
                test: /\.jsx?$/,
                loaders: ['babel'],
                include: APP_PATH
            },
            {
                test: /\.css$/,
                loaders: ['style', 'css', 'postcss'],
                include: APP_PATH
            }
        ]
    },
    postcss: function () {
        return [autoprefixer];
    },
    plugins: [
        new HtmlWebPackPlugin(
            {
                title: 'Socket.io debugger',
                template: 'index-template.html',
                inject: 'body',
                favicon: 'favicon.png'
            }
        )
    ]
};

if(TARGET === 'start' || !TARGET) {
    module.exports = merge(common, {
        devtool: 'source-map',
        devServer: {
            historyApiFallback: true,
            hot: true,
            inline: true,
            progress: true
        },
        plugins: [
            new webpack.HotModuleReplacementPlugin()
        ]
    });
}

if(TARGET === 'build') {
    module.exports = merge(common, {
        devtool: 'source-map',
        entry: {
            app: APP_PATH,
            vendor: Object.keys(pkg.dependencies)
        },
        output: {
            path: BUILD_PATH,
            filename: '[name].[chunkhash].js?'
        },
        plugins: [
            new webpack.optimize.UglifyJsPlugin({
                compress: {
                    warnings: false
                }
            }),
            new webpack.DefinePlugin({
                'process.env': {
                    // This affects react lib size
                    'NODE_ENV': JSON.stringify('production')
                }
            }),
            new webpack.optimize.CommonsChunkPlugin(
                'vendor',
                '[name].[chunkhash].js'
            ),
            new Clean(['build'])
        ]
    });
}


text:
FROM debian:jessie
MAINTAINER Kévin Rauscher <kevin.rauscher@tomahna.fr>

RUN echo "deb http://ftp.debian.org/debian jessie-backports main" >> /etc/apt/sources.list.d/backports.list && \
	echo "deb http://dl.bintray.com/sbt/debian /" | tee -a /etc/apt/sources.list.d/sbt.list && \
	apt-key adv --keyserver hkp://keyserver.ubuntu.com:80 --recv 642AC823 && \
	apt-get update -y && \
	apt-get install -y --no-install-recommends fakeroot && \
	apt-get install -y --no-install-recommends openjdk-8-jdk && \
	apt-get install -y --no-install-recommends sbt && \
	sbt exit && \
	apt-get clean -y && \
	rm -rf /var/lib/apt/lists/*


text:
//Problem 7. One system to any other

//    Write a program to convert from any numeral system of given base
//    s to any other numeral system of base d (2 ≤ s, d ≤ 16).

using System;
using System.Text;

class OneSystemToAnyOther
{
    static void Main()
    {
        Console.Write("Enter system base s: ");
        int s = int.Parse(Console.ReadLine());
        Console.Write("Enter system base d: ");
        int d = int.Parse(Console.ReadLine());
        Console.Write("Enter number: ");
        string inputstring = Console.ReadLine();
        long decimalNumber = Convert.ToInt64(inputstring, s);

        if (d == 10)
        {
            Console.WriteLine("Number in {0} base system is:{1}", d, decimalNumber);
        }
        else
        {
            string result = ConvertNumber(decimalNumber, d);
            Console.WriteLine("Number in {0} base system is:{1}", d, result);
        }
    }

    private static string ConvertNumber(long decimalNumber, int d)
    {
        StringBuilder result = new StringBuilder();

        while (decimalNumber > 0)
        {
            long remainder = decimalNumber % d;
            result.Insert(0, SwitchNumbers(remainder));
            decimalNumber /= d;
        }
        return result.ToString();
    }

    private static string SwitchNumbers(long remainder)
    {
        switch (remainder)
        {

            case 1:
            case 2:
            case 3:
            case 4:
            case 5:
            case 6:
            case 7:
            case 8:
            case 9:
                return remainder.ToString();
            case 10: return "A";
            case 11: return "B";
            case 12: return "C";
            case 13: return "D";
            case 14: return "E";
            case 15: return "F";
            default: throw new Exception("Incorect numerical system");

        }
    }
}


text:
class AddIndexToProcessedFiles < ActiveRecord::Migration
  def change
    add_index :processed_files, :file_name, :unique => true
  end
end


text:
<META http-equiv="content-type" content="text/html;charset=iso-8859-9"/><meta name="viewport" content="width=device-width, initial-scale=1"><title>ac</title> <link rel="stylesheet"  href="css/jquery.mobile-1.2.0.css" />

EBU TAHÝR MAHALLÝ

Geri

Tasavvuf, hadis, Þafii mezhebi fýkýh alimi, vaiz ve hatib. Künyesi Ebu Tahir'dir. Ýsmi,
Muhammed olup babasýnýnki Hüseyin'dir. 1159 (H.554) yýlýnda Mýsýr'da Dimyat taraflarýnda
bir yer olan Cevcer'de doðdu. Mahalli ve Ensari nisbet edildi. Cami-i Mýsr-ý Atik'de ve
Cami-i Amr ibni As'da hatiblik yaptýðý için Hatib Ebu Tahir diye tanýndý.

Önceleri kötü kimselerle arkadaþlýk edip, Allahü tealanýn rýzasýna uygun olmayan iþlerle
meþgul idi. Genç yaþta halinin kötülüðünü anlayýp tövbe ederek, kendini ilim ve ibadete
verdi. Zamanýnda Mýsýr'ýn üç büyük fýkýh aliminden ders aldý. Bu alimlerden Tacüddin
Muhammed bin Hibetullah Hamevi'nin sohbetinde kemale geldi. Ebu Ýshak Iraki ve Ali bin
Zeyn et-Tüccar da, onun diðer fýkýh hocalarýydý. Hadis ilmini ise, Hafýz Ýbrahim bin Ömer
Si'ridi'den öðrendi. Eþ-Þeyh-ül-Celi, es-Seyyid-ül-Kebir Ebu Abdullah Kuraþi'nin
sohbetlerinde bulundu.

Ebu Tahir Abdullah fýkýh ve usul ilimlerinde çok ilerledi. Ýnsanlarýn sorularýna cevap verir,
sýkýntýlarýný giderirdi. Kendisine yapýlan kadýlýk tekliflerini reddederdi. Cami-i Atik ve
Cami-i Amr ibni As'ta hatiblik yapar, taliblerine usul ve fýkýh dersleri verirdi. Þafii
mezhebine göre fetva verirdi. Kimseden hiçbir þey istemez, hiçbir þekilde hediye kabul
etmezdi. Mýsýr Eyyubi Sultaný Melik Nasýrüddin Kamil tarafýndan, kardeþi Þam Sultaný
Melik-ül-Eþref Muzafferüddin Musa'ya, aralarýnda sulh yapmak için elçi olarak gönderildi.
Ýki kardeþin aralarýndaki kýrgýnlýklarý atarak barýþmalarýný saðlayýp, iki müslüman devletin
birlik ve beraberlik halinde yaþamalarýna vesile oldu. Allahü tealanýn rýzasýný kazanabilmek
gayesiyle kendisini ilim ve ibadete verdi. Gece ibadet eder, gündüzleri oruç tutardý.
Vakitlerini ilim öðrenmek ve öðretmekle geçirirdi. "Din nasihattir." emrine uymak için,
insanlara devamlý nasihatlerde bulunurdu.

Allahü tealanýn emir ve yasaklarýný çok iyi bilir ve bildiklerini tatbik ederdi. Allahü tealanýn
rýzasýna muhalif bir iþ yapmamak ve bir söz söylememek için çalýþýrdý. Selef-i salihin gibi
yaþamaya gayret eder, Resulullah efendimize bütün hal ve hareketlerinde uymaða çalýþýrdý.
Dünya ve dünya malýna hiç kýymet vermezdi. Eline geçeni Allahü tealanýn dininin yayýlmasý
ve kullarýnýn ihtiyaçlarýnýn karþýlanmasý için harcardý. Kimseye ihtiyacýndan bahsetmez,
ihtiyacýný cenab-ý Hakk'a arz ederdi. Pekçok kerametleri görüldü. Kýymetli eserler yazdý.

Birçok talebe yetiþtirdi. Ýbn-i Kalyubi'nin babasý Ziyaüddin Ebu Ravh Ýsa bin Rýdvan
Askalani, Ebü'l-Hüseyin Yahya bin Hüseyin bin Attar Kuraþi, Ýbn-i Rif'a ve daha birçok alim
kendisinden ilim öðrendi. Ýbn-i Kalyubi, onun keramet ve menkýbelerini Ez-Zahir fi

Menakýb-ý Ebu Tahir adlý eserinde yazdý. Bu eserden okunan, Ebu Tahir Mahalli
hazretlerinin hal ve kerametleri, dilden dile, gönülden gönüle aktarýldý.

Yine Ýbn-i Kalyubi babasýndan þöyle nakleder: "Bir gün Ebu Tahir'in kitaplarýndan bir kitap
aldým. Dýþýna bir þey bulaþtý. Öyle býrakýrsam eline bulaþýr, diye düþündüm. Su ile yýkadým,
temizlendi. Kitabý teslim etmek için götürdüðümde: "Kimden izin alýp da kitabýn cildini
yýkadýn?" diye sual edince, hiçbir þey söyleyemedim. Bir defasýnda da huzurlarýna vardým.
Arkasýnda namaz kýldýktan sonra müthiþ bir þekilde karným aðrýmaya baþladý ve þiddetinden
yerimde duramaz oldum. Ebu Tahir hazretleri ellerini uzattýlar. Onun eline yapýþtýðým anda
hiçbir þeyim kalmadý."

Kadý
Þerefüddin ibni Ayniddevle, minberde iken kendisi için dua etmesini istedi. Uzun bir
zaman sonra karþýlaþtýlar. Kadý
Þerefüddin'e; "Sen söylediðinden bu yana, hiçbir Cuma
hutbesinde, senin için dua etmeyi unutmadým." dedi.

Ebu Tahir Mahalli 1235 (H.633) yýlýnda vefat etti. Cenaze namazýný çok kalabalýk bir cemaat
kýldý. Ýmam-ý
Þafii hazretlerinin talebelerinden Ýmam-ý Müzeni'nin cenaze namazýndan bu
yana, Mýsýr'da böyle bir kalabalýk görülmedi. Alim, amir, fakir, zengin, cahil, sultan herkes
onun cenazesine iþtirak etti. Melik Kamil Þam'da olduðu için, oðlu Sultan Adil hazýr
bulundu. Mukattam daðý eteklerine, sýcak bir günde defnedildi. Kabri herkes tarafýndan
bilinmekte ve ziyarette bulunularak, istifade edilmektedir.

HÝÇ SAVAÞA GÝRMEMÝÞ GÝBÝ

Ýbn-i Kalyubi anlatýr: Zamanýn sultaný yolculuða çýkacaðý zaman Ebu Tahir Mahalli'ye uðrar, onun duasýný
almadan yola çýkmazdý. O da her defasýnda; "Allahü teala, sultaný muvaffak etsin." diye dua ederdi. Yine bir
seferinde Sultan ve arkadaþlarý kendisini ziyaret edip duasýný aldýlar. Onlar ayrýldýktan sonra; "Sanki
düþmanlarýnýn üstüne gidiyormuþ gibi benden nusret için dua istedi." dedi. Daha sonra sultanýn askerleri arasýna
katýlýp, Avrupa'dan gelen zalim Haçlý kuvvetlerine karþý çarpýþmak için gitti. Mensure'deki savaþta atýndan inip
düþmanla savaþtý. Yanýndakiler, hep þehid oldular. O da pekçok kafiri öldürdü. Ebu Tahir Mahalli'ye de birçok
ok ve kýlýç darbesi isabet etmesine raðmen, hiç savaþa girmemiþ gibi geri döndü."

1) Tabakat-üþ-Þafiiyye (Sübki); c.8, s.48

2) Hüsn-ül-Muhadara; c.1, s.411

3) Ýslam Alimleri Ansiklopedisi; c.8, s.260


text:
package com.intel.analytics.bigdl.dllib.keras.layers

import com.intel.analytics.bigdl.dllib.nn.Cell
import com.intel.analytics.bigdl.dllib.nn.abstractnn.TensorModule
import com.intel.analytics.bigdl.dllib.nn.internal.KerasLayer
import com.intel.analytics.bigdl.dllib.optim.Regularizer
import com.intel.analytics.bigdl.dllib.tensor.Tensor
import com.intel.analytics.bigdl.dllib.tensor.TensorNumericMath.TensorNumeric
import com.intel.analytics.bigdl.dllib.utils.{Log4Error, Shape}
import com.intel.analytics.bigdl.dllib.keras.Net
import com.intel.analytics.bigdl.dllib.keras.layers.utils.KerasUtils

import scala.reflect.ClassTag

/**
 * Convolutional LSTM.
 * Note that currently only 'same' padding is supported.
 * The convolution kernel for this layer is a square kernel with equal strides.
 * The input of this layer should be 5D, i.e. (samples, time, channels, rows, cols), and
 * 'CHANNEL_FIRST' (dimOrdering='th') is expected.
 *
 * When using this layer as the first layer in a model, you need to provide the argument
 * inputShape (a Single Shape, does not include the batch dimension).
 *
 * @param outputDimension Number of convolution filters to use.
 * @param nbKernel Number of rows/columns in the convolution kernel. Square kernel.
 * @param activation Activation function to use.
 *                   You can also pass in corresponding string representations such as 'relu'
 *                   or 'sigmoid', etc. for simple activations in the factory method.
 *                   Default is 'tanh'.
 * @param innerActivation Activation function for inner cells.
 *                        You can also pass in corresponding string representations such as 'relu'
 *                        or 'sigmoid', etc. for simple activations in the factory method.
 *                        Default is 'hard_sigmoid'.
 * @param dimOrdering Format of input data. Please use "CHANNEL_FIRST" (dimOrdering='th').
 * @param subsample Factor by which to subsample output.
 *                  Also called strides elsewhere. Default is 1.
 * @param borderMode One of "same" or "valid".
 *                  Also called padding elsewhere. Default is "valid".
 * @param wRegularizer An instance of [[Regularizer]], (eg. L1 or L2 regularization),
 *                     applied to the input weights matrices. Default is null.
 * @param uRegularizer An instance of [[Regularizer]], (eg. L1 or L2 regularization),
 *                     applied to the recurrent weights matrices. Default is null.
 * @param bRegularizer An instance of [[Regularizer]], applied to the bias. Default is null.
 * @param returnSeq Whether to return the full sequence or the last output
 *                  in the output sequence. Default is false.
 * @param goBackward Whether the input sequence will be processed backwards. Default is false.
 * @param mInputShape A Single Shape, does not include the batch dimension.
 * @tparam T The numeric type of parameter(e.g. weight, bias). Only support float/double now.
 */
class ConvLSTM2D[T: ClassTag](
   var outputDimension: Int,
   val nbKernel: Int,
   val activation: KerasLayer[Tensor[T], Tensor[T], T] = null,
   val innerActivation: KerasLayer[Tensor[T], Tensor[T], T] = null,
   val dimOrdering: String = "CHANNEL_FIRST",
   val subsample: Int = 1,
   val borderMode: String = "valid",
   var wRegularizer: Regularizer[T] = null,
   var uRegularizer: Regularizer[T] = null,
   var bRegularizer: Regularizer[T] = null,
   var returnSeq: Boolean = false,
   var goBackward: Boolean = false,
   var mInputShape: Shape = null)(implicit ev: TensorNumeric[T])
  extends Recurrent[T](outputDimension, returnSeq, goBackward, mInputShape) with Net {

  Log4Error.invalidInputError(dimOrdering.toLowerCase() == "channel_first",
    s"ConvLSTM2D currently only supports format CHANNEL_FIRST, but got format $dimOrdering")
  Log4Error.invalidInputError(borderMode.toLowerCase() == "same"
    || borderMode.toLowerCase() == "valid", s"ConvLSTM2D currently only supports " +
    s"same and valid, but got padding $borderMode")

  override def computeOutputShape(inputShape: Shape): Shape = {
    val input = inputShape.toSingle().toArray
    Log4Error.invalidInputError(input.length == 5,
      s"ConvLSTM2D requires 5D input, but got input dim ${input.length}")
    val rows = KerasUtils.computeConvOutputLength(input(3), nbKernel, borderMode, subsample)
    val cols = KerasUtils.computeConvOutputLength(input(4), nbKernel, borderMode, subsample)
    if (returnSequences) Shape(input(0), input(1), outputDimension, rows, cols)
    else Shape(input(0), outputDimension, rows, cols)
  }

  override def buildCell(input: Array[Int]): Cell[T] = {
    val paddingValue = if (borderMode.toLowerCase == "same") -1
    else 0
    new InternalConvLSTM2D[T](
      inputSize = input(2),
      outputSize = outputDimension,
      kernel = nbKernel,
      stride = subsample,
      padding = paddingValue,
      activation = activation.doBuild(inputShape).asInstanceOf[TensorModule[T]],
      innerActivation = innerActivation.doBuild(inputShape).asInstanceOf[TensorModule[T]],
      wRegularizer = wRegularizer,
      uRegularizer = uRegularizer,
      bRegularizer = bRegularizer,
      withPeephole = false)
  }
}

object ConvLSTM2D {
  def apply[@specialized(Float, Double) T: ClassTag](
    nbFilter: Int,
    nbKernel: Int,
    activation: String = "tanh",
    innerActivation: String = "hard_sigmoid",
    dimOrdering: String = "th",
    subsample: Int = 1,
    borderMode: String = "valid",
    wRegularizer: Regularizer[T] = null,
    uRegularizer: Regularizer[T] = null,
    bRegularizer: Regularizer[T] = null,
    returnSequences: Boolean = false,
    goBackwards: Boolean = false,
    inputShape: Shape = null)(implicit ev: TensorNumeric[T]): ConvLSTM2D[T] = {
    new ConvLSTM2D[T](nbFilter, nbKernel, KerasUtils.getKerasActivation(activation),
      KerasUtils.getKerasActivation(innerActivation),
      KerasUtils.toBigDLFormat5D(dimOrdering),
      subsample, borderMode, wRegularizer, uRegularizer, bRegularizer,
      returnSequences, goBackwards, inputShape)
  }
}


text:
class CefKeyboardHandlerCppToC
    : public CefCppToC<CefKeyboardHandlerCppToC, CefKeyboardHandler,
        cef_keyboard_handler_t> {
 public:
  explicit CefKeyboardHandlerCppToC(CefKeyboardHandler* cls);
  virtual ~CefKeyboardHandlerCppToC() {}
};

#endif  // USING_CEF_SHARED
#endif  // CEF_LIBCEF_DLL_CPPTOC_KEYBOARD_HANDLER_CPPTOC_H_


text:
package org.apache.ignite.internal.processors.cache.distributed.dht;

import org.apache.ignite.cache.*;

import static org.apache.ignite.cache.CacheMemoryMode.*;

/**
 * Tests colocated cache with values being stored off-heap.
 */
public class GridCachePartitionedNearDisabledOffHeapFullApiSelfTest extends
    GridCachePartitionedNearDisabledFullApiSelfTest {
    /** {@inheritDoc} */
    @Override protected CacheMemoryMode memoryMode() {
        return OFFHEAP_VALUES;
    }
}


text:
package org.jretty.util;
import java.net.InetAddress;

import org.jretty.util.InetAddressHelper;

public class InetAddressHelperTest {

    public static void main(String[] args) {

        InetAddress ia = new InetAddressHelper("www.baidu.com").startJoin(2000).getInetAddress();

        System.out.println(ia != null ? ia.getHostAddress() : null);

        String host = new InetAddressHelper(ia).startJoin(2000).getHostName();
        System.out.println(host);

    }

}


text:
<?php

/*
 * To change this template, choose Tools | Templates
 * and open the template in the editor.
 */

/**
 * Description of DataView
 *
 * @author Dan Kottke
 */
class DataView {

    //ordered flow, subsequent nodes can only connect to existing nodes.
    //connections only link primary key of one to FK of other
    //can have multiple connections between same two nodes (join on and)
    //connections also contain left, inner, or right stipulation, order important
    //persistable nodes must be retrievable once generated
    //must be able to figure out FK hierarchy for save (children upward)

    //TODO: add specific keyPair model

    //output
    protected $generatedSQL;
    protected $sqlResultSet;
    protected $resultSet; //index => array(memID => template)
    //protected $transformedResultsSet;
    //input
    //protected $persistableWeb;

    protected $friendlyNames; // uniqueString => memID;

    protected $persistableInputCollection; //$memID => template
    protected $graphLinks; // index => (memID1, memID2, array(key1, key2), joinType)
    protected $exclusions;
    protected $includeKeys;

    protected $keyPairs;

    protected $connection;

    public function __construct($connection = null) {
        $this->resultSet = array();
        $this->friendlyNames = array();
        $this->persistableInputCollection = array();
        $this->graphLinks = array();
        $this->exclusions = array();
        $this->includeKeys = array();
        $this->set_connection($connection);
    }

    public function encodeGUIDForSQL($guid)
    {
        return str_replace('-', '_', $guid);
    }

    public function decodeGUIDForSQL($encodedGuid)
    {
        return str_replace('_', '-', $encodedGuid);
    }

    public function encodeColumnForSQL(DataBoundSimplePersistable $persistable, $columnName)
    {
        return $persistable->get_table()."__X__". $this->encodeGUIDForSQL($persistable->getUniqueReferenceKey()) ."__X__".$columnName;
    }

    public function decodeColumnForSQL($column)
    {
        $tripletTemp = explode('__X__', $column);
        $returnMe = array(
                            'tableName' => $tripletTemp[0],
                            'memID' => $this->decodeGUIDForSQL($tripletTemp[1]),
                            'field' => $tripletTemp[2]
            );
        return $returnMe;
    }

    public function startWeb(IPersistable $persistable,
                                $friendlyName,
                                $exclusions = array(),
                                $includeKey = false)
    {
        $newMemID = $persistable->getUniqueReferenceKey();

        $friendlyNames = $this->get_friendlyNames();
        $friendlyNames[$friendlyName] = $newMemID;
        $this->set_friendlyNames($friendlyNames);

        $persistableInputCollection = $this->get_persistableInputCollection();
        $persistableInputCollection[$newMemID] = $persistable;
        $this->set_persistableInputCollection($persistableInputCollection);

        $ex = $this->get_exclusions();
        $ex[$newMemID] = $exclusions;
        $this->set_exclusions($ex);

        $ik = $this->get_includeKeys();
        $ik[$newMemID] = $includeKey;
        $this->set_includeKeys($ik);

        return $this;
    }

    public function addToWeb(IPersistable $persistable,
                                $friendlyName,
                                $keyPairs,
                                $joinType,
                                $exclusions = array(),
                                $includeKey = false)
    {

        $this->startWeb($persistable, $friendlyName, $exclusions, $includeKey);
        $newMemID = $persistable->getUniqueReferenceKey();
        //$friendlyNames = $this->get_friendlyNames();

        $graphLink = new DataViewGraphLink($newMemID, $keyPairs, $joinType);
        $graphLinks = $this->get_graphLinks();
        $graphLinks[] = $graphLink;
        $this->set_graphLinks($graphLinks);

    }

    public function generateSQL($excludedMemIDsFromSelect = array(), $orderBy = array(), $limit = null, $condition = null)
    {
        $this->set_generatedSQL($this->translatePropertiesIntoQuery($excludedMemIDsFromSelect, $orderBy, $limit, $condition));
    }

    public function execute()
    {
        return $this->get_connection()->query($this->get_generatedSQL()->toSQL());
    }

    public function read()
    {
        //$this->execute();
        return $this->get_connection()->fetch();
    }

    public function readObjectRow($excludedMemIDsFromPopulate = array())
    {
        //$this->execute();
        if($row = $this->get_connection()->fetch())
        {
            //return $row;
            return $this->retrieveComponentsFromRow($row, $excludedMemIDsFromPopulate);
        }
        else
        {
            return false;
        }

    }

    public function generateSelectionCollection($columnName)
    {
        //$tempArr = $this->decodeColumnForSQL($columnName);
        //$tempArr['memID'];
        $returnMe = array();
        $this->execute();
        while($row = $this->read())
        {
            if(!in_array($row->$columnName, $returnMe))
            $returnMe[$row->$columnName] = $row->$columnName;
        }
        return $returnMe;

    }

    public function generateObjectCollection($memID)
    {
        $returnMe = array();
        $tempArr = array_keys($this->get_persistableInputCollection());
        $tempArr = array_combine($tempArr, $tempArr);
        unset($tempArr[$memID]);

        $this->execute();

        while($row = $this->readObjectRow($tempArr))
        {
            //var_dump($row);
            //echo $memID;
            if(!array_key_exists($row[$memID]->get_keyValue(), $returnMe))
            $returnMe[$row[$memID]->get_keyValue()] = $row[$memID];
        }
        return $returnMe;
    }

    public function generateDataRows()
    {
        $sqlResultSet = array();
        $this->execute();
        //$ds = $this->get_connection();// $firstPersistable->get_connection();//MySQLConfig::dsConnect();
        while($row = $this->read())
        {
            $sqlResultSet[] = $row;
        }
        $this->set_sqlResultSet($sqlResultSet);
        return $sqlResultSet;
        /*
        try
        {
            $ds->query($this->get_generatedSQL()->toSQL());

            while($row = $ds->fetch())
            {
                $sqlResultSet[] = $row;
                $resultSet[] = $this->retrieveComponentsFromRow($row);

            }
            $this->set_sqlResultSet($sqlResultSet);
            $this->set_resultSet($resultSet);
            //echo $query;
            return $resultSet;
        }
        catch(Exception $ex)
        {
            throw new Exception("Generate failed with query " . $this->get_generatedSQL());
        }
         *
         */
    }

    public function generateObjectRows($excludedMemIDsFromPopulate = array())
    {
        $resultSet = array();
        $this->execute();
        while($row = $this->readObjectRow($excludedMemIDsFromPopulate))
        {
            $resultSet[] = $row;
        }
        $this->set_resultSet($resultSet);
        return $resultSet;

    }
    /*
    public function generateSelectionCollectionAndDataRows($columnName)
    {

    }

    public function generateSelectionCollectionAndObjectRows($columnName, $excludedMemIDsFromPopulate = array())
    {

    }
    */
    public function generateDataAndObjectRows($excludedMemIDsFromPopulate = null)
    {
        $sqlResultSet = array();
        $resultSet = array();
        $this->execute();
        //$ds = $this->get_connection();// $firstPersistable->get_connection();//MySQLConfig::dsConnect();
        while($row = $this->read())
        {
            $sqlResultSet[] = $row;
            $resultSet[] = $this->retrieveComponentsFromRow($row);
        }
        $this->set_sqlResultSet($sqlResultSet);
        $this->set_resultSet($resultSet);
        //return $sqlResultSet;
    }
    /*
    public function generateSelectionCollectionAndDataAndObjectRows($columnName, $excludedMemIDsFromPopulate = array())
    {

    }
    */
    /*
    public function generateComplexObjectRows()
    {

    }
    */
    /*
    public function generate($excludedMemIDsFromSelect = array(), $orderBy = array(), $limit = null, $condition = null)
    {
        $this->translatePropertiesIntoQuery($excludedMemIDsFromSelect, $orderBy, $limit);
        return $this->generateResultSetFromAttachedQueryAndKeys();

    }
    */

    public function translatePropertiesIntoQuery($excludedMemIDsFromSelect = array(), $orderBy = array(), $limit = null, $condition = null)
    {
        $persistableCollection = $this->get_persistableInputCollection();
        $firstPersistable = array_shift(array_values($persistableCollection));
        $this->set_persistableInputCollection($persistableCollection);

        //$friendlyNames = clone $this->get_friendlyNames();

        //$graphLinks = clone $this->get_graphLinks();
        $exclusions = $this->get_exclusions();
        $includeKeys = $this->get_includeKeys();

        $firstMemID = $firstPersistable->getUniqueReferenceKey();

        $firstVal = $firstPersistable->get_keyValue();
        if($includeKeys[$firstMemID] && !isset($firstVal))
        {
            throw new Exception('Key is not set, cannot include key');
        }
        // TODO: allow a way to pass in source so IPersistable is proper here. This expects SQL simple persistable
        $query = SQLGen::Query(ValidQueryDatabaseFormats::MYSQL, $firstPersistable->get_database())->
                fromTable($firstPersistable->get_table(), $firstPersistable->get_table())->join();

        $arrayToWhereLater = array();

        foreach($this->get_graphLinks() as $link)
        {
            $link instanceof DataViewGraphLink;
            // var_dump($link);

            $keyPairs = $link->get_keyPairs();
            $pair = array_pop($keyPairs);
            $pair instanceof DataViewKeyPair;

            foreach($keyPairs as $wherePair)
            {
                $arrayToWhereLater[] = $wherePair;
            }
            //echo $persistableCollection[$link->get_memID1()]->get_table();
            //var_dump($persistableCollection);
            //echo $link->get_memID1();
            //$templates = $this->get_persistableInputCollection();
            //$query = $query->joinTable($joinType, $newSourceName, $newSourceAlias, $newSelectionName, $existingSourceAlias, $existingSelectionName, $newSourceDBName)
            if($pair->get_memIDOne() == $link->get_memID())
            {
                $oldMemID = $pair->get_memIDTwo();
                $newMemID = $pair->get_memIDOne();
                $oldKey = $pair->get_keyTwo();
                $newKey = $pair->get_keyOne();
            }
            else
            {
                $oldMemID = $pair->get_memIDOne();
                $newMemID = $pair->get_memIDTwo();
                $oldKey = $pair->get_keyOne();
                $newKey = $pair->get_keyTwo();
            }
            // echo $oldMemID; echo '-xxx';
            // echo $this->get_persistableInputCollection()[$oldMemID]->get_table(); echo '---';
            // echo $oldMemID; echo '-----';

            $query = $query->joinTable($link->get_joinType(),
                                        $persistableCollection[$newMemID]->get_table(),
                                        $persistableCollection[$newMemID]->get_table(),
                                        $newKey,
                                        $persistableCollection[$oldMemID]->get_table(),
                                        $oldKey,
                                        $persistableCollection[$newMemID]->get_database());
            //echo $query;
        }
        //echo $query;

        $query = $query->select();
        foreach($this->get_persistableInputCollection() as $persistable)
        {
            $persistable instanceof DataBoundSimplePersistable;
            if(!in_array($persistable->getUniqueReferenceKey(), $excludedMemIDsFromSelect))
            {
                $query = $query->select($persistable->get_keyName(), $persistable->get_table(), $this->encodeColumnForSQL($persistable, $persistable->get_keyName()));// $persistable->get_table()."__X__".  $this->encodeGUIDForSQL($persistable->getUniqueReferenceKey()) ."__X__".$persistable->get_keyName());
                foreach($persistable->get_sourceKeys() as $key)
                {
                    $query = $query->select($key, $persistable->get_table(), $this->encodeColumnForSQL($persistable, $key));// $persistable->get_table()."__X__". $this->encodeGUIDForSQL($persistable->getUniqueReferenceKey()) ."__X__".$key);
                }
            }
        }

        foreach($arrayToWhereLater as $wherePair)
        {

            $wherePair instanceof DataViewKeyPair;
            $firstConstant = new QueryFreeFormConstant($persistableCollection[$wherePair->get_memIDOne()]->get_source() .".". $wherePair->get_keyOne());
            $secondConstant = new QueryFreeFormConstant($persistableCollection[$wherePair->get_memIDTwo()]->get_source() .".". $wherePair->get_keyTwo());;
            $query = $query->where($firstConstant, ValidSQLComparisonOperations::EQUALS, $secondConstant);

        }
        foreach($this->get_persistableInputCollection() as $persistable)
        {
            foreach($persistable->get_sourceValues() as $key => $value)
            {
                if(isset($value) && !in_array($key, $exclusions[$persistable->getUniqueReferenceKey()]))
                {
                    if(/*($includeKey && isset($this->get_keyValue())) ||*/ $key != $persistable->get_keyName())
                    {
                        $query = $query->where(SQLGen::referenceSourceSelection($query, $persistable->get_table(), $key),
                            ValidSQLComparisonOperations::EQUALS,
                            $value);
                    }
                }
            }
            $thisVal = $persistable->get_keyValue();
            if(isset($thisVal))
            {
                $query = $query->where(SQLGen::referenceSourceSelection($query, $persistable->get_table(), $persistable->get_keyName()),
                            ValidSQLComparisonOperations::EQUALS,
                            $thisVal);
            }
        }
        if(isset($condition))
        {
            $query = $query->where_condition($condition, ValidSQLComparisonOperations::_AND);
        }
                //joinTable($joinType, $newSourceName, $newSourceAlias, $newSelectionName, $existingSourceAlias, $existingSelectionName, $newSourceDBName)
                //select()->selectStar();
        foreach($orderBy as $encodedColName => $secondaryParam)
        {

            if(array_key_exists('direction', $secondaryParam))
            {
                $direction = $secondaryParam['direction'];
            }
            else
            {
                $direction = null;
            }
            if(array_key_exists('cast_type', $secondaryParam))
            {
                $cast_type = $secondaryParam['cast_type'];
            }
            else
            {
                $cast_type = null;
            }
            $query = $query->orderBy($encodedColName, $direction, $cast_type);

            //$query = $query->orderBy($encodedColName, $direction);
        }
        if(isset($limit))
        {
            $query = $query->limit($limit);
        }

        $this->set_generatedSQL($query);
        $this->set_keyPairs($this->populatePairsFromLinks());
        return $query;
    }

    /*
    public function generateResultSetFromAttachedQueryAndKeys()
    {
        $resultSet = array();
        $sqlResultSet = array();
        $ds = $this->get_connection();// $firstPersistable->get_connection();//MySQLConfig::dsConnect();
        try
        {
            $ds->query($this->get_generatedSQL()->toSQL());

            while($row = $ds->fetch())
            {
                $sqlResultSet[] = $row;
                $resultSet[] = $this->retrieveComponentsFromRow($row);

            }
            $this->set_sqlResultSet($sqlResultSet);
            $this->set_resultSet($resultSet);
            //echo $query;
            return $resultSet;
        }
        catch(Exception $ex)
        {
            throw new Exception("Generate failed with query " . $this->get_generatedSQL());
        }
    }
    */
    protected function retrieveComponentsFromRow($row, $excludedMemIDsFromPopulate = array())
    {
        $persistables = $this->get_persistableInputCollection();

        $includedPersistables = array();

        foreach($row as $key => $value)
        {
            if(ctype_digit($value))
            {
                $value = (int)$value;
            }
            // else if(is_string($value))
            // {
            //     $value = addslashes($value);
            // }
            //$triplet = array();
            //$tripletTemp = explode('__X__', $key);
            $colParts = $this->decodeColumnForSQL($key);
            $tableName = $colParts['tableName'];//$tripletTemp[0];
            $memID = $colParts['memID'];//$this->decodeGUIDForSQL($tripletTemp[1]);
            $field = $colParts['field'];//$tripletTemp[2];

            if(array_key_exists($memID, $persistables) && !in_array($memID, $excludedMemIDsFromPopulate))
            {
                if(!array_key_exists($memID, $includedPersistables))
                {

                    $persistable = clone $persistables[$memID];
                    //$persistable->$field = $value;
                    if($field != $persistable->get_keyName())
                    {
                        if(!isset($value) || $value === DB_NULL)
                        {
                            $persistable->$field = DB_NULL;
                        }
                        else
                        {
                            $persistable->$field = $value;
                        }
                    }
                    else
                    {
                        $persistable->set_keyValue($value);

                    }
                    $persistable->set_isDirty(false);
                    $includedPersistables[$memID] = $persistable;

                }
                else
                {

                    $persistable = $includedPersistables[$memID];

                    if($field != $persistable->get_keyName())
                    {
                        if(!isset($value) || $value === DB_NULL)
                        {
                            $persistable->$field = DB_NULL;
                        }
                        else
                        {
                            $persistable->$field = $value;
                        }

                    }
                    else
                    {
                        $persistable->set_keyValue($value);

                    }
                    $persistable->set_isDirty(false);
                    $includedPersistables[$memID] = $persistable;

                }
            }

            //echo $persistable->get_keyValue();

        }
        return $includedPersistables;
    }

    //recursive params : result array, link pairs
    //step 1, ma

    //initializeFunction
    //-focal memID
    //
    //creates array of result arrays (eventually populated) with row for every unique focal entity
    // each row of these is passed into recursive function
    //
    //recursive function
    // -result array
    // -remaining link pairs
    public function recursiveExperiment($focalMemID, $linkPairsLeft = array(), $transformedResultSet = array())
    {
        // TODO: add recursive calls once output can be made into tree rather than flat-ish array
        $resultSet = $this->get_resultSet();
        if(!isset($resultSet))
        {
            return false;
        }

        $childMemIDs = array();
        $parentsMemIDs = array();

        foreach($linkPairsLeft as $pairKey => $pair)
        {
            $pair instanceof DataViewKeyPair;

            if($pair->getParentMemID() == $focalMemID)
            {
                $childMemIDs[$pair->getChildMemID()] = $pair->getChildMemID();
                unset($linkPairsLeft[$pairKey]);
            }
            if($pair->getChildMemID() == $focalMemID)
            {
                $parentsMemIDs[$pair->getParentMemID()] = $pair->getParentMemID();
                unset($linkPairsLeft[$pairKey]);
            }

        }

        // 1 row per focal, index is array( keyVal => array ( memID => array(keyVal => object), memID => array(keyVal => object), memID => array(keyVal => object) ) )

        $accountedForKeys = array(); //$memID => array( keyValue )

        foreach($resultSet as $arrayRow)
        {
            //reference to row of current focal object in return array
            $transformedRowKey = null;
            //find focal object (must do this first to determine row)
            foreach($arrayRow as $memID => $object)
            {
                if(!array_key_exists($memID, $accountedForKeys))
                {
                    $accountedForKeys[$memID] = array();
                }
                $object instanceof IPersistable;
                if($memID == $focalMemID  )
                {
                    $transformedRowKey = $object->get_keyValue();

                    if(!(in_array($transformedRowKey, $accountedForKeys[$memID])))
                    {
                        $transformedResultSet[$transformedRowKey] = array();
                        $transformedResultSet[$transformedRowKey][$memID] = array();
                        $transformedResultSet[$transformedRowKey][$memID][$object->get_keyValue()] = $object;
                        $accountedForKeys[$memID][] = $object->get_keyValue();
                    }

                    //see if focal object row already exists in transformedResultSet
                    //if so get that row

                }
            }
            foreach($arrayRow as $memID => $object)
            {
                $object instanceof IPersistable;

                if(in_array ($memID, $childMemIDs))
                {
                    if(!(in_array($object->get_keyValue(), $accountedForKeys[$memID])))
                    {
                        if(!array_key_exists($memID, $transformedResultSet[$transformedRowKey]))
                        {
                            $transformedResultSet[$transformedRowKey][$memID] = array();
                        }
                        $transformedResultSet[$transformedRowKey][$memID][$object->get_keyValue()] = $object; //later object here is recursive call
                        $accountedForKeys[$memID][] =  $object->get_keyValue();
                    }
                }
                elseif(in_array ($memID, $parentsMemIDs))
                {
                    if(!(in_array($object->get_keyValue(), $accountedForKeys[$memID])))
                    {
                        if(!array_key_exists($memID, $transformedResultSet[$transformedRowKey]))
                        {
                            $transformedResultSet[$transformedRowKey][$memID] = array();
                        }
                        $transformedResultSet[$transformedRowKey][$memID][$object->get_keyValue()] = $object; //later object here is recursive call
                        $accountedForKeys[$memID][] =  $object->get_keyValue();
                    }
                }

            }

        }

        return $transformedResultSet;

    }

    public function transformResultSetFriendly($friendlyName)
    {
        $friendlies = $this->get_friendlyNames();
        return $this->transformResultSet($friendlies[$friendlyName]);
    }

    public function transformResultSet($focalMemID)
    {
        /*
        $pairs = array();
        foreach($this->get_graphLinks() as $link)
        {
            foreach($link->get_keyPairs() as $pair)
            {

            }
            $pairs[] = $pair;
        }
         */
        return $this->recursiveExperiment($focalMemID, $this->get_keyPairs());

    }
    /*
    protected function getChildrenMemIDNodes($pairs)
    {
        $returnMe = array('links' => null, 'children' => null);

        foreach($pairs as $pair)
        {
            $pair instanceof DataViewKeyPair;

        }

    }

    protected function getParentMemIDNodes($pairs)
    {
        $returnMe = array('links' => null, 'parents' => null);
        foreach($pairs as $pair)
        {

        }

    }
    */

    public function populatePairsFromLinks()
    {
        $pairs = array();
        foreach($this->get_graphLinks() as $link)
        {
            foreach($link->get_keyPairs() as $pair)
            {

            }
            $pairs[] = $pair;
        }
        return $pairs;
    }

    public function get_keyPairs() {
        return $this->keyPairs;
    }

    public function set_keyPairs($keyPairs) {
        $this->keyPairs = $keyPairs;
    }

    public function getFromResult($memID, array $resultRow)
    {
        return $resultRow[$memID];
    }
    public function getFromResultFriendly($friendlyName, array $resultRow)
    {
        //$friendlies = $this->get_friendlyNames();
        return $this->getFromResult($this->getMemIDFromFriendly($friendlyName), $resultRow);
    }

    public function get_resultSet() {
        return $this->resultSet;
    }

    public function set_resultSet($resultSet) {
        $this->resultSet = $resultSet;
    }

    public function get_sqlResultSet() {
        return $this->sqlResultSet;
    }

    public function set_sqlResultSet($sqlResultSet) {
        $this->sqlResultSet = $sqlResultSet;
    }

    public function get_exclusions() {
        return $this->exclusions;
    }

    public function set_exclusions($exclusions) {
        $this->exclusions = $exclusions;
    }

    public function get_includeKeys() {
        return $this->includeKeys;
    }

    public function set_includeKeys($includeKeys) {
        $this->includeKeys = $includeKeys;
    }

    public function get_friendlyNames() {
        return $this->friendlyNames;
    }

    public function set_friendlyNames($friendlyNames) {
        $this->friendlyNames = $friendlyNames;
    }

    public function getMemIDFromFriendly($friendlyName)
    {
        $friendlies = $this->get_friendlyNames();
        return $friendlies[$friendlyName];
    }

    public function getFromPersistableInputCollection($memID)
    {
        $persistables = $this->get_persistableInputCollection();
        return $persistables[$memID];
    }
    public function getFromPersistableInputCollectionFriendly($friendlyName)
    {
        //$friendlies = $this->get_friendlyNames();
        return $this->getFromPersistableInputCollection($this->getMemIDFromFriendly($friendlyName));
    }

    public function get_persistableInputCollection() {
        return $this->persistableInputCollection;
    }

    public function set_persistableInputCollection($persistableInputCollection) {
        $this->persistableInputCollection = $persistableInputCollection;
    }

    public function get_graphLinks() {
        return $this->graphLinks;
    }

    public function set_graphLinks($graphLinks) {
        $this->graphLinks = $graphLinks;
    }

    public function get_generatedSQL() {
        return $this->generatedSQL;
    }

    public function set_generatedSQL($generatedSQL) {
        $this->generatedSQL = $generatedSQL;
    }

    public function get_connection() {
        return $this->connection;
    }

    public function set_connection($connection) {
        $this->connection = $connection;
    }

        /*
    public function save()
    {

    }
     *
     */

}

?>


text:
Allowed Relay Recipients Map

When this map is enabled, only email to addresses that are keys (names) in this
map will be relayed or held for delivery to a primary mail server. The value
for each email address should be just <tt>OK</tt>.


text:
require "verbalizeit/version"
require "verbalizeit/client"
require "verbalizeit/language"
require "verbalizeit/error"
require "verbalizeit/task"
require "verbalizeit/translator"

module Verbalizeit
  # Your code goes here...
end


text:
"""Meteoclimatic component constants."""

from datetime import timedelta

from meteoclimatic import Condition

from homeassistant.components.weather import (
    ATTR_CONDITION_CLEAR_NIGHT,
    ATTR_CONDITION_CLOUDY,
    ATTR_CONDITION_EXCEPTIONAL,
    ATTR_CONDITION_FOG,
    ATTR_CONDITION_HAIL,
    ATTR_CONDITION_LIGHTNING,
    ATTR_CONDITION_LIGHTNING_RAINY,
    ATTR_CONDITION_PARTLYCLOUDY,
    ATTR_CONDITION_POURING,
    ATTR_CONDITION_RAINY,
    ATTR_CONDITION_SNOWY,
    ATTR_CONDITION_SNOWY_RAINY,
    ATTR_CONDITION_SUNNY,
    ATTR_CONDITION_WINDY,
    ATTR_CONDITION_WINDY_VARIANT,
)
from homeassistant.const import (
    DEGREE,
    DEVICE_CLASS_HUMIDITY,
    DEVICE_CLASS_PRESSURE,
    DEVICE_CLASS_TEMPERATURE,
    LENGTH_MILLIMETERS,
    PERCENTAGE,
    PRESSURE_HPA,
    SPEED_KILOMETERS_PER_HOUR,
    TEMP_CELSIUS,
)

DOMAIN = "meteoclimatic"
PLATFORMS = ["sensor", "weather"]
ATTRIBUTION = "Data provided by Meteoclimatic"
MODEL = "Meteoclimatic RSS feed"
MANUFACTURER = "Meteoclimatic"

SCAN_INTERVAL = timedelta(minutes=10)

CONF_STATION_CODE = "station_code"

DEFAULT_WEATHER_CARD = True

SENSOR_TYPE_NAME = "name"
SENSOR_TYPE_UNIT = "unit"
SENSOR_TYPE_ICON = "icon"
SENSOR_TYPE_CLASS = "device_class"
SENSOR_TYPES = {
    "temp_current": {
        SENSOR_TYPE_NAME: "Temperature",
        SENSOR_TYPE_UNIT: TEMP_CELSIUS,
        SENSOR_TYPE_CLASS: DEVICE_CLASS_TEMPERATURE,
    },
    "temp_max": {
        SENSOR_TYPE_NAME: "Daily Max Temperature",
        SENSOR_TYPE_UNIT: TEMP_CELSIUS,
        SENSOR_TYPE_CLASS: DEVICE_CLASS_TEMPERATURE,
    },
    "temp_min": {
        SENSOR_TYPE_NAME: "Daily Min Temperature",
        SENSOR_TYPE_UNIT: TEMP_CELSIUS,
        SENSOR_TYPE_CLASS: DEVICE_CLASS_TEMPERATURE,
    },
    "humidity_current": {
        SENSOR_TYPE_NAME: "Humidity",
        SENSOR_TYPE_UNIT: PERCENTAGE,
        SENSOR_TYPE_CLASS: DEVICE_CLASS_HUMIDITY,
    },
    "humidity_max": {
        SENSOR_TYPE_NAME: "Daily Max Humidity",
        SENSOR_TYPE_UNIT: PERCENTAGE,
        SENSOR_TYPE_CLASS: DEVICE_CLASS_HUMIDITY,
    },
    "humidity_min": {
        SENSOR_TYPE_NAME: "Daily Min Humidity",
        SENSOR_TYPE_UNIT: PERCENTAGE,
        SENSOR_TYPE_CLASS: DEVICE_CLASS_HUMIDITY,
    },
    "pressure_current": {
        SENSOR_TYPE_NAME: "Pressure",
        SENSOR_TYPE_UNIT: PRESSURE_HPA,
        SENSOR_TYPE_CLASS: DEVICE_CLASS_PRESSURE,
    },
    "pressure_max": {
        SENSOR_TYPE_NAME: "Daily Max Pressure",
        SENSOR_TYPE_UNIT: PRESSURE_HPA,
        SENSOR_TYPE_CLASS: DEVICE_CLASS_PRESSURE,
    },
    "pressure_min": {
        SENSOR_TYPE_NAME: "Daily Min Pressure",
        SENSOR_TYPE_UNIT: PRESSURE_HPA,
        SENSOR_TYPE_CLASS: DEVICE_CLASS_PRESSURE,
    },
    "wind_current": {
        SENSOR_TYPE_NAME: "Wind Speed",
        SENSOR_TYPE_UNIT: SPEED_KILOMETERS_PER_HOUR,
        SENSOR_TYPE_ICON: "mdi:weather-windy",
    },
    "wind_max": {
        SENSOR_TYPE_NAME: "Daily Max Wind Speed",
        SENSOR_TYPE_UNIT: SPEED_KILOMETERS_PER_HOUR,
        SENSOR_TYPE_ICON: "mdi:weather-windy",
    },
    "wind_bearing": {
        SENSOR_TYPE_NAME: "Wind Bearing",
        SENSOR_TYPE_UNIT: DEGREE,
        SENSOR_TYPE_ICON: "mdi:weather-windy",
    },
    "rain": {
        SENSOR_TYPE_NAME: "Daily Precipitation",
        SENSOR_TYPE_UNIT: LENGTH_MILLIMETERS,
        SENSOR_TYPE_ICON: "mdi:cup-water",
    },
}

CONDITION_CLASSES = {
    ATTR_CONDITION_CLEAR_NIGHT: [Condition.moon, Condition.hazemoon],
    ATTR_CONDITION_CLOUDY: [Condition.mooncloud],
    ATTR_CONDITION_EXCEPTIONAL: [],
    ATTR_CONDITION_FOG: [Condition.fog, Condition.mist],
    ATTR_CONDITION_HAIL: [],
    ATTR_CONDITION_LIGHTNING: [Condition.storm],
    ATTR_CONDITION_LIGHTNING_RAINY: [],
    ATTR_CONDITION_PARTLYCLOUDY: [Condition.suncloud, Condition.hazesun],
    ATTR_CONDITION_POURING: [],
    ATTR_CONDITION_RAINY: [Condition.rain],
    ATTR_CONDITION_SNOWY: [],
    ATTR_CONDITION_SNOWY_RAINY: [],
    ATTR_CONDITION_SUNNY: [Condition.sun],
    ATTR_CONDITION_WINDY: [],
    ATTR_CONDITION_WINDY_VARIANT: [],
}


text:
A small delta bot with a mask attached to it, hung on a wall, controlled by
a website


text:
using System;
using System.Drawing;
using System.Drawing.Drawing2D;
using System.IO;

namespace Pngp {
    public class MainClass {
        public static int Main() {
            var files = new DirectoryInfo(Directory.GetCurrentDirectory()).EnumerateFiles("*.png");

            foreach (var img in files) {
                var i = (Bitmap)(Image.FromFile(img.FullName));
                i.MakeTransparent(Color.White);
                i.Save(img.FullName);
            }

            return 0;
        }
    }
}


text:
import queue
import threading
from GlobalPlayer.player import Player

"""
  the thread module provides:
   * the global_queue for communication with any GlobalThread object
     here, dictionaries with at least an 'action' and a 'response' field
   * the GlobalThread class for reacting to user input via the Flask server
     and controlling the vlc player
   * the call_me workaround function.
     To play a video stream such as a youtube video, one has to wait for an
     event from vlc, triggering a callback function. But this callback function
     cannot call another vlc function (such as play, which would be *really*
     nice). So we just queue another request in our global_queue from the
     outside call_me function. For a workaround, it's ok.
"""
global_queue = queue.Queue()

def callme(*args):
    """ see module doc string: workaround function """
    global_queue.put({'action': 'stream'})

class GlobalThread(threading.Thread):
    """ The GlobalThread class reacts to user_input forwarded by the flask
        server to the global_queue. It processes the requests and controls
        the VLC player.
    """
    player = Player(callback=callme)

    def run(self):
        while True:
            task = global_queue.get()

            #try:
            getattr(self.player, task['action'])(task)
            #except Exception as e:
            #    print(e)
            #    self.player.get_status(task['response'])


text:
package com.navercorp.pinpoint.batch.alarm.checker;

import com.navercorp.pinpoint.batch.alarm.collector.AgentStatDataCollector;
import com.navercorp.pinpoint.web.alarm.vo.Rule;

import java.util.Map;

/**
 * @author minwoo.jung
 * @author Jongjin.Bae
 */
public class GcCountChecker extends LongValueAgentChecker {

    public GcCountChecker(AgentStatDataCollector dataCollector, Rule rule) {
        super(rule, "", dataCollector);
    }

    @Override
    protected Map<String, Long> getAgentValues() {
        return ((AgentStatDataCollector)dataCollector).getGCCount();
    }
}


text:
import { getEventTarget } from "../utils/dom";
function momentPlugin(config) {
    var moment = config.moment;
    return function (fp) {
        function captureIncrement(e) {
            var event = e;
            event.stopPropagation();
            var date = moment(fp.selectedDates[0]);
            var input = getEventTarget(event);
            var unit = Array.from(input.classList)
                .filter(function (name) { return name.startsWith("flatpickr-"); })
                .map(function (name) { return name.substring(10); })[0];
            var step = parseFloat(input.getAttribute("step"));
            date.add(step * event.delta, unit);
            fp.setDate(date.toDate());
        }
        return {
            parseDate: function (datestr, format) {
                return moment(datestr, format, true).toDate();
            },
            formatDate: function (date, format) {
                var momentDate = moment(date);
                if (typeof fp.config.locale === "string") {
                    momentDate.locale(fp.config.locale);
                }
                return momentDate.format(format);
            },
            onReady: function () {
                [fp.hourElement, fp.minuteElement, fp.secondElement].forEach(function (element) {
                    return element &&
                        element.addEventListener("increment", captureIncrement, {
                            capture: true,
                        });
                });
            },
            onDestroy: function () {
                [fp.hourElement, fp.minuteElement, fp.secondElement].forEach(function (element) {
                    return element &&
                        element.removeEventListener("increment", captureIncrement, {
                            capture: true,
                        });
                });
            },
        };
    };
}
export default momentPlugin;


text:
package de.espend.idea.php.toolbox.utils;

import com.intellij.openapi.application.ApplicationManager;
import com.intellij.openapi.components.ServiceManager;
import com.intellij.openapi.fileTypes.FileType;
import com.intellij.psi.PsiElement;
import com.intellij.util.containers.*;
import com.intellij.util.containers.HashMap;
import de.espend.idea.php.toolbox.PhpToolboxApplicationService;
import de.espend.idea.php.toolbox.dict.json.JsonRegistrar;
import de.espend.idea.php.toolbox.dict.json.JsonSignature;
import de.espend.idea.php.toolbox.dict.matcher.LanguageMatcherParameter;
import de.espend.idea.php.toolbox.extension.LanguageRegistrarMatcherInterface;
import de.espend.idea.php.toolbox.extension.PhpToolboxProviderInterface;
import org.jetbrains.annotations.NotNull;

import java.util.*;

/**
 * @author Daniel Espendiller <daniel@espendiller.net>
 */
public class RegistrarMatchUtil {

    @NotNull
    public static Map<PhpToolboxProviderInterface, Set<JsonRegistrar>> getProviders(@NotNull PsiElement psiElement) {

        Collection<JsonRegistrar> registrars = ExtensionProviderUtil.getRegistrar(psiElement.getProject(), ServiceManager.getService(PhpToolboxApplicationService.class));
        if(registrars.size() == 0) {
            return Collections.emptyMap();
        }

        FileType fileType = psiElement.getContainingFile().getFileType();
        String fileTypeName = fileType.getName();

        Collection<PhpToolboxProviderInterface> providers = null;

        Map<PhpToolboxProviderInterface, Set<JsonRegistrar>> providerMatches = new HashMap<>();

        for (JsonRegistrar registrar : registrars) {

            if(registrar == null) {
                continue;
            }

            Collection<JsonSignature> signatures = registrar.getSignatures();
            if(!fileTypeName.equalsIgnoreCase(registrar.getLanguage()) || registrar.getProvider() == null || signatures.size() == 0) {
                continue;
            }

            // init providers
            if(providers == null) {
                providers = ExtensionProviderUtil.getProviders(psiElement.getProject());
            }

            Collection<PhpToolboxProviderInterface> matchedProviders = new ArrayList<>();
            for (PhpToolboxProviderInterface provider : providers) {
                String name = provider.getName();
                if (name.equals(registrar.getProvider())) {
                    matchedProviders.add(provider);
                }
            }

            if(matchedProviders.size() == 0) {
                continue;
            }

            LanguageMatcherParameter parameter = null;

            for (LanguageRegistrarMatcherInterface matcher : ExtensionProviderUtil.REGISTRAR_MATCHER.getExtensions()) {

                if(!matcher.supports(psiElement.getContainingFile().getFileType())) {
                    continue;
                }

                if(parameter == null) {
                    parameter = new LanguageMatcherParameter(psiElement, registrar);
                }

                if(matcher.matches(parameter)) {
                    for (PhpToolboxProviderInterface matchedProvider : matchedProviders) {
                        if(providerMatches.containsKey(matchedProvider)) {
                            providerMatches.get(matchedProvider).add(registrar);
                        }
                        providerMatches.put(matchedProvider, ContainerUtil.newHashSet(registrar));
                    }

                    break;
                }

            }

        }

        return providerMatches;
    }

}


text:
package com.google.android.exoplayer2.audio;

import com.google.android.exoplayer2.C;
import com.google.android.exoplayer2.Format;
import java.nio.ByteBuffer;

/**
 * An {@link AudioProcessor} that converts different PCM audio encodings to 16-bit integer PCM. The
 * following encodings are supported as input:
 *
 * <ul>
 *   <li>{@link C#ENCODING_PCM_8BIT}
 *   <li>{@link C#ENCODING_PCM_16BIT} ({@link #isActive()} will return {@code false})
 *   <li>{@link C#ENCODING_PCM_16BIT_BIG_ENDIAN}
 *   <li>{@link C#ENCODING_PCM_24BIT}
 *   <li>{@link C#ENCODING_PCM_32BIT}
 *   <li>{@link C#ENCODING_PCM_FLOAT}
 * </ul>
 */
/* package */ final class ResamplingAudioProcessor extends BaseAudioProcessor {

  @Override
  public AudioFormat onConfigure(AudioFormat inputAudioFormat)
      throws UnhandledAudioFormatException {
    @C.PcmEncoding int encoding = inputAudioFormat.encoding;
    if (encoding != C.ENCODING_PCM_8BIT
        && encoding != C.ENCODING_PCM_16BIT
        && encoding != C.ENCODING_PCM_16BIT_BIG_ENDIAN
        && encoding != C.ENCODING_PCM_24BIT
        && encoding != C.ENCODING_PCM_32BIT
        && encoding != C.ENCODING_PCM_FLOAT) {
      throw new UnhandledAudioFormatException(inputAudioFormat);
    }
    return encoding != C.ENCODING_PCM_16BIT
        ? new AudioFormat(
            inputAudioFormat.sampleRate, inputAudioFormat.channelCount, C.ENCODING_PCM_16BIT)
        : AudioFormat.NOT_SET;
  }

  @Override
  public void queueInput(ByteBuffer inputBuffer) {
    // Prepare the output buffer.
    int position = inputBuffer.position();
    int limit = inputBuffer.limit();
    int size = limit - position;
    int resampledSize;
    switch (inputAudioFormat.encoding) {
      case C.ENCODING_PCM_8BIT:
        resampledSize = size * 2;
        break;
      case C.ENCODING_PCM_16BIT_BIG_ENDIAN:
        resampledSize = size;
        break;
      case C.ENCODING_PCM_24BIT:
        resampledSize = (size / 3) * 2;
        break;
      case C.ENCODING_PCM_32BIT:
      case C.ENCODING_PCM_FLOAT:
        resampledSize = size / 2;
        break;
      case C.ENCODING_PCM_16BIT:
      case C.ENCODING_INVALID:
      case Format.NO_VALUE:
      default:
        throw new IllegalStateException();
    }

    // Resample the little endian input and update the input/output buffers.
    ByteBuffer buffer = replaceOutputBuffer(resampledSize);
    switch (inputAudioFormat.encoding) {
      case C.ENCODING_PCM_8BIT:
        // 8 -> 16 bit resampling. Shift each byte from [0, 256) to [-128, 128) and scale up.
        for (int i = position; i < limit; i++) {
          buffer.put((byte) 0);
          buffer.put((byte) ((inputBuffer.get(i) & 0xFF) - 128));
        }
        break;
      case C.ENCODING_PCM_16BIT_BIG_ENDIAN:
        // Big endian to little endian resampling. Swap the byte order.
        for (int i = position; i < limit; i += 2) {
          buffer.put(inputBuffer.get(i + 1));
          buffer.put(inputBuffer.get(i));
        }
        break;
      case C.ENCODING_PCM_24BIT:
        // 24 -> 16 bit resampling. Drop the least significant byte.
        for (int i = position; i < limit; i += 3) {
          buffer.put(inputBuffer.get(i + 1));
          buffer.put(inputBuffer.get(i + 2));
        }
        break;
      case C.ENCODING_PCM_32BIT:
        // 32 -> 16 bit resampling. Drop the two least significant bytes.
        for (int i = position; i < limit; i += 4) {
          buffer.put(inputBuffer.get(i + 2));
          buffer.put(inputBuffer.get(i + 3));
        }
        break;
      case C.ENCODING_PCM_FLOAT:
        // 32 bit floating point -> 16 bit resampling. Floating point values are in the range
        // [-1.0, 1.0], so need to be scaled by Short.MAX_VALUE.
        for (int i = position; i < limit; i += 4) {
          short value = (short) (inputBuffer.getFloat(i) * Short.MAX_VALUE);
          buffer.put((byte) (value & 0xFF));
          buffer.put((byte) ((value >> 8) & 0xFF));
        }
        break;
      case C.ENCODING_PCM_16BIT:
      case C.ENCODING_INVALID:
      case Format.NO_VALUE:
      default:
        // Never happens.
        throw new IllegalStateException();
    }
    inputBuffer.position(inputBuffer.limit());
    buffer.flip();
  }

}


text: ssh -f edison@tesla '/home/edison/term_ros.sh'


text:
"Memcached cache backend"

from django.core.cache.backends.base import BaseCache, InvalidCacheBackendError
from django.utils.encoding import smart_unicode, smart_str

try:
    import cmemcache as memcache
except ImportError:
    try:
        import memcache
    except:
        raise InvalidCacheBackendError("Memcached cache backend requires either the 'memcache' or 'cmemcache' library")

class CacheClass(BaseCache):
    def __init__(self, server, params):
        BaseCache.__init__(self, params)
        self._cache = memcache.Client(server.split(';'))

    def add(self, key, value, timeout=0):
        if isinstance(value, unicode):
            value = value.encode('utf-8')
        return self._cache.add(smart_str(key), value, timeout or self.default_timeout)

    def get(self, key, default=None):
        val = self._cache.get(smart_str(key))
        if val is None:
            return default
        else:
            if isinstance(val, basestring):
                return smart_unicode(val)
            else:
                return val

    def set(self, key, value, timeout=0):
        if isinstance(value, unicode):
            value = value.encode('utf-8')
        self._cache.set(smart_str(key), value, timeout or self.default_timeout)

    def delete(self, key):
        self._cache.delete(smart_str(key))

    def get_many(self, keys):
        return self._cache.get_multi(map(smart_str,keys))

    def close(self, **kwargs):
        self._cache.disconnect_all()

    def incr(self, key, delta=1):
        return self._cache.incr(key, delta)

    def decr(self, key, delta=1):
        return self._cache.decr(key, delta)


text:
package webim.actions;

import java.util.List;

import org.json.JSONObject;

import webim.model.WebimEndpoint;
import webim.model.WebimMember;
import webim.model.WebimRoom;

/**
 * 读取群组成员: /Webim/members.do
 *
 * @author Ery Lee <ery.lee at gmail.com>
 * @since 1.0
 */
@SuppressWarnings("serial")
public class MembersAction extends WebimAction {

	private String id;

	private List<WebimMember> members;

	public String getId() {
		return id;
	}

	public void setId(String id) {
		this.id = id;
	}

	public List<WebimMember> getMembers() {
		return members;
	}

	public void setMembers(List<WebimMember> members) {
		this.members = members;
	}

	public String execute() throws Exception {
		WebimEndpoint endpoint = currentEndpoint();
		String roomId = getId();
		WebimRoom room = this.plugin.findRoom(roomId);
		if (room != null) {
			members = this.plugin.members(roomId);
		} else {
			room = this.model.findRoom(roomId);
			if (room != null) {
				members = this.model.members(roomId);
			}
		}
		if (room == null)
			return null;
		JSONObject presences = client(endpoint).members(roomId);
		for (WebimMember member : members) {
			String mid = member.getId();
			if (presences.has(mid)) {
				String show = presences.getString(mid);
				if (!"invisible".equals(show)) {
					member.setPresence("online");
					member.setShow(presences.getString(mid));
				}
			}
		}
		return SUCCESS;
	}

}


text:
<?php

define('PUN_ROOT', dirname(__FILE__).'/');
require PUN_ROOT.'include/common.php';

if ($pun_user['g_read_board'] == '0')
	message($lang_common['No view']);

$id = isset($_GET['id']) ? intval($_GET['id']) : 0;
if ($id < 1)
	message($lang_common['Bad request']);

// Fetch some info about the post, the topic and the forum
$result = $db->query('SELECT f.id AS fid, f.forum_name, f.moderators, f.redirect_url, fp.post_replies, fp.post_topics, t.id AS tid, t.subject, t.first_post_id, t.closed, p.posted, p.poster, p.poster_id, p.message, p.hide_smilies FROM '.$db->prefix.'posts AS p INNER JOIN '.$db->prefix.'topics AS t ON t.id=p.topic_id INNER JOIN '.$db->prefix.'forums AS f ON f.id=t.forum_id LEFT JOIN '.$db->prefix.'forum_perms AS fp ON (fp.forum_id=f.id AND fp.group_id='.$pun_user['g_id'].') WHERE (fp.read_forum IS NULL OR fp.read_forum=1) AND p.id='.$id) or error('Unable to fetch post info', __FILE__, __LINE__, $db->error());
if (!$db->num_rows($result))
	message($lang_common['Bad request']);

$cur_post = $db->fetch_assoc($result);

if ($pun_config['o_censoring'] == '1')
	$cur_post['subject'] = censor_words($cur_post['subject']);

// Sort out who the moderators are and if we are currently a moderator (or an admin)
$mods_array = ($cur_post['moderators'] != '') ? unserialize($cur_post['moderators']) : array();
$is_admmod = ($pun_user['g_id'] == PUN_ADMIN || ($pun_user['g_moderator'] == '1' && array_key_exists($pun_user['username'], $mods_array))) ? true : false;

$is_topic_post = ($id == $cur_post['first_post_id']) ? true : false;

// Do we have permission to edit this post?
if (($pun_user['g_delete_posts'] == '0' ||
	($pun_user['g_delete_topics'] == '0' && $is_topic_post) ||
	$cur_post['poster_id'] != $pun_user['id'] ||
	$cur_post['closed'] == '1') &&
	!$is_admmod)
	message($lang_common['No permission']);

// Load the delete.php language file
require PUN_ROOT.'lang/'.$pun_user['language'].'/delete.php';

if (isset($_POST['delete']))
{
	if ($is_admmod)
		confirm_referrer('delete.php');

	require PUN_ROOT.'include/search_idx.php';

	if ($is_topic_post)
	{
		// Delete the topic and all of it's posts
		delete_topic($cur_post['tid']);
		update_forum($cur_post['fid']);

		redirect('viewforum.php?id='.$cur_post['fid'], $lang_delete['Topic del redirect']);
	}
	else
	{
		// Delete just this one post
		delete_post($id, $cur_post['tid']);
		update_forum($cur_post['fid']);

		// Redirect towards the previous post
		$result = $db->query('SELECT id FROM '.$db->prefix.'posts WHERE topic_id='.$cur_post['tid'].' AND id < '.$id.' ORDER BY id DESC LIMIT 1') or error('Unable to fetch post info', __FILE__, __LINE__, $db->error());
		$post_id = $db->result($result);

		redirect('viewtopic.php?pid='.$post_id.'#p'.$post_id, $lang_delete['Post del redirect']);
	}
}

$page_title = array(pun_htmlspecialchars($pun_config['o_board_title']), $lang_delete['Delete post']);
define ('PUN_ACTIVE_PAGE', 'index');
require PUN_ROOT.'header.php';

require PUN_ROOT.'include/parser.php';
$cur_post['message'] = parse_message($cur_post['message'], $cur_post['hide_smilies']);

?>

<?php echo $lang_common['Index'] ?>

» <a href="viewforum.php?id=<?php echo $cur_post['fid'] ?>"><?php echo pun_htmlspecialchars($cur_post['forum_name']) ?>

» <a href="viewtopic.php?pid=<?php echo $id ?>#p<?php echo $id ?>"><?php echo pun_htmlspecialchars($cur_post['subject']) ?>

» <?php echo $lang_delete['Delete post'] ?>

<?php echo $lang_delete['Delete post'] ?>

		<form method="post" action="delete.php?id=<?php echo $id ?>">

<?php printf($is_topic_post ? $lang_delete['Topic by'] : $lang_delete['Reply by'], ''.pun_htmlspecialchars($cur_post['poster']).'', format_time($cur_post['posted'])) ?>

<?php echo ($is_topic_post) ? ''.$lang_delete['Topic warning'].'' : ''.$lang_delete['Warning'].'' ?>
<?php echo $lang_delete['Delete info'] ?>

<input type="submit" name="delete" value="<?php echo $lang_delete['Delete'] ?>" /> <?php echo $lang_common['Go back'] ?>

		</form>

<?php echo pun_htmlspecialchars($cur_post['poster']) ?>

<?php echo format_time($cur_post['posted']) ?>

							<?php echo $cur_post['message']."\n" ?>

<?php

require PUN_ROOT.'footer.php';