text
stringlengths 54
60.6k
|
|---|
<commit_before>// Copyright 2017 Google Inc.
//
// Licensed under the Apache License, Version 2.0 (the "License");
// you may not use this file except in compliance with the License.
// You may obtain a copy of the License at
//
// http://www.apache.org/licenses/LICENSE-2.0
//
// Unless required by applicable law or agreed to in writing, software
// distributed under the License is distributed on an "AS IS" BASIS,
// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
// See the License for the specific language governing permissions and
// limitations under the License.
#include "google/cloud/bigtable/table_admin.h"
#include "google/cloud/bigtable/grpc_error.h"
#include "google/cloud/bigtable/internal/async_future_from_callback.h"
#include "google/cloud/bigtable/internal/grpc_error_delegate.h"
#include "google/cloud/bigtable/internal/poll_longrunning_operation.h"
#include "google/cloud/bigtable/internal/unary_client_utils.h"
#include <google/protobuf/duration.pb.h>
#include <sstream>
namespace btadmin = ::google::bigtable::admin::v2;
namespace google {
namespace cloud {
namespace bigtable {
inline namespace BIGTABLE_CLIENT_NS {
static_assert(std::is_copy_constructible<bigtable::TableAdmin>::value,
"bigtable::TableAdmin must be constructible");
static_assert(std::is_copy_assignable<bigtable::TableAdmin>::value,
"bigtable::TableAdmin must be assignable");
StatusOr<btadmin::Table> TableAdmin::CreateTable(std::string table_id,
TableConfig config) {
grpc::Status status;
auto result =
impl_.CreateTable(std::move(table_id), std::move(config), status);
if (!status.ok()) {
return internal::MakeStatusFromRpcError(status);
}
return result;
}
future<StatusOr<google::bigtable::admin::v2::Table>>
TableAdmin::AsyncCreateTable(CompletionQueue& cq, std::string table_id,
TableConfig config) {
promise<StatusOr<google::bigtable::admin::v2::Table>> p;
auto result = p.get_future();
impl_.AsyncCreateTable(
cq,
internal::MakeAsyncFutureFromCallback(std::move(p), "AsyncCreateTable"),
std::move(table_id), std::move(config));
return result;
}
future<StatusOr<google::bigtable::admin::v2::Table>> TableAdmin::AsyncGetTable(
CompletionQueue& cq, std::string const& table_id,
btadmin::Table::View view) {
promise<StatusOr<google::bigtable::admin::v2::Table>> p;
auto result = p.get_future();
impl_.AsyncGetTable(
cq, internal::MakeAsyncFutureFromCallback(std::move(p), "AsyncGetTable"),
table_id, view);
return result;
}
StatusOr<std::vector<btadmin::Table>> TableAdmin::ListTables(
btadmin::Table::View view) {
grpc::Status status;
auto result = impl_.ListTables(view, status);
if (!status.ok()) {
return internal::MakeStatusFromRpcError(status);
}
return result;
}
StatusOr<btadmin::Table> TableAdmin::GetTable(std::string const& table_id,
btadmin::Table::View view) {
grpc::Status status;
auto result = impl_.GetTable(table_id, status, view);
if (!status.ok()) {
return internal::MakeStatusFromRpcError(status);
}
return result;
}
Status TableAdmin::DeleteTable(std::string const& table_id) {
grpc::Status status;
impl_.DeleteTable(table_id, status);
return internal::MakeStatusFromRpcError(status);
}
StatusOr<btadmin::Table> TableAdmin::ModifyColumnFamilies(
std::string const& table_id,
std::vector<ColumnFamilyModification> modifications) {
grpc::Status status;
auto result =
impl_.ModifyColumnFamilies(table_id, std::move(modifications), status);
if (!status.ok()) {
return internal::MakeStatusFromRpcError(status);
}
return result;
}
Status TableAdmin::DropRowsByPrefix(std::string const& table_id,
std::string row_key_prefix) {
grpc::Status status;
impl_.DropRowsByPrefix(table_id, std::move(row_key_prefix), status);
return internal::MakeStatusFromRpcError(status);
}
Status TableAdmin::DropAllRows(std::string const& table_id) {
grpc::Status status;
impl_.DropAllRows(table_id, status);
return internal::MakeStatusFromRpcError(status);
}
std::future<StatusOr<btadmin::Snapshot>> TableAdmin::SnapshotTable(
bigtable::ClusterId const& cluster_id,
bigtable::SnapshotId const& snapshot_id, bigtable::TableId const& table_id,
std::chrono::seconds duration_ttl) {
return std::async(std::launch::async, &TableAdmin::SnapshotTableImpl, this,
cluster_id, snapshot_id, table_id, duration_ttl);
}
StatusOr<btadmin::Snapshot> TableAdmin::SnapshotTableImpl(
bigtable::ClusterId const& cluster_id,
bigtable::SnapshotId const& snapshot_id, bigtable::TableId const& table_id,
std::chrono::seconds duration_ttl) {
using ClientUtils = bigtable::internal::noex::UnaryClientUtils<AdminClient>;
btadmin::SnapshotTableRequest request;
request.set_name(impl_.TableName(table_id.get()));
request.set_cluster(impl_.ClusterName(cluster_id));
request.set_snapshot_id(snapshot_id.get());
request.mutable_ttl()->set_seconds(duration_ttl.count());
MetadataUpdatePolicy metadata_update_policy(
instance_name(), MetadataParamTypes::NAME, cluster_id, snapshot_id);
grpc::Status status;
auto operation = ClientUtils::MakeCall(
*(impl_.client_), impl_.rpc_retry_policy_->clone(),
impl_.rpc_backoff_policy_->clone(), metadata_update_policy,
&AdminClient::SnapshotTable, request, "SnapshotTable", status, true);
if (!status.ok()) {
return bigtable::internal::MakeStatusFromRpcError(status);
}
auto result =
internal::PollLongRunningOperation<btadmin::Snapshot, AdminClient>(
impl_.client_, impl_.polling_policy_->clone(),
impl_.metadata_update_policy_, operation, "TableAdmin::SnapshotTable",
status);
if (!status.ok()) {
return bigtable::internal::MakeStatusFromRpcError(status);
}
return result;
}
StatusOr<btadmin::Snapshot> TableAdmin::GetSnapshot(
bigtable::ClusterId const& cluster_id,
bigtable::SnapshotId const& snapshot_id) {
grpc::Status status;
auto result = impl_.GetSnapshot(cluster_id, snapshot_id, status);
if (!status.ok()) {
return internal::MakeStatusFromRpcError(status);
}
return result;
}
StatusOr<ConsistencyToken> TableAdmin::GenerateConsistencyToken(
std::string const& table_id) {
grpc::Status status;
std::string token = impl_.GenerateConsistencyToken(table_id, status);
if (!status.ok()) {
return internal::MakeStatusFromRpcError(status);
}
return ConsistencyToken(token);
}
StatusOr<Consistency> TableAdmin::CheckConsistency(
bigtable::TableId const& table_id,
bigtable::ConsistencyToken const& consistency_token) {
grpc::Status status;
bool consistent = impl_.CheckConsistency(table_id, consistency_token, status);
if (!status.ok()) {
return internal::MakeStatusFromRpcError(status);
}
return consistent ? Consistency::kConsistent : Consistency::kInconsistent;
}
StatusOr<bool> TableAdmin::WaitForConsistencyCheckImpl(
bigtable::TableId const& table_id,
bigtable::ConsistencyToken const& consistency_token) {
grpc::Status status;
bool consistent =
impl_.WaitForConsistencyCheckHelper(table_id, consistency_token, status);
if (!status.ok()) {
return bigtable::internal::MakeStatusFromRpcError(status);
}
return consistent;
}
Status TableAdmin::DeleteSnapshot(bigtable::ClusterId const& cluster_id,
bigtable::SnapshotId const& snapshot_id) {
grpc::Status status;
impl_.DeleteSnapshot(cluster_id, snapshot_id, status);
return internal::MakeStatusFromRpcError(status);
}
std::future<StatusOr<btadmin::Table>> TableAdmin::CreateTableFromSnapshot(
bigtable::ClusterId const& cluster_id,
bigtable::SnapshotId const& snapshot_id, std::string table_id) {
return std::async(std::launch::async,
&TableAdmin::CreateTableFromSnapshotImpl, this, cluster_id,
snapshot_id, table_id);
}
StatusOr<btadmin::Table> TableAdmin::CreateTableFromSnapshotImpl(
bigtable::ClusterId const& cluster_id,
bigtable::SnapshotId const& snapshot_id, std::string table_id) {
// Copy the policies in effect for the operation.
auto rpc_policy = impl_.rpc_retry_policy_->clone();
auto backoff_policy = impl_.rpc_backoff_policy_->clone();
// Build the RPC request, try to minimize copying.
btadmin::Table result;
btadmin::CreateTableFromSnapshotRequest request;
request.set_parent(instance_name());
request.set_source_snapshot(impl_.SnapshotName(cluster_id, snapshot_id));
request.set_table_id(std::move(table_id));
grpc::Status status;
using ClientUtils = bigtable::internal::noex::UnaryClientUtils<AdminClient>;
auto operation = ClientUtils::MakeCall(
*impl_.client_, *rpc_policy, *backoff_policy,
impl_.metadata_update_policy_, &AdminClient::CreateTableFromSnapshot,
request, "TableAdmin", status, true);
if (!status.ok()) {
return bigtable::internal::MakeStatusFromRpcError(status);
}
result = internal::PollLongRunningOperation<btadmin::Table, AdminClient>(
impl_.client_, impl_.polling_policy_->clone(),
impl_.metadata_update_policy_, operation,
"TableAdmin::CreateTableFromSnapshot", status);
if (!status.ok()) {
return bigtable::internal::MakeStatusFromRpcError(status);
}
return result;
}
StatusOr<std::vector<::google::bigtable::admin::v2::Snapshot>>
TableAdmin::ListSnapshots(bigtable::ClusterId const& cluster_id) {
grpc::Status status;
auto res = impl_.ListSnapshots(status, cluster_id);
if (!status.ok()) {
return internal::MakeStatusFromRpcError(status);
}
return res;
}
} // namespace BIGTABLE_CLIENT_NS
} // namespace bigtable
} // namespace cloud
} // namespace google
<commit_msg>Moving noex::TableAdmin::CreateTable to TableAdmin::CreateTable (#2191)<commit_after>// Copyright 2017 Google Inc.
//
// Licensed under the Apache License, Version 2.0 (the "License");
// you may not use this file except in compliance with the License.
// You may obtain a copy of the License at
//
// http://www.apache.org/licenses/LICENSE-2.0
//
// Unless required by applicable law or agreed to in writing, software
// distributed under the License is distributed on an "AS IS" BASIS,
// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
// See the License for the specific language governing permissions and
// limitations under the License.
#include "google/cloud/bigtable/table_admin.h"
#include "google/cloud/bigtable/grpc_error.h"
#include "google/cloud/bigtable/internal/async_future_from_callback.h"
#include "google/cloud/bigtable/internal/grpc_error_delegate.h"
#include "google/cloud/bigtable/internal/poll_longrunning_operation.h"
#include "google/cloud/bigtable/internal/unary_client_utils.h"
#include <google/protobuf/duration.pb.h>
#include <sstream>
namespace btadmin = ::google::bigtable::admin::v2;
namespace google {
namespace cloud {
namespace bigtable {
inline namespace BIGTABLE_CLIENT_NS {
static_assert(std::is_copy_constructible<bigtable::TableAdmin>::value,
"bigtable::TableAdmin must be constructible");
static_assert(std::is_copy_assignable<bigtable::TableAdmin>::value,
"bigtable::TableAdmin must be assignable");
/// Shortcuts to avoid typing long names over and over.
using ClientUtils = bigtable::internal::noex::UnaryClientUtils<AdminClient>;
StatusOr<btadmin::Table> TableAdmin::CreateTable(std::string table_id,
TableConfig config) {
grpc::Status status;
auto request = std::move(config).as_proto();
request.set_parent(instance_name());
request.set_table_id(std::move(table_id));
// This is a non-idempotent API, use the correct retry loop for this type of
// operation.
auto result = ClientUtils::MakeNonIdemponentCall(
*(impl_.client_), impl_.rpc_retry_policy_->clone(),
impl_.metadata_update_policy_, &AdminClient::CreateTable, request,
"CreateTable", status);
if (!status.ok()) {
return internal::MakeStatusFromRpcError(status);
}
return result;
}
future<StatusOr<google::bigtable::admin::v2::Table>>
TableAdmin::AsyncCreateTable(CompletionQueue& cq, std::string table_id,
TableConfig config) {
promise<StatusOr<google::bigtable::admin::v2::Table>> p;
auto result = p.get_future();
impl_.AsyncCreateTable(
cq,
internal::MakeAsyncFutureFromCallback(std::move(p), "AsyncCreateTable"),
std::move(table_id), std::move(config));
return result;
}
future<StatusOr<google::bigtable::admin::v2::Table>> TableAdmin::AsyncGetTable(
CompletionQueue& cq, std::string const& table_id,
btadmin::Table::View view) {
promise<StatusOr<google::bigtable::admin::v2::Table>> p;
auto result = p.get_future();
impl_.AsyncGetTable(
cq, internal::MakeAsyncFutureFromCallback(std::move(p), "AsyncGetTable"),
table_id, view);
return result;
}
StatusOr<std::vector<btadmin::Table>> TableAdmin::ListTables(
btadmin::Table::View view) {
grpc::Status status;
auto result = impl_.ListTables(view, status);
if (!status.ok()) {
return internal::MakeStatusFromRpcError(status);
}
return result;
}
StatusOr<btadmin::Table> TableAdmin::GetTable(std::string const& table_id,
btadmin::Table::View view) {
grpc::Status status;
auto result = impl_.GetTable(table_id, status, view);
if (!status.ok()) {
return internal::MakeStatusFromRpcError(status);
}
return result;
}
Status TableAdmin::DeleteTable(std::string const& table_id) {
grpc::Status status;
impl_.DeleteTable(table_id, status);
return internal::MakeStatusFromRpcError(status);
}
StatusOr<btadmin::Table> TableAdmin::ModifyColumnFamilies(
std::string const& table_id,
std::vector<ColumnFamilyModification> modifications) {
grpc::Status status;
auto result =
impl_.ModifyColumnFamilies(table_id, std::move(modifications), status);
if (!status.ok()) {
return internal::MakeStatusFromRpcError(status);
}
return result;
}
Status TableAdmin::DropRowsByPrefix(std::string const& table_id,
std::string row_key_prefix) {
grpc::Status status;
impl_.DropRowsByPrefix(table_id, std::move(row_key_prefix), status);
return internal::MakeStatusFromRpcError(status);
}
Status TableAdmin::DropAllRows(std::string const& table_id) {
grpc::Status status;
impl_.DropAllRows(table_id, status);
return internal::MakeStatusFromRpcError(status);
}
std::future<StatusOr<btadmin::Snapshot>> TableAdmin::SnapshotTable(
bigtable::ClusterId const& cluster_id,
bigtable::SnapshotId const& snapshot_id, bigtable::TableId const& table_id,
std::chrono::seconds duration_ttl) {
return std::async(std::launch::async, &TableAdmin::SnapshotTableImpl, this,
cluster_id, snapshot_id, table_id, duration_ttl);
}
StatusOr<btadmin::Snapshot> TableAdmin::SnapshotTableImpl(
bigtable::ClusterId const& cluster_id,
bigtable::SnapshotId const& snapshot_id, bigtable::TableId const& table_id,
std::chrono::seconds duration_ttl) {
using ClientUtils = bigtable::internal::noex::UnaryClientUtils<AdminClient>;
btadmin::SnapshotTableRequest request;
request.set_name(impl_.TableName(table_id.get()));
request.set_cluster(impl_.ClusterName(cluster_id));
request.set_snapshot_id(snapshot_id.get());
request.mutable_ttl()->set_seconds(duration_ttl.count());
MetadataUpdatePolicy metadata_update_policy(
instance_name(), MetadataParamTypes::NAME, cluster_id, snapshot_id);
grpc::Status status;
auto operation = ClientUtils::MakeCall(
*(impl_.client_), impl_.rpc_retry_policy_->clone(),
impl_.rpc_backoff_policy_->clone(), metadata_update_policy,
&AdminClient::SnapshotTable, request, "SnapshotTable", status, true);
if (!status.ok()) {
return bigtable::internal::MakeStatusFromRpcError(status);
}
auto result =
internal::PollLongRunningOperation<btadmin::Snapshot, AdminClient>(
impl_.client_, impl_.polling_policy_->clone(),
impl_.metadata_update_policy_, operation, "TableAdmin::SnapshotTable",
status);
if (!status.ok()) {
return bigtable::internal::MakeStatusFromRpcError(status);
}
return result;
}
StatusOr<btadmin::Snapshot> TableAdmin::GetSnapshot(
bigtable::ClusterId const& cluster_id,
bigtable::SnapshotId const& snapshot_id) {
grpc::Status status;
auto result = impl_.GetSnapshot(cluster_id, snapshot_id, status);
if (!status.ok()) {
return internal::MakeStatusFromRpcError(status);
}
return result;
}
StatusOr<ConsistencyToken> TableAdmin::GenerateConsistencyToken(
std::string const& table_id) {
grpc::Status status;
std::string token = impl_.GenerateConsistencyToken(table_id, status);
if (!status.ok()) {
return internal::MakeStatusFromRpcError(status);
}
return ConsistencyToken(token);
}
StatusOr<Consistency> TableAdmin::CheckConsistency(
bigtable::TableId const& table_id,
bigtable::ConsistencyToken const& consistency_token) {
grpc::Status status;
bool consistent = impl_.CheckConsistency(table_id, consistency_token, status);
if (!status.ok()) {
return internal::MakeStatusFromRpcError(status);
}
return consistent ? Consistency::kConsistent : Consistency::kInconsistent;
}
StatusOr<bool> TableAdmin::WaitForConsistencyCheckImpl(
bigtable::TableId const& table_id,
bigtable::ConsistencyToken const& consistency_token) {
grpc::Status status;
bool consistent =
impl_.WaitForConsistencyCheckHelper(table_id, consistency_token, status);
if (!status.ok()) {
return bigtable::internal::MakeStatusFromRpcError(status);
}
return consistent;
}
Status TableAdmin::DeleteSnapshot(bigtable::ClusterId const& cluster_id,
bigtable::SnapshotId const& snapshot_id) {
grpc::Status status;
impl_.DeleteSnapshot(cluster_id, snapshot_id, status);
return internal::MakeStatusFromRpcError(status);
}
std::future<StatusOr<btadmin::Table>> TableAdmin::CreateTableFromSnapshot(
bigtable::ClusterId const& cluster_id,
bigtable::SnapshotId const& snapshot_id, std::string table_id) {
return std::async(std::launch::async,
&TableAdmin::CreateTableFromSnapshotImpl, this, cluster_id,
snapshot_id, table_id);
}
StatusOr<btadmin::Table> TableAdmin::CreateTableFromSnapshotImpl(
bigtable::ClusterId const& cluster_id,
bigtable::SnapshotId const& snapshot_id, std::string table_id) {
// Copy the policies in effect for the operation.
auto rpc_policy = impl_.rpc_retry_policy_->clone();
auto backoff_policy = impl_.rpc_backoff_policy_->clone();
// Build the RPC request, try to minimize copying.
btadmin::Table result;
btadmin::CreateTableFromSnapshotRequest request;
request.set_parent(instance_name());
request.set_source_snapshot(impl_.SnapshotName(cluster_id, snapshot_id));
request.set_table_id(std::move(table_id));
grpc::Status status;
using ClientUtils = bigtable::internal::noex::UnaryClientUtils<AdminClient>;
auto operation = ClientUtils::MakeCall(
*impl_.client_, *rpc_policy, *backoff_policy,
impl_.metadata_update_policy_, &AdminClient::CreateTableFromSnapshot,
request, "TableAdmin", status, true);
if (!status.ok()) {
return bigtable::internal::MakeStatusFromRpcError(status);
}
result = internal::PollLongRunningOperation<btadmin::Table, AdminClient>(
impl_.client_, impl_.polling_policy_->clone(),
impl_.metadata_update_policy_, operation,
"TableAdmin::CreateTableFromSnapshot", status);
if (!status.ok()) {
return bigtable::internal::MakeStatusFromRpcError(status);
}
return result;
}
StatusOr<std::vector<::google::bigtable::admin::v2::Snapshot>>
TableAdmin::ListSnapshots(bigtable::ClusterId const& cluster_id) {
grpc::Status status;
auto res = impl_.ListSnapshots(status, cluster_id);
if (!status.ok()) {
return internal::MakeStatusFromRpcError(status);
}
return res;
}
} // namespace BIGTABLE_CLIENT_NS
} // namespace bigtable
} // namespace cloud
} // namespace google
<|endoftext|>
|
<commit_before>/*
* Copyright 2021 The TensorFlow Runtime Authors
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
//===- cpurt.cc - ---------------------------------------------------------===//
//
// Support library for implementing TFRT kernels that do JIT compilation using
// MLIR framework.
//
//===----------------------------------------------------------------------===//
#include "tfrt/cpu/jit/cpurt.h"
#include "llvm/ExecutionEngine/Orc/Core.h"
#include "llvm/ExecutionEngine/Orc/Mangling.h"
#include "llvm/Support/MemoryBuffer.h"
#include "llvm/Support/TargetSelect.h"
#include "mlir/Conversion/AsyncToLLVM/AsyncToLLVM.h"
#include "mlir/Conversion/SCFToStandard/SCFToStandard.h"
#include "mlir/Conversion/StandardToLLVM/ConvertStandardToLLVMPass.h"
#include "mlir/Dialect/Affine/IR/AffineOps.h"
#include "mlir/Dialect/Async/IR/Async.h"
#include "mlir/Dialect/Async/Passes.h"
#include "mlir/Dialect/LLVMIR/LLVMDialect.h"
#include "mlir/Dialect/Linalg/IR/LinalgOps.h"
#include "mlir/Dialect/Linalg/IR/LinalgTypes.h"
#include "mlir/Dialect/Linalg/Passes.h"
#include "mlir/Dialect/SCF/SCF.h"
#include "mlir/Dialect/StandardOps/IR/Ops.h"
#include "mlir/Dialect/StandardOps/Transforms/Passes.h"
#include "mlir/ExecutionEngine/ExecutionEngine.h"
#include "mlir/ExecutionEngine/OptUtils.h"
#include "mlir/IR/BuiltinOps.h"
#include "mlir/IR/MLIRContext.h"
#include "mlir/Parser.h"
#include "mlir/Pass/Pass.h"
#include "mlir/Pass/PassManager.h"
#include "mlir/Support/LogicalResult.h"
#include "mlir/Transforms/Passes.h"
#include "tfrt/cpu/jit/async_runtime.h"
#include "tfrt/cpu/jit/async_runtime_api.h"
#include "tfrt/support/error_util.h"
#include "tfrt/tensor/dense_host_tensor.h"
#include "tfrt/tensor/tensor.h"
namespace tfrt {
namespace cpu {
namespace jit {
// Enable IR pringing during the kernel compilation pipeline execution.
static bool DebugCpurtCompile() {
#if defined(DEBUG_CPURT)
return true;
#else
return false;
#endif
}
using MemrefArg = CompilationResult::MemrefArg;
using CallFrame = CompilationResult::CallFrame;
//----------------------------------------------------------------------------//
// CompilationResult implementation.
//----------------------------------------------------------------------------//
// Converts Tensor to Memref argument for supported tensor types. Returns
// error othwrwise.
static Expected<MemrefArg> ConvertTensorToMemrefArg(const Tensor& tensor) {
if (auto* dht = dyn_cast<DenseHostTensor>(&tensor)) {
MemrefArg memref;
memref.data = const_cast<void*>(dht->data());
memref.offset = 0;
dht->shape().GetDimensions(&memref.sizes);
dht->shape().GetStrides(&memref.strides);
return memref;
}
return MakeStringError("unsupported tensor type: ", tensor.tensor_type());
}
// Unpack `memref` argument into pointers to the data to be compatible with
// compiled MLIR function ABI.
static void AddMemrefArgument(const MemrefArg& memref,
llvm::SmallVectorImpl<void*>* args) {
assert(memref.sizes.size() == memref.strides.size());
auto add_arg = [&](const void* p) { args->push_back(const_cast<void*>(p)); };
add_arg(&memref.data); // memref.basePtr
add_arg(&memref.data); // memref.data
add_arg(&memref.offset);
size_t rank = memref.sizes.size();
for (int i = 0; i < rank; ++i) add_arg(&memref.sizes[i]);
for (int i = 0; i < rank; ++i) add_arg(&memref.strides[i]);
}
// Initializes call frame by adding all arguments to it to ensure that all the
// arguments are alive when we call compiled kernel.
//
// Returns compiled function arguments as `void*` type erased pointers. These
// pointers are pointing to the arguments that are stored in the CallFrame
// instance. See mlir::ExecutionEngine `packFunctionArguments` for the details.
static Expected<llvm::SmallVector<void*, 32>> InitializeCallFrame(
RepeatedArguments<Tensor> operands, CallFrame* call_frame) {
llvm::SmallVector<void*, 32> args;
// Pack all Tensor operands as memref arguments.
for (Tensor& tensor : operands) {
Expected<MemrefArg> memref = ConvertTensorToMemrefArg(tensor);
if (auto err = memref.takeError()) return std::move(err);
call_frame->memrefs.push_back(*memref);
AddMemrefArgument(call_frame->memrefs.back(), &args);
}
// Address to write the returned async.token value.
args.push_back(&call_frame->return_value);
return args;
}
AsyncValueRef<Chain> CompilationResult::Execute(
RepeatedArguments<Tensor> operands,
const ExecutionContext& exec_ctx) const {
// CallFrame can be allocated on the stack because compiled function will
// unpack all the arguments it needs, and async regions will not access
// the data after the initial function will return the result.
CallFrame call_frame;
// Compiled function takes arguments as `void**` type erased pointer. See
// mlir::ExecutionEngine `packFunctionArguments` for the details.
auto args = InitializeCallFrame(operands, &call_frame);
if (auto err = args.takeError())
return EmitErrorAsync(exec_ctx, std::move(err));
// Set the AsyncRuntime context to be used by all async tasks.
ResourceContext* res_ctx = exec_ctx.resource_context();
AsyncRuntime* runtime = res_ctx->GetOrCreateResource<AsyncRuntime>(
"cpurt.runtime", exec_ctx.host());
SetAsyncRuntimeContext(runtime);
// Call the compiled function.
(*fptr_)(args->data());
return ConverAsyncTokenToChain(
static_cast<mlir::runtime::AsyncToken*>(call_frame.return_value));
}
//----------------------------------------------------------------------------//
// CompilationResultCache implementation.
//----------------------------------------------------------------------------//
AsyncValueRef<CompilationResult> CompilationResultCache::Find(
intptr_t key) const {
tfrt::mutex_lock lock(mu_);
auto it = cache_.find(key);
if (it != cache_.end()) return it->second.CopyRef();
return AsyncValueRef<CompilationResult>();
}
AsyncValueRef<CompilationResult> CompilationResultCache::Insert(
intptr_t key, CompilationResult compilation_result) {
tfrt::mutex_lock lock(mu_);
auto it = cache_.find(key);
if (it != cache_.end()) return it->second.CopyRef();
auto emplaced =
cache_.try_emplace(key, MakeAvailableAsyncValueRef<CompilationResult>(
host_, std::move(compilation_result)));
return emplaced.first->getSecond().CopyRef();
}
//----------------------------------------------------------------------------//
// Setup MLIR pass pipeline to lower to LLVM dialect, and use ORC JIT to codegen
// functions at runtime.
//----------------------------------------------------------------------------//
static void InitializeCompiler() {
static const bool initialized = ([] {
llvm::InitializeNativeTarget();
llvm::InitializeNativeTargetAsmPrinter();
return true;
})();
(void)initialized;
}
// Runs the pipeline to lower kernel IR to LLVM dialect.
static mlir::LogicalResult LowerToLlvm(mlir::MLIRContext* context,
mlir::ModuleOp module,
const CompilationOptions& opts) {
mlir::PassManager pm(context);
pm.addPass(mlir::createInlinerPass());
pm.addPass(mlir::createCanonicalizerPass());
pm.addPass(mlir::createCSEPass());
// TODO(ezhulenev): Move this to a pipeline exposed upstream when it will
// stabilize, e.g. `LinalgToAsyncRuntime`.
// Convert all linalg operations to parallel loops, and then add async
// operations to actually execute them in parallel using the async runtime.
mlir::OpPassManager& fpm = pm.nest<mlir::FuncOp>();
fpm.addPass(mlir::createConvertLinalgToParallelLoopsPass());
fpm.addPass(mlir::createAsyncParallelForPass(opts.num_worker_threads));
fpm.addPass(mlir::createAsyncRefCountingPass());
fpm.addPass(mlir::createAsyncRefCountingOptimizationPass());
fpm.addPass(mlir::createStdExpandOpsPass());
// Lower from hight level async operations to async runtime.
pm.addPass(mlir::createAsyncToAsyncRuntimePass());
// Lower everything down to LLVM dialect.
mlir::LowerToLLVMOptions lower_to_llvm_opts;
pm.addPass(mlir::createConvertAsyncToLLVMPass());
pm.addPass(mlir::createLowerToCFGPass());
pm.addPass(mlir::createLowerToLLVMPass(lower_to_llvm_opts));
// Print IR after all passes.
if (DebugCpurtCompile()) {
context->disableMultithreading();
pm.enableIRPrinting([](mlir::Pass*, mlir::Operation*) { return false; },
[](mlir::Pass*, mlir::Operation*) { return true; },
/*printModuleScope=*/true,
/*printAfterOnlyOnChange=*/false, llvm::errs());
}
return pm.run(module);
}
Expected<CompilationResult> CompileKernelMlirModule(
string_view mlir_module, string_view entrypoint,
const CompilationOptions& opts) {
// Setup LLVM target for code generation.
InitializeCompiler();
llvm::SourceMgr source_mgr;
source_mgr.AddNewSourceBuffer(
llvm::MemoryBuffer::getMemBuffer(mlir_module, "<unknown>"),
llvm::SMLoc());
// Register MLIR dialects supported by the compiled kernels.
mlir::MLIRContext context;
context.getDialectRegistry()
.insert<mlir::async::AsyncDialect, mlir::linalg::LinalgDialect,
mlir::scf::SCFDialect, mlir::StandardOpsDialect,
mlir::LLVM::LLVMDialect>();
// Parse a kernel source code into the MLIR Module.
mlir::OwningModuleRef module(mlir::parseSourceFile(source_mgr, &context));
if (!module) return MakeStringError("failed to parse kernel source");
// Lower kernel IR from high level dialects to the MLIR LLVM Dialect.
if (failed(LowerToLlvm(&context, *module, opts)))
return MakeStringError("Failed to lower module to LLVM");
// Prepare JIT target machine for code generation.
auto builder = llvm::orc::JITTargetMachineBuilder::detectHost();
if (!builder) return builder.takeError();
auto target_machine = builder->createTargetMachine();
if (!target_machine) return target_machine.takeError();
// Link with shared libraries for symbol resolution.
llvm::SmallVector<llvm::StringRef, 4> libs;
// Additional LLVM passes to run.
llvm::SmallVector<const llvm::PassInfo*, 4> passes;
auto transformer = mlir::makeLLVMPassesTransformer(passes, /*mbOptLevel=*/2,
target_machine->get());
// Build MLIR exection engine.
auto engine =
mlir::ExecutionEngine::create(*module, /*llvmModuleBuilder=*/nullptr,
transformer, opts.jit_code_opt_level, libs);
if (!engine) return engine.takeError();
// Register Async Runtime API intrinsics.
(*engine)->registerSymbols(AsyncRuntimeApiSymbolMap);
return CompilationResult(entrypoint, std::move(*engine));
}
} // namespace jit
} // namespace cpu
} // namespace tfrt
<commit_msg>Fix some comment typos in cpurt.cc<commit_after>/*
* Copyright 2021 The TensorFlow Runtime Authors
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
//===- cpurt.cc - ---------------------------------------------------------===//
//
// Support library for implementing TFRT kernels that do JIT compilation using
// MLIR framework.
//
//===----------------------------------------------------------------------===//
#include "tfrt/cpu/jit/cpurt.h"
#include "llvm/ExecutionEngine/Orc/Core.h"
#include "llvm/ExecutionEngine/Orc/Mangling.h"
#include "llvm/Support/MemoryBuffer.h"
#include "llvm/Support/TargetSelect.h"
#include "mlir/Conversion/AsyncToLLVM/AsyncToLLVM.h"
#include "mlir/Conversion/SCFToStandard/SCFToStandard.h"
#include "mlir/Conversion/StandardToLLVM/ConvertStandardToLLVMPass.h"
#include "mlir/Dialect/Affine/IR/AffineOps.h"
#include "mlir/Dialect/Async/IR/Async.h"
#include "mlir/Dialect/Async/Passes.h"
#include "mlir/Dialect/LLVMIR/LLVMDialect.h"
#include "mlir/Dialect/Linalg/IR/LinalgOps.h"
#include "mlir/Dialect/Linalg/IR/LinalgTypes.h"
#include "mlir/Dialect/Linalg/Passes.h"
#include "mlir/Dialect/SCF/SCF.h"
#include "mlir/Dialect/StandardOps/IR/Ops.h"
#include "mlir/Dialect/StandardOps/Transforms/Passes.h"
#include "mlir/ExecutionEngine/ExecutionEngine.h"
#include "mlir/ExecutionEngine/OptUtils.h"
#include "mlir/IR/BuiltinOps.h"
#include "mlir/IR/MLIRContext.h"
#include "mlir/Parser.h"
#include "mlir/Pass/Pass.h"
#include "mlir/Pass/PassManager.h"
#include "mlir/Support/LogicalResult.h"
#include "mlir/Transforms/Passes.h"
#include "tfrt/cpu/jit/async_runtime.h"
#include "tfrt/cpu/jit/async_runtime_api.h"
#include "tfrt/support/error_util.h"
#include "tfrt/tensor/dense_host_tensor.h"
#include "tfrt/tensor/tensor.h"
namespace tfrt {
namespace cpu {
namespace jit {
// Enable IR printing during the kernel compilation pipeline execution.
static bool DebugCpurtCompile() {
#if defined(DEBUG_CPURT)
return true;
#else
return false;
#endif
}
using MemrefArg = CompilationResult::MemrefArg;
using CallFrame = CompilationResult::CallFrame;
//----------------------------------------------------------------------------//
// CompilationResult implementation.
//----------------------------------------------------------------------------//
// Converts Tensor to Memref argument for supported tensor types. Returns
// error otherwise.
static Expected<MemrefArg> ConvertTensorToMemrefArg(const Tensor& tensor) {
if (auto* dht = dyn_cast<DenseHostTensor>(&tensor)) {
MemrefArg memref;
memref.data = const_cast<void*>(dht->data());
memref.offset = 0;
dht->shape().GetDimensions(&memref.sizes);
dht->shape().GetStrides(&memref.strides);
return memref;
}
return MakeStringError("unsupported tensor type: ", tensor.tensor_type());
}
// Unpack `memref` argument into pointers to the data to be compatible with
// compiled MLIR function ABI.
static void AddMemrefArgument(const MemrefArg& memref,
llvm::SmallVectorImpl<void*>* args) {
assert(memref.sizes.size() == memref.strides.size());
auto add_arg = [&](const void* p) { args->push_back(const_cast<void*>(p)); };
add_arg(&memref.data); // memref.basePtr
add_arg(&memref.data); // memref.data
add_arg(&memref.offset);
size_t rank = memref.sizes.size();
for (int i = 0; i < rank; ++i) add_arg(&memref.sizes[i]);
for (int i = 0; i < rank; ++i) add_arg(&memref.strides[i]);
}
// Initializes call frame by adding all arguments to it to ensure that all the
// arguments are alive when we call compiled kernel.
//
// Returns compiled function arguments as `void*` type erased pointers. These
// pointers are pointing to the arguments that are stored in the CallFrame
// instance. See mlir::ExecutionEngine `packFunctionArguments` for the details.
static Expected<llvm::SmallVector<void*, 32>> InitializeCallFrame(
RepeatedArguments<Tensor> operands, CallFrame* call_frame) {
llvm::SmallVector<void*, 32> args;
// Pack all Tensor operands as memref arguments.
for (Tensor& tensor : operands) {
Expected<MemrefArg> memref = ConvertTensorToMemrefArg(tensor);
if (auto err = memref.takeError()) return std::move(err);
call_frame->memrefs.push_back(*memref);
AddMemrefArgument(call_frame->memrefs.back(), &args);
}
// Address to write the returned async.token value.
args.push_back(&call_frame->return_value);
return args;
}
AsyncValueRef<Chain> CompilationResult::Execute(
RepeatedArguments<Tensor> operands,
const ExecutionContext& exec_ctx) const {
// CallFrame can be allocated on the stack because compiled function will
// unpack all the arguments it needs, and async regions will not access
// the data after the initial function will return the result.
CallFrame call_frame;
// Compiled function takes arguments as `void**` type erased pointer. See
// mlir::ExecutionEngine `packFunctionArguments` for the details.
auto args = InitializeCallFrame(operands, &call_frame);
if (auto err = args.takeError())
return EmitErrorAsync(exec_ctx, std::move(err));
// Set the AsyncRuntime context to be used by all async tasks.
ResourceContext* res_ctx = exec_ctx.resource_context();
AsyncRuntime* runtime = res_ctx->GetOrCreateResource<AsyncRuntime>(
"cpurt.runtime", exec_ctx.host());
SetAsyncRuntimeContext(runtime);
// Call the compiled function.
(*fptr_)(args->data());
return ConverAsyncTokenToChain(
static_cast<mlir::runtime::AsyncToken*>(call_frame.return_value));
}
//----------------------------------------------------------------------------//
// CompilationResultCache implementation.
//----------------------------------------------------------------------------//
AsyncValueRef<CompilationResult> CompilationResultCache::Find(
intptr_t key) const {
tfrt::mutex_lock lock(mu_);
auto it = cache_.find(key);
if (it != cache_.end()) return it->second.CopyRef();
return AsyncValueRef<CompilationResult>();
}
AsyncValueRef<CompilationResult> CompilationResultCache::Insert(
intptr_t key, CompilationResult compilation_result) {
tfrt::mutex_lock lock(mu_);
auto it = cache_.find(key);
if (it != cache_.end()) return it->second.CopyRef();
auto emplaced =
cache_.try_emplace(key, MakeAvailableAsyncValueRef<CompilationResult>(
host_, std::move(compilation_result)));
return emplaced.first->getSecond().CopyRef();
}
//----------------------------------------------------------------------------//
// Setup MLIR pass pipeline to lower to LLVM dialect, and use ORC JIT to codegen
// functions at runtime.
//----------------------------------------------------------------------------//
static void InitializeCompiler() {
static const bool initialized = ([] {
llvm::InitializeNativeTarget();
llvm::InitializeNativeTargetAsmPrinter();
return true;
})();
(void)initialized;
}
// Runs the pipeline to lower kernel IR to LLVM dialect.
static mlir::LogicalResult LowerToLlvm(mlir::MLIRContext* context,
mlir::ModuleOp module,
const CompilationOptions& opts) {
mlir::PassManager pm(context);
pm.addPass(mlir::createInlinerPass());
pm.addPass(mlir::createCanonicalizerPass());
pm.addPass(mlir::createCSEPass());
// TODO(ezhulenev): Move this to a pipeline exposed upstream when it will
// stabilize, e.g. `LinalgToAsyncRuntime`.
// Convert all linalg operations to parallel loops, and then add async
// operations to actually execute them in parallel using the async runtime.
mlir::OpPassManager& fpm = pm.nest<mlir::FuncOp>();
fpm.addPass(mlir::createConvertLinalgToParallelLoopsPass());
fpm.addPass(mlir::createAsyncParallelForPass(opts.num_worker_threads));
fpm.addPass(mlir::createAsyncRefCountingPass());
fpm.addPass(mlir::createAsyncRefCountingOptimizationPass());
fpm.addPass(mlir::createStdExpandOpsPass());
// Lower from high level async operations to async runtime.
pm.addPass(mlir::createAsyncToAsyncRuntimePass());
// Lower everything down to LLVM dialect.
mlir::LowerToLLVMOptions lower_to_llvm_opts;
pm.addPass(mlir::createConvertAsyncToLLVMPass());
pm.addPass(mlir::createLowerToCFGPass());
pm.addPass(mlir::createLowerToLLVMPass(lower_to_llvm_opts));
// Print IR after all passes.
if (DebugCpurtCompile()) {
context->disableMultithreading();
pm.enableIRPrinting([](mlir::Pass*, mlir::Operation*) { return false; },
[](mlir::Pass*, mlir::Operation*) { return true; },
/*printModuleScope=*/true,
/*printAfterOnlyOnChange=*/false, llvm::errs());
}
return pm.run(module);
}
Expected<CompilationResult> CompileKernelMlirModule(
string_view mlir_module, string_view entrypoint,
const CompilationOptions& opts) {
// Setup LLVM target for code generation.
InitializeCompiler();
llvm::SourceMgr source_mgr;
source_mgr.AddNewSourceBuffer(
llvm::MemoryBuffer::getMemBuffer(mlir_module, "<unknown>"),
llvm::SMLoc());
// Register MLIR dialects supported by the compiled kernels.
mlir::MLIRContext context;
context.getDialectRegistry()
.insert<mlir::async::AsyncDialect, mlir::linalg::LinalgDialect,
mlir::scf::SCFDialect, mlir::StandardOpsDialect,
mlir::LLVM::LLVMDialect>();
// Parse a kernel source code into the MLIR Module.
mlir::OwningModuleRef module(mlir::parseSourceFile(source_mgr, &context));
if (!module) return MakeStringError("failed to parse kernel source");
// Lower kernel IR from high level dialects to the MLIR LLVM Dialect.
if (failed(LowerToLlvm(&context, *module, opts)))
return MakeStringError("Failed to lower module to LLVM");
// Prepare JIT target machine for code generation.
auto builder = llvm::orc::JITTargetMachineBuilder::detectHost();
if (!builder) return builder.takeError();
auto target_machine = builder->createTargetMachine();
if (!target_machine) return target_machine.takeError();
// Link with shared libraries for symbol resolution.
llvm::SmallVector<llvm::StringRef, 4> libs;
// Additional LLVM passes to run.
llvm::SmallVector<const llvm::PassInfo*, 4> passes;
auto transformer = mlir::makeLLVMPassesTransformer(passes, /*mbOptLevel=*/2,
target_machine->get());
// Build MLIR exection engine.
auto engine =
mlir::ExecutionEngine::create(*module, /*llvmModuleBuilder=*/nullptr,
transformer, opts.jit_code_opt_level, libs);
if (!engine) return engine.takeError();
// Register Async Runtime API intrinsics.
(*engine)->registerSymbols(AsyncRuntimeApiSymbolMap);
return CompilationResult(entrypoint, std::move(*engine));
}
} // namespace jit
} // namespace cpu
} // namespace tfrt
<|endoftext|>
|
<commit_before>/**
* @file allknn_main.cpp
* @author Ryan Curtin
*
* Implementation of the AllkNN executable. Allows some number of standard
* options.
*/
#include <mlpack/core.hpp>
#include <mlpack/core/tree/cover_tree.hpp>
#include <string>
#include <fstream>
#include <iostream>
#include "neighbor_search.hpp"
#include "unmap.hpp"
using namespace std;
using namespace mlpack;
using namespace mlpack::neighbor;
using namespace mlpack::tree;
// Information about the program itself.
PROGRAM_INFO("All K-Nearest-Neighbors",
"This program will calculate the all k-nearest-neighbors of a set of "
"points using kd-trees or cover trees (cover tree support is experimental "
"and may not be optimally fast). You may specify a separate set of "
"reference points and query points, or just a reference set which will be "
"used as both the reference and query set."
"\n\n"
"For example, the following will calculate the 5 nearest neighbors of each"
"point in 'input.csv' and store the distances in 'distances.csv' and the "
"neighbors in the file 'neighbors.csv':"
"\n\n"
"$ allknn --k=5 --reference_file=input.csv --distances_file=distances.csv\n"
" --neighbors_file=neighbors.csv"
"\n\n"
"The output files are organized such that row i and column j in the "
"neighbors output file corresponds to the index of the point in the "
"reference set which is the i'th nearest neighbor from the point in the "
"query set with index j. Row i and column j in the distances output file "
"corresponds to the distance between those two points.");
// Define our input parameters that this program will take.
PARAM_STRING_REQ("reference_file", "File containing the reference dataset.",
"r");
PARAM_STRING_REQ("distances_file", "File to output distances into.", "d");
PARAM_STRING_REQ("neighbors_file", "File to output neighbors into.", "n");
PARAM_INT_REQ("k", "Number of furthest neighbors to find.", "k");
PARAM_STRING("query_file", "File containing query points (optional).", "q", "");
PARAM_INT("leaf_size", "Leaf size for tree building.", "l", 20);
PARAM_FLAG("naive", "If true, O(n^2) naive mode is used for computation.", "N");
PARAM_FLAG("single_mode", "If true, single-tree search is used (as opposed to "
"dual-tree search).", "s");
PARAM_FLAG("cover_tree", "If true, use cover trees to perform the search "
"(experimental, may be slow).", "c");
PARAM_FLAG("random_basis", "Before tree-building, project the data onto a "
"random orthogonal basis.", "R");
PARAM_INT("seed", "Random seed (if 0, std::time(NULL) is used).", "s", 0);
int main(int argc, char *argv[])
{
// Give CLI the command line parameters the user passed in.
CLI::ParseCommandLine(argc, argv);
if (CLI::GetParam<int>("seed") != 0)
math::RandomSeed((size_t) CLI::GetParam<int>("seed"));
else
math::RandomSeed((size_t) std::time(NULL));
// Get all the parameters.
const string referenceFile = CLI::GetParam<string>("reference_file");
const string queryFile = CLI::GetParam<string>("query_file");
const string distancesFile = CLI::GetParam<string>("distances_file");
const string neighborsFile = CLI::GetParam<string>("neighbors_file");
int lsInt = CLI::GetParam<int>("leaf_size");
size_t k = CLI::GetParam<int>("k");
bool naive = CLI::HasParam("naive");
bool singleMode = CLI::HasParam("single_mode");
const bool randomBasis = CLI::HasParam("random_basis");
arma::mat referenceData;
arma::mat queryData; // So it doesn't go out of scope.
data::Load(referenceFile, referenceData, true);
Log::Info << "Loaded reference data from '" << referenceFile << "' ("
<< referenceData.n_rows << " x " << referenceData.n_cols << ")." << endl;
if (queryFile != "")
{
data::Load(queryFile, queryData, true);
Log::Info << "Loaded query data from '" << queryFile << "' ("
<< queryData.n_rows << " x " << queryData.n_cols << ")." << endl;
}
// Sanity check on k value: must be greater than 0, must be less than the
// number of reference points.
if (k > referenceData.n_cols)
{
Log::Fatal << "Invalid k: " << k << "; must be greater than 0 and less ";
Log::Fatal << "than or equal to the number of reference points (";
Log::Fatal << referenceData.n_cols << ")." << endl;
}
// Sanity check on leaf size.
if (lsInt < 0)
{
Log::Fatal << "Invalid leaf size: " << lsInt << ". Must be greater "
"than or equal to 0." << endl;
}
size_t leafSize = lsInt;
// Naive mode overrides single mode.
if (singleMode && naive)
{
Log::Warn << "--single_mode ignored because --naive is present." << endl;
}
if (naive)
leafSize = referenceData.n_cols;
// See if we want to project onto a random basis.
if (randomBasis)
{
// Generate the random basis.
while (true)
{
// [Q, R] = qr(randn(d, d));
// Q = Q * diag(sign(diag(R)));
arma::mat q, r;
if (arma::qr(q, r, arma::randn<arma::mat>(referenceData.n_rows,
referenceData.n_rows)))
{
arma::vec rDiag(r.n_rows);
for (size_t i = 0; i < rDiag.n_elem; ++i)
{
if (r(i, i) < 0)
rDiag(i) = -1;
else if (r(i, i) > 0)
rDiag(i) = 1;
else
rDiag(i) = 0;
}
q *= arma::diagmat(rDiag);
// Check if the determinant is positive.
if (arma::det(q) >= 0)
{
referenceData = q * referenceData;
if (queryFile != "")
queryData = q * queryData;
break;
}
}
}
}
arma::Mat<size_t> neighbors;
arma::mat distances;
if (!CLI::HasParam("cover_tree"))
{
// Because we may construct it differently, we need a pointer.
AllkNN* allknn = NULL;
// Mappings for when we build the tree.
std::vector<size_t> oldFromNewRefs;
// Build trees by hand, so we can save memory: if we pass a tree to
// NeighborSearch, it does not copy the matrix.
Log::Info << "Building reference tree..." << endl;
Timer::Start("tree_building");
BinarySpaceTree<bound::HRectBound<2>, QueryStat<NearestNeighborSort> >
refTree(referenceData, oldFromNewRefs, leafSize);
BinarySpaceTree<bound::HRectBound<2>, QueryStat<NearestNeighborSort> >*
queryTree = NULL; // Empty for now.
Timer::Stop("tree_building");
std::vector<size_t> oldFromNewQueries;
if (CLI::GetParam<string>("query_file") != "")
{
if (naive && leafSize < queryData.n_cols)
leafSize = queryData.n_cols;
Log::Info << "Loaded query data from '" << queryFile << "' ("
<< queryData.n_rows << " x " << queryData.n_cols << ")." << endl;
Log::Info << "Building query tree..." << endl;
// Build trees by hand, so we can save memory: if we pass a tree to
// NeighborSearch, it does not copy the matrix.
if (!singleMode)
{
Timer::Start("tree_building");
queryTree = new BinarySpaceTree<bound::HRectBound<2>,
QueryStat<NearestNeighborSort> >(queryData, oldFromNewQueries,
leafSize);
Timer::Stop("tree_building");
}
allknn = new AllkNN(&refTree, queryTree, referenceData, queryData,
singleMode);
Log::Info << "Tree built." << endl;
}
else
{
allknn = new AllkNN(&refTree, referenceData, singleMode);
Log::Info << "Trees built." << endl;
}
arma::mat distancesOut;
arma::Mat<size_t> neighborsOut;
Log::Info << "Computing " << k << " nearest neighbors..." << endl;
allknn->Search(k, neighborsOut, distancesOut);
Log::Info << "Neighbors computed." << endl;
// We have to map back to the original indices from before the tree
// construction.
Log::Info << "Re-mapping indices..." << endl;
// Map the results back to the correct places.
if ((CLI::GetParam<string>("query_file") != "") && !singleMode)
Unmap(neighborsOut, distancesOut, oldFromNewRefs, oldFromNewQueries,
neighbors, distances);
else if ((CLI::GetParam<string>("query_file") != "") && singleMode)
Unmap(neighborsOut, distancesOut, oldFromNewRefs, neighbors, distances);
else
Unmap(neighborsOut, distancesOut, oldFromNewRefs, oldFromNewRefs,
neighbors, distances);
// Clean up.
if (queryTree)
delete queryTree;
delete allknn;
}
else // Cover trees.
{
// Make sure to notify the user that they are using cover trees.
Log::Info << "Using cover trees for nearest-neighbor calculation." << endl;
// Build our reference tree.
Log::Info << "Building reference tree..." << endl;
Timer::Start("tree_building");
CoverTree<metric::LMetric<2, true>, tree::FirstPointIsRoot,
QueryStat<NearestNeighborSort> > referenceTree(referenceData, 1.3);
CoverTree<metric::LMetric<2, true>, tree::FirstPointIsRoot,
QueryStat<NearestNeighborSort> >* queryTree = NULL;
Timer::Stop("tree_building");
NeighborSearch<NearestNeighborSort, metric::LMetric<2, true>,
CoverTree<metric::LMetric<2, true>, tree::FirstPointIsRoot,
QueryStat<NearestNeighborSort> > >* allknn = NULL;
// See if we have query data.
if (CLI::HasParam("query_file"))
{
// Build query tree.
if (!singleMode)
{
Log::Info << "Building query tree..." << endl;
Timer::Start("tree_building");
queryTree = new CoverTree<metric::LMetric<2, true>,
tree::FirstPointIsRoot, QueryStat<NearestNeighborSort> >(queryData,
1.3);
Timer::Stop("tree_building");
}
allknn = new NeighborSearch<NearestNeighborSort, metric::LMetric<2, true>,
CoverTree<metric::LMetric<2, true>, tree::FirstPointIsRoot,
QueryStat<NearestNeighborSort> > >(&referenceTree, queryTree,
referenceData, queryData, singleMode);
}
else
{
allknn = new NeighborSearch<NearestNeighborSort, metric::LMetric<2, true>,
CoverTree<metric::LMetric<2, true>, tree::FirstPointIsRoot,
QueryStat<NearestNeighborSort> > >(&referenceTree, referenceData,
singleMode);
}
Log::Info << "Computing " << k << " nearest neighbors..." << endl;
allknn->Search(k, neighbors, distances);
Log::Info << "Neighbors computed." << endl;
delete allknn;
if (queryTree)
delete queryTree;
}
// Save output.
data::Save(distancesFile, distances);
data::Save(neighborsFile, neighbors);
}
<commit_msg>Fix ambiguous match: option -s matches --seed and --single_mode.<commit_after>/**
* @file allknn_main.cpp
* @author Ryan Curtin
*
* Implementation of the AllkNN executable. Allows some number of standard
* options.
*/
#include <mlpack/core.hpp>
#include <mlpack/core/tree/cover_tree.hpp>
#include <string>
#include <fstream>
#include <iostream>
#include "neighbor_search.hpp"
#include "unmap.hpp"
using namespace std;
using namespace mlpack;
using namespace mlpack::neighbor;
using namespace mlpack::tree;
// Information about the program itself.
PROGRAM_INFO("All K-Nearest-Neighbors",
"This program will calculate the all k-nearest-neighbors of a set of "
"points using kd-trees or cover trees (cover tree support is experimental "
"and may not be optimally fast). You may specify a separate set of "
"reference points and query points, or just a reference set which will be "
"used as both the reference and query set."
"\n\n"
"For example, the following will calculate the 5 nearest neighbors of each"
"point in 'input.csv' and store the distances in 'distances.csv' and the "
"neighbors in the file 'neighbors.csv':"
"\n\n"
"$ allknn --k=5 --reference_file=input.csv --distances_file=distances.csv\n"
" --neighbors_file=neighbors.csv"
"\n\n"
"The output files are organized such that row i and column j in the "
"neighbors output file corresponds to the index of the point in the "
"reference set which is the i'th nearest neighbor from the point in the "
"query set with index j. Row i and column j in the distances output file "
"corresponds to the distance between those two points.");
// Define our input parameters that this program will take.
PARAM_STRING_REQ("reference_file", "File containing the reference dataset.",
"r");
PARAM_STRING_REQ("distances_file", "File to output distances into.", "d");
PARAM_STRING_REQ("neighbors_file", "File to output neighbors into.", "n");
PARAM_INT_REQ("k", "Number of furthest neighbors to find.", "k");
PARAM_STRING("query_file", "File containing query points (optional).", "q", "");
PARAM_INT("leaf_size", "Leaf size for tree building.", "l", 20);
PARAM_FLAG("naive", "If true, O(n^2) naive mode is used for computation.", "N");
PARAM_FLAG("single_mode", "If true, single-tree search is used (as opposed to "
"dual-tree search).", "S");
PARAM_FLAG("cover_tree", "If true, use cover trees to perform the search "
"(experimental, may be slow).", "c");
PARAM_FLAG("random_basis", "Before tree-building, project the data onto a "
"random orthogonal basis.", "R");
PARAM_INT("seed", "Random seed (if 0, std::time(NULL) is used).", "s", 0);
int main(int argc, char *argv[])
{
// Give CLI the command line parameters the user passed in.
CLI::ParseCommandLine(argc, argv);
if (CLI::GetParam<int>("seed") != 0)
math::RandomSeed((size_t) CLI::GetParam<int>("seed"));
else
math::RandomSeed((size_t) std::time(NULL));
// Get all the parameters.
const string referenceFile = CLI::GetParam<string>("reference_file");
const string queryFile = CLI::GetParam<string>("query_file");
const string distancesFile = CLI::GetParam<string>("distances_file");
const string neighborsFile = CLI::GetParam<string>("neighbors_file");
int lsInt = CLI::GetParam<int>("leaf_size");
size_t k = CLI::GetParam<int>("k");
bool naive = CLI::HasParam("naive");
bool singleMode = CLI::HasParam("single_mode");
const bool randomBasis = CLI::HasParam("random_basis");
arma::mat referenceData;
arma::mat queryData; // So it doesn't go out of scope.
data::Load(referenceFile, referenceData, true);
Log::Info << "Loaded reference data from '" << referenceFile << "' ("
<< referenceData.n_rows << " x " << referenceData.n_cols << ")." << endl;
if (queryFile != "")
{
data::Load(queryFile, queryData, true);
Log::Info << "Loaded query data from '" << queryFile << "' ("
<< queryData.n_rows << " x " << queryData.n_cols << ")." << endl;
}
// Sanity check on k value: must be greater than 0, must be less than the
// number of reference points.
if (k > referenceData.n_cols)
{
Log::Fatal << "Invalid k: " << k << "; must be greater than 0 and less ";
Log::Fatal << "than or equal to the number of reference points (";
Log::Fatal << referenceData.n_cols << ")." << endl;
}
// Sanity check on leaf size.
if (lsInt < 0)
{
Log::Fatal << "Invalid leaf size: " << lsInt << ". Must be greater "
"than or equal to 0." << endl;
}
size_t leafSize = lsInt;
// Naive mode overrides single mode.
if (singleMode && naive)
{
Log::Warn << "--single_mode ignored because --naive is present." << endl;
}
if (naive)
leafSize = referenceData.n_cols;
// See if we want to project onto a random basis.
if (randomBasis)
{
// Generate the random basis.
while (true)
{
// [Q, R] = qr(randn(d, d));
// Q = Q * diag(sign(diag(R)));
arma::mat q, r;
if (arma::qr(q, r, arma::randn<arma::mat>(referenceData.n_rows,
referenceData.n_rows)))
{
arma::vec rDiag(r.n_rows);
for (size_t i = 0; i < rDiag.n_elem; ++i)
{
if (r(i, i) < 0)
rDiag(i) = -1;
else if (r(i, i) > 0)
rDiag(i) = 1;
else
rDiag(i) = 0;
}
q *= arma::diagmat(rDiag);
// Check if the determinant is positive.
if (arma::det(q) >= 0)
{
referenceData = q * referenceData;
if (queryFile != "")
queryData = q * queryData;
break;
}
}
}
}
arma::Mat<size_t> neighbors;
arma::mat distances;
if (!CLI::HasParam("cover_tree"))
{
// Because we may construct it differently, we need a pointer.
AllkNN* allknn = NULL;
// Mappings for when we build the tree.
std::vector<size_t> oldFromNewRefs;
// Build trees by hand, so we can save memory: if we pass a tree to
// NeighborSearch, it does not copy the matrix.
Log::Info << "Building reference tree..." << endl;
Timer::Start("tree_building");
BinarySpaceTree<bound::HRectBound<2>, QueryStat<NearestNeighborSort> >
refTree(referenceData, oldFromNewRefs, leafSize);
BinarySpaceTree<bound::HRectBound<2>, QueryStat<NearestNeighborSort> >*
queryTree = NULL; // Empty for now.
Timer::Stop("tree_building");
std::vector<size_t> oldFromNewQueries;
if (CLI::GetParam<string>("query_file") != "")
{
if (naive && leafSize < queryData.n_cols)
leafSize = queryData.n_cols;
Log::Info << "Loaded query data from '" << queryFile << "' ("
<< queryData.n_rows << " x " << queryData.n_cols << ")." << endl;
Log::Info << "Building query tree..." << endl;
// Build trees by hand, so we can save memory: if we pass a tree to
// NeighborSearch, it does not copy the matrix.
if (!singleMode)
{
Timer::Start("tree_building");
queryTree = new BinarySpaceTree<bound::HRectBound<2>,
QueryStat<NearestNeighborSort> >(queryData, oldFromNewQueries,
leafSize);
Timer::Stop("tree_building");
}
allknn = new AllkNN(&refTree, queryTree, referenceData, queryData,
singleMode);
Log::Info << "Tree built." << endl;
}
else
{
allknn = new AllkNN(&refTree, referenceData, singleMode);
Log::Info << "Trees built." << endl;
}
arma::mat distancesOut;
arma::Mat<size_t> neighborsOut;
Log::Info << "Computing " << k << " nearest neighbors..." << endl;
allknn->Search(k, neighborsOut, distancesOut);
Log::Info << "Neighbors computed." << endl;
// We have to map back to the original indices from before the tree
// construction.
Log::Info << "Re-mapping indices..." << endl;
// Map the results back to the correct places.
if ((CLI::GetParam<string>("query_file") != "") && !singleMode)
Unmap(neighborsOut, distancesOut, oldFromNewRefs, oldFromNewQueries,
neighbors, distances);
else if ((CLI::GetParam<string>("query_file") != "") && singleMode)
Unmap(neighborsOut, distancesOut, oldFromNewRefs, neighbors, distances);
else
Unmap(neighborsOut, distancesOut, oldFromNewRefs, oldFromNewRefs,
neighbors, distances);
// Clean up.
if (queryTree)
delete queryTree;
delete allknn;
}
else // Cover trees.
{
// Make sure to notify the user that they are using cover trees.
Log::Info << "Using cover trees for nearest-neighbor calculation." << endl;
// Build our reference tree.
Log::Info << "Building reference tree..." << endl;
Timer::Start("tree_building");
CoverTree<metric::LMetric<2, true>, tree::FirstPointIsRoot,
QueryStat<NearestNeighborSort> > referenceTree(referenceData, 1.3);
CoverTree<metric::LMetric<2, true>, tree::FirstPointIsRoot,
QueryStat<NearestNeighborSort> >* queryTree = NULL;
Timer::Stop("tree_building");
NeighborSearch<NearestNeighborSort, metric::LMetric<2, true>,
CoverTree<metric::LMetric<2, true>, tree::FirstPointIsRoot,
QueryStat<NearestNeighborSort> > >* allknn = NULL;
// See if we have query data.
if (CLI::HasParam("query_file"))
{
// Build query tree.
if (!singleMode)
{
Log::Info << "Building query tree..." << endl;
Timer::Start("tree_building");
queryTree = new CoverTree<metric::LMetric<2, true>,
tree::FirstPointIsRoot, QueryStat<NearestNeighborSort> >(queryData,
1.3);
Timer::Stop("tree_building");
}
allknn = new NeighborSearch<NearestNeighborSort, metric::LMetric<2, true>,
CoverTree<metric::LMetric<2, true>, tree::FirstPointIsRoot,
QueryStat<NearestNeighborSort> > >(&referenceTree, queryTree,
referenceData, queryData, singleMode);
}
else
{
allknn = new NeighborSearch<NearestNeighborSort, metric::LMetric<2, true>,
CoverTree<metric::LMetric<2, true>, tree::FirstPointIsRoot,
QueryStat<NearestNeighborSort> > >(&referenceTree, referenceData,
singleMode);
}
Log::Info << "Computing " << k << " nearest neighbors..." << endl;
allknn->Search(k, neighbors, distances);
Log::Info << "Neighbors computed." << endl;
delete allknn;
if (queryTree)
delete queryTree;
}
// Save output.
data::Save(distancesFile, distances);
data::Save(neighborsFile, neighbors);
}
<|endoftext|>
|
<commit_before><commit_msg>Add Rrrola to copyright string<commit_after><|endoftext|>
|
<commit_before><commit_msg>remove dummy test<commit_after><|endoftext|>
|
<commit_before>#include "FileEvent.h"
#if defined(__linux__)
// POSIX++
#include <cstring>
#include <cassert>
// Linux
#include <sys/inotify.h>
// PDTK
#include <cxxutils/vterm.h>
// file/directory flags
static constexpr uint32_t from_native_flags(const native_flags_t flags) noexcept
{
return
(flags & IN_ACCESS ? FileEvent::ReadEvent : 0) |
(flags & IN_MODIFY ? FileEvent::WriteEvent : 0) |
(flags & IN_ATTRIB ? FileEvent::AttributeMod : 0) |
(flags & IN_MOVE_SELF ? FileEvent::Moved : 0) |
(flags & IN_DELETE_SELF ? FileEvent::Deleted : 0) ;
//data.flags.SubCreated = flags & IN_CREATE ? 1 : 0;
//data.flags.SubMoved = flags & IN_MOVE ? 1 : 0;
//data.flags.SubDeleted = flags & IN_DELETE ? 1 : 0;
}
static constexpr native_flags_t to_native_flags(const uint32_t flags) noexcept
{
return
(flags & FileEvent::ReadEvent ? native_flags_t(IN_ACCESS ) : 0) | // File was accessed (read) (*).
(flags & FileEvent::WriteEvent ? native_flags_t(IN_MODIFY ) : 0) | // File was modified (*).
(flags & FileEvent::AttributeMod ? native_flags_t(IN_ATTRIB ) : 0) | // Metadata changed, e.g., permissions, timestamps, extended attributes, link count (since Linux 2.6.25), UID, GID, etc. (*).
(flags & FileEvent::Moved ? native_flags_t(IN_MOVE_SELF ) : 0) | // Watched File was moved.
(flags & FileEvent::Deleted ? native_flags_t(IN_DELETE_SELF) : 0); // Watched File was deleted.
// (flags & FileEvent::SubCreated ? native_flags_t(IN_CREATE ) : 0) | // File created in watched dir.
// (flags & FileEvent::SubMoved ? native_flags_t(IN_MOVE ) : 0) | // File moved in watched dir.
// (flags & FileEvent::SubDeleted ? native_flags_t(IN_DELETE ) : 0) ; // File deleted in watched dir.
}
struct FileEvent::platform_dependant // file notification (inotify)
{
posix::fd_t fd;
platform_dependant(void) noexcept
: fd(posix::invalid_descriptor)
{
fd = ::inotify_init();
flaw(fd == posix::invalid_descriptor, terminal::severe,,,
"Unable to create an instance of inotify!: %s", std::strerror(errno))
}
~platform_dependant(void) noexcept
{
posix::close(fd);
fd = posix::invalid_descriptor;
}
posix::fd_t add(const char* path, FileEvent::Flags_t flags) noexcept
{
return ::inotify_add_watch(fd, path, to_native_flags(flags));
}
bool remove(posix::fd_t wd) noexcept
{
return ::inotify_rm_watch(fd, wd) == posix::success_response;
}
struct return_data
{
const char* name;
FileEvent::Flags_t flags;
};
#define INOTIFY_EVENT_SIZE (sizeof(inotify_event) + NAME_MAX + 1)
return_data read(posix::fd_t wd) noexcept
{
static uint8_t inotifiy_buffer_data[INOTIFY_EVENT_SIZE * 16]; // queue has a minimum of size of 16 inotify events
union {
uint8_t* inpos;
inotify_event* incur;
};
uint8_t* inend = inotifiy_buffer_data + posix::read(wd, inotifiy_buffer_data, sizeof(inotifiy_buffer_data)); // read data and locate it's end
for(inpos = inotifiy_buffer_data; inpos < inend; inpos += sizeof(inotify_event) + incur->len) // iterate through the inotify events
if(incur->wd == wd)
return { incur->name, from_native_flags(incur->mask) };
assert(false);
return { nullptr, 0 };
}
} FileEvent::s_platform;
FileEvent::FileEvent(const char* _file, Flags_t _flags) noexcept
: m_flags(_flags), m_fd(posix::invalid_descriptor)
{
std::memset(m_file, 0, sizeof(m_file));
std::strcpy(m_file, _file);
m_fd = s_platform.add(m_file, m_flags);
EventBackend::add(m_fd, EventBackend::SimplePollReadFlags,
[this](posix::fd_t lambda_fd, native_flags_t) noexcept
{
platform_dependant::return_data data = s_platform.read(lambda_fd);
assert(m_flags & data.flags);
assert(!std::strcmp(m_file, data.name));
Object::enqueue(activated, data.name, data.flags);
});
}
FileEvent::~FileEvent(void) noexcept
{
assert(EventBackend::remove(m_fd, EventBackend::SimplePollReadFlags));
assert(s_platform.remove(m_fd));
}
#elif defined(__APPLE__) /* Darwin 7+ */ || \
defined(__FreeBSD__) /* FreeBSD 4.1+ */ || \
defined(__DragonFly__) /* DragonFly BSD */ || \
defined(__OpenBSD__) /* OpenBSD 2.9+ */ || \
defined(__NetBSD__) /* NetBSD 2+ */
#include <sys/event.h> // kqueue
#include <sys/types.h>
static constexpr native_flags_t composite_flag(uint16_t actions, int16_t filters, uint32_t flags) noexcept
{ return native_flags_t(actions) | (native_flags_t(uint16_t(filters)) << 16) | (native_flags_t(flags) << 32); }
static constexpr bool flag_subset(native_flags_t flags, native_flags_t subset)
{ return (flags & subset) == subset; }
// file flags
static constexpr uint32_t from_native_flags(const native_flags_t flags) noexcept
{
return
(flag_subset(flags, composite_flag(0, EVFILT_VNODE, NOTE_READ )) ? FileEvent::ReadEvent : 0) |
(flag_subset(flags, composite_flag(0, EVFILT_VNODE, NOTE_WRITE )) ? FileEvent::WriteEvent : 0) |
(flag_subset(flags, composite_flag(0, EVFILT_VNODE, NOTE_ATTRIB)) ? FileEvent::AttributeMod : 0) |
(flag_subset(flags, composite_flag(0, EVFILT_VNODE, NOTE_RENAME)) ? FileEvent::Moved : 0) |
(flag_subset(flags, composite_flag(0, EVFILT_VNODE, NOTE_DELETE)) ? FileEvent::Deleted : 0) ;
}
static constexpr native_flags_t to_native_flags(const uint32_t flags) noexcept
{
return
(flags & FileEvent::ReadEvent ? composite_flag(0, EVFILT_VNODE, NOTE_READ ) : 0) |
(flags & FileEvent::WriteEvent ? composite_flag(0, EVFILT_VNODE, NOTE_WRITE ) : 0) |
(flags & FileEvent::AttributeMod ? composite_flag(0, EVFILT_VNODE, NOTE_ATTRIB) : 0) |
(flags & FileEvent::Moved ? composite_flag(0, EVFILT_VNODE, NOTE_RENAME) : 0) |
(flags & FileEvent::Deleted ? composite_flag(0, EVFILT_VNODE, NOTE_DELETE) : 0) ;
}
FileEvent::FileEvent(const char* _file, Flags_t _flags) noexcept
: m_flags(_flags), m_fd(posix::invalid_descriptor)
{
std::memset(m_file, 0, sizeof(m_file));
std::strcpy(m_file, _file);
m_fd = posix::open(m_file, O_EVTONLY);
EventBackend::add(m_fd, to_native_flags(m_flags), // connect FD with flags to signal
[this](posix::fd_t lambda_fd, native_flags_t lambda_flags) noexcept
{ Object::enqueue_copy<const char*, Flags_t>(activated, m_file, from_native_flags(lambda_flags)); });
}
FileEvent::~FileEvent(void) noexcept
{
EventBackend::remove(m_fd, to_native_flags(m_flags)); // disconnect FD with flags from signal
posix::close(m_fd);
m_fd = posix::invalid_descriptor;
}
#elif defined(__sun) && defined(__SVR4) // Solaris / OpenSolaris / OpenIndiana / illumos
# error No file event backend code exists in PDTK for Solaris / OpenSolaris / OpenIndiana / illumos! Please submit a patch!
#elif defined(__minix) // MINIX
# error No process event backend code exists in PDTK for MINIX! Please submit a patch!
#elif defined(__QNX__) // QNX
// QNX docs: http://www.qnx.com/developers/docs/7.0.0/index.html#com.qnx.doc.neutrino.devctl/topic/about.html
# error No file event backend code exists in PDTK for QNX! Please submit a patch!
#elif defined(__hpux) // HP-UX
# error No file event backend code exists in PDTK for HP-UX! Please submit a patch!
#elif defined(_AIX) // IBM AIX
# error No file event backend code exists in PDTK for IBM AIX! Please submit a patch!
#elif defined(BSD)
# error Unrecognized BSD derivative!
#elif defined(__unix__)
# error Unrecognized UNIX variant!
#else
# error This platform is not supported.
#endif
<commit_msg>kqueue fixes for older versions of kqueue<commit_after>#include "FileEvent.h"
#if defined(__linux__)
// POSIX++
#include <cstring>
#include <cassert>
// Linux
#include <sys/inotify.h>
// PDTK
#include <cxxutils/vterm.h>
// file/directory flags
static constexpr uint32_t from_native_flags(const native_flags_t flags) noexcept
{
return
(flags & IN_ACCESS ? FileEvent::ReadEvent : 0) |
(flags & IN_MODIFY ? FileEvent::WriteEvent : 0) |
(flags & IN_ATTRIB ? FileEvent::AttributeMod : 0) |
(flags & IN_MOVE_SELF ? FileEvent::Moved : 0) |
(flags & IN_DELETE_SELF ? FileEvent::Deleted : 0) ;
//data.flags.SubCreated = flags & IN_CREATE ? 1 : 0;
//data.flags.SubMoved = flags & IN_MOVE ? 1 : 0;
//data.flags.SubDeleted = flags & IN_DELETE ? 1 : 0;
}
static constexpr native_flags_t to_native_flags(const uint32_t flags) noexcept
{
return
(flags & FileEvent::ReadEvent ? native_flags_t(IN_ACCESS ) : 0) | // File was accessed (read) (*).
(flags & FileEvent::WriteEvent ? native_flags_t(IN_MODIFY ) : 0) | // File was modified (*).
(flags & FileEvent::AttributeMod ? native_flags_t(IN_ATTRIB ) : 0) | // Metadata changed, e.g., permissions, timestamps, extended attributes, link count (since Linux 2.6.25), UID, GID, etc. (*).
(flags & FileEvent::Moved ? native_flags_t(IN_MOVE_SELF ) : 0) | // Watched File was moved.
(flags & FileEvent::Deleted ? native_flags_t(IN_DELETE_SELF) : 0); // Watched File was deleted.
// (flags & FileEvent::SubCreated ? native_flags_t(IN_CREATE ) : 0) | // File created in watched dir.
// (flags & FileEvent::SubMoved ? native_flags_t(IN_MOVE ) : 0) | // File moved in watched dir.
// (flags & FileEvent::SubDeleted ? native_flags_t(IN_DELETE ) : 0) ; // File deleted in watched dir.
}
struct FileEvent::platform_dependant // file notification (inotify)
{
posix::fd_t fd;
platform_dependant(void) noexcept
: fd(posix::invalid_descriptor)
{
fd = ::inotify_init();
flaw(fd == posix::invalid_descriptor, terminal::severe,,,
"Unable to create an instance of inotify!: %s", std::strerror(errno))
}
~platform_dependant(void) noexcept
{
posix::close(fd);
fd = posix::invalid_descriptor;
}
posix::fd_t add(const char* path, FileEvent::Flags_t flags) noexcept
{
return ::inotify_add_watch(fd, path, to_native_flags(flags));
}
bool remove(posix::fd_t wd) noexcept
{
return ::inotify_rm_watch(fd, wd) == posix::success_response;
}
struct return_data
{
const char* name;
FileEvent::Flags_t flags;
};
#define INOTIFY_EVENT_SIZE (sizeof(inotify_event) + NAME_MAX + 1)
return_data read(posix::fd_t wd) noexcept
{
static uint8_t inotifiy_buffer_data[INOTIFY_EVENT_SIZE * 16]; // queue has a minimum of size of 16 inotify events
union {
uint8_t* inpos;
inotify_event* incur;
};
uint8_t* inend = inotifiy_buffer_data + posix::read(wd, inotifiy_buffer_data, sizeof(inotifiy_buffer_data)); // read data and locate it's end
for(inpos = inotifiy_buffer_data; inpos < inend; inpos += sizeof(inotify_event) + incur->len) // iterate through the inotify events
if(incur->wd == wd)
return { incur->name, from_native_flags(incur->mask) };
assert(false);
return { nullptr, 0 };
}
} FileEvent::s_platform;
FileEvent::FileEvent(const char* _file, Flags_t _flags) noexcept
: m_flags(_flags), m_fd(posix::invalid_descriptor)
{
std::memset(m_file, 0, sizeof(m_file));
std::strcpy(m_file, _file);
m_fd = s_platform.add(m_file, m_flags);
EventBackend::add(m_fd, EventBackend::SimplePollReadFlags,
[this](posix::fd_t lambda_fd, native_flags_t) noexcept
{
platform_dependant::return_data data = s_platform.read(lambda_fd);
assert(m_flags & data.flags);
assert(!std::strcmp(m_file, data.name));
Object::enqueue(activated, data.name, data.flags);
});
}
FileEvent::~FileEvent(void) noexcept
{
assert(EventBackend::remove(m_fd, EventBackend::SimplePollReadFlags));
assert(s_platform.remove(m_fd));
}
#elif defined(__APPLE__) /* Darwin 7+ */ || \
defined(__FreeBSD__) /* FreeBSD 4.1+ */ || \
defined(__DragonFly__) /* DragonFly BSD */ || \
defined(__OpenBSD__) /* OpenBSD 2.9+ */ || \
defined(__NetBSD__) /* NetBSD 2+ */
#include <sys/event.h> // kqueue
static constexpr native_flags_t composite_flag(uint16_t actions, int16_t filters, uint32_t flags) noexcept
{ return native_flags_t(actions) | (native_flags_t(uint16_t(filters)) << 16) | (native_flags_t(flags) << 32); }
static constexpr bool flag_subset(native_flags_t flags, native_flags_t subset)
{ return (flags & subset) == subset; }
// file flags
static constexpr uint32_t from_native_flags(const native_flags_t flags) noexcept
{
return
#if defined(NOTE_READ)
(flag_subset(flags, composite_flag(0, EVFILT_VNODE, NOTE_READ )) ? FileEvent::ReadEvent : 0) |
#endif
(flag_subset(flags, composite_flag(0, EVFILT_VNODE, NOTE_WRITE )) ? FileEvent::WriteEvent : 0) |
(flag_subset(flags, composite_flag(0, EVFILT_VNODE, NOTE_ATTRIB)) ? FileEvent::AttributeMod : 0) |
(flag_subset(flags, composite_flag(0, EVFILT_VNODE, NOTE_RENAME)) ? FileEvent::Moved : 0) |
(flag_subset(flags, composite_flag(0, EVFILT_VNODE, NOTE_DELETE)) ? FileEvent::Deleted : 0) ;
}
static constexpr native_flags_t to_native_flags(const uint32_t flags) noexcept
{
return
#if defined(NOTE_READ)
(flags & FileEvent::ReadEvent ? composite_flag(0, EVFILT_VNODE, NOTE_READ ) : 0) |
#endif
(flags & FileEvent::WriteEvent ? composite_flag(0, EVFILT_VNODE, NOTE_WRITE ) : 0) |
(flags & FileEvent::AttributeMod ? composite_flag(0, EVFILT_VNODE, NOTE_ATTRIB) : 0) |
(flags & FileEvent::Moved ? composite_flag(0, EVFILT_VNODE, NOTE_RENAME) : 0) |
(flags & FileEvent::Deleted ? composite_flag(0, EVFILT_VNODE, NOTE_DELETE) : 0) ;
}
FileEvent::FileEvent(const char* _file, Flags_t _flags) noexcept
: m_flags(_flags), m_fd(posix::invalid_descriptor)
{
std::memset(m_file, 0, sizeof(m_file));
std::strcpy(m_file, _file);
m_fd = posix::open(m_file, O_EVTONLY);
EventBackend::add(m_fd, to_native_flags(m_flags), // connect FD with flags to signal
[this](posix::fd_t lambda_fd, native_flags_t lambda_flags) noexcept
{ Object::enqueue_copy<const char*, Flags_t>(activated, m_file, from_native_flags(lambda_flags)); });
}
FileEvent::~FileEvent(void) noexcept
{
EventBackend::remove(m_fd, to_native_flags(m_flags)); // disconnect FD with flags from signal
posix::close(m_fd);
m_fd = posix::invalid_descriptor;
}
#elif defined(__sun) && defined(__SVR4) // Solaris / OpenSolaris / OpenIndiana / illumos
# error No file event backend code exists in PDTK for Solaris / OpenSolaris / OpenIndiana / illumos! Please submit a patch!
#elif defined(__minix) // MINIX
# error No process event backend code exists in PDTK for MINIX! Please submit a patch!
#elif defined(__QNX__) // QNX
// QNX docs: http://www.qnx.com/developers/docs/7.0.0/index.html#com.qnx.doc.neutrino.devctl/topic/about.html
# error No file event backend code exists in PDTK for QNX! Please submit a patch!
#elif defined(__hpux) // HP-UX
# error No file event backend code exists in PDTK for HP-UX! Please submit a patch!
#elif defined(_AIX) // IBM AIX
# error No file event backend code exists in PDTK for IBM AIX! Please submit a patch!
#elif defined(BSD)
# error Unrecognized BSD derivative!
#elif defined(__unix__)
# error Unrecognized UNIX variant!
#else
# error This platform is not supported.
#endif
<|endoftext|>
|
<commit_before>#include "detectors.h"
//Constructor vacio
Detectors::Detectors(void)
{
this->hog = HOGDescriptor();
}
//Constructores
Detectors::Detectors(HOGDescriptor hog_)
{
this->hog = HOGDescriptor(hog_);
}
//Constructor Copia
Detectors::Detectors(const Detectors& Detectors_)
{
this->hog = Detectors_.hog;
}
//Load SVM
void Detectors::LoadSVM(string svm_model)
{
this->SVM.load(svm_model.c_str());
}
//Load Adaboost
void Detectors::LoadAdaboost(string boost_model)
{
this->boost.load(boost_model.c_str());
}
//Deteccion con HOG + SVM unitaria
Mat Detectors::HOGSVMDetectShow(string filename)
{
Mat img;
img = imread(filename);
if(!img.data)
return img;
vector<float> descriptor_result;
for (int x = 3; x < (img.cols-3-hog.winSize.width); x++)
{
for (int y = 3; y < (img.rows-3-hog.winSize.height); y++)
{
Rect roi(x,y,hog.winSize.width,hog.winSize.height);
Mat crop = img(roi);
hog.compute(crop,descriptor_result);
Mat crop_hog = Mat(1,descriptor_result.size(),CV_32FC1);
for (int i = 0; i < descriptor_result.size(); i++)
{
crop_hog.at<float>(0,i) = descriptor_result[i];
}
float result = SVM.predict(crop_hog,true);
Point ce = Point((roi.tl().x+roi.br().x)/2,(roi.tl().y+roi.br().y)/2);
line( img, ce,ce, Scalar(0, 0, 255*result),1,8);
//rectangle(img, roi.tl(), roi.br(), cv::Scalar(0,255*result,0), 1);
}
}
return img;
}
//Deteccion con HOG + SVM unitaria
Mat Detectors::HOGSVMDetectShow(string filename, string svm_model)
{
this->SVM.load(svm_model.c_str());
return HOGSVMDetectShow(filename);
}
//
NeighbourhoodMatrix Detectors::HOGSVMDetectPrint(string filename, Sigmoid sig)
{
Mat img;
img = imread(filename);
NeighbourhoodMatrix null_matrix;
if(!img.data)
return null_matrix;
int rows = img.rows-6-hog.winSize.height;
int cols = img.cols-6-hog.winSize.width;
vector<vector<double>> matrix = vector<vector<double>>(rows, vector<double>(cols,0.0));
#pragma omp parallel num_threads(20)
{
vector<float> descriptor_result;
#pragma omp for schedule(dynamic,rows/40)
for (int x = 3; x < (img.cols-3-hog.winSize.width); x++)
{
for (int y = 3; y < (img.rows-3-hog.winSize.height); y++)
{
Rect roi(x,y,hog.winSize.width,hog.winSize.height);
Mat crop = img(roi);
hog.compute(crop,descriptor_result);
Mat crop_hog = Mat(1,descriptor_result.size(),CV_32FC1);
for (int i = 0; i < descriptor_result.size(); i++)
{
crop_hog.at<float>(0,i) = descriptor_result[i];
}
float result = sig.EvaluateSigmoid(SVM.predict(crop_hog,true));
#pragma omp critical
matrix[y-3][x-3] = (double)result;
}
}
}
NeighbourhoodMatrix neighbourhood_matrix(matrix);
return neighbourhood_matrix;
}
NeighbourhoodMatrix Detectors::HOGSVMDetectPrint(string filename, string svm_model, Sigmoid sig)
{
this->SVM.load(svm_model.c_str());
return HOGSVMDetectPrint(filename, sig);
}
//Deteccion con SVM bucle
void Detectors::HOGSVMDetectBucleShow(string img_filename_list)
{
ifstream img_filename(img_filename_list);
string img_filename_line;
Mat img;
namedWindow("People Detector", 1);
while(getline(img_filename, img_filename_line)) {
img = HOGSVMDetectShow(img_filename_line);
imshow("People Detector", img);
int c = waitKey(0) & 255;
if( c == 'q' || c == 'Q')
break;
}
}
void Detectors::HOGSVMDetectBuclePrint(string img_filename_list, string folder, Sigmoid sig)
{
ifstream img_filename(img_filename_list);
string img_filename_line;
while(getline(img_filename, img_filename_line)) {
NeighbourhoodMatrix neighbourhood_matrix(HOGSVMDetectPrint(img_filename_line, sig));
img_filename_line.erase(img_filename_line.find_last_of("."), string::npos);
img_filename_line.erase(0,img_filename_line.find_last_of("/")+1);
string file = folder+img_filename_line+boost::lexical_cast<string>(".mat");
neighbourhood_matrix.WriteNeigbourhoodMatrix(file);
cout << file << endl;
}
}
//Deteccion con HOG + Adaboost unitaria
Mat Detectors::HOGAdaboostDetectShow(string filename)
{
Mat img;
img = imread(filename);
if(!img.data)
return img;
vector<float> descriptor_result;
for (int x = 3; x < (img.cols-3-hog.winSize.width); x++)
{
for (int y = 3; y < (img.rows-3-hog.winSize.height); y++)
{
Rect roi(x,y,hog.winSize.width,hog.winSize.height);
Mat crop = img(roi);
hog.compute(crop,descriptor_result);
Mat crop_hog = Mat(1,descriptor_result.size(),CV_32FC1);
for (int i = 0; i < descriptor_result.size(); i++)
{
crop_hog.at<float>(0,i) = descriptor_result[i];
}
float result = boost.predict(crop_hog,Mat(),Range::all(),false,true);
Point ce = Point((roi.tl().x+roi.br().x)/2,(roi.tl().y+roi.br().y)/2);
line( img, ce,ce, Scalar(0, 0, 255*result),1,8);
//rectangle(img, roi.tl(), roi.br(), cv::Scalar(0,255*result,0), 1);
}
}
return img;
}
//Deteccion con HOG + SVM unitaria
Mat Detectors::HOGAdaboostDetectShow(string filename, string boost_model)
{
this->boost.load(boost_model.c_str());
return HOGAdaboostDetectShow(filename);
}
//
NeighbourhoodMatrix Detectors::HOGAdaboostDetectPrint(string filename, Sigmoid sig)
{
Mat img;
img = imread(filename);
NeighbourhoodMatrix null_matrix;
if(!img.data)
return null_matrix;
int rows = img.rows-6-hog.winSize.height;
int cols = img.cols-6-hog.winSize.width;
vector<vector<double>> matrix = vector<vector<double>>(rows, vector<double>(cols,0.0));
#pragma omp parallel num_threads(30)
{
vector<float> descriptor_result;
#pragma omp for schedule(dynamic,rows/40)
for (int x = 3; x < (img.cols-3-hog.winSize.width); x++)
{
for (int y = 3; y < (img.rows-3-hog.winSize.height); y++)
{
Rect roi(x,y,hog.winSize.width,hog.winSize.height);
Mat crop = img(roi);
hog.compute(crop,descriptor_result);
Mat crop_hog = Mat(1,descriptor_result.size(),CV_32FC1);
for (int i = 0; i < descriptor_result.size(); i++)
{
crop_hog.at<float>(0,i) = descriptor_result[i];
}
float result = sig.EvaluateSigmoid(boost.predict(crop_hog,Mat(),Range::all(),false,false));
#pragma omp critical
matrix[y-3][x-3] = (double)result;
}
}
}
NeighbourhoodMatrix neighbourhood_matrix(matrix);
return neighbourhood_matrix;
}
NeighbourhoodMatrix Detectors::HOGAdaboostDetectPrint(string filename, string boost_model, Sigmoid sig)
{
this->boost.load(boost_model.c_str());
return HOGAdaboostDetectPrint(filename, sig);
}
//Deteccion con SVM bucle
void Detectors::HOGAdaboostDetectBucleShow(string img_filename_list)
{
ifstream img_filename(img_filename_list);
string img_filename_line;
Mat img;
namedWindow("People Detector", 1);
while(getline(img_filename, img_filename_line)) {
img = HOGAdaboostDetectShow(img_filename_line);
imshow("People Detector", img);
int c = waitKey(0) & 255;
if( c == 'q' || c == 'Q')
break;
}
}
void Detectors::HOGAdaboostDetectBuclePrint(string img_filename_list,string folder, Sigmoid sig)
{
ifstream img_filename(img_filename_list);
string img_filename_line;
while(getline(img_filename, img_filename_line)) {
NeighbourhoodMatrix neighbourhood_matrix(HOGAdaboostDetectPrint(img_filename_line, sig));
img_filename_line.erase(img_filename_line.find_last_of("."), string::npos);
img_filename_line.erase(0,img_filename_line.find_last_of("/")+1);
string file = folder+img_filename_line+boost::lexical_cast<string>(".mat");
neighbourhood_matrix.WriteNeigbourhoodMatrix(file);
cout << file << endl;
}
}
<commit_msg>parallel<commit_after>#include "detectors.h"
//Constructor vacio
Detectors::Detectors(void)
{
this->hog = HOGDescriptor();
}
//Constructores
Detectors::Detectors(HOGDescriptor hog_)
{
this->hog = HOGDescriptor(hog_);
}
//Constructor Copia
Detectors::Detectors(const Detectors& Detectors_)
{
this->hog = Detectors_.hog;
}
//Load SVM
void Detectors::LoadSVM(string svm_model)
{
this->SVM.load(svm_model.c_str());
}
//Load Adaboost
void Detectors::LoadAdaboost(string boost_model)
{
this->boost.load(boost_model.c_str());
}
//Deteccion con HOG + SVM unitaria
Mat Detectors::HOGSVMDetectShow(string filename)
{
Mat img;
img = imread(filename);
if(!img.data)
return img;
vector<float> descriptor_result;
for (int x = 3; x < (img.cols-3-hog.winSize.width); x++)
{
for (int y = 3; y < (img.rows-3-hog.winSize.height); y++)
{
Rect roi(x,y,hog.winSize.width,hog.winSize.height);
Mat crop = img(roi);
hog.compute(crop,descriptor_result);
Mat crop_hog = Mat(1,descriptor_result.size(),CV_32FC1);
for (int i = 0; i < descriptor_result.size(); i++)
{
crop_hog.at<float>(0,i) = descriptor_result[i];
}
float result = SVM.predict(crop_hog,true);
Point ce = Point((roi.tl().x+roi.br().x)/2,(roi.tl().y+roi.br().y)/2);
line( img, ce,ce, Scalar(0, 0, 255*result),1,8);
//rectangle(img, roi.tl(), roi.br(), cv::Scalar(0,255*result,0), 1);
}
}
return img;
}
//Deteccion con HOG + SVM unitaria
Mat Detectors::HOGSVMDetectShow(string filename, string svm_model)
{
this->SVM.load(svm_model.c_str());
return HOGSVMDetectShow(filename);
}
//
NeighbourhoodMatrix Detectors::HOGSVMDetectPrint(string filename, Sigmoid sig)
{
Mat img;
img = imread(filename);
NeighbourhoodMatrix null_matrix;
if(!img.data)
return null_matrix;
int rows = img.rows-6-hog.winSize.height;
int cols = img.cols-6-hog.winSize.width;
vector<vector<double>> matrix = vector<vector<double>>(rows, vector<double>(cols,0.0));
#pragma omp parallel num_threads(34)
{
vector<float> descriptor_result;
#pragma omp for schedule(dynamic,rows/50)
for (int x = 3; x < (img.cols-3-hog.winSize.width); x++)
{
for (int y = 3; y < (img.rows-3-hog.winSize.height); y++)
{
Rect roi(x,y,hog.winSize.width,hog.winSize.height);
Mat crop = img(roi);
hog.compute(crop,descriptor_result);
Mat crop_hog = Mat(1,descriptor_result.size(),CV_32FC1);
for (int i = 0; i < descriptor_result.size(); i++)
{
crop_hog.at<float>(0,i) = descriptor_result[i];
}
float result = sig.EvaluateSigmoid(SVM.predict(crop_hog,true));
#pragma omp critical
matrix[y-3][x-3] = (double)result;
}
}
}
NeighbourhoodMatrix neighbourhood_matrix(matrix);
return neighbourhood_matrix;
}
NeighbourhoodMatrix Detectors::HOGSVMDetectPrint(string filename, string svm_model, Sigmoid sig)
{
this->SVM.load(svm_model.c_str());
return HOGSVMDetectPrint(filename, sig);
}
//Deteccion con SVM bucle
void Detectors::HOGSVMDetectBucleShow(string img_filename_list)
{
ifstream img_filename(img_filename_list);
string img_filename_line;
Mat img;
namedWindow("People Detector", 1);
while(getline(img_filename, img_filename_line)) {
img = HOGSVMDetectShow(img_filename_line);
imshow("People Detector", img);
int c = waitKey(0) & 255;
if( c == 'q' || c == 'Q')
break;
}
}
void Detectors::HOGSVMDetectBuclePrint(string img_filename_list, string folder, Sigmoid sig)
{
ifstream img_filename(img_filename_list);
string img_filename_line;
while(getline(img_filename, img_filename_line)) {
NeighbourhoodMatrix neighbourhood_matrix(HOGSVMDetectPrint(img_filename_line, sig));
img_filename_line.erase(img_filename_line.find_last_of("."), string::npos);
img_filename_line.erase(0,img_filename_line.find_last_of("/")+1);
string file = folder+img_filename_line+boost::lexical_cast<string>(".mat");
neighbourhood_matrix.WriteNeigbourhoodMatrix(file);
cout << file << endl;
}
}
//Deteccion con HOG + Adaboost unitaria
Mat Detectors::HOGAdaboostDetectShow(string filename)
{
Mat img;
img = imread(filename);
if(!img.data)
return img;
vector<float> descriptor_result;
for (int x = 3; x < (img.cols-3-hog.winSize.width); x++)
{
for (int y = 3; y < (img.rows-3-hog.winSize.height); y++)
{
Rect roi(x,y,hog.winSize.width,hog.winSize.height);
Mat crop = img(roi);
hog.compute(crop,descriptor_result);
Mat crop_hog = Mat(1,descriptor_result.size(),CV_32FC1);
for (int i = 0; i < descriptor_result.size(); i++)
{
crop_hog.at<float>(0,i) = descriptor_result[i];
}
float result = boost.predict(crop_hog,Mat(),Range::all(),false,true);
Point ce = Point((roi.tl().x+roi.br().x)/2,(roi.tl().y+roi.br().y)/2);
line( img, ce,ce, Scalar(0, 0, 255*result),1,8);
//rectangle(img, roi.tl(), roi.br(), cv::Scalar(0,255*result,0), 1);
}
}
return img;
}
//Deteccion con HOG + SVM unitaria
Mat Detectors::HOGAdaboostDetectShow(string filename, string boost_model)
{
this->boost.load(boost_model.c_str());
return HOGAdaboostDetectShow(filename);
}
//
NeighbourhoodMatrix Detectors::HOGAdaboostDetectPrint(string filename, Sigmoid sig)
{
Mat img;
img = imread(filename);
NeighbourhoodMatrix null_matrix;
if(!img.data)
return null_matrix;
int rows = img.rows-6-hog.winSize.height;
int cols = img.cols-6-hog.winSize.width;
vector<vector<double>> matrix = vector<vector<double>>(rows, vector<double>(cols,0.0));
#pragma omp parallel num_threads(34)
{
vector<float> descriptor_result;
#pragma omp for schedule(dynamic,rows/50)
for (int x = 3; x < (img.cols-3-hog.winSize.width); x++)
{
for (int y = 3; y < (img.rows-3-hog.winSize.height); y++)
{
Rect roi(x,y,hog.winSize.width,hog.winSize.height);
Mat crop = img(roi);
hog.compute(crop,descriptor_result);
Mat crop_hog = Mat(1,descriptor_result.size(),CV_32FC1);
for (int i = 0; i < descriptor_result.size(); i++)
{
crop_hog.at<float>(0,i) = descriptor_result[i];
}
float result = sig.EvaluateSigmoid(boost.predict(crop_hog,Mat(),Range::all(),false,true));
#pragma omp critical
matrix[y-3][x-3] = (double)result;
}
}
}
NeighbourhoodMatrix neighbourhood_matrix(matrix);
return neighbourhood_matrix;
}
NeighbourhoodMatrix Detectors::HOGAdaboostDetectPrint(string filename, string boost_model, Sigmoid sig)
{
this->boost.load(boost_model.c_str());
return HOGAdaboostDetectPrint(filename, sig);
}
//Deteccion con SVM bucle
void Detectors::HOGAdaboostDetectBucleShow(string img_filename_list)
{
ifstream img_filename(img_filename_list);
string img_filename_line;
Mat img;
namedWindow("People Detector", 1);
while(getline(img_filename, img_filename_line)) {
img = HOGAdaboostDetectShow(img_filename_line);
imshow("People Detector", img);
int c = waitKey(0) & 255;
if( c == 'q' || c == 'Q')
break;
}
}
void Detectors::HOGAdaboostDetectBuclePrint(string img_filename_list,string folder, Sigmoid sig)
{
ifstream img_filename(img_filename_list);
string img_filename_line;
while(getline(img_filename, img_filename_line)) {
NeighbourhoodMatrix neighbourhood_matrix(HOGAdaboostDetectPrint(img_filename_line, sig));
img_filename_line.erase(img_filename_line.find_last_of("."), string::npos);
img_filename_line.erase(0,img_filename_line.find_last_of("/")+1);
string file = folder+img_filename_line+boost::lexical_cast<string>(".mat");
neighbourhood_matrix.WriteNeigbourhoodMatrix(file);
cout << file << endl;
}
}
<|endoftext|>
|
<commit_before>#ifndef CINSERT_ITERATOR
#define CINSERT_ITERATOR
#include<iterator>
#include<memory> //addressof
#include<utility> //declval, move
namespace nTool
{
template<class T,class Holder,class RefFunc_t,RefFunc_t RefFunc,class MoveFunc_t=RefFunc_t,MoveFunc_t MoveFunc=RefFunc>
class CInsert_iterator:public std::iterator<std::output_iterator_tag,void,void,void,void>
{
Holder *hold_;
public:
using holder_type=Holder;
using value_type=T;
explicit CInsert_iterator(Holder &hold) noexcept
:hold_{std::addressof(hold)}{}
inline CInsert_iterator& operator*() noexcept
{
return *this;
}
inline CInsert_iterator& operator++() noexcept
{
return *this;
}
inline CInsert_iterator& operator++(const int) noexcept
{
return *this;
}
CInsert_iterator& operator=(const value_type &val) noexcept(noexcept((std::declval<Holder>().*RefFunc)(std::declval<value_type&>())))
{
(hold_->*RefFunc)(val);
return *this;
}
CInsert_iterator& operator=(value_type &&val) noexcept(noexcept((std::declval<Holder>().*MoveFunc)(std::declval<value_type>())))
{
(hold_->*MoveFunc)(std::move(val));
return *this;
}
};
template<class T,class RefFunc_t,RefFunc_t RefFunc,class MoveFunc_t,MoveFunc_t MoveFunc,class Holder>
inline CInsert_iterator<T,Holder,RefFunc_t,RefFunc,MoveFunc_t,MoveFunc> inserter(Holder &holder)
{
return CInsert_iterator<T,Holder,RefFunc_t,RefFunc,MoveFunc_t,MoveFunc>{holder};
}
template<class T,class RefFunc_t,RefFunc_t RefFunc,class Holder>
inline CInsert_iterator<T,Holder,RefFunc_t,RefFunc> inserter(Holder &holder)
{
return CInsert_iterator<T,Holder,RefFunc_t,RefFunc>{holder};
}
}
#endif<commit_msg>fix type name<commit_after>#ifndef CINSERT_ITERATOR
#define CINSERT_ITERATOR
#include<iterator>
#include<memory> //addressof
#include<utility> //declval, move
namespace nTool
{
template<class T,class Holder,class RefFunc_t,RefFunc_t RefFunc,class MoveFunc_t=RefFunc_t,MoveFunc_t MoveFunc=RefFunc>
class CInsert_iterator:public std::iterator<std::output_iterator_tag,void,void,void,void>
{
Holder *hold_;
public:
using holder_type=Holder;
using value_type=T;
explicit CInsert_iterator(holder_type &hold) noexcept
:hold_{std::addressof(hold)}{}
inline CInsert_iterator& operator*() noexcept
{
return *this;
}
inline CInsert_iterator& operator++() noexcept
{
return *this;
}
inline CInsert_iterator& operator++(const int) noexcept
{
return *this;
}
CInsert_iterator& operator=(const value_type &val) noexcept(noexcept((std::declval<holder_type>().*RefFunc)(std::declval<value_type&>())))
{
(hold_->*RefFunc)(val);
return *this;
}
CInsert_iterator& operator=(value_type &&val) noexcept(noexcept((std::declval<holder_type>().*MoveFunc)(std::declval<value_type>())))
{
(hold_->*MoveFunc)(std::move(val));
return *this;
}
};
template<class T,class RefFunc_t,RefFunc_t RefFunc,class MoveFunc_t,MoveFunc_t MoveFunc,class Holder>
inline CInsert_iterator<T,Holder,RefFunc_t,RefFunc,MoveFunc_t,MoveFunc> inserter(Holder &holder)
{
return CInsert_iterator<T,Holder,RefFunc_t,RefFunc,MoveFunc_t,MoveFunc>{holder};
}
template<class T,class RefFunc_t,RefFunc_t RefFunc,class Holder>
inline CInsert_iterator<T,Holder,RefFunc_t,RefFunc> inserter(Holder &holder)
{
return CInsert_iterator<T,Holder,RefFunc_t,RefFunc>{holder};
}
}
#endif<|endoftext|>
|
<commit_before>#include "../utils/utils.hpp"
#include <stdint.h>
#include <ctime>
Rand randgen(time(NULL));
// From Numerical Recipes
static const uint64_t Mul = 2685821657736338717LL;
static const uint64_t Vini = 4101842887655102017LL;
static const double Fl = 5.42101086242752217e-20;
Rand::Rand(unsigned long seed) : theseed(seed) {
v = Vini ^ seed;
v = bits();
}
unsigned long Rand::bits(void)
{
v ^= v >> 21;
v ^= v << 35;
v ^= v >> 4;
v *= Mul;
return v;
}
long Rand::integer(long min, long max)
{
if (min == max)
return min;
return bits() % ((max+1) - min) + min;
}
double Rand::real(void) {
return bits() * Fl;
}<commit_msg>utils: initialize randgen's seed with a finer-grained time.<commit_after>#include "../utils/utils.hpp"
#include <stdint.h>
#include <ctime>
Rand randgen(walltime() * 1e9);
// From Numerical Recipes
static const uint64_t Mul = 2685821657736338717LL;
static const uint64_t Vini = 4101842887655102017LL;
static const double Fl = 5.42101086242752217e-20;
Rand::Rand(unsigned long seed) : theseed(seed) {
v = Vini ^ seed;
v = bits();
}
unsigned long Rand::bits(void)
{
v ^= v >> 21;
v ^= v << 35;
v ^= v >> 4;
v *= Mul;
return v;
}
long Rand::integer(long min, long max)
{
if (min == max)
return min;
return bits() % ((max+1) - min) + min;
}
double Rand::real(void) {
return bits() * Fl;
}<|endoftext|>
|
<commit_before>/****************************************************************************
**
** Copyright (C) 2012 Digia Plc and/or its subsidiary(-ies).
** Contact: http://www.qt-project.org/legal
**
** This file is part of Qt Creator.
**
** Commercial License Usage
** Licensees holding valid commercial Qt licenses may use this file in
** accordance with the commercial license agreement provided with the
** Software or, alternatively, in accordance with the terms contained in
** a written agreement between you and Digia. For licensing terms and
** conditions see http://qt.digia.com/licensing. For further information
** use the contact form at http://qt.digia.com/contact-us.
**
** GNU Lesser General Public License Usage
** Alternatively, this file may be used under the terms of the GNU Lesser
** General Public License version 2.1 as published by the Free Software
** Foundation and appearing in the file LICENSE.LGPL included in the
** packaging of this file. Please review the following information to
** ensure the GNU Lesser General Public License version 2.1 requirements
** will be met: http://www.gnu.org/licenses/old-licenses/lgpl-2.1.html.
**
** In addition, as a special exception, Digia gives you certain additional
** rights. These rights are described in the Digia Qt LGPL Exception
** version 1.1, included in the file LGPL_EXCEPTION.txt in this package.
**
****************************************************************************/
#include "tarpackagecreationstep.h"
#include "remotelinuxdeployconfiguration.h"
#include <projectexplorer/deploymentdata.h>
#include <projectexplorer/project.h>
#include <projectexplorer/target.h>
#include <QDateTime>
#include <QDir>
#include <QFile>
#include <QFileInfo>
#include <cstring>
using namespace ProjectExplorer;
namespace RemoteLinux {
namespace {
class CreateTarStepWidget : public SimpleBuildStepConfigWidget
{
Q_OBJECT
public:
CreateTarStepWidget(TarPackageCreationStep *step) : SimpleBuildStepConfigWidget(step)
{
connect(step, SIGNAL(packageFilePathChanged()), SIGNAL(updateSummary()));
}
QString summaryText() const
{
TarPackageCreationStep * const step = qobject_cast<TarPackageCreationStep *>(this->step());
if (step->packageFilePath().isEmpty()) {
return QLatin1String("<font color=\"red\">")
+ tr("Tarball creation not possible.") + QLatin1String("</font>");
}
return QLatin1String("<b>") + tr("Create tarball:") + QLatin1String("</b> ")
+ step->packageFilePath();
}
};
const int TarBlockSize = 512;
struct TarFileHeader {
char fileName[100];
char fileMode[8];
char uid[8];
char gid[8];
char length[12];
char mtime[12];
char chksum[8];
char typeflag;
char linkname[100];
char magic[6];
char version[2];
char uname[32];
char gname[32];
char devmajor[8];
char devminor[8];
char fileNamePrefix[155];
char padding[12];
};
} // Anonymous namespace.
TarPackageCreationStep::TarPackageCreationStep(BuildStepList *bsl)
: AbstractPackagingStep(bsl, stepId())
{
ctor();
}
TarPackageCreationStep::TarPackageCreationStep(BuildStepList *bsl, TarPackageCreationStep *other)
: AbstractPackagingStep(bsl, other)
{
ctor();
}
void TarPackageCreationStep::ctor()
{
setDefaultDisplayName(displayName());
}
bool TarPackageCreationStep::init()
{
if (!AbstractPackagingStep::init())
return false;
m_packagingNeeded = isPackagingNeeded();
if (m_packagingNeeded)
m_files = target()->deploymentData().allFiles();
return true;
}
void TarPackageCreationStep::run(QFutureInterface<bool> &fi)
{
setPackagingStarted();
const bool success = doPackage(fi);
setPackagingFinished(success);
if (success)
emit addOutput(tr("Packaging finished successfully."), MessageOutput);
else
emit addOutput(tr("Packaging failed."), ErrorMessageOutput);
fi.reportResult(success);
}
bool TarPackageCreationStep::doPackage(QFutureInterface<bool> &fi)
{
emit addOutput(tr("Creating tarball..."), MessageOutput);
if (!m_packagingNeeded) {
emit addOutput(tr("Tarball up to date, skipping packaging."), MessageOutput);
return true;
}
// TODO: Optimization: Only package changed files
QFile tarFile(cachedPackageFilePath());
if (!tarFile.open(QIODevice::WriteOnly | QIODevice::Truncate)) {
raiseError(tr("Error: tar file %1 cannot be opened (%2).")
.arg(QDir::toNativeSeparators(cachedPackageFilePath()), tarFile.errorString()));
return false;
}
foreach (const DeployableFile &d, m_files) {
if (d.remoteDirectory().isEmpty()) {
emit addOutput(tr("No remote path specified for file '%1', skipping.")
.arg(d.localFilePath().toUserOutput()), ErrorMessageOutput);
continue;
}
QFileInfo fileInfo = d.localFilePath().toFileInfo();
if (!appendFile(tarFile, fileInfo, d.remoteDirectory() + QLatin1Char('/')
+ fileInfo.fileName(), fi)) {
return false;
}
}
const QByteArray eofIndicator(2*sizeof(TarFileHeader), 0);
if (tarFile.write(eofIndicator) != eofIndicator.length()) {
raiseError(tr("Error writing tar file '%1': %2.")
.arg(QDir::toNativeSeparators(tarFile.fileName()), tarFile.errorString()));
return false;
}
return true;
}
bool TarPackageCreationStep::appendFile(QFile &tarFile, const QFileInfo &fileInfo,
const QString &remoteFilePath, const QFutureInterface<bool> &fi)
{
if (!writeHeader(tarFile, fileInfo, remoteFilePath))
return false;
if (fileInfo.isDir()) {
QDir dir(fileInfo.absoluteFilePath());
foreach (const QString &fileName,
dir.entryList(QDir::Dirs | QDir::Files | QDir::NoDotAndDotDot)) {
const QString thisLocalFilePath = dir.path() + QLatin1Char('/') + fileName;
const QString thisRemoteFilePath = remoteFilePath + QLatin1Char('/') + fileName;
if (!appendFile(tarFile, QFileInfo(thisLocalFilePath), thisRemoteFilePath, fi))
return false;
}
return true;
}
const QString nativePath = QDir::toNativeSeparators(fileInfo.filePath());
QFile file(fileInfo.filePath());
if (!file.open(QIODevice::ReadOnly)) {
raiseError(tr("Error reading file '%1': %2.").arg(nativePath, file.errorString()));
return false;
}
const int chunkSize = 1024*1024;
emit addOutput(tr("Adding file '%1' to tarball...").arg(nativePath), MessageOutput);
// TODO: Wasteful. Work with fixed-size buffer.
while (!file.atEnd() && !file.error() != QFile::NoError && !tarFile.error() != QFile::NoError) {
const QByteArray data = file.read(chunkSize);
tarFile.write(data);
if (fi.isCanceled())
return false;
}
if (file.error() != QFile::NoError) {
raiseError(tr("Error reading file '%1': %2.").arg(nativePath, file.errorString()));
return false;
}
const int blockModulo = file.size() % TarBlockSize;
if (blockModulo != 0)
tarFile.write(QByteArray(TarBlockSize - blockModulo, 0));
if (tarFile.error() != QFile::NoError) {
raiseError(tr("Error writing tar file '%1': %2.")
.arg(QDir::toNativeSeparators(tarFile.fileName()), tarFile.errorString()));
return false;
}
return true;
}
bool TarPackageCreationStep::writeHeader(QFile &tarFile, const QFileInfo &fileInfo,
const QString &remoteFilePath)
{
TarFileHeader header;
std::memset(&header, '\0', sizeof header);
const QByteArray &filePath = remoteFilePath.toUtf8();
const int maxFilePathLength = sizeof header.fileNamePrefix + sizeof header.fileName;
if (filePath.count() > maxFilePathLength) {
raiseError(tr("Cannot add file '%1' to tar-archive: path too long.")
.arg(QDir::toNativeSeparators(remoteFilePath)));
return false;
}
const int fileNameBytesToWrite = qMin<int>(filePath.length(), sizeof header.fileName);
const int fileNameOffset = filePath.length() - fileNameBytesToWrite;
std::memcpy(&header.fileName, filePath.data() + fileNameOffset, fileNameBytesToWrite);
if (fileNameOffset > 0)
std::memcpy(&header.fileNamePrefix, filePath.data(), fileNameOffset);
int permissions = (0400 * fileInfo.permission(QFile::ReadOwner))
| (0200 * fileInfo.permission(QFile::WriteOwner))
| (0100 * fileInfo.permission(QFile::ExeOwner))
| (040 * fileInfo.permission(QFile::ReadGroup))
| (020 * fileInfo.permission(QFile::WriteGroup))
| (010 * fileInfo.permission(QFile::ExeGroup))
| (04 * fileInfo.permission(QFile::ReadOther))
| (02 * fileInfo.permission(QFile::WriteOther))
| (01 * fileInfo.permission(QFile::ExeOther));
const QByteArray permissionString = QString::fromLatin1("%1").arg(permissions,
sizeof header.fileMode - 1, 8, QLatin1Char('0')).toLatin1();
std::memcpy(&header.fileMode, permissionString.data(), permissionString.length());
const QByteArray uidString = QString::fromLatin1("%1").arg(fileInfo.ownerId(),
sizeof header.uid - 1, 8, QLatin1Char('0')).toLatin1();
std::memcpy(&header.uid, uidString.data(), uidString.length());
const QByteArray gidString = QString::fromLatin1("%1").arg(fileInfo.groupId(),
sizeof header.gid - 1, 8, QLatin1Char('0')).toLatin1();
std::memcpy(&header.gid, gidString.data(), gidString.length());
const QByteArray sizeString = QString::fromLatin1("%1").arg(fileInfo.size(),
sizeof header.length - 1, 8, QLatin1Char('0')).toLatin1();
std::memcpy(&header.length, sizeString.data(), sizeString.length());
const QByteArray mtimeString = QString::fromLatin1("%1").arg(fileInfo.lastModified().toTime_t(),
sizeof header.mtime - 1, 8, QLatin1Char('0')).toLatin1();
std::memcpy(&header.mtime, mtimeString.data(), mtimeString.length());
if (fileInfo.isDir())
header.typeflag = '5';
std::memcpy(&header.magic, "ustar", sizeof "ustar");
std::memcpy(&header.version, "00", 2);
const QByteArray &owner = fileInfo.owner().toUtf8();
std::memcpy(&header.uname, owner.data(), qMin<int>(owner.length(), sizeof header.uname - 1));
const QByteArray &group = fileInfo.group().toUtf8();
std::memcpy(&header.gname, group.data(), qMin<int>(group.length(), sizeof header.gname - 1));
std::memset(&header.chksum, ' ', sizeof header.chksum);
quint64 checksum = 0;
for (size_t i = 0; i < sizeof header; ++i)
checksum += reinterpret_cast<char *>(&header)[i];
const QByteArray checksumString = QString::fromLatin1("%1").arg(checksum,
sizeof header.chksum - 1, 8, QLatin1Char('0')).toLatin1();
std::memcpy(&header.chksum, checksumString.data(), checksumString.length());
header.chksum[sizeof header.chksum-1] = 0;
if (!tarFile.write(reinterpret_cast<char *>(&header), sizeof header)) {
raiseError(tr("Error writing tar file '%1': %2")
.arg(QDir::toNativeSeparators(cachedPackageFilePath()), tarFile.errorString()));
return false;
}
return true;
}
QString TarPackageCreationStep::packageFileName() const
{
return project()->displayName() + QLatin1String(".tar");
}
BuildStepConfigWidget *TarPackageCreationStep::createConfigWidget()
{
return new CreateTarStepWidget(this);
}
Core::Id TarPackageCreationStep::stepId()
{
return Core::Id("MaemoTarPackageCreationStep");
}
QString TarPackageCreationStep::displayName()
{
return tr("Create tarball");
}
} // namespace RemoteLinux
#include "tarpackagecreationstep.moc"
<commit_msg>TarPackageCreationStep: Use static_cast not qobject_cast<commit_after>/****************************************************************************
**
** Copyright (C) 2012 Digia Plc and/or its subsidiary(-ies).
** Contact: http://www.qt-project.org/legal
**
** This file is part of Qt Creator.
**
** Commercial License Usage
** Licensees holding valid commercial Qt licenses may use this file in
** accordance with the commercial license agreement provided with the
** Software or, alternatively, in accordance with the terms contained in
** a written agreement between you and Digia. For licensing terms and
** conditions see http://qt.digia.com/licensing. For further information
** use the contact form at http://qt.digia.com/contact-us.
**
** GNU Lesser General Public License Usage
** Alternatively, this file may be used under the terms of the GNU Lesser
** General Public License version 2.1 as published by the Free Software
** Foundation and appearing in the file LICENSE.LGPL included in the
** packaging of this file. Please review the following information to
** ensure the GNU Lesser General Public License version 2.1 requirements
** will be met: http://www.gnu.org/licenses/old-licenses/lgpl-2.1.html.
**
** In addition, as a special exception, Digia gives you certain additional
** rights. These rights are described in the Digia Qt LGPL Exception
** version 1.1, included in the file LGPL_EXCEPTION.txt in this package.
**
****************************************************************************/
#include "tarpackagecreationstep.h"
#include "remotelinuxdeployconfiguration.h"
#include <projectexplorer/deploymentdata.h>
#include <projectexplorer/project.h>
#include <projectexplorer/target.h>
#include <QDateTime>
#include <QDir>
#include <QFile>
#include <QFileInfo>
#include <cstring>
using namespace ProjectExplorer;
namespace RemoteLinux {
namespace {
class CreateTarStepWidget : public SimpleBuildStepConfigWidget
{
Q_OBJECT
public:
CreateTarStepWidget(TarPackageCreationStep *step) : SimpleBuildStepConfigWidget(step)
{
connect(step, SIGNAL(packageFilePathChanged()), SIGNAL(updateSummary()));
}
QString summaryText() const
{
TarPackageCreationStep * const step = static_cast<TarPackageCreationStep *>(this->step());
if (step->packageFilePath().isEmpty()) {
return QLatin1String("<font color=\"red\">")
+ tr("Tarball creation not possible.") + QLatin1String("</font>");
}
return QLatin1String("<b>") + tr("Create tarball:") + QLatin1String("</b> ")
+ step->packageFilePath();
}
};
const int TarBlockSize = 512;
struct TarFileHeader {
char fileName[100];
char fileMode[8];
char uid[8];
char gid[8];
char length[12];
char mtime[12];
char chksum[8];
char typeflag;
char linkname[100];
char magic[6];
char version[2];
char uname[32];
char gname[32];
char devmajor[8];
char devminor[8];
char fileNamePrefix[155];
char padding[12];
};
} // Anonymous namespace.
TarPackageCreationStep::TarPackageCreationStep(BuildStepList *bsl)
: AbstractPackagingStep(bsl, stepId())
{
ctor();
}
TarPackageCreationStep::TarPackageCreationStep(BuildStepList *bsl, TarPackageCreationStep *other)
: AbstractPackagingStep(bsl, other)
{
ctor();
}
void TarPackageCreationStep::ctor()
{
setDefaultDisplayName(displayName());
}
bool TarPackageCreationStep::init()
{
if (!AbstractPackagingStep::init())
return false;
m_packagingNeeded = isPackagingNeeded();
if (m_packagingNeeded)
m_files = target()->deploymentData().allFiles();
return true;
}
void TarPackageCreationStep::run(QFutureInterface<bool> &fi)
{
setPackagingStarted();
const bool success = doPackage(fi);
setPackagingFinished(success);
if (success)
emit addOutput(tr("Packaging finished successfully."), MessageOutput);
else
emit addOutput(tr("Packaging failed."), ErrorMessageOutput);
fi.reportResult(success);
}
bool TarPackageCreationStep::doPackage(QFutureInterface<bool> &fi)
{
emit addOutput(tr("Creating tarball..."), MessageOutput);
if (!m_packagingNeeded) {
emit addOutput(tr("Tarball up to date, skipping packaging."), MessageOutput);
return true;
}
// TODO: Optimization: Only package changed files
QFile tarFile(cachedPackageFilePath());
if (!tarFile.open(QIODevice::WriteOnly | QIODevice::Truncate)) {
raiseError(tr("Error: tar file %1 cannot be opened (%2).")
.arg(QDir::toNativeSeparators(cachedPackageFilePath()), tarFile.errorString()));
return false;
}
foreach (const DeployableFile &d, m_files) {
if (d.remoteDirectory().isEmpty()) {
emit addOutput(tr("No remote path specified for file '%1', skipping.")
.arg(d.localFilePath().toUserOutput()), ErrorMessageOutput);
continue;
}
QFileInfo fileInfo = d.localFilePath().toFileInfo();
if (!appendFile(tarFile, fileInfo, d.remoteDirectory() + QLatin1Char('/')
+ fileInfo.fileName(), fi)) {
return false;
}
}
const QByteArray eofIndicator(2*sizeof(TarFileHeader), 0);
if (tarFile.write(eofIndicator) != eofIndicator.length()) {
raiseError(tr("Error writing tar file '%1': %2.")
.arg(QDir::toNativeSeparators(tarFile.fileName()), tarFile.errorString()));
return false;
}
return true;
}
bool TarPackageCreationStep::appendFile(QFile &tarFile, const QFileInfo &fileInfo,
const QString &remoteFilePath, const QFutureInterface<bool> &fi)
{
if (!writeHeader(tarFile, fileInfo, remoteFilePath))
return false;
if (fileInfo.isDir()) {
QDir dir(fileInfo.absoluteFilePath());
foreach (const QString &fileName,
dir.entryList(QDir::Dirs | QDir::Files | QDir::NoDotAndDotDot)) {
const QString thisLocalFilePath = dir.path() + QLatin1Char('/') + fileName;
const QString thisRemoteFilePath = remoteFilePath + QLatin1Char('/') + fileName;
if (!appendFile(tarFile, QFileInfo(thisLocalFilePath), thisRemoteFilePath, fi))
return false;
}
return true;
}
const QString nativePath = QDir::toNativeSeparators(fileInfo.filePath());
QFile file(fileInfo.filePath());
if (!file.open(QIODevice::ReadOnly)) {
raiseError(tr("Error reading file '%1': %2.").arg(nativePath, file.errorString()));
return false;
}
const int chunkSize = 1024*1024;
emit addOutput(tr("Adding file '%1' to tarball...").arg(nativePath), MessageOutput);
// TODO: Wasteful. Work with fixed-size buffer.
while (!file.atEnd() && !file.error() != QFile::NoError && !tarFile.error() != QFile::NoError) {
const QByteArray data = file.read(chunkSize);
tarFile.write(data);
if (fi.isCanceled())
return false;
}
if (file.error() != QFile::NoError) {
raiseError(tr("Error reading file '%1': %2.").arg(nativePath, file.errorString()));
return false;
}
const int blockModulo = file.size() % TarBlockSize;
if (blockModulo != 0)
tarFile.write(QByteArray(TarBlockSize - blockModulo, 0));
if (tarFile.error() != QFile::NoError) {
raiseError(tr("Error writing tar file '%1': %2.")
.arg(QDir::toNativeSeparators(tarFile.fileName()), tarFile.errorString()));
return false;
}
return true;
}
bool TarPackageCreationStep::writeHeader(QFile &tarFile, const QFileInfo &fileInfo,
const QString &remoteFilePath)
{
TarFileHeader header;
std::memset(&header, '\0', sizeof header);
const QByteArray &filePath = remoteFilePath.toUtf8();
const int maxFilePathLength = sizeof header.fileNamePrefix + sizeof header.fileName;
if (filePath.count() > maxFilePathLength) {
raiseError(tr("Cannot add file '%1' to tar-archive: path too long.")
.arg(QDir::toNativeSeparators(remoteFilePath)));
return false;
}
const int fileNameBytesToWrite = qMin<int>(filePath.length(), sizeof header.fileName);
const int fileNameOffset = filePath.length() - fileNameBytesToWrite;
std::memcpy(&header.fileName, filePath.data() + fileNameOffset, fileNameBytesToWrite);
if (fileNameOffset > 0)
std::memcpy(&header.fileNamePrefix, filePath.data(), fileNameOffset);
int permissions = (0400 * fileInfo.permission(QFile::ReadOwner))
| (0200 * fileInfo.permission(QFile::WriteOwner))
| (0100 * fileInfo.permission(QFile::ExeOwner))
| (040 * fileInfo.permission(QFile::ReadGroup))
| (020 * fileInfo.permission(QFile::WriteGroup))
| (010 * fileInfo.permission(QFile::ExeGroup))
| (04 * fileInfo.permission(QFile::ReadOther))
| (02 * fileInfo.permission(QFile::WriteOther))
| (01 * fileInfo.permission(QFile::ExeOther));
const QByteArray permissionString = QString::fromLatin1("%1").arg(permissions,
sizeof header.fileMode - 1, 8, QLatin1Char('0')).toLatin1();
std::memcpy(&header.fileMode, permissionString.data(), permissionString.length());
const QByteArray uidString = QString::fromLatin1("%1").arg(fileInfo.ownerId(),
sizeof header.uid - 1, 8, QLatin1Char('0')).toLatin1();
std::memcpy(&header.uid, uidString.data(), uidString.length());
const QByteArray gidString = QString::fromLatin1("%1").arg(fileInfo.groupId(),
sizeof header.gid - 1, 8, QLatin1Char('0')).toLatin1();
std::memcpy(&header.gid, gidString.data(), gidString.length());
const QByteArray sizeString = QString::fromLatin1("%1").arg(fileInfo.size(),
sizeof header.length - 1, 8, QLatin1Char('0')).toLatin1();
std::memcpy(&header.length, sizeString.data(), sizeString.length());
const QByteArray mtimeString = QString::fromLatin1("%1").arg(fileInfo.lastModified().toTime_t(),
sizeof header.mtime - 1, 8, QLatin1Char('0')).toLatin1();
std::memcpy(&header.mtime, mtimeString.data(), mtimeString.length());
if (fileInfo.isDir())
header.typeflag = '5';
std::memcpy(&header.magic, "ustar", sizeof "ustar");
std::memcpy(&header.version, "00", 2);
const QByteArray &owner = fileInfo.owner().toUtf8();
std::memcpy(&header.uname, owner.data(), qMin<int>(owner.length(), sizeof header.uname - 1));
const QByteArray &group = fileInfo.group().toUtf8();
std::memcpy(&header.gname, group.data(), qMin<int>(group.length(), sizeof header.gname - 1));
std::memset(&header.chksum, ' ', sizeof header.chksum);
quint64 checksum = 0;
for (size_t i = 0; i < sizeof header; ++i)
checksum += reinterpret_cast<char *>(&header)[i];
const QByteArray checksumString = QString::fromLatin1("%1").arg(checksum,
sizeof header.chksum - 1, 8, QLatin1Char('0')).toLatin1();
std::memcpy(&header.chksum, checksumString.data(), checksumString.length());
header.chksum[sizeof header.chksum-1] = 0;
if (!tarFile.write(reinterpret_cast<char *>(&header), sizeof header)) {
raiseError(tr("Error writing tar file '%1': %2")
.arg(QDir::toNativeSeparators(cachedPackageFilePath()), tarFile.errorString()));
return false;
}
return true;
}
QString TarPackageCreationStep::packageFileName() const
{
return project()->displayName() + QLatin1String(".tar");
}
BuildStepConfigWidget *TarPackageCreationStep::createConfigWidget()
{
return new CreateTarStepWidget(this);
}
Core::Id TarPackageCreationStep::stepId()
{
return Core::Id("MaemoTarPackageCreationStep");
}
QString TarPackageCreationStep::displayName()
{
return tr("Create tarball");
}
} // namespace RemoteLinux
#include "tarpackagecreationstep.moc"
<|endoftext|>
|
<commit_before>/**************************************************************************
**
** This file is part of Qt Creator
**
** Copyright (c) 2010 Nokia Corporation and/or its subsidiary(-ies).
**
** Contact: Nokia Corporation (qt-info@nokia.com)
**
** Commercial Usage
**
** Licensees holding valid Qt Commercial licenses may use this file in
** accordance with the Qt Commercial License Agreement provided with the
** Software or, alternatively, in accordance with the terms contained in
** a written agreement between you and Nokia.
**
** GNU Lesser General Public License Usage
**
** Alternatively, this file may be used under the terms of the GNU Lesser
** General Public License version 2.1 as published by the Free Software
** Foundation and appearing in the file LICENSE.LGPL included in the
** packaging of this file. Please review the following information to
** ensure the GNU Lesser General Public License version 2.1 requirements
** will be met: http://www.gnu.org/licenses/old-licenses/lgpl-2.1.html.
**
** If you are unsure which license is appropriate for your use, please
** contact the sales department at http://qt.nokia.com/contact.
**
**************************************************************************/
#include "communitywelcomepagewidget.h"
#include "ui_communitywelcomepagewidget.h"
#include "rssfetcher.h"
#include <QtCore/QMap>
#include <QtCore/QUrl>
#include <QtGui/QDesktopServices>
#include <QtGui/QTreeWidgetItem>
struct Site {
const char *description;
const char *url;
};
static const Site supportSites[] = {
{ QT_TRANSLATE_NOOP("Welcome::Internal::CommunityWelcomePageWidget",
"<b>Forum Nokia</b><br /><font color='gray'>Mobile Application Support</font>"),
"http://www.forum.nokia.com/I_Want_To/Develop_Mobile_Applications/Technical_Support/"},
{ QT_TRANSLATE_NOOP("Welcome::Internal::CommunityWelcomePageWidget",
"<b>Qt LGPL Support</b><br /><font color='gray'>Buy commercial Qt support</font>"),
"http://shop.qt.nokia.com/en/support.html"},
{ QT_TRANSLATE_NOOP("Welcome::Internal::CommunityWelcomePageWidget",
"<b>Qt Centre</b><br /><font color='gray'>Community based Qt support</font>"),
"http://www.qtcentre.org" }
};
static const Site sites[] = {
{ QT_TRANSLATE_NOOP("Welcome::Internal::CommunityWelcomePageWidget",
"<b>Qt Home</b><br /><font color='gray'>Qt by Nokia on the web</font>"),
"http://qt.nokia.com" },
{ QT_TRANSLATE_NOOP("Welcome::Internal::CommunityWelcomePageWidget",
"<b>Qt Git Hosting</b><br /><font color='gray'>Participate in Qt development</font>"),
"http://qt.gitorious.org"},
{ QT_TRANSLATE_NOOP("Welcome::Internal::CommunityWelcomePageWidget",
"<b>Qt Apps</b><br /><font color='gray'>Find free Qt-based apps</font>"),
"http://www.qt-apps.org"}
};
namespace Welcome {
namespace Internal {
static inline void populateWelcomeTreeWidget(const Site *sites, int count, Utils::WelcomeModeTreeWidget *wt)
{
for (int s = 0; s < count; s++) {
const QString description = CommunityWelcomePageWidget::tr(sites[s].description);
const QString url = QLatin1String(sites[s].url);
wt->addItem(description, url, url);
}
}
CommunityWelcomePageWidget::CommunityWelcomePageWidget(QWidget *parent) :
QWidget(parent),
m_rssFetcher(new RSSFetcher(7)),
ui(new Ui::CommunityWelcomePageWidget)
{
ui->setupUi(this);
connect(ui->newsTreeWidget, SIGNAL(activated(QString)), SLOT(slotUrlClicked(QString)));
connect(ui->miscSitesTreeWidget, SIGNAL(activated(QString)), SLOT(slotUrlClicked(QString)));
connect(ui->supportSitesTreeWidget, SIGNAL(activated(QString)), SLOT(slotUrlClicked(QString)));
connect(m_rssFetcher, SIGNAL(newsItemReady(QString, QString, QString)),
ui->newsTreeWidget, SLOT(addNewsItem(QString, QString, QString)), Qt::QueuedConnection);
connect(this, SIGNAL(startRssFetching(QUrl)), m_rssFetcher, SLOT(fetch(QUrl)), Qt::QueuedConnection);
//: Add localized feed here only if one exists
m_rssFetcher->start(QThread::LowestPriority);
emit startRssFetching(QUrl(tr("http://labs.trolltech.com/blogs/feed")));
populateWelcomeTreeWidget(supportSites, sizeof(supportSites)/sizeof(Site), ui->supportSitesTreeWidget);
populateWelcomeTreeWidget(sites, sizeof(sites)/sizeof(Site), ui->miscSitesTreeWidget);
}
CommunityWelcomePageWidget::~CommunityWelcomePageWidget()
{
m_rssFetcher->exit();
m_rssFetcher->wait();
delete m_rssFetcher;
delete ui;
}
void CommunityWelcomePageWidget::slotUrlClicked(const QString &data)
{
QDesktopServices::openUrl(QUrl(data));
}
} // namespace Internal
} // namespace Welcome
<commit_msg>Add Qt DevNet to link page, dropped QtCentre instead.<commit_after>/**************************************************************************
**
** This file is part of Qt Creator
**
** Copyright (c) 2010 Nokia Corporation and/or its subsidiary(-ies).
**
** Contact: Nokia Corporation (qt-info@nokia.com)
**
** Commercial Usage
**
** Licensees holding valid Qt Commercial licenses may use this file in
** accordance with the Qt Commercial License Agreement provided with the
** Software or, alternatively, in accordance with the terms contained in
** a written agreement between you and Nokia.
**
** GNU Lesser General Public License Usage
**
** Alternatively, this file may be used under the terms of the GNU Lesser
** General Public License version 2.1 as published by the Free Software
** Foundation and appearing in the file LICENSE.LGPL included in the
** packaging of this file. Please review the following information to
** ensure the GNU Lesser General Public License version 2.1 requirements
** will be met: http://www.gnu.org/licenses/old-licenses/lgpl-2.1.html.
**
** If you are unsure which license is appropriate for your use, please
** contact the sales department at http://qt.nokia.com/contact.
**
**************************************************************************/
#include "communitywelcomepagewidget.h"
#include "ui_communitywelcomepagewidget.h"
#include "rssfetcher.h"
#include <QtCore/QMap>
#include <QtCore/QUrl>
#include <QtGui/QDesktopServices>
#include <QtGui/QTreeWidgetItem>
struct Site {
const char *description;
const char *url;
};
static const Site supportSites[] = {
{ QT_TRANSLATE_NOOP("Welcome::Internal::CommunityWelcomePageWidget",
"<b>Forum Nokia</b><br /><font color='gray'>Mobile application support</font>"),
"http://www.forum.nokia.com/I_Want_To/Develop_Mobile_Applications/Technical_Support/"},
{ QT_TRANSLATE_NOOP("Welcome::Internal::CommunityWelcomePageWidget",
"<b>Qt LGPL Support</b><br /><font color='gray'>Buy commercial Qt support</font>"),
"http://shop.qt.nokia.com/en/support.html"},
{ QT_TRANSLATE_NOOP("Welcome::Internal::CommunityWelcomePageWidget",
"<b>Qt DevNet</b><br /><font color='gray'>Qt Developer Resources</font>"),
"http://developer.qt.nokia.com" }
};
static const Site sites[] = {
{ QT_TRANSLATE_NOOP("Welcome::Internal::CommunityWelcomePageWidget",
"<b>Qt Home</b><br /><font color='gray'>Qt by Nokia on the web</font>"),
"http://qt.nokia.com" },
{ QT_TRANSLATE_NOOP("Welcome::Internal::CommunityWelcomePageWidget",
"<b>Qt Git Hosting</b><br /><font color='gray'>Participate in Qt development</font>"),
"http://qt.gitorious.org"},
{ QT_TRANSLATE_NOOP("Welcome::Internal::CommunityWelcomePageWidget",
"<b>Qt Apps</b><br /><font color='gray'>Find free Qt-based apps</font>"),
"http://www.qt-apps.org"}
};
namespace Welcome {
namespace Internal {
static inline void populateWelcomeTreeWidget(const Site *sites, int count, Utils::WelcomeModeTreeWidget *wt)
{
for (int s = 0; s < count; s++) {
const QString description = CommunityWelcomePageWidget::tr(sites[s].description);
const QString url = QLatin1String(sites[s].url);
wt->addItem(description, url, url);
}
}
CommunityWelcomePageWidget::CommunityWelcomePageWidget(QWidget *parent) :
QWidget(parent),
m_rssFetcher(new RSSFetcher(7)),
ui(new Ui::CommunityWelcomePageWidget)
{
ui->setupUi(this);
connect(ui->newsTreeWidget, SIGNAL(activated(QString)), SLOT(slotUrlClicked(QString)));
connect(ui->miscSitesTreeWidget, SIGNAL(activated(QString)), SLOT(slotUrlClicked(QString)));
connect(ui->supportSitesTreeWidget, SIGNAL(activated(QString)), SLOT(slotUrlClicked(QString)));
connect(m_rssFetcher, SIGNAL(newsItemReady(QString, QString, QString)),
ui->newsTreeWidget, SLOT(addNewsItem(QString, QString, QString)), Qt::QueuedConnection);
connect(this, SIGNAL(startRssFetching(QUrl)), m_rssFetcher, SLOT(fetch(QUrl)), Qt::QueuedConnection);
//: Add localized feed here only if one exists
m_rssFetcher->start(QThread::LowestPriority);
emit startRssFetching(QUrl(tr("http://labs.trolltech.com/blogs/feed")));
populateWelcomeTreeWidget(supportSites, sizeof(supportSites)/sizeof(Site), ui->supportSitesTreeWidget);
populateWelcomeTreeWidget(sites, sizeof(sites)/sizeof(Site), ui->miscSitesTreeWidget);
}
CommunityWelcomePageWidget::~CommunityWelcomePageWidget()
{
m_rssFetcher->exit();
m_rssFetcher->wait();
delete m_rssFetcher;
delete ui;
}
void CommunityWelcomePageWidget::slotUrlClicked(const QString &data)
{
QDesktopServices::openUrl(QUrl(data));
}
} // namespace Internal
} // namespace Welcome
<|endoftext|>
|
<commit_before>/*
* Copyright (c) 2014, Shogun Toolbox Foundation
* All rights reserved.
*
* Redistribution and use in source and binary forms, with or without
* modification, are permitted provided that the following conditions are met:
* 1. Redistributions of source code must retain the above copyright notice,
* this list of conditions and the following disclaimer.
*
* 2. Redistributions in binary form must reproduce the above copyright notice,
* this list of conditions and the following disclaimer in the documentation
* and/or other materials provided with the distribution.
*
* 3. Neither the name of the copyright holder nor the names of its
* contributors may be used to endorse or promote products derived from this
* software without specific prior written permission.
* THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS"
* AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE
* IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE
* ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT HOLDER OR CONTRIBUTORS BE
* LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR
* CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF
* SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS
* INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN
* CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE)
* ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE
* POSSIBILITY OF SUCH DAMAGE.
*
* Written (W) 2014 Khaled Nasr
*/
#include <shogun/neuralnets/NeuralConvolutionalLayer.h>
#include <shogun/mathematics/Math.h>
#include <shogun/lib/SGVector.h>
using namespace shogun;
CNeuralConvolutionalLayer::CNeuralConvolutionalLayer() : CNeuralLayer()
{
init();
}
CNeuralConvolutionalLayer::CNeuralConvolutionalLayer(
EConvMapActivationFunction function,
int32_t num_maps,
int32_t radius_x, int32_t radius_y,
int32_t pooling_width, int32_t pooling_height,
int32_t stride_x, int32_t stride_y) : CNeuralLayer()
{
init();
m_num_maps = num_maps;
m_radius_x = radius_x;
m_radius_y = radius_y;
m_pooling_width = pooling_width;
m_pooling_height = pooling_height;
m_stride_x = stride_x;
m_stride_y = stride_y;
}
void CNeuralConvolutionalLayer::set_batch_size(int32_t batch_size)
{
CNeuralLayer::set_batch_size(batch_size);
if (autoencoder_position==NLAP_NONE)
m_convolution_output = SGMatrix<float64_t>(m_num_maps*
(m_input_width/m_stride_x)*(m_input_height/m_stride_y), batch_size);
else
m_convolution_output = SGMatrix<float64_t>(
m_num_maps*m_input_width*m_input_height, batch_size);
m_max_indices = SGMatrix<float64_t>(m_num_neurons, m_batch_size);
m_convolution_output_gradients = SGMatrix<float64_t>(
m_convolution_output.num_rows, m_convolution_output.num_cols);
}
void CNeuralConvolutionalLayer::initialize(CDynamicObjectArray* layers,
SGVector< int32_t > input_indices)
{
CNeuralLayer* first_input_layer =
(CNeuralLayer*)layers->element(input_indices[0]);
m_input_width = first_input_layer->get_width();
m_input_height = first_input_layer->get_height();
if (autoencoder_position==NLAP_NONE)
{
m_width = m_input_width/(m_stride_x*m_pooling_width);
m_height = m_input_height/(m_stride_y*m_pooling_height);
}
else
{
m_width = m_input_width;
m_height = m_input_height;
}
m_num_neurons = m_width*m_height*m_num_maps;
CNeuralLayer::initialize(layers, input_indices);
m_input_num_channels = 0;
for (int32_t l=0; l<input_indices.vlen; l++)
{
CNeuralLayer* layer =
(CNeuralLayer*)layers->element(input_indices[l]);
m_input_num_channels += layer->get_num_neurons()/(m_input_height*m_input_width);
SG_UNREF(layer);
}
// one bias for each map and one weight matrix between each map in this
// layer and each channel in the input layers
m_num_parameters =
m_num_maps*(1 + m_input_num_channels*(2*m_radius_x+1)*(2*m_radius_y+1));
}
void CNeuralConvolutionalLayer::initialize_parameters(SGVector<float64_t> parameters,
SGVector<bool> parameter_regularizable,
float64_t sigma)
{
int32_t num_parameters_per_map =
1 + m_input_num_channels*(2*m_radius_x+1)*(2*m_radius_y+1);
for (int32_t m=0; m<m_num_maps; m++)
{
float64_t* map_params = parameters.vector+m*num_parameters_per_map;
bool* map_param_regularizable =
parameter_regularizable.vector+m*num_parameters_per_map;
for (int32_t i=0; i<num_parameters_per_map; i++)
{
map_params[i] = CMath::normal_random(0.0, sigma);
// turn off regularization for the bias, on for the rest of the parameters
map_param_regularizable[i] = (i != 0);
}
}
}
void CNeuralConvolutionalLayer::compute_activations(
SGVector<float64_t> parameters,
CDynamicObjectArray* layers)
{
int32_t num_parameters_per_map =
1 + m_input_num_channels*(2*m_radius_x+1)*(2*m_radius_y+1);
for (int32_t m=0; m<m_num_maps; m++)
{
SGVector<float64_t> map_params(
parameters.vector+m*num_parameters_per_map,
num_parameters_per_map, false);
CConvolutionalFeatureMap map(m_input_width, m_input_height,
m_radius_x, m_radius_y, m_stride_x, m_stride_y, m,
m_activation_function, autoencoder_position);
map.compute_activations(map_params, layers, m_input_indices,
m_convolution_output);
map.pool_activations(m_convolution_output,
m_pooling_width, m_pooling_height, m_activations, m_max_indices);
}
}
void CNeuralConvolutionalLayer::compute_gradients(
SGVector<float64_t> parameters,
SGMatrix<float64_t> targets,
CDynamicObjectArray* layers,
SGVector<float64_t> parameter_gradients)
{
if (targets.num_rows != 0)
{
// sqaured error measure
// local_gradients = activations-targets
int32_t length = m_num_neurons*m_batch_size;
for (int32_t i=0; i<length; i++)
m_activation_gradients[i] = (m_activations[i]-targets[i])/m_batch_size;
}
if (dropout_prop>0.0)
{
int32_t len = m_num_neurons*m_batch_size;
for (int32_t i=0; i<len; i++)
m_activation_gradients[i] *= m_dropout_mask[i];
}
// compute the pre-pooling activation gradients
m_convolution_output_gradients.zero();
for (int32_t i=0; i<m_num_neurons; i++)
for (int32_t j=0; j<m_batch_size; j++)
if (m_max_indices(i,j)!=-1.0)
m_convolution_output_gradients(m_max_indices(i,j),j) =
m_activation_gradients(i,j);
int32_t num_parameters_per_map =
1 + m_input_num_channels*(2*m_radius_x+1)*(2*m_radius_y+1);
for (int32_t m=0; m<m_num_maps; m++)
{
SGVector<float64_t> map_params(
parameters.vector+m*num_parameters_per_map,
num_parameters_per_map, false);
SGVector<float64_t> map_gradients(
parameter_gradients.vector+m*num_parameters_per_map,
num_parameters_per_map, false);
CConvolutionalFeatureMap map(m_input_width, m_input_height,
m_radius_x, m_radius_y, m_stride_x, m_stride_y, m,
m_activation_function, autoencoder_position);
map.compute_gradients(map_params, m_convolution_output,
m_convolution_output_gradients, layers,
m_input_indices, map_gradients);
}
}
float64_t CNeuralConvolutionalLayer::compute_error(SGMatrix<float64_t> targets)
{
// error = 0.5*(sum(targets-activations)^2)/batch_size
float64_t sum = 0;
int32_t length = m_num_neurons*m_batch_size;
for (int32_t i=0; i<length; i++)
sum += (targets[i]-m_activations[i])*(targets[i]-m_activations[i]);
sum *= (0.5/m_batch_size);
return sum;
}
void CNeuralConvolutionalLayer::enforce_max_norm(SGVector<float64_t> parameters,
float64_t max_norm)
{
int32_t num_weights = (2*m_radius_x+1)*(2*m_radius_y+1);
int32_t num_parameters_per_map = 1 + m_input_num_channels*num_weights;
for (int32_t offset=1; offset<parameters.vlen; offset+=num_parameters_per_map)
{
float64_t* weights = parameters.vector+offset;
float64_t norm =
SGVector<float64_t>::twonorm(weights, num_weights);
if (norm > max_norm)
{
float64_t multiplier = max_norm/norm;
for (int32_t i=0; i<num_weights; i++)
weights[i] *= multiplier;
}
}
}
void CNeuralConvolutionalLayer::init()
{
m_num_maps = 1;
m_input_width = 0;
m_input_height = 0;
m_input_num_channels = 0;
m_radius_x = 0;
m_radius_y = 0;
m_pooling_width = 1;
m_pooling_height = 1;
m_stride_x = 1;
m_stride_y = 1;
m_activation_function = CMAF_IDENTITY;
SG_ADD(&m_num_maps, "num_maps", "Number of maps", MS_NOT_AVAILABLE);
SG_ADD(&m_input_width, "input_width", "Input Width", MS_NOT_AVAILABLE);
SG_ADD(&m_input_height, "input_height", "Input Height", MS_NOT_AVAILABLE);
SG_ADD(&m_input_num_channels, "input_num_channels", "Input's number of channels",
MS_NOT_AVAILABLE);
SG_ADD(&m_radius_x, "radius_x", "X Radius", MS_NOT_AVAILABLE);
SG_ADD(&m_radius_y, "radius_y", "Y Radius", MS_NOT_AVAILABLE);
SG_ADD(&m_pooling_width, "pooling_width", "Pooling Width", MS_NOT_AVAILABLE);
SG_ADD(&m_pooling_height, "pooling_height", "Pooling Height", MS_NOT_AVAILABLE);
SG_ADD(&m_stride_x, "stride_x", "X Stride", MS_NOT_AVAILABLE);
SG_ADD(&m_stride_y, "stride_y", "Y Stride", MS_NOT_AVAILABLE);
SG_ADD((machine_int_t*) &m_activation_function, "activation_function",
"Activation Function", MS_NOT_AVAILABLE);
SG_ADD(&m_convolution_output, "convolution_output",
"Convolution Output", MS_NOT_AVAILABLE);
SG_ADD(&m_convolution_output_gradients, "convolution_output_gradients",
"Convolution Output Gradients", MS_NOT_AVAILABLE);
}
<commit_msg>fixed a memory leak in CNeuralConvolutionalLayer<commit_after>/*
* Copyright (c) 2014, Shogun Toolbox Foundation
* All rights reserved.
*
* Redistribution and use in source and binary forms, with or without
* modification, are permitted provided that the following conditions are met:
* 1. Redistributions of source code must retain the above copyright notice,
* this list of conditions and the following disclaimer.
*
* 2. Redistributions in binary form must reproduce the above copyright notice,
* this list of conditions and the following disclaimer in the documentation
* and/or other materials provided with the distribution.
*
* 3. Neither the name of the copyright holder nor the names of its
* contributors may be used to endorse or promote products derived from this
* software without specific prior written permission.
* THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS"
* AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE
* IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE
* ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT HOLDER OR CONTRIBUTORS BE
* LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR
* CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF
* SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS
* INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN
* CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE)
* ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE
* POSSIBILITY OF SUCH DAMAGE.
*
* Written (W) 2014 Khaled Nasr
*/
#include <shogun/neuralnets/NeuralConvolutionalLayer.h>
#include <shogun/mathematics/Math.h>
#include <shogun/lib/SGVector.h>
using namespace shogun;
CNeuralConvolutionalLayer::CNeuralConvolutionalLayer() : CNeuralLayer()
{
init();
}
CNeuralConvolutionalLayer::CNeuralConvolutionalLayer(
EConvMapActivationFunction function,
int32_t num_maps,
int32_t radius_x, int32_t radius_y,
int32_t pooling_width, int32_t pooling_height,
int32_t stride_x, int32_t stride_y) : CNeuralLayer()
{
init();
m_num_maps = num_maps;
m_radius_x = radius_x;
m_radius_y = radius_y;
m_pooling_width = pooling_width;
m_pooling_height = pooling_height;
m_stride_x = stride_x;
m_stride_y = stride_y;
}
void CNeuralConvolutionalLayer::set_batch_size(int32_t batch_size)
{
CNeuralLayer::set_batch_size(batch_size);
if (autoencoder_position==NLAP_NONE)
m_convolution_output = SGMatrix<float64_t>(m_num_maps*
(m_input_width/m_stride_x)*(m_input_height/m_stride_y), batch_size);
else
m_convolution_output = SGMatrix<float64_t>(
m_num_maps*m_input_width*m_input_height, batch_size);
m_max_indices = SGMatrix<float64_t>(m_num_neurons, m_batch_size);
m_convolution_output_gradients = SGMatrix<float64_t>(
m_convolution_output.num_rows, m_convolution_output.num_cols);
}
void CNeuralConvolutionalLayer::initialize(CDynamicObjectArray* layers,
SGVector< int32_t > input_indices)
{
CNeuralLayer* first_input_layer =
(CNeuralLayer*)layers->element(input_indices[0]);
m_input_width = first_input_layer->get_width();
m_input_height = first_input_layer->get_height();
SG_UNREF(first_input_layer);
if (autoencoder_position==NLAP_NONE)
{
m_width = m_input_width/(m_stride_x*m_pooling_width);
m_height = m_input_height/(m_stride_y*m_pooling_height);
}
else
{
m_width = m_input_width;
m_height = m_input_height;
}
m_num_neurons = m_width*m_height*m_num_maps;
CNeuralLayer::initialize(layers, input_indices);
m_input_num_channels = 0;
for (int32_t l=0; l<input_indices.vlen; l++)
{
CNeuralLayer* layer =
(CNeuralLayer*)layers->element(input_indices[l]);
m_input_num_channels += layer->get_num_neurons()/(m_input_height*m_input_width);
SG_UNREF(layer);
}
// one bias for each map and one weight matrix between each map in this
// layer and each channel in the input layers
m_num_parameters =
m_num_maps*(1 + m_input_num_channels*(2*m_radius_x+1)*(2*m_radius_y+1));
}
void CNeuralConvolutionalLayer::initialize_parameters(SGVector<float64_t> parameters,
SGVector<bool> parameter_regularizable,
float64_t sigma)
{
int32_t num_parameters_per_map =
1 + m_input_num_channels*(2*m_radius_x+1)*(2*m_radius_y+1);
for (int32_t m=0; m<m_num_maps; m++)
{
float64_t* map_params = parameters.vector+m*num_parameters_per_map;
bool* map_param_regularizable =
parameter_regularizable.vector+m*num_parameters_per_map;
for (int32_t i=0; i<num_parameters_per_map; i++)
{
map_params[i] = CMath::normal_random(0.0, sigma);
// turn off regularization for the bias, on for the rest of the parameters
map_param_regularizable[i] = (i != 0);
}
}
}
void CNeuralConvolutionalLayer::compute_activations(
SGVector<float64_t> parameters,
CDynamicObjectArray* layers)
{
int32_t num_parameters_per_map =
1 + m_input_num_channels*(2*m_radius_x+1)*(2*m_radius_y+1);
for (int32_t m=0; m<m_num_maps; m++)
{
SGVector<float64_t> map_params(
parameters.vector+m*num_parameters_per_map,
num_parameters_per_map, false);
CConvolutionalFeatureMap map(m_input_width, m_input_height,
m_radius_x, m_radius_y, m_stride_x, m_stride_y, m,
m_activation_function, autoencoder_position);
map.compute_activations(map_params, layers, m_input_indices,
m_convolution_output);
map.pool_activations(m_convolution_output,
m_pooling_width, m_pooling_height, m_activations, m_max_indices);
}
}
void CNeuralConvolutionalLayer::compute_gradients(
SGVector<float64_t> parameters,
SGMatrix<float64_t> targets,
CDynamicObjectArray* layers,
SGVector<float64_t> parameter_gradients)
{
if (targets.num_rows != 0)
{
// sqaured error measure
// local_gradients = activations-targets
int32_t length = m_num_neurons*m_batch_size;
for (int32_t i=0; i<length; i++)
m_activation_gradients[i] = (m_activations[i]-targets[i])/m_batch_size;
}
if (dropout_prop>0.0)
{
int32_t len = m_num_neurons*m_batch_size;
for (int32_t i=0; i<len; i++)
m_activation_gradients[i] *= m_dropout_mask[i];
}
// compute the pre-pooling activation gradients
m_convolution_output_gradients.zero();
for (int32_t i=0; i<m_num_neurons; i++)
for (int32_t j=0; j<m_batch_size; j++)
if (m_max_indices(i,j)!=-1.0)
m_convolution_output_gradients(m_max_indices(i,j),j) =
m_activation_gradients(i,j);
int32_t num_parameters_per_map =
1 + m_input_num_channels*(2*m_radius_x+1)*(2*m_radius_y+1);
for (int32_t m=0; m<m_num_maps; m++)
{
SGVector<float64_t> map_params(
parameters.vector+m*num_parameters_per_map,
num_parameters_per_map, false);
SGVector<float64_t> map_gradients(
parameter_gradients.vector+m*num_parameters_per_map,
num_parameters_per_map, false);
CConvolutionalFeatureMap map(m_input_width, m_input_height,
m_radius_x, m_radius_y, m_stride_x, m_stride_y, m,
m_activation_function, autoencoder_position);
map.compute_gradients(map_params, m_convolution_output,
m_convolution_output_gradients, layers,
m_input_indices, map_gradients);
}
}
float64_t CNeuralConvolutionalLayer::compute_error(SGMatrix<float64_t> targets)
{
// error = 0.5*(sum(targets-activations)^2)/batch_size
float64_t sum = 0;
int32_t length = m_num_neurons*m_batch_size;
for (int32_t i=0; i<length; i++)
sum += (targets[i]-m_activations[i])*(targets[i]-m_activations[i]);
sum *= (0.5/m_batch_size);
return sum;
}
void CNeuralConvolutionalLayer::enforce_max_norm(SGVector<float64_t> parameters,
float64_t max_norm)
{
int32_t num_weights = (2*m_radius_x+1)*(2*m_radius_y+1);
int32_t num_parameters_per_map = 1 + m_input_num_channels*num_weights;
for (int32_t offset=1; offset<parameters.vlen; offset+=num_parameters_per_map)
{
float64_t* weights = parameters.vector+offset;
float64_t norm =
SGVector<float64_t>::twonorm(weights, num_weights);
if (norm > max_norm)
{
float64_t multiplier = max_norm/norm;
for (int32_t i=0; i<num_weights; i++)
weights[i] *= multiplier;
}
}
}
void CNeuralConvolutionalLayer::init()
{
m_num_maps = 1;
m_input_width = 0;
m_input_height = 0;
m_input_num_channels = 0;
m_radius_x = 0;
m_radius_y = 0;
m_pooling_width = 1;
m_pooling_height = 1;
m_stride_x = 1;
m_stride_y = 1;
m_activation_function = CMAF_IDENTITY;
SG_ADD(&m_num_maps, "num_maps", "Number of maps", MS_NOT_AVAILABLE);
SG_ADD(&m_input_width, "input_width", "Input Width", MS_NOT_AVAILABLE);
SG_ADD(&m_input_height, "input_height", "Input Height", MS_NOT_AVAILABLE);
SG_ADD(&m_input_num_channels, "input_num_channels", "Input's number of channels",
MS_NOT_AVAILABLE);
SG_ADD(&m_radius_x, "radius_x", "X Radius", MS_NOT_AVAILABLE);
SG_ADD(&m_radius_y, "radius_y", "Y Radius", MS_NOT_AVAILABLE);
SG_ADD(&m_pooling_width, "pooling_width", "Pooling Width", MS_NOT_AVAILABLE);
SG_ADD(&m_pooling_height, "pooling_height", "Pooling Height", MS_NOT_AVAILABLE);
SG_ADD(&m_stride_x, "stride_x", "X Stride", MS_NOT_AVAILABLE);
SG_ADD(&m_stride_y, "stride_y", "Y Stride", MS_NOT_AVAILABLE);
SG_ADD((machine_int_t*) &m_activation_function, "activation_function",
"Activation Function", MS_NOT_AVAILABLE);
SG_ADD(&m_convolution_output, "convolution_output",
"Convolution Output", MS_NOT_AVAILABLE);
SG_ADD(&m_convolution_output_gradients, "convolution_output_gradients",
"Convolution Output Gradients", MS_NOT_AVAILABLE);
}
<|endoftext|>
|
<commit_before>/*
*
* Copyright 2015 gRPC authors.
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*
*/
#include <grpc/support/port_platform.h>
#include "src/core/lib/iomgr/port.h"
#ifdef GRPC_POSIX_SOCKET_RESOLVE_ADDRESS
#include <string.h>
#include <sys/types.h>
#include <grpc/support/alloc.h>
#include <grpc/support/log.h>
#include <grpc/support/string_util.h>
#include <grpc/support/time.h>
#include "src/core/lib/event_engine/default_event_engine.h"
#include "src/core/lib/gpr/string.h"
#include "src/core/lib/gpr/useful.h"
#include "src/core/lib/gprpp/host_port.h"
#include "src/core/lib/gprpp/thd.h"
#include "src/core/lib/iomgr/block_annotate.h"
#include "src/core/lib/iomgr/exec_ctx.h"
#include "src/core/lib/iomgr/executor.h"
#include "src/core/lib/iomgr/iomgr_internal.h"
#include "src/core/lib/iomgr/resolve_address.h"
#include "src/core/lib/iomgr/resolve_address_posix.h"
#include "src/core/lib/iomgr/sockaddr.h"
#include "src/core/lib/iomgr/unix_sockets_posix.h"
#include "src/core/lib/transport/error_utils.h"
namespace grpc_core {
namespace {
class NativeDNSRequest {
public:
NativeDNSRequest(
absl::string_view name, absl::string_view default_port,
std::function<void(absl::StatusOr<std::vector<grpc_resolved_address>>)>
on_done)
: name_(name), default_port_(default_port), on_done_(std::move(on_done)) {
GRPC_CLOSURE_INIT(&request_closure_, DoRequestThread, this, nullptr);
Executor::Run(&request_closure_, absl::OkStatus(), ExecutorType::RESOLVER);
}
private:
// Callback to be passed to grpc Executor to asynch-ify
// LookupHostnameBlocking
static void DoRequestThread(void* rp, grpc_error_handle /*error*/) {
NativeDNSRequest* r = static_cast<NativeDNSRequest*>(rp);
auto result =
GetDNSResolver()->LookupHostnameBlocking(r->name_, r->default_port_);
// running inline is safe since we've already been scheduled on the executor
r->on_done_(std::move(result));
delete r;
}
const std::string name_;
const std::string default_port_;
const std::function<void(absl::StatusOr<std::vector<grpc_resolved_address>>)>
on_done_;
grpc_closure request_closure_;
};
} // namespace
DNSResolver::TaskHandle NativeDNSResolver::LookupHostname(
std::function<void(absl::StatusOr<std::vector<grpc_resolved_address>>)>
on_done,
absl::string_view name, absl::string_view default_port,
Duration /* timeout */, grpc_pollset_set* /* interested_parties */,
absl::string_view /* name_server */) {
// self-deleting class
new NativeDNSRequest(name, default_port, std::move(on_done));
return kNullHandle;
}
absl::StatusOr<std::vector<grpc_resolved_address>>
NativeDNSResolver::LookupHostnameBlocking(absl::string_view name,
absl::string_view default_port) {
ExecCtx exec_ctx;
struct addrinfo hints;
struct addrinfo *result = nullptr, *resp;
int s;
size_t i;
grpc_error_handle err;
std::vector<grpc_resolved_address> addresses;
std::string host;
std::string port;
// parse name, splitting it into host and port parts
SplitHostPort(name, &host, &port);
if (host.empty()) {
err = grpc_error_set_str(GRPC_ERROR_CREATE("unparseable host:port"),
StatusStrProperty::kTargetAddress, name);
goto done;
}
if (port.empty()) {
if (default_port.empty()) {
err = grpc_error_set_str(GRPC_ERROR_CREATE("no port in name"),
StatusStrProperty::kTargetAddress, name);
goto done;
}
port = std::string(default_port);
}
// Call getaddrinfo
memset(&hints, 0, sizeof(hints));
hints.ai_family = AF_UNSPEC; /* ipv4 or ipv6 */
hints.ai_socktype = SOCK_STREAM; /* stream socket */
hints.ai_flags = AI_PASSIVE; /* for wildcard IP address */
GRPC_SCHEDULING_START_BLOCKING_REGION;
s = getaddrinfo(host.c_str(), port.c_str(), &hints, &result);
GRPC_SCHEDULING_END_BLOCKING_REGION;
if (s != 0) {
// Retry if well-known service name is recognized
const char* svc[][2] = {{"http", "80"}, {"https", "443"}};
for (i = 0; i < GPR_ARRAY_SIZE(svc); i++) {
if (port == svc[i][0]) {
GRPC_SCHEDULING_START_BLOCKING_REGION;
s = getaddrinfo(host.c_str(), svc[i][1], &hints, &result);
GRPC_SCHEDULING_END_BLOCKING_REGION;
break;
}
}
}
if (s != 0) {
err = grpc_error_set_str(
grpc_error_set_str(
grpc_error_set_str(
grpc_error_set_int(GRPC_ERROR_CREATE(gai_strerror(s)),
StatusIntProperty::kErrorNo, s),
StatusStrProperty::kOsError, gai_strerror(s)),
StatusStrProperty::kSyscall, "getaddrinfo"),
StatusStrProperty::kTargetAddress, name);
goto done;
}
// Success path: fill in addrs
for (resp = result; resp != nullptr; resp = resp->ai_next) {
grpc_resolved_address addr;
memcpy(&addr.addr, resp->ai_addr, resp->ai_addrlen);
addr.len = resp->ai_addrlen;
addresses.push_back(addr);
}
err = absl::OkStatus();
done:
if (result) {
freeaddrinfo(result);
}
if (err.ok()) {
return addresses;
}
auto error_result = grpc_error_to_absl_status(err);
return error_result;
}
DNSResolver::TaskHandle NativeDNSResolver::LookupSRV(
std::function<void(absl::StatusOr<std::vector<grpc_resolved_address>>)>
on_resolved,
absl::string_view /* name */, Duration /* timeout */,
grpc_pollset_set* /* interested_parties */,
absl::string_view /* name_server */) {
grpc_event_engine::experimental::GetDefaultEventEngine()->Run([on_resolved] {
ApplicationCallbackExecCtx app_exec_ctx;
ExecCtx exec_ctx;
on_resolved(absl::UnimplementedError(
"The Native resolver does not support looking up SRV records"));
});
return {-1, -1};
};
DNSResolver::TaskHandle NativeDNSResolver::LookupTXT(
std::function<void(absl::StatusOr<std::string>)> on_resolved,
absl::string_view /* name */, Duration /* timeout */,
grpc_pollset_set* /* interested_parties */,
absl::string_view /* name_server */) {
// Not supported
grpc_event_engine::experimental::GetDefaultEventEngine()->Run([on_resolved] {
ApplicationCallbackExecCtx app_exec_ctx;
ExecCtx exec_ctx;
on_resolved(absl::UnimplementedError(
"The Native resolver does not support looking up TXT records"));
});
return {-1, -1};
};
bool NativeDNSResolver::Cancel(TaskHandle /*handle*/) { return false; }
} // namespace grpc_core
#endif
<commit_msg>[event_engine] Move DNS resolution executor usage to event engine (#31230)<commit_after>/*
*
* Copyright 2015 gRPC authors.
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*
*/
#include <grpc/support/port_platform.h>
#include "src/core/lib/iomgr/port.h"
#ifdef GRPC_POSIX_SOCKET_RESOLVE_ADDRESS
#include <string.h>
#include <sys/types.h>
#include <grpc/support/alloc.h>
#include <grpc/support/log.h>
#include <grpc/support/string_util.h>
#include <grpc/support/time.h>
#include "src/core/lib/event_engine/default_event_engine.h"
#include "src/core/lib/gpr/string.h"
#include "src/core/lib/gpr/useful.h"
#include "src/core/lib/gprpp/host_port.h"
#include "src/core/lib/gprpp/thd.h"
#include "src/core/lib/iomgr/block_annotate.h"
#include "src/core/lib/iomgr/exec_ctx.h"
#include "src/core/lib/iomgr/executor.h"
#include "src/core/lib/iomgr/iomgr_internal.h"
#include "src/core/lib/iomgr/resolve_address.h"
#include "src/core/lib/iomgr/resolve_address_posix.h"
#include "src/core/lib/iomgr/sockaddr.h"
#include "src/core/lib/iomgr/unix_sockets_posix.h"
#include "src/core/lib/transport/error_utils.h"
namespace grpc_core {
namespace {
void NativeDNSRequest(
std::string name, std::string default_port,
std::function<void(absl::StatusOr<std::vector<grpc_resolved_address>>)>
on_done) {
grpc_event_engine::experimental::GetDefaultEventEngine()->Run(
[name = std::move(name), default_port = std::move(default_port),
on_done = std::move(on_done)]() mutable {
ApplicationCallbackExecCtx callback_exec_ctx;
ExecCtx exec_ctx;
auto result =
GetDNSResolver()->LookupHostnameBlocking(name, default_port);
// running inline is safe since we've already been scheduled on the
// executor
on_done(std::move(result));
});
}
} // namespace
DNSResolver::TaskHandle NativeDNSResolver::LookupHostname(
std::function<void(absl::StatusOr<std::vector<grpc_resolved_address>>)>
on_done,
absl::string_view name, absl::string_view default_port,
Duration /* timeout */, grpc_pollset_set* /* interested_parties */,
absl::string_view /* name_server */) {
NativeDNSRequest(std::string(name), std::string(default_port),
std::move(on_done));
return kNullHandle;
}
absl::StatusOr<std::vector<grpc_resolved_address>>
NativeDNSResolver::LookupHostnameBlocking(absl::string_view name,
absl::string_view default_port) {
ExecCtx exec_ctx;
struct addrinfo hints;
struct addrinfo *result = nullptr, *resp;
int s;
size_t i;
grpc_error_handle err;
std::vector<grpc_resolved_address> addresses;
std::string host;
std::string port;
// parse name, splitting it into host and port parts
SplitHostPort(name, &host, &port);
if (host.empty()) {
err = grpc_error_set_str(GRPC_ERROR_CREATE("unparseable host:port"),
StatusStrProperty::kTargetAddress, name);
goto done;
}
if (port.empty()) {
if (default_port.empty()) {
err = grpc_error_set_str(GRPC_ERROR_CREATE("no port in name"),
StatusStrProperty::kTargetAddress, name);
goto done;
}
port = std::string(default_port);
}
// Call getaddrinfo
memset(&hints, 0, sizeof(hints));
hints.ai_family = AF_UNSPEC; /* ipv4 or ipv6 */
hints.ai_socktype = SOCK_STREAM; /* stream socket */
hints.ai_flags = AI_PASSIVE; /* for wildcard IP address */
GRPC_SCHEDULING_START_BLOCKING_REGION;
s = getaddrinfo(host.c_str(), port.c_str(), &hints, &result);
GRPC_SCHEDULING_END_BLOCKING_REGION;
if (s != 0) {
// Retry if well-known service name is recognized
const char* svc[][2] = {{"http", "80"}, {"https", "443"}};
for (i = 0; i < GPR_ARRAY_SIZE(svc); i++) {
if (port == svc[i][0]) {
GRPC_SCHEDULING_START_BLOCKING_REGION;
s = getaddrinfo(host.c_str(), svc[i][1], &hints, &result);
GRPC_SCHEDULING_END_BLOCKING_REGION;
break;
}
}
}
if (s != 0) {
err = grpc_error_set_str(
grpc_error_set_str(
grpc_error_set_str(
grpc_error_set_int(GRPC_ERROR_CREATE(gai_strerror(s)),
StatusIntProperty::kErrorNo, s),
StatusStrProperty::kOsError, gai_strerror(s)),
StatusStrProperty::kSyscall, "getaddrinfo"),
StatusStrProperty::kTargetAddress, name);
goto done;
}
// Success path: fill in addrs
for (resp = result; resp != nullptr; resp = resp->ai_next) {
grpc_resolved_address addr;
memcpy(&addr.addr, resp->ai_addr, resp->ai_addrlen);
addr.len = resp->ai_addrlen;
addresses.push_back(addr);
}
err = absl::OkStatus();
done:
if (result) {
freeaddrinfo(result);
}
if (err.ok()) {
return addresses;
}
auto error_result = grpc_error_to_absl_status(err);
return error_result;
}
DNSResolver::TaskHandle NativeDNSResolver::LookupSRV(
std::function<void(absl::StatusOr<std::vector<grpc_resolved_address>>)>
on_resolved,
absl::string_view /* name */, Duration /* timeout */,
grpc_pollset_set* /* interested_parties */,
absl::string_view /* name_server */) {
grpc_event_engine::experimental::GetDefaultEventEngine()->Run([on_resolved] {
ApplicationCallbackExecCtx app_exec_ctx;
ExecCtx exec_ctx;
on_resolved(absl::UnimplementedError(
"The Native resolver does not support looking up SRV records"));
});
return {-1, -1};
};
DNSResolver::TaskHandle NativeDNSResolver::LookupTXT(
std::function<void(absl::StatusOr<std::string>)> on_resolved,
absl::string_view /* name */, Duration /* timeout */,
grpc_pollset_set* /* interested_parties */,
absl::string_view /* name_server */) {
// Not supported
grpc_event_engine::experimental::GetDefaultEventEngine()->Run([on_resolved] {
ApplicationCallbackExecCtx app_exec_ctx;
ExecCtx exec_ctx;
on_resolved(absl::UnimplementedError(
"The Native resolver does not support looking up TXT records"));
});
return {-1, -1};
};
bool NativeDNSResolver::Cancel(TaskHandle /*handle*/) { return false; }
} // namespace grpc_core
#endif
<|endoftext|>
|
<commit_before>#include <powerset.hpp>
#include "helpers.hpp"
#include <vector>
#include <string>
#include <iterator>
#include "catch.hpp"
using iter::powerset;
using IntPermSet = std::multiset<std::multiset<int>>;
TEST_CASE("powerset: basic test, [1, 2, 3]", "[powerset]") {
const std::vector<int> ns = {1, 2, 3};
IntPermSet v;
for (auto&& st : powerset(ns)) {
v.emplace(std::begin(st), std::end(st));
}
const IntPermSet vc = { {}, {1}, {2}, {3,}, {1,2}, {1,3}, {2,3}, {1,2,3} };
REQUIRE( v == vc );
}
TEST_CASE("powerset: empty sequence gives only empty set", "[powerset]") {
const std::vector<int> ns = {};
auto ps = powerset(ns);
auto it = std::begin(ps);
REQUIRE( std::begin(*it) == std::end(*it) ); // it's empty
++it;
REQUIRE( it == std::end(ps) );
}
TEST_CASE("powerset: iterators can be compared", "[powerset]") {
const std::vector<int> ns = {1, 2};
auto p = powerset(ns);
auto it = std::begin(p);
REQUIRE( it == std::begin(p) );
REQUIRE_FALSE( it != std::begin(p) );
REQUIRE( it != std::end(p) );
REQUIRE_FALSE( it == std::end(p) );
++it;
REQUIRE_FALSE( it == std::begin(p) );
REQUIRE( it != std::begin(p) );
REQUIRE_FALSE( it == std::end(p) );
REQUIRE( it != std::end(p) );
++it;
++it;
++it;
REQUIRE( it == std::end(p) );
REQUIRE_FALSE( it != std::end(p) );
}
TEST_CASE("powerset: binds to lvalues, moves rvalues", "[powerset]") {
itertest::BasicIterable<int> bi{1, 2};
SECTION("binds to lvalues") {
powerset(bi);
REQUIRE_FALSE(bi.was_moved_from());
}
SECTION("moves rvalues") {
powerset(std::move(bi));
REQUIRE(bi.was_moved_from());
}
}
TEST_CASE("powerset: doesn't move or copy elements of iterable", "[powerset]"){
constexpr itertest::SolidInt arr[] = {{1}, {0}, {2}};
for (auto&& st : powerset(arr)) {
for (auto&& i : st) {
(void)i;
}
}
}
<commit_msg>tests powerset iterator copy ctor<commit_after>#include <powerset.hpp>
#include "helpers.hpp"
#include <vector>
#include <string>
#include <iterator>
#include "catch.hpp"
using iter::powerset;
using IntPermSet = std::multiset<std::multiset<int>>;
TEST_CASE("powerset: basic test, [1, 2, 3]", "[powerset]") {
const std::vector<int> ns = {1, 2, 3};
IntPermSet v;
for (auto&& st : powerset(ns)) {
v.emplace(std::begin(st), std::end(st));
}
const IntPermSet vc = { {}, {1}, {2}, {3,}, {1,2}, {1,3}, {2,3}, {1,2,3} };
REQUIRE( v == vc );
}
TEST_CASE("powerset: empty sequence gives only empty set", "[powerset]") {
const std::vector<int> ns = {};
auto ps = powerset(ns);
auto it = std::begin(ps);
REQUIRE( std::begin(*it) == std::end(*it) ); // it's empty
++it;
REQUIRE( it == std::end(ps) );
}
TEST_CASE("powerset: iterators can be compared", "[powerset]") {
std::vector<int> ns = {1, 2};
auto p = powerset(ns);
{
auto it = std::begin(p);
REQUIRE( it == std::begin(p) );
REQUIRE_FALSE( it != std::begin(p) );
REQUIRE( it != std::end(p) );
REQUIRE_FALSE( it == std::end(p) );
++it;
REQUIRE_FALSE( it == std::begin(p) );
REQUIRE( it != std::begin(p) );
REQUIRE_FALSE( it == std::end(p) );
REQUIRE( it != std::end(p) );
++it;
++it;
++it;
REQUIRE( it == std::end(p) );
}
ns.push_back(3);
{
auto it = std::begin(p);
auto it2 = std::begin(p);
std::advance(it, 4);
std::advance(it2, 4);
REQUIRE( it == it2 );
++it2;
REQUIRE( it != it2 );
}
}
TEST_CASE("powerset: iterator copy ctor is correct", "[powerset]") {
// { {}, {1}, {2}, {1, 2} }
std::vector<int> ns = {1, 2};
auto p = powerset(ns);
auto it = std::begin(p);
auto it2(it);
REQUIRE( it == it2 );
++it2;
REQUIRE( it != it2 );
REQUIRE( std::begin(*it) == std::end(*it) );
}
TEST_CASE("powerset: binds to lvalues, moves rvalues", "[powerset]") {
itertest::BasicIterable<int> bi{1, 2};
SECTION("binds to lvalues") {
powerset(bi);
REQUIRE_FALSE(bi.was_moved_from());
}
SECTION("moves rvalues") {
powerset(std::move(bi));
REQUIRE(bi.was_moved_from());
}
}
TEST_CASE("powerset: doesn't move or copy elements of iterable", "[powerset]"){
constexpr itertest::SolidInt arr[] = {{1}, {0}, {2}};
for (auto&& st : powerset(arr)) {
for (auto&& i : st) {
(void)i;
}
}
}
<|endoftext|>
|
<commit_before>#include "connection.hpp"
#include <boost/log/trivial.hpp>
#include <boost/throw_exception.hpp>
#include <tmsp/types.pb.cc>
namespace tmsp
{
namespace wire
{
/*
Original tendermint implementation:
func ReadVarint(r io.Reader, n *int, err *error) int {
var size = ReadUint8(r, n, err)
var negate = false
if (size >> 4) == 0xF {
negate = true
size = size & 0x0F
}
if size > 8 {
setFirstErr(err, errors.New("Varint overflow"))
return 0
}
if size == 0 {
if negate {
setFirstErr(err, errors.New("Varint does not allow negative zero"))
}
return 0
}
buf := make([]byte, 8)
ReadFull(buf[(8-size):], r, n, err)
var i = int(binary.BigEndian.Uint64(buf))
if negate {
return -i
} else {
return i
}
}
*/
template<typename Integer>
bool read_variable_integer(buffer_type::pointer& iter, buffer_type::pointer end, Integer& result)
{
auto size(*iter & char(0x0F));
auto const negate(*iter & char(0xF0));
if(size == 0 && negate)
{
BOOST_THROW_EXCEPTION(std::range_error("varint does not allow negative zero"));
}
else if(size > 8)
{
BOOST_THROW_EXCEPTION(std::range_error("varint overflow"));
}
else if(++ iter + size > end)
{
return false;
}
result = 0;
for(; size; -- size, ++ iter)
{
result <<= 8;
result += static_cast<std::uint8_t>(*iter);
}
if(negate)
{
result = - result;
}
return true;
}
/*
Original tendermint implementation:
func WriteVarint(i int, w io.Writer, n *int, err *error) {
var negate = false
if i < 0 {
negate = true
i = -i
}
var size = uvarintSize(uint64(i))
if negate {
// e.g. 0xF1 for a single negative byte
WriteUint8(uint8(size+0xF0), w, n, err)
} else {
WriteUint8(uint8(size), w, n, err)
}
if size > 0 {
buf := make([]byte, 8)
binary.BigEndian.PutUint64(buf, uint64(i))
WriteTo(buf[(8-size):], w, n, err)
}
}
*/
template<typename Integer>
bool write_variable_integer(buffer_type::pointer& iter, buffer_type::pointer end, Integer value)
{
if(iter == end)
{
return false;
}
auto& size(*iter);
if(value < 0)
{
size = char(0xF0);
value = - value;
}
else
{
size = char(0x00);
}
for(++ iter; value; ++ size, ++ iter)
{
if(iter == end)
{
return false;
}
*iter = static_cast<std::uint8_t>(value);
value >>= 8;
}
return true;
}
} // namespace wire
connection_type::connection_type(boost::asio::ip::tcp::socket socket, application_ptr_type const& application) :
socket_(std::move(socket)),
read_head_(read_buffer_.data()),
read_tail_(read_head_),
write_head_(write_buffer_.data()),
write_tail_(write_head_),
application_(application)
{
}
void connection_type::start()
{
async_read_();
}
void connection_type::async_read_()
{
auto const self(shared_from_this());
auto const remaining(read_buffer_.data() + read_buffer_.size() - read_tail_);
boost::asio::async_read(socket_, boost::asio::buffer(read_tail_, remaining), boost::asio::transfer_at_least(1),
[self, this](boost::system::error_code const& error, std::size_t const& transferred)
{
if(error)
{
return;
}
read_tail_ += transferred;
try_advance_read_buffer_();
async_read_();
});
}
void connection_type::async_write_()
{
auto const self(shared_from_this());
auto const remaining(write_tail_ - write_head_);
if(remaining)
{
boost::asio::async_write(socket_, boost::asio::buffer(write_head_, remaining), boost::asio::transfer_all(),
[self, this](boost::system::error_code const& error, std::size_t const& transferred)
{
if(error)
{
BOOST_LOG_TRIVIAL(error) << socket_.remote_endpoint() << ": Write error: " << error;
return;
}
async_write_();
});
write_head_ = write_tail_;
}
else
{
write_head_ = write_buffer_.data();
write_tail_ = write_head_;
// Now that the write buffer is empty, see if there are any unprocessed requests available
try_advance_read_buffer_();
}
}
void connection_type::try_advance_read_buffer_()
{
while(read_head_ != read_tail_)
{
auto iter(read_head_);
std::int32_t message_size(0);
if(!wire::read_variable_integer(iter, read_tail_, message_size))
{
break;
}
if(message_size <= 0)
{
BOOST_THROW_EXCEPTION(std::range_error("invalid message size"));
}
if(iter + message_size > read_tail_)
{
// Buffer does not contain the full message
break;
}
types::Request request;
request.ParseFromArray(iter, message_size);
if(!request.IsInitialized())
{
BOOST_THROW_EXCEPTION(std::runtime_error("unable to parse request"));
}
// Only advance read head (i.e. treat request as completed) if a response could be prepared and written
types::Response response;
if(prepare_response_(request, response))
{
if(!write_message_(response))
{
BOOST_LOG_TRIVIAL(warning) << "Unable to write response - buffer full";
break;
}
}
read_head_ = iter + message_size;
}
if(read_head_ == read_tail_)
{
// All data consumed
read_head_ = read_buffer_.data();
read_tail_ = read_head_;
}
else
{
// Copy remaining data to front of buffer
read_tail_ = std::copy(read_head_, read_tail_, read_buffer_.data());
read_head_ = read_buffer_.data();
}
}
bool connection_type::prepare_response_(types::Request const& request, types::Response& response)
{
if(request.type() == types::Echo)
{
response.set_type(types::Echo);
response.set_data(request.data());
response.set_code(types::OK);
return true;
}
else if(request.type() == types::Flush)
{
response.set_type(types::Flush);
response.set_code(types::OK);
return true;
}
else if(request.type() == types::Info)
{
std::string out;
application_->info(out);
response.set_type(types::Info);
response.set_data(out);
return true;
}
else if(request.type() == types::SetOption)
{
std::string log;
application_->set_option(request.key(), request.value(), log);
response.set_type(types::SetOption);
response.set_log(log);
return true;
}
else if(request.type() == types::Query)
{
std::string out, log;
response.set_code(application_->query(request.data(), out, log));
response.set_type(types::CheckTx);
response.set_data(out);
response.set_log(log);
return true;
}
else if(request.type() == types::BeginBlock)
{
application_->begin_block(request.height());
return false;
}
else if(request.type() == types::EndBlock)
{
response.set_type(types::EndBlock);
response.set_code(application_->end_block(request.height()));
return true;
}
else if(request.type() == types::CheckTx)
{
std::string out, log;
response.set_code(application_->check_tx(request.data(), out, log));
response.set_type(types::CheckTx);
response.set_data(out);
response.set_log(log);
return true;
}
else if(request.type() == types::AppendTx)
{
std::string out, log;
response.set_code(application_->append_tx(request.data(), out, log));
response.set_type(types::AppendTx);
response.set_data(out);
response.set_log(log);
return true;
}
else if(request.type() == types::Commit)
{
std::string out, log;
application_->commit(out, log);
response.set_type(types::Commit);
response.set_data(out);
response.set_log(log);
return true;
}
BOOST_THROW_EXCEPTION(std::logic_error("unsupported TMSP request: " + request.DebugString()));
}
bool connection_type::write_message_(google::protobuf::MessageLite const& message)
{
auto iter(write_tail_);
if(!wire::write_variable_integer(iter, write_buffer_.data() + write_buffer_.size(), message.ByteSize()))
{
// Not enough room for message size
return false;
}
if(write_tail_ + message.ByteSize() > write_buffer_.data() + write_buffer_.size())
{
// Not enough room for message content
return false;
}
if(!message.SerializeToArray(iter, message.ByteSize()))
{
BOOST_THROW_EXCEPTION(std::runtime_error("unable to serialize message"));
}
write_tail_ = iter + message.ByteSize();
// Start async write if the write head is at the start of the buffer
if(write_head_ == write_buffer_.data())
{
async_write_();
}
return true;
}
} // namespace tmsp<commit_msg>Set proper response type for "Query" requests<commit_after>#include "connection.hpp"
#include <boost/log/trivial.hpp>
#include <boost/throw_exception.hpp>
#include <tmsp/types.pb.cc>
namespace tmsp
{
namespace wire
{
/*
Original tendermint implementation:
func ReadVarint(r io.Reader, n *int, err *error) int {
var size = ReadUint8(r, n, err)
var negate = false
if (size >> 4) == 0xF {
negate = true
size = size & 0x0F
}
if size > 8 {
setFirstErr(err, errors.New("Varint overflow"))
return 0
}
if size == 0 {
if negate {
setFirstErr(err, errors.New("Varint does not allow negative zero"))
}
return 0
}
buf := make([]byte, 8)
ReadFull(buf[(8-size):], r, n, err)
var i = int(binary.BigEndian.Uint64(buf))
if negate {
return -i
} else {
return i
}
}
*/
template<typename Integer>
bool read_variable_integer(buffer_type::pointer& iter, buffer_type::pointer end, Integer& result)
{
auto size(*iter & char(0x0F));
auto const negate(*iter & char(0xF0));
if(size == 0 && negate)
{
BOOST_THROW_EXCEPTION(std::range_error("varint does not allow negative zero"));
}
else if(size > 8)
{
BOOST_THROW_EXCEPTION(std::range_error("varint overflow"));
}
else if(++ iter + size > end)
{
return false;
}
result = 0;
for(; size; -- size, ++ iter)
{
result <<= 8;
result += static_cast<std::uint8_t>(*iter);
}
if(negate)
{
result = - result;
}
return true;
}
/*
Original tendermint implementation:
func WriteVarint(i int, w io.Writer, n *int, err *error) {
var negate = false
if i < 0 {
negate = true
i = -i
}
var size = uvarintSize(uint64(i))
if negate {
// e.g. 0xF1 for a single negative byte
WriteUint8(uint8(size+0xF0), w, n, err)
} else {
WriteUint8(uint8(size), w, n, err)
}
if size > 0 {
buf := make([]byte, 8)
binary.BigEndian.PutUint64(buf, uint64(i))
WriteTo(buf[(8-size):], w, n, err)
}
}
*/
template<typename Integer>
bool write_variable_integer(buffer_type::pointer& iter, buffer_type::pointer end, Integer value)
{
if(iter == end)
{
return false;
}
auto& size(*iter);
if(value < 0)
{
size = char(0xF0);
value = - value;
}
else
{
size = char(0x00);
}
for(++ iter; value; ++ size, ++ iter)
{
if(iter == end)
{
return false;
}
*iter = static_cast<std::uint8_t>(value);
value >>= 8;
}
return true;
}
} // namespace wire
connection_type::connection_type(boost::asio::ip::tcp::socket socket, application_ptr_type const& application) :
socket_(std::move(socket)),
read_head_(read_buffer_.data()),
read_tail_(read_head_),
write_head_(write_buffer_.data()),
write_tail_(write_head_),
application_(application)
{
}
void connection_type::start()
{
async_read_();
}
void connection_type::async_read_()
{
auto const self(shared_from_this());
auto const remaining(read_buffer_.data() + read_buffer_.size() - read_tail_);
boost::asio::async_read(socket_, boost::asio::buffer(read_tail_, remaining), boost::asio::transfer_at_least(1),
[self, this](boost::system::error_code const& error, std::size_t const& transferred)
{
if(error)
{
return;
}
read_tail_ += transferred;
try_advance_read_buffer_();
async_read_();
});
}
void connection_type::async_write_()
{
auto const self(shared_from_this());
auto const remaining(write_tail_ - write_head_);
if(remaining)
{
boost::asio::async_write(socket_, boost::asio::buffer(write_head_, remaining), boost::asio::transfer_all(),
[self, this](boost::system::error_code const& error, std::size_t const& transferred)
{
if(error)
{
BOOST_LOG_TRIVIAL(error) << socket_.remote_endpoint() << ": Write error: " << error;
return;
}
async_write_();
});
write_head_ = write_tail_;
}
else
{
write_head_ = write_buffer_.data();
write_tail_ = write_head_;
// Now that the write buffer is empty, see if there are any unprocessed requests available
try_advance_read_buffer_();
}
}
void connection_type::try_advance_read_buffer_()
{
while(read_head_ != read_tail_)
{
auto iter(read_head_);
std::int32_t message_size(0);
if(!wire::read_variable_integer(iter, read_tail_, message_size))
{
break;
}
if(message_size <= 0)
{
BOOST_THROW_EXCEPTION(std::range_error("invalid message size"));
}
if(iter + message_size > read_tail_)
{
// Buffer does not contain the full message
break;
}
types::Request request;
request.ParseFromArray(iter, message_size);
if(!request.IsInitialized())
{
BOOST_THROW_EXCEPTION(std::runtime_error("unable to parse request"));
}
// Only advance read head (i.e. treat request as completed) if a response could be prepared and written
types::Response response;
if(prepare_response_(request, response))
{
if(!write_message_(response))
{
BOOST_LOG_TRIVIAL(warning) << "Unable to write response - buffer full";
break;
}
}
read_head_ = iter + message_size;
}
if(read_head_ == read_tail_)
{
// All data consumed
read_head_ = read_buffer_.data();
read_tail_ = read_head_;
}
else
{
// Copy remaining data to front of buffer
read_tail_ = std::copy(read_head_, read_tail_, read_buffer_.data());
read_head_ = read_buffer_.data();
}
}
bool connection_type::prepare_response_(types::Request const& request, types::Response& response)
{
if(request.type() == types::Echo)
{
response.set_type(types::Echo);
response.set_data(request.data());
response.set_code(types::OK);
return true;
}
else if(request.type() == types::Flush)
{
response.set_type(types::Flush);
response.set_code(types::OK);
return true;
}
else if(request.type() == types::Info)
{
std::string out;
application_->info(out);
response.set_type(types::Info);
response.set_data(out);
return true;
}
else if(request.type() == types::SetOption)
{
std::string log;
application_->set_option(request.key(), request.value(), log);
response.set_type(types::SetOption);
response.set_log(log);
return true;
}
else if(request.type() == types::Query)
{
std::string out, log;
response.set_code(application_->query(request.data(), out, log));
response.set_type(types::Query);
response.set_data(out);
response.set_log(log);
return true;
}
else if(request.type() == types::BeginBlock)
{
application_->begin_block(request.height());
return false;
}
else if(request.type() == types::EndBlock)
{
response.set_type(types::EndBlock);
response.set_code(application_->end_block(request.height()));
return true;
}
else if(request.type() == types::CheckTx)
{
std::string out, log;
response.set_code(application_->check_tx(request.data(), out, log));
response.set_type(types::CheckTx);
response.set_data(out);
response.set_log(log);
return true;
}
else if(request.type() == types::AppendTx)
{
std::string out, log;
response.set_code(application_->append_tx(request.data(), out, log));
response.set_type(types::AppendTx);
response.set_data(out);
response.set_log(log);
return true;
}
else if(request.type() == types::Commit)
{
std::string out, log;
application_->commit(out, log);
response.set_type(types::Commit);
response.set_data(out);
response.set_log(log);
return true;
}
BOOST_THROW_EXCEPTION(std::logic_error("unsupported TMSP request: " + request.DebugString()));
}
bool connection_type::write_message_(google::protobuf::MessageLite const& message)
{
auto iter(write_tail_);
if(!wire::write_variable_integer(iter, write_buffer_.data() + write_buffer_.size(), message.ByteSize()))
{
// Not enough room for message size
return false;
}
if(write_tail_ + message.ByteSize() > write_buffer_.data() + write_buffer_.size())
{
// Not enough room for message content
return false;
}
if(!message.SerializeToArray(iter, message.ByteSize()))
{
BOOST_THROW_EXCEPTION(std::runtime_error("unable to serialize message"));
}
write_tail_ = iter + message.ByteSize();
// Start async write if the write head is at the start of the buffer
if(write_head_ == write_buffer_.data())
{
async_write_();
}
return true;
}
} // namespace tmsp<|endoftext|>
|
<commit_before>/*******************************************************************************
Licensed to the OpenCOR team under one or more contributor license agreements.
See the NOTICE.txt file distributed with this work for additional information
regarding copyright ownership. The OpenCOR team licenses this file to you under
the Apache License, Version 2.0 (the "License"); you may not use this file
except in compliance with the License. You may obtain a copy of the License at
http://www.apache.org/licenses/LICENSE-2.0
Unless required by applicable law or agreed to in writing, software distributed
under the License is distributed on an "AS IS" BASIS, WITHOUT WARRANTIES OR
CONDITIONS OF ANY KIND, either express or implied. See the License for the
specific language governing permissions and limitations under the License.
*******************************************************************************/
//==============================================================================
// CellML Model Repository window
//==============================================================================
#include "cellmlmodelrepositorywindowwindow.h"
#include "cellmlmodelrepositorywindowwidget.h"
#include "cliutils.h"
#include "guiutils.h"
//==============================================================================
#include "ui_cellmlmodelrepositorywindowwindow.h"
//==============================================================================
#include <Qt>
//==============================================================================
#include <QClipboard>
#include <QJsonDocument>
#include <QJsonObject>
#include <QMenu>
#include <QNetworkAccessManager>
#include <QNetworkReply>
#include <QNetworkRequest>
#include <QPoint>
#include <QRegularExpression>
//==============================================================================
namespace OpenCOR {
namespace CellMLModelRepositoryWindow {
//==============================================================================
CellmlModelRepositoryWindowWindow::CellmlModelRepositoryWindowWindow(QWidget *pParent) :
Core::OrganisationWidget(pParent),
mGui(new Ui::CellmlModelRepositoryWindowWindow),
mModelListRequested(false)
{
// Set up the GUI
mGui->setupUi(this);
#ifdef Q_OS_MAC
mGui->filterValue->setAttribute(Qt::WA_MacShowFocusRect, false);
// Note: the above removes the focus border since it messes up the look of
// our filter value widget...
#endif
// Make the name value our focus proxy
setFocusProxy(mGui->filterValue);
// Create and add the CellML Model Repository widget
mCellmlModelRepositoryWidget = new CellmlModelRepositoryWindowWidget(this);
mGui->dockWidgetContents->layout()->addWidget(mCellmlModelRepositoryWidget);
// Create and populate our context menu
mContextMenu = new QMenu(this);
mContextMenu->addAction(mGui->actionCopy);
// We want our own context menu for the help widget (indeed, we don't want
// the default one which has the reload menu item and not the other actions
// that we have in our tool bar widget, so...)
mCellmlModelRepositoryWidget->setContextMenuPolicy(Qt::CustomContextMenu);
connect(mCellmlModelRepositoryWidget, SIGNAL(customContextMenuRequested(const QPoint &)),
this, SLOT(showCustomContextMenu(const QPoint &)));
// Keep track of the window's visibility, so that we can request the list of
// models, if necessary
connect(this, SIGNAL(visibilityChanged(bool)),
this, SLOT(retrieveModelList(const bool &)));
// Create a network access manager so that we can then retrieve a list of
// CellML models from the CellML Model Repository
mNetworkAccessManager = new QNetworkAccessManager(this);
// Make sure that we get told when the download of our Internet file is
// complete, as well as if there are SSL errors (which would happen if the
// website's certificate is invalid, e.g. it has expired)
connect(mNetworkAccessManager, SIGNAL(finished(QNetworkReply *)),
this, SLOT(finished(QNetworkReply *)) );
connect(mNetworkAccessManager, SIGNAL(sslErrors(QNetworkReply *, const QList<QSslError> &)),
this, SLOT(sslErrors(QNetworkReply *, const QList<QSslError> &)) );
// Connection to update the enabled state of our copy action
connect(mCellmlModelRepositoryWidget, SIGNAL(copyTextEnabled(const bool &)),
mGui->actionCopy, SLOT(setEnabled(bool)));
}
//==============================================================================
CellmlModelRepositoryWindowWindow::~CellmlModelRepositoryWindowWindow()
{
// Delete the GUI
delete mGui;
}
//==============================================================================
void CellmlModelRepositoryWindowWindow::retranslateUi()
{
// Retranslate the whole window
mGui->retranslateUi(this);
// Retranslate our list of models
outputModelList(mModelList);
}
//==============================================================================
void CellmlModelRepositoryWindowWindow::outputModelList(const QStringList &pModelList)
{
// Output a given list of models
mModelList = pModelList;
QString contents = QString();
static const QString leadingSpaces = " ";
if (mModelList.count()) {
// We have models to list, so...
if (mModelList.count() == 1)
contents = tr("<strong>1</strong> CellML model was found:")+"\n";
else
contents = tr("<strong>%1</strong> CellML models were found:").arg(mModelList.count())+"\n";
contents += leadingSpaces+"<ul>\n";
foreach (const QString &model, mModelList)
contents += leadingSpaces+"<li><a href=\""+mModelUrls[mModelNames.indexOf(model)]+"\">"+model+"</a></li>\n";
contents += leadingSpaces+"</ul>";
} else if (mModelNames.empty()) {
if (mErrorMessage.count())
// Something went wrong while trying to retrieve the list of models,
// so...
contents = leadingSpaces+tr("<strong>Error:</strong> ")+Core::formatErrorMessage(mErrorMessage);
} else {
// No model could be found, so...
contents = leadingSpaces+tr("No CellML model matches your criteria");
}
// Show/hide our busy widget
if (mModelListRequested)
showBusyWidget(mCellmlModelRepositoryWidget);
else
hideBusyWidget();
// Output the list matching the search criteria, or a message telling the
// user what went wrong, if anything and if needed
if (!mModelListRequested)
mCellmlModelRepositoryWidget->output(contents);
}
//==============================================================================
void CellmlModelRepositoryWindowWindow::on_filterValue_textChanged(const QString &text)
{
// Generate a Web page that contains all the models that match our search
// criteria
outputModelList(mModelNames.filter(QRegularExpression(text, QRegularExpression::CaseInsensitiveOption)));
}
//==============================================================================
void CellmlModelRepositoryWindowWindow::on_actionCopy_triggered()
{
// Copy the current selection to the clipboard
QApplication::clipboard()->setText(mCellmlModelRepositoryWidget->selectedText());
}
//==============================================================================
void CellmlModelRepositoryWindowWindow::on_refreshButton_clicked()
{
// Output the message telling the user that the list is being downloaded
// Note: to clear mModelNames ensures that we get the correct message from
// outputModelList...
mModelListRequested = true;
mModelNames.clear();
outputModelList(QStringList());
// Disable the GUI side, so that the user doesn't get confused and ask to
// refresh over and over again while he should just be patient
mGui->dockWidgetContents->setEnabled(false);
// Get the list of CellML models
mNetworkAccessManager->get(QNetworkRequest(QUrl("https://models.physiomeproject.org/cellml/workspace/rest/contents.json")));
}
//==============================================================================
void CellmlModelRepositoryWindowWindow::finished(QNetworkReply *pNetworkReply)
{
// Clear some properties
mModelNames.clear();
mModelUrls.clear();
mModelListRequested = false;
// Output the list of models, should we have retrieved it without any
// problem
if (pNetworkReply->error() == QNetworkReply::NoError) {
// Parse the JSON code
QJsonParseError jsonParseError;
QJsonDocument jsonDocument = QJsonDocument::fromJson(pNetworkReply->readAll(), &jsonParseError);
if (jsonParseError.error == QJsonParseError::NoError) {
// Retrieve the list of CellML models
QVariantMap resultMap = jsonDocument.object().toVariantMap();
foreach (const QVariant &modelVariant, resultMap["values"].toList()) {
QVariantList modelDetailsVariant = modelVariant.toList();
mModelNames << modelDetailsVariant[0].toString();
mModelUrls << modelDetailsVariant[1].toString();
}
// Everything went fine, so...
mErrorMessage = QString();
} else {
// Something went wrong, so...
mErrorMessage = jsonParseError.errorString();
}
} else {
// Something went wrong, so...
mErrorMessage = pNetworkReply->errorString();
}
// Initialise the output using whatever search criteria is present
on_filterValue_textChanged(mGui->filterValue->text());
// Re-enable the GUI side
mGui->dockWidgetContents->setEnabled(true);
// Give, within the current window, the focus to mGui->filterValue, but
// only if the current window already has the focus
Core::setFocusTo(mGui->filterValue);
// Delete (later) the network reply
pNetworkReply->deleteLater();
}
//==============================================================================
void CellmlModelRepositoryWindowWindow::sslErrors(QNetworkReply *pNetworkReply,
const QList<QSslError> &pSslErrors)
{
// Ignore the SSL errors since we trust the website and therefore its
// certificate (even if it is invalid, e.g. it has expired)
pNetworkReply->ignoreSslErrors(pSslErrors);
}
//==============================================================================
void CellmlModelRepositoryWindowWindow::showCustomContextMenu(const QPoint &pPosition) const
{
Q_UNUSED(pPosition);
// Show our context menu for our CellML Models Repository widget
mContextMenu->exec(QCursor::pos());
}
//==============================================================================
void CellmlModelRepositoryWindowWindow::retrieveModelList(const bool &pVisible)
{
// Retrieve the list of models, if we are becoming visible and the list of
// models has never been requested before
static bool firstTime = true;
if (pVisible && firstTime) {
firstTime = false;
on_refreshButton_clicked();
}
}
//==============================================================================
} // namespace CellMLModelRepositoryWindow
} // namespace OpenCOR
//==============================================================================
// End of file
//==============================================================================
<commit_msg>Some minor cleaning up [ci skip].<commit_after>/*******************************************************************************
Licensed to the OpenCOR team under one or more contributor license agreements.
See the NOTICE.txt file distributed with this work for additional information
regarding copyright ownership. The OpenCOR team licenses this file to you under
the Apache License, Version 2.0 (the "License"); you may not use this file
except in compliance with the License. You may obtain a copy of the License at
http://www.apache.org/licenses/LICENSE-2.0
Unless required by applicable law or agreed to in writing, software distributed
under the License is distributed on an "AS IS" BASIS, WITHOUT WARRANTIES OR
CONDITIONS OF ANY KIND, either express or implied. See the License for the
specific language governing permissions and limitations under the License.
*******************************************************************************/
//==============================================================================
// CellML Model Repository window
//==============================================================================
#include "cellmlmodelrepositorywindowwindow.h"
#include "cellmlmodelrepositorywindowwidget.h"
#include "cliutils.h"
#include "guiutils.h"
//==============================================================================
#include "ui_cellmlmodelrepositorywindowwindow.h"
//==============================================================================
#include <Qt>
//==============================================================================
#include <QClipboard>
#include <QJsonDocument>
#include <QJsonObject>
#include <QMenu>
#include <QNetworkAccessManager>
#include <QNetworkReply>
#include <QNetworkRequest>
#include <QPoint>
#include <QRegularExpression>
//==============================================================================
namespace OpenCOR {
namespace CellMLModelRepositoryWindow {
//==============================================================================
CellmlModelRepositoryWindowWindow::CellmlModelRepositoryWindowWindow(QWidget *pParent) :
Core::OrganisationWidget(pParent),
mGui(new Ui::CellmlModelRepositoryWindowWindow),
mModelListRequested(false)
{
// Set up the GUI
mGui->setupUi(this);
#ifdef Q_OS_MAC
mGui->filterValue->setAttribute(Qt::WA_MacShowFocusRect, false);
// Note: the above removes the focus border since it messes up the look of
// our filter value widget...
#endif
// Make the name value our focus proxy
setFocusProxy(mGui->filterValue);
// Create and add the CellML Model Repository widget
mCellmlModelRepositoryWidget = new CellmlModelRepositoryWindowWidget(this);
mGui->dockWidgetContents->layout()->addWidget(mCellmlModelRepositoryWidget);
// Create and populate our context menu
mContextMenu = new QMenu(this);
mContextMenu->addAction(mGui->actionCopy);
// We want our own context menu for the help widget (indeed, we don't want
// the default one which has the reload menu item and not the other actions
// that we have in our tool bar widget, so...)
mCellmlModelRepositoryWidget->setContextMenuPolicy(Qt::CustomContextMenu);
connect(mCellmlModelRepositoryWidget, SIGNAL(customContextMenuRequested(const QPoint &)),
this, SLOT(showCustomContextMenu(const QPoint &)));
// Keep track of the window's visibility, so that we can request the list of
// models, if necessary
connect(this, SIGNAL(visibilityChanged(bool)),
this, SLOT(retrieveModelList(const bool &)));
// Create a network access manager so that we can then retrieve a list of
// CellML models from the CellML Model Repository
mNetworkAccessManager = new QNetworkAccessManager(this);
// Make sure that we get told when the download of our Internet file is
// complete, as well as if there are SSL errors (which would happen if the
// website's certificate is invalid, e.g. it has expired)
connect(mNetworkAccessManager, SIGNAL(finished(QNetworkReply *)),
this, SLOT(finished(QNetworkReply *)) );
connect(mNetworkAccessManager, SIGNAL(sslErrors(QNetworkReply *, const QList<QSslError> &)),
this, SLOT(sslErrors(QNetworkReply *, const QList<QSslError> &)) );
// Connection to update the enabled state of our copy action
connect(mCellmlModelRepositoryWidget, SIGNAL(copyTextEnabled(const bool &)),
mGui->actionCopy, SLOT(setEnabled(bool)));
}
//==============================================================================
CellmlModelRepositoryWindowWindow::~CellmlModelRepositoryWindowWindow()
{
// Delete the GUI
delete mGui;
}
//==============================================================================
void CellmlModelRepositoryWindowWindow::retranslateUi()
{
// Retranslate the whole window
mGui->retranslateUi(this);
// Retranslate our list of models
outputModelList(mModelList);
}
//==============================================================================
void CellmlModelRepositoryWindowWindow::outputModelList(const QStringList &pModelList)
{
// Output a given list of models
mModelList = pModelList;
QString contents = QString();
static const QString leadingSpaces = " ";
if (mModelList.count()) {
// We have models to list, so...
if (mModelList.count() == 1)
contents = tr("<strong>1</strong> CellML model was found:")+"\n";
else
contents = tr("<strong>%1</strong> CellML models were found:").arg(mModelList.count())+"\n";
contents += leadingSpaces+"<ul>\n";
foreach (const QString &model, mModelList)
contents += leadingSpaces+"<li><a href=\""+mModelUrls[mModelNames.indexOf(model)]+"\">"+model+"</a></li>\n";
contents += leadingSpaces+"</ul>";
} else if (mModelNames.empty()) {
if (mErrorMessage.count())
// Something went wrong while trying to retrieve the list of models,
// so...
contents = leadingSpaces+tr("<strong>Error:</strong> ")+Core::formatErrorMessage(mErrorMessage);
} else {
// No model could be found, so...
contents = leadingSpaces+tr("No CellML model matches your criteria");
}
// Show/hide our busy widget and output the list matching the search
// criteria, or a message telling the user what went wrong, if anything and
// if needed
if (mModelListRequested) {
showBusyWidget(mCellmlModelRepositoryWidget);
} else {
hideBusyWidget();
mCellmlModelRepositoryWidget->output(contents);
}
}
//==============================================================================
void CellmlModelRepositoryWindowWindow::on_filterValue_textChanged(const QString &text)
{
// Generate a Web page that contains all the models that match our search
// criteria
outputModelList(mModelNames.filter(QRegularExpression(text, QRegularExpression::CaseInsensitiveOption)));
}
//==============================================================================
void CellmlModelRepositoryWindowWindow::on_actionCopy_triggered()
{
// Copy the current selection to the clipboard
QApplication::clipboard()->setText(mCellmlModelRepositoryWidget->selectedText());
}
//==============================================================================
void CellmlModelRepositoryWindowWindow::on_refreshButton_clicked()
{
// Output the message telling the user that the list is being downloaded
// Note: to clear mModelNames ensures that we get the correct message from
// outputModelList...
mModelListRequested = true;
mModelNames.clear();
outputModelList(QStringList());
// Disable the GUI side, so that the user doesn't get confused and ask to
// refresh over and over again while he should just be patient
mGui->dockWidgetContents->setEnabled(false);
// Get the list of CellML models
mNetworkAccessManager->get(QNetworkRequest(QUrl("https://models.physiomeproject.org/cellml/workspace/rest/contents.json")));
}
//==============================================================================
void CellmlModelRepositoryWindowWindow::finished(QNetworkReply *pNetworkReply)
{
// Clear some properties
mModelNames.clear();
mModelUrls.clear();
mModelListRequested = false;
// Output the list of models, should we have retrieved it without any
// problem
if (pNetworkReply->error() == QNetworkReply::NoError) {
// Parse the JSON code
QJsonParseError jsonParseError;
QJsonDocument jsonDocument = QJsonDocument::fromJson(pNetworkReply->readAll(), &jsonParseError);
if (jsonParseError.error == QJsonParseError::NoError) {
// Retrieve the list of CellML models
QVariantMap resultMap = jsonDocument.object().toVariantMap();
foreach (const QVariant &modelVariant, resultMap["values"].toList()) {
QVariantList modelDetailsVariant = modelVariant.toList();
mModelNames << modelDetailsVariant[0].toString();
mModelUrls << modelDetailsVariant[1].toString();
}
// Everything went fine, so...
mErrorMessage = QString();
} else {
// Something went wrong, so...
mErrorMessage = jsonParseError.errorString();
}
} else {
// Something went wrong, so...
mErrorMessage = pNetworkReply->errorString();
}
// Initialise the output using whatever search criteria is present
on_filterValue_textChanged(mGui->filterValue->text());
// Re-enable the GUI side
mGui->dockWidgetContents->setEnabled(true);
// Give, within the current window, the focus to mGui->filterValue, but
// only if the current window already has the focus
Core::setFocusTo(mGui->filterValue);
// Delete (later) the network reply
pNetworkReply->deleteLater();
}
//==============================================================================
void CellmlModelRepositoryWindowWindow::sslErrors(QNetworkReply *pNetworkReply,
const QList<QSslError> &pSslErrors)
{
// Ignore the SSL errors since we trust the website and therefore its
// certificate (even if it is invalid, e.g. it has expired)
pNetworkReply->ignoreSslErrors(pSslErrors);
}
//==============================================================================
void CellmlModelRepositoryWindowWindow::showCustomContextMenu(const QPoint &pPosition) const
{
Q_UNUSED(pPosition);
// Show our context menu for our CellML Models Repository widget
mContextMenu->exec(QCursor::pos());
}
//==============================================================================
void CellmlModelRepositoryWindowWindow::retrieveModelList(const bool &pVisible)
{
// Retrieve the list of models, if we are becoming visible and the list of
// models has never been requested before
static bool firstTime = true;
if (pVisible && firstTime) {
firstTime = false;
on_refreshButton_clicked();
}
}
//==============================================================================
} // namespace CellMLModelRepositoryWindow
} // namespace OpenCOR
//==============================================================================
// End of file
//==============================================================================
<|endoftext|>
|
<commit_before>/**
MQTT433gateway - MQTT 433.92 MHz radio gateway utilizing ESPiLight
Project home: https://github.com/puuu/MQTT433gateway/
The MIT License (MIT)
Copyright (c) 2017 Jan Losinski
Permission is hereby granted, free of charge, to any person
obtaining a copy of this software and associated documentation files
(the "Software"), to deal in the Software without restriction,
including without limitation the rights to use, copy, modify, merge,
publish, distribute, sublicense, and/or sell copies of the Software,
and to permit persons to whom the Software is furnished to do so,
subject to the following conditions:
The above copyright notice and this permission notice shall be
included in all copies or substantial portions of the Software.
THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND,
EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF
MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND
NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS
BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN
ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN
CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
SOFTWARE.
*/
#include <ArduinoSimpleLogging.h>
#include <Version.h>
#include "MqttClient.h"
class PayloadString : public String {
public:
PayloadString(const uint8_t *data, unsigned int length) : String() {
if (reserve(length)) {
memcpy(buffer, data, length);
len = length;
}
}
};
MqttClient::MqttClient(const Settings &settings, WiFiClient &client)
: settings(settings), mqttClient(client), lastConnectAttempt(0) {}
MqttClient::~MqttClient() { mqttClient.disconnect(); }
void MqttClient::begin() {
using namespace std::placeholders;
mqttClient.setServer(settings.mqttBroker.c_str(), settings.mqttBrokerPort);
mqttClient.setCallback(std::bind(&MqttClient::onMessage, this, _1, _2, _3));
reconnect();
}
static String stateMessage(const bool online) {
return String(F("{\"chipId\":\"")) + chipId() +
String(F("\",\"firmware\":\"")) + fwVersion() + F("\",\"state\":\"") +
String(online ? F("online") : F("offline")) + String(F("\"}"));
}
bool MqttClient::connect() {
if (0 == settings.mqttUser.length()) {
return mqttClient.connect(settings.deviceName.c_str(),
settings.mqttStateTopic.c_str(), 0, true,
stateMessage(false).c_str());
} else {
return mqttClient.connect(
settings.deviceName.c_str(), settings.mqttUser.c_str(),
settings.mqttPassword.c_str(), settings.mqttStateTopic.c_str(), 0, true,
stateMessage(false).c_str());
}
}
void MqttClient::reconnect() {
if (lastConnectAttempt > 0 &&
(millis() - lastConnectAttempt) < MQTT_CONNECTION_ATTEMPT_DELAY) {
return;
}
if (!mqttClient.connected()) {
Logger.debug.println(F("Try to (re)connect to MQTT broker"));
if (connect()) {
Logger.info.println(F("MQTT connected."));
if (subsrcibe()) {
mqttClient.publish(settings.mqttStateTopic.c_str(),
stateMessage(true).c_str(), true);
mqttClient.publish(settings.mqttVersionTopic.c_str(),
fwJsonVersion(false).c_str(), true);
Logger.info.println(F("MQTT subscribed."));
} else {
Logger.error.println(F("MQTT subsrcibe failed!"));
}
} else {
Logger.error.println(F("MQTT connect failed!"));
}
}
lastConnectAttempt = millis();
}
bool MqttClient::subsrcibe() {
String topic = settings.mqttSendTopic + "+";
Logger.debug.print(F("MQTT subscribe to topic: "));
Logger.debug.println(topic);
return mqttClient.subscribe(topic.c_str());
}
void MqttClient::loop() {
reconnect();
mqttClient.loop();
}
void MqttClient::onMessage(char *topic, uint8_t *payload, unsigned int length) {
PayloadString strPayload(payload, length);
String strTopic(topic);
Logger.debug.print(F("New MQTT message: "));
Logger.debug.print(strTopic);
Logger.debug.print(F(" .. "));
Logger.debug.println(strPayload);
if (strTopic.startsWith(settings.mqttSendTopic)) {
if (onRfDataCallback) {
onRfDataCallback(String(topic + settings.mqttSendTopic.length()),
strPayload);
}
}
}
void MqttClient::registerRfDataHandler(const MqttClient::RfDataCb &cb) {
onRfDataCallback = cb;
}
void MqttClient::publishCode(const String &protocol, const String &payload) {
String topic = settings.mqttReceiveTopic + protocol;
Logger.debug.print(F("Publish MQTT message: "));
Logger.debug.print(topic);
Logger.debug.print(F(" retain="));
Logger.debug.print(settings.mqttRetain);
Logger.debug.print(F(" .. "));
Logger.debug.println(payload);
mqttClient.publish(topic.c_str(), payload.c_str(), settings.mqttRetain);
}
bool MqttClient::isConnected() { return mqttClient.connected(); }
<commit_msg>lib/MQTT/MqttClient.cpp: let state topic only be 'online' or 'offline'<commit_after>/**
MQTT433gateway - MQTT 433.92 MHz radio gateway utilizing ESPiLight
Project home: https://github.com/puuu/MQTT433gateway/
The MIT License (MIT)
Copyright (c) 2017 Jan Losinski
Permission is hereby granted, free of charge, to any person
obtaining a copy of this software and associated documentation files
(the "Software"), to deal in the Software without restriction,
including without limitation the rights to use, copy, modify, merge,
publish, distribute, sublicense, and/or sell copies of the Software,
and to permit persons to whom the Software is furnished to do so,
subject to the following conditions:
The above copyright notice and this permission notice shall be
included in all copies or substantial portions of the Software.
THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND,
EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF
MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND
NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS
BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN
ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN
CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
SOFTWARE.
*/
#include <ArduinoSimpleLogging.h>
#include <Version.h>
#include "MqttClient.h"
class PayloadString : public String {
public:
PayloadString(const uint8_t *data, unsigned int length) : String() {
if (reserve(length)) {
memcpy(buffer, data, length);
len = length;
}
}
};
MqttClient::MqttClient(const Settings &settings, WiFiClient &client)
: settings(settings), mqttClient(client), lastConnectAttempt(0) {}
MqttClient::~MqttClient() { mqttClient.disconnect(); }
void MqttClient::begin() {
using namespace std::placeholders;
mqttClient.setServer(settings.mqttBroker.c_str(), settings.mqttBrokerPort);
mqttClient.setCallback(std::bind(&MqttClient::onMessage, this, _1, _2, _3));
reconnect();
}
static String stateMessage(const bool online) {
return String(online ? F("online") : F("offline"));
}
bool MqttClient::connect() {
if (0 == settings.mqttUser.length()) {
return mqttClient.connect(settings.deviceName.c_str(),
settings.mqttStateTopic.c_str(), 0, true,
stateMessage(false).c_str());
} else {
return mqttClient.connect(
settings.deviceName.c_str(), settings.mqttUser.c_str(),
settings.mqttPassword.c_str(), settings.mqttStateTopic.c_str(), 0, true,
stateMessage(false).c_str());
}
}
void MqttClient::reconnect() {
if (lastConnectAttempt > 0 &&
(millis() - lastConnectAttempt) < MQTT_CONNECTION_ATTEMPT_DELAY) {
return;
}
if (!mqttClient.connected()) {
Logger.debug.println(F("Try to (re)connect to MQTT broker"));
if (connect()) {
Logger.info.println(F("MQTT connected."));
if (subsrcibe()) {
mqttClient.publish(settings.mqttStateTopic.c_str(),
stateMessage(true).c_str(), true);
mqttClient.publish(settings.mqttVersionTopic.c_str(),
fwJsonVersion(false).c_str(), true);
Logger.info.println(F("MQTT subscribed."));
} else {
Logger.error.println(F("MQTT subsrcibe failed!"));
}
} else {
Logger.error.println(F("MQTT connect failed!"));
}
}
lastConnectAttempt = millis();
}
bool MqttClient::subsrcibe() {
String topic = settings.mqttSendTopic + "+";
Logger.debug.print(F("MQTT subscribe to topic: "));
Logger.debug.println(topic);
return mqttClient.subscribe(topic.c_str());
}
void MqttClient::loop() {
reconnect();
mqttClient.loop();
}
void MqttClient::onMessage(char *topic, uint8_t *payload, unsigned int length) {
PayloadString strPayload(payload, length);
String strTopic(topic);
Logger.debug.print(F("New MQTT message: "));
Logger.debug.print(strTopic);
Logger.debug.print(F(" .. "));
Logger.debug.println(strPayload);
if (strTopic.startsWith(settings.mqttSendTopic)) {
if (onRfDataCallback) {
onRfDataCallback(String(topic + settings.mqttSendTopic.length()),
strPayload);
}
}
}
void MqttClient::registerRfDataHandler(const MqttClient::RfDataCb &cb) {
onRfDataCallback = cb;
}
void MqttClient::publishCode(const String &protocol, const String &payload) {
String topic = settings.mqttReceiveTopic + protocol;
Logger.debug.print(F("Publish MQTT message: "));
Logger.debug.print(topic);
Logger.debug.print(F(" retain="));
Logger.debug.print(settings.mqttRetain);
Logger.debug.print(F(" .. "));
Logger.debug.println(payload);
mqttClient.publish(topic.c_str(), payload.c_str(), settings.mqttRetain);
}
bool MqttClient::isConnected() { return mqttClient.connected(); }
<|endoftext|>
|
<commit_before>//===------------------------- MemLocation.cpp ----------------------------===//
//
// This source file is part of the Swift.org open source project
//
// Copyright (c) 2014 - 2015 Apple Inc. and the Swift project authors
// Licensed under Apache License v2.0 with Runtime Library Exception
//
// See http://swift.org/LICENSE.txt for license information
// See http://swift.org/CONTRIBUTORS.txt for the list of Swift project authors
//
//===----------------------------------------------------------------------===//
#define DEBUG_TYPE "sil-memlocation"
#include "swift/SIL/MemLocation.h"
#include "llvm/Support/Debug.h"
using namespace swift;
//===----------------------------------------------------------------------===//
// Utility Functions
//===----------------------------------------------------------------------===//
static inline void removeMemLocations(MemLocationValueMap &Values,
MemLocationList &FirstLevel) {
for (auto &X : FirstLevel)
Values.erase(X);
}
//===----------------------------------------------------------------------===//
// SILValue Projection
//===----------------------------------------------------------------------===//
void SILValueProjection::print() const {
llvm::outs() << Base;
llvm::outs() << Path.getValue();
}
//===----------------------------------------------------------------------===//
// Load Store Value
//===----------------------------------------------------------------------===//
SILValue LoadStoreValue::createExtract(SILValue Base,
Optional<ProjectionPath> &Path,
SILInstruction *Inst) {
// If we found a projection path, but there are no projections, then the two
// loads must be the same, return PrevLI.
if (!Path || Path->empty())
return Base;
// Ok, at this point we know that we can construct our aggregate projections
// from our list of address projections.
SILValue LastExtract = Base;
SILBuilder Builder(Inst);
// Construct the path!
for (auto PI = Path->rbegin(), PE = Path->rend(); PI != PE; ++PI) {
LastExtract =
PI->createValueProjection(Builder, Inst->getLoc(), LastExtract).get();
continue;
}
// Return the last extract we created.
return LastExtract;
}
//===----------------------------------------------------------------------===//
// Memory Location
//===----------------------------------------------------------------------===//
void MemLocation::initialize(SILValue Dest) {
Base = getUnderlyingObject(Dest);
Path = ProjectionPath::getAddrProjectionPath(Base, Dest);
}
bool MemLocation::isMustAliasMemLocation(const MemLocation &RHS,
AliasAnalysis *AA) {
// If the bases are not must-alias, the locations may not alias.
if (!AA->isMustAlias(Base, RHS.getBase()))
return false;
// If projection paths are different, then the locations can not alias.
if (!hasIdenticalProjectionPath(RHS))
return false;
return true;
}
bool MemLocation::isMayAliasMemLocation(const MemLocation &RHS,
AliasAnalysis *AA) {
// If the bases do not alias, then the locations can not alias.
if (AA->isNoAlias(Base, RHS.getBase()))
return false;
// If one projection path is a prefix of another, then the locations
// could alias.
if (hasNonEmptySymmetricPathDifference(RHS))
return false;
return true;
}
MemLocation MemLocation::createMemLocation(SILValue Base, ProjectionPath &P1,
ProjectionPath &P2) {
ProjectionPath T;
T.append(P1);
T.append(P2);
return MemLocation(Base, T);
}
void MemLocation::getFirstLevelMemLocations(MemLocationList &Locs,
SILModule *Mod) {
SILType Ty = getType();
llvm::SmallVector<Projection, 8> Out;
Projection::getFirstLevelAddrProjections(Ty, *Mod, Out);
for (auto &X : Out) {
ProjectionPath P;
P.append(X);
P.append(Path.getValue());
Locs.push_back(MemLocation(Base, P));
}
}
void MemLocation::expand(MemLocation &Base, SILModule *Mod,
MemLocationList &Locs,
TypeExpansionMap &TypeExpansionVault) {
// To expand a memory location to its indivisible parts, we first get the
// address projection paths from the accessed type to each indivisible field,
// i.e. leaf nodes, then we append these projection paths to the Base.
//
// NOTE: we get the address projection because the Base memory location is
// initialized with address projection paths. By keeping it consistent makes
// it easier to implement the getType function for MemLocation.
//
SILType BaseType = Base.getType();
if (TypeExpansionVault.find(BaseType) == TypeExpansionVault.end()) {
// There is no cached expansion for this type, build and cache it now.
ProjectionPathList Paths;
ProjectionPath::expandTypeIntoLeafProjectionPaths(BaseType, Mod, Paths,
true);
for (auto &X : Paths) {
TypeExpansionVault[Base.getType()].push_back(std::move(X.getValue()));
}
}
// Construct the MemLocation by appending the projection path from the
// accessed node to the leaf nodes.
for (auto &X : TypeExpansionVault[BaseType]) {
Locs.push_back(MemLocation::createMemLocation(Base.getBase(), X.getValue(),
Base.getPath().getValue()));
}
}
void MemLocation::reduce(MemLocation &Base, SILModule *Mod,
MemLocationSet &Locs) {
// First, construct the MemLocation by appending the projection path from the
// accessed node to the leaf nodes.
MemLocationList ALocs;
ProjectionPathList Paths;
ProjectionPath::expandTypeIntoLeafProjectionPaths(Base.getType(), Mod, Paths,
false);
for (auto &X : Paths) {
ALocs.push_back(MemLocation::createMemLocation(Base.getBase(), X.getValue(),
Base.getPath().getValue()));
}
// Second, go from leaf nodes to their parents. This guarantees that at the
// point the parent is processed, its children have been processed already.
for (auto I = ALocs.rbegin(), E = ALocs.rend(); I != E; ++I) {
MemLocationList FirstLevel;
I->getFirstLevelMemLocations(FirstLevel, Mod);
// Reached the end of the projection tree, this is a leaf node.
if (FirstLevel.empty())
continue;
// If this is a class reference type, we have reached end of the type tree.
if (I->getType().getClassOrBoundGenericClass())
continue;
// This is NOT a leaf node, check whether all its first level children are
// alive.
bool Alive = true;
for (auto &X : FirstLevel) {
if (Locs.find(X) != Locs.end())
continue;
Alive = false;
}
// All first level locations are alive, create the new aggregated location.
if (Alive) {
for (auto &X : FirstLevel)
Locs.erase(X);
Locs.insert(*I);
}
}
}
void MemLocation::expandWithValues(MemLocation &Base, SILValue &Val,
SILModule *Mod, MemLocationList &Locs,
LoadStoreValueList &Vals) {
// To expand a memory location to its indivisible parts, we first get the
// projection paths from the accessed type to each indivisible field, i.e.
// leaf nodes, then we append these projection paths to the Base.
ProjectionPathList Paths;
ProjectionPath::expandTypeIntoLeafProjectionPaths(Base.getType(), Mod, Paths,
true);
// Construct the MemLocation and LoadStoreValues by appending the projection
// path
// from the accessed node to the leaf nodes.
for (auto &X : Paths) {
Locs.push_back(MemLocation::createMemLocation(Base.getBase(), X.getValue(),
Base.getPath().getValue()));
Vals.push_back(LoadStoreValue(Val, X.getValue()));
}
}
SILValue MemLocation::reduceWithValues(MemLocation &Base, SILModule *Mod,
MemLocationValueMap &Values,
SILInstruction *InsertPt) {
// Walk bottom up the projection tree, try to reason about how to construct
// a single SILValue out of all the available values for all the memory
// locations.
//
// First, get a list of all the leaf nodes and intermediate nodes for the
// Base memory location.
MemLocationList ALocs;
ProjectionPathList Paths;
ProjectionPath::expandTypeIntoLeafProjectionPaths(Base.getType(), Mod, Paths,
false);
for (auto &X : Paths) {
ALocs.push_back(MemLocation::createMemLocation(Base.getBase(), X.getValue(),
Base.getPath().getValue()));
}
// Second, go from leaf nodes to their parents. This guarantees that at the
// point the parent is processed, its children have been processed already.
for (auto I = ALocs.rbegin(), E = ALocs.rend(); I != E; ++I) {
// This is a leaf node, we have a value for it.
//
// Reached the end of the projection tree, this is a leaf node.
MemLocationList FirstLevel;
I->getFirstLevelMemLocations(FirstLevel, Mod);
if (FirstLevel.empty())
continue;
// If this is a class reference type, we have reached end of the type tree.
if (I->getType().getClassOrBoundGenericClass())
continue;
// This is NOT a leaf node, we need to construct a value for it.
//
// If there are more than 1 children and all the children nodes have
// LoadStoreValues with the same base. we can get away by not extracting
// value
// for every single field.
//
// Simply create a new node with all the aggregated base value, i.e.
// stripping off the last level projection.
//
bool HasIdenticalValueBase = true;
auto Iter = FirstLevel.begin();
LoadStoreValue &FirstVal = Values[*Iter];
SILValue FirstBase = FirstVal.getBase();
Iter = std::next(Iter);
for (auto EndIter = FirstLevel.end(); Iter != EndIter; ++Iter) {
LoadStoreValue &V = Values[*Iter];
HasIdenticalValueBase &= (FirstBase == V.getBase());
}
if (HasIdenticalValueBase &&
(FirstLevel.size() > 1 || !FirstVal.hasEmptyProjectionPath())) {
Values[*I] = FirstVal.stripLastLevelProjection();
// We have a value for the parent, remove all the values for children.
removeMemLocations(Values, FirstLevel);
continue;
}
// In 2 cases do we need aggregation.
//
// 1. If there is only 1 child and we can not strip off any projections,
// that means we need to create an aggregation.
//
// 2. Children have values from different bases, We need to create
// extractions and aggregation in this case.
//
llvm::SmallVector<SILValue, 8> Vals;
for (auto &X : FirstLevel) {
Vals.push_back(Values[X].materialize(InsertPt));
}
SILBuilder Builder(InsertPt);
NullablePtr<swift::SILInstruction> AI =
Projection::createAggFromFirstLevelProjections(
Builder, InsertPt->getLoc(), I->getType(), Vals);
// This is the Value for the current node.
ProjectionPath P;
Values[*I] = LoadStoreValue(SILValue(AI.get()), P);
removeMemLocations(Values, FirstLevel);
// Keep iterating until we have reach the top-most level of the projection
// tree.
// i.e. the memory location represented by the Base.
}
assert(Values.size() == 1 && "Should have a single location this point");
// Finally materialize and return the forwarding SILValue.
return Values.begin()->second.materialize(InsertPt);
}
void MemLocation::enumerateMemLocation(SILModule *M, SILValue Mem,
std::vector<MemLocation> &LV,
MemLocationIndexMap &BM,
TypeExpansionMap &TV) {
// Construct a Location to represent the memory written by this instruction.
MemLocation L(Mem);
// If we cant figure out the Base or Projection Path for the memory location,
// simply ignore it for now.
if (!L.isValid())
return;
// Expand the given Mem into individual fields and add them to the
// locationvault.
MemLocationList Locs;
MemLocation::expand(L, M, Locs, TV);
for (auto &Loc : Locs) {
BM[Loc] = LV.size();
LV.push_back(Loc);
}
}
void MemLocation::enumerateMemLocations(SILFunction &F,
std::vector<MemLocation> &LV,
MemLocationIndexMap &BM,
TypeExpansionMap &TV) {
// Enumerate all locations accessed by the loads or stores.
//
// TODO: process more instructions as we process more instructions in
// processInstruction.
//
SILValue Op;
for (auto &B : F) {
for (auto &I : B) {
if (auto *LI = dyn_cast<LoadInst>(&I)) {
enumerateMemLocation(&I.getModule(), LI->getOperand(), LV, BM, TV);
} else if (auto *SI = dyn_cast<StoreInst>(&I)) {
enumerateMemLocation(&I.getModule(), SI->getDest(), LV, BM, TV);
}
}
}
}
<commit_msg>Refactor in MemLocation. NFC<commit_after>//===------------------------- MemLocation.cpp ----------------------------===//
//
// This source file is part of the Swift.org open source project
//
// Copyright (c) 2014 - 2015 Apple Inc. and the Swift project authors
// Licensed under Apache License v2.0 with Runtime Library Exception
//
// See http://swift.org/LICENSE.txt for license information
// See http://swift.org/CONTRIBUTORS.txt for the list of Swift project authors
//
//===----------------------------------------------------------------------===//
#define DEBUG_TYPE "sil-memlocation"
#include "swift/SIL/MemLocation.h"
#include "llvm/Support/Debug.h"
using namespace swift;
//===----------------------------------------------------------------------===//
// Utility Functions
//===----------------------------------------------------------------------===//
static inline void removeMemLocations(MemLocationValueMap &Values,
MemLocationList &FirstLevel) {
for (auto &X : FirstLevel)
Values.erase(X);
}
//===----------------------------------------------------------------------===//
// SILValue Projection
//===----------------------------------------------------------------------===//
void SILValueProjection::print() const {
llvm::outs() << Base;
llvm::outs() << Path.getValue();
}
//===----------------------------------------------------------------------===//
// Load Store Value
//===----------------------------------------------------------------------===//
SILValue LoadStoreValue::createExtract(SILValue Base,
Optional<ProjectionPath> &Path,
SILInstruction *Inst) {
// If we found a projection path, but there are no projections, then the two
// loads must be the same, return PrevLI.
if (!Path || Path->empty())
return Base;
// Ok, at this point we know that we can construct our aggregate projections
// from our list of address projections.
SILValue LastExtract = Base;
SILBuilder Builder(Inst);
// Construct the path!
for (auto PI = Path->rbegin(), PE = Path->rend(); PI != PE; ++PI) {
LastExtract =
PI->createValueProjection(Builder, Inst->getLoc(), LastExtract).get();
continue;
}
// Return the last extract we created.
return LastExtract;
}
//===----------------------------------------------------------------------===//
// Memory Location
//===----------------------------------------------------------------------===//
void MemLocation::initialize(SILValue Dest) {
Base = getUnderlyingObject(Dest);
Path = ProjectionPath::getAddrProjectionPath(Base, Dest);
}
bool MemLocation::isMustAliasMemLocation(const MemLocation &RHS,
AliasAnalysis *AA) {
// If the bases are not must-alias, the locations may not alias.
if (!AA->isMustAlias(Base, RHS.getBase()))
return false;
// If projection paths are different, then the locations can not alias.
if (!hasIdenticalProjectionPath(RHS))
return false;
return true;
}
bool MemLocation::isMayAliasMemLocation(const MemLocation &RHS,
AliasAnalysis *AA) {
// If the bases do not alias, then the locations can not alias.
if (AA->isNoAlias(Base, RHS.getBase()))
return false;
// If one projection path is a prefix of another, then the locations
// could alias.
if (hasNonEmptySymmetricPathDifference(RHS))
return false;
return true;
}
MemLocation MemLocation::createMemLocation(SILValue Base, ProjectionPath &P1,
ProjectionPath &P2) {
ProjectionPath T;
T.append(P1);
T.append(P2);
return MemLocation(Base, T);
}
void MemLocation::getFirstLevelMemLocations(MemLocationList &Locs,
SILModule *Mod) {
SILType Ty = getType();
llvm::SmallVector<Projection, 8> Out;
Projection::getFirstLevelAddrProjections(Ty, *Mod, Out);
for (auto &X : Out) {
ProjectionPath P;
P.append(X);
P.append(Path.getValue());
Locs.push_back(MemLocation(Base, P));
}
}
void MemLocation::expand(MemLocation &Base, SILModule *Mod,
MemLocationList &Locs,
TypeExpansionMap &TECache) {
// To expand a memory location to its indivisible parts, we first get the
// address projection paths from the accessed type to each indivisible field,
// i.e. leaf nodes, then we append these projection paths to the Base.
//
// NOTE: we get the address projection because the Base memory location is
// initialized with address projection paths. By keeping it consistent makes
// it easier to implement the getType function for MemLocation.
//
SILType BaseType = Base.getType();
if (TECache.find(BaseType) == TECache.end()) {
// There is no cached expansion for this type, build and cache it now.
ProjectionPathList Paths;
ProjectionPath::expandTypeIntoLeafProjectionPaths(BaseType, Mod, Paths,
true);
for (auto &P : Paths) {
TECache[BaseType()].push_back(std::move(P.getValue()));
}
}
// Construct the MemLocation by appending the projection path from the
// accessed node to the leaf nodes.
for (auto &X : TECache[BaseType]) {
Locs.push_back(MemLocation::createMemLocation(Base.getBase(), X.getValue(),
Base.getPath().getValue()));
}
}
void MemLocation::reduce(MemLocation &Base, SILModule *Mod,
MemLocationSet &Locs) {
// First, construct the MemLocation by appending the projection path from the
// accessed node to the leaf nodes.
MemLocationList ALocs;
ProjectionPathList Paths;
ProjectionPath::expandTypeIntoLeafProjectionPaths(Base.getType(), Mod, Paths,
false);
for (auto &X : Paths) {
ALocs.push_back(MemLocation::createMemLocation(Base.getBase(), X.getValue(),
Base.getPath().getValue()));
}
// Second, go from leaf nodes to their parents. This guarantees that at the
// point the parent is processed, its children have been processed already.
for (auto I = ALocs.rbegin(), E = ALocs.rend(); I != E; ++I) {
MemLocationList FirstLevel;
I->getFirstLevelMemLocations(FirstLevel, Mod);
// Reached the end of the projection tree, this is a leaf node.
if (FirstLevel.empty())
continue;
// If this is a class reference type, we have reached end of the type tree.
if (I->getType().getClassOrBoundGenericClass())
continue;
// This is NOT a leaf node, check whether all its first level children are
// alive.
bool Alive = true;
for (auto &X : FirstLevel) {
if (Locs.find(X) != Locs.end())
continue;
Alive = false;
}
// All first level locations are alive, create the new aggregated location.
if (Alive) {
for (auto &X : FirstLevel)
Locs.erase(X);
Locs.insert(*I);
}
}
}
void MemLocation::expandWithValues(MemLocation &Base, SILValue &Val,
SILModule *Mod, MemLocationList &Locs,
LoadStoreValueList &Vals) {
// To expand a memory location to its indivisible parts, we first get the
// projection paths from the accessed type to each indivisible field, i.e.
// leaf nodes, then we append these projection paths to the Base.
ProjectionPathList Paths;
ProjectionPath::expandTypeIntoLeafProjectionPaths(Base.getType(), Mod, Paths,
true);
// Construct the MemLocation and LoadStoreValues by appending the projection
// path
// from the accessed node to the leaf nodes.
for (auto &X : Paths) {
Locs.push_back(MemLocation::createMemLocation(Base.getBase(), X.getValue(),
Base.getPath().getValue()));
Vals.push_back(LoadStoreValue(Val, X.getValue()));
}
}
SILValue MemLocation::reduceWithValues(MemLocation &Base, SILModule *Mod,
MemLocationValueMap &Values,
SILInstruction *InsertPt) {
// Walk bottom up the projection tree, try to reason about how to construct
// a single SILValue out of all the available values for all the memory
// locations.
//
// First, get a list of all the leaf nodes and intermediate nodes for the
// Base memory location.
MemLocationList ALocs;
ProjectionPathList Paths;
ProjectionPath::expandTypeIntoLeafProjectionPaths(Base.getType(), Mod, Paths,
false);
for (auto &X : Paths) {
ALocs.push_back(MemLocation::createMemLocation(Base.getBase(), X.getValue(),
Base.getPath().getValue()));
}
// Second, go from leaf nodes to their parents. This guarantees that at the
// point the parent is processed, its children have been processed already.
for (auto I = ALocs.rbegin(), E = ALocs.rend(); I != E; ++I) {
// This is a leaf node, we have a value for it.
//
// Reached the end of the projection tree, this is a leaf node.
MemLocationList FirstLevel;
I->getFirstLevelMemLocations(FirstLevel, Mod);
if (FirstLevel.empty())
continue;
// If this is a class reference type, we have reached end of the type tree.
if (I->getType().getClassOrBoundGenericClass())
continue;
// This is NOT a leaf node, we need to construct a value for it.
//
// If there are more than 1 children and all the children nodes have
// LoadStoreValues with the same base. we can get away by not extracting
// value
// for every single field.
//
// Simply create a new node with all the aggregated base value, i.e.
// stripping off the last level projection.
//
bool HasIdenticalValueBase = true;
auto Iter = FirstLevel.begin();
LoadStoreValue &FirstVal = Values[*Iter];
SILValue FirstBase = FirstVal.getBase();
Iter = std::next(Iter);
for (auto EndIter = FirstLevel.end(); Iter != EndIter; ++Iter) {
LoadStoreValue &V = Values[*Iter];
HasIdenticalValueBase &= (FirstBase == V.getBase());
}
if (HasIdenticalValueBase &&
(FirstLevel.size() > 1 || !FirstVal.hasEmptyProjectionPath())) {
Values[*I] = FirstVal.stripLastLevelProjection();
// We have a value for the parent, remove all the values for children.
removeMemLocations(Values, FirstLevel);
continue;
}
// In 2 cases do we need aggregation.
//
// 1. If there is only 1 child and we can not strip off any projections,
// that means we need to create an aggregation.
//
// 2. Children have values from different bases, We need to create
// extractions and aggregation in this case.
//
llvm::SmallVector<SILValue, 8> Vals;
for (auto &X : FirstLevel) {
Vals.push_back(Values[X].materialize(InsertPt));
}
SILBuilder Builder(InsertPt);
NullablePtr<swift::SILInstruction> AI =
Projection::createAggFromFirstLevelProjections(
Builder, InsertPt->getLoc(), I->getType(), Vals);
// This is the Value for the current node.
ProjectionPath P;
Values[*I] = LoadStoreValue(SILValue(AI.get()), P);
removeMemLocations(Values, FirstLevel);
// Keep iterating until we have reach the top-most level of the projection
// tree.
// i.e. the memory location represented by the Base.
}
assert(Values.size() == 1 && "Should have a single location this point");
// Finally materialize and return the forwarding SILValue.
return Values.begin()->second.materialize(InsertPt);
}
void MemLocation::enumerateMemLocation(SILModule *M, SILValue Mem,
std::vector<MemLocation> &LV,
MemLocationIndexMap &BM,
TypeExpansionMap &TV) {
// Construct a Location to represent the memory written by this instruction.
MemLocation L(Mem);
// If we cant figure out the Base or Projection Path for the memory location,
// simply ignore it for now.
if (!L.isValid())
return;
// Expand the given Mem into individual fields and add them to the
// locationvault.
MemLocationList Locs;
MemLocation::expand(L, M, Locs, TV);
for (auto &Loc : Locs) {
BM[Loc] = LV.size();
LV.push_back(Loc);
}
}
void MemLocation::enumerateMemLocations(SILFunction &F,
std::vector<MemLocation> &LV,
MemLocationIndexMap &BM,
TypeExpansionMap &TV) {
// Enumerate all locations accessed by the loads or stores.
//
// TODO: process more instructions as we process more instructions in
// processInstruction.
//
SILValue Op;
for (auto &B : F) {
for (auto &I : B) {
if (auto *LI = dyn_cast<LoadInst>(&I)) {
enumerateMemLocation(&I.getModule(), LI->getOperand(), LV, BM, TV);
} else if (auto *SI = dyn_cast<StoreInst>(&I)) {
enumerateMemLocation(&I.getModule(), SI->getDest(), LV, BM, TV);
}
}
}
}
<|endoftext|>
|
<commit_before>////////////////////////////////////////////////////////////////////////////////
/// @brief V8 line editor
///
/// @file
///
/// DISCLAIMER
///
/// Copyright 2014-2015 ArangoDB GmbH, Cologne, Germany
///
/// Licensed under the Apache License, Version 2.0 (the "License");
/// you may not use this file except in compliance with the License.
/// You may obtain a copy of the License at
///
/// http://www.apache.org/licenses/LICENSE-2.0
///
/// Unless required by applicable law or agreed to in writing, software
/// distributed under the License is distributed on an "AS IS" BASIS,
/// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
/// See the License for the specific language governing permissions and
/// limitations under the License.
///
/// Copyright holder is ArangoDB GmbH, Cologne, Germany
///
/// @author Dr. Frank Celler
/// @author Copyright 2014-2015, ArangoDB GmbH, Cologne, Germany
/// @author Copyright 2011-2013, triAGENS GmbH, Cologne, Germany
////////////////////////////////////////////////////////////////////////////////
#include "V8LineEditor.h"
#include "Basics/logging.h"
#include "Basics/StringUtils.h"
#include "Basics/tri-strings.h"
#include "Utilities/ShellImplementation.h"
#include "Utilities/ShellImplFactory.h"
#include "V8/v8-utils.h"
using namespace std;
using namespace triagens;
using namespace arangodb;
// -----------------------------------------------------------------------------
// --SECTION-- helper functions
// -----------------------------------------------------------------------------
////////////////////////////////////////////////////////////////////////////////
/// @brief signal handler for CTRL-C
////////////////////////////////////////////////////////////////////////////////
#ifndef _WIN32
static void SignalHandler (int signal) {
// get the instance of the console
auto instance = V8LineEditor::instance();
if (instance != nullptr) {
if (instance->isExecutingCommand()) {
v8::Isolate* isolate = instance->isolate();
if (! v8::V8::IsExecutionTerminating(isolate)) {
v8::V8::TerminateExecution(isolate);
}
}
instance->signal();
}
}
#endif
// -----------------------------------------------------------------------------
// --SECTION-- class V8Completer
// -----------------------------------------------------------------------------
// -----------------------------------------------------------------------------
// --SECTION-- Completer methods
// -----------------------------------------------------------------------------
////////////////////////////////////////////////////////////////////////////////
/// {@inheritDoc}
////////////////////////////////////////////////////////////////////////////////
bool V8Completer::isComplete (std::string const& source, size_t lineno) {
int openParen = 0;
int openBrackets = 0;
int openBraces = 0;
int openStrings = 0; // only used for template strings, which can be multi-line
int openComments = 0;
enum line_parse_state_e {
NORMAL, // start
NORMAL_1, // from NORMAL: seen a single /
DOUBLE_QUOTE, // from NORMAL: seen a single "
DOUBLE_QUOTE_ESC, // from DOUBLE_QUOTE: seen a backslash
SINGLE_QUOTE, // from NORMAL: seen a single '
SINGLE_QUOTE_ESC, // from SINGLE_QUOTE: seen a backslash
BACKTICK, // from NORMAL: seen a single `
BACKTICK_ESC, // from BACKTICK: seen a backslash
MULTI_COMMENT, // from NORMAL_1: seen a *
MULTI_COMMENT_1, // from MULTI_COMMENT, seen a *
SINGLE_COMMENT // from NORMAL_1; seen a /
};
char const* ptr = source.c_str();
char const* end = ptr + source.length();
line_parse_state_e state = NORMAL;
while (ptr < end) {
if (state == DOUBLE_QUOTE) {
if (*ptr == '\\') {
state = DOUBLE_QUOTE_ESC;
}
else if (*ptr == '"') {
state = NORMAL;
}
++ptr;
}
else if (state == DOUBLE_QUOTE_ESC) {
state = DOUBLE_QUOTE;
ptr++;
}
else if (state == SINGLE_QUOTE) {
if (*ptr == '\\') {
state = SINGLE_QUOTE_ESC;
}
else if (*ptr == '\'') {
state = NORMAL;
}
++ptr;
}
else if (state == SINGLE_QUOTE_ESC) {
state = SINGLE_QUOTE;
ptr++;
}
else if (state == BACKTICK) {
if (*ptr == '\\') {
state = BACKTICK_ESC;
}
else if (*ptr == '`') {
state = NORMAL;
--openStrings;
}
++ptr;
}
else if (state == BACKTICK_ESC) {
state = BACKTICK;
ptr++;
}
else if (state == MULTI_COMMENT) {
if (*ptr == '*') {
state = MULTI_COMMENT_1;
}
++ptr;
}
else if (state == MULTI_COMMENT_1) {
if (*ptr == '/') {
state = NORMAL;
--openComments;
}
++ptr;
}
else if (state == SINGLE_COMMENT) {
++ptr;
if (ptr == end) {
state = NORMAL;
--openComments;
}
}
else if (state == NORMAL_1) {
switch (*ptr) {
case '/':
state = SINGLE_COMMENT;
++openComments;
++ptr;
break;
case '*':
state = MULTI_COMMENT;
++openComments;
++ptr;
break;
default:
state = NORMAL; // try again, do not change ptr
break;
}
}
else {
switch (*ptr) {
case '"':
state = DOUBLE_QUOTE;
break;
case '\'':
state = SINGLE_QUOTE;
break;
case '`':
state = BACKTICK;
++openStrings;
break;
case '/':
state = NORMAL_1;
break;
case '(':
++openParen;
break;
case ')':
--openParen;
break;
case '[':
++openBrackets;
break;
case ']':
--openBrackets;
break;
case '{':
++openBraces;
break;
case '}':
--openBraces;
break;
case '\\':
++ptr;
break;
}
++ptr;
}
}
return (openParen <= 0 && openBrackets <= 0 && openBraces <= 0 && openStrings <= 0 && openComments <= 0);
}
////////////////////////////////////////////////////////////////////////////////
/// {@inheritDoc}
////////////////////////////////////////////////////////////////////////////////
vector<string> V8Completer::alternatives (char const * text) {
vector<string> result;
// locate global object or sub-object
v8::Isolate* isolate = v8::Isolate::GetCurrent();
v8::Local<v8::Context> context = isolate->GetCurrentContext();
v8::Handle<v8::Object> current = context->Global();
string path;
char* prefix;
if (*text != '\0') {
TRI_vector_string_t splitted = TRI_SplitString(text, '.');
if (1 < splitted._length) {
for (size_t i = 0; i < splitted._length - 1; ++i) {
v8::Handle<v8::String> name = TRI_V8_STRING(splitted._buffer[i]);
if (! current->Has(name)) {
TRI_DestroyVectorString(&splitted);
return result;
}
v8::Handle<v8::Value> val = current->Get(name);
if (! val->IsObject()) {
TRI_DestroyVectorString(&splitted);
return result;
}
current = val->ToObject();
path = path + splitted._buffer[i] + ".";
}
prefix = TRI_DuplicateString(splitted._buffer[splitted._length - 1]);
}
else {
prefix = TRI_DuplicateString(text);
}
TRI_DestroyVectorString(&splitted);
}
else {
prefix = TRI_DuplicateString(text);
}
v8::HandleScope scope(isolate);
// compute all possible completions
v8::Handle<v8::Array> properties;
v8::Handle<v8::String> cpl = TRI_V8_ASCII_STRING("_COMPLETIONS");
if (current->HasOwnProperty(cpl)) {
v8::Handle<v8::Value> funcVal = current->Get(cpl);
if (funcVal->IsFunction()) {
v8::Handle<v8::Function> func = v8::Handle<v8::Function>::Cast(funcVal);
v8::Handle<v8::Value> args;
try {
v8::Handle<v8::Value> cpls = func->Call(current, 0, &args);
if (cpls->IsArray()) {
properties = v8::Handle<v8::Array>::Cast(cpls);
}
}
catch (...) {
// silently ignore errors here
}
}
}
else {
properties = current->GetPropertyNames();
}
// locate
try {
if (! properties.IsEmpty()) {
uint32_t const n = properties->Length();
result.reserve(static_cast<size_t>(n));
for (uint32_t i = 0; i < n; ++i) {
v8::Handle<v8::Value> v = properties->Get(i);
TRI_Utf8ValueNFC str(TRI_UNKNOWN_MEM_ZONE, v);
char const* s = *str;
if (s != nullptr && *s) {
string suffix = (current->Get(v)->IsFunction()) ? "()" : "";
string name = path + s + suffix;
if (*prefix == '\0' || TRI_IsPrefixString(s, prefix)) {
result.emplace_back(name);
}
}
}
}
}
catch (...) {
// ignore errors in case of OOM
}
TRI_FreeString(TRI_CORE_MEM_ZONE, prefix);
return result;
}
// -----------------------------------------------------------------------------
// --SECTION-- class V8LineEditor
// -----------------------------------------------------------------------------
// -----------------------------------------------------------------------------
// --SECTION-- static private variables
// -----------------------------------------------------------------------------
////////////////////////////////////////////////////////////////////////////////
/// @brief the active instance of the editor
////////////////////////////////////////////////////////////////////////////////
std::atomic<V8LineEditor*> V8LineEditor::_instance(nullptr);
// -----------------------------------------------------------------------------
// --SECTION-- constructors and destructors
// -----------------------------------------------------------------------------
////////////////////////////////////////////////////////////////////////////////
/// @brief constructs a new editor
////////////////////////////////////////////////////////////////////////////////
V8LineEditor::V8LineEditor (v8::Isolate* isolate,
v8::Handle<v8::Context> context,
std::string const& history)
: LineEditor(history),
_isolate(isolate),
_context(context),
_completer(V8Completer()),
_executingCommand(false) {
// register global instance
TRI_ASSERT(_instance.load() == nullptr);
_instance.store(this);
}
////////////////////////////////////////////////////////////////////////////////
/// @brief destroys the editor
////////////////////////////////////////////////////////////////////////////////
V8LineEditor::~V8LineEditor () {
// unregister global instance
TRI_ASSERT(_instance.load() != nullptr);
_instance.store(nullptr);
}
// -----------------------------------------------------------------------------
// --SECTION-- public methods
// -----------------------------------------------------------------------------
////////////////////////////////////////////////////////////////////////////////
/// @brief whether or not the shell implementation supports colors
////////////////////////////////////////////////////////////////////////////////
bool V8LineEditor::supportsColors () const {
if (_shellImpl == nullptr) {
return false;
}
return _shellImpl->supportsColors();
}
// -----------------------------------------------------------------------------
// --SECTION-- protected methods
// -----------------------------------------------------------------------------
////////////////////////////////////////////////////////////////////////////////
/// @brief setup a signal handler for CTRL-C
////////////////////////////////////////////////////////////////////////////////
void V8LineEditor::setupCtrlCHandler () {
#ifndef _WIN32
if (_shellImpl != nullptr &&
_shellImpl->supportsCtrlCHandler()) {
struct sigaction sa;
sa.sa_flags = 0;
sigemptyset(&sa.sa_mask);
sa.sa_handler = &SignalHandler;
int res = sigaction(SIGINT, &sa, 0);
if (res != 0) {
LOG_ERROR("unable to install signal handler");
}
}
#endif
}
// -----------------------------------------------------------------------------
// --SECTION-- protected methods
// -----------------------------------------------------------------------------
void V8LineEditor::initializeShell () {
_shellImpl = ShellImplFactory::buildShell(_history, &_completer);
setupCtrlCHandler();
}
// -----------------------------------------------------------------------------
// --SECTION-- END-OF-FILE
// -----------------------------------------------------------------------------
<commit_msg>do not halt on single-line comments<commit_after>////////////////////////////////////////////////////////////////////////////////
/// @brief V8 line editor
///
/// @file
///
/// DISCLAIMER
///
/// Copyright 2014-2015 ArangoDB GmbH, Cologne, Germany
///
/// Licensed under the Apache License, Version 2.0 (the "License");
/// you may not use this file except in compliance with the License.
/// You may obtain a copy of the License at
///
/// http://www.apache.org/licenses/LICENSE-2.0
///
/// Unless required by applicable law or agreed to in writing, software
/// distributed under the License is distributed on an "AS IS" BASIS,
/// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
/// See the License for the specific language governing permissions and
/// limitations under the License.
///
/// Copyright holder is ArangoDB GmbH, Cologne, Germany
///
/// @author Dr. Frank Celler
/// @author Copyright 2014-2015, ArangoDB GmbH, Cologne, Germany
/// @author Copyright 2011-2013, triAGENS GmbH, Cologne, Germany
////////////////////////////////////////////////////////////////////////////////
#include "V8LineEditor.h"
#include "Basics/logging.h"
#include "Basics/StringUtils.h"
#include "Basics/tri-strings.h"
#include "Utilities/ShellImplementation.h"
#include "Utilities/ShellImplFactory.h"
#include "V8/v8-utils.h"
using namespace std;
using namespace triagens;
using namespace arangodb;
// -----------------------------------------------------------------------------
// --SECTION-- helper functions
// -----------------------------------------------------------------------------
////////////////////////////////////////////////////////////////////////////////
/// @brief signal handler for CTRL-C
////////////////////////////////////////////////////////////////////////////////
#ifndef _WIN32
static void SignalHandler (int signal) {
// get the instance of the console
auto instance = V8LineEditor::instance();
if (instance != nullptr) {
if (instance->isExecutingCommand()) {
v8::Isolate* isolate = instance->isolate();
if (! v8::V8::IsExecutionTerminating(isolate)) {
v8::V8::TerminateExecution(isolate);
}
}
instance->signal();
}
}
#endif
// -----------------------------------------------------------------------------
// --SECTION-- class V8Completer
// -----------------------------------------------------------------------------
// -----------------------------------------------------------------------------
// --SECTION-- Completer methods
// -----------------------------------------------------------------------------
////////////////////////////////////////////////////////////////////////////////
/// {@inheritDoc}
////////////////////////////////////////////////////////////////////////////////
bool V8Completer::isComplete (std::string const& source, size_t lineno) {
int openParen = 0;
int openBrackets = 0;
int openBraces = 0;
int openStrings = 0; // only used for template strings, which can be multi-line
int openComments = 0;
enum line_parse_state_e {
NORMAL, // start
NORMAL_1, // from NORMAL: seen a single /
DOUBLE_QUOTE, // from NORMAL: seen a single "
DOUBLE_QUOTE_ESC, // from DOUBLE_QUOTE: seen a backslash
SINGLE_QUOTE, // from NORMAL: seen a single '
SINGLE_QUOTE_ESC, // from SINGLE_QUOTE: seen a backslash
BACKTICK, // from NORMAL: seen a single `
BACKTICK_ESC, // from BACKTICK: seen a backslash
MULTI_COMMENT, // from NORMAL_1: seen a *
MULTI_COMMENT_1, // from MULTI_COMMENT, seen a *
SINGLE_COMMENT // from NORMAL_1; seen a /
};
char const* ptr = source.c_str();
char const* end = ptr + source.length();
line_parse_state_e state = NORMAL;
while (ptr < end) {
if (state == DOUBLE_QUOTE) {
if (*ptr == '\\') {
state = DOUBLE_QUOTE_ESC;
}
else if (*ptr == '"') {
state = NORMAL;
}
++ptr;
}
else if (state == DOUBLE_QUOTE_ESC) {
state = DOUBLE_QUOTE;
ptr++;
}
else if (state == SINGLE_QUOTE) {
if (*ptr == '\\') {
state = SINGLE_QUOTE_ESC;
}
else if (*ptr == '\'') {
state = NORMAL;
}
++ptr;
}
else if (state == SINGLE_QUOTE_ESC) {
state = SINGLE_QUOTE;
ptr++;
}
else if (state == BACKTICK) {
if (*ptr == '\\') {
state = BACKTICK_ESC;
}
else if (*ptr == '`') {
state = NORMAL;
--openStrings;
}
++ptr;
}
else if (state == BACKTICK_ESC) {
state = BACKTICK;
ptr++;
}
else if (state == MULTI_COMMENT) {
if (*ptr == '*') {
state = MULTI_COMMENT_1;
}
++ptr;
}
else if (state == MULTI_COMMENT_1) {
if (*ptr == '/') {
state = NORMAL;
--openComments;
}
++ptr;
}
else if (state == SINGLE_COMMENT) {
++ptr;
if (ptr == end || *ptr == '\n') {
state = NORMAL;
--openComments;
}
}
else if (state == NORMAL_1) {
switch (*ptr) {
case '/':
state = SINGLE_COMMENT;
++openComments;
++ptr;
break;
case '*':
state = MULTI_COMMENT;
++openComments;
++ptr;
break;
default:
state = NORMAL; // try again, do not change ptr
break;
}
}
else {
switch (*ptr) {
case '"':
state = DOUBLE_QUOTE;
break;
case '\'':
state = SINGLE_QUOTE;
break;
case '`':
state = BACKTICK;
++openStrings;
break;
case '/':
state = NORMAL_1;
break;
case '(':
++openParen;
break;
case ')':
--openParen;
break;
case '[':
++openBrackets;
break;
case ']':
--openBrackets;
break;
case '{':
++openBraces;
break;
case '}':
--openBraces;
break;
case '\\':
++ptr;
break;
}
++ptr;
}
}
return (openParen <= 0 && openBrackets <= 0 && openBraces <= 0 && openStrings <= 0 && openComments <= 0);
}
////////////////////////////////////////////////////////////////////////////////
/// {@inheritDoc}
////////////////////////////////////////////////////////////////////////////////
vector<string> V8Completer::alternatives (char const * text) {
vector<string> result;
// locate global object or sub-object
v8::Isolate* isolate = v8::Isolate::GetCurrent();
v8::Local<v8::Context> context = isolate->GetCurrentContext();
v8::Handle<v8::Object> current = context->Global();
string path;
char* prefix;
if (*text != '\0') {
TRI_vector_string_t splitted = TRI_SplitString(text, '.');
if (1 < splitted._length) {
for (size_t i = 0; i < splitted._length - 1; ++i) {
v8::Handle<v8::String> name = TRI_V8_STRING(splitted._buffer[i]);
if (! current->Has(name)) {
TRI_DestroyVectorString(&splitted);
return result;
}
v8::Handle<v8::Value> val = current->Get(name);
if (! val->IsObject()) {
TRI_DestroyVectorString(&splitted);
return result;
}
current = val->ToObject();
path = path + splitted._buffer[i] + ".";
}
prefix = TRI_DuplicateString(splitted._buffer[splitted._length - 1]);
}
else {
prefix = TRI_DuplicateString(text);
}
TRI_DestroyVectorString(&splitted);
}
else {
prefix = TRI_DuplicateString(text);
}
v8::HandleScope scope(isolate);
// compute all possible completions
v8::Handle<v8::Array> properties;
v8::Handle<v8::String> cpl = TRI_V8_ASCII_STRING("_COMPLETIONS");
if (current->HasOwnProperty(cpl)) {
v8::Handle<v8::Value> funcVal = current->Get(cpl);
if (funcVal->IsFunction()) {
v8::Handle<v8::Function> func = v8::Handle<v8::Function>::Cast(funcVal);
v8::Handle<v8::Value> args;
try {
v8::Handle<v8::Value> cpls = func->Call(current, 0, &args);
if (cpls->IsArray()) {
properties = v8::Handle<v8::Array>::Cast(cpls);
}
}
catch (...) {
// silently ignore errors here
}
}
}
else {
properties = current->GetPropertyNames();
}
// locate
try {
if (! properties.IsEmpty()) {
uint32_t const n = properties->Length();
result.reserve(static_cast<size_t>(n));
for (uint32_t i = 0; i < n; ++i) {
v8::Handle<v8::Value> v = properties->Get(i);
TRI_Utf8ValueNFC str(TRI_UNKNOWN_MEM_ZONE, v);
char const* s = *str;
if (s != nullptr && *s) {
string suffix = (current->Get(v)->IsFunction()) ? "()" : "";
string name = path + s + suffix;
if (*prefix == '\0' || TRI_IsPrefixString(s, prefix)) {
result.emplace_back(name);
}
}
}
}
}
catch (...) {
// ignore errors in case of OOM
}
TRI_FreeString(TRI_CORE_MEM_ZONE, prefix);
return result;
}
// -----------------------------------------------------------------------------
// --SECTION-- class V8LineEditor
// -----------------------------------------------------------------------------
// -----------------------------------------------------------------------------
// --SECTION-- static private variables
// -----------------------------------------------------------------------------
////////////////////////////////////////////////////////////////////////////////
/// @brief the active instance of the editor
////////////////////////////////////////////////////////////////////////////////
std::atomic<V8LineEditor*> V8LineEditor::_instance(nullptr);
// -----------------------------------------------------------------------------
// --SECTION-- constructors and destructors
// -----------------------------------------------------------------------------
////////////////////////////////////////////////////////////////////////////////
/// @brief constructs a new editor
////////////////////////////////////////////////////////////////////////////////
V8LineEditor::V8LineEditor (v8::Isolate* isolate,
v8::Handle<v8::Context> context,
std::string const& history)
: LineEditor(history),
_isolate(isolate),
_context(context),
_completer(V8Completer()),
_executingCommand(false) {
// register global instance
TRI_ASSERT(_instance.load() == nullptr);
_instance.store(this);
}
////////////////////////////////////////////////////////////////////////////////
/// @brief destroys the editor
////////////////////////////////////////////////////////////////////////////////
V8LineEditor::~V8LineEditor () {
// unregister global instance
TRI_ASSERT(_instance.load() != nullptr);
_instance.store(nullptr);
}
// -----------------------------------------------------------------------------
// --SECTION-- public methods
// -----------------------------------------------------------------------------
////////////////////////////////////////////////////////////////////////////////
/// @brief whether or not the shell implementation supports colors
////////////////////////////////////////////////////////////////////////////////
bool V8LineEditor::supportsColors () const {
if (_shellImpl == nullptr) {
return false;
}
return _shellImpl->supportsColors();
}
// -----------------------------------------------------------------------------
// --SECTION-- protected methods
// -----------------------------------------------------------------------------
////////////////////////////////////////////////////////////////////////////////
/// @brief setup a signal handler for CTRL-C
////////////////////////////////////////////////////////////////////////////////
void V8LineEditor::setupCtrlCHandler () {
#ifndef _WIN32
if (_shellImpl != nullptr &&
_shellImpl->supportsCtrlCHandler()) {
struct sigaction sa;
sa.sa_flags = 0;
sigemptyset(&sa.sa_mask);
sa.sa_handler = &SignalHandler;
int res = sigaction(SIGINT, &sa, 0);
if (res != 0) {
LOG_ERROR("unable to install signal handler");
}
}
#endif
}
// -----------------------------------------------------------------------------
// --SECTION-- protected methods
// -----------------------------------------------------------------------------
void V8LineEditor::initializeShell () {
_shellImpl = ShellImplFactory::buildShell(_history, &_completer);
setupCtrlCHandler();
}
// -----------------------------------------------------------------------------
// --SECTION-- END-OF-FILE
// -----------------------------------------------------------------------------
<|endoftext|>
|
<commit_before>//===-- Method.cpp - Implement the Method class ------------------*- C++ -*--=//
//
// This file implements the Method & GlobalVariable classes for the VMCore
// library.
//
//===----------------------------------------------------------------------===//
#include "llvm/ValueHolderImpl.h"
#include "llvm/DerivedTypes.h"
#include "llvm/SymbolTable.h"
#include "llvm/Module.h"
#include "llvm/Method.h"
#include "llvm/GlobalVariable.h"
#include "llvm/BasicBlock.h"
#include "llvm/iOther.h"
//===----------------------------------------------------------------------===//
// Method Implementation
//===----------------------------------------------------------------------===//
// Instantiate Templates - This ugliness is the price we have to pay
// for having a ValueHolderImpl.h file seperate from ValueHolder.h! :(
//
template class ValueHolder<MethodArgument, Method, Method>;
template class ValueHolder<BasicBlock , Method, Method>;
Method::Method(const MethodType *Ty, const string &name)
: GlobalValue(PointerType::get(Ty), Value::MethodVal, name),
SymTabValue(this), BasicBlocks(this), ArgumentList(this, this) {
assert(::isa<MethodType>(Ty) && "Method signature must be of method type!");
}
Method::~Method() {
dropAllReferences(); // After this it is safe to delete instructions.
// TODO: Should remove from the end, not the beginning of vector!
iterator BI = begin();
while ((BI = begin()) != end())
delete BasicBlocks.remove(BI);
// Delete all of the method arguments and unlink from symbol table...
ArgumentList.delete_all();
ArgumentList.setParent(0);
}
// Specialize setName to take care of symbol table majik
void Method::setName(const string &name, SymbolTable *ST) {
Module *P;
assert((ST == 0 || (!getParent() || ST == getParent()->getSymbolTable())) &&
"Invalid symtab argument!");
if ((P = getParent()) && hasName()) P->getSymbolTable()->remove(this);
Value::setName(name);
if (P && getName() != "") P->getSymbolTableSure()->insert(this);
}
void Method::setParent(Module *parent) {
Parent = parent;
// Relink symbol tables together...
setParentSymTab(Parent ? Parent->getSymbolTableSure() : 0);
}
const MethodType *Method::getMethodType() const {
return cast<MethodType>(cast<PointerType>(getType())->getValueType());
}
const Type *Method::getReturnType() const {
return getMethodType()->getReturnType();
}
// dropAllReferences() - This function causes all the subinstructions to "let
// go" of all references that they are maintaining. This allows one to
// 'delete' a whole class at a time, even though there may be circular
// references... first all references are dropped, and all use counts go to
// zero. Then everything is delete'd for real. Note that no operations are
// valid on an object that has "dropped all references", except operator
// delete.
//
void Method::dropAllReferences() {
for_each(begin(), end(), std::mem_fun(&BasicBlock::dropAllReferences));
}
//===----------------------------------------------------------------------===//
// GlobalVariable Implementation
//===----------------------------------------------------------------------===//
GlobalVariable::GlobalVariable(const Type *Ty, bool isConstant,
ConstPoolVal *Initializer = 0,
const string &Name = "")
: GlobalValue(PointerType::get(Ty), Value::GlobalVariableVal, Name),
Constant(isConstant) {
if (Initializer) Operands.push_back(Use((Value*)Initializer, this));
}
// Specialize setName to take care of symbol table majik
void GlobalVariable::setName(const string &name, SymbolTable *ST) {
Module *P;
assert((ST == 0 || (!getParent() || ST == getParent()->getSymbolTable())) &&
"Invalid symtab argument!");
if ((P = getParent()) && hasName()) P->getSymbolTable()->remove(this);
Value::setName(name);
if (P && getName() != "") P->getSymbolTableSure()->insert(this);
}
<commit_msg>Added MachineCodeForMethod object in class Method.<commit_after>//===-- Method.cpp - Implement the Method class ------------------*- C++ -*--=//
//
// This file implements the Method & GlobalVariable classes for the VMCore
// library.
//
//===----------------------------------------------------------------------===//
#include "llvm/ValueHolderImpl.h"
#include "llvm/DerivedTypes.h"
#include "llvm/SymbolTable.h"
#include "llvm/Module.h"
#include "llvm/Method.h"
#include "llvm/GlobalVariable.h"
#include "llvm/BasicBlock.h"
#include "llvm/iOther.h"
#include "llvm/CodeGen/MachineInstr.h"
//===----------------------------------------------------------------------===//
// Method Implementation
//===----------------------------------------------------------------------===//
// Instantiate Templates - This ugliness is the price we have to pay
// for having a ValueHolderImpl.h file seperate from ValueHolder.h! :(
//
template class ValueHolder<MethodArgument, Method, Method>;
template class ValueHolder<BasicBlock , Method, Method>;
Method::Method(const MethodType *Ty, const string &name)
: GlobalValue(PointerType::get(Ty), Value::MethodVal, name),
SymTabValue(this), BasicBlocks(this), ArgumentList(this, this),
machineCode(new MachineCodeForMethod(this)) {
assert(::isa<MethodType>(Ty) && "Method signature must be of method type!");
}
Method::~Method() {
dropAllReferences(); // After this it is safe to delete instructions.
// TODO: Should remove from the end, not the beginning of vector!
iterator BI = begin();
while ((BI = begin()) != end())
delete BasicBlocks.remove(BI);
// Delete all of the method arguments and unlink from symbol table...
ArgumentList.delete_all();
ArgumentList.setParent(0);
}
// Specialize setName to take care of symbol table majik
void Method::setName(const string &name, SymbolTable *ST) {
Module *P;
assert((ST == 0 || (!getParent() || ST == getParent()->getSymbolTable())) &&
"Invalid symtab argument!");
if ((P = getParent()) && hasName()) P->getSymbolTable()->remove(this);
Value::setName(name);
if (P && getName() != "") P->getSymbolTableSure()->insert(this);
}
void Method::setParent(Module *parent) {
Parent = parent;
// Relink symbol tables together...
setParentSymTab(Parent ? Parent->getSymbolTableSure() : 0);
}
const MethodType *Method::getMethodType() const {
return cast<MethodType>(cast<PointerType>(getType())->getValueType());
}
const Type *Method::getReturnType() const {
return getMethodType()->getReturnType();
}
// dropAllReferences() - This function causes all the subinstructions to "let
// go" of all references that they are maintaining. This allows one to
// 'delete' a whole class at a time, even though there may be circular
// references... first all references are dropped, and all use counts go to
// zero. Then everything is delete'd for real. Note that no operations are
// valid on an object that has "dropped all references", except operator
// delete.
//
void Method::dropAllReferences() {
for_each(begin(), end(), std::mem_fun(&BasicBlock::dropAllReferences));
}
//===----------------------------------------------------------------------===//
// GlobalVariable Implementation
//===----------------------------------------------------------------------===//
GlobalVariable::GlobalVariable(const Type *Ty, bool isConstant,
ConstPoolVal *Initializer = 0,
const string &Name = "")
: GlobalValue(PointerType::get(Ty), Value::GlobalVariableVal, Name),
Constant(isConstant) {
if (Initializer) Operands.push_back(Use((Value*)Initializer, this));
}
// Specialize setName to take care of symbol table majik
void GlobalVariable::setName(const string &name, SymbolTable *ST) {
Module *P;
assert((ST == 0 || (!getParent() || ST == getParent()->getSymbolTable())) &&
"Invalid symtab argument!");
if ((P = getParent()) && hasName()) P->getSymbolTable()->remove(this);
Value::setName(name);
if (P && getName() != "") P->getSymbolTableSure()->insert(this);
}
<|endoftext|>
|
<commit_before>// -*- mode: c++; c-basic-offset:4 -*-
// This file is part of libdap, A C++ implementation of the OPeNDAP Data
// Access Protocol.
// Copyright (c) 2011 OPeNDAP, Inc.
// Author: James Gallagher <jgallagher@opendap.org>
//
// This library is free software; you can redistribute it and/or
// modify it under the terms of the GNU Lesser General Public
// License as published by the Free Software Foundation; either
// version 2.1 of the License, or (at your option) any later version.
//
// This library is distributed in the hope that it will be useful,
// but WITHOUT ANY WARRANTY; without even the implied warranty of
// MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
// Lesser General Public License for more details.
//
// You should have received a copy of the GNU Lesser General Public
// License along with this library; if not, write to the Free Software
// Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA 02111-1307 USA
//
// You can contact OPeNDAP, Inc. at PO Box 112, Saunderstown, RI. 02874-0112.
#include "config.h"
static char rcsid[] not_used = { "$Id: ResponseBuilder.cc 23477 2010-09-02 21:02:59Z jimg $" };
#include <iostream>
#include <vector>
//#define DODS_DEBUG
#include "Keywords2.h"
#include "Error.h"
#include "escaping.h"
#include "debug.h"
using namespace std;
namespace libdap {
Keywords::Keywords()
{
// Load known keywords and their allowed values
vector<string> v1(7);
v1[0] = "2"; v1[1] = "2.0"; v1[2] = "3.2"; v1[3] = "3.3"; v1[4] = "3.4";
v1[5] = "4"; v1[6] = "4.0";
value_set_t vs = value_set_t(v1.begin(), v1.end());
d_known_keywords["dap"] = vs;
vector<string> v2(4);
v2[0] = "md5"; v2[1] = "MD5"; v2[2] = "sha1"; v2[3] = "SHA1";
value_set_t vs2 = value_set_t(v2.begin(), v2.end());
d_known_keywords["checksum"] = vs2;
}
Keywords::~Keywords()
{
}
/** Static function to parse the curly-brace keyword notation.
* @param kw the keyword clause '<word> ( <value> )'
* @param word (result) the word
* @param value (result) the value
* @return True if the parse was successful (word and value contain useful
* results) and False otherwise.
*/
static bool f_parse_keyword(const string &kw, string &word, string &value)
{
word = "";
value = "";
string::size_type i = kw.find('(');
if (i == string::npos)
return false;
word = kw.substr(0, i);
string::size_type j = kw.find(')');
if (j == string::npos)
return false;
++i; // Move past the opening brace
value = kw.substr(i, j-i);
return (!word.empty() && !value.empty());
}
/**
* Add the keyword to the set of keywords that apply to this request.
* @note Should call m_is_valid_keyword first.
* @param word The keyword/function name
* @param value The keyword/function value
*/
void Keywords::m_add_keyword(const keyword &word, const keyword_value &value)
{
d_parsed_keywords[word] = value;
}
/** Is the string a valid keyword clause? Assumption: the word and value have
* already been successfully parsed.
* @param word The keyword/function name
* @param value The keyword/function value
* @return True if the string is valid keyword and the value is one of the
* allowed values.
*/
bool Keywords::m_is_valid_keyword(const keyword &word, const keyword_value &value) const
{
map<keyword, value_set_t>::const_iterator ci = d_known_keywords.find(word);
if (ci == d_known_keywords.end())
return false;
else {
value_set_t vs = ci->second;
if (vs.find(value) == vs.end())
throw Error("Bad value passed to the keyword/function: " + word);
}
return true;
}
/**
* Is the word one of the known keywords for this version of libdap?
* @param s As a string, including the value
* @return true if the keyword is known
*/
bool Keywords::is_known_keyword(const string &word) const
{
return d_known_keywords.count(word) == 1;
}
/**
* Get a list of the strings that make up the set of current keywords for
* this request.
* @return The list of keywords as a list of string objects.
*/
list<Keywords::keyword> Keywords::get_keywords() const
{
list<keyword> kws;
map<keyword, keyword_value>::const_iterator i;
for (i = d_parsed_keywords.begin(); i != d_parsed_keywords.end(); ++i)
kws.push_front((*i).first);
return kws;
}
/**
* Lookup a keyword_kind and return true if it has been set for this request,
* otherwise return false.
* @param kw Keyword
* @return true if the keyword is set.
*/
bool Keywords::has_keyword(const keyword &kw) const
{
return d_parsed_keywords.count(kw) == 1;
}
/** Look at the parsed keywords for the value associated with a given keyword.
*
* @param k
* @return The value
*/
Keywords::keyword_value Keywords::get_keyword_value(const keyword &kw) const
{
if (d_known_keywords.find(kw) == d_known_keywords.end())
throw Error("Keyword not known (" + kw + ")");
return d_parsed_keywords.find(kw)->second;
}
/** Parse the constraint expression, removing all keywords. As a side effect,
* return the remaining CE.
* @param ce
* @return The CE stripped of all recognized keywords.
*/
string Keywords::parse_keywords(const string &ce)
{
// Get the whole CE
string projection = www2id(ce, "%", "%20");
string selection = "";
// Separate the selection part (which follows/includes the first '&')
string::size_type amp = projection.find('&');
if (amp != string::npos) {
selection = projection.substr(amp);
projection = projection.substr(0, amp);
}
// Extract keywords; add to the Keywords keywords. For this, scan for
// a known set of keywords and assume that anything else is part of the
// projection and should be left alone. Keywords must come before variables
// The 'projection' string will look like: '' or 'dap4.0' or 'dap4.0,u,v'
while (!projection.empty()) {
string::size_type i = projection.find(',');
string next_word = projection.substr(0, i);
string word, value;
if (f_parse_keyword(next_word, word, value)
&& m_is_valid_keyword(word, value)) {
m_add_keyword(word, value);
if (i != string::npos)
projection = projection.substr(i + 1);
else
projection = "";
}
else {
break; // exit on first non-keyword
}
}
// The CE is whatever is left after removing the keywords
return projection + selection;
}
}
<commit_msg>Updated comments<commit_after>// -*- mode: c++; c-basic-offset:4 -*-
// This file is part of libdap, A C++ implementation of the OPeNDAP Data
// Access Protocol.
// Copyright (c) 2011 OPeNDAP, Inc.
// Author: James Gallagher <jgallagher@opendap.org>
//
// This library is free software; you can redistribute it and/or
// modify it under the terms of the GNU Lesser General Public
// License as published by the Free Software Foundation; either
// version 2.1 of the License, or (at your option) any later version.
//
// This library is distributed in the hope that it will be useful,
// but WITHOUT ANY WARRANTY; without even the implied warranty of
// MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
// Lesser General Public License for more details.
//
// You should have received a copy of the GNU Lesser General Public
// License along with this library; if not, write to the Free Software
// Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA 02111-1307 USA
//
// You can contact OPeNDAP, Inc. at PO Box 112, Saunderstown, RI. 02874-0112.
#include "config.h"
static char rcsid[] not_used = { "$Id: ResponseBuilder.cc 23477 2010-09-02 21:02:59Z jimg $" };
#include <iostream>
#include <vector>
//#define DODS_DEBUG
#include "Keywords2.h"
#include "Error.h"
#include "escaping.h"
#include "debug.h"
using namespace std;
namespace libdap {
Keywords::Keywords()
{
// Load known keywords and their allowed values
vector<string> v1(7);
v1[0] = "2"; v1[1] = "2.0"; v1[2] = "3.2"; v1[3] = "3.3"; v1[4] = "3.4";
v1[5] = "4"; v1[6] = "4.0";
value_set_t vs = value_set_t(v1.begin(), v1.end());
d_known_keywords["dap"] = vs;
vector<string> v2(4);
v2[0] = "md5"; v2[1] = "MD5"; v2[2] = "sha1"; v2[3] = "SHA1";
value_set_t vs2 = value_set_t(v2.begin(), v2.end());
d_known_keywords["checksum"] = vs2;
}
Keywords::~Keywords()
{
}
/** Static function to parse the keyword notation.
* @param kw the keyword clause '<word> ( <value> )'
* @param word (result) the word
* @param value (result) the value
* @return True if the parse was successful (word and value contain useful
* results) and False otherwise.
*/
static bool f_parse_keyword(const string &kw, string &word, string &value)
{
word = "";
value = "";
string::size_type i = kw.find('(');
if (i == string::npos)
return false;
word = kw.substr(0, i);
string::size_type j = kw.find(')');
if (j == string::npos)
return false;
++i; // Move past the opening paren
value = kw.substr(i, j-i);
return (!word.empty() && !value.empty());
}
/**
* Add the keyword to the set of keywords that apply to this request.
* @note Should call m_is_valid_keyword first.
* @param word The keyword/function name
* @param value The keyword/function value
*/
void Keywords::m_add_keyword(const keyword &word, const keyword_value &value)
{
d_parsed_keywords[word] = value;
}
/** Is the string a valid keyword clause? Assumption: the word and value have
* already been successfully parsed.
* @param word The keyword/function name
* @param value The keyword/function value
* @return True if the string is valid keyword and the value is one of the
* allowed values.
*/
bool Keywords::m_is_valid_keyword(const keyword &word, const keyword_value &value) const
{
map<keyword, value_set_t>::const_iterator ci = d_known_keywords.find(word);
if (ci == d_known_keywords.end())
return false;
else {
value_set_t vs = ci->second;
if (vs.find(value) == vs.end())
throw Error("Bad value passed to the keyword/function: " + word);
}
return true;
}
/**
* Is the word one of the known keywords for this version of libdap?
* @param s As a string, including the value
* @return true if the keyword is known
*/
bool Keywords::is_known_keyword(const string &word) const
{
return d_known_keywords.count(word) == 1;
}
/**
* Get a list of the strings that make up the set of current keywords for
* this request.
* @return The list of keywords as a list of string objects.
*/
list<Keywords::keyword> Keywords::get_keywords() const
{
list<keyword> kws;
map<keyword, keyword_value>::const_iterator i;
for (i = d_parsed_keywords.begin(); i != d_parsed_keywords.end(); ++i)
kws.push_front((*i).first);
return kws;
}
/**
* Lookup a keyword_kind and return true if it has been set for this request,
* otherwise return false.
* @param kw Keyword
* @return true if the keyword is set.
*/
bool Keywords::has_keyword(const keyword &kw) const
{
return d_parsed_keywords.count(kw) == 1;
}
/** Look at the parsed keywords for the value associated with a given keyword.
*
* @param k
* @return The value
*/
Keywords::keyword_value Keywords::get_keyword_value(const keyword &kw) const
{
if (d_known_keywords.find(kw) == d_known_keywords.end())
throw Error("Keyword not known (" + kw + ")");
return d_parsed_keywords.find(kw)->second;
}
/** Parse the constraint expression, removing all keywords. As a side effect,
* return the remaining CE.
* @param ce
* @return The CE stripped of all recognized keywords.
*/
string Keywords::parse_keywords(const string &ce)
{
// Get the whole CE
string projection = www2id(ce, "%", "%20");
string selection = "";
// Separate the selection part (which follows/includes the first '&')
string::size_type amp = projection.find('&');
if (amp != string::npos) {
selection = projection.substr(amp);
projection = projection.substr(0, amp);
}
// Extract keywords; add to the Keywords keywords. For this, scan for
// a known set of keywords and assume that anything else is part of the
// projection and should be left alone. Keywords must come before variables
// The 'projection' string will look like: '' or 'dap4.0' or 'dap4.0,u,v'
while (!projection.empty()) {
string::size_type i = projection.find(',');
string next_word = projection.substr(0, i);
string word, value;
if (f_parse_keyword(next_word, word, value)
&& m_is_valid_keyword(word, value)) {
m_add_keyword(word, value);
if (i != string::npos)
projection = projection.substr(i + 1);
else
projection = "";
}
else {
break; // exit on first non-keyword
}
}
// The CE is whatever is left after removing the keywords
return projection + selection;
}
}
<|endoftext|>
|
<commit_before>#include "frame.h"
#include "util.h"
#include "gtest/gtest.h"
#include <string>
#include <iostream>
TEST(UtilTest, NormalTest) {
std::string data = "hello world";
uint8_t enc_a_wire[30];
const uint8_t e_wire[13] = {0x00, 0x0b, 'h', 'e', 'l', 'l', 'o', ' ', 'w', 'o', 'r', 'l', 'd'};
int32_t enc_a_len = UTF8_encode(enc_a_wire, data);
int32_t enc_e_len = data.size()+2;
EXPECT_EQ(enc_e_len, enc_a_len);
EXPECT_TRUE(0 == std::memcmp(enc_a_wire, e_wire, enc_a_len));
int64_t dec_a_len = 0;
std::string dec_a_str = UTF8_decode(e_wire, &dec_a_len);
EXPECT_EQ(enc_e_len, dec_a_len);
EXPECT_TRUE(0 == std::memcmp(data.c_str(), dec_a_str.c_str(), data.size()));
int dataNum = 8;
uint32_t lens[8] = {0, 127, 128, 16383, 16384, 2097151, 2097152, 268435455};
uint8_t remEnc_a_wire[30];
uint8_t remEnc_e_wires[8][4] = {{0x00}, {0x7f}, {0x80, 0x01}, {0xff, 0x7f}, {0x80, 0x80, 0x01},
{0xff, 0xff, 0x7f}, {0x80, 0x80, 0x80, 0x01}, {0xff, 0xff, 0xff, 0x7f}};
for (int i = 0; i < dataNum; i++) {
int32_t remEnc_e_len = remainEncode(remEnc_a_wire, lens[i]);
EXPECT_TRUE(0 == std::memcmp(remEnc_e_wires[i], remEnc_a_wire, remEnc_e_len));
}
int wire_progress = 0;
MQTT_ERROR err;
for (int i = 0; i < dataNum; i++) {
int32_t a_remLength = remainDecode(remEnc_e_wires[i], &wire_progress, err);
EXPECT_EQ(lens[i], a_remLength);
}
std::vector<std::string> a_parts, e_parts;
e_parts.push_back("a");
e_parts.push_back("b");
e_parts.push_back("c");
std::string splitted = "a/b/c";
int done = split(splitted, "/", &a_parts);
for (int i = 0; i < 3; i++) {
EXPECT_TRUE(e_parts[i] == a_parts[i]);
}
}
int main(int argc, char **argv) {
::testing::InitGoogleTest(&argc, argv);
return RUN_ALL_TESTS();
}
<commit_msg>add fixedheader test<commit_after>#include "frame.h"
#include "util.h"
#include "gtest/gtest.h"
#include <string>
#include <iostream>
TEST(UtilTest, NormalTest) {
std::string data = "hello world";
uint8_t enc_a_wire[30];
const uint8_t e_wire[13] = {0x00, 0x0b, 'h', 'e', 'l', 'l', 'o', ' ', 'w', 'o', 'r', 'l', 'd'};
int32_t enc_a_len = UTF8_encode(enc_a_wire, data);
int32_t enc_e_len = data.size()+2;
EXPECT_EQ(enc_e_len, enc_a_len);
EXPECT_TRUE(0 == std::memcmp(enc_a_wire, e_wire, enc_a_len));
int64_t dec_a_len = 0;
std::string dec_a_str = UTF8_decode(e_wire, &dec_a_len);
EXPECT_EQ(enc_e_len, dec_a_len);
EXPECT_TRUE(0 == std::memcmp(data.c_str(), dec_a_str.c_str(), data.size()));
int dataNum = 8;
uint32_t lens[8] = {0, 127, 128, 16383, 16384, 2097151, 2097152, 268435455};
uint8_t remEnc_a_wire[30];
uint8_t remEnc_e_wires[8][4] = {{0x00}, {0x7f}, {0x80, 0x01}, {0xff, 0x7f}, {0x80, 0x80, 0x01},
{0xff, 0xff, 0x7f}, {0x80, 0x80, 0x80, 0x01}, {0xff, 0xff, 0xff, 0x7f}};
for (int i = 0; i < dataNum; i++) {
int32_t remEnc_e_len = remainEncode(remEnc_a_wire, lens[i]);
EXPECT_TRUE(0 == std::memcmp(remEnc_e_wires[i], remEnc_a_wire, remEnc_e_len));
}
int wire_progress = 0;
MQTT_ERROR err;
for (int i = 0; i < dataNum; i++) {
int32_t a_remLength = remainDecode(remEnc_e_wires[i], &wire_progress, err);
EXPECT_EQ(lens[i], a_remLength);
}
std::vector<std::string> a_parts, e_parts;
e_parts.push_back("a");
e_parts.push_back("b");
e_parts.push_back("c");
std::string splitted = "a/b/c";
int done = split(splitted, "/", &a_parts);
for (int i = 0; i < 3; i++) {
EXPECT_TRUE(e_parts[i] == a_parts[i]);
}
}
TEST(FrameTest, NormalTest) {
MessageType type = CONNECT_MESSAGE_TYPE;
bool dup = false;
uint8_t qos = 0;
bool retain = false;
uint32_t len = 0;
uint16_t id = 0;
FixedHeader* fh = new FixedHeader(type, dup, qos, retain, len, id);
EXPECT_EQ(type, fh->Type);
EXPECT_EQ(dup, fh->Dup);
EXPECT_EQ(qos, fh->QoS);
EXPECT_EQ(retain, fh->Retain);
EXPECT_EQ(len, fh->Length);
EXPECT_EQ(id, fh->PacketID);
}
int main(int argc, char **argv) {
::testing::InitGoogleTest(&argc, argv);
return RUN_ALL_TESTS();
}
<|endoftext|>
|
<commit_before>/* bzflag
* Copyright (c) 1993 - 2004 Tim Riker
*
* This package is free software; you can redistribute it and/or
* modify it under the terms of the license found in the file
* named COPYING that should have accompanied this file.
*
* THIS PACKAGE IS PROVIDED ``AS IS'' AND WITHOUT ANY EXPRESS OR
* IMPLIED WARRANTIES, INCLUDING, WITHOUT LIMITATION, THE IMPLIED
* WARRANTIES OF MERCHANTIBILITY AND FITNESS FOR A PARTICULAR PURPOSE.
*/
#ifdef _MSC_VER
#pragma warning( 4: 4786 )
#endif
#include "TextureManager.h"
#include "TextUtils.h"
#include "texture.h"
#include "global.h"
#include "MediaFile.h"
#include "ErrorHandler.h"
/*const int NO_VARIANT = (-1); */
// initialize the singleton
template <>
TextureManager* Singleton<TextureManager>::_instance = (TextureManager*)0;
static int noiseProc( ProcTextureInit &init );
ProcTextureInit procLoader[1];
TextureManager::TextureManager()
{
// fill out the standard proc textures
procLoader[0].name = "noise";
procLoader[0].filter = OpenGLTexture::Nearest;
procLoader[0].proc = noiseProc;
lastImageID = -1;
lastBoundID = -1;
int i, numTextures;
numTextures = countof(procLoader);
for (i = 0; i < numTextures; i++)
{
procLoader[i].manager = this;
procLoader[i].proc( procLoader[i] );
}
}
TextureManager::~TextureManager()
{
// we are done remove all textures
for( TextureNameMap::iterator it = textureNames.begin(); it != textureNames.end(); ++it) {
ImageInfo &tex = it->second;
if (tex.texture != NULL) {
delete tex.texture;
}
}
textureNames.clear();
textureIDs.clear();
}
int TextureManager::getTextureID( const char* name, bool reportFail )
{
if (!name)
return -1;
std::string texName = name;
// see if we have the texture
TextureNameMap::iterator it = textureNames.find(texName);
if (it != textureNames.end())
return it->second.id;
else { // we don't have it so try and load it
FileTextureInit file;
file.filter = OpenGLTexture::LinearMipmapLinear;
file.name = texName;
ImageInfo info;
OpenGLTexture *image = loadTexture(file,reportFail);
if (!image)
return -1;
return addTexture(name,image);
}
return -1;
}
bool TextureManager::bind ( int id )
{
TextureIDMap::iterator it = textureIDs.find(id);
if (it == textureIDs.end())
return false;
if (id != lastBoundID)
{
it->second->texture->execute();
lastBoundID = id;
}
return true;
}
bool TextureManager::bind ( const char* name )
{
std::string nameStr = name;
TextureNameMap::iterator it = textureNames.find(nameStr);
if (it == textureNames.end())
return false;
int id = it->second.id;
if (id != lastBoundID)
{
it->second.texture->execute();
lastBoundID = id;
}
return true;
}
float TextureManager::GetAspectRatio ( int id )
{
TextureIDMap::iterator it = textureIDs.find(id);
if (it == textureIDs.end())
return 0.0;
return (float)it->second->y/(float)it->second->x;
}
const ImageInfo& TextureManager::getInfo ( int id )
{
static ImageInfo crapInfo;
crapInfo.id = -1;
TextureIDMap::iterator it = textureIDs.find(id);
if (it == textureIDs.end())
return crapInfo;
return *(it->second);
}
const ImageInfo& TextureManager::getInfo ( const char* name )
{
static ImageInfo crapInfo;
crapInfo.id = -1;
std::string nameStr = name;
TextureNameMap::iterator it = textureNames.find(nameStr);
if (it == textureNames.end())
return crapInfo;
return it->second;
}
int TextureManager::addTexture( const char* name, OpenGLTexture *texture )
{
if (!name || !texture)
return -1;
// if the texture allready exists kill it
// this is why IDs are way better then objects for this stuff
TextureNameMap::iterator it = textureNames.find(name);
if (it != textureNames.end())
{
textureIDs.erase(textureIDs.find(it->second.id));
delete it->second.texture;
}
ImageInfo info;
info.name = name;
info.texture = texture;
info.id = ++lastImageID;
info.alpha = texture->hasAlpha();
info.x = texture->getWidth();
info.y = texture->getHeight();
textureNames[name] = info;
textureIDs[info.id] = &textureNames[name];
return info.id;
}
OpenGLTexture* TextureManager::loadTexture(FileTextureInit &init, bool reportFail)
{
int width, height;
std::string nameToTry = "";
if (BZDB.isSet( "altImageDir" )) {
nameToTry = BZDB.get( "altImageDir" );
#ifdef WIN32
nameToTry += '\\';
#else
nameToTry += '/';
#endif
nameToTry += init.name;
}
else
nameToTry = init.name;
unsigned char* image =NULL;
if (nameToTry.size() && nameToTry.c_str())
image = MediaFile::readImage( nameToTry.c_str(), &width, &height);
if (!image)
image = MediaFile::readImage( init.name.c_str(), &width, &height);
if (!image) {
if (reportFail) {
std::vector<std::string> args;
args.push_back(init.name);
printError("cannot load texture: {1}", &args);
}
return NULL;
}
OpenGLTexture *texture = new OpenGLTexture(width, height, image, init.filter, true);
delete[] image;
return texture;
}
int TextureManager::newTexture ( const char* name, int x, int y, unsigned char* data, OpenGLTexture::Filter filter, bool repeat, int format )
{
return addTexture(name,new OpenGLTexture(x,y,data,filter,repeat,format));
}
/* --- Procs --- */
int noiseProc(ProcTextureInit &init)
{
int noizeSize = 128;
const int size = 4 * noizeSize * noizeSize;
unsigned char* noise = new unsigned char[size];
for (int i = 0; i < size; i += 4 ) {
unsigned char n = (unsigned char)floor(256.0 * bzfrand());
noise[i+0] = n;
noise[i+1] = n;
noise[i+2] = n;
noise[i+3] = n;
}
int texture = init.manager->newTexture(init.name.c_str(),noizeSize,noizeSize,noise,init.filter);
delete noise;
return texture;
}
// Local Variables: ***
// mode: C++ ***
// tab-width: 8 ***
// c-basic-offset: 2 ***
// indent-tabs-mode: t ***
// End: ***
// ex: shiftwidth=2 tabstop=8
<commit_msg>add some debugage<commit_after>/* bzflag
* Copyright (c) 1993 - 2004 Tim Riker
*
* This package is free software; you can redistribute it and/or
* modify it under the terms of the license found in the file
* named COPYING that should have accompanied this file.
*
* THIS PACKAGE IS PROVIDED ``AS IS'' AND WITHOUT ANY EXPRESS OR
* IMPLIED WARRANTIES, INCLUDING, WITHOUT LIMITATION, THE IMPLIED
* WARRANTIES OF MERCHANTIBILITY AND FITNESS FOR A PARTICULAR PURPOSE.
*/
#ifdef _MSC_VER
#pragma warning( 4: 4786 )
#endif
#include "TextureManager.h"
#include "TextUtils.h"
#include "texture.h"
#include "global.h"
#include "MediaFile.h"
#include "ErrorHandler.h"
/*const int NO_VARIANT = (-1); */
// initialize the singleton
template <>
TextureManager* Singleton<TextureManager>::_instance = (TextureManager*)0;
static int noiseProc( ProcTextureInit &init );
ProcTextureInit procLoader[1];
TextureManager::TextureManager()
{
// fill out the standard proc textures
procLoader[0].name = "noise";
procLoader[0].filter = OpenGLTexture::Nearest;
procLoader[0].proc = noiseProc;
lastImageID = -1;
lastBoundID = -1;
int i, numTextures;
numTextures = countof(procLoader);
for (i = 0; i < numTextures; i++)
{
procLoader[i].manager = this;
procLoader[i].proc( procLoader[i] );
}
}
TextureManager::~TextureManager()
{
// we are done remove all textures
for( TextureNameMap::iterator it = textureNames.begin(); it != textureNames.end(); ++it) {
ImageInfo &tex = it->second;
if (tex.texture != NULL) {
delete tex.texture;
}
}
textureNames.clear();
textureIDs.clear();
}
int TextureManager::getTextureID( const char* name, bool reportFail )
{
if (!name)
return -1;
std::string texName = name;
// see if we have the texture
TextureNameMap::iterator it = textureNames.find(texName);
if (it != textureNames.end())
return it->second.id;
else { // we don't have it so try and load it
FileTextureInit file;
file.filter = OpenGLTexture::LinearMipmapLinear;
file.name = texName;
ImageInfo info;
OpenGLTexture *image = loadTexture(file,reportFail);
if (!image) {
DEBUG1("Image not found or unloadable: %s\n", name);
return -1;
}
return addTexture(name,image);
}
return -1;
}
bool TextureManager::bind ( int id )
{
TextureIDMap::iterator it = textureIDs.find(id);
if (it == textureIDs.end()) {
DEBUG1("Unable to bind texture (by id): %d\n", id);
return false;
}
if (id != lastBoundID) {
it->second->texture->execute();
lastBoundID = id;
}
return true;
}
bool TextureManager::bind ( const char* name )
{
std::string nameStr = name;
TextureNameMap::iterator it = textureNames.find(nameStr);
if (it == textureNames.end()) {
DEBUG1("Unable to bind texture (by name): %s\n", name);
return false;
}
int id = it->second.id;
if (id != lastBoundID) {
it->second.texture->execute();
lastBoundID = id;
}
return true;
}
float TextureManager::GetAspectRatio ( int id )
{
TextureIDMap::iterator it = textureIDs.find(id);
if (it == textureIDs.end())
return 0.0;
return (float)it->second->y/(float)it->second->x;
}
const ImageInfo& TextureManager::getInfo ( int id )
{
static ImageInfo crapInfo;
crapInfo.id = -1;
TextureIDMap::iterator it = textureIDs.find(id);
if (it == textureIDs.end())
return crapInfo;
return *(it->second);
}
const ImageInfo& TextureManager::getInfo ( const char* name )
{
static ImageInfo crapInfo;
crapInfo.id = -1;
std::string nameStr = name;
TextureNameMap::iterator it = textureNames.find(nameStr);
if (it == textureNames.end())
return crapInfo;
return it->second;
}
int TextureManager::addTexture( const char* name, OpenGLTexture *texture )
{
if (!name || !texture)
return -1;
// if the texture already exists kill it
// this is why IDs are way better than objects for this stuff
TextureNameMap::iterator it = textureNames.find(name);
if (it != textureNames.end()) {
DEBUG4("Texture %s already exists, overwriting\n", name);
textureIDs.erase(textureIDs.find(it->second.id));
delete it->second.texture;
}
ImageInfo info;
info.name = name;
info.texture = texture;
info.id = ++lastImageID;
info.alpha = texture->hasAlpha();
info.x = texture->getWidth();
info.y = texture->getHeight();
textureNames[name] = info;
textureIDs[info.id] = &textureNames[name];
return info.id;
}
OpenGLTexture* TextureManager::loadTexture(FileTextureInit &init, bool reportFail)
{
int width, height;
std::string nameToTry = "";
if (BZDB.isSet( "altImageDir" )) {
nameToTry = BZDB.get( "altImageDir" );
#ifdef WIN32
nameToTry += '\\';
#else
nameToTry += '/';
#endif
nameToTry += init.name;
}
else
nameToTry = init.name;
unsigned char* image = NULL;
if (nameToTry.size() && nameToTry.c_str())
image = MediaFile::readImage( nameToTry.c_str(), &width, &height);
if (!image)
image = MediaFile::readImage( init.name.c_str(), &width, &height);
if (!image) {
if (reportFail) {
std::vector<std::string> args;
args.push_back(init.name);
printError("cannot load texture: {1}", &args);
}
return NULL;
}
OpenGLTexture *texture = new OpenGLTexture(width, height, image, init.filter, true);
delete[] image;
return texture;
}
int TextureManager::newTexture ( const char* name, int x, int y, unsigned char* data, OpenGLTexture::Filter filter, bool repeat, int format )
{
return addTexture(name,new OpenGLTexture(x,y,data,filter,repeat,format));
}
/* --- Procs --- */
int noiseProc(ProcTextureInit &init)
{
int noizeSize = 128;
const int size = 4 * noizeSize * noizeSize;
unsigned char* noise = new unsigned char[size];
for (int i = 0; i < size; i += 4 ) {
unsigned char n = (unsigned char)floor(256.0 * bzfrand());
noise[i+0] = n;
noise[i+1] = n;
noise[i+2] = n;
noise[i+3] = n;
}
int texture = init.manager->newTexture(init.name.c_str(),noizeSize,noizeSize,noise,init.filter);
delete[] noise;
return texture;
}
// Local Variables: ***
// mode: C++ ***
// tab-width: 8 ***
// c-basic-offset: 2 ***
// indent-tabs-mode: t ***
// End: ***
// ex: shiftwidth=2 tabstop=8
<|endoftext|>
|
<commit_before>// Virvo - Virtual Reality Volume Rendering
// Copyright (C) 1999-2003 University of Stuttgart, 2004-2005 Brown University
// Contact: Jurgen P. Schulze, jschulze@ucsd.edu
//
// This file is part of Virvo.
//
// Virvo is free software; you can redistribute it and/or
// modify it under the terms of the GNU Lesser General Public
// License as published by the Free Software Foundation; either
// version 2.1 of the License, or (at your option) any later version.
//
// This library is distributed in the hope that it will be useful,
// but WITHOUT ANY WARRANTY; without even the implied warranty of
// MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
// Lesser General Public License for more details.
//
// You should have received a copy of the GNU Lesser General Public
// License along with this library (see license.txt); if not, write to the
// Free Software Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA 02111-1307 USA
#ifdef HAVE_CONFIG_H
#include "vvconfig.h"
#endif
#include "vvbonjoureventloop.h"
#include "vvdebugmsg.h"
#include "vvpthread.h"
#include "vvsocketmonitor.h"
#include "vvtcpsocket.h"
#ifdef HAVE_BONJOUR
#include <dns_sd.h>
#endif
namespace
{
#ifdef HAVE_BONJOUR
_DNSServiceRef_t *dnsServiceRef;
#endif
}
struct Thread
{
pthread_t _pthread;
};
vvBonjourEventLoop::vvBonjourEventLoop(void* service)
{
_thread = new Thread;
_thread->_pthread = NULL;
#ifdef HAVE_BONJOUR
::dnsServiceRef = reinterpret_cast<_DNSServiceRef_t*>(service);
#else
(void)service;
#endif
}
vvBonjourEventLoop::~vvBonjourEventLoop()
{
if(_thread->_pthread)
{
pthread_join(_thread->_pthread, NULL);
}
delete _thread;
}
void vvBonjourEventLoop::run(bool inThread, double timeout)
{
#ifdef HAVE_BONJOUR
_timeout = timeout;
_noMoreFlags = false;
if(inThread == false)
{
loop(this);
::dnsServiceRef = NULL;
}
else
{
pthread_create(&(_thread->_pthread), NULL, loop, this);
}
#else
(void)inThread;
(void)timeout;
#endif
}
void * vvBonjourEventLoop::loop(void * attrib)
{
#ifdef HAVE_BONJOUR
vvDebugMsg::msg(3, "vvBonjourEventLoop::loop()");
vvBonjourEventLoop *instance = reinterpret_cast<vvBonjourEventLoop*>(attrib);
instance->_run = true;
int dns_sd_fd = DNSServiceRefSockFD(::dnsServiceRef);
vvTcpSocket sock = vvTcpSocket();
sock.setSockfd(dns_sd_fd);
std::vector<vvSocket*> sockets;
sockets.push_back(&sock);
vvSocketMonitor socketMonitor;
socketMonitor.setReadFds(sockets);
while (instance->_run)
{
vvSocket *ready;
double to = instance->_timeout;
vvSocketMonitor::ErrorType smErr = socketMonitor.wait(&ready, &to);
if (smErr == vvSocketMonitor::VV_OK)
{
DNSServiceErrorType err = DNSServiceProcessResult(::dnsServiceRef);
switch(err)
{
case kDNSServiceErr_NoError:
continue;
break;
case kDNSServiceErr_NoSuchName:
vvDebugMsg::msg(0, "DNSServiceProcessResult() Given name does not exist");
break;
case kDNSServiceErr_NoMemory:
vvDebugMsg::msg(0, "DNSServiceProcessResult() Out of memory");
break;
case kDNSServiceErr_BadParam:
vvDebugMsg::msg(0, "DNSServiceProcessResult() Parameter contains invalid data");
break;
case kDNSServiceErr_BadReference:
vvDebugMsg::msg(0, "DNSServiceProcessResult() Reference being passed is invalid");
break;
case kDNSServiceErr_BadState:
vvDebugMsg::msg(0, "DNSServiceProcessResult() Internal error");
break;
case kDNSServiceErr_BadFlags:
vvDebugMsg::msg(0, "DNSServiceProcessResult() Invalid values for flags");
break;
case kDNSServiceErr_Unsupported:
vvDebugMsg::msg(0, "DNSServiceProcessResult() Operation not supported");
break;
case kDNSServiceErr_NotInitialized:
vvDebugMsg::msg(0, "DNSServiceProcessResult() Reference not initialized");
break;
case kDNSServiceErr_AlreadyRegistered:
vvDebugMsg::msg(0, "DNSServiceProcessResult() Attempt to register a service that is registered");
break;
case kDNSServiceErr_NameConflict:
vvDebugMsg::msg(0, "DNSServiceProcessResult() Attempt to register a service with an already used name");
break;
case kDNSServiceErr_Invalid:
vvDebugMsg::msg(0, "DNSServiceProcessResult() Certain invalid parameter data, such as domain name more than 255 bytes long");
break;
case kDNSServiceErr_Incompatible:
vvDebugMsg::msg(0, "DNSServiceProcessResult() Client library incompatible with daemon");
break;
case kDNSServiceErr_BadInterfaceIndex:
vvDebugMsg::msg(0, "DNSServiceProcessResult() Specified interface does not exist");
break;
case kDNSServiceErr_Unknown:
default:
vvDebugMsg::msg(0, "DNSServiceProcessResult() unknown error");
break;
}
// did not "continue", so error occured -> break!
break;
}
else if(smErr == vvSocketMonitor::VV_TIMEOUT)
{
vvDebugMsg::msg(0, "vvBonjourEventLoop::loop() timeout reached");
break;
}
else
{
vvDebugMsg::msg(0, "vvBonjourEventLoop::loop() socketmonitor returned error");
break;
}
}
#else
(void)attrib;
#endif
return NULL;
}
void vvBonjourEventLoop::stop()
{
vvDebugMsg::msg(3, "vvBonjourEventLoop::stop()");
_run = false;
}
// vim: sw=2:expandtab:softtabstop=2:ts=2:cino=\:0g0t0
<commit_msg>Don't compare non-pointer type pthread_t to NULL<commit_after>// Virvo - Virtual Reality Volume Rendering
// Copyright (C) 1999-2003 University of Stuttgart, 2004-2005 Brown University
// Contact: Jurgen P. Schulze, jschulze@ucsd.edu
//
// This file is part of Virvo.
//
// Virvo is free software; you can redistribute it and/or
// modify it under the terms of the GNU Lesser General Public
// License as published by the Free Software Foundation; either
// version 2.1 of the License, or (at your option) any later version.
//
// This library is distributed in the hope that it will be useful,
// but WITHOUT ANY WARRANTY; without even the implied warranty of
// MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
// Lesser General Public License for more details.
//
// You should have received a copy of the GNU Lesser General Public
// License along with this library (see license.txt); if not, write to the
// Free Software Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA 02111-1307 USA
#ifdef HAVE_CONFIG_H
#include "vvconfig.h"
#endif
#include "vvbonjoureventloop.h"
#include "vvdebugmsg.h"
#include "vvpthread.h"
#include "vvsocketmonitor.h"
#include "vvtcpsocket.h"
#ifdef HAVE_BONJOUR
#include <dns_sd.h>
#endif
namespace
{
#ifdef HAVE_BONJOUR
_DNSServiceRef_t *dnsServiceRef;
#endif
}
struct Thread
{
Thread()
: _pthread(NULL)
{
}
pthread_t* _pthread;
};
vvBonjourEventLoop::vvBonjourEventLoop(void* service)
{
_thread = new Thread;
_thread->_pthread = NULL;
#ifdef HAVE_BONJOUR
::dnsServiceRef = reinterpret_cast<_DNSServiceRef_t*>(service);
#else
(void)service;
#endif
}
vvBonjourEventLoop::~vvBonjourEventLoop()
{
if (_thread != NULL && _thread->_pthread != NULL)
{
pthread_join(*_thread->_pthread, NULL);
delete _thread->_pthread;
}
delete _thread;
}
void vvBonjourEventLoop::run(bool inThread, double timeout)
{
#ifdef HAVE_BONJOUR
_timeout = timeout;
_noMoreFlags = false;
if(inThread == false)
{
loop(this);
::dnsServiceRef = NULL;
}
else
{
delete _thread->_pthread;
_thread->_pthread = new pthread_t;
pthread_create(_thread->_pthread, NULL, loop, this);
}
#else
(void)inThread;
(void)timeout;
#endif
}
void * vvBonjourEventLoop::loop(void * attrib)
{
#ifdef HAVE_BONJOUR
vvDebugMsg::msg(3, "vvBonjourEventLoop::loop()");
vvBonjourEventLoop *instance = reinterpret_cast<vvBonjourEventLoop*>(attrib);
instance->_run = true;
int dns_sd_fd = DNSServiceRefSockFD(::dnsServiceRef);
vvTcpSocket sock = vvTcpSocket();
sock.setSockfd(dns_sd_fd);
std::vector<vvSocket*> sockets;
sockets.push_back(&sock);
vvSocketMonitor socketMonitor;
socketMonitor.setReadFds(sockets);
while (instance->_run)
{
vvSocket *ready;
double to = instance->_timeout;
vvSocketMonitor::ErrorType smErr = socketMonitor.wait(&ready, &to);
if (smErr == vvSocketMonitor::VV_OK)
{
DNSServiceErrorType err = DNSServiceProcessResult(::dnsServiceRef);
switch(err)
{
case kDNSServiceErr_NoError:
continue;
break;
case kDNSServiceErr_NoSuchName:
vvDebugMsg::msg(0, "DNSServiceProcessResult() Given name does not exist");
break;
case kDNSServiceErr_NoMemory:
vvDebugMsg::msg(0, "DNSServiceProcessResult() Out of memory");
break;
case kDNSServiceErr_BadParam:
vvDebugMsg::msg(0, "DNSServiceProcessResult() Parameter contains invalid data");
break;
case kDNSServiceErr_BadReference:
vvDebugMsg::msg(0, "DNSServiceProcessResult() Reference being passed is invalid");
break;
case kDNSServiceErr_BadState:
vvDebugMsg::msg(0, "DNSServiceProcessResult() Internal error");
break;
case kDNSServiceErr_BadFlags:
vvDebugMsg::msg(0, "DNSServiceProcessResult() Invalid values for flags");
break;
case kDNSServiceErr_Unsupported:
vvDebugMsg::msg(0, "DNSServiceProcessResult() Operation not supported");
break;
case kDNSServiceErr_NotInitialized:
vvDebugMsg::msg(0, "DNSServiceProcessResult() Reference not initialized");
break;
case kDNSServiceErr_AlreadyRegistered:
vvDebugMsg::msg(0, "DNSServiceProcessResult() Attempt to register a service that is registered");
break;
case kDNSServiceErr_NameConflict:
vvDebugMsg::msg(0, "DNSServiceProcessResult() Attempt to register a service with an already used name");
break;
case kDNSServiceErr_Invalid:
vvDebugMsg::msg(0, "DNSServiceProcessResult() Certain invalid parameter data, such as domain name more than 255 bytes long");
break;
case kDNSServiceErr_Incompatible:
vvDebugMsg::msg(0, "DNSServiceProcessResult() Client library incompatible with daemon");
break;
case kDNSServiceErr_BadInterfaceIndex:
vvDebugMsg::msg(0, "DNSServiceProcessResult() Specified interface does not exist");
break;
case kDNSServiceErr_Unknown:
default:
vvDebugMsg::msg(0, "DNSServiceProcessResult() unknown error");
break;
}
// did not "continue", so error occured -> break!
break;
}
else if(smErr == vvSocketMonitor::VV_TIMEOUT)
{
vvDebugMsg::msg(0, "vvBonjourEventLoop::loop() timeout reached");
break;
}
else
{
vvDebugMsg::msg(0, "vvBonjourEventLoop::loop() socketmonitor returned error");
break;
}
}
#else
(void)attrib;
#endif
return NULL;
}
void vvBonjourEventLoop::stop()
{
vvDebugMsg::msg(3, "vvBonjourEventLoop::stop()");
_run = false;
}
// vim: sw=2:expandtab:softtabstop=2:ts=2:cino=\:0g0t0
<|endoftext|>
|
<commit_before>// Copyright (c) 2009 The Chromium Authors. All rights reserved.
// Use of this source code is governed by a BSD-style license that can be
// found in the LICENSE file.
#include "base/message_loop.h"
#include "base/thread.h"
#include "testing/gtest/include/gtest/gtest.h"
namespace {
// We use caps here just to ensure that the method name doesn't interfere with
// the wildcarded suppressions.
class TOOLS_SANITY_TEST_CONCURRENT_THREAD : public PlatformThread::Delegate {
public:
explicit TOOLS_SANITY_TEST_CONCURRENT_THREAD(bool *value) : value_(value) {}
~TOOLS_SANITY_TEST_CONCURRENT_THREAD() {}
void ThreadMain() {
*value_ = true;
}
private:
bool* value_;
};
}
// A memory leak detector should report an error in this test.
TEST(ToolsSanityTest, MemoryLeak) {
int *leak = new int[256]; // Leak some memory intentionally.
leak[4] = 1; // Make sure the allocated memory is used.
}
// A data race detector should report an error in this test.
TEST(ToolsSanityTest, DataRace) {
bool shared = false;
PlatformThreadHandle a;
PlatformThreadHandle b;
PlatformThread::Delegate *thread1 =
new TOOLS_SANITY_TEST_CONCURRENT_THREAD(&shared);
PlatformThread::Delegate *thread2 =
new TOOLS_SANITY_TEST_CONCURRENT_THREAD(&shared);
PlatformThread::Create(0, thread1, &a);
PlatformThread::Create(0, thread2, &b);
PlatformThread::Join(a);
PlatformThread::Join(b);
EXPECT_TRUE(shared);
delete thread1;
delete thread2;
}
<commit_msg>Add sleep into data race sanity test since it fails on TSan x64 FYI bot (too fast?) TBR=glider TEST=TSAN x64 FYI bot should become green Review URL: http://codereview.chromium.org/668176<commit_after>// Copyright (c) 2009 The Chromium Authors. All rights reserved.
// Use of this source code is governed by a BSD-style license that can be
// found in the LICENSE file.
#include "base/message_loop.h"
#include "base/thread.h"
#include "testing/gtest/include/gtest/gtest.h"
namespace {
// We use caps here just to ensure that the method name doesn't interfere with
// the wildcarded suppressions.
class TOOLS_SANITY_TEST_CONCURRENT_THREAD : public PlatformThread::Delegate {
public:
explicit TOOLS_SANITY_TEST_CONCURRENT_THREAD(bool *value) : value_(value) {}
~TOOLS_SANITY_TEST_CONCURRENT_THREAD() {}
void ThreadMain() {
*value_ = true;
// Sleep for a few milliseconds so the two threads are more likely to live
// simultaneously. Otherwise we may miss the report due to mutex
// lock/unlock's inside thread creation code in pure-happens-before mode...
PlatformThread::Sleep(100);
}
private:
bool* value_;
};
}
// A memory leak detector should report an error in this test.
TEST(ToolsSanityTest, MemoryLeak) {
int *leak = new int[256]; // Leak some memory intentionally.
leak[4] = 1; // Make sure the allocated memory is used.
}
// A data race detector should report an error in this test.
TEST(ToolsSanityTest, DataRace) {
bool shared = false;
PlatformThreadHandle a;
PlatformThreadHandle b;
PlatformThread::Delegate *thread1 =
new TOOLS_SANITY_TEST_CONCURRENT_THREAD(&shared);
PlatformThread::Delegate *thread2 =
new TOOLS_SANITY_TEST_CONCURRENT_THREAD(&shared);
PlatformThread::Create(0, thread1, &a);
PlatformThread::Create(0, thread2, &b);
PlatformThread::Join(a);
PlatformThread::Join(b);
EXPECT_TRUE(shared);
delete thread1;
delete thread2;
}
<|endoftext|>
|
<commit_before>/*=========================================================================
Program: Insight Segmentation & Registration Toolkit (ITK)
Module: itkThresholdImageFilterTest.cxx
Language: C++
Date: $Date$
Version: $Revision$
Copyright (c) 2000 National Library of Medicine
All rights reserved.
See COPYRIGHT.txt for copyright details.
=========================================================================*/
#include <iostream>
#include <string>
#include "itkPhysicalImage.h"
#include "itkScalar.h"
#include "itkRandomImageSource.h"
#include "itkThresholdImageFilter.h"
#include "itkCommand.h"
#include "itkOutputWindow.h"
// this class is used to send output to stdout and not the itk window
class TextOutput : public itk::OutputWindow
{
public:
virtual void DisplayText(const char* s)
{
std::cout << s << std::endl;
}
};
int main()
{
// Comment the following if you want to use the itk text output window
itk::OutputWindow::SetInstance(new TextOutput);
// Uncomment the following if you want to see each message independently
// itk::OutputWindow::GetInstance()->PromptUserOn();
// typedef itk::Image<itk::Scalar<float>,2> FloatImage2DType;
typedef itk::PhysicalImage<float,2> FloatImage2DType;
itk::RandomImageSource<FloatImage2DType>::Pointer random;
random = itk::RandomImageSource<FloatImage2DType>::New();
random->SetMin(0.0);
random->SetMax(1000.0);
char buffer[8];
std::string os;
// Test #1, filter goes out of scope
itk::OutputWindow::GetInstance()->DisplayText( "Test #1: Filter goes out of scope -----------------" );
{
itk::ThresholdImageFilter<FloatImage2DType>::Pointer threshold;
threshold = itk::ThresholdImageFilter<FloatImage2DType>::New();
threshold->SetInput(random->GetOutput());
threshold->Update();
os = "Filter: " + std::string(itoa((int)(void *)(threshold), buffer, 10));
itk::OutputWindow::GetInstance()->DisplayText( os.c_str() );
os = "Output #0: " + std::string(itoa((int)(void *)(threshold->GetOutput(0)),
buffer, 10));
itk::OutputWindow::GetInstance()->DisplayText( os.c_str() );
os = "Output #1: " + std::string(itoa((int)(void *)(threshold->GetOutput(1)),
buffer, 10));
itk::OutputWindow::GetInstance()->DisplayText( os.c_str() );
threshold->GetOutput(0)->DebugOn();
threshold->GetOutput(1)->DebugOn();
threshold->DebugOn();
itk::OutputWindow::GetInstance()->DisplayText( "Ending Test #1: filter goes out of scope" );
itk::OutputWindow::GetInstance()->DisplayText( "End of Test #1 -----------------------------------" );
}
// Test #2, user keeps an extra handle to an output
itk::OutputWindow::GetInstance()->DisplayText( "Test #2: User keeps an extra hold on an output -----------------" );
{
FloatImage2DType::Pointer keep;
itk::ThresholdImageFilter<FloatImage2DType>::Pointer threshold;
threshold = itk::ThresholdImageFilter<FloatImage2DType>::New();
threshold->SetInput(random->GetOutput());
threshold->Update();
os = "Filter: " + std::string(itoa((int)(void *)(threshold), buffer, 10));
itk::OutputWindow::GetInstance()->DisplayText( os.c_str() );
os = "Output #0: " + std::string(itoa((int)(void *)(threshold->GetOutput(0)),
buffer, 10));
itk::OutputWindow::GetInstance()->DisplayText( os.c_str() );
os = "Output #1: " + std::string(itoa((int)(void *)(threshold->GetOutput(1)),
buffer, 10));
itk::OutputWindow::GetInstance()->DisplayText( os.c_str() );
threshold->GetOutput(0)->DebugOn();
threshold->GetOutput(1)->DebugOn();
threshold->DebugOn();
keep = threshold->GetOutput(0);
itk::OutputWindow::GetInstance()->DisplayText( "End of Test #2: last handle on output 0 should go out of scope");
}
itk::OutputWindow::GetInstance()->DisplayText( "End of Test #2 -----------------------------------");
// Test #3, user disconnects a data object from the pipeline
itk::OutputWindow::GetInstance()->DisplayText( "Test #3: application disconnects a data object from the pipeline -----------------" );
{
FloatImage2DType::Pointer keep;
itk::ThresholdImageFilter<FloatImage2DType>::Pointer threshold;
threshold = itk::ThresholdImageFilter<FloatImage2DType>::New();
threshold->SetInput(random->GetOutput());
threshold->Update();
os = "Filter: " + std::string(itoa((int)(void *)(threshold), buffer, 10));
itk::OutputWindow::GetInstance()->DisplayText( os.c_str() );
os = "Output #0: " + std::string(itoa((int)(void *)(threshold->GetOutput(0)),
buffer, 10));
itk::OutputWindow::GetInstance()->DisplayText( os.c_str() );
os = "Output #1: " + std::string(itoa((int)(void *)(threshold->GetOutput(1)),
buffer, 10));
itk::OutputWindow::GetInstance()->DisplayText( os.c_str() );
threshold->GetOutput(0)->DebugOn();
threshold->GetOutput(1)->DebugOn();
threshold->DebugOn();
keep = threshold->GetOutput(0);
keep->DisconnectPipeline();
itk::OutputWindow::GetInstance()->DisplayText( "End of Test #3: last handle on output 0 should go out of scope");
}
itk::OutputWindow::GetInstance()->DisplayText( "End of Test #3 -----------------------------------");
return EXIT_SUCCESS;
}
<commit_msg>FIX: removed itoa() calls<commit_after>/*=========================================================================
Program: Insight Segmentation & Registration Toolkit (ITK)
Module: itkThresholdImageFilterTest.cxx
Language: C++
Date: $Date$
Version: $Revision$
Copyright (c) 2000 National Library of Medicine
All rights reserved.
See COPYRIGHT.txt for copyright details.
=========================================================================*/
#include <iostream>
#include <strstream>
#include "itkPhysicalImage.h"
#include "itkScalar.h"
#include "itkRandomImageSource.h"
#include "itkThresholdImageFilter.h"
#include "itkCommand.h"
#include "itkOutputWindow.h"
// this class is used to send output to stdout and not the itk window
class TextOutput : public itk::OutputWindow
{
public:
virtual void DisplayText(const char* s)
{
std::cout << s << std::endl;
}
};
int main()
{
// Comment the following if you want to use the itk text output window
itk::OutputWindow::SetInstance(new TextOutput);
// Uncomment the following if you want to see each message independently
// itk::OutputWindow::GetInstance()->PromptUserOn();
// typedef itk::Image<itk::Scalar<float>,2> FloatImage2DType;
typedef itk::PhysicalImage<float,2> FloatImage2DType;
itk::RandomImageSource<FloatImage2DType>::Pointer random;
random = itk::RandomImageSource<FloatImage2DType>::New();
random->SetMin(0.0);
random->SetMax(1000.0);
std::ostrstream *os;
// Test #1, filter goes out of scope
itk::OutputWindow::GetInstance()->DisplayText( "Test #1: Filter goes out of scope -----------------" );
{
itk::ThresholdImageFilter<FloatImage2DType>::Pointer threshold;
threshold = itk::ThresholdImageFilter<FloatImage2DType>::New();
threshold->SetInput(random->GetOutput());
threshold->Update();
os = new std::ostrstream();
*os << "Filter: " << threshold.GetPointer() << std::ends;
itk::OutputWindow::GetInstance()->DisplayText( os->str() );
os->rdbuf()->freeze(0);
delete os;
os = new std::ostrstream();
*os << "Output #0: " << threshold->GetOutput(0).GetPointer() << std::ends;
itk::OutputWindow::GetInstance()->DisplayText( os->str() );
os->rdbuf()->freeze(0);
delete os;
os = new std::ostrstream();
*os << "Output #1: " << threshold->GetOutput(1).GetPointer() << std::ends;
itk::OutputWindow::GetInstance()->DisplayText( os->str() );
os->rdbuf()->freeze(0);
delete os;
threshold->GetOutput(0)->DebugOn();
threshold->GetOutput(1)->DebugOn();
threshold->DebugOn();
itk::OutputWindow::GetInstance()->DisplayText( "Ending Test #1: filter goes out of scope" );
itk::OutputWindow::GetInstance()->DisplayText( "End of Test #1 -----------------------------------" );
}
// Test #2, user keeps an extra handle to an output
itk::OutputWindow::GetInstance()->DisplayText( "Test #2: User keeps an extra hold on an output -----------------" );
{
FloatImage2DType::Pointer keep;
itk::ThresholdImageFilter<FloatImage2DType>::Pointer threshold;
threshold = itk::ThresholdImageFilter<FloatImage2DType>::New();
threshold->SetInput(random->GetOutput());
threshold->Update();
os = new std::ostrstream();
*os << "Filter: " << threshold.GetPointer() << std::ends;
itk::OutputWindow::GetInstance()->DisplayText( os->str() );
os->rdbuf()->freeze(0);
delete os;
os = new std::ostrstream();
*os << "Output #0: " << threshold->GetOutput(0).GetPointer() << std::ends;
itk::OutputWindow::GetInstance()->DisplayText( os->str() );
os->rdbuf()->freeze(0);
delete os;
os = new std::ostrstream();
*os << "Output #1: " << threshold->GetOutput(1).GetPointer() << std::ends;
itk::OutputWindow::GetInstance()->DisplayText( os->str() );
os->rdbuf()->freeze(0);
delete os;
threshold->GetOutput(0)->DebugOn();
threshold->GetOutput(1)->DebugOn();
threshold->DebugOn();
keep = threshold->GetOutput(0);
itk::OutputWindow::GetInstance()->DisplayText( "End of Test #2: last handle on output 0 should go out of scope");
}
itk::OutputWindow::GetInstance()->DisplayText( "End of Test #2 -----------------------------------");
// Test #3, user disconnects a data object from the pipeline
itk::OutputWindow::GetInstance()->DisplayText( "Test #3: application disconnects a data object from the pipeline -----------------" );
{
FloatImage2DType::Pointer keep;
itk::ThresholdImageFilter<FloatImage2DType>::Pointer threshold;
threshold = itk::ThresholdImageFilter<FloatImage2DType>::New();
threshold->SetInput(random->GetOutput());
threshold->Update();
os = new std::ostrstream();
*os << "Filter: " << threshold.GetPointer() << std::ends;
itk::OutputWindow::GetInstance()->DisplayText( os->str() );
os->rdbuf()->freeze(0);
delete os;
os = new std::ostrstream();
*os << "Output #0: " << threshold->GetOutput(0).GetPointer() << std::ends;
itk::OutputWindow::GetInstance()->DisplayText( os->str() );
os->rdbuf()->freeze(0);
delete os;
os = new std::ostrstream();
*os << "Output #1: " << threshold->GetOutput(1).GetPointer() << std::ends;
itk::OutputWindow::GetInstance()->DisplayText( os->str() );
os->rdbuf()->freeze(0);
delete os;
threshold->GetOutput(0)->DebugOn();
threshold->GetOutput(1)->DebugOn();
threshold->DebugOn();
keep = threshold->GetOutput(0);
keep->DisconnectPipeline();
itk::OutputWindow::GetInstance()->DisplayText( "End of Test #3: last handle on output 0 should go out of scope");
}
itk::OutputWindow::GetInstance()->DisplayText( "End of Test #3 -----------------------------------");
return EXIT_SUCCESS;
}
<|endoftext|>
|
<commit_before>/*=========================================================================
Program: Insight Segmentation & Registration Toolkit
Module: itkVersorTransformOptimizerTest.cxx
Language: C++
Date: $Date$
Version: $Revision$
Copyright (c) 2002 Insight Consortium. All rights reserved.
See ITKCopyright.txt or http://www.itk.org/HTML/Copyright.htm for details.
This software is distributed WITHOUT ANY WARRANTY; without even
the implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR
PURPOSE. See the above copyright notices for more information.
=========================================================================*/
#include <itkVersorTransformOptimizer.h>
#include <itkVector.h>
#include <itkVersor.h>
#include <itkCovariantVector.h>
#include <itkVersorTransform.h>
/**
* The objectif function is the scalar product:
*
* f( V ) = < A, V(B) >
*
* where:
*
* V is a Versor representing a rotation
* A is a vector
* B is another vector
*
* the vector A = [ 0 0 1 ]
* the vector B = [ 0 1 0 ]
*
* the Versor solution should be: V = [ k1 0 0 k2 ]
*
* k1 = sin( 45 degrees )
* k2 = cos( 45 degrees )
*
*/
class CostFunction : public itk::LightObject
{
public:
typedef CostFunction Self;
typedef itk::LightObject Superclass;
typedef itk::SmartPointer<Self> Pointer;
typedef itk::SmartPointer<const Self> ConstPointer;
typedef itk::VersorTransform<double> TransformType;
itkNewMacro( Self );
enum { SpaceDimension = 3 };
typedef itk::Versor< double > ParametersType;
typedef ParametersType::VectorType AxisType;
typedef itk::CovariantVector< double,
SpaceDimension > DerivativeType;
typedef itk::Vector< double, SpaceDimension > VectorType;
typedef double MeasureType;
CostFunction()
{
m_Transform = TransformType::New();
}
const ParametersType & GetParameters(void) const
{
return m_Parameters;
}
const MeasureType & GetValue( const ParametersType & parameters ) const
{
VectorType A;
VectorType B;
A[0] = 0;
A[1] = 0;
A[2] = 1;
B[0] = 0;
B[1] = 1;
B[2] = 0;
m_Parameters = parameters;
m_Transform->SetRotation( m_Parameters );
const VectorType C = m_Transform->TransformVector( B );
m_Measure = A * C;
return m_Measure;
}
const DerivativeType & GetDerivative(
const ParametersType & parameters ) const
{
const MeasureType baseValue = this->GetValue( parameters );
ParametersType versorX;
ParametersType versorY;
ParametersType versorZ;
const double deltaAngle = 0.00175; // in radians = about 0.1 degree
versorX.SetRotationAroundX( deltaAngle );
versorY.SetRotationAroundY( deltaAngle );
versorZ.SetRotationAroundZ( deltaAngle );
const MeasureType turnXValue = this->GetValue( parameters * versorX );
const MeasureType turnYValue = this->GetValue( parameters * versorY );
const MeasureType turnZValue = this->GetValue( parameters * versorZ );
m_Derivative[0] = ( turnXValue - baseValue ) / deltaAngle;
m_Derivative[1] = ( turnYValue - baseValue ) / deltaAngle;
m_Derivative[2] = ( turnZValue - baseValue ) / deltaAngle;
return m_Derivative;
}
private:
mutable TransformType::Pointer m_Transform;
mutable ParametersType m_Parameters;
mutable MeasureType m_Measure;
mutable DerivativeType m_Derivative;
};
int main()
{
std::cout << "VersorTransform Optimizer Test ";
std::cout << std::endl << std::endl;
typedef itk::VersorTransformOptimizer< CostFunction > OptimizerType;
// Declaration of a itkOptimizer
OptimizerType::Pointer itkOptimizer = OptimizerType::New();
// Declaration of the CostFunction adaptor
CostFunction::Pointer costFunction = CostFunction::New();
itkOptimizer->SetCostFunction( costFunction );
typedef CostFunction::ParametersType ParametersType;
typedef OptimizerType::TransformType TransformType;
typedef TransformType::ParametersType TransformParametersType;
// We start with a null rotation
ParametersType initialRotation;
ParametersType::VectorType axis;
axis = 1.0f, 0.0f, 0.0f;
ParametersType::ValueType angle = 0.0f;
initialRotation.Set( axis, angle );
itkOptimizer->MaximizeOn();
itkOptimizer->SetGradientMagnitudeTolerance( 1e-15 );
itkOptimizer->SetMaximumStepLength( 0.1745 ); // About 10 deegres
itkOptimizer->SetMinimumStepLength( 1e-9 );
itkOptimizer->SetNumberOfIterations( 300 );
itkOptimizer->SetInitialPosition( initialRotation );
itkOptimizer->StartOptimization();
ParametersType finalPosition;
finalPosition = costFunction->GetParameters();
std::cout << "Solution = (" << finalPosition << ")" << std::endl;
//
// check results to see if it is within range
//
bool pass = true;
// True versor
ParametersType trueParameters;
ParametersType::VectorType trueAxis;
ParametersType::ValueType trueAngle;
trueAxis = 1.0f, 0.0f, 0.0f;
trueAngle = 2.0 * atan( 1.0f );
trueParameters.Set( trueAxis, trueAngle );
std::cout << "True Parameters = " << trueParameters << std::endl;
for( unsigned int j = 0; j < 2; j++ )
{
ParametersType ratio = finalPosition * trueParameters.GetReciprocal();
const ParametersType::ValueType cosHalfAngle = ratio.GetW();
const ParametersType::ValueType cosHalfAngleSquare =
cosHalfAngle * cosHalfAngle;
if( cosHalfAngleSquare < 0.95 )
{
pass = false;
break;
}
}
if( !pass )
{
std::cout << "Test failed." << std::endl;
return EXIT_FAILURE;
}
std::cout << "Test passed." << std::endl;
return EXIT_SUCCESS;
}
<commit_msg>ERR: bad initialization.<commit_after>/*=========================================================================
Program: Insight Segmentation & Registration Toolkit
Module: itkVersorTransformOptimizerTest.cxx
Language: C++
Date: $Date$
Version: $Revision$
Copyright (c) 2002 Insight Consortium. All rights reserved.
See ITKCopyright.txt or http://www.itk.org/HTML/Copyright.htm for details.
This software is distributed WITHOUT ANY WARRANTY; without even
the implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR
PURPOSE. See the above copyright notices for more information.
=========================================================================*/
#include <itkVersorTransformOptimizer.h>
#include <itkVector.h>
#include <itkVersor.h>
#include <itkCovariantVector.h>
#include <itkVersorTransform.h>
/**
* The objectif function is the scalar product:
*
* f( V ) = < A, V(B) >
*
* where:
*
* V is a Versor representing a rotation
* A is a vector
* B is another vector
*
* the vector A = [ 0 0 1 ]
* the vector B = [ 0 1 0 ]
*
* the Versor solution should be: V = [ k1 0 0 k2 ]
*
* k1 = sin( 45 degrees )
* k2 = cos( 45 degrees )
*
*/
class CostFunction : public itk::LightObject
{
public:
typedef CostFunction Self;
typedef itk::LightObject Superclass;
typedef itk::SmartPointer<Self> Pointer;
typedef itk::SmartPointer<const Self> ConstPointer;
typedef itk::VersorTransform<double> TransformType;
itkNewMacro( Self );
enum { SpaceDimension = 3 };
typedef itk::Versor< double > ParametersType;
typedef ParametersType::VectorType AxisType;
typedef itk::CovariantVector< double,
SpaceDimension > DerivativeType;
typedef itk::Vector< double, SpaceDimension > VectorType;
typedef double MeasureType;
CostFunction()
{
m_Transform = TransformType::New();
}
const ParametersType & GetParameters(void) const
{
return m_Parameters;
}
const MeasureType & GetValue( const ParametersType & parameters ) const
{
VectorType A;
VectorType B;
A[0] = 0;
A[1] = 0;
A[2] = 1;
B[0] = 0;
B[1] = 1;
B[2] = 0;
m_Parameters = parameters;
m_Transform->SetRotation( m_Parameters );
const VectorType C = m_Transform->TransformVector( B );
m_Measure = A * C;
return m_Measure;
}
const DerivativeType & GetDerivative(
const ParametersType & parameters ) const
{
const MeasureType baseValue = this->GetValue( parameters );
ParametersType versorX;
ParametersType versorY;
ParametersType versorZ;
const double deltaAngle = 0.00175; // in radians = about 0.1 degree
versorX.SetRotationAroundX( deltaAngle );
versorY.SetRotationAroundY( deltaAngle );
versorZ.SetRotationAroundZ( deltaAngle );
const MeasureType turnXValue = this->GetValue( parameters * versorX );
const MeasureType turnYValue = this->GetValue( parameters * versorY );
const MeasureType turnZValue = this->GetValue( parameters * versorZ );
m_Derivative[0] = ( turnXValue - baseValue ) / deltaAngle;
m_Derivative[1] = ( turnYValue - baseValue ) / deltaAngle;
m_Derivative[2] = ( turnZValue - baseValue ) / deltaAngle;
return m_Derivative;
}
private:
mutable TransformType::Pointer m_Transform;
mutable ParametersType m_Parameters;
mutable MeasureType m_Measure;
mutable DerivativeType m_Derivative;
};
int main()
{
std::cout << "VersorTransform Optimizer Test ";
std::cout << std::endl << std::endl;
typedef itk::VersorTransformOptimizer< CostFunction > OptimizerType;
// Declaration of a itkOptimizer
OptimizerType::Pointer itkOptimizer = OptimizerType::New();
// Declaration of the CostFunction adaptor
CostFunction::Pointer costFunction = CostFunction::New();
itkOptimizer->SetCostFunction( costFunction );
typedef CostFunction::ParametersType ParametersType;
typedef OptimizerType::TransformType TransformType;
typedef TransformType::ParametersType TransformParametersType;
// We start with a null rotation
ParametersType initialRotation;
ParametersType::VectorType axis;
axis[0] = 1.0f;
axis[1] = 0.0f;
axis[2] = 0.0f;
ParametersType::ValueType angle = 0.0f;
initialRotation.Set( axis, angle );
itkOptimizer->MaximizeOn();
itkOptimizer->SetGradientMagnitudeTolerance( 1e-15 );
itkOptimizer->SetMaximumStepLength( 0.1745 ); // About 10 deegres
itkOptimizer->SetMinimumStepLength( 1e-9 );
itkOptimizer->SetNumberOfIterations( 300 );
itkOptimizer->SetInitialPosition( initialRotation );
itkOptimizer->StartOptimization();
ParametersType finalPosition;
finalPosition = costFunction->GetParameters();
std::cout << "Solution = (" << finalPosition << ")" << std::endl;
//
// check results to see if it is within range
//
bool pass = true;
// True versor
ParametersType trueParameters;
ParametersType::VectorType trueAxis;
ParametersType::ValueType trueAngle;
trueAxis = 1.0f, 0.0f, 0.0f;
trueAngle = 2.0 * atan( 1.0f );
trueParameters.Set( trueAxis, trueAngle );
std::cout << "True Parameters = " << trueParameters << std::endl;
for( unsigned int j = 0; j < 2; j++ )
{
ParametersType ratio = finalPosition * trueParameters.GetReciprocal();
const ParametersType::ValueType cosHalfAngle = ratio.GetW();
const ParametersType::ValueType cosHalfAngleSquare =
cosHalfAngle * cosHalfAngle;
if( cosHalfAngleSquare < 0.95 )
{
pass = false;
break;
}
}
if( !pass )
{
std::cout << "Test failed." << std::endl;
return EXIT_FAILURE;
}
std::cout << "Test passed." << std::endl;
return EXIT_SUCCESS;
}
<|endoftext|>
|
<commit_before>#include "Neohuman.h"
#include <iostream>
#include "BWEM/bwem.h"
using namespace BWAPI;
using namespace Filter;
using namespace BWEM;
using namespace BWEM::BWAPI_ext;
using namespace BWEM::utils;
#define MIN(a, b) (((a) < (b) ? (a) : (b)))
#define MAX(a, b) (((a) < (b) ? (b) : (a)))
#define SATRUATION_RADIUS 350
#define WORKERAGGRORADIUS 200
#define SHOWTHINGS
namespace { auto & BWEMMap = Map::Instance(); }
bool Neohuman::doBuild(Unit u, UnitType building, TilePosition at) {
_buildingQueue.push_back(Triple<int, UnitType, TilePosition>{u->getID(), building, at});
}
std::pair <int, int> Neohuman::getQueuedResources() {
std::pair <int, int> resources;
for (auto &o : _buildingQueue)
resources.first += o.second.mineralPrice(),
resources.second += o.second.gasPrice();
return resources;
}
std::pair <int, int> Neohuman::getSpendableResources() {
std::pair <int, int> result = { Broodwar->self()->minerals(), Broodwar->self()->gas() };
auto queued = this->getQueuedResources();
result.first -= queued.first, result.second -= queued.second;
return result;
}
void Neohuman::onStart() {
Broodwar << "The map is totally not " << Broodwar->mapName() << "!" << std::endl;
//Broodwar->enableFlag(Flag::UserInput);
// Uncomment the following line and the bot will know about everything through the fog of war (cheat).
//Broodwar->enableFlag(Flag::CompleteMapInformation);
// Set the command optimization level so that common commands can be grouped
// and reduce the bot's APM (Actions Per Minute).
Broodwar->setCommandOptimizationLevel(2);
// Check if this is a replay
if (!Broodwar->isReplay()) {
if (Broodwar->enemy())
Broodwar << "The matchup is me (" << Broodwar->self()->getRace() << ") vs " << Broodwar->enemy()->getRace() << std::endl;
}
BWEMMap.Initialize();
BWEMMap.EnableAutomaticPathAnalysis();
}
void Neohuman::onEnd(bool didWin) {
// Called when the game ends
if (didWin) {
} else {
}
}
int Neohuman::randint(int min, int max) {
std::uniform_int_distribution<int> dist(min, max);
return dist(_rand);
}
template <typename T>
T Neohuman::randele(std::vector <T> &v) {
return v[randint(0, v.size())];
}
void Neohuman::onFrame() {
// Called once every game frame
int constructingLine = 0;
int availableMinerals = Broodwar->self()->minerals();
#ifdef SHOWTHINGS
// Display the game frame rate as text in the upper left area of the screen
Broodwar->drawTextScreen(200, 0, "FPS: %d", Broodwar->getFPS());
Broodwar->drawTextScreen(200, 12, "Average FPS: %f", Broodwar->getAverageFPS());
Broodwar->drawTextScreen(200, 24, "I want %d more supply (%d queued, %d in production)", _wantedExtraSupply, _queuedSupply, _supplyBeingMade);
Broodwar->drawTextScreen(200, 36, "I have %d barracks!", _nBarracks);
#endif
try {
//BWEM::utils::gridMapExample(BWEMMap);
//BWEM::utils::drawMap(BWEMMap);
} catch (const std::exception & e) {
Broodwar << "EXCEPTION: " << e.what() << std::endl;
}
// Return if the game is a replay or is paused
if (Broodwar->isReplay() || Broodwar->isPaused() || !Broodwar->self())
return;
for (auto &u : Broodwar->self()->getUnits()) {
if (u->exists() && u->isBeingConstructed()) {
Broodwar->drawTextScreen(0, constructingLine, "%s", u->getType().c_str());
constructingLine += 12;
}
}
#ifdef SHOWTHINGS
// Show worker info
for (auto &u : Broodwar->self()->getUnits()) {
if (u->getType().isResourceDepot()) {
Broodwar->drawCircleMap(u->getPosition(), SATRUATION_RADIUS, Colors::Blue);
auto workers = u->getUnitsInRadius(SATRUATION_RADIUS, (IsGatheringMinerals));
auto refineries = u->getUnitsInRadius(SATRUATION_RADIUS, (IsRefinery));
auto gasGeysers = u->getUnitsInRadius(SATRUATION_RADIUS);
auto mineralFields = u->getUnitsInRadius(SATRUATION_RADIUS, (IsMineralField));
Broodwar->drawTextMap(u->getPosition() + Position(0, 30), "%cWorkers: %d/%d", Text::White, workers.size(), 2*mineralFields.size());
}
}
#endif
// Prevent spamming by only running our onFrame once every number of latency frames.
// Latency frames are the number of frames before commands are processed.
if (Broodwar->getFrameCount() % Broodwar->getLatencyFrames() != 0)
return;
_supplyBeingMade = 0;
for (auto &u : Broodwar->self()->getUnits()) {
if (u->isConstructing() && u->getType().getRace().getSupplyProvider() == u->getType())
_supplyBeingMade += 8;
}
availableMinerals -= 100*_queuedSupply/8;
if (Broodwar->elapsedTime() - _timeLastQueuedSupply > 5) {
_queuedSupply = 0;
_timeLastQueuedSupply = Broodwar->elapsedTime();
}
_nSupplyOverhead = 2 + MAX((Broodwar->self()->supplyUsed() - 10) / 8, 0);
_wantedExtraSupply = (Broodwar->self()->supplyUsed() - (Broodwar->self()->supplyTotal() + _supplyBeingMade + _queuedSupply)) / 2 + _nSupplyOverhead;
_nBarracks = 0;
for (auto &u : Broodwar->self()->getUnits()) {
// If a cc is under construction
if (u->isConstructing() && u->getType() == u->getType().getRace().getCenter() && _isExpanding)
availableMinerals += 400;
// If a barracks is under construction
if (u->isConstructing() && u->getType() == UnitTypes::Terran_Barracks && _isBuildingBarracks)
availableMinerals += 150;
if (u->getType() == UnitTypes::Terran_Barracks) {
++_nBarracks;
}
}
if (_isExpanding) {
availableMinerals -= 400;
}
if (_isBuildingBarracks) {
availableMinerals -= 150;
}
// Check if supply should be increased
if (_wantedExtraSupply > 0 && availableMinerals >= 100 && Broodwar->self()->supplyTotal() < 400) {
// Find unit to build our supply!
for (auto &unit : Broodwar->self()->getUnits()) {
if (unit->exists() && unit->isGatheringMinerals() && unit->isMoving() && !unit->isCarryingMinerals()) {
// We have found our candidate!
auto supplyType = unit->getType().getRace().getSupplyProvider();
auto buildPos = Broodwar->getBuildLocation(supplyType, unit->getTilePosition());
if (unit->build(supplyType, buildPos)) {
_queuedSupply += 8;
_timeLastQueuedSupply = Broodwar->elapsedTime();
break;
}
}
}
}
if (availableMinerals >= 150 && !_isBuildingBarracks && _nBarracks < 20) {
// Build barracks!
for (auto &u : Broodwar->self()->getUnits()) {
if (u->exists() && u->isGatheringMinerals() && u->isMoving() && !u->isCarryingMinerals()) {
auto buildingType = UnitTypes::Terran_Barracks;
auto buildingPos = Broodwar->getBuildLocation(buildingType, u->getTilePosition());
if (u->build(buildingType, buildingPos)) {
_isBuildingBarracks = true;
availableMinerals -= 150;
break;
}
}
}
}
/*if (!_isExpanding && availableMinerals >= 400){
// Expand!
for (auto &u : Broodwar->self()->getUnits()) {
if (u->exists() && u->isGatheringMinerals() && u->isMoving() && !u->isCarryingMinerals()) {
// Builder found!
auto buildingType = u->getType().getRace().getCenter();
auto buildPos = Broodwar->getBuildLocation(buildingType, u->getTilePosition());
if (u->build(buildingType, buildPos)) {
_isExpanding = true;
availableMinerals -= 400;
break;
}
}
}
}*/
// Iterate through all the units that we own
for (auto &u : Broodwar->self()->getUnits()) {
// Ignore the unit if it no longer exists
// Make sure to include this block when handling any Unit pointer!
if (!u->exists())
continue;
// Ignore the unit if it has one of the following status ailments
if (u->isLockedDown() || u->isMaelstrommed() || u->isStasised())
continue;
// Ignore the unit if it is in one of the following states
if (u->isLoaded() || !u->isPowered() || u->isStuck())
continue;
// Ignore the unit if it is incomplete or busy constructing
if (!u->isCompleted() || u->isConstructing())
continue;
// If the unit is a worker unit
if (u->getType().isWorker()) {
auto enemyUnit = u->getClosestUnit(IsEnemy && IsAttacking, WORKERAGGRORADIUS);
if (enemyUnit)
u->attack(enemyUnit);
// if our worker is idle
if (u->isIdle()) {
// Order workers carrying a resource to return them to the center,
// otherwise find a mineral patch to harvest.
if (u->isCarryingGas() || u->isCarryingMinerals())
u->returnCargo();
else if (!u->getPowerUp()) {
// Probably need to set up some better logic for this
auto preferredMiningLocation = u->getClosestUnit(IsMineralField);
u->gather(preferredMiningLocation);
}
}
} else if (u->getType().isResourceDepot()) {
auto nearbyGeysers = u->getUnitsInRadius(SATRUATION_RADIUS, (GetType == UnitTypes::Resource_Vespene_Geyser));
if (u->isIdle()) {
auto workers = u->getUnitsInRadius(SATRUATION_RADIUS, (IsGatheringMinerals));
if (nWorkers >= 70)
continue;
auto mineralFields = u->getUnitsInRadius(SATRUATION_RADIUS, (IsMineralField));
if (workers.size() < mineralFields.size() * 2 && availableMinerals >= 50) {
if (u->train(u->getType().getRace().getWorker())) {
Position pos = u->getPosition();
Error lastErr = Broodwar->getLastError();
Broodwar->registerEvent([pos, lastErr](Game*){ Broodwar->drawTextMap(pos + Position(0, -10), "%c%s", Text::Red, lastErr.c_str()); }, // action
nullptr, // condition
Broodwar->getLatencyFrames()); // frames to run
} else {
availableMinerals -= 50;
}
}
}
} else if (u->getType() == UnitTypes::Terran_Barracks) {
if (u->isIdle() && availableMinerals >= 50)
if (!u->train(UnitTypes::Terran_Marine))
availableMinerals -= 50;
} else if (u->getType() == UnitTypes::Terran_Marine && Broodwar->getFrameCount() % 20 == 0) {
auto enemyUnit = u->getClosestUnit(IsEnemy && IsAttacking);
if (enemyUnit) {
u->attack(enemyUnit->getPosition());
continue;
}
enemyUnit = u->getClosestUnit(IsEnemy);
if (enemyUnit) {
u->attack(enemyUnit->getPosition());
continue;
}
auto closestMarine = u->getClosestUnit(GetType == UnitTypes::Terran_Marine);
if (closestMarine) {
auto walk = u->getPosition() - closestMarine->getPosition();
u->move(u->getPosition() + walk);
}
}
}
}
void Neohuman::onSendText(std::string text) {
Broodwar->sendText("%s", text.c_str());
}
void Neohuman::onReceiveText(Player player, std::string text) {
Broodwar << player->getName() << " said \"" << text << "\"" << std::endl;
}
void Neohuman::onPlayerLeft(Player player) {
Broodwar->sendText("Goodbye %s!", player->getName().c_str());
}
void Neohuman::onNukeDetect(Position target) {
if (target) {
Broodwar << "Nuclear Launch Detected at " << target << std::endl;
} else {
Broodwar->sendText("Where's the nuke?");
}
// You can also retrieve all the nuclear missile targets using Broodwar->getNukeDots()!
}
void Neohuman::onUnitDiscover(Unit unit) {
}
void Neohuman::onUnitEvade(Unit unit) {
}
void Neohuman::onUnitShow(Unit unit) {
}
void Neohuman::onUnitHide(Unit unit) {
}
void Neohuman::onUnitCreate(Unit unit) {
}
void Neohuman::onUnitDestroy(Unit unit) {
}
void Neohuman::onUnitMorph(Unit unit) {
this->onUnitComplete(unit);
}
void Neohuman::onUnitRenegade(Unit unit){
}
void Neohuman::onSaveGame(std::string gameName){
}
void Neohuman::onUnitComplete(Unit unit){
if (unit->getType() == unit->getType().getRace().getCenter())
_isExpanding = false;
if (unit->getType() == UnitTypes::Terran_Barracks)
_isBuildingBarracks = false;
}
<commit_msg>Worker logic<commit_after>#include "Neohuman.h"
#include <iostream>
#include "BWEM/bwem.h"
using namespace BWAPI;
using namespace Filter;
using namespace BWEM;
using namespace BWEM::BWAPI_ext;
using namespace BWEM::utils;
#define MIN(a, b) (((a) < (b) ? (a) : (b)))
#define MAX(a, b) (((a) < (b) ? (b) : (a)))
#define SATRUATION_RADIUS 350
#define WORKERAGGRORADIUS 200
#define SHOWTHINGS
namespace { auto & BWEMMap = Map::Instance(); }
bool Neohuman::doBuild(Unit u, UnitType building, TilePosition at) {
_buildingQueue.push_back(Triple<int, UnitType, TilePosition>{u->getID(), building, at});
}
std::pair <int, int> Neohuman::getQueuedResources() {
std::pair <int, int> resources;
for (auto &o : _buildingQueue)
resources.first += o.second.mineralPrice(),
resources.second += o.second.gasPrice();
return resources;
}
std::pair <int, int> Neohuman::getSpendableResources() {
std::pair <int, int> result = { Broodwar->self()->minerals(), Broodwar->self()->gas() };
auto queued = this->getQueuedResources();
result.first -= queued.first, result.second -= queued.second;
return result;
}
void Neohuman::onStart() {
Broodwar << "The map is totally not " << Broodwar->mapName() << "!" << std::endl;
//Broodwar->enableFlag(Flag::UserInput);
// Uncomment the following line and the bot will know about everything through the fog of war (cheat).
//Broodwar->enableFlag(Flag::CompleteMapInformation);
// Set the command optimization level so that common commands can be grouped
// and reduce the bot's APM (Actions Per Minute).
Broodwar->setCommandOptimizationLevel(2);
// Check if this is a replay
if (!Broodwar->isReplay()) {
if (Broodwar->enemy())
Broodwar << "The matchup is me (" << Broodwar->self()->getRace() << ") vs " << Broodwar->enemy()->getRace() << std::endl;
}
BWEMMap.Initialize();
BWEMMap.EnableAutomaticPathAnalysis();
}
void Neohuman::onEnd(bool didWin) {
// Called when the game ends
if (didWin) {
} else {
}
}
int Neohuman::randint(int min, int max) {
std::uniform_int_distribution<int> dist(min, max);
return dist(_rand);
}
template <typename T>
T Neohuman::randele(std::vector <T> &v) {
return v[randint(0, v.size())];
}
void Neohuman::onFrame() {
// Called once every game frame
int constructingLine = 0;
int availableMinerals = Broodwar->self()->minerals();
#ifdef SHOWTHINGS
// Display the game frame rate as text in the upper left area of the screen
Broodwar->drawTextScreen(200, 0, "FPS: %d", Broodwar->getFPS());
Broodwar->drawTextScreen(200, 12, "Average FPS: %f", Broodwar->getAverageFPS());
Broodwar->drawTextScreen(200, 24, "I want %d more supply (%d queued, %d in production)", _wantedExtraSupply, _queuedSupply, _supplyBeingMade);
Broodwar->drawTextScreen(200, 36, "I have %d barracks!", _nBarracks);
#endif
try {
//BWEM::utils::gridMapExample(BWEMMap);
//BWEM::utils::drawMap(BWEMMap);
} catch (const std::exception & e) {
Broodwar << "EXCEPTION: " << e.what() << std::endl;
}
// Return if the game is a replay or is paused
if (Broodwar->isReplay() || Broodwar->isPaused() || !Broodwar->self())
return;
for (auto &u : Broodwar->self()->getUnits()) {
if (u->exists() && u->isBeingConstructed()) {
Broodwar->drawTextScreen(0, constructingLine, "%s", u->getType().c_str());
constructingLine += 12;
}
}
#ifdef SHOWTHINGS
// Show worker info
for (auto &u : Broodwar->self()->getUnits()) {
if (u->getType().isResourceDepot()) {
Broodwar->drawCircleMap(u->getPosition(), SATRUATION_RADIUS, Colors::Blue);
auto workers = u->getUnitsInRadius(SATRUATION_RADIUS, (IsGatheringMinerals));
auto refineries = u->getUnitsInRadius(SATRUATION_RADIUS, (IsRefinery));
auto gasGeysers = u->getUnitsInRadius(SATRUATION_RADIUS);
auto mineralFields = u->getUnitsInRadius(SATRUATION_RADIUS, (IsMineralField));
Broodwar->drawTextMap(u->getPosition() + Position(0, 30), "%cWorkers: %d/%d", Text::White, workers.size(), 2*mineralFields.size());
}
}
#endif
// Prevent spamming by only running our onFrame once every number of latency frames.
// Latency frames are the number of frames before commands are processed.
if (Broodwar->getFrameCount() % Broodwar->getLatencyFrames() != 0)
return;
_supplyBeingMade = 0;
for (auto &u : Broodwar->self()->getUnits()) {
if (u->isConstructing() && u->getType().getRace().getSupplyProvider() == u->getType())
_supplyBeingMade += 8;
}
availableMinerals -= 100*_queuedSupply/8;
if (Broodwar->elapsedTime() - _timeLastQueuedSupply > 5) {
_queuedSupply = 0;
_timeLastQueuedSupply = Broodwar->elapsedTime();
}
_nSupplyOverhead = 2 + MAX((Broodwar->self()->supplyUsed() - 10) / 8, 0);
_wantedExtraSupply = (Broodwar->self()->supplyUsed() - (Broodwar->self()->supplyTotal() + _supplyBeingMade + _queuedSupply)) / 2 + _nSupplyOverhead;
_nBarracks = 0;
for (auto &u : Broodwar->self()->getUnits()) {
// If a cc is under construction
if (u->isConstructing() && u->getType() == u->getType().getRace().getCenter() && _isExpanding)
availableMinerals += 400;
// If a barracks is under construction
if (u->isConstructing() && u->getType() == UnitTypes::Terran_Barracks && _isBuildingBarracks)
availableMinerals += 150;
if (u->getType() == UnitTypes::Terran_Barracks) {
++_nBarracks;
}
}
if (_isExpanding) {
availableMinerals -= 400;
}
if (_isBuildingBarracks) {
availableMinerals -= 150;
}
int nWorkers = 0;
for (auto &u : Broodwar->getAllUnits()) {
if (u->getType() == u->getType().getRace().getWorker() && u->getPlayer() == Broodwar->self()) {
++nWorkers;
}
}
// Check if supply should be increased
if (_wantedExtraSupply > 0 && availableMinerals >= 100 && Broodwar->self()->supplyTotal() < 400) {
// Find unit to build our supply!
for (auto &unit : Broodwar->self()->getUnits()) {
if (unit->exists() && unit->isGatheringMinerals() && unit->isMoving() && !unit->isCarryingMinerals()) {
// We have found our candidate!
auto supplyType = unit->getType().getRace().getSupplyProvider();
auto buildPos = Broodwar->getBuildLocation(supplyType, unit->getTilePosition());
if (unit->build(supplyType, buildPos)) {
_queuedSupply += 8;
_timeLastQueuedSupply = Broodwar->elapsedTime();
break;
}
}
}
}
if (availableMinerals >= 150 && !_isBuildingBarracks && _nBarracks < 20) {
// Build barracks!
for (auto &u : Broodwar->self()->getUnits()) {
if (u->exists() && u->isGatheringMinerals() && u->isMoving() && !u->isCarryingMinerals()) {
auto buildingType = UnitTypes::Terran_Barracks;
auto buildingPos = Broodwar->getBuildLocation(buildingType, u->getTilePosition());
if (u->build(buildingType, buildingPos)) {
_isBuildingBarracks = true;
availableMinerals -= 150;
break;
}
}
}
}
/*if (!_isExpanding && availableMinerals >= 400){
// Expand!
for (auto &u : Broodwar->self()->getUnits()) {
if (u->exists() && u->isGatheringMinerals() && u->isMoving() && !u->isCarryingMinerals()) {
// Builder found!
auto buildingType = u->getType().getRace().getCenter();
auto buildPos = Broodwar->getBuildLocation(buildingType, u->getTilePosition());
if (u->build(buildingType, buildPos)) {
_isExpanding = true;
availableMinerals -= 400;
break;
}
}
}
}*/
// Iterate through all the units that we own
for (auto &u : Broodwar->self()->getUnits()) {
// Ignore the unit if it no longer exists
// Make sure to include this block when handling any Unit pointer!
if (!u->exists())
continue;
// Ignore the unit if it has one of the following status ailments
if (u->isLockedDown() || u->isMaelstrommed() || u->isStasised())
continue;
// Ignore the unit if it is in one of the following states
if (u->isLoaded() || !u->isPowered() || u->isStuck())
continue;
// Ignore the unit if it is incomplete or busy constructing
if (!u->isCompleted() || u->isConstructing())
continue;
// If the unit is a worker unit
if (u->getType().isWorker()) {
auto enemyUnit = u->getClosestUnit(IsEnemy && IsAttacking, WORKERAGGRORADIUS);
if (enemyUnit)
u->attack(enemyUnit);
// if our worker is idle
if (u->isIdle()) {
// Order workers carrying a resource to return them to the center,
// otherwise find a mineral patch to harvest.
if (u->isCarryingGas() || u->isCarryingMinerals())
u->returnCargo();
else if (!u->getPowerUp()) {
// Probably need to set up some better logic for this
auto preferredMiningLocation = u->getClosestUnit(IsMineralField);
u->gather(preferredMiningLocation);
}
}
} else if (u->getType().isResourceDepot()) {
auto nearbyGeysers = u->getUnitsInRadius(SATRUATION_RADIUS, (GetType == UnitTypes::Resource_Vespene_Geyser));
if (u->isIdle()) {
auto workers = u->getUnitsInRadius(SATRUATION_RADIUS, (IsGatheringMinerals));
if (nWorkers >= 70)
continue;
auto mineralFields = u->getUnitsInRadius(SATRUATION_RADIUS, (IsMineralField));
if (workers.size() < mineralFields.size() * 2 && availableMinerals >= 50) {
if (u->train(u->getType().getRace().getWorker())) {
Position pos = u->getPosition();
Error lastErr = Broodwar->getLastError();
Broodwar->registerEvent([pos, lastErr](Game*){ Broodwar->drawTextMap(pos + Position(0, -10), "%c%s", Text::Red, lastErr.c_str()); }, // action
nullptr, // condition
Broodwar->getLatencyFrames()); // frames to run
} else {
availableMinerals -= 50;
}
}
}
} else if (u->getType() == UnitTypes::Terran_Barracks) {
if (u->isIdle() && availableMinerals >= 50)
if (!u->train(UnitTypes::Terran_Marine))
availableMinerals -= 50;
} else if (u->getType() == UnitTypes::Terran_Marine && Broodwar->getFrameCount() % 20 == 0) {
auto enemyUnit = u->getClosestUnit(IsEnemy && IsAttacking);
if (enemyUnit) {
u->attack(enemyUnit->getPosition());
continue;
}
enemyUnit = u->getClosestUnit(IsEnemy);
if (enemyUnit) {
u->attack(enemyUnit->getPosition());
continue;
}
auto closestMarine = u->getClosestUnit(GetType == UnitTypes::Terran_Marine);
if (closestMarine) {
auto walk = u->getPosition() - closestMarine->getPosition();
u->move(u->getPosition() + walk);
}
}
}
}
void Neohuman::onSendText(std::string text) {
Broodwar->sendText("%s", text.c_str());
}
void Neohuman::onReceiveText(Player player, std::string text) {
Broodwar << player->getName() << " said \"" << text << "\"" << std::endl;
}
void Neohuman::onPlayerLeft(Player player) {
Broodwar->sendText("Goodbye %s!", player->getName().c_str());
}
void Neohuman::onNukeDetect(Position target) {
if (target) {
Broodwar << "Nuclear Launch Detected at " << target << std::endl;
} else {
Broodwar->sendText("Where's the nuke?");
}
// You can also retrieve all the nuclear missile targets using Broodwar->getNukeDots()!
}
void Neohuman::onUnitDiscover(Unit unit) {
}
void Neohuman::onUnitEvade(Unit unit) {
}
void Neohuman::onUnitShow(Unit unit) {
}
void Neohuman::onUnitHide(Unit unit) {
}
void Neohuman::onUnitCreate(Unit unit) {
}
void Neohuman::onUnitDestroy(Unit unit) {
}
void Neohuman::onUnitMorph(Unit unit) {
this->onUnitComplete(unit);
}
void Neohuman::onUnitRenegade(Unit unit){
}
void Neohuman::onSaveGame(std::string gameName){
}
void Neohuman::onUnitComplete(Unit unit){
if (unit->getType() == unit->getType().getRace().getCenter())
_isExpanding = false;
if (unit->getType() == UnitTypes::Terran_Barracks)
_isBuildingBarracks = false;
}
<|endoftext|>
|
<commit_before>#include <Servo.h>
#include <Arduino.h>
#include "PicoRobo.h"
//====================================================================================================================
//Parameter
//====================================================================================================================
#define SERV_NUM 4 //number of servo for array
#define FRAME 20 //interval time from current step to next step: 20msecc
int current_angle[SERV_NUM];
int target_angle[SERV_NUM+1];
float rotating_angle[SERV_NUM]; //rotating angle on each frame: calcurated by (target_angle - current_angle)/number of steps
int servo_trim[SERV_NUM]; //trim to adjust each servo motors's angle to center
Servo servo[SERV_NUM];
#define CENTER 4
#define RIGHT 5
#define LEFT 6
#define NECK 7
#define DELAY 50
//====================================================================================================================
//Servo Method
//====================================================================================================================
void PicoRobo::initServo(){
//attach pins to each servo
servo[0].attach(CENTER);
servo[1].attach(RIGHT);
servo[2].attach(LEFT);
servo[3].attach(NECK);
//set trim
int tmp_trim[SERV_NUM]={0,0,0,0}; //set trim to each servo
for(int i=0;i<SERV_NUM;i++){
servo_trim[i]=tmp_trim[i];
}
//rotate all servos to center position
setCenterToServo();
}
void PicoRobo::setCenterToServo(){
for(int i=0;i<SERV_NUM;i++){
servo[i].write(90 + servo_trim[i]);
current_angle[i] = 0;
target_angle[i] = 0;
}
}
//move to next position
void PicoRobo::moveToNextPosition(){
//check limit
for(int i=0;i<SERV_NUM;i++){
if(target_angle[i]>90){
target_angle[i]=90;
}else if(target_angle[i]<-90){
target_angle[i]=-90;
}
}
int numberOfStep = target_angle[SERV_NUM]/FRAME; //total number of steps to move to next position
for(int i=0;i<SERV_NUM;i++){
rotating_angle[i]=((float)target_angle[i]-(float)current_angle[i])/(float)numberOfStep;
}
int next_timing = millis() + FRAME;
int current_time;
float tmp_angle[SERV_NUM];
for(int i=0;i<SERV_NUM;i++){
tmp_angle[i]=(float)current_angle[i];
}
while(numberOfStep){
current_time=millis();
if(current_time>next_timing){
for(int i=0;i<SERV_NUM;i++){
tmp_angle[i] += rotating_angle[i];
current_angle[i] = (int)tmp_angle[i];
servo[i].write(current_angle[i]+servo_trim[i]+90);
}
next_timing = next_timing + FRAME;
numberOfStep--;
}
}
//adjust current_angle
for(int i=0;i<SERV_NUM;i++){
current_angle[i] = target_angle[i];
servo[i].write(current_angle[i]+servo_trim[i]+90);
}
}
//call moveToNextPosition() method continuously
void PicoRobo::playMotion(int motion[][SERV_NUM+1], int numberOfMotion){
for(int i=0;i<numberOfMotion;i++){
for(int j=0;j<SERV_NUM+1;j++){
target_angle[j]=motion[i][j];
}
moveToNextPosition();
}
}
<commit_msg>Introducing a seperate limit for every servo<commit_after>#include <Servo.h>
#include <Arduino.h>
#include "PicoRobo.h"
//====================================================================================================================
//Parameter
//====================================================================================================================
#define SERV_NUM 4 //number of servo for array
#define FRAME 20 //interval time from current step to next step: 20msecc
int current_angle[SERV_NUM];
int target_angle[SERV_NUM+1];
float rotating_angle[SERV_NUM]; //rotating angle on each frame: calcurated by (target_angle - current_angle)/number of steps
int servo_trim[SERV_NUM]; //trim to adjust each servo motors's angle to center
int servo_limit[SERV_NUM]; //limit to prevent each motor going to bad places
Servo servo[SERV_NUM];
#define CENTER 4
#define RIGHT 5
#define LEFT 6
#define NECK 7
#define DELAY 50
//====================================================================================================================
//Servo Method
//====================================================================================================================
void PicoRobo::initServo(){
//attach pins to each servo
servo[0].attach(CENTER);
servo[1].attach(RIGHT);
servo[2].attach(LEFT);
servo[3].attach(NECK);
//set trim
int tmp_trim[SERV_NUM]={0,-4,3,0}; //set trim to each servo
int tmp_limit[SERV_NUM]={40,15,15,75}; //set trim to each servo
for(int i=0;i<SERV_NUM;i++){
servo_trim[i]=tmp_trim[i];
servo_limit[i]=tmp_limit[i];
}
//rotate all servos to center position
setCenterToServo();
}
void PicoRobo::setCenterToServo(){
for(int i=0;i<SERV_NUM;i++){
servo[i].write(90 + servo_trim[i]);
current_angle[i] = 0;
target_angle[i] = 0;
}
}
//move to next position
void PicoRobo::moveToNextPosition(){
//check limit
for(int i=0;i<SERV_NUM;i++){
if(target_angle[i]>servo_limit[i]){
target_angle[i]=servo_limit[i];
}else if(target_angle[i]<-servo_limit[i]){
target_angle[i]=-servo_limit[i];
}
}
int numberOfStep = target_angle[SERV_NUM]/FRAME; //total number of steps to move to next position
for(int i=0;i<SERV_NUM;i++){
rotating_angle[i]=((float)target_angle[i]-(float)current_angle[i])/(float)numberOfStep;
}
int next_timing = millis() + FRAME;
int current_time;
float tmp_angle[SERV_NUM];
for(int i=0;i<SERV_NUM;i++){
tmp_angle[i]=(float)current_angle[i];
}
while(numberOfStep){
current_time=millis();
if(current_time>next_timing){
for(int i=0;i<SERV_NUM;i++){
tmp_angle[i] += rotating_angle[i];
current_angle[i] = (int)tmp_angle[i];
servo[i].write(current_angle[i]+servo_trim[i]+90);
}
next_timing = next_timing + FRAME;
numberOfStep--;
}
}
//adjust current_angle
for(int i=0;i<SERV_NUM;i++){
current_angle[i] = target_angle[i];
servo[i].write(current_angle[i]+servo_trim[i]+90);
}
}
//call moveToNextPosition() method continuously
void PicoRobo::playMotion(int motion[][SERV_NUM+1], int numberOfMotion){
for(int i=0;i<numberOfMotion;i++){
for(int j=0;j<SERV_NUM+1;j++){
target_angle[j]=motion[i][j];
}
moveToNextPosition();
}
}
<|endoftext|>
|
<commit_before>// Copyright (c) 2010 The Chromium Authors. All rights reserved.
// Use of this source code is governed by a BSD-style license that can be
// found in the LICENSE file.
#include "base/string_number_conversions.h"
#include "base/utf_string_conversions.h"
#include "chrome/browser/extensions/extension_browsertest.h"
#include "chrome/browser/extensions/extension_test_message_listener.h"
#include "chrome/browser/extensions/extension_webstore_private_api.h"
#include "chrome/browser/sync/profile_sync_service.h"
#include "chrome/common/chrome_switches.h"
#include "chrome/common/url_constants.h"
#include "chrome/test/ui_test_utils.h"
#include "googleurl/src/gurl.h"
#include "net/base/mock_host_resolver.h"
using chrome::kHttpScheme;
using chrome::kStandardSchemeSeparator;
namespace {
const char kTestUrlHostname[] = "www.example.com";
} // namespace
// A fake version of ProfileSyncService used for testing.
class FakeProfileSyncService : public ProfileSyncService {
public:
// The |username_after_login| parameter determines what this fake
// ProfileSyncService will set the username to when ShowLoginDialog is called.
FakeProfileSyncService(const std::string& initial_username,
const std::string& username_after_login) :
username_(ASCIIToUTF16(initial_username)),
username_after_login_(username_after_login),
observer_(NULL) {}
virtual ~FakeProfileSyncService() {
EXPECT_TRUE(observer_ == NULL);
}
// Overrides of virtual methods in ProfileSyncService.
virtual string16 GetAuthenticatedUsername() const {
return username_;
}
virtual void ShowLoginDialog(gfx::NativeWindow) {
EXPECT_TRUE(observer_ != NULL);
username_ = ASCIIToUTF16(username_after_login_);
observer_->OnStateChanged();
}
virtual bool SetupInProgress() const {
return false;
}
virtual void AddObserver(ProfileSyncServiceObserver* observer) {
EXPECT_TRUE(observer_ == NULL);
observer_ = observer;
}
virtual void RemoveObserver(ProfileSyncServiceObserver* observer) {
EXPECT_TRUE(observer == observer_);
observer_ = NULL;
}
private:
string16 username_;
std::string username_after_login_;
ProfileSyncServiceObserver* observer_;
};
class ExtensionWebstorePrivateBrowserTest : public ExtensionBrowserTest {
public:
ExtensionWebstorePrivateBrowserTest() {
test_url_base_ = std::string() + kHttpScheme + kStandardSchemeSeparator +
kTestUrlHostname;
}
void SetUpCommandLine(CommandLine* command_line) {
ExtensionBrowserTest::SetUpCommandLine(command_line);
command_line->AppendSwitchASCII(switches::kAppsGalleryURL, test_url_base_);
}
// This generates a regular test server url pointing to a test file at
// |relative_path|, but replaces the hostname with kTestUrlHostname so that
// we get the webstore private APIs injected (this happens because of the
// command line switch we added in SetupCommandLine).
GURL GetUrl(const std::string& relative_path) {
GURL base_url = test_server()->GetURL(
"files/extensions/webstore_private/" + relative_path);
GURL::Replacements replacements;
std::string replacement_host = std::string(kTestUrlHostname);
replacements.SetHostStr(replacement_host);
return base_url.ReplaceComponents(replacements);
}
void RunLoginTest(const std::string& relative_path,
const std::string& initial_login,
const std::string& login_result) {
FakeProfileSyncService sync_service(initial_login, login_result);
WebstorePrivateApi::SetTestingProfileSyncService(&sync_service);
ExtensionTestMessageListener listener("success", false);
GURL url = GetUrl(relative_path);
ui_test_utils::NavigateToURL(browser(), url);
EXPECT_TRUE(listener.WaitUntilSatisfied());
WebstorePrivateApi::SetTestingProfileSyncService(NULL);
}
protected:
std::string test_url_base_;
};
IN_PROC_BROWSER_TEST_F(ExtensionWebstorePrivateBrowserTest, BrowserLogin) {
host_resolver()->AddRule(kTestUrlHostname, "127.0.0.1");
ASSERT_TRUE(test_server()->Start());
RunLoginTest("browser_login/expect_nonempty.html", "foo@bar.com", "");
RunLoginTest("browser_login/prompt_no_preferred.html", "", "");
RunLoginTest("browser_login/prompt_preferred.html", "", "foo@bar.com");
RunLoginTest("browser_login/prompt_already_logged_in_error.html",
"foo@bar.com",
"foo@bar.com");
}
<commit_msg>Disable failing test while I investigate it.<commit_after>// Copyright (c) 2010 The Chromium Authors. All rights reserved.
// Use of this source code is governed by a BSD-style license that can be
// found in the LICENSE file.
#include "base/string_number_conversions.h"
#include "base/utf_string_conversions.h"
#include "chrome/browser/extensions/extension_browsertest.h"
#include "chrome/browser/extensions/extension_test_message_listener.h"
#include "chrome/browser/extensions/extension_webstore_private_api.h"
#include "chrome/browser/sync/profile_sync_service.h"
#include "chrome/common/chrome_switches.h"
#include "chrome/common/url_constants.h"
#include "chrome/test/ui_test_utils.h"
#include "googleurl/src/gurl.h"
#include "net/base/mock_host_resolver.h"
using chrome::kHttpScheme;
using chrome::kStandardSchemeSeparator;
namespace {
const char kTestUrlHostname[] = "www.example.com";
} // namespace
// A fake version of ProfileSyncService used for testing.
class FakeProfileSyncService : public ProfileSyncService {
public:
// The |username_after_login| parameter determines what this fake
// ProfileSyncService will set the username to when ShowLoginDialog is called.
FakeProfileSyncService(const std::string& initial_username,
const std::string& username_after_login) :
username_(ASCIIToUTF16(initial_username)),
username_after_login_(username_after_login),
observer_(NULL) {}
virtual ~FakeProfileSyncService() {
EXPECT_TRUE(observer_ == NULL);
}
// Overrides of virtual methods in ProfileSyncService.
virtual string16 GetAuthenticatedUsername() const {
return username_;
}
virtual void ShowLoginDialog(gfx::NativeWindow) {
EXPECT_TRUE(observer_ != NULL);
username_ = ASCIIToUTF16(username_after_login_);
observer_->OnStateChanged();
}
virtual bool SetupInProgress() const {
return false;
}
virtual void AddObserver(ProfileSyncServiceObserver* observer) {
EXPECT_TRUE(observer_ == NULL);
observer_ = observer;
}
virtual void RemoveObserver(ProfileSyncServiceObserver* observer) {
EXPECT_TRUE(observer == observer_);
observer_ = NULL;
}
private:
string16 username_;
std::string username_after_login_;
ProfileSyncServiceObserver* observer_;
};
class ExtensionWebstorePrivateBrowserTest : public ExtensionBrowserTest {
public:
ExtensionWebstorePrivateBrowserTest() {
test_url_base_ = std::string() + kHttpScheme + kStandardSchemeSeparator +
kTestUrlHostname;
}
void SetUpCommandLine(CommandLine* command_line) {
ExtensionBrowserTest::SetUpCommandLine(command_line);
command_line->AppendSwitchASCII(switches::kAppsGalleryURL, test_url_base_);
}
// This generates a regular test server url pointing to a test file at
// |relative_path|, but replaces the hostname with kTestUrlHostname so that
// we get the webstore private APIs injected (this happens because of the
// command line switch we added in SetupCommandLine).
GURL GetUrl(const std::string& relative_path) {
GURL base_url = test_server()->GetURL(
"files/extensions/webstore_private/" + relative_path);
GURL::Replacements replacements;
std::string replacement_host = std::string(kTestUrlHostname);
replacements.SetHostStr(replacement_host);
return base_url.ReplaceComponents(replacements);
}
void RunLoginTest(const std::string& relative_path,
const std::string& initial_login,
const std::string& login_result) {
FakeProfileSyncService sync_service(initial_login, login_result);
WebstorePrivateApi::SetTestingProfileSyncService(&sync_service);
ExtensionTestMessageListener listener("success", false);
GURL url = GetUrl(relative_path);
ui_test_utils::NavigateToURL(browser(), url);
EXPECT_TRUE(listener.WaitUntilSatisfied());
WebstorePrivateApi::SetTestingProfileSyncService(NULL);
}
protected:
std::string test_url_base_;
};
IN_PROC_BROWSER_TEST_F(ExtensionWebstorePrivateBrowserTest,
FAILS_BrowserLogin) {
host_resolver()->AddRule(kTestUrlHostname, "127.0.0.1");
ASSERT_TRUE(test_server()->Start());
RunLoginTest("browser_login/expect_nonempty.html", "foo@bar.com", "");
RunLoginTest("browser_login/prompt_no_preferred.html", "", "");
RunLoginTest("browser_login/prompt_preferred.html", "", "foo@bar.com");
RunLoginTest("browser_login/prompt_already_logged_in_error.html",
"foo@bar.com",
"foo@bar.com");
}
<|endoftext|>
|
<commit_before>/* -------------------------------------------------------------------------- *
* OpenSim: toyLeg_example.cpp *
* -------------------------------------------------------------------------- *
* The OpenSim API is a toolkit for musculoskeletal modeling and simulation. *
* See http://opensim.stanford.edu and the NOTICE file for more information. *
* OpenSim is developed at Stanford University and supported by the US *
* National Institutes of Health (U54 GM072970, R24 HD065690) and by DARPA *
* through the Warrior Web program. *
* *
* Copyright (c) 2005-2012 Stanford University and the Authors *
* Author(s): Matt S. DeMers *
* *
* Licensed under the Apache License, Version 2.0 (the "License"); you may *
* not use this file except in compliance with the License. You may obtain a *
* copy of the License at http://www.apache.org/licenses/LICENSE-2.0. *
* *
* Unless required by applicable law or agreed to in writing, software *
* distributed under the License is distributed on an "AS IS" BASIS, *
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. *
* See the License for the specific language governing permissions and *
* limitations under the License. *
* -------------------------------------------------------------------------- */
/*
* Below is an example of an OpenSim application that provides its own
* main() routine. This application acts as an example for utilizing the
* ControllabeSpring actuator.
*/
// Author: Matt DeMers
//==============================================================================
//==============================================================================
#include "PistonActuator.h"
#include "ControllableSpring.h"
#include <OpenSim/OpenSim.h>
using namespace OpenSim;
using namespace SimTK;
//______________________________________________________________________________
/**
* Run a simulation of block sliding with contact on by two muscles sliding with contact
*/
int main()
{
try {
// Create a new OpenSim model
Model osimModel;
osimModel.setName("osimModel");
osimModel.setAuthors("Matt DeMers");
double Pi = SimTK::Pi;
// Get the ground body
Ground& ground = osimModel.updGround();
ground.addMeshGeometry("checkered_floor.vtp");
// create linkage body
double linkageMass = 0.001, linkageLength = 0.5, linkageDiameter = 0.06;
Vec3 linkageDimensions(linkageDiameter, linkageLength, linkageDiameter);
Vec3 linkageMassCenter(0,linkageLength/2,0);
Inertia linkageInertia = Inertia::cylinderAlongY(linkageDiameter/2.0, linkageLength/2.0);
OpenSim::Body* linkage1 = new OpenSim::Body("linkage1", linkageMass, linkageMassCenter, linkageMass*linkageInertia);
// Graphical representation
Cylinder cyl;
//This cylinder.vtp geometry is 1 meter tall, 1 meter diameter. Scale and shift it to look pretty
cyl.set_scale_factors(linkageDimensions);
Frame* cyl1Frame = new PhysicalOffsetFrame(*linkage1, Transform(Vec3(0.0, linkageLength / 2.0, 0.0)));
cyl1Frame->setName("Cyl1_frame");
osimModel.addFrame(cyl1Frame);
cyl.setFrameName("Cyl1_frame");
linkage1->addGeometry(cyl);
Sphere sphere(0.1);
linkage1->addGeometry(sphere);
//This sphere.vtp is 1 meter in diameter. Scale it.
// Creat a second linkage body
OpenSim::Body* linkage2 = new OpenSim::Body(*linkage1);
linkage2->setName("linkage2");
Frame* cyl2Frame = new PhysicalOffsetFrame(*linkage2, Transform(Vec3(0.0, linkageLength / 2.0, 0.0)));
cyl2Frame->setName("Cyl2_frame");
osimModel.addFrame(cyl2Frame);
(linkage2->upd_GeometrySet(0)).setFrameName("Cyl2_frame");
// Creat a block to be the pelvis
double blockMass = 20.0, blockSideLength = 0.2;
Vec3 blockMassCenter(0);
Inertia blockInertia = blockMass*Inertia::brick(blockSideLength, blockSideLength, blockSideLength);
OpenSim::Body *block = new OpenSim::Body("block", blockMass, blockMassCenter, blockInertia);
Brick brick(SimTK::Vec3(0.05, 0.05, 0.05));
block->addGeometry(brick);
//This block.vtp is 0.1x0.1x0.1 meters. scale its appearance
//block->updDisplayer()->updGeometrySet()[0].setScaleFactors(Vec3(2.0));
// Create 1 degree-of-freedom pin joints between the bodies to creat a kinematic chain from ground through the block
Vec3 orientationInGround(0), locationInGround(0), locationInParent(0.0, linkageLength, 0.0), orientationInChild(0), locationInChild(0);
PinJoint *ankle = new PinJoint("ankle", ground, locationInGround, orientationInGround, *linkage1,
locationInChild, orientationInChild);
PinJoint *knee = new PinJoint("knee", *linkage1, locationInParent, orientationInChild, *linkage2,
locationInChild, orientationInChild);
PinJoint *hip = new PinJoint("hip", *linkage2, locationInParent, orientationInChild, *block,
locationInChild, orientationInChild);
double range[2] = {-SimTK::Pi*2, SimTK::Pi*2};
CoordinateSet& ankleCoordinateSet = ankle->upd_CoordinateSet();
ankleCoordinateSet[0].setName("q1");
ankleCoordinateSet[0].setRange(range);
CoordinateSet& kneeCoordinateSet = knee->upd_CoordinateSet();
kneeCoordinateSet[0].setName("q2");
kneeCoordinateSet[0].setRange(range);
CoordinateSet& hipCoordinateSet = hip->upd_CoordinateSet();
hipCoordinateSet[0].setName("q3");
hipCoordinateSet[0].setRange(range);
// Add the bodies to the model
osimModel.addBody(linkage1);
osimModel.addBody(linkage2);
osimModel.addBody(block);
// Add the joints to the model
osimModel.addJoint(ankle);
osimModel.addJoint(knee);
osimModel.addJoint(hip);
// Define contraints on the model
// Add a point on line constraint to limit the block to vertical motion
Vec3 lineDirection(0,1,0), pointOnLine(0,0,0), pointOnBlock(0);
PointOnLineConstraint *lineConstraint = new PointOnLineConstraint(ground, lineDirection, pointOnLine, *block, pointOnBlock);
osimModel.addConstraint(lineConstraint);
// Add PistonActuator between the first linkage and the block
Vec3 pointOnBodies(0);
PistonActuator *piston = new PistonActuator();
piston->setName("piston");
piston->setBodyA(linkage1);
piston->setBodyB(block);
piston->setPointA(pointOnBodies);
piston->setPointB(pointOnBodies);
piston->setOptimalForce(200.0);
piston->setPointsAreGlobal(false);
osimModel.addForce(piston);
//+++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++
// Added ControllableSpring between the first linkage and the second block
//+++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++
ControllableSpring *spring = new ControllableSpring;
spring->setName("spring");
spring->setBodyA(block);
spring->setBodyB(linkage1);
spring->setPointA(pointOnBodies);
spring->setPointB(pointOnBodies);
spring->setOptimalForce(2000.0);
spring->setPointsAreGlobal(false);
spring->setRestLength(0.8);
osimModel.addForce(spring);
// define the simulation times
double t0(0.0), tf(15);
// create a controller to control the piston and spring actuators
// the prescribed controller sets the controls as functions of time
PrescribedController *legController = new PrescribedController();
// give the legController control over all (two) model actuators
legController->setActuators(osimModel.updActuators());
// specify some control nodes for spring stiffness control
double t[] = {0.0, 4.0, 7.0, 10.0, 15.0};
double x[] = {1.0, 1.0, 0.25, 0.25, 5.0};
// specify the control function for each actuator
legController->prescribeControlForActuator("piston", new Constant(0.1));
legController->prescribeControlForActuator("spring", new PiecewiseLinearFunction(5, t, x));
// add the controller to the model
osimModel.addController(legController);
// define the acceration due to gravity
osimModel.setGravity(Vec3(0, -9.80665, 0));
// enable the model visualizer see the model in action, which can be
// useful for debugging
osimModel.setUseVisualizer(false);
// Initialize system
SimTK::State& si = osimModel.initSystem();
// Pin joint initial states
double q1_i = -Pi/4;
double q2_i = - 2*q1_i;
CoordinateSet &coordinates = osimModel.updCoordinateSet();
coordinates[0].setValue(si, q1_i, true);
coordinates[1].setValue(si,q2_i, true);
// Setup integrator and manager
SimTK::RungeKuttaMersonIntegrator integrator(osimModel.getMultibodySystem());
integrator.setAccuracy(1.0e-3);
ForceReporter *forces = new ForceReporter(&osimModel);
osimModel.updAnalysisSet().adoptAndAppend(forces);
Manager manager(osimModel, integrator);
//Examine the model
osimModel.printDetailedInfo(si, std::cout);
// Save the model
osimModel.print("toyLeg.osim");
// Print out the initial position and velocity states
si.getQ().dump("Initial q's");
si.getU().dump("Initial u's");
std::cout << "Initial time: " << si.getTime() << std::endl;
osimModel.dumpPathName();
// Integrate
manager.setInitialTime(t0);
manager.setFinalTime(tf);
std::cout<<"\n\nIntegrating from " << t0 << " to " << tf << std::endl;
manager.integrate(si);
// Save results
osimModel.printControlStorage("SpringActuatedLeg_controls.sto");
Storage statesDegrees(manager.getStateStorage());
osimModel.updSimbodyEngine().convertRadiansToDegrees(statesDegrees);
//statesDegrees.print("PistonActuatedLeg_states_degrees.mot");
statesDegrees.print("SpringActuatedLeg_states_degrees.mot");
forces->getForceStorage().print("actuator_forces.mot");
}
catch (const std::exception& ex)
{
std::cout << "Exception in toyLeg_example: " << ex.what() << std::endl;
return 1;
}
std::cout << "Done." << std::endl;
return 0;
}
<commit_msg>Remove references in comments to sphere.vtp, block.vtp and cylinder.vtp as they're replaced with Geometry primitives Sphere, Brick and Cylinder.<commit_after>/* -------------------------------------------------------------------------- *
* OpenSim: toyLeg_example.cpp *
* -------------------------------------------------------------------------- *
* The OpenSim API is a toolkit for musculoskeletal modeling and simulation. *
* See http://opensim.stanford.edu and the NOTICE file for more information. *
* OpenSim is developed at Stanford University and supported by the US *
* National Institutes of Health (U54 GM072970, R24 HD065690) and by DARPA *
* through the Warrior Web program. *
* *
* Copyright (c) 2005-2012 Stanford University and the Authors *
* Author(s): Matt S. DeMers *
* *
* Licensed under the Apache License, Version 2.0 (the "License"); you may *
* not use this file except in compliance with the License. You may obtain a *
* copy of the License at http://www.apache.org/licenses/LICENSE-2.0. *
* *
* Unless required by applicable law or agreed to in writing, software *
* distributed under the License is distributed on an "AS IS" BASIS, *
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. *
* See the License for the specific language governing permissions and *
* limitations under the License. *
* -------------------------------------------------------------------------- */
/*
* Below is an example of an OpenSim application that provides its own
* main() routine. This application acts as an example for utilizing the
* ControllabeSpring actuator.
*/
// Author: Matt DeMers
//==============================================================================
//==============================================================================
#include "PistonActuator.h"
#include "ControllableSpring.h"
#include <OpenSim/OpenSim.h>
using namespace OpenSim;
using namespace SimTK;
//______________________________________________________________________________
/**
* Run a simulation of block sliding with contact on by two muscles sliding with contact
*/
int main()
{
try {
// Create a new OpenSim model
Model osimModel;
osimModel.setName("osimModel");
osimModel.setAuthors("Matt DeMers");
double Pi = SimTK::Pi;
// Get the ground body
Ground& ground = osimModel.updGround();
ground.addMeshGeometry("checkered_floor.vtp");
// create linkage body
double linkageMass = 0.001, linkageLength = 0.5, linkageDiameter = 0.06;
Vec3 linkageDimensions(linkageDiameter, linkageLength, linkageDiameter);
Vec3 linkageMassCenter(0,linkageLength/2,0);
Inertia linkageInertia = Inertia::cylinderAlongY(linkageDiameter/2.0, linkageLength/2.0);
OpenSim::Body* linkage1 = new OpenSim::Body("linkage1", linkageMass, linkageMassCenter, linkageMass*linkageInertia);
// Graphical representation
Cylinder cyl;
cyl.set_scale_factors(linkageDimensions);
Frame* cyl1Frame = new PhysicalOffsetFrame(*linkage1, Transform(Vec3(0.0, linkageLength / 2.0, 0.0)));
cyl1Frame->setName("Cyl1_frame");
osimModel.addFrame(cyl1Frame);
cyl.setFrameName("Cyl1_frame");
linkage1->addGeometry(cyl);
Sphere sphere(0.1);
linkage1->addGeometry(sphere);
// Creat a second linkage body
OpenSim::Body* linkage2 = new OpenSim::Body(*linkage1);
linkage2->setName("linkage2");
Frame* cyl2Frame = new PhysicalOffsetFrame(*linkage2, Transform(Vec3(0.0, linkageLength / 2.0, 0.0)));
cyl2Frame->setName("Cyl2_frame");
osimModel.addFrame(cyl2Frame);
(linkage2->upd_GeometrySet(0)).setFrameName("Cyl2_frame");
// Creat a block to be the pelvis
double blockMass = 20.0, blockSideLength = 0.2;
Vec3 blockMassCenter(0);
Inertia blockInertia = blockMass*Inertia::brick(blockSideLength, blockSideLength, blockSideLength);
OpenSim::Body *block = new OpenSim::Body("block", blockMass, blockMassCenter, blockInertia);
Brick brick(SimTK::Vec3(0.05, 0.05, 0.05));
block->addGeometry(brick);
// Create 1 degree-of-freedom pin joints between the bodies to creat a kinematic chain from ground through the block
Vec3 orientationInGround(0), locationInGround(0), locationInParent(0.0, linkageLength, 0.0), orientationInChild(0), locationInChild(0);
PinJoint *ankle = new PinJoint("ankle", ground, locationInGround, orientationInGround, *linkage1,
locationInChild, orientationInChild);
PinJoint *knee = new PinJoint("knee", *linkage1, locationInParent, orientationInChild, *linkage2,
locationInChild, orientationInChild);
PinJoint *hip = new PinJoint("hip", *linkage2, locationInParent, orientationInChild, *block,
locationInChild, orientationInChild);
double range[2] = {-SimTK::Pi*2, SimTK::Pi*2};
CoordinateSet& ankleCoordinateSet = ankle->upd_CoordinateSet();
ankleCoordinateSet[0].setName("q1");
ankleCoordinateSet[0].setRange(range);
CoordinateSet& kneeCoordinateSet = knee->upd_CoordinateSet();
kneeCoordinateSet[0].setName("q2");
kneeCoordinateSet[0].setRange(range);
CoordinateSet& hipCoordinateSet = hip->upd_CoordinateSet();
hipCoordinateSet[0].setName("q3");
hipCoordinateSet[0].setRange(range);
// Add the bodies to the model
osimModel.addBody(linkage1);
osimModel.addBody(linkage2);
osimModel.addBody(block);
// Add the joints to the model
osimModel.addJoint(ankle);
osimModel.addJoint(knee);
osimModel.addJoint(hip);
// Define contraints on the model
// Add a point on line constraint to limit the block to vertical motion
Vec3 lineDirection(0,1,0), pointOnLine(0,0,0), pointOnBlock(0);
PointOnLineConstraint *lineConstraint = new PointOnLineConstraint(ground, lineDirection, pointOnLine, *block, pointOnBlock);
osimModel.addConstraint(lineConstraint);
// Add PistonActuator between the first linkage and the block
Vec3 pointOnBodies(0);
PistonActuator *piston = new PistonActuator();
piston->setName("piston");
piston->setBodyA(linkage1);
piston->setBodyB(block);
piston->setPointA(pointOnBodies);
piston->setPointB(pointOnBodies);
piston->setOptimalForce(200.0);
piston->setPointsAreGlobal(false);
osimModel.addForce(piston);
//+++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++
// Added ControllableSpring between the first linkage and the second block
//+++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++
ControllableSpring *spring = new ControllableSpring;
spring->setName("spring");
spring->setBodyA(block);
spring->setBodyB(linkage1);
spring->setPointA(pointOnBodies);
spring->setPointB(pointOnBodies);
spring->setOptimalForce(2000.0);
spring->setPointsAreGlobal(false);
spring->setRestLength(0.8);
osimModel.addForce(spring);
// define the simulation times
double t0(0.0), tf(15);
// create a controller to control the piston and spring actuators
// the prescribed controller sets the controls as functions of time
PrescribedController *legController = new PrescribedController();
// give the legController control over all (two) model actuators
legController->setActuators(osimModel.updActuators());
// specify some control nodes for spring stiffness control
double t[] = {0.0, 4.0, 7.0, 10.0, 15.0};
double x[] = {1.0, 1.0, 0.25, 0.25, 5.0};
// specify the control function for each actuator
legController->prescribeControlForActuator("piston", new Constant(0.1));
legController->prescribeControlForActuator("spring", new PiecewiseLinearFunction(5, t, x));
// add the controller to the model
osimModel.addController(legController);
// define the acceration due to gravity
osimModel.setGravity(Vec3(0, -9.80665, 0));
// enable the model visualizer see the model in action, which can be
// useful for debugging
osimModel.setUseVisualizer(false);
// Initialize system
SimTK::State& si = osimModel.initSystem();
// Pin joint initial states
double q1_i = -Pi/4;
double q2_i = - 2*q1_i;
CoordinateSet &coordinates = osimModel.updCoordinateSet();
coordinates[0].setValue(si, q1_i, true);
coordinates[1].setValue(si,q2_i, true);
// Setup integrator and manager
SimTK::RungeKuttaMersonIntegrator integrator(osimModel.getMultibodySystem());
integrator.setAccuracy(1.0e-3);
ForceReporter *forces = new ForceReporter(&osimModel);
osimModel.updAnalysisSet().adoptAndAppend(forces);
Manager manager(osimModel, integrator);
//Examine the model
osimModel.printDetailedInfo(si, std::cout);
// Save the model
osimModel.print("toyLeg.osim");
// Print out the initial position and velocity states
si.getQ().dump("Initial q's");
si.getU().dump("Initial u's");
std::cout << "Initial time: " << si.getTime() << std::endl;
osimModel.dumpPathName();
// Integrate
manager.setInitialTime(t0);
manager.setFinalTime(tf);
std::cout<<"\n\nIntegrating from " << t0 << " to " << tf << std::endl;
manager.integrate(si);
// Save results
osimModel.printControlStorage("SpringActuatedLeg_controls.sto");
Storage statesDegrees(manager.getStateStorage());
osimModel.updSimbodyEngine().convertRadiansToDegrees(statesDegrees);
//statesDegrees.print("PistonActuatedLeg_states_degrees.mot");
statesDegrees.print("SpringActuatedLeg_states_degrees.mot");
forces->getForceStorage().print("actuator_forces.mot");
}
catch (const std::exception& ex)
{
std::cout << "Exception in toyLeg_example: " << ex.what() << std::endl;
return 1;
}
std::cout << "Done." << std::endl;
return 0;
}
<|endoftext|>
|
<commit_before>/***********************************************************************
filename: CEGUIXMLAttributes.cpp
created: Sat Mar 12 2005
author: Paul D Turner
*************************************************************************/
/***************************************************************************
* Copyright (C) 2004 - 2006 Paul D Turner & The CEGUI Development Team
*
* Permission is hereby granted, free of charge, to any person obtaining
* a copy of this software and associated documentation files (the
* "Software"), to deal in the Software without restriction, including
* without limitation the rights to use, copy, modify, merge, publish,
* distribute, sublicense, and/or sell copies of the Software, and to
* permit persons to whom the Software is furnished to do so, subject to
* the following conditions:
*
* The above copyright notice and this permission notice shall be
* included in all copies or substantial portions of the Software.
*
* THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND,
* EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF
* MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT.
* IN NO EVENT SHALL THE AUTHORS BE LIABLE FOR ANY CLAIM, DAMAGES OR
* OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE,
* ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR
* OTHER DEALINGS IN THE SOFTWARE.
***************************************************************************/
#include "CEGUI/XMLAttributes.h"
#include "CEGUI/Exceptions.h"
#include <sstream>
#include <iterator>
// Start of CEGUI namespace section
namespace CEGUI
{
XMLAttributes::XMLAttributes(void)
{}
XMLAttributes::~XMLAttributes(void)
{}
void XMLAttributes::add(const String& attrName, const String& attrValue)
{
d_attrs[attrName] = attrValue;
}
void XMLAttributes::remove(const String& attrName)
{
AttributeMap::iterator pos = d_attrs.find(attrName);
if (pos != d_attrs.end())
d_attrs.erase(pos);
}
bool XMLAttributes::exists(const String& attrName) const
{
return d_attrs.find(attrName) != d_attrs.end();
}
size_t XMLAttributes::getCount(void) const
{
return d_attrs.size();
}
const String& XMLAttributes::getName(size_t index) const
{
if (index >= d_attrs.size())
{
CEGUI_THROW(InvalidRequestException("XMLAttributes::getName - The specified index is out of range for this XMLAttributes block."));
}
AttributeMap::const_iterator iter = d_attrs.begin();
std::advance(iter, index);
return (*iter).first;
}
const String& XMLAttributes::getValue(size_t index) const
{
if (index >= d_attrs.size())
{
CEGUI_THROW(InvalidRequestException("XMLAttributes::getValue - The specified index is out of range for this XMLAttributes block."));
}
AttributeMap::const_iterator iter = d_attrs.begin();
std::advance(iter, index);
return (*iter).second;
}
const String& XMLAttributes::getValue(const String& attrName) const
{
AttributeMap::const_iterator pos = d_attrs.find(attrName);
if (pos != d_attrs.end())
{
return (*pos).second;
}
else
{
CEGUI_THROW(UnknownObjectException("XMLAttributes::getValue - no value exists for an attribute named '" + attrName + "'."));
}
}
const String& XMLAttributes::getValueAsString(const String& attrName, const String& def) const
{
return (exists(attrName)) ? getValue(attrName) : def;
}
bool XMLAttributes::getValueAsBool(const String& attrName, bool def) const
{
if (!exists(attrName))
{
return def;
}
const String& val = getValue(attrName);
if (val == "false" || val == "0")
{
return false;
}
else if (val == "true" || val == "1")
{
return true;
}
else
{
CEGUI_THROW(InvalidRequestException("XMLAttributes::getValueAsInteger - failed to convert attribute '" + attrName + "' with value '" + getValue(attrName) + "' to bool."));
}
}
int XMLAttributes::getValueAsInteger(const String& attrName, int def) const
{
if (!exists(attrName))
{
return def;
}
int val;
std::istringstream strm(getValue(attrName).c_str());
strm >> val;
// success?
if (strm.fail())
{
CEGUI_THROW(InvalidRequestException("XMLAttributes::getValueAsInteger - failed to convert attribute '" + attrName + "' with value '" + getValue(attrName) + "' to integer."));
}
return val;
}
float XMLAttributes::getValueAsFloat(const String& attrName, float def) const
{
if (!exists(attrName))
{
return def;
}
float val;
std::istringstream strm(getValue(attrName).c_str());
strm >> val;
// success?
if (strm.fail())
{
CEGUI_THROW(InvalidRequestException("XMLAttributes::getValueAsInteger - failed to convert attribute '" + attrName + "' with value '" + getValue(attrName) + "' to float."));
}
return val;
}
} // End of CEGUI namespace section
<commit_msg>Interpret False and True as boolean values when loading XML<commit_after>/***********************************************************************
filename: CEGUIXMLAttributes.cpp
created: Sat Mar 12 2005
author: Paul D Turner
*************************************************************************/
/***************************************************************************
* Copyright (C) 2004 - 2006 Paul D Turner & The CEGUI Development Team
*
* Permission is hereby granted, free of charge, to any person obtaining
* a copy of this software and associated documentation files (the
* "Software"), to deal in the Software without restriction, including
* without limitation the rights to use, copy, modify, merge, publish,
* distribute, sublicense, and/or sell copies of the Software, and to
* permit persons to whom the Software is furnished to do so, subject to
* the following conditions:
*
* The above copyright notice and this permission notice shall be
* included in all copies or substantial portions of the Software.
*
* THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND,
* EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF
* MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT.
* IN NO EVENT SHALL THE AUTHORS BE LIABLE FOR ANY CLAIM, DAMAGES OR
* OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE,
* ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR
* OTHER DEALINGS IN THE SOFTWARE.
***************************************************************************/
#include "CEGUI/XMLAttributes.h"
#include "CEGUI/Exceptions.h"
#include <sstream>
#include <iterator>
// Start of CEGUI namespace section
namespace CEGUI
{
XMLAttributes::XMLAttributes(void)
{}
XMLAttributes::~XMLAttributes(void)
{}
void XMLAttributes::add(const String& attrName, const String& attrValue)
{
d_attrs[attrName] = attrValue;
}
void XMLAttributes::remove(const String& attrName)
{
AttributeMap::iterator pos = d_attrs.find(attrName);
if (pos != d_attrs.end())
d_attrs.erase(pos);
}
bool XMLAttributes::exists(const String& attrName) const
{
return d_attrs.find(attrName) != d_attrs.end();
}
size_t XMLAttributes::getCount(void) const
{
return d_attrs.size();
}
const String& XMLAttributes::getName(size_t index) const
{
if (index >= d_attrs.size())
{
CEGUI_THROW(InvalidRequestException("XMLAttributes::getName - The specified index is out of range for this XMLAttributes block."));
}
AttributeMap::const_iterator iter = d_attrs.begin();
std::advance(iter, index);
return (*iter).first;
}
const String& XMLAttributes::getValue(size_t index) const
{
if (index >= d_attrs.size())
{
CEGUI_THROW(InvalidRequestException("XMLAttributes::getValue - The specified index is out of range for this XMLAttributes block."));
}
AttributeMap::const_iterator iter = d_attrs.begin();
std::advance(iter, index);
return (*iter).second;
}
const String& XMLAttributes::getValue(const String& attrName) const
{
AttributeMap::const_iterator pos = d_attrs.find(attrName);
if (pos != d_attrs.end())
{
return (*pos).second;
}
else
{
CEGUI_THROW(UnknownObjectException("XMLAttributes::getValue - no value exists for an attribute named '" + attrName + "'."));
}
}
const String& XMLAttributes::getValueAsString(const String& attrName, const String& def) const
{
return (exists(attrName)) ? getValue(attrName) : def;
}
bool XMLAttributes::getValueAsBool(const String& attrName, bool def) const
{
if (!exists(attrName))
{
return def;
}
const String& val = getValue(attrName);
if (val == "false" || val == "False" || val == "0")
{
return false;
}
else if (val == "true" || val == "True" || val == "1")
{
return true;
}
else
{
CEGUI_THROW(InvalidRequestException("XMLAttributes::getValueAsBool - failed to convert attribute '" + attrName + "' with value '" + getValue(attrName) + "' to bool."));
}
}
int XMLAttributes::getValueAsInteger(const String& attrName, int def) const
{
if (!exists(attrName))
{
return def;
}
int val;
std::istringstream strm(getValue(attrName).c_str());
strm >> val;
// success?
if (strm.fail())
{
CEGUI_THROW(InvalidRequestException("XMLAttributes::getValueAsInteger - failed to convert attribute '" + attrName + "' with value '" + getValue(attrName) + "' to integer."));
}
return val;
}
float XMLAttributes::getValueAsFloat(const String& attrName, float def) const
{
if (!exists(attrName))
{
return def;
}
float val;
std::istringstream strm(getValue(attrName).c_str());
strm >> val;
// success?
if (strm.fail())
{
CEGUI_THROW(InvalidRequestException("XMLAttributes::getValueAsInteger - failed to convert attribute '" + attrName + "' with value '" + getValue(attrName) + "' to float."));
}
return val;
}
} // End of CEGUI namespace section
<|endoftext|>
|
<commit_before>// alien:///alice/cern.ch/user/t/tschuste/correction_hybrid_nulled.root
AliDhcTask *AddTaskDhc(
Int_t iAna = 2,
TString chUName = "",
TString chHEffFile = "",
TString chMuEffFile = "",
TString chTaskFile = "",
TString chTaskName = "",
TString chNTracks = "PicoTracks")
{
Char_t chExtraName[256];
// Get the analysis manager
AliAnalysisManager *mgr = AliAnalysisManager::GetAnalysisManager();
if (!mgr) {
Error("AddTaskDhc", "No analysis manager found.");
return;
}
// ESD or AOD? write into the task name etc.
sprintf(chExtraName,"_%s",mgr->GetInputEventHandler()->GetDataType());
AliDhcTask *dhcTask = 0x0;
// If string chTaskFile is given, load a pre-configured task from file
if (!chTaskFile.EqualTo("")) {
iAna=999;
TFile *fiDhcTask = 0x0;
fiDhcTask = TFile::Open(chTaskFile,"OLD");
if (!fiDhcTask){
Error("AddTaskDhc",Form("Requested file: %s was not opened. ABORT.",chTaskFile));
return;
}
dhcTask = (AliDhcTask*) fiDhcTask->Get(chTaskName);
}
else { // create a new task
// Binning
Double_t arPt[5] = {0.5, 1.0, 2.0, 4.0};
TAxis *axPt = new TAxis(3,arPt);
Double_t arCent[5] = {0.0, 20.0, 40.0, 60.0, 100.0};
TAxis *axCent = new TAxis(4,arCent);
TAxis *axZvtx = new TAxis(1,-10.0,10.0);
Double_t arCentMix[9] = {0.0, 10.0, 20.0, 30.0, 40.0, 50.0, 60.0, 80.0, 100.0};
TAxis *axCentMix = new TAxis(8,arCentMix);
TAxis *axZvtxMix = new TAxis(8,-10.0,10.0);
// Efficiency correction files
TFile *fiHEff = 0x0;
TFile *fiMuEff = 0x0;
THnF* hHEff = 0x0;
THnF* hMuEff = 0x0;
if (!chHEffFile.EqualTo("")) {
fiHEff = TFile::Open(chHEffFile,"OLD");
if (!fiHEff){
Error("AddTaskDhc",Form("Requested file: %s was not opened. ABORT.",chHEffFile));
return;
}
hHEff = (THnF*) fiHEff->Get("correction");
}
if (!chMuEffFile.EqualTo("")) {
fiMuEff = TFile::Open(chMuEffFile,"OLD");
if (!fiMuEff){
Error("AddTaskDhc",Form("Requested file: %s was not opened. ABORT.",chMuEffFile));
return;
}
hMuEff = (THnF*) fiMuEff->Get("correction");
}
dhcTask = new AliDhcTask("Task_tschuste_Dhc_fornow");
if (iAna==1) { // h-h
Int_t nDetaBins = 40;
Int_t nDPhiBins = 72;
dhcTask->SetAnaMode(AliDhcTask::kHH);
dhcTask->SetHEffT(hHEff);
dhcTask->SetHEffA(hHEff);
dhcTask->SetEtaMax(1.2);
dhcTask->SetPtTACrit(kTRUE);
sprintf(chExtraName,"%s_HH",chExtraName);
if (hHEff) {
sprintf(chExtraName,"%s_corrH",chExtraName);
}
} else if (iAna==2) { // mu-h
Int_t nDetaBins = 100;
Int_t nDPhiBins = 36;
dhcTask->SetAnaMode(AliDhcTask::kMuH);
dhcTask->SetHEffT(hMuEff);
dhcTask->SetHEffA(hHEff);
dhcTask->SetEtaMax(5.0);
dhcTask->SetPtTACrit(kFALSE);
sprintf(chExtraName,"%s_MuH",chExtraName);
if (hMuEff) {
sprintf(chExtraName,"%s_corrMu",chExtraName);
}
if (hHEff) {
sprintf(chExtraName,"%s_corrH",chExtraName);
}
}
dhcTask->SetTracksName(chNTracks);
dhcTask->SetDoWeights(kFALSE);
dhcTask->SetCentMethod("V0M");
dhcTask->SetDEtaDPhiBins(nDetaBins,nDPhiBins);
dhcTask->SetPtTBins(axPt);
dhcTask->SetPtABins(axPt);
dhcTask->SetCentBins(axCent);
dhcTask->SetZVtxBins(axZvtx);
dhcTask->SetCentMixBins(axCentMix);
dhcTask->SetZVtxMixBins(axZvtxMix);
dhcTask->SelectCollisionCandidates(AliVEvent::kINT7);
dhcTask->SetVerbosity(0);
}
if (!dhcTask) {
Error("AddTaskDhc","no dhcTask");
return 0x0;
}
// make a unique task name
Char_t chNewTaskName[256];
if (chTaskName.EqualTo("")) {
sprintf(chNewTaskName,"Task_Dhc%s%s",chExtraName,chUName.Data());
} else {
sprintf(chNewTaskName,"%s",chTaskName);
}
AliDhcTask *mgrTask = mgr->GetTask(chNewTaskName);
if (mgrTask)
sprintf(chNewTaskName,"%s_bis%04.0f",chNewTaskName,10000*gRandom->Rndm());
dhcTask->SetName(chNewTaskName);
Info("AddTaskDhc",Form("DHC Analysis, adding task %s",dhcTask->GetName()));
mgr->AddTask(dhcTask);
AliAnalysisDataContainer *co_Dhc = mgr->CreateContainer(Form("Cont_%s",chNewTaskName),
TList::Class(),
AliAnalysisManager::kOutputContainer,
Form("%s:PWGCF_out_%s", AliAnalysisManager::GetCommonFileName(), chNewTaskName));
mgr->ConnectInput(dhcTask,0,mgr->GetCommonInputContainer());
mgr->ConnectOutput(dhcTask,1,co_Dhc);
return dhcTask;
}
<commit_msg>add iana4<commit_after>// $Id$
// File config location
// alien:///alice/cern.ch/user/t/tschuste/correction_hybrid_nulled.root
AliDhcTask *AddTaskDhc(
Int_t iAna = 2,
TString chUName = "",
TString chHEffFile = "",
TString chMuEffFile = "",
TString chTaskFile = "",
TString chTaskName = "",
TString chNTracks = "PicoTracks"
)
{
Char_t chExtraName[256];
// Get the analysis manager
AliAnalysisManager *mgr = AliAnalysisManager::GetAnalysisManager();
if (!mgr) {
Error("AddTaskDhc", "No analysis manager found.");
return;
}
// ESD or AOD? write into the task name etc.
sprintf(chExtraName,"_%s",mgr->GetInputEventHandler()->GetDataType());
AliDhcTask *dhcTask = 0x0;
// if string chTaskFile is given, load a pre-configured task from file
if (!chTaskFile.EqualTo("")) {
iAna=999;
TFile *fiDhcTask = 0x0;
fiDhcTask = TFile::Open(chTaskFile,"OLD");
if (!fiDhcTask){
Error("AddTaskDhc",Form("Requested file: %s was not opened. ABORT.",chTaskFile));
return;
}
dhcTask = (AliDhcTask*) fiDhcTask->Get(chTaskName);
}
else { // create a new task
// Binning
Double_t arPt[5] = {0.5, 1.0, 2.0, 4.0};
TAxis *axPt = new TAxis(3,arPt);
Double_t arCent[5] = {0.0, 20.0, 40.0, 60.0, 100.0};
TAxis *axCent = new TAxis(4,arCent);
TAxis *axZvtx = new TAxis(1,-10.0,10.0);
Double_t arCentMix[9] = {0.0, 10.0, 20.0, 30.0, 40.0, 50.0, 60.0, 80.0, 100.0};
TAxis *axCentMix = new TAxis(8,arCentMix);
TAxis *axZvtxMix = new TAxis(8,-10.0,10.0);
// Efficiency correction files
TFile *fiHEff = 0x0;
TFile *fiMuEff = 0x0;
THnF* hHEff = 0x0;
THnF* hMuEff = 0x0;
if (!chHEffFile.EqualTo("")) {
fiHEff = TFile::Open(chHEffFile,"OLD");
if (!fiHEff){
Error("AddTaskDhc",Form("Requested file: %s was not opened. ABORT.",chHEffFile));
return;
}
hHEff = (THnF*) fiHEff->Get("correction");
}
if (!chMuEffFile.EqualTo("")) {
fiMuEff = TFile::Open(chMuEffFile,"OLD");
if (!fiMuEff){
Error("AddTaskDhc",Form("Requested file: %s was not opened. ABORT.",chMuEffFile));
return;
}
hMuEff = (THnF*) fiMuEff->Get("correction");
}
dhcTask = new AliDhcTask("Task_Dhc_Temp_Name");
if (iAna==1) { // h-h
Int_t nDetaBins = 40;
Int_t nDPhiBins = 72;
dhcTask->SetAnaMode(AliDhcTask::kHH);
dhcTask->SetHEffT(hHEff);
dhcTask->SetHEffA(hHEff);
dhcTask->SetEtaMax(1.2);
dhcTask->SetPtTACrit(kTRUE);
sprintf(chExtraName,"%s_HH",chExtraName);
if (hHEff) {
sprintf(chExtraName,"%s_corrH",chExtraName);
}
} else if (iAna==2) { // mu-h
Int_t nDetaBins = 100;
Int_t nDPhiBins = 36;
dhcTask->SetAnaMode(AliDhcTask::kMuH);
dhcTask->SetHEffT(hMuEff);
dhcTask->SetHEffA(hHEff);
dhcTask->SetEtaMax(5.0);
dhcTask->SetPtTACrit(kFALSE);
sprintf(chExtraName,"%s_MuH",chExtraName);
if (hMuEff) {
sprintf(chExtraName,"%s_corrMu",chExtraName);
}
if (hHEff) {
sprintf(chExtraName,"%s_corrH",chExtraName);
}
} else if (iAna==4) { // mu-mu
Int_t nDetaBins = 60;
Int_t nDPhiBins = 36;
dhcTask->SetAnaMode(AliDhcTask::kMuMu);
dhcTask->SetHEffT(hMuEff);
dhcTask->SetHEffA(hHEff);
dhcTask->SetEtaMax(5.0);
dhcTask->SetPtTACrit(kFALSE);
sprintf(chExtraName,"%s_MuMu",chExtraName);
if (hMuEff) {
sprintf(chExtraName,"%s_corrMu",chExtraName);
}
if (hHEff) {
sprintf(chExtraName,"%s_corrH",chExtraName);
}
} else {
Error("AddTaskDhc", Form("iAna %d not known", iAna));
}
dhcTask->SetTracksName(chNTracks);
dhcTask->SetDoWeights(kFALSE);
dhcTask->SetCentMethod("V0M");
dhcTask->SetDEtaDPhiBins(nDetaBins,nDPhiBins);
dhcTask->SetPtTBins(axPt);
dhcTask->SetPtABins(axPt);
dhcTask->SetCentBins(axCent);
dhcTask->SetZVtxBins(axZvtx);
dhcTask->SetCentMixBins(axCentMix);
dhcTask->SetZVtxMixBins(axZvtxMix);
dhcTask->SelectCollisionCandidates(AliVEvent::kINT7);
dhcTask->SetVerbosity(0);
}
if (!dhcTask) {
Error("AddTaskDhc","no dhcTask");
return 0x0;
}
// make a unique task name
Char_t chNewTaskName[256];
if (chTaskName.EqualTo("")) {
sprintf(chNewTaskName,"Task_Dhc%s%s",chExtraName,chUName.Data());
} else {
sprintf(chNewTaskName,"%s",chTaskName);
}
AliDhcTask *mgrTask = mgr->GetTask(chNewTaskName);
if (mgrTask)
sprintf(chNewTaskName,"%s_bis%04.0f",chNewTaskName,10000*gRandom->Rndm());
dhcTask->SetName(chNewTaskName);
Info("AddTaskDhc",Form("DHC Analysis, adding task %s",dhcTask->GetName()));
mgr->AddTask(dhcTask);
AliAnalysisDataContainer *co_Dhc = mgr->CreateContainer(Form("Cont_%s",chNewTaskName),
TList::Class(),
AliAnalysisManager::kOutputContainer,
Form("%s:PWGCF_out_%s", AliAnalysisManager::GetCommonFileName(), chNewTaskName));
mgr->ConnectInput(dhcTask,0,mgr->GetCommonInputContainer());
mgr->ConnectOutput(dhcTask,1,co_Dhc);
return dhcTask;
}
<|endoftext|>
|
<commit_before>
#pragma once
#include "physics/rigid_motion.hpp"
#include <utility>
#include "geometry/identity.hpp"
#include "geometry/linear_map.hpp"
namespace principia {
namespace physics {
namespace internal_rigid_motion {
using geometry::LinearMap;
template<typename FromFrame, typename ToFrame>
RigidMotion<FromFrame, ToFrame>::RigidMotion(
RigidTransformation<FromFrame, ToFrame> const& rigid_transformation,
AngularVelocity<FromFrame> const& angular_velocity_of_to_frame,
Velocity<FromFrame> const& velocity_of_to_frame_origin)
: rigid_transformation_(rigid_transformation),
angular_velocity_of_to_frame_(angular_velocity_of_to_frame),
velocity_of_to_frame_origin_(velocity_of_to_frame_origin) {}
template<typename FromFrame, typename ToFrame>
template<typename F, typename T, typename>
RigidMotion<FromFrame, ToFrame>::RigidMotion(
RigidTransformation<FromFrame, ToFrame> const& rigid_transformation,
AngularVelocity<ToFrame> const& angular_velocity_of_from_frame,
Velocity<ToFrame> const& velocity_of_from_frame_origin)
: RigidMotion(
RigidMotion<ToFrame, FromFrame>(rigid_transformation.Inverse(),
angular_velocity_of_from_frame,
velocity_of_from_frame_origin)
.Inverse()) {}
template<typename FromFrame, typename ToFrame>
RigidTransformation<FromFrame, ToFrame> const&
RigidMotion<FromFrame, ToFrame>::rigid_transformation() const {
return rigid_transformation_;
}
template<typename FromFrame, typename ToFrame>
OrthogonalMap<FromFrame, ToFrame> const&
RigidMotion<FromFrame, ToFrame>::orthogonal_map() const {
return rigid_transformation_.linear_map();
}
template<typename FromFrame, typename ToFrame>
template<typename F>
AngularVelocity<
typename RigidMotion<FromFrame, ToFrame>::template other_frame_t<F>>
RigidMotion<FromFrame, ToFrame>::angular_velocity_of() const {
if constexpr (std::is_same_v<F, ToFrame>) {
return angular_velocity_of_to_frame_;
} else if constexpr (std::is_same_v<F, FromFrame>) {
return Inverse().angular_velocity_of_to_frame_;
} else {
static_assert(std::disjunction_v<std::is_same<F, ToFrame>,
std::is_same<F, FromFrame>>,
"Nonsensical frame");
}
}
template<typename FromFrame, typename ToFrame>
template<typename F>
Velocity<typename RigidMotion<FromFrame, ToFrame>::template other_frame_t<F>>
RigidMotion<FromFrame, ToFrame>::velocity_of_origin_of() const {
if constexpr (std::is_same_v<F, ToFrame>) {
return velocity_of_to_frame_origin_;
} else if constexpr (std::is_same_v<F, FromFrame>) {
return Inverse().velocity_of_to_frame_origin_;
} else {
static_assert(std::disjunction_v<std::is_same<F, ToFrame>,
std::is_same<F, FromFrame>>,
"Nonsensical frame");
}
}
template<typename FromFrame, typename ToFrame>
DegreesOfFreedom<ToFrame> RigidMotion<FromFrame, ToFrame>::operator()(
DegreesOfFreedom<FromFrame> const& degrees_of_freedom) const {
return {rigid_transformation_(degrees_of_freedom.position()),
orthogonal_map()(
degrees_of_freedom.velocity() - velocity_of_to_frame_origin_ -
angular_velocity_of_to_frame_ *
(degrees_of_freedom.position() -
rigid_transformation_.Inverse()(ToFrame::origin)) /
Radian)};
}
template<typename FromFrame, typename ToFrame>
RigidMotion<ToFrame, FromFrame>
RigidMotion<FromFrame, ToFrame>::Inverse() const {
return RigidMotion<ToFrame, FromFrame>(
rigid_transformation_.Inverse(),
-orthogonal_map()(angular_velocity_of_to_frame_),
(*this)({FromFrame::origin, FromFrame::unmoving}).velocity());
}
template<typename FromFrame, typename ToFrame>
RigidMotion<FromFrame, ToFrame>
RigidMotion<FromFrame, ToFrame>::MakeNonRotatingMotion(
DegreesOfFreedom<ToFrame> const& degrees_of_freedom_of_from_frame_origin) {
if constexpr (FromFrame::handedness == ToFrame::handedness) {
return RigidMotion(RigidTransformation<FromFrame, ToFrame>(
FromFrame::origin,
degrees_of_freedom_of_from_frame_origin.position(),
geometry::Identity<FromFrame, ToFrame>().Forget()),
ToFrame::nonrotating,
degrees_of_freedom_of_from_frame_origin.velocity());
} else {
// TODO(phl): This is extremely dubious. We apply the sun_looking_glass
// permutation because we "know" that we have World and RigidPart here.
return RigidMotion(
RigidTransformation<FromFrame, ToFrame>(
FromFrame::origin,
degrees_of_freedom_of_from_frame_origin.position(),
geometry::Permutation<FromFrame, ToFrame>(
geometry::Permutation<FromFrame,
ToFrame>::CoordinatePermutation::XZY)
.template Forget<OrthogonalMap>()),
ToFrame::nonrotating,
degrees_of_freedom_of_from_frame_origin.velocity());
}
}
template<typename FromFrame, typename ToFrame>
void RigidMotion<FromFrame, ToFrame>::WriteToMessage(
not_null<serialization::RigidMotion*> const message) const {
rigid_transformation_.WriteToMessage(message->mutable_rigid_transformation());
angular_velocity_of_to_frame_.WriteToMessage(
message->mutable_angular_velocity_of_to_frame());
velocity_of_to_frame_origin_.WriteToMessage(
message->mutable_velocity_of_to_frame_origin());
}
template<typename FromFrame, typename ToFrame>
RigidMotion<FromFrame, ToFrame>
RigidMotion<FromFrame, ToFrame>::ReadFromMessage(
serialization::RigidMotion const& message) {
return RigidMotion(RigidTransformation<FromFrame, ToFrame>::ReadFromMessage(
message.rigid_transformation()),
AngularVelocity<FromFrame>::ReadFromMessage(
message.angular_velocity_of_to_frame()),
Velocity<FromFrame>::ReadFromMessage(
message.velocity_of_to_frame_origin()));
}
template<typename FromFrame, typename ToFrame>
template<typename F, typename T, typename>
RigidMotion<FromFrame, ToFrame> RigidMotion<FromFrame, ToFrame>::Identity() {
return RigidMotion(RigidTransformation<FromFrame, ToFrame>::Identity(),
FromFrame::nonrotating,
FromFrame::unmoving);
}
template<typename FromFrame, typename ThroughFrame, typename ToFrame>
RigidMotion<FromFrame, ToFrame> operator*(
RigidMotion<ThroughFrame, ToFrame> const& left,
RigidMotion<FromFrame, ThroughFrame> const& right) {
return RigidMotion<FromFrame, ToFrame>(
left.rigid_transformation() * right.rigid_transformation(),
right.angular_velocity_of_to_frame_ +
right.orthogonal_map().Inverse()(left.angular_velocity_of_to_frame_),
right.Inverse()(left.Inverse()(
{ToFrame::origin, ToFrame::unmoving})).velocity());
}
template<typename FromFrame, typename ToFrame>
std::ostream& operator<<(std::ostream& out,
RigidMotion<FromFrame, ToFrame> const& rigid_motion) {
return out << "{transformation: " << rigid_motion.rigid_transformation()
<< ", angular velocity: "
<< rigid_motion.template angular_velocity_of<ToFrame>()
<< ", velocity: "
<< rigid_motion.template velocity_of_origin_of<ToFrame>()
<< "}";
}
template<typename FromFrame, typename ToFrame>
std::ostream& operator<<(std::ostream& out,
AcceleratedRigidMotion<FromFrame, ToFrame> const&
accelerated_rigid_motion) {
return out
<< "{motion: " << accelerated_rigid_motion.rigid_motion()
<< ", angular acceleration: "
<< accelerated_rigid_motion.template angular_acceleration_of<ToFrame>()
<< ", acceleration: "
<< accelerated_rigid_motion
.template acceleration_of_origin_of<ToFrame>()
<< "}";
}
template<typename FromFrame, typename ToFrame>
AcceleratedRigidMotion<FromFrame, ToFrame>::AcceleratedRigidMotion(
RigidMotion<FromFrame, ToFrame> const& rigid_motion,
Bivector<AngularAcceleration, FromFrame> const&
angular_acceleration_of_to_frame,
Vector<Acceleration, FromFrame> const& acceleration_of_to_frame_origin)
: rigid_motion_(rigid_motion),
angular_acceleration_of_to_frame_(angular_acceleration_of_to_frame),
acceleration_of_to_frame_origin_(acceleration_of_to_frame_origin) {}
template<typename FromFrame, typename ToFrame>
RigidMotion<FromFrame, ToFrame> const&
AcceleratedRigidMotion<FromFrame, ToFrame>::rigid_motion() const {
return rigid_motion_;
}
template<typename FromFrame, typename ToFrame>
template<typename F>
Bivector<AngularAcceleration,
typename AcceleratedRigidMotion<FromFrame, ToFrame>::
template other_frame_t<F>>
AcceleratedRigidMotion<FromFrame, ToFrame>::angular_acceleration_of() const {
if constexpr (std::is_same_v<F, ToFrame>) {
return angular_acceleration_of_to_frame_;
} else if constexpr (std::is_same_v<F, FromFrame>) {
static_assert(!std::is_same_v<F, FromFrame>,
"Time to implement AcceleratedRigidMotion::Inverse");
} else {
static_assert(std::is_same_v<F, ToFrame> || std::is_same_v<F, FromFrame>,
"Nonsensical frame");
}
}
template<typename FromFrame, typename ToFrame>
template<typename F>
Vector<Acceleration,
typename AcceleratedRigidMotion<FromFrame, ToFrame>::
template other_frame_t<F>>
AcceleratedRigidMotion<FromFrame, ToFrame>::acceleration_of_origin_of() const {
if constexpr (std::is_same_v<F, ToFrame>) {
return acceleration_of_to_frame_origin_;
} else if constexpr (std::is_same_v<F, FromFrame>) {
static_assert(!std::is_same_v<F, FromFrame>,
"Time to implement AcceleratedRigidMotion::Inverse");
} else {
static_assert(std::is_same_v<F, ToFrame> || std::is_same_v<F, FromFrame>,
"Nonsensical frame");
}
}
} // namespace internal_rigid_motion
} // namespace physics
} // namespace principia
<commit_msg>Some more disjunctions.<commit_after>
#pragma once
#include "physics/rigid_motion.hpp"
#include <utility>
#include "geometry/identity.hpp"
#include "geometry/linear_map.hpp"
namespace principia {
namespace physics {
namespace internal_rigid_motion {
using geometry::LinearMap;
template<typename FromFrame, typename ToFrame>
RigidMotion<FromFrame, ToFrame>::RigidMotion(
RigidTransformation<FromFrame, ToFrame> const& rigid_transformation,
AngularVelocity<FromFrame> const& angular_velocity_of_to_frame,
Velocity<FromFrame> const& velocity_of_to_frame_origin)
: rigid_transformation_(rigid_transformation),
angular_velocity_of_to_frame_(angular_velocity_of_to_frame),
velocity_of_to_frame_origin_(velocity_of_to_frame_origin) {}
template<typename FromFrame, typename ToFrame>
template<typename F, typename T, typename>
RigidMotion<FromFrame, ToFrame>::RigidMotion(
RigidTransformation<FromFrame, ToFrame> const& rigid_transformation,
AngularVelocity<ToFrame> const& angular_velocity_of_from_frame,
Velocity<ToFrame> const& velocity_of_from_frame_origin)
: RigidMotion(
RigidMotion<ToFrame, FromFrame>(rigid_transformation.Inverse(),
angular_velocity_of_from_frame,
velocity_of_from_frame_origin)
.Inverse()) {}
template<typename FromFrame, typename ToFrame>
RigidTransformation<FromFrame, ToFrame> const&
RigidMotion<FromFrame, ToFrame>::rigid_transformation() const {
return rigid_transformation_;
}
template<typename FromFrame, typename ToFrame>
OrthogonalMap<FromFrame, ToFrame> const&
RigidMotion<FromFrame, ToFrame>::orthogonal_map() const {
return rigid_transformation_.linear_map();
}
template<typename FromFrame, typename ToFrame>
template<typename F>
AngularVelocity<
typename RigidMotion<FromFrame, ToFrame>::template other_frame_t<F>>
RigidMotion<FromFrame, ToFrame>::angular_velocity_of() const {
if constexpr (std::is_same_v<F, ToFrame>) {
return angular_velocity_of_to_frame_;
} else if constexpr (std::is_same_v<F, FromFrame>) {
return Inverse().angular_velocity_of_to_frame_;
} else {
static_assert(std::is_same_v<F, ToFrame> || std::is_same_v<F, FromFrame>,
"Nonsensical frame");
}
}
template<typename FromFrame, typename ToFrame>
template<typename F>
Velocity<typename RigidMotion<FromFrame, ToFrame>::template other_frame_t<F>>
RigidMotion<FromFrame, ToFrame>::velocity_of_origin_of() const {
if constexpr (std::is_same_v<F, ToFrame>) {
return velocity_of_to_frame_origin_;
} else if constexpr (std::is_same_v<F, FromFrame>) {
return Inverse().velocity_of_to_frame_origin_;
} else {
static_assert(std::is_same_v<F, ToFrame> || std::is_same_v<F, FromFrame>,
"Nonsensical frame");
}
}
template<typename FromFrame, typename ToFrame>
DegreesOfFreedom<ToFrame> RigidMotion<FromFrame, ToFrame>::operator()(
DegreesOfFreedom<FromFrame> const& degrees_of_freedom) const {
return {rigid_transformation_(degrees_of_freedom.position()),
orthogonal_map()(
degrees_of_freedom.velocity() - velocity_of_to_frame_origin_ -
angular_velocity_of_to_frame_ *
(degrees_of_freedom.position() -
rigid_transformation_.Inverse()(ToFrame::origin)) /
Radian)};
}
template<typename FromFrame, typename ToFrame>
RigidMotion<ToFrame, FromFrame>
RigidMotion<FromFrame, ToFrame>::Inverse() const {
return RigidMotion<ToFrame, FromFrame>(
rigid_transformation_.Inverse(),
-orthogonal_map()(angular_velocity_of_to_frame_),
(*this)({FromFrame::origin, FromFrame::unmoving}).velocity());
}
template<typename FromFrame, typename ToFrame>
RigidMotion<FromFrame, ToFrame>
RigidMotion<FromFrame, ToFrame>::MakeNonRotatingMotion(
DegreesOfFreedom<ToFrame> const& degrees_of_freedom_of_from_frame_origin) {
if constexpr (FromFrame::handedness == ToFrame::handedness) {
return RigidMotion(RigidTransformation<FromFrame, ToFrame>(
FromFrame::origin,
degrees_of_freedom_of_from_frame_origin.position(),
geometry::Identity<FromFrame, ToFrame>().Forget()),
ToFrame::nonrotating,
degrees_of_freedom_of_from_frame_origin.velocity());
} else {
// TODO(phl): This is extremely dubious. We apply the sun_looking_glass
// permutation because we "know" that we have World and RigidPart here.
return RigidMotion(
RigidTransformation<FromFrame, ToFrame>(
FromFrame::origin,
degrees_of_freedom_of_from_frame_origin.position(),
geometry::Permutation<FromFrame, ToFrame>(
geometry::Permutation<FromFrame,
ToFrame>::CoordinatePermutation::XZY)
.template Forget<OrthogonalMap>()),
ToFrame::nonrotating,
degrees_of_freedom_of_from_frame_origin.velocity());
}
}
template<typename FromFrame, typename ToFrame>
void RigidMotion<FromFrame, ToFrame>::WriteToMessage(
not_null<serialization::RigidMotion*> const message) const {
rigid_transformation_.WriteToMessage(message->mutable_rigid_transformation());
angular_velocity_of_to_frame_.WriteToMessage(
message->mutable_angular_velocity_of_to_frame());
velocity_of_to_frame_origin_.WriteToMessage(
message->mutable_velocity_of_to_frame_origin());
}
template<typename FromFrame, typename ToFrame>
RigidMotion<FromFrame, ToFrame>
RigidMotion<FromFrame, ToFrame>::ReadFromMessage(
serialization::RigidMotion const& message) {
return RigidMotion(RigidTransformation<FromFrame, ToFrame>::ReadFromMessage(
message.rigid_transformation()),
AngularVelocity<FromFrame>::ReadFromMessage(
message.angular_velocity_of_to_frame()),
Velocity<FromFrame>::ReadFromMessage(
message.velocity_of_to_frame_origin()));
}
template<typename FromFrame, typename ToFrame>
template<typename F, typename T, typename>
RigidMotion<FromFrame, ToFrame> RigidMotion<FromFrame, ToFrame>::Identity() {
return RigidMotion(RigidTransformation<FromFrame, ToFrame>::Identity(),
FromFrame::nonrotating,
FromFrame::unmoving);
}
template<typename FromFrame, typename ThroughFrame, typename ToFrame>
RigidMotion<FromFrame, ToFrame> operator*(
RigidMotion<ThroughFrame, ToFrame> const& left,
RigidMotion<FromFrame, ThroughFrame> const& right) {
return RigidMotion<FromFrame, ToFrame>(
left.rigid_transformation() * right.rigid_transformation(),
right.angular_velocity_of_to_frame_ +
right.orthogonal_map().Inverse()(left.angular_velocity_of_to_frame_),
right.Inverse()(left.Inverse()(
{ToFrame::origin, ToFrame::unmoving})).velocity());
}
template<typename FromFrame, typename ToFrame>
std::ostream& operator<<(std::ostream& out,
RigidMotion<FromFrame, ToFrame> const& rigid_motion) {
return out << "{transformation: " << rigid_motion.rigid_transformation()
<< ", angular velocity: "
<< rigid_motion.template angular_velocity_of<ToFrame>()
<< ", velocity: "
<< rigid_motion.template velocity_of_origin_of<ToFrame>()
<< "}";
}
template<typename FromFrame, typename ToFrame>
std::ostream& operator<<(std::ostream& out,
AcceleratedRigidMotion<FromFrame, ToFrame> const&
accelerated_rigid_motion) {
return out
<< "{motion: " << accelerated_rigid_motion.rigid_motion()
<< ", angular acceleration: "
<< accelerated_rigid_motion.template angular_acceleration_of<ToFrame>()
<< ", acceleration: "
<< accelerated_rigid_motion
.template acceleration_of_origin_of<ToFrame>()
<< "}";
}
template<typename FromFrame, typename ToFrame>
AcceleratedRigidMotion<FromFrame, ToFrame>::AcceleratedRigidMotion(
RigidMotion<FromFrame, ToFrame> const& rigid_motion,
Bivector<AngularAcceleration, FromFrame> const&
angular_acceleration_of_to_frame,
Vector<Acceleration, FromFrame> const& acceleration_of_to_frame_origin)
: rigid_motion_(rigid_motion),
angular_acceleration_of_to_frame_(angular_acceleration_of_to_frame),
acceleration_of_to_frame_origin_(acceleration_of_to_frame_origin) {}
template<typename FromFrame, typename ToFrame>
RigidMotion<FromFrame, ToFrame> const&
AcceleratedRigidMotion<FromFrame, ToFrame>::rigid_motion() const {
return rigid_motion_;
}
template<typename FromFrame, typename ToFrame>
template<typename F>
Bivector<AngularAcceleration,
typename AcceleratedRigidMotion<FromFrame, ToFrame>::
template other_frame_t<F>>
AcceleratedRigidMotion<FromFrame, ToFrame>::angular_acceleration_of() const {
if constexpr (std::is_same_v<F, ToFrame>) {
return angular_acceleration_of_to_frame_;
} else if constexpr (std::is_same_v<F, FromFrame>) {
static_assert(!std::is_same_v<F, FromFrame>,
"Time to implement AcceleratedRigidMotion::Inverse");
} else {
static_assert(std::is_same_v<F, ToFrame> || std::is_same_v<F, FromFrame>,
"Nonsensical frame");
}
}
template<typename FromFrame, typename ToFrame>
template<typename F>
Vector<Acceleration,
typename AcceleratedRigidMotion<FromFrame, ToFrame>::
template other_frame_t<F>>
AcceleratedRigidMotion<FromFrame, ToFrame>::acceleration_of_origin_of() const {
if constexpr (std::is_same_v<F, ToFrame>) {
return acceleration_of_to_frame_origin_;
} else if constexpr (std::is_same_v<F, FromFrame>) {
static_assert(!std::is_same_v<F, FromFrame>,
"Time to implement AcceleratedRigidMotion::Inverse");
} else {
static_assert(std::is_same_v<F, ToFrame> || std::is_same_v<F, FromFrame>,
"Nonsensical frame");
}
}
} // namespace internal_rigid_motion
} // namespace physics
} // namespace principia
<|endoftext|>
|
<commit_before>/*!
@file
@author Albert Semenov
@date 05/2008
*/
#include "MyGUI_OgreDataManager.h"
#include "MyGUI_OgreDiagnostic.h"
#include "MyGUI_OgreDataStream.h"
#include <Ogre.h>
#include "MyGUI_LastHeader.h"
namespace MyGUI
{
OgreDataManager::OgreDataManager() :
mIsInitialise(false)
{
}
void OgreDataManager::initialise(const std::string& _group)
{
MYGUI_ASSERT(!mIsInitialise, getClassTypeName() << " initialised twice");
MYGUI_LOG(Info, "* Initialise: " << getClassTypeName());
mGroup = _group;
MYGUI_LOG(Info, getClassTypeName() << " successfully initialized");
mIsInitialise = true;
}
void OgreDataManager::shutdown()
{
MYGUI_ASSERT(mIsInitialise, getClassTypeName() << " is not initialised");
MYGUI_LOG(Info, "* Shutdown: " << getClassTypeName());
MYGUI_LOG(Info, getClassTypeName() << " successfully shutdown");
mIsInitialise = false;
}
IDataStream* OgreDataManager::getData(const std::string& _name)
{
try
{
Ogre::DataStreamPtr stream = Ogre::ResourceGroupManager::getSingleton().openResource(_name, mGroup, true);
OgreDataStream* data = new OgreDataStream(stream);
return data;
}
catch(Ogre::FileNotFoundException)
{
}
return nullptr;
}
bool OgreDataManager::isDataExist(const std::string& _name)
{
const VectorString& files = getDataListNames(_name);
return (files.size() == 1);
}
const VectorString& OgreDataManager::getDataListNames(const std::string& _pattern)
{
return getDataListNames(_pattern, false);
}
const VectorString& OgreDataManager::getDataListNames(const std::string& _pattern, bool _fullpath)
{
static VectorString result;
result.clear();
Ogre::FileInfoListPtr pFileInfo = Ogre::ResourceGroupManager::getSingleton().findResourceFileInfo(mGroup, _pattern);
result.reserve(pFileInfo->size());
for (Ogre::FileInfoList::iterator fi = pFileInfo->begin(); fi != pFileInfo->end(); ++fi )
{
if (fi->path.empty())
{
bool found = false;
for (VectorString::iterator iter=result.begin(); iter!=result.end(); ++iter)
{
if (*iter == fi->filename)
{
found = true;
break;
}
}
if (!found)
{
result.push_back(_fullpath ? fi->archive->getName() + "/" + fi->filename : fi->filename);
}
}
}
pFileInfo.setNull();
return result;
}
const std::string& OgreDataManager::getDataPath(const std::string& _name)
{
static std::string result;
const VectorString& files = getDataListNames(_name, true);
result = files.size() == 1 ? files[0] : "";
return result;
}
} // namespace MyGUI
<commit_msg>add log to ogre data manager<commit_after>/*!
@file
@author Albert Semenov
@date 05/2008
*/
#include "MyGUI_OgreDataManager.h"
#include "MyGUI_OgreDiagnostic.h"
#include "MyGUI_OgreDataStream.h"
#include <Ogre.h>
#include "MyGUI_LastHeader.h"
namespace MyGUI
{
OgreDataManager::OgreDataManager() :
mIsInitialise(false)
{
}
void OgreDataManager::initialise(const std::string& _group)
{
MYGUI_ASSERT(!mIsInitialise, getClassTypeName() << " initialised twice");
MYGUI_LOG(Info, "* Initialise: " << getClassTypeName());
mGroup = _group;
MYGUI_LOG(Info, getClassTypeName() << " successfully initialized");
mIsInitialise = true;
}
void OgreDataManager::shutdown()
{
MYGUI_ASSERT(mIsInitialise, getClassTypeName() << " is not initialised");
MYGUI_LOG(Info, "* Shutdown: " << getClassTypeName());
MYGUI_LOG(Info, getClassTypeName() << " successfully shutdown");
mIsInitialise = false;
}
IDataStream* OgreDataManager::getData(const std::string& _name)
{
try
{
Ogre::DataStreamPtr stream = Ogre::ResourceGroupManager::getSingleton().openResource(_name, mGroup, true);
OgreDataStream* data = new OgreDataStream(stream);
return data;
}
catch(Ogre::FileNotFoundException _e)
{
MYGUI_LOG(Warning, _e.getDescription());
}
return nullptr;
}
bool OgreDataManager::isDataExist(const std::string& _name)
{
const VectorString& files = getDataListNames(_name);
return (files.size() == 1);
}
const VectorString& OgreDataManager::getDataListNames(const std::string& _pattern)
{
return getDataListNames(_pattern, false);
}
const VectorString& OgreDataManager::getDataListNames(const std::string& _pattern, bool _fullpath)
{
static VectorString result;
result.clear();
Ogre::FileInfoListPtr pFileInfo = Ogre::ResourceGroupManager::getSingleton().findResourceFileInfo(mGroup, _pattern);
result.reserve(pFileInfo->size());
for (Ogre::FileInfoList::iterator fi = pFileInfo->begin(); fi != pFileInfo->end(); ++fi )
{
if (fi->path.empty())
{
bool found = false;
for (VectorString::iterator iter=result.begin(); iter!=result.end(); ++iter)
{
if (*iter == fi->filename)
{
found = true;
break;
}
}
if (!found)
{
result.push_back(_fullpath ? fi->archive->getName() + "/" + fi->filename : fi->filename);
}
}
}
pFileInfo.setNull();
return result;
}
const std::string& OgreDataManager::getDataPath(const std::string& _name)
{
static std::string result;
const VectorString& files = getDataListNames(_name, true);
result = files.size() == 1 ? files[0] : "";
return result;
}
} // namespace MyGUI
<|endoftext|>
|
<commit_before>/*
Highly Optimized Object-Oriented Molecular Dynamics (HOOMD) Open
Source Software License
Copyright (c) 2008 Ames Laboratory Iowa State University
All rights reserved.
Redistribution and use of HOOMD, in source and binary forms, with or
without modification, are permitted, provided that the following
conditions are met:
* Redistributions of source code must retain the above copyright notice,
this list of conditions and the following disclaimer.
* Redistributions in binary form must reproduce the above copyright
notice, this list of conditions and the following disclaimer in the
documentation and/or other materials provided with the distribution.
* Neither the name of the copyright holder nor the names HOOMD's
contributors may be used to endorse or promote products derived from this
software without specific prior written permission.
Disclaimer
THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDER AND
CONTRIBUTORS ``AS IS'' AND ANY EXPRESS OR IMPLIED WARRANTIES,
INCLUDING, BUT NOT LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY
AND FITNESS FOR A PARTICULAR PURPOSE ARE DISCLAIMED.
IN NO EVENT SHALL THE COPYRIGHT HOLDER OR CONTRIBUTORS BE LIABLE
FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR
CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF
SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS
INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN
CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE)
ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF
THE POSSIBILITY OF SUCH DAMAGE.
*/
#ifdef WIN32
#pragma warning( push )
#pragma warning( disable : 4103 4244 )
#endif
#include <iostream>
//! Name the unit test module
#define BOOST_TEST_MODULE ElectrostaticLongRangePPPMTests
#include "boost_utf_configure.h"
#include <boost/test/floating_point_comparison.hpp>
#include <boost/bind.hpp>
#include <boost/function.hpp>
#include <boost/shared_ptr.hpp>
#include "ParticleData.h"
#include <math.h>
using namespace std;
using namespace boost;
//You need a fft defined in order to pass this text
#ifdef USE_FFTW
#include "ElectrostaticLongRangePPPM.h"
#include "FFTClass.h"
#include "FftwWrapper.h"
/*! \file ElectrostaticLongRange_PPPM_test.cc
\brief Implements unit tests for ElectrostaticLongRangePPPM and descendants
\ingroup unit_tests
*/
//! Helper macro for testing if two numbers are close
#define MY_BOOST_CHECK_CLOSE(a,b,c) BOOST_CHECK_CLOSE(a,Scalar(b),Scalar(c))
//! Helper macro for testing if a number is small
#define MY_BOOST_CHECK_SMALL(a,c) BOOST_CHECK_SMALL(a,Scalar(c))
//! Tolerance in percent to use for comparing various ElectrostaticLongRangePPPM to each other
const Scalar tol = Scalar(1);
//! minimum force worth computing
const Scalar MIN_force=Scalar(1.0e-9);
//! Typedef ElectrostaticLongRangePPPM factory
typedef function<shared_ptr<ElectrostaticLongRangePPPM> (shared_ptr<ParticleData> pdata,unsigned int Mmesh_x,unsigned int Mmesh_y,unsigned int Mmesh_z, unsigned int P_order_a, Scalar alpha, shared_ptr<FFTClass> FFTP,bool third_law_m)> LongRangePPPM_creator;
//! Test the ability of the Short Range Electrostatic force compute to actually calculate forces
/*! \param LongRangePPPM_object_n1 I have no idea: the write of this code needs to document it better
\note With the creator as a parameter, the same code can be used to test any derived child
of ElectrostaticLongRangePPPM
*/
void LongRangePPPM_PositionGrid(LongRangePPPM_creator LongRangePPPM_object_n1)
{
cout << "Testing charge distribution on the grid in class ElectrostaticLongRangePPPM" << endl;
// Simple test to check that the charge is defined correctly on the grid
shared_ptr<ParticleData> pdata_6(new ParticleData(6, BoxDim(20.0,40.0,60.0), 1));
ParticleDataArrays arrays = pdata_6->acquireReadWrite();
// six charges are located near the edge of the box
arrays.x[0]=Scalar(-9.6);arrays.y[0]=Scalar(0.0);arrays.z[0]=Scalar(0.0);arrays.charge[0]=1.0;
arrays.x[1]=Scalar(9.6);arrays.y[1]=Scalar(0.0);arrays.z[1]=Scalar(0.0);arrays.charge[1]=-2.0;
arrays.x[2]=Scalar(0.0);arrays.y[2]=Scalar(-19.5);arrays.z[2]=Scalar(0.0);arrays.charge[2]=1.0;
arrays.x[3]=Scalar(0.0);arrays.y[3]=Scalar(19.5);arrays.z[3]=Scalar(0.0);arrays.charge[3]=3.0;
arrays.x[4]=Scalar(0.0);arrays.y[4]=Scalar(0.0);arrays.z[4]=Scalar(-29.4);arrays.charge[4]=-1.0;
arrays.x[5]=Scalar(0.0);arrays.y[5]=Scalar(0.0);arrays.z[5]=Scalar(29.4);arrays.charge[5]=-2.0;
// allow for acquiring data in the future
pdata_6->release();
// Define mesh parameters as well as order of the distribution, etc..
unsigned int Nmesh_x=40;
unsigned int Nmesh_y=80;
unsigned int Nmesh_z=120;
unsigned int P_order=6;
Scalar alpha=4.0;
shared_ptr<FftwWrapper> FFTW(new FftwWrapper(Nmesh_x,Nmesh_y,Nmesh_z));
bool third_law=false;
shared_ptr<ElectrostaticLongRangePPPM> PPPM_6=LongRangePPPM_object_n1(pdata_6,Nmesh_x,Nmesh_y,Nmesh_z,P_order,alpha,FFTW,third_law);
// An ElectrostaticLongRangePPPM object with specified value of grid parameters, alpha, and fft routine instantiated
// now let us check that the charges are correctly distributed
//First check that the polynomials used to spread the charge on the grid are what they should be
//This may eliminate unpleasant bugs
//The values of the coefficents are taken from Appendix E in the Deserno and Holm paper
Scalar **Exact=new Scalar*[P_order];
for(unsigned int i=0;i<P_order;i++) Exact[i]=new Scalar[P_order];
Exact[0][0]=1.0;Exact[0][1]=-10.0;Exact[0][2]=40.0;Exact[0][3]=-80.0;Exact[0][4]=80.0;Exact[0][5]=-32.0;
Exact[1][0]=237.0;Exact[1][1]=-750.0;Exact[1][2]=840.0;Exact[1][3]=-240.0;Exact[1][4]=-240.0;Exact[1][5]=160.0;
Exact[2][0]=1682.0;Exact[2][1]=-1540.0;Exact[2][2]=-880.0;Exact[2][3]=1120.0;Exact[2][4]=160.0;Exact[2][5]=-320.0;
Exact[3][0]=1682.0;Exact[3][1]=1540.0;Exact[3][2]=880.0;Exact[3][3]=-1120.0;Exact[3][4]=-160.0;Exact[3][5]=320.0;
Exact[4][0]=237.0;Exact[4][1]=750.0;Exact[4][2]=840.0;Exact[4][3]=240.0;Exact[4][4]=-240.0;Exact[4][5]=-160.0;
Exact[5][0]=1.0;Exact[5][1]=10.0;Exact[5][2]=40.0;Exact[5][3]=80.0;Exact[5][4]=80.0;Exact[5][5]=32.0;
for(unsigned int i=0;i<P_order;i++){
for(unsigned int j=0;j<P_order;j++){
Exact[i][j]*=static_cast<Scalar>(1/3840.0);
}
}
for(unsigned int i=0;i<P_order;i++){
for(unsigned int j=0;j<P_order;j++){
MY_BOOST_CHECK_CLOSE(Exact[i][j],PPPM_6->Poly_coeff_Grid(i,j),tol);
}
}
//Check passed, now let us compute the charges on the grid
}
//! ElectrostaticShortRange creator for unit tests
shared_ptr<ElectrostaticLongRangePPPM> base_class_PPPM_creator(shared_ptr<ParticleData> pdata,unsigned int Nmesh_x,unsigned int Nmesh_y,unsigned int Nmesh_z, unsigned int P_order, Scalar alpha,shared_ptr<FFTClass> FFTW,bool third_law_m)
{
return shared_ptr<ElectrostaticLongRangePPPM>(new ElectrostaticLongRangePPPM(pdata, Nmesh_x, Nmesh_y, Nmesh_z, P_order,alpha,FFTW,third_law_m));
}
//! boost test case for particle test on CPU
BOOST_AUTO_TEST_CASE(LongRangePPPM_PositionGrid_test)
{
LongRangePPPM_creator LongRangePPPM_creator_base = bind(base_class_PPPM_creator, _1, _2, _3, _4, _5,_6,_7,_8);
LongRangePPPM_PositionGrid(LongRangePPPM_creator_base);
}
#else
// We can't have the unit test passing if the code wasn't even compiled!
BOOST_AUTO_TEST_CASE(dummy_test)
{
BOOST_FAIL("ElectrostaticLongRange_PPPM not compiled");
}
#endif
#ifdef WIN32
#pragma warning( pop )
#endif
<commit_msg>back up of PPPM test, compiles but does not work yet ticket #79<commit_after>/*
Highly Optimized Object-Oriented Molecular Dynamics (HOOMD) Open
Source Software License
Copyright (c) 2008 Ames Laboratory Iowa State University
All rights reserved.
Redistribution and use of HOOMD, in source and binary forms, with or
without modification, are permitted, provided that the following
conditions are met:
* Redistributions of source code must retain the above copyright notice,
this list of conditions and the following disclaimer.
* Redistributions in binary form must reproduce the above copyright
notice, this list of conditions and the following disclaimer in the
documentation and/or other materials provided with the distribution.
* Neither the name of the copyright holder nor the names HOOMD's
contributors may be used to endorse or promote products derived from this
software without specific prior written permission.
Disclaimer
THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDER AND
CONTRIBUTORS ``AS IS'' AND ANY EXPRESS OR IMPLIED WARRANTIES,
INCLUDING, BUT NOT LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY
AND FITNESS FOR A PARTICULAR PURPOSE ARE DISCLAIMED.
IN NO EVENT SHALL THE COPYRIGHT HOLDER OR CONTRIBUTORS BE LIABLE
FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR
CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF
SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS
INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN
CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE)
ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF
THE POSSIBILITY OF SUCH DAMAGE.
*/
#ifdef WIN32
#pragma warning( push )
#pragma warning( disable : 4103 4244 )
#endif
#include <iostream>
//! Name the unit test module
#define BOOST_TEST_MODULE ElectrostaticLongRangePPPMTests
#include "boost_utf_configure.h"
#include <boost/test/floating_point_comparison.hpp>
#include <boost/bind.hpp>
#include <boost/function.hpp>
#include <boost/shared_ptr.hpp>
#include "ParticleData.h"
#include <math.h>
using namespace std;
using namespace boost;
//You need a fft defined in order to pass this text
#ifdef USE_FFTW
#include "ElectrostaticLongRangePPPM.h"
#include "FFTClass.h"
#include "FftwWrapper.h"
/*! \file ElectrostaticLongRange_PPPM_test.cc
\brief Implements unit tests for ElectrostaticLongRangePPPM and descendants
\ingroup unit_tests
*/
//! Helper macro for testing if two numbers are close
#define MY_BOOST_CHECK_CLOSE(a,b,c) BOOST_CHECK_CLOSE(a,Scalar(b),Scalar(c))
//! Helper macro for testing if a number is small
#define MY_BOOST_CHECK_SMALL(a,c) BOOST_CHECK_SMALL(a,Scalar(c))
//! Tolerance in percent to use for comparing various ElectrostaticLongRangePPPM to each other
const Scalar tol = Scalar(1);
//! minimum force worth computing
const Scalar MIN_force=Scalar(1.0e-9);
//! Typedef ElectrostaticLongRangePPPM factory
typedef function<shared_ptr<ElectrostaticLongRangePPPM> (shared_ptr<ParticleData> pdata,unsigned int Mmesh_x,unsigned int Mmesh_y,unsigned int Mmesh_z, unsigned int P_order_a, Scalar alpha, shared_ptr<FFTClass> FFTP,bool third_law_m)> LongRangePPPM_creator;
//! Test the ability of the Short Range Electrostatic force compute to actually calculate forces
/*! \param LongRangePPPM_object_n1 I have no idea: the write of this code needs to document it better
\note With the creator as a parameter, the same code can be used to test any derived child
of ElectrostaticLongRangePPPM
*/
void LongRangePPPM_PositionGrid(LongRangePPPM_creator LongRangePPPM_object_n1)
{
cout << "Testing charge distribution on the grid in class ElectrostaticLongRangePPPM" << endl;
// Simple test to check that the charge is defined correctly on the grid
shared_ptr<ParticleData> pdata_6(new ParticleData(6, BoxDim(20.0,40.0,60.0), 1));
ParticleDataArrays arrays = pdata_6->acquireReadWrite();
// six charges are located near the edge of the box
arrays.x[0]=Scalar(-9.6);arrays.y[0]=Scalar(0.0);arrays.z[0]=Scalar(0.0);arrays.charge[0]=1.0;
arrays.x[1]=Scalar(9.6);arrays.y[1]=Scalar(0.0);arrays.z[1]=Scalar(0.0);arrays.charge[1]=-2.0;
arrays.x[2]=Scalar(0.0);arrays.y[2]=Scalar(-19.5);arrays.z[2]=Scalar(0.0);arrays.charge[2]=1.0;
arrays.x[3]=Scalar(0.0);arrays.y[3]=Scalar(19.5);arrays.z[3]=Scalar(0.0);arrays.charge[3]=3.0;
arrays.x[4]=Scalar(0.0);arrays.y[4]=Scalar(0.0);arrays.z[4]=Scalar(-29.4);arrays.charge[4]=-1.0;
arrays.x[5]=Scalar(0.0);arrays.y[5]=Scalar(0.0);arrays.z[5]=Scalar(29.4);arrays.charge[5]=-2.0;
// allow for acquiring data in the future
pdata_6->release();
// Define mesh parameters as well as order of the distribution, etc..
unsigned int Nmesh_x=40;
unsigned int Nmesh_y=80;
unsigned int Nmesh_z=120;
unsigned int P_order=6;
Scalar alpha=4.0;
shared_ptr<FftwWrapper> FFTW(new FftwWrapper(Nmesh_x,Nmesh_y,Nmesh_z));
bool third_law=false;
//shared_ptr<ElectrostaticLongRangePPPM> PPPM_6=LongRangePPPM_object_n1(pdata_6,Nmesh_x,Nmesh_y,Nmesh_z,P_order,alpha,FFTW,third_law);
// An ElectrostaticLongRangePPPM object with specified value of grid parameters, alpha, and fft routine instantiated
// now let us check that the charges are correctly distributed
//First check that the polynomials used to spread the charge on the grid are what they should be
//This may eliminate unpleasant bugs
//The values of the coefficents are taken from Appendix E in the Deserno and Holm paper
Scalar **Exact=new Scalar*[P_order];
for(unsigned int i=0;i<P_order;i++) Exact[i]=new Scalar[P_order];
Exact[0][0]=1.0;Exact[0][1]=-10.0;Exact[0][2]=40.0;Exact[0][3]=-80.0;Exact[0][4]=80.0;Exact[0][5]=-32.0;
Exact[1][0]=237.0;Exact[1][1]=-750.0;Exact[1][2]=840.0;Exact[1][3]=-240.0;Exact[1][4]=-240.0;Exact[1][5]=160.0;
Exact[2][0]=1682.0;Exact[2][1]=-1540.0;Exact[2][2]=-880.0;Exact[2][3]=1120.0;Exact[2][4]=160.0;Exact[2][5]=-320.0;
Exact[3][0]=1682.0;Exact[3][1]=1540.0;Exact[3][2]=880.0;Exact[3][3]=-1120.0;Exact[3][4]=-160.0;Exact[3][5]=320.0;
Exact[4][0]=237.0;Exact[4][1]=750.0;Exact[4][2]=840.0;Exact[4][3]=240.0;Exact[4][4]=-240.0;Exact[4][5]=-160.0;
Exact[5][0]=1.0;Exact[5][1]=10.0;Exact[5][2]=40.0;Exact[5][3]=80.0;Exact[5][4]=80.0;Exact[5][5]=32.0;
for(unsigned int i=0;i<P_order;i++){
for(unsigned int j=0;j<P_order;j++){
Exact[i][j]*=static_cast<Scalar>(1/3840.0);
}
}
for(unsigned int i=0;i<P_order;i++){
for(unsigned int j=0;j<P_order;j++){
//MY_BOOST_CHECK_CLOSE(Exact[i][j],PPPM_6->Poly_coeff_Grid(i,j),tol);
}
}
//Check passed, now let us compute the charges on the grid
for(unsigned int i=0;i<P_order;i++) delete[] Exact[i];
delete [] Exact;
}
//! ElectrostaticShortRange creator for unit tests
shared_ptr<ElectrostaticLongRangePPPM> base_class_PPPM_creator(shared_ptr<ParticleData> pdata,unsigned int Nmesh_x,unsigned int Nmesh_y,unsigned int Nmesh_z, unsigned int P_order, Scalar alpha,shared_ptr<FFTClass> FFTW,bool third_law_m)
{
return shared_ptr<ElectrostaticLongRangePPPM>(new ElectrostaticLongRangePPPM(pdata, Nmesh_x, Nmesh_y, Nmesh_z, P_order,alpha,FFTW,third_law_m));
}
//! boost test case for particle test on CPU
BOOST_AUTO_TEST_CASE(LongRangePPPM_PositionGrid_test)
{
LongRangePPPM_creator LongRangePPPM_creator_base = bind(base_class_PPPM_creator, _1, _2, _3, _4, _5,_6,_7,_8);
LongRangePPPM_PositionGrid(LongRangePPPM_creator_base);
}
#else
// We can't have the unit test passing if the code wasn't even compiled!
BOOST_AUTO_TEST_CASE(dummy_test)
{
BOOST_FAIL("ElectrostaticLongRange_PPPM not compiled");
}
#endif
#ifdef WIN32
#pragma warning( pop )
#endif
<|endoftext|>
|
<commit_before>#include <iostream>
#include <string>
#include <vector>
#include "../../include/ktt.h"
int main(int argc, char** argv)
{
// Initialize platform and device index
size_t platformIndex = 0;
size_t deviceIndex = 0;
if (argc >= 2)
{
platformIndex = std::stoul(std::string{ argv[1] });
if (argc >= 3)
{
deviceIndex = std::stoul(std::string{ argv[2] });
}
}
// Declare kernel parameters
const std::string kernelFile = std::string("../examples/coulomb_sum_3d/coulomb_kernel_3d.cl");
const std::string referenceKernelFile = std::string("../examples/coulomb_sum_3d/coulomb_kernel_3d_reference.cl");
const int gridSize = 128;
const int atoms = 4000;
ktt::DimensionVector ndRangeDimensions(gridSize, gridSize, gridSize);
ktt::DimensionVector workGroupDimensions(1, 1, 1);
ktt::DimensionVector referenceWorkGroupDimensions(16, 16, 1);
// Declare data variables
float gridSpacing;
std::vector<float> atomInfoX(atoms);
std::vector<float> atomInfoY(atoms);
std::vector<float> atomInfoZ(atoms);
std::vector<float> atomInfoW(atoms);
std::vector<float> atomInfo(atoms*4);
std::vector<float> energyGrid(gridSize*gridSize*gridSize, 0.0f);
// Initialize data
gridSpacing = 0.5; // in Angstroms
for (int i = 0; i < atoms; i++)
{
atomInfoX.at(i) = static_cast<float>((float)rand() / (RAND_MAX/20));
atomInfoY.at(i) = static_cast<float>((float)rand() / (RAND_MAX/20));
atomInfoZ.at(i) = static_cast<float>((float)rand() / (RAND_MAX/20));
atomInfoW.at(i) = static_cast<float>((float)rand() / (RAND_MAX/20));
atomInfo.at(i*4) = atomInfoX.at(i);
atomInfo.at(i*4+1) = atomInfoY.at(i);
atomInfo.at(i*4+2) = atomInfoZ.at(i);
atomInfo.at(i*4+3) = atomInfoW.at(i);
}
ktt::Tuner tuner(platformIndex, deviceIndex);
size_t kernelId = tuner.addKernelFromFile(kernelFile, std::string("directCoulombSum"), ndRangeDimensions, workGroupDimensions);
size_t referenceKernelId = tuner.addKernelFromFile(referenceKernelFile, std::string("directCoulombSumReference"), ndRangeDimensions, referenceWorkGroupDimensions);
size_t aiId = tuner.addArgument(atomInfo, ktt::ArgumentMemoryType::ReadOnly);
size_t aixId = tuner.addArgument(atomInfoX, ktt::ArgumentMemoryType::ReadOnly);
size_t aiyId = tuner.addArgument(atomInfoY, ktt::ArgumentMemoryType::ReadOnly);
size_t aizId = tuner.addArgument(atomInfoZ, ktt::ArgumentMemoryType::ReadOnly);
size_t aiwId = tuner.addArgument(atomInfoW, ktt::ArgumentMemoryType::ReadOnly);
size_t aId = tuner.addArgument(atoms);
size_t gsId = tuner.addArgument(gridSpacing);
size_t gridId = tuner.addArgument(energyGrid, ktt::ArgumentMemoryType::WriteOnly);
tuner.addParameter(kernelId, "WORK_GROUP_SIZE_X", { 16, 32 },
ktt::ThreadModifierType::Local,
ktt::ThreadModifierAction::Multiply,
ktt::Dimension::X);
tuner.addParameter(kernelId, "WORK_GROUP_SIZE_Y", { 1, 2, 4, 8 },
ktt::ThreadModifierType::Local,
ktt::ThreadModifierAction::Multiply,
ktt::Dimension::Y);
tuner.addParameter(kernelId, "WORK_GROUP_SIZE_Z", { 1 });
tuner.addParameter(kernelId, "Z_ITERATIONS", { 1, 2, 4, 8, 16, 32 },
ktt::ThreadModifierType::Global,
ktt::ThreadModifierAction::Divide,
ktt::Dimension::Z);
tuner.addParameter(kernelId, "INNER_UNROLL_FACTOR", { 0, 1, 2, 4, 8, 16, 32 });
tuner.addParameter(kernelId, "USE_CONSTANT_MEMORY", { 0, 1 });
tuner.addParameter(kernelId, "USE_SOA", { 0, 1 });
tuner.addParameter(kernelId, "VECTOR_SIZE", { 1, 2 , 4, 8, 16 });
tuner.addParameter(kernelId, "ONE", { 1 }); //XXX helper, must be always
auto lt = [](std::vector<size_t> vector) { return vector.at(0) < vector.at(1); };
tuner.addConstraint(kernelId, lt, { "INNER_UNROLL_FACTOR", "Z_ITERATIONS" } );
auto vec = [](std::vector<size_t> vector) { return vector.at(0) || vector.at(1) == 1; };
tuner.addConstraint(kernelId, vec, { "USE_SOA", "VECTOR_SIZE" } );
tuner.setKernelArguments(kernelId, std::vector<size_t>{ aiId, aixId, aiyId, aizId, aiwId, aId, gsId, gridId });
tuner.setKernelArguments(referenceKernelId, std::vector<size_t>{ aiId, aixId, aiyId, aizId, aiwId, aId, gsId, gridId });
tuner.setReferenceKernel(kernelId, referenceKernelId, std::vector<ktt::ParameterValue>{}, std::vector<size_t>{ gridId });
tuner.setValidationMethod(ktt::ValidationMethod::SideBySideComparison, 0.1);
tuner.setSearchMethod(kernelId, ktt::SearchMethod::RandomSearch, std::vector<double> { 0.1 });
tuner.tuneKernel(kernelId);
tuner.printResult(kernelId, std::cout, ktt::PrintFormat::Verbose);
tuner.printResult(kernelId, std::string("output.csv"), ktt::PrintFormat::CSV);
return 0;
}
<commit_msg>Revert "bugfix in argument handling"<commit_after>#include <iostream>
#include <string>
#include <vector>
#include "../../include/ktt.h"
int main(int argc, char** argv)
{
// Initialize platform and device index
size_t platformIndex = 0;
size_t deviceIndex = 0;
if (argc >= 2)
{
platformIndex = std::stoul(std::string{ argv[1] });
if (argc >= 3)
{
deviceIndex = std::stoul(std::string{ argv[2] });
}
}
// Declare kernel parameters
const std::string kernelFile = std::string("../examples/coulomb_sum_3d/coulomb_kernel_3d.cl");
const std::string referenceKernelFile = std::string("../examples/coulomb_sum_3d/coulomb_kernel_3d_reference.cl");
const int gridSize = 128;
const int atoms = 4000;
ktt::DimensionVector ndRangeDimensions(gridSize, gridSize, gridSize);
ktt::DimensionVector workGroupDimensions(1, 1, 1);
ktt::DimensionVector referenceWorkGroupDimensions(16, 16, 1);
// Declare data variables
float gridSpacing;
std::vector<float> atomInfoX(atoms);
std::vector<float> atomInfoY(atoms);
std::vector<float> atomInfoZ(atoms);
std::vector<float> atomInfoW(atoms);
std::vector<float> atomInfo(atoms*4);
std::vector<float> energyGrid(gridSize*gridSize*gridSize, 0.0f);
// Initialize data
gridSpacing = 0.5; // in Angstroms
for (int i = 0; i < atoms; i++)
{
atomInfoX.at(i) = static_cast<float>((float)rand() / (RAND_MAX/20));
atomInfoY.at(i) = static_cast<float>((float)rand() / (RAND_MAX/20));
atomInfoZ.at(i) = static_cast<float>((float)rand() / (RAND_MAX/20));
atomInfoW.at(i) = static_cast<float>((float)rand() / (RAND_MAX/20));
atomInfo.at(i*4) = atomInfoX.at(i);
atomInfo.at(i*4+1) = atomInfoY.at(i);
atomInfo.at(i*4+2) = atomInfoZ.at(i);
atomInfo.at(i*4+3) = atomInfoW.at(i);
}
ktt::Tuner tuner(platformIndex, deviceIndex);
size_t kernelId = tuner.addKernelFromFile(kernelFile, std::string("directCoulombSum"), ndRangeDimensions, workGroupDimensions);
size_t referenceKernelId = tuner.addKernelFromFile(referenceKernelFile, std::string("directCoulombSumReference"), ndRangeDimensions, referenceWorkGroupDimensions);
size_t aiId = tuner.addArgument(atomInfo, ktt::ArgumentMemoryType::ReadOnly);
size_t aixId = tuner.addArgument(atomInfoX, ktt::ArgumentMemoryType::ReadOnly);
size_t aiyId = tuner.addArgument(atomInfoY, ktt::ArgumentMemoryType::ReadOnly);
size_t aizId = tuner.addArgument(atomInfoZ, ktt::ArgumentMemoryType::ReadOnly);
size_t aiwId = tuner.addArgument(atomInfoW, ktt::ArgumentMemoryType::ReadOnly);
size_t aId = tuner.addArgument(atoms);
size_t gsId = tuner.addArgument(gridSpacing);
size_t gridId = tuner.addArgument(atomInfoW, ktt::ArgumentMemoryType::WriteOnly);
tuner.addParameter(kernelId, "WORK_GROUP_SIZE_X", { 16, 32 },
ktt::ThreadModifierType::Local,
ktt::ThreadModifierAction::Multiply,
ktt::Dimension::X);
tuner.addParameter(kernelId, "WORK_GROUP_SIZE_Y", { 1, 2, 4, 8 },
ktt::ThreadModifierType::Local,
ktt::ThreadModifierAction::Multiply,
ktt::Dimension::Y);
tuner.addParameter(kernelId, "WORK_GROUP_SIZE_Z", { 1 });
tuner.addParameter(kernelId, "Z_ITERATIONS", { 1, 2, 4, 8, 16, 32 },
ktt::ThreadModifierType::Global,
ktt::ThreadModifierAction::Divide,
ktt::Dimension::Z);
tuner.addParameter(kernelId, "INNER_UNROLL_FACTOR", { 0, 1, 2, 4, 8, 16, 32 });
tuner.addParameter(kernelId, "USE_CONSTANT_MEMORY", { 0, 1 });
tuner.addParameter(kernelId, "USE_SOA", { 0, 1 });
tuner.addParameter(kernelId, "VECTOR_SIZE", { 1, 2 , 4, 8, 16 });
tuner.addParameter(kernelId, "ONE", { 1 }); //XXX helper, must be always
auto lt = [](std::vector<size_t> vector) { return vector.at(0) < vector.at(1); };
tuner.addConstraint(kernelId, lt, { "INNER_UNROLL_FACTOR", "Z_ITERATIONS" } );
auto vec = [](std::vector<size_t> vector) { return vector.at(0) || vector.at(1) == 1; };
tuner.addConstraint(kernelId, vec, { "USE_SOA", "VECTOR_SIZE" } );
tuner.setKernelArguments(kernelId, std::vector<size_t>{ aiId, aixId, aiyId, aizId, aiwId, aId, gsId, gridId });
tuner.setKernelArguments(referenceKernelId, std::vector<size_t>{ aiId, aixId, aiyId, aizId, aiwId, aId, gsId, gridId });
tuner.setReferenceKernel(kernelId, referenceKernelId, std::vector<ktt::ParameterValue>{}, std::vector<size_t>{ gridId });
tuner.setValidationMethod(ktt::ValidationMethod::SideBySideComparison, 0.1);
tuner.setSearchMethod(kernelId, ktt::SearchMethod::RandomSearch, std::vector<double> { 0.1 });
tuner.tuneKernel(kernelId);
tuner.printResult(kernelId, std::cout, ktt::PrintFormat::Verbose);
tuner.printResult(kernelId, std::string("output.csv"), ktt::PrintFormat::CSV);
return 0;
}
<|endoftext|>
|
<commit_before>/******************************************************************************
* SOFA, Simulation Open-Framework Architecture, version 1.0 beta 4 *
* (c) 2006-2009 MGH, INRIA, USTL, UJF, CNRS *
* *
* This library is free software; you can redistribute it and/or modify it *
* under the terms of the GNU Lesser General Public License as published by *
* the Free Software Foundation; either version 2.1 of the License, or (at *
* your option) any later version. *
* *
* This library is distributed in the hope that it will be useful, but WITHOUT *
* ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or *
* FITNESS FOR A PARTICULAR PURPOSE. See the GNU Lesser General Public License *
* for more details. *
* *
* You should have received a copy of the GNU Lesser General Public License *
* along with this library; if not, write to the Free Software Foundation, *
* Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA. *
*******************************************************************************
* SOFA :: Modules *
* *
* Authors: The SOFA Team and external contributors (see Authors.txt) *
* *
* Contact information: contact@sofa-framework.org *
******************************************************************************/
#define SOFA_COMPONENT_CONSTRAINTSET_PRECOMPUTEDCONSTRAINTCORRECTION_CPP
#include "PrecomputedConstraintCorrection.inl"
#include <sofa/defaulttype/Vec3Types.h>
#include <sofa/core/ObjectFactory.h>
namespace sofa
{
namespace component
{
namespace constraintset
{
#ifndef SOFA_FLOAT
template<>
SOFA_COMPONENT_CONSTRAINTSET_API void PrecomputedConstraintCorrection<defaulttype::Vec3dTypes>::draw()
{
if (!getContext()->getShowBehaviorModels() || !m_rotations.getValue()) return;
// we draw the rotations associated to each node //
simulation::Node *node = dynamic_cast<simulation::Node *>(getContext());
sofa::component::forcefield::TetrahedronFEMForceField<defaulttype::Vec3dTypes>* forceField = NULL;
sofa::component::container::RotationFinder<defaulttype::Vec3dTypes>* rotationFinder = NULL;
if (node != NULL)
{
// core::behavior::BaseForceField* _forceField = node->forceField[1];
forceField = node->get<component::forcefield::TetrahedronFEMForceField<defaulttype::Vec3dTypes> > ();
if (forceField == NULL)
{
rotationFinder = node->get<component::container::RotationFinder<defaulttype::Vec3dTypes> > ();
if (rotationFinder == NULL)
{
sout << "No rotation defined : only defined for TetrahedronFEMForceField and RotationFinder!";
return;
}
}
}
VecCoord& x = *mstate->getX();
for (unsigned int i=0; i< x.size(); i++)
{
Transformation Ri;
if (forceField != NULL)
{
forceField->getRotation(Ri, i);
}
else // rotationFinder has been defined
{
Ri = rotationFinder->getRotations()[i];
}
sofa::defaulttype::Matrix3 RotMat;
for (unsigned int a=0; a<3; a++)
{
for (unsigned int b=0; b<3; b++)
{
RotMat[a][b] = Ri(a,b);
}
}
sofa::defaulttype::Quat q;
q.fromMatrix(RotMat);
helper::gl::Axis::draw(x[i], q , this->debugViewFrameScale.getValue());
}
}
template<>
SOFA_COMPONENT_CONSTRAINTSET_API void PrecomputedConstraintCorrection<defaulttype::Rigid3dTypes>::rotateConstraints(bool back)
{
VecCoord& x = *mstate->getX();
VecConst& constraints = *mstate->getC();
VecCoord& x0 = *mstate->getX0();
unsigned int numConstraints = constraints.size();
// int sizemax=0;
// int index_const = -1;
// on fait tourner les normales (en les ramenant dans le "pseudo" repere initial) //
for(unsigned int curRowConst = 0; curRowConst < numConstraints; curRowConst++)
{
ConstraintIterator itConstraint;
std::pair< ConstraintIterator, ConstraintIterator > iter=constraints[curRowConst].data();
for (itConstraint=iter.first; itConstraint!=iter.second; itConstraint++)
{
unsigned int dof = itConstraint->first;
Deriv& n = itConstraint->second;
const int localRowNodeIdx = dof;
Quat q;
if (m_restRotations.getValue())
q = x[localRowNodeIdx].getOrientation() * x0[localRowNodeIdx].getOrientation().inverse();
else
q = x[localRowNodeIdx].getOrientation();
Vec3d n_i = q.inverseRotate(n.getVCenter());
Vec3d wn_i= q.inverseRotate(n.getVOrientation());
if(back)
{
n_i = q.rotate(n.getVCenter());
wn_i= q.rotate(n.getVOrientation());
}
// on passe les normales du repere global au repere local
n.getVCenter() = n_i;
n.getVOrientation() = wn_i;
}
}
}
template<>
SOFA_COMPONENT_CONSTRAINTSET_API void PrecomputedConstraintCorrection<defaulttype::Vec1dTypes>::rotateConstraints(bool /*back*/)
{
}
template<>
SOFA_COMPONENT_CONSTRAINTSET_API void PrecomputedConstraintCorrection<defaulttype::Rigid3dTypes>::rotateResponse()
{
VecDeriv& dx = *mstate->getDx();
VecCoord& x = *mstate->getX();
VecCoord& x0 = *mstate->getX0();
for(unsigned int j = 0; j < dx.size(); j++)
{
// on passe les deplacements du repere local (au repos) au repere global
Deriv temp ;
Quat q;
if (m_restRotations.getValue())
q = x[j].getOrientation() * x0[j].getOrientation().inverse();
else
q = x[j].getOrientation();
temp.getVCenter() = q.rotate(dx[j].getVCenter());
temp.getVOrientation() = q.rotate(dx[j].getVOrientation());
dx[j] = temp;
}
}
template<>
SOFA_COMPONENT_CONSTRAINTSET_API void PrecomputedConstraintCorrection<defaulttype::Vec1dTypes>::rotateResponse()
{
}
#endif
#ifndef SOFA_DOUBLE
template<>
SOFA_COMPONENT_CONSTRAINTSET_API void PrecomputedConstraintCorrection<defaulttype::Vec3fTypes>::rotateConstraints(bool back)
{
VecConst& constraints = *mstate->getC();
unsigned int numConstraints = constraints.size();
simulation::Node *node = dynamic_cast<simulation::Node *>(getContext());
sofa::component::forcefield::TetrahedronFEMForceField<defaulttype::Vec3fTypes>* forceField = NULL;
sofa::component::container::RotationFinder<defaulttype::Vec3fTypes>* rotationFinder = NULL;
if (node != NULL)
{
forceField = node->get<component::forcefield::TetrahedronFEMForceField<defaulttype::Vec3fTypes> > ();
if (forceField == NULL)
{
rotationFinder = node->get<component::container::RotationFinder<defaulttype::Vec3fTypes> > ();
if (rotationFinder == NULL)
{
sout << "No rotation defined : only defined for TetrahedronFEMForceField and RotationFinder!";
return;
}
}
}
else
{
sout << "Error getting context in method: PrecomputedConstraintCorrection<defaulttype::Vec3dTypes>::rotateConstraints()";
return;
}
//sout << "start rotating normals " << g_timer_elapsed(timer, µ) << sendl;
// int sizemax=0;
// int index_const = -1;
// on fait tourner les normales (en les ramenant dans le "pseudo" repere initial) //
for(unsigned int curRowConst = 0; curRowConst < numConstraints; curRowConst++)
{
ConstraintIterator itConstraint;
std::pair< ConstraintIterator, ConstraintIterator > iter=constraints[curRowConst].data();
for (itConstraint=iter.first; itConstraint!=iter.second; itConstraint++)
{
unsigned int dof = itConstraint->first;
Deriv& n = itConstraint->second;
const int localRowNodeIdx = dof;
Transformation Ri;
if (forceField != NULL)
{
forceField->getRotation(Ri, localRowNodeIdx);
}
else // rotationFinder has been defined
{
Ri = rotationFinder->getRotations()[localRowNodeIdx];
}
if(!back)
Ri.transpose();
// on passe les normales du repere global au repere local
Deriv n_i = Ri * n;
n.x() = n_i.x();
n.y() = n_i.y();
n.z() = n_i.z();
}
/*
// test pour voir si on peut reduire le nombre de contrainte
if (sizeCurRowConst > sizemax)
{
sizemax = sizeCurRowConst;
index_const = curRowConst;
}
*/
}
}
template<>
SOFA_COMPONENT_CONSTRAINTSET_API void PrecomputedConstraintCorrection<defaulttype::Rigid3fTypes>::rotateConstraints(bool back)
{
VecCoord& x = *mstate->getX();
VecConst& constraints = *mstate->getC();
VecCoord& x0 = *mstate->getX0();
unsigned int numConstraints = constraints.size();
// int sizemax=0;
// int index_const = -1;
// on fait tourner les normales (en les ramenant dans le "pseudo" repere initial) //
for(unsigned int curRowConst = 0; curRowConst < numConstraints; curRowConst++)
{
ConstraintIterator itConstraint;
std::pair< ConstraintIterator, ConstraintIterator > iter=constraints[curRowConst].data();
for (itConstraint=iter.first; itConstraint!=iter.second; itConstraint++)
{
unsigned int dof = itConstraint->first;
Deriv& n = itConstraint->second;
const int localRowNodeIdx = dof;
Quat q;
if (m_restRotations)
q = x[localRowNodeIdx].getOrientation() * x0[localRowNodeIdx].getOrientation().inverse();
else
q = x[localRowNodeIdx].getOrientation();
Vec3d n_i = q.inverseRotate(n.getVCenter());
Vec3d wn_i= q.inverseRotate(n.getVOrientation());
if(back)
{
n_i = q.rotate(n.getVCenter());
wn_i= q.rotate(n.getVOrientation());
}
// on passe les normales du repere global au repere local
n.getVCenter() = n_i;
n.getVOrientation() = wn_i;
}
}
}
template<>
SOFA_COMPONENT_CONSTRAINTSET_API void PrecomputedConstraintCorrection<defaulttype::Vec1fTypes>::rotateConstraints(bool /*back*/)
{
}
template<>
SOFA_COMPONENT_CONSTRAINTSET_API void PrecomputedConstraintCorrection<defaulttype::Vec3fTypes>::rotateResponse()
{
simulation::Node *node = dynamic_cast<simulation::Node *>(getContext());
sofa::component::forcefield::TetrahedronFEMForceField<defaulttype::Vec3fTypes>* forceField = NULL;
sofa::component::container::RotationFinder<defaulttype::Vec3fTypes>* rotationFinder = NULL;
if (node != NULL)
{
// core::behavior::BaseForceField* _forceField = node->forceField[1];
forceField = node->get<component::forcefield::TetrahedronFEMForceField<defaulttype::Vec3fTypes> > ();
if (forceField == NULL)
{
rotationFinder = node->get<component::container::RotationFinder<defaulttype::Vec3fTypes> > ();
if (rotationFinder == NULL)
{
sout << "No rotation defined : only defined for TetrahedronFEMForceField and RotationFinder!";
return;
}
}
}
else
{
sout << "Error getting context in method: PrecomputedConstraintCorrection<defaulttype::Vec3dTypes>::rotateConstraints()";
return;
}
VecDeriv& dx = *mstate->getDx();
for(unsigned int j = 0; j < dx.size(); j++)
{
Transformation Rj;
if (forceField != NULL)
{
forceField->getRotation(Rj, j);
}
else // rotationFinder has been defined
{
Rj = rotationFinder->getRotations()[j];
}
// on passe les deplacements du repere local au repere global
const Deriv& temp = Rj * dx[j];
dx[j] = temp;
}
}
template<>
SOFA_COMPONENT_CONSTRAINTSET_API void PrecomputedConstraintCorrection<defaulttype::Rigid3fTypes>::rotateResponse()
{
VecDeriv& dx = *mstate->getDx();
VecCoord& x = *mstate->getX();
VecCoord& x0 = *mstate->getX0();
for(unsigned int j = 0; j < dx.size(); j++)
{
// on passe les deplacements du repere local (au repos) au repere global
Deriv temp ;
Quat q;
if (m_restRotations)
q = x[j].getOrientation() * x0[j].getOrientation().inverse();
else
q = x[j].getOrientation();
temp.getVCenter() = q.rotate(dx[j].getVCenter());
temp.getVOrientation() = q.rotate(dx[j].getVOrientation());
dx[j] = temp;
}
}
template<>
SOFA_COMPONENT_CONSTRAINTSET_API void PrecomputedConstraintCorrection<defaulttype::Vec1fTypes>::rotateResponse()
{
}
#endif
using namespace sofa::defaulttype;
SOFA_DECL_CLASS(PrecomputedConstraintCorrection)
int PrecomputedConstraintCorrectionClass = core::RegisterObject("Component computing contact forces within a simulated body using the compliance method.")
#ifndef SOFA_FLOAT
.add< PrecomputedConstraintCorrection<Vec3dTypes> >()
// .add< PrecomputedConstraintCorrection<Vec2dTypes> >()
.add< PrecomputedConstraintCorrection<Vec1dTypes> >()
.add< PrecomputedConstraintCorrection<Rigid3dTypes> >()
#endif
#ifndef SOFA_DOUBLE
.add< PrecomputedConstraintCorrection<Vec3fTypes> >()
// .add< PrecomputedConstraintCorrection<Vec2fTypes> >()
.add< PrecomputedConstraintCorrection<Vec1fTypes> >()
.add< PrecomputedConstraintCorrection<Rigid3fTypes> >()
#endif
;
#ifndef SOFA_FLOAT
template class SOFA_COMPONENT_CONSTRAINTSET_API PrecomputedConstraintCorrection<Vec3dTypes>;
//template class SOFA_COMPONENT_CONSTRAINTSET_API PrecomputedConstraintCorrection<Vec2dTypes>;
template class SOFA_COMPONENT_CONSTRAINTSET_API PrecomputedConstraintCorrection<Vec1dTypes>;
//template class SOFA_COMPONENT_CONSTRAINTSET_API PrecomputedConstraintCorrection<Vec6dTypes>;
template class SOFA_COMPONENT_CONSTRAINTSET_API PrecomputedConstraintCorrection<Rigid3dTypes>;
//template class SOFA_COMPONENT_CONSTRAINTSET_API PrecomputedConstraintCorrection<Rigid2dTypes>;
#endif
#ifndef SOFA_DOUBLE
template class SOFA_COMPONENT_CONSTRAINTSET_API PrecomputedConstraintCorrection<Vec3fTypes>;
//template class SOFA_COMPONENT_CONSTRAINTSET_API PrecomputedConstraintCorrection<Vec2fTypes>;
template class SOFA_COMPONENT_CONSTRAINTSET_API PrecomputedConstraintCorrection<Vec1fTypes>;
//template class SOFA_COMPONENT_CONSTRAINTSET_API PrecomputedConstraintCorrection<Vec6fTypes>;
template class SOFA_COMPONENT_CONSTRAINTSET_API PrecomputedConstraintCorrection<Rigid3fTypes>;
//template class SOFA_COMPONENT_CONSTRAINTSET_API PrecomputedConstraintCorrection<Rigid2fTypes>;
#endif
} // namespace collision
} // namespace component
} // namespace sofa
<commit_msg>r7900/sofa-dev : FIX : Forgotten modifications.<commit_after>/******************************************************************************
* SOFA, Simulation Open-Framework Architecture, version 1.0 beta 4 *
* (c) 2006-2009 MGH, INRIA, USTL, UJF, CNRS *
* *
* This library is free software; you can redistribute it and/or modify it *
* under the terms of the GNU Lesser General Public License as published by *
* the Free Software Foundation; either version 2.1 of the License, or (at *
* your option) any later version. *
* *
* This library is distributed in the hope that it will be useful, but WITHOUT *
* ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or *
* FITNESS FOR A PARTICULAR PURPOSE. See the GNU Lesser General Public License *
* for more details. *
* *
* You should have received a copy of the GNU Lesser General Public License *
* along with this library; if not, write to the Free Software Foundation, *
* Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA. *
*******************************************************************************
* SOFA :: Modules *
* *
* Authors: The SOFA Team and external contributors (see Authors.txt) *
* *
* Contact information: contact@sofa-framework.org *
******************************************************************************/
#define SOFA_COMPONENT_CONSTRAINTSET_PRECOMPUTEDCONSTRAINTCORRECTION_CPP
#include "PrecomputedConstraintCorrection.inl"
#include <sofa/defaulttype/Vec3Types.h>
#include <sofa/core/ObjectFactory.h>
namespace sofa
{
namespace component
{
namespace constraintset
{
#ifndef SOFA_FLOAT
template<>
SOFA_COMPONENT_CONSTRAINTSET_API void PrecomputedConstraintCorrection<defaulttype::Vec3dTypes>::draw()
{
if (!getContext()->getShowBehaviorModels() || !m_rotations.getValue()) return;
// we draw the rotations associated to each node //
simulation::Node *node = dynamic_cast<simulation::Node *>(getContext());
sofa::component::forcefield::TetrahedronFEMForceField<defaulttype::Vec3dTypes>* forceField = NULL;
sofa::component::container::RotationFinder<defaulttype::Vec3dTypes>* rotationFinder = NULL;
if (node != NULL)
{
// core::behavior::BaseForceField* _forceField = node->forceField[1];
forceField = node->get<component::forcefield::TetrahedronFEMForceField<defaulttype::Vec3dTypes> > ();
if (forceField == NULL)
{
rotationFinder = node->get<component::container::RotationFinder<defaulttype::Vec3dTypes> > ();
if (rotationFinder == NULL)
{
sout << "No rotation defined : only defined for TetrahedronFEMForceField and RotationFinder!";
return;
}
}
}
VecCoord& x = *mstate->getX();
for (unsigned int i=0; i< x.size(); i++)
{
Transformation Ri;
if (forceField != NULL)
{
forceField->getRotation(Ri, i);
}
else // rotationFinder has been defined
{
Ri = rotationFinder->getRotations()[i];
}
sofa::defaulttype::Matrix3 RotMat;
for (unsigned int a=0; a<3; a++)
{
for (unsigned int b=0; b<3; b++)
{
RotMat[a][b] = Ri(a,b);
}
}
sofa::defaulttype::Quat q;
q.fromMatrix(RotMat);
helper::gl::Axis::draw(x[i], q , this->debugViewFrameScale.getValue());
}
}
template<>
SOFA_COMPONENT_CONSTRAINTSET_API void PrecomputedConstraintCorrection<defaulttype::Rigid3dTypes>::rotateConstraints(bool back)
{
VecCoord& x = *mstate->getX();
VecConst& constraints = *mstate->getC();
VecCoord& x0 = *mstate->getX0();
unsigned int numConstraints = constraints.size();
// int sizemax=0;
// int index_const = -1;
// on fait tourner les normales (en les ramenant dans le "pseudo" repere initial) //
for(unsigned int curRowConst = 0; curRowConst < numConstraints; curRowConst++)
{
ConstraintIterator itConstraint;
std::pair< ConstraintIterator, ConstraintIterator > iter=constraints[curRowConst].data();
for (itConstraint=iter.first; itConstraint!=iter.second; itConstraint++)
{
unsigned int dof = itConstraint->first;
Deriv& n = itConstraint->second;
const int localRowNodeIdx = dof;
Quat q;
if (m_restRotations.getValue())
q = x[localRowNodeIdx].getOrientation() * x0[localRowNodeIdx].getOrientation().inverse();
else
q = x[localRowNodeIdx].getOrientation();
Vec3d n_i = q.inverseRotate(n.getVCenter());
Vec3d wn_i= q.inverseRotate(n.getVOrientation());
if(back)
{
n_i = q.rotate(n.getVCenter());
wn_i= q.rotate(n.getVOrientation());
}
// on passe les normales du repere global au repere local
n.getVCenter() = n_i;
n.getVOrientation() = wn_i;
}
}
}
template<>
SOFA_COMPONENT_CONSTRAINTSET_API void PrecomputedConstraintCorrection<defaulttype::Vec1dTypes>::rotateConstraints(bool /*back*/)
{
}
template<>
SOFA_COMPONENT_CONSTRAINTSET_API void PrecomputedConstraintCorrection<defaulttype::Rigid3dTypes>::rotateResponse()
{
VecDeriv& dx = *mstate->getDx();
VecCoord& x = *mstate->getX();
VecCoord& x0 = *mstate->getX0();
for(unsigned int j = 0; j < dx.size(); j++)
{
// on passe les deplacements du repere local (au repos) au repere global
Deriv temp ;
Quat q;
if (m_restRotations.getValue())
q = x[j].getOrientation() * x0[j].getOrientation().inverse();
else
q = x[j].getOrientation();
temp.getVCenter() = q.rotate(dx[j].getVCenter());
temp.getVOrientation() = q.rotate(dx[j].getVOrientation());
dx[j] = temp;
}
}
template<>
SOFA_COMPONENT_CONSTRAINTSET_API void PrecomputedConstraintCorrection<defaulttype::Vec1dTypes>::rotateResponse()
{
}
#endif
#ifndef SOFA_DOUBLE
template<>
SOFA_COMPONENT_CONSTRAINTSET_API void PrecomputedConstraintCorrection<defaulttype::Vec3fTypes>::rotateConstraints(bool back)
{
VecConst& constraints = *mstate->getC();
unsigned int numConstraints = constraints.size();
simulation::Node *node = dynamic_cast<simulation::Node *>(getContext());
sofa::component::forcefield::TetrahedronFEMForceField<defaulttype::Vec3fTypes>* forceField = NULL;
sofa::component::container::RotationFinder<defaulttype::Vec3fTypes>* rotationFinder = NULL;
if (node != NULL)
{
forceField = node->get<component::forcefield::TetrahedronFEMForceField<defaulttype::Vec3fTypes> > ();
if (forceField == NULL)
{
rotationFinder = node->get<component::container::RotationFinder<defaulttype::Vec3fTypes> > ();
if (rotationFinder == NULL)
{
sout << "No rotation defined : only defined for TetrahedronFEMForceField and RotationFinder!";
return;
}
}
}
else
{
sout << "Error getting context in method: PrecomputedConstraintCorrection<defaulttype::Vec3dTypes>::rotateConstraints()";
return;
}
//sout << "start rotating normals " << g_timer_elapsed(timer, µ) << sendl;
// int sizemax=0;
// int index_const = -1;
// on fait tourner les normales (en les ramenant dans le "pseudo" repere initial) //
for(unsigned int curRowConst = 0; curRowConst < numConstraints; curRowConst++)
{
ConstraintIterator itConstraint;
std::pair< ConstraintIterator, ConstraintIterator > iter=constraints[curRowConst].data();
for (itConstraint=iter.first; itConstraint!=iter.second; itConstraint++)
{
unsigned int dof = itConstraint->first;
Deriv& n = itConstraint->second;
const int localRowNodeIdx = dof;
Transformation Ri;
if (forceField != NULL)
{
forceField->getRotation(Ri, localRowNodeIdx);
}
else // rotationFinder has been defined
{
Ri = rotationFinder->getRotations()[localRowNodeIdx];
}
if(!back)
Ri.transpose();
// on passe les normales du repere global au repere local
Deriv n_i = Ri * n;
n.x() = n_i.x();
n.y() = n_i.y();
n.z() = n_i.z();
}
/*
// test pour voir si on peut reduire le nombre de contrainte
if (sizeCurRowConst > sizemax)
{
sizemax = sizeCurRowConst;
index_const = curRowConst;
}
*/
}
}
template<>
SOFA_COMPONENT_CONSTRAINTSET_API void PrecomputedConstraintCorrection<defaulttype::Rigid3fTypes>::rotateConstraints(bool back)
{
VecCoord& x = *mstate->getX();
VecConst& constraints = *mstate->getC();
VecCoord& x0 = *mstate->getX0();
unsigned int numConstraints = constraints.size();
// int sizemax=0;
// int index_const = -1;
// on fait tourner les normales (en les ramenant dans le "pseudo" repere initial) //
for(unsigned int curRowConst = 0; curRowConst < numConstraints; curRowConst++)
{
ConstraintIterator itConstraint;
std::pair< ConstraintIterator, ConstraintIterator > iter=constraints[curRowConst].data();
for (itConstraint=iter.first; itConstraint!=iter.second; itConstraint++)
{
unsigned int dof = itConstraint->first;
Deriv& n = itConstraint->second;
const int localRowNodeIdx = dof;
Quat q;
if (m_restRotations.getValue())
q = x[localRowNodeIdx].getOrientation() * x0[localRowNodeIdx].getOrientation().inverse();
else
q = x[localRowNodeIdx].getOrientation();
Vec3d n_i = q.inverseRotate(n.getVCenter());
Vec3d wn_i= q.inverseRotate(n.getVOrientation());
if(back)
{
n_i = q.rotate(n.getVCenter());
wn_i= q.rotate(n.getVOrientation());
}
// on passe les normales du repere global au repere local
n.getVCenter() = n_i;
n.getVOrientation() = wn_i;
}
}
}
template<>
SOFA_COMPONENT_CONSTRAINTSET_API void PrecomputedConstraintCorrection<defaulttype::Vec1fTypes>::rotateConstraints(bool /*back*/)
{
}
template<>
SOFA_COMPONENT_CONSTRAINTSET_API void PrecomputedConstraintCorrection<defaulttype::Vec3fTypes>::rotateResponse()
{
simulation::Node *node = dynamic_cast<simulation::Node *>(getContext());
sofa::component::forcefield::TetrahedronFEMForceField<defaulttype::Vec3fTypes>* forceField = NULL;
sofa::component::container::RotationFinder<defaulttype::Vec3fTypes>* rotationFinder = NULL;
if (node != NULL)
{
// core::behavior::BaseForceField* _forceField = node->forceField[1];
forceField = node->get<component::forcefield::TetrahedronFEMForceField<defaulttype::Vec3fTypes> > ();
if (forceField == NULL)
{
rotationFinder = node->get<component::container::RotationFinder<defaulttype::Vec3fTypes> > ();
if (rotationFinder == NULL)
{
sout << "No rotation defined : only defined for TetrahedronFEMForceField and RotationFinder!";
return;
}
}
}
else
{
sout << "Error getting context in method: PrecomputedConstraintCorrection<defaulttype::Vec3dTypes>::rotateConstraints()";
return;
}
VecDeriv& dx = *mstate->getDx();
for(unsigned int j = 0; j < dx.size(); j++)
{
Transformation Rj;
if (forceField != NULL)
{
forceField->getRotation(Rj, j);
}
else // rotationFinder has been defined
{
Rj = rotationFinder->getRotations()[j];
}
// on passe les deplacements du repere local au repere global
const Deriv& temp = Rj * dx[j];
dx[j] = temp;
}
}
template<>
SOFA_COMPONENT_CONSTRAINTSET_API void PrecomputedConstraintCorrection<defaulttype::Rigid3fTypes>::rotateResponse()
{
VecDeriv& dx = *mstate->getDx();
VecCoord& x = *mstate->getX();
VecCoord& x0 = *mstate->getX0();
for(unsigned int j = 0; j < dx.size(); j++)
{
// on passe les deplacements du repere local (au repos) au repere global
Deriv temp ;
Quat q;
if (m_restRotations.getValue())
q = x[j].getOrientation() * x0[j].getOrientation().inverse();
else
q = x[j].getOrientation();
temp.getVCenter() = q.rotate(dx[j].getVCenter());
temp.getVOrientation() = q.rotate(dx[j].getVOrientation());
dx[j] = temp;
}
}
template<>
SOFA_COMPONENT_CONSTRAINTSET_API void PrecomputedConstraintCorrection<defaulttype::Vec1fTypes>::rotateResponse()
{
}
#endif
using namespace sofa::defaulttype;
SOFA_DECL_CLASS(PrecomputedConstraintCorrection)
int PrecomputedConstraintCorrectionClass = core::RegisterObject("Component computing contact forces within a simulated body using the compliance method.")
#ifndef SOFA_FLOAT
.add< PrecomputedConstraintCorrection<Vec3dTypes> >()
// .add< PrecomputedConstraintCorrection<Vec2dTypes> >()
.add< PrecomputedConstraintCorrection<Vec1dTypes> >()
.add< PrecomputedConstraintCorrection<Rigid3dTypes> >()
#endif
#ifndef SOFA_DOUBLE
.add< PrecomputedConstraintCorrection<Vec3fTypes> >()
// .add< PrecomputedConstraintCorrection<Vec2fTypes> >()
.add< PrecomputedConstraintCorrection<Vec1fTypes> >()
.add< PrecomputedConstraintCorrection<Rigid3fTypes> >()
#endif
;
#ifndef SOFA_FLOAT
template class SOFA_COMPONENT_CONSTRAINTSET_API PrecomputedConstraintCorrection<Vec3dTypes>;
//template class SOFA_COMPONENT_CONSTRAINTSET_API PrecomputedConstraintCorrection<Vec2dTypes>;
template class SOFA_COMPONENT_CONSTRAINTSET_API PrecomputedConstraintCorrection<Vec1dTypes>;
//template class SOFA_COMPONENT_CONSTRAINTSET_API PrecomputedConstraintCorrection<Vec6dTypes>;
template class SOFA_COMPONENT_CONSTRAINTSET_API PrecomputedConstraintCorrection<Rigid3dTypes>;
//template class SOFA_COMPONENT_CONSTRAINTSET_API PrecomputedConstraintCorrection<Rigid2dTypes>;
#endif
#ifndef SOFA_DOUBLE
template class SOFA_COMPONENT_CONSTRAINTSET_API PrecomputedConstraintCorrection<Vec3fTypes>;
//template class SOFA_COMPONENT_CONSTRAINTSET_API PrecomputedConstraintCorrection<Vec2fTypes>;
template class SOFA_COMPONENT_CONSTRAINTSET_API PrecomputedConstraintCorrection<Vec1fTypes>;
//template class SOFA_COMPONENT_CONSTRAINTSET_API PrecomputedConstraintCorrection<Vec6fTypes>;
template class SOFA_COMPONENT_CONSTRAINTSET_API PrecomputedConstraintCorrection<Rigid3fTypes>;
//template class SOFA_COMPONENT_CONSTRAINTSET_API PrecomputedConstraintCorrection<Rigid2fTypes>;
#endif
} // namespace collision
} // namespace component
} // namespace sofa
<|endoftext|>
|
<commit_before>#include "asocket.h"
// C++
#include <cassert>
#include <cstring>
#include <cstdint>
// STL
#include <iostream>
// PDTK
#include <cxxutils/error_helpers.h>
#include <cxxutils/streamcolors.h>
#ifndef CMSG_LEN
#define CMSG_ALIGN(len) (((len) + sizeof(size_t) - 1) & (size_t) ~ (sizeof(size_t) - 1))
#define CMSG_SPACE(len) (CMSG_ALIGN (len) + CMSG_ALIGN (sizeof (struct cmsghdr)))
#define CMSG_LEN(len) (CMSG_ALIGN (sizeof (struct cmsghdr)) + (len))
#endif
static_assert(sizeof(uint8_t) == sizeof(char), "size mismatch!");
// NOTE: this is not an enumeration so that each value can be referenced
namespace LocalCommand
{
static const uint64_t write = 1;
static const uint64_t update = 2;
static const uint64_t exit = 3;
}
namespace posix
{
inline bool getpeercred(fd_t sockfd, proccred_t& cred) noexcept
{ return ::getpeercred(sockfd, cred) == posix::success_response; }
}
AsyncSocket::AsyncSocket(EDomain domain, EType type, EProtocol protocol, int flags) noexcept
: AsyncSocket(posix::socket(domain, type, protocol, flags)) { }
AsyncSocket::AsyncSocket(posix::fd_t socket) noexcept
: m_socket(socket),
m_bound(false)
{
posix::fd_t cmdio[2];
assert(::pipe(cmdio) != posix::error_response);
m_read_command = cmdio[0];
m_write_command = cmdio[1];
EventBackend::watch(m_read_command, EventFlags::Readable);
EventBackend::watch(m_socket, EventFlags::Readable);
}
AsyncSocket::~AsyncSocket(void) noexcept
{
posix::write(m_write_command, &LocalCommand::exit, sizeof(uint64_t));
m_iothread.join(); // wait for thread to exit
if(m_socket != posix::invalid_descriptor)
posix::close(m_socket);
if(m_selfaddr != EDomain::unspec)
::unlink(m_selfaddr.sun_path);
}
bool AsyncSocket::bind(const char *socket_path, int socket_backlog) noexcept
{
if(!has_socket())
return false;
assert(std::strlen(socket_path) < sizeof(sockaddr_un::sun_path));
m_selfaddr = socket_path;
m_selfaddr = EDomain::local;
return m_bound = posix::bind(m_socket, m_selfaddr, m_selfaddr.size()) &&
posix::listen(m_socket, socket_backlog) &&
async_spawn();
}
bool AsyncSocket::connect(const char *socket_path) noexcept
{
if(!has_socket())
return false;
assert(std::strlen(socket_path) < sizeof(sockaddr_un::sun_path));
posix::sockaddr_t peeraddr;
proccred_t peercred;
peeraddr = socket_path;
peeraddr = EDomain::local;
m_selfaddr = EDomain::unspec;
return posix::connect(m_socket, peeraddr, peeraddr.size()) &&
posix::getpeercred(m_socket, peercred) &&
async_spawn() &&
Object::enqueue(connectedToPeer, m_socket, peeraddr, peercred);
}
bool AsyncSocket::async_spawn(void) noexcept
{
if(m_iothread.joinable()) // if thread already active
return posix::write(m_write_command, &LocalCommand::update, sizeof(uint64_t)) != posix::error_response; // notify thread of an update
m_iothread = std::thread(&AsyncSocket::async_io , this); // create a new thread
return m_iothread.joinable(); // if thread creation succeeded
}
void AsyncSocket::async_io(void) noexcept // runs as it's own thread
{
msghdr msg = {};
iovec iov = {};
char aux_buffer[CMSG_SPACE(sizeof(int))] = { 0 };
uint64_t command_buffer = 0;
ssize_t byte_count = 0;
msg.msg_iov = &iov;
msg.msg_iovlen = 1;
msg.msg_control = aux_buffer;
for(;;)
{
if(EventBackend::getevents())
{
for(const auto& pos : EventBackend::results)
{
if(pos.first == m_read_command && (pos.second.flags & EventFlags::Readable))
{
command_buffer = 0;
byte_count = posix::read(pos.first, &command_buffer, sizeof(uint64_t));
if(byte_count == posix::error_response)
continue;
switch(command_buffer)
{
case LocalCommand::update: continue; // EventBackend::m_queue size changed
case LocalCommand::exit:
std::cout << "thread exiting!" << std::endl << std::flush;
return; // thread exit
case LocalCommand::write: // m_messages isn't empty
{
for(auto& msg_pos : m_messages)
{
msg.msg_iov = &iov;
msg.msg_iovlen = 1;
msg.msg_control = aux_buffer;
iov.iov_base = msg_pos.buffer.begin();
iov.iov_len = msg_pos.buffer.size();
msg.msg_controllen = 0;
if(msg_pos.fd_buffer != posix::invalid_descriptor) // if a file descriptor needs to be sent
{
msg.msg_controllen = CMSG_SPACE(sizeof(int));
cmsghdr* cmsg = CMSG_FIRSTHDR(&msg);
cmsg->cmsg_level = SOL_SOCKET;
cmsg->cmsg_type = SCM_RIGHTS;
cmsg->cmsg_len = CMSG_LEN(sizeof(int));
*reinterpret_cast<int*>(CMSG_DATA(cmsg)) = msg_pos.fd_buffer;
}
byte_count = posix::sendmsg(msg_pos.socket, &msg, 0);
if(byte_count == posix::error_response) // error
std::cout << std::flush << std::endl << std::red << "sendmsg error: " << std::strerror(errno) << std::none << std::endl << std::flush;
else
Object::enqueue(writeFinished, msg_pos.socket, byte_count);
}
m_messages.clear();
}
}
}
else if(m_bound && // if in server mode
pos.first == m_socket && // and this is a primary socket
pos.second.flags & EventFlags::Readable) // and it's a read event
{
proccred_t peercred;
posix::sockaddr_t peeraddr;
socklen_t addrlen = 0;
posix::fd_t fd = posix::accept(m_socket, peeraddr, &addrlen); // accept a new socket connection
if(fd == posix::error_response)
std::cout << "accept error: " << std::strerror(errno) << std::endl << std::flush;
else
{
if(!EventBackend::watch(fd, EventFlags::Readable)) // monitor new socket connection
std::cout << "watch failure: " << std::strerror(errno) << std::endl << std::flush;
if(!posix::getpeercred(fd, peercred)) // get creditials of connected peer process
std::cout << "peercred failure: " << std::strerror(errno) << std::endl << std::flush;
Object::enqueue(connectedToPeer, fd, peeraddr, peercred);
}
}
else
{
if(pos.second.flags & (EventFlags::Disconnected | EventFlags::Error)) // connection severed or connection error
{
EventBackend::remove(pos.first); // stop watching for events
posix::close(pos.first); // close connection if open
}
else if(pos.second.flags & EventFlags::Readable) // read
{
m_incomming.socket = m_bound ? m_socket : m_read_command; // select proper output socket
m_incomming.buffer.allocate(); // allocate 64KB buffer
iov.iov_base = m_incomming.buffer.data();
iov.iov_len = m_incomming.buffer.capacity();
msg.msg_controllen = sizeof(aux_buffer);
byte_count = posix::recvmsg(pos.first, &msg, 0);
if(byte_count == posix::error_response)
std::cout << std::red << "recvmsg error: " << std::strerror(errno) << std::none << std::endl << std::flush;
else if(!byte_count)
{
EventBackend::remove(pos.first); // stop watching for events
posix::close(pos.first); // connection severed!
}
else if(m_incomming.buffer.expand(byte_count))
{
m_incomming.fd_buffer = posix::invalid_descriptor;
if(msg.msg_controllen == CMSG_SPACE(sizeof(int)))
{
cmsghdr* cmsg = CMSG_FIRSTHDR(&msg);
if(cmsg->cmsg_level == SOL_SOCKET &&
cmsg->cmsg_type == SCM_RIGHTS &&
cmsg->cmsg_len == CMSG_LEN(sizeof(int)))
m_incomming.fd_buffer = *reinterpret_cast<int*>(CMSG_DATA(cmsg));
}
else if(msg.msg_flags)
std::cout << std::red << "error, message flags: " << std::hex << msg.msg_flags << std::dec << std::none << std::endl << std::flush;
Object::enqueue(readFinished, m_incomming.socket, m_incomming);
}
}
else if(pos.second.flags >= 0)
{
std::cout << "unknown event at: " << pos.first << " value: " << std::hex << uint32_t(EventFlags(pos.second.flags)) << std::dec << std::endl << std::flush;
}
}
}
}
}
}
bool AsyncSocket::write(message_t msg) noexcept
{
if(!is_connected(msg.socket))
return false;
m_messages.push_back(msg);
posix::write(m_write_command, &LocalCommand::write, sizeof(uint64_t));
return true;
}
<commit_msg>work in progress<commit_after>#include "asocket.h"
// C++
#include <cassert>
#include <cstring>
#include <cstdint>
// STL
#include <iostream>
// PDTK
#include <cxxutils/error_helpers.h>
#include <cxxutils/streamcolors.h>
#ifndef CMSG_LEN
#define CMSG_ALIGN(len) (((len) + sizeof(size_t) - 1) & (size_t) ~ (sizeof(size_t) - 1))
#define CMSG_SPACE(len) (CMSG_ALIGN (len) + CMSG_ALIGN (sizeof (struct cmsghdr)))
#define CMSG_LEN(len) (CMSG_ALIGN (sizeof (struct cmsghdr)) + (len))
#endif
static_assert(sizeof(uint8_t) == sizeof(char), "size mismatch!");
// NOTE: this is not an enumeration so that each value can be referenced
namespace LocalCommand
{
static const uint64_t write = 1;
static const uint64_t update = 2;
static const uint64_t exit = 3;
}
namespace posix
{
inline bool getpeercred(fd_t sockfd, proccred_t& cred) noexcept
{ return ::getpeercred(sockfd, cred) == posix::success_response; }
}
AsyncSocket::AsyncSocket(EDomain domain, EType type, EProtocol protocol, int flags) noexcept
: AsyncSocket(posix::socket(domain, type, protocol, flags)) { }
AsyncSocket::AsyncSocket(posix::fd_t socket) noexcept
: m_socket(socket),
m_bound(false)
{
posix::fd_t cmdio[2];
assert(::pipe(cmdio) != posix::error_response);
m_read_command = cmdio[0];
m_write_command = cmdio[1];
EventBackend::watch(m_read_command, EventFlags::Readable);
EventBackend::watch(m_socket, EventFlags::Readable);
}
AsyncSocket::~AsyncSocket(void) noexcept
{
posix::write(m_write_command, &LocalCommand::exit, sizeof(uint64_t));
m_iothread.join(); // wait for thread to exit
if(m_socket != posix::invalid_descriptor)
posix::close(m_socket);
if(m_selfaddr != EDomain::unspec)
::unlink(m_selfaddr.sun_path);
}
bool AsyncSocket::bind(const char *socket_path, int socket_backlog) noexcept
{
if(!has_socket())
return false;
assert(std::strlen(socket_path) < sizeof(sockaddr_un::sun_path));
m_selfaddr = socket_path;
m_selfaddr = EDomain::local;
return m_bound = posix::bind(m_socket, m_selfaddr, m_selfaddr.size()) &&
posix::listen(m_socket, socket_backlog) &&
async_spawn();
}
bool AsyncSocket::connect(const char *socket_path) noexcept
{
if(!has_socket())
return false;
assert(std::strlen(socket_path) < sizeof(sockaddr_un::sun_path));
posix::sockaddr_t peeraddr;
proccred_t peercred;
peeraddr = socket_path;
peeraddr = EDomain::local;
m_selfaddr = EDomain::unspec;
return posix::connect(m_socket, peeraddr, peeraddr.size()) &&
posix::getpeercred(m_socket, peercred) &&
async_spawn() &&
Object::enqueue(connectedToPeer, m_socket, peeraddr, peercred);
}
bool AsyncSocket::async_spawn(void) noexcept
{
if(m_iothread.joinable()) // if thread already active
return posix::write(m_write_command, &LocalCommand::update, sizeof(uint64_t)) != posix::error_response; // notify thread of an update
m_iothread = std::thread(&AsyncSocket::async_io , this); // create a new thread
return m_iothread.joinable(); // if thread creation succeeded
}
void AsyncSocket::async_io(void) noexcept // runs as it's own thread
{
msghdr msg = {};
iovec iov = {};
char aux_buffer[CMSG_SPACE(sizeof(int))] = { 0 };
uint64_t command_buffer = 0;
ssize_t byte_count = 0;
msg.msg_iov = &iov;
msg.msg_iovlen = 1;
msg.msg_control = aux_buffer;
for(;;)
{
if(EventBackend::getevents())
{
for(const auto& pos : EventBackend::results)
{
if(pos.first == m_read_command && (pos.second.flags & EventFlags::Readable))
{
command_buffer = 0;
byte_count = posix::read(pos.first, &command_buffer, sizeof(uint64_t));
if(byte_count == posix::error_response)
continue;
switch(command_buffer)
{
case LocalCommand::update: continue; // EventBackend::m_queue size changed
case LocalCommand::exit:
std::cout << "thread exiting!" << std::endl << std::flush;
return; // thread exit
case LocalCommand::write: // m_messages isn't empty
{
for(auto& msg_pos : m_messages)
{
msg.msg_iov = &iov;
msg.msg_iovlen = 1;
msg.msg_control = aux_buffer;
iov.iov_base = msg_pos.buffer.begin();
iov.iov_len = msg_pos.buffer.size();
msg.msg_controllen = 0;
if(msg_pos.fd_buffer != posix::invalid_descriptor) // if a file descriptor needs to be sent
{
msg.msg_controllen = CMSG_SPACE(sizeof(int));
cmsghdr* cmsg = CMSG_FIRSTHDR(&msg);
cmsg->cmsg_level = SOL_SOCKET;
cmsg->cmsg_type = SCM_RIGHTS;
cmsg->cmsg_len = CMSG_LEN(sizeof(int));
*reinterpret_cast<int*>(CMSG_DATA(cmsg)) = msg_pos.fd_buffer;
}
byte_count = posix::sendmsg(msg_pos.socket, &msg, 0);
if(byte_count == posix::error_response) // error
std::cout << std::flush << std::endl << posix::fg::red << "sendmsg error: " << std::strerror(errno) << posix::fg::reset << std::endl << std::flush;
else
Object::enqueue(writeFinished, msg_pos.socket, byte_count);
}
m_messages.clear();
}
}
}
else if(m_bound && // if in server mode
pos.first == m_socket && // and this is a primary socket
pos.second.flags & EventFlags::Readable) // and it's a read event
{
proccred_t peercred;
posix::sockaddr_t peeraddr;
socklen_t addrlen = 0;
posix::fd_t fd = posix::accept(m_socket, peeraddr, &addrlen); // accept a new socket connection
if(fd == posix::error_response)
std::cout << "accept error: " << std::strerror(errno) << std::endl << std::flush;
else
{
if(!EventBackend::watch(fd, EventFlags::Readable)) // monitor new socket connection
std::cout << "watch failure: " << std::strerror(errno) << std::endl << std::flush;
if(!posix::getpeercred(fd, peercred)) // get creditials of connected peer process
std::cout << "peercred failure: " << std::strerror(errno) << std::endl << std::flush;
Object::enqueue(connectedToPeer, fd, peeraddr, peercred);
}
}
else
{
if(pos.second.flags & (EventFlags::Disconnected | EventFlags::Error)) // connection severed or connection error
{
EventBackend::remove(pos.first); // stop watching for events
posix::close(pos.first); // close connection if open
}
else if(pos.second.flags & EventFlags::Readable) // read
{
m_incomming.socket = m_bound ? m_socket : m_read_command; // select proper output socket
m_incomming.buffer.allocate(); // allocate 64KB buffer
iov.iov_base = m_incomming.buffer.data();
iov.iov_len = m_incomming.buffer.capacity();
msg.msg_controllen = sizeof(aux_buffer);
byte_count = posix::recvmsg(pos.first, &msg, 0);
if(byte_count == posix::error_response)
std::cout << posix::fg::red << "recvmsg error: " << std::strerror(errno) << posix::fg::reset << std::endl << std::flush;
else if(!byte_count)
{
EventBackend::remove(pos.first); // stop watching for events
posix::close(pos.first); // connection severed!
}
else if(m_incomming.buffer.expand(byte_count))
{
m_incomming.fd_buffer = posix::invalid_descriptor;
if(msg.msg_controllen == CMSG_SPACE(sizeof(int)))
{
cmsghdr* cmsg = CMSG_FIRSTHDR(&msg);
if(cmsg->cmsg_level == SOL_SOCKET &&
cmsg->cmsg_type == SCM_RIGHTS &&
cmsg->cmsg_len == CMSG_LEN(sizeof(int)))
m_incomming.fd_buffer = *reinterpret_cast<int*>(CMSG_DATA(cmsg));
}
else if(msg.msg_flags)
std::cout << posix::fg::red << "error, message flags: " << std::hex << msg.msg_flags << std::dec << posix::fg::reset << std::endl << std::flush;
Object::enqueue(readFinished, m_incomming.socket, m_incomming);
}
}
else if(pos.second.flags >= 0)
{
std::cout << "unknown event at: " << pos.first << " value: " << std::hex << uint32_t(EventFlags(pos.second.flags)) << std::dec << std::endl << std::flush;
}
}
}
}
}
}
bool AsyncSocket::write(message_t msg) noexcept
{
if(!is_connected(msg.socket))
return false;
m_messages.push_back(msg);
posix::write(m_write_command, &LocalCommand::write, sizeof(uint64_t));
return true;
}
#if 0
// connect to primary socket
static bool accept(posix::fd_t socket, posix::fd_t& fd) noexcept
{
proccred_t peercred;
posix::sockaddr_t peeraddr;
socklen_t addrlen = 0;
fd = posix::accept(m_socket, peeraddr, &addrlen); // accept a new socket connection
if(fd == posix::error_response)
std::cout << "accept error: " << std::strerror(errno) << std::endl << std::flush;
else
{
if(!EventBackend::watch(fd, EventFlags::Readable)) // monitor new socket connection
std::cout << "watch failure: " << std::strerror(errno) << std::endl << std::flush;
if(!posix::getpeercred(fd, peercred)) // get creditials of connected peer process
std::cout << "peercred failure: " << std::strerror(errno) << std::endl << std::flush;
Object::enqueue(connectedToPeer, fd, peeraddr, peercred);
}
}
struct BufferedSocket
{
bool read(void) noexcept
{
msghdr header = {};
iovec iov = {};
char aux_buffer[CMSG_SPACE(sizeof(int))] = { 0 };
header.msg_iov = &iov;
header.msg_iovlen = 1;
header.msg_control = aux_buffer;
iov.iov_base = buffer.begin();
iov.iov_len = buffer.capacity();
header.msg_controllen = sizeof(aux_buffer);
ssize_t byte_count = posix::recvmsg(socket, &header, 0);
flaw(byte_count > 0xFFFF, errno = EMSGSIZE, false, "Absurdly large socket message!: %i bytes", byte_count)
if(byte_count == posix::error_response)
{
std::cout << posix::fg::red << "recvmsg error: " << std::strerror(errno) << posix::fg::reset << std::endl << std::flush;
return false;
}
else if(!byte_count)
{
EventBackend::remove(socket); // stop watching for events
posix::close(socket); // connection severed!
}
else if(buffer.resize(byte_count))
{
fd = posix::invalid_descriptor;
if(header.msg_controllen == CMSG_SPACE(sizeof(int)))
{
cmsghdr* cmsg = CMSG_FIRSTHDR(&header);
if(cmsg->cmsg_level == SOL_SOCKET &&
cmsg->cmsg_type == SCM_RIGHTS &&
cmsg->cmsg_len == CMSG_LEN(sizeof(int)))
fd = *reinterpret_cast<int*>(CMSG_DATA(cmsg));
}
else if(header.msg_flags)
{
std::cout << posix::fg::red << "error, message flags: " << std::hex << header.msg_flags << std::dec << posix::fg::reset << std::endl << std::flush;
return false;
}
}
else // buffer too small!
{
errno = ENOBUFS;
return false;
}
return true;
}
bool write(void) noexcept
{
msghdr header = {};
iovec iov = {};
char aux_buffer[CMSG_SPACE(sizeof(int))] = { 0 };
header.msg_iov = &iov;
header.msg_iovlen = 1;
header.msg_control = aux_buffer;
iov.iov_base = buffer.begin();
iov.iov_len = buffer.size();
header.msg_controllen = 0;
if(fd != posix::invalid_descriptor) // if a file descriptor needs to be sent
{
header.msg_controllen = CMSG_SPACE(sizeof(int));
cmsghdr* cmsg = CMSG_FIRSTHDR(&header);
cmsg->cmsg_level = SOL_SOCKET;
cmsg->cmsg_type = SCM_RIGHTS;
cmsg->cmsg_len = CMSG_LEN(sizeof(int));
*reinterpret_cast<int*>(CMSG_DATA(cmsg)) = fd;
}
return posix::sendmsg(socket, &header, 0) != posix::error_response;
}
posix::fd_t socket;
vfifo buffer;
posix::fd_t fd;
};
#endif
<|endoftext|>
|
<commit_before>
#include "SerialData.h"
#include "PIDDataManager.h"
#include "SelfPositionManager.h"
#include "StrategyManager.h"
#include "BlockMoveManager.h"
#include "BlockMoveStrategy.h"
#include "InOutManager.h"
#include "PIDDataManager.h"
#include "SoundPlayTask.h"
#define FIELD 220
#define EDGE_LINE 120 // 黒線との境界線
#define TURN_POWER 15 // 旋回時のパワー
#define ONLINE 25 // 黒線上での輝度値
#define NotONLINE 60 // 黒線以外での輝度値
// 次のステートに切り替える
void BlockMoveStrategy::ChangeState(AbstractMoveState* nextState)
{
delete State;
State = nextState;
}
void BlockMoveStrategy::Run()
{
State->Run();
}
// ブロックまで移動中の動作
void ApproachState::Run()
{
BlockMoveManager* BtManager = BlockMoveManager::GetInstance();
SelfPositionManager* SpManager = SelfPositionManager::GetInstance();
InOutManager* IoManager = InOutManager::GetInstance();
PIDData BlockMovePID = PIDDataManager::GetInstance()->GetPIDData(BlockMovePIDState);
int currentAngle = SpManager->RobotAngle;
int targetWaypointAngle = BtManager->GetSrcWaypointAngle(SpManager->RobotPoint.X, SpManager->RobotPoint.Y);
int targetBlockAngle = BtManager->GetSrcBlockAngle(SpManager->RobotPoint.X, SpManager->RobotPoint.Y);
switch(SubState){
// 初回処理
case Initialize:
if(BtManager->CurrentCommand.SourceBlockPosition == 9) {
// 最寄の場合には、即ライントレース
LeftEdge = false;
SubState = LineTrace;
} else if(CurrentWayPointNo == BtManager->GetSrcWayPointNo()) {
// すでにウェイポイントの上にいるとき
SubState = LineTurn;
} else if(CurrentWayPointNo == 26) {
// 初回であり、9ではないとき
SubState = FirstTurn;
} else {
SubState = FirstTurn;
}
break;
// 仮想ウェイポイント間を移動中の動作
case FirstTurn:
// 角度が一致したため、仮想ウェイポイント間の移動に遷移
if (abs(targetWaypointAngle - currentAngle) < 2) {
SubState = ImaginaryWaypoint;
}
// 旋回動作を実行
IoManager->Turn(currentAngle, targetWaypointAngle, TURN_POWER);
break;
// ウェイポイントに向かって移動する動作
case ImaginaryWaypoint:
// ラインを認識した場合には、直進ステートに遷移
if(IoManager->InputData.ReflectLight < ONLINE) {
// ラインをまたぐまで直進
SubState = OverLine;
// ラインを跨いだので、ウェイポイントの座標に変更
SpManager->ResetPoint(BtManager->GetLine(BtManager->GetSrcWayPointNo())->WayPoint);
} else {
IoManager->Forward(BlockMovePID.BasePower);
}
break;
// ラインをまたぐまでの処理
case OverLine:
if(IoManager->InputData.ReflectLight > FIELD) {
// ウェイポイントに到達したので、現在いるウェイポイントNoを更新
CurrentWayPointNo = BtManager->GetSrcWayPointNo();
// 白認識(ラインを跨いだ)ので、次の状態に繊維
bool last = BtManager->ArrivalSrcWayPoint();
// 最終ウェイポイントの場合
if(last) {
// ライントレース前の旋回動作に遷移
SubState = LineTurn;
CW = IoManager->JudgeTurnCW(currentAngle, targetBlockAngle);
} else {
// 初回旋回に遷移
SubState = FirstTurn;
}
} else {
// ラインをまたぐまでは直進
IoManager->Forward(BlockMovePID.BasePower);
}
break;
// ライントレース前の旋回動作
case LineTurn:
// 旋回動作を実行
if(abs(targetBlockAngle - currentAngle) > 45 || IoManager->InputData.ReflectLight > EDGE_LINE){
IoManager->Turn(CW, TURN_POWER);
} else {
// 角度が一致したため、ライントレースに遷移
SubState = LineTrace;
// 旋回方向によって、ラインのどちら側を走行するか決定
LeftEdge = CW;
}
break;
// ライントレースする動作
case LineTrace:
//目標とするブロック置き場の色を取得したら、現在のステートをブロック運搬中に変更
if(IoManager->HSLKind == BtManager->GetSrcBlockPositionColor()){
// ブロック置き場の座標に修正
SpManager->ResetPoint(BtManager->GetSrcBlockPoint());
// ブロック運搬時の経路がある(最終コマンドではない)場合には、ブロック運搬ステートに遷移
if(BtManager->CurrentCommand.BlockMoveWaypointCount != 0) {
// ブロック置き場到達メッセージ
BtManager->ArrivalSrcBlockPosition();
auto moveState = new MoveState(ParentStrategy);
moveState->LeftEdge = LeftEdge;
int nextWaypointAngle = BtManager->GetDstWaypointAngle(SpManager->RobotPoint.X, SpManager->RobotPoint.Y);
moveState->CW = IoManager->JudgeTurnCW(currentAngle, nextWaypointAngle);
moveState->CurrentWayPointNo = CurrentWayPointNo;
ParentStrategy->ChangeState(moveState);
// 積算距離をリセット
SpManager->Distance = 0;
} else {
IoManager->Stop();
}
break;
}
// ライントレース中は、ラインの角度に修正
{
int angle = BtManager->GetLine(BtManager->GetSrcWayPointNo())->GetAngle(BtManager->CurrentCommand.SourceBlockPosition);
SpManager->ResetAngle(angle);
}
IoManager->LineTraceAction(BlockMovePID, EDGE_LINE, LeftEdge);
break;
case FirstStraight:
case FirstLineTrace:
case Back:
break;
}
}
void MoveState::Run()
{
BlockMoveManager* BtManager = BlockMoveManager::GetInstance();
SelfPositionManager* SpManager = SelfPositionManager::GetInstance();
InOutManager* IoManager = InOutManager::GetInstance();
SpManager->ParticleFilterON = false;
PIDData BlockMovePID = PIDDataManager::GetInstance()->GetPIDData(BlockMovePIDState);
int currentAngle = SpManager->RobotAngle;
int dstWayPointNo = BtManager->GetDstWayPointNo();
int moveDistance = 0;
int targetWaypointAngle = BtManager->GetDstWaypointAngle(SpManager->RobotPoint.X, SpManager->RobotPoint.Y);
int targetBlockAngle = BtManager->GetDstBlockAngle(SpManager->RobotPoint.X, SpManager->RobotPoint.Y);
switch(SubState){
// 初回処理
case Initialize:
/*
// ウェイポイントが複数ある場合には、最初の1個は無視して、初回旋回に遷移
if(BtManager->CurrentCommand.BlockMoveWaypointCount > 1) {
// それ以外の場合には、最初のウェイポイントに即到達して、初回旋回に遷移
BtManager->ArrivalDstWayPoint();
// 角度を再計算して、方向を判定
SubState = FirstTurn;
break;
}
*/
// 角度が一致したため、仮想ウェイポイント間の移動に遷移
if (abs(targetWaypointAngle - currentAngle) < 3) {
SubState = FirstStraight;
SpManager->Distance = 0;
break;
}
if(CurrentWayPointNo == 22 && BtManager->CurrentCommand.SourceBlockPosition == 10) {
CW = false;
}
LeftEdge = CW;
// 旋回動作を実行
IoManager->TurnWithBlock(CW, TURN_POWER , 0);
break;
case FirstStraight:
if(dstWayPointNo == 0 || dstWayPointNo == 1 || dstWayPointNo == 2){
moveDistance = 340;
} else {
moveDistance = 120;
}
if(SpManager->Distance > moveDistance) {
SubState = FirstLineTrace;
}
IoManager->Forward(BlockMovePID.BasePower);
break;
// 仮想ウェイポイント間を移動中の動作
case FirstTurn:
// 角度が一致したため、仮想ウェイポイント間の移動に遷移
if (abs(targetWaypointAngle - currentAngle) < 2) {
SubState = ImaginaryWaypoint;
// 移動距離をクリア
SpManager->Distance = 0;
break;
}
CW = IoManager->JudgeTurnCW(currentAngle, targetWaypointAngle);
// 旋回動作を実行
IoManager->TurnWithBlock(CW, TURN_POWER, -0.2);
break;
case FirstLineTrace:
// // 10cm程度進む
// if(SpManager->Distance > 150)
{
// ウェイポイントに到達したので、現在いるウェイポイントNoを更新
CurrentWayPointNo = BtManager->GetDstWayPointNo();
// 次の状態に繊維
bool last = BtManager->ArrivalDstWayPoint();
// 最終ウェイポイントの場合
if(last) {
if(CurrentWayPointNo == 7 && BtManager->CurrentCommand.DestinationBlockPosition == 5) {
CW = true;
}
// ライントレースに遷移
SubState = LineTrace;
} else {
// 初回旋回に遷移
SubState = FirstTurn;
}
}
// IoManager->LineTraceAction(BlockMovePID, EDGE_LINE, LeftEdge);
break;
// ウェイポイントに向かって移動する動作
case ImaginaryWaypoint:
// 一定距離進んだ後、ラインを認識した場合には、直進ステートに遷移
if(IoManager->InputData.ReflectLight < ONLINE && SpManager->Distance > 30) {
// ラインをまたぐまで直進
SubState = OverLine;
// ラインを跨いだので、ウェイポイントの座標に変更
SpManager->ResetPoint(BtManager->GetLine(BtManager->GetDstWayPointNo())->WayPoint);
} else {
IoManager->Forward(BlockMovePID.BasePower);
}
break;
// ラインをまたぐまでの処理
case OverLine:
if(IoManager->InputData.ReflectLight > EDGE_LINE) {
// ウェイポイントに到達したので、現在いるウェイポイントNoを更新
CurrentWayPointNo = BtManager->GetDstWayPointNo();
// 白認識(ラインを跨いだ)ので、次の状態に繊維
bool last = BtManager->ArrivalDstWayPoint();
// 最終ウェイポイントの場合
if(last) {
// ライントレース前の旋回動作に遷移
SubState = LineTurn;
// 旋回方向を判定
CW = IoManager->JudgeTurnCW(currentAngle, targetBlockAngle);
} else {
// 初回旋回に遷移
SubState = FirstTurn;
}
} else {
// ラインをまたぐまでは直進
IoManager->Forward(BlockMovePID.BasePower);
}
break;
// ライントレース前の旋回動作
case LineTurn:
// 旋回動作を実行
if(abs(targetBlockAngle - currentAngle) < 70 &&
(IoManager->InputData.ReflectLight < EDGE_LINE || IoManager->HSLKind == BtManager->GetDstBlockPositionColor()))
{
// 角度が一致したため、ライントレースに遷移
SubState = LineTrace;
// 旋回方向によって、ラインのどちら側を走行するか決定
LeftEdge = CW;
break;
}
IoManager->TurnWithBlock(CW, TURN_POWER, -0.3);
break;
// ライントレースする動作
case LineTrace:
//目標とするブロック置き場の色を取得したら、現在のステートをブロック運搬中に変更
if(IoManager->HSLKind == BtManager->GetDstBlockPositionColor()) ColorDetectCount++;
if(IoManager->HSLKind == HSLBlack) ColorDetectCount = 0;
if(ColorDetectCount > 10)
{
// ブロック置き場の座標に修正
SpManager->ResetPoint(BtManager->GetDstBlockPoint());
SpManager->Distance = 200;
SubState = Back;
break;
}
// ライントレース中は、ラインの角度に修正
{
int angle = BtManager->GetLine(CurrentWayPointNo)->GetAngle(BtManager->CurrentCommand.DestinationBlockPosition);
SpManager->ResetAngle(angle);
}
IoManager->LineTraceAction(BlockMovePID, EDGE_LINE, LeftEdge);
break;
// 後退する動作
case Back:
if(SpManager->Distance < 80) {
// 12cm後退したら、アプローチに遷移する
// ブロック置き場到達メッセージ
bool last = BtManager->ArrivalDstBlockPosition();
// 最後までやったら、やりきった感を出す
if (last) {
IoManager->Stop();
IoManager->WriteOutputMotor();
PlaySound(BlockEnd);
ParentStrategy->Manager->SetStrategy(NULL);
break;
}
auto approachState = new ApproachState(ParentStrategy);
approachState->CurrentWayPointNo = CurrentWayPointNo;
ParentStrategy->ChangeState(approachState);
break;
}
IoManager->Back(BlockMovePID.BasePower);
break;
}
}
<commit_msg>ウェイポイント番号が違っているバグを修正<commit_after>
#include "SerialData.h"
#include "PIDDataManager.h"
#include "SelfPositionManager.h"
#include "StrategyManager.h"
#include "BlockMoveManager.h"
#include "BlockMoveStrategy.h"
#include "InOutManager.h"
#include "PIDDataManager.h"
#include "SoundPlayTask.h"
#define FIELD 220
#define EDGE_LINE 120 // 黒線との境界線
#define TURN_POWER 15 // 旋回時のパワー
#define ONLINE 25 // 黒線上での輝度値
#define NotONLINE 60 // 黒線以外での輝度値
// 次のステートに切り替える
void BlockMoveStrategy::ChangeState(AbstractMoveState* nextState)
{
delete State;
State = nextState;
}
void BlockMoveStrategy::Run()
{
State->Run();
}
// ブロックまで移動中の動作
void ApproachState::Run()
{
BlockMoveManager* BtManager = BlockMoveManager::GetInstance();
SelfPositionManager* SpManager = SelfPositionManager::GetInstance();
InOutManager* IoManager = InOutManager::GetInstance();
PIDData BlockMovePID = PIDDataManager::GetInstance()->GetPIDData(BlockMovePIDState);
int currentAngle = SpManager->RobotAngle;
int targetWaypointAngle = BtManager->GetSrcWaypointAngle(SpManager->RobotPoint.X, SpManager->RobotPoint.Y);
int targetBlockAngle = BtManager->GetSrcBlockAngle(SpManager->RobotPoint.X, SpManager->RobotPoint.Y);
switch(SubState){
// 初回処理
case Initialize:
if(BtManager->CurrentCommand.SourceBlockPosition == 9) {
// 最寄の場合には、即ライントレース
LeftEdge = false;
SubState = LineTrace;
} else if(CurrentWayPointNo == BtManager->GetSrcWayPointNo()) {
// すでにウェイポイントの上にいるとき
SubState = LineTurn;
} else if(CurrentWayPointNo == 26) {
// 初回であり、9ではないとき
SubState = FirstTurn;
} else {
SubState = FirstTurn;
}
break;
// 仮想ウェイポイント間を移動中の動作
case FirstTurn:
// 角度が一致したため、仮想ウェイポイント間の移動に遷移
if (abs(targetWaypointAngle - currentAngle) < 2) {
SubState = ImaginaryWaypoint;
}
// 旋回動作を実行
IoManager->Turn(currentAngle, targetWaypointAngle, TURN_POWER);
break;
// ウェイポイントに向かって移動する動作
case ImaginaryWaypoint:
// ラインを認識した場合には、直進ステートに遷移
if(IoManager->InputData.ReflectLight < ONLINE) {
// ラインをまたぐまで直進
SubState = OverLine;
// ラインを跨いだので、ウェイポイントの座標に変更
SpManager->ResetPoint(BtManager->GetLine(BtManager->GetSrcWayPointNo())->WayPoint);
} else {
IoManager->Forward(BlockMovePID.BasePower);
}
break;
// ラインをまたぐまでの処理
case OverLine:
if(IoManager->InputData.ReflectLight > FIELD) {
// ウェイポイントに到達したので、現在いるウェイポイントNoを更新
CurrentWayPointNo = BtManager->GetSrcWayPointNo();
// 白認識(ラインを跨いだ)ので、次の状態に繊維
bool last = BtManager->ArrivalSrcWayPoint();
// 最終ウェイポイントの場合
if(last) {
// ライントレース前の旋回動作に遷移
SubState = LineTurn;
CW = IoManager->JudgeTurnCW(currentAngle, targetBlockAngle);
} else {
// 初回旋回に遷移
SubState = FirstTurn;
}
} else {
// ラインをまたぐまでは直進
IoManager->Forward(BlockMovePID.BasePower);
}
break;
// ライントレース前の旋回動作
case LineTurn:
// 旋回動作を実行
if(abs(targetBlockAngle - currentAngle) > 45 || IoManager->InputData.ReflectLight > EDGE_LINE){
IoManager->Turn(CW, TURN_POWER);
} else {
// 角度が一致したため、ライントレースに遷移
SubState = LineTrace;
// 旋回方向によって、ラインのどちら側を走行するか決定
LeftEdge = CW;
}
break;
// ライントレースする動作
case LineTrace:
//目標とするブロック置き場の色を取得したら、現在のステートをブロック運搬中に変更
if(IoManager->HSLKind == BtManager->GetSrcBlockPositionColor()){
// ブロック置き場の座標に修正
SpManager->ResetPoint(BtManager->GetSrcBlockPoint());
// ブロック運搬時の経路がある(最終コマンドではない)場合には、ブロック運搬ステートに遷移
if(BtManager->CurrentCommand.BlockMoveWaypointCount != 0) {
// ブロック置き場到達メッセージ
BtManager->ArrivalSrcBlockPosition();
auto moveState = new MoveState(ParentStrategy);
moveState->LeftEdge = LeftEdge;
int nextWaypointAngle = BtManager->GetDstWaypointAngle(SpManager->RobotPoint.X, SpManager->RobotPoint.Y);
moveState->CW = IoManager->JudgeTurnCW(currentAngle, nextWaypointAngle);
moveState->CurrentWayPointNo = CurrentWayPointNo;
ParentStrategy->ChangeState(moveState);
// 積算距離をリセット
SpManager->Distance = 0;
} else {
IoManager->Stop();
}
break;
}
// ライントレース中は、ラインの角度に修正
{
int angle = BtManager->GetLine(BtManager->GetSrcWayPointNo())->GetAngle(BtManager->CurrentCommand.SourceBlockPosition);
SpManager->ResetAngle(angle);
}
IoManager->LineTraceAction(BlockMovePID, EDGE_LINE, LeftEdge);
break;
case FirstStraight:
case FirstLineTrace:
case Back:
break;
}
}
void MoveState::Run()
{
BlockMoveManager* BtManager = BlockMoveManager::GetInstance();
SelfPositionManager* SpManager = SelfPositionManager::GetInstance();
InOutManager* IoManager = InOutManager::GetInstance();
SpManager->ParticleFilterON = false;
PIDData BlockMovePID = PIDDataManager::GetInstance()->GetPIDData(BlockMovePIDState);
int currentAngle = SpManager->RobotAngle;
int dstWayPointNo = BtManager->GetDstWayPointNo();
int moveDistance = 0;
int targetWaypointAngle = BtManager->GetDstWaypointAngle(SpManager->RobotPoint.X, SpManager->RobotPoint.Y);
int targetBlockAngle = BtManager->GetDstBlockAngle(SpManager->RobotPoint.X, SpManager->RobotPoint.Y);
switch(SubState){
// 初回処理
case Initialize:
/*
// ウェイポイントが複数ある場合には、最初の1個は無視して、初回旋回に遷移
if(BtManager->CurrentCommand.BlockMoveWaypointCount > 1) {
// それ以外の場合には、最初のウェイポイントに即到達して、初回旋回に遷移
BtManager->ArrivalDstWayPoint();
// 角度を再計算して、方向を判定
SubState = FirstTurn;
break;
}
*/
// 角度が一致したため、仮想ウェイポイント間の移動に遷移
if (abs(targetWaypointAngle - currentAngle) < 3) {
SubState = FirstStraight;
SpManager->Distance = 0;
break;
}
if(CurrentWayPointNo == 22 && BtManager->CurrentCommand.SourceBlockPosition == 10) {
CW = false;
}
LeftEdge = CW;
// 旋回動作を実行
IoManager->TurnWithBlock(CW, TURN_POWER , 0);
break;
case FirstStraight:
if(dstWayPointNo == 0 || dstWayPointNo == 1 || dstWayPointNo == 2){
moveDistance = 340;
} else {
moveDistance = 120;
}
if(SpManager->Distance > moveDistance) {
SubState = FirstLineTrace;
}
IoManager->Forward(BlockMovePID.BasePower);
break;
// 仮想ウェイポイント間を移動中の動作
case FirstTurn:
// 角度が一致したため、仮想ウェイポイント間の移動に遷移
if (abs(targetWaypointAngle - currentAngle) < 2) {
SubState = ImaginaryWaypoint;
// 移動距離をクリア
SpManager->Distance = 0;
break;
}
CW = IoManager->JudgeTurnCW(currentAngle, targetWaypointAngle);
// 旋回動作を実行
IoManager->TurnWithBlock(CW, TURN_POWER, -0.2);
break;
case FirstLineTrace:
// // 10cm程度進む
// if(SpManager->Distance > 150)
{
// ウェイポイントに到達したので、現在いるウェイポイントNoを更新
CurrentWayPointNo = BtManager->GetDstWayPointNo();
// 次の状態に繊維
bool last = BtManager->ArrivalDstWayPoint();
// 最終ウェイポイントの場合
if(last) {
if(CurrentWayPointNo == 6 && BtManager->CurrentCommand.DestinationBlockPosition == 5) {
CW = true;
}
// ライントレースに遷移
SubState = LineTrace;
} else {
// 初回旋回に遷移
SubState = FirstTurn;
}
}
// IoManager->LineTraceAction(BlockMovePID, EDGE_LINE, LeftEdge);
break;
// ウェイポイントに向かって移動する動作
case ImaginaryWaypoint:
// 一定距離進んだ後、ラインを認識した場合には、直進ステートに遷移
if(IoManager->InputData.ReflectLight < ONLINE && SpManager->Distance > 30) {
// ラインをまたぐまで直進
SubState = OverLine;
// ラインを跨いだので、ウェイポイントの座標に変更
SpManager->ResetPoint(BtManager->GetLine(BtManager->GetDstWayPointNo())->WayPoint);
} else {
IoManager->Forward(BlockMovePID.BasePower);
}
break;
// ラインをまたぐまでの処理
case OverLine:
if(IoManager->InputData.ReflectLight > EDGE_LINE) {
// ウェイポイントに到達したので、現在いるウェイポイントNoを更新
CurrentWayPointNo = BtManager->GetDstWayPointNo();
// 白認識(ラインを跨いだ)ので、次の状態に繊維
bool last = BtManager->ArrivalDstWayPoint();
// 最終ウェイポイントの場合
if(last) {
// ライントレース前の旋回動作に遷移
SubState = LineTurn;
// 旋回方向を判定
CW = IoManager->JudgeTurnCW(currentAngle, targetBlockAngle);
} else {
// 初回旋回に遷移
SubState = FirstTurn;
}
} else {
// ラインをまたぐまでは直進
IoManager->Forward(BlockMovePID.BasePower);
}
break;
// ライントレース前の旋回動作
case LineTurn:
// 旋回動作を実行
if(abs(targetBlockAngle - currentAngle) < 70 &&
(IoManager->InputData.ReflectLight < EDGE_LINE || IoManager->HSLKind == BtManager->GetDstBlockPositionColor()))
{
// 角度が一致したため、ライントレースに遷移
SubState = LineTrace;
// 旋回方向によって、ラインのどちら側を走行するか決定
LeftEdge = CW;
break;
}
IoManager->TurnWithBlock(CW, TURN_POWER, -0.3);
break;
// ライントレースする動作
case LineTrace:
//目標とするブロック置き場の色を取得したら、現在のステートをブロック運搬中に変更
if(IoManager->HSLKind == BtManager->GetDstBlockPositionColor()) ColorDetectCount++;
if(IoManager->HSLKind == HSLBlack) ColorDetectCount = 0;
if(ColorDetectCount > 10)
{
// ブロック置き場の座標に修正
SpManager->ResetPoint(BtManager->GetDstBlockPoint());
SpManager->Distance = 200;
SubState = Back;
break;
}
// ライントレース中は、ラインの角度に修正
{
int angle = BtManager->GetLine(CurrentWayPointNo)->GetAngle(BtManager->CurrentCommand.DestinationBlockPosition);
SpManager->ResetAngle(angle);
}
IoManager->LineTraceAction(BlockMovePID, EDGE_LINE, LeftEdge);
break;
// 後退する動作
case Back:
if(SpManager->Distance < 80) {
// 12cm後退したら、アプローチに遷移する
// ブロック置き場到達メッセージ
bool last = BtManager->ArrivalDstBlockPosition();
// 最後までやったら、やりきった感を出す
if (last) {
IoManager->Stop();
IoManager->WriteOutputMotor();
PlaySound(BlockEnd);
ParentStrategy->Manager->SetStrategy(NULL);
break;
}
auto approachState = new ApproachState(ParentStrategy);
approachState->CurrentWayPointNo = CurrentWayPointNo;
ParentStrategy->ChangeState(approachState);
break;
}
IoManager->Back(BlockMovePID.BasePower);
break;
}
}
<|endoftext|>
|
<commit_before>#include "physics/n_body_system.hpp"
#include <cmath>
#include <functional>
#include <vector>
#include "geometry/r3_element.hpp"
#ifndef _MANAGED
#include "glog/logging.h"
#endif
#include "integrators/symplectic_partitioned_runge_kutta_integrator.hpp"
#include "quantities/quantities.hpp"
using principia::geometry::R3Element;
using principia::integrators::SPRKIntegrator;
using principia::integrators::SymplecticIntegrator;
using principia::quantities::Acceleration;
using principia::quantities::Exponentiation;
using principia::quantities::GravitationalParameter;
using principia::quantities::Length;
using principia::quantities::Speed;
using principia::quantities::SIUnit;
namespace principia {
namespace physics {
template<typename InertialFrame>
NBodySystem<InertialFrame>::NBodySystem(
std::vector<Body<InertialFrame>*> const* bodies)
: bodies_(bodies) {}
template<typename InertialFrame>
NBodySystem<InertialFrame>::~NBodySystem() {
for (Body<InertialFrame>* body : *bodies_) {
delete body;
}
}
template<typename InertialFrame>
std::vector<Body<InertialFrame>*> const&
NBodySystem<InertialFrame>::bodies() const {
return *bodies_;
}
template<typename InertialFrame>
void NBodySystem<InertialFrame>::Integrate(
SymplecticIntegrator<Length, Speed> const& integrator,
Time const& tmax,
Time const& Δt,
int const sampling_period) {
SymplecticIntegrator<Length, Speed>::Parameters parameters;
SymplecticIntegrator<Length, Speed>::Solution solution;
// Prepare the input data.
std::unique_ptr<Time> reference_time;
for (Body<InertialFrame> const* body : *bodies_) {
R3Element<Length> const& position = body->positions().back().coordinates();
R3Element<Speed> const& velocity = body->velocities().back().coordinates();
Time const& time = body->times().back();
for (int i = 0; i < 3; ++i) {
parameters.q0.push_back(position[i]);
}
for (int i = 0; i < 3; ++i) {
parameters.p0.push_back(velocity[i]);
}
parameters.t0 = time;
// All the positions/velocities must be for the same time.
if (reference_time == nullptr) {
reference_time.reset(new Time(time));
} else {
#ifndef _MANAGED
CHECK_EQ(*reference_time, time);
#endif
}
}
parameters.tmax = tmax;
parameters.Δt = Δt;
parameters.sampling_period = sampling_period;
dynamic_cast<const SPRKIntegrator<Length, Speed>*>(&integrator)->Solve(
std::bind(&NBodySystem::ComputeGravitationalAccelerations, this,
std::placeholders::_1,
std::placeholders::_2,
std::placeholders::_3),
&ComputeGravitationalVelocities,
parameters, &solution);
#ifndef _MANAGED
// TODO(phl): Ignoring errors for now.
CHECK_EQ(solution.position.size(), solution.momentum.size());
#endif
std::vector<Time> const& t = solution.time.quantities;
// Loop over the bodies.
// TODO(phl): It looks like we are transposing in the integrator and then
// transposing here again.
for (size_t i = 0; i < solution.position.size(); i += 3) {
Body<InertialFrame>* body = (*bodies_)[i / 3];
std::vector<Length> const& q0 = solution.position[i + 0].quantities;
std::vector<Length> const& q1 = solution.position[i + 1].quantities;
std::vector<Length> const& q2 = solution.position[i + 2].quantities;
std::vector<Speed> const& p0 = solution.momentum[i + 0].quantities;
std::vector<Speed> const& p1 = solution.momentum[i + 1].quantities;
std::vector<Speed> const& p2 = solution.momentum[i + 2].quantities;
#ifndef _MANAGED
CHECK_EQ(t.size(), q0.size());
CHECK_EQ(t.size(), q1.size());
CHECK_EQ(t.size(), q2.size());
CHECK_EQ(t.size(), p0.size());
CHECK_EQ(t.size(), p1.size());
CHECK_EQ(t.size(), p2.size());
#endif
for (size_t j = 0; j < t.size(); ++j) {
Vector<Length, InertialFrame> const position(
R3Element<Length>(q0[j], q1[j], q2[j]));
Vector<Speed, InertialFrame> const velocity(
R3Element<Speed>(p0[j], p1[j], p2[j]));
Time const time = t[j];
body->AppendToTrajectory(position, velocity, time);
}
}
}
template<typename InertialFrame>
void NBodySystem<InertialFrame>::ComputeGravitationalAccelerations(
Time const& t,
std::vector<Length> const& q,
std::vector<Acceleration>* result) const {
result->assign(result->size(), Acceleration());
// TODO(phl): Used to deal with proper accelerations here.
for (size_t b1 = 0, three_b1 = 0; b1 < bodies_->size(); ++b1, three_b1 += 3) {
Body<InertialFrame> const& body1 = *(*bodies_)[b1];
bool const body1_is_massless = body1.is_massless();
for (size_t b2 = b1 + 1; b2 < bodies_->size(); ++b2) {
Body<InertialFrame> const& body2 = *(*bodies_)[b2];
bool const body2_is_massless = body2.is_massless();
size_t three_b2 = 3 * b2;
if (!body1_is_massless || !body2_is_massless) {
Length const Δq0 = q[three_b1] - q[three_b2];
Length const Δq1 = q[three_b1 + 1] - q[three_b2 + 1];
Length const Δq2 = q[three_b1 + 2] - q[three_b2 + 2];
Exponentiation<Length, 2> const squared_distance =
Δq0 * Δq0 + Δq1 * Δq1 + Δq2 * Δq2;
Exponentiation<Length, -3> const multiplier =
Sqrt(squared_distance) / (squared_distance * squared_distance);
if (!body2_is_massless) {
auto const μ2OverRSquared =
body2.gravitational_parameter() * multiplier;
(*result)[three_b1] -= Δq0 * μ2OverRSquared;
(*result)[three_b1 + 1] -= Δq1 * μ2OverRSquared;
(*result)[three_b1 + 2] -= Δq2 * μ2OverRSquared;
}
// Lex. III. Actioni contrariam semper & æqualem esse reactionem:
// sive corporum duorum actiones in se mutuo semper esse æquales &
// in partes contrarias dirigi.
if (!body1_is_massless) {
auto const μ1OverRSquared =
body1.gravitational_parameter() * multiplier;
(*result)[three_b2] += Δq0 * μ1OverRSquared;
(*result)[three_b2 + 1] += Δq1 * μ1OverRSquared;
(*result)[three_b2 + 2] += Δq2 * μ1OverRSquared;
}
}
}
}
}
template<typename InertialFrame>
void NBodySystem<InertialFrame>::ComputeGravitationalVelocities(
std::vector<Speed> const& p,
std::vector<Speed>* result) {
*result = p;
}
} // namespace physics
} // namespace principia
<commit_msg>After eggrobin's review.<commit_after>#include "physics/n_body_system.hpp"
#include <cmath>
#include <functional>
#include <vector>
#include "geometry/r3_element.hpp"
#ifndef _MANAGED
#include "glog/logging.h"
#endif
#include "integrators/symplectic_partitioned_runge_kutta_integrator.hpp"
#include "quantities/quantities.hpp"
using principia::geometry::R3Element;
using principia::integrators::SPRKIntegrator;
using principia::integrators::SymplecticIntegrator;
using principia::quantities::Acceleration;
using principia::quantities::Exponentiation;
using principia::quantities::GravitationalParameter;
using principia::quantities::Length;
using principia::quantities::Speed;
using principia::quantities::SIUnit;
namespace principia {
namespace physics {
template<typename InertialFrame>
NBodySystem<InertialFrame>::NBodySystem(
std::vector<Body<InertialFrame>*> const* bodies)
: bodies_(bodies) {}
template<typename InertialFrame>
NBodySystem<InertialFrame>::~NBodySystem() {
for (Body<InertialFrame>* body : *bodies_) {
delete body;
}
}
template<typename InertialFrame>
std::vector<Body<InertialFrame>*> const&
NBodySystem<InertialFrame>::bodies() const {
return *bodies_;
}
template<typename InertialFrame>
void NBodySystem<InertialFrame>::Integrate(
SymplecticIntegrator<Length, Speed> const& integrator,
Time const& tmax,
Time const& Δt,
int const sampling_period) {
SymplecticIntegrator<Length, Speed>::Parameters parameters;
SymplecticIntegrator<Length, Speed>::Solution solution;
// Prepare the input data.
std::unique_ptr<Time> reference_time;
for (Body<InertialFrame> const* body : *bodies_) {
R3Element<Length> const& position = body->positions().back().coordinates();
R3Element<Speed> const& velocity = body->velocities().back().coordinates();
Time const& time = body->times().back();
for (int i = 0; i < 3; ++i) {
parameters.q0.push_back(position[i]);
}
for (int i = 0; i < 3; ++i) {
parameters.p0.push_back(velocity[i]);
}
parameters.t0 = time;
// All the positions/velocities must be for the same time.
if (reference_time == nullptr) {
reference_time.reset(new Time(time));
} else {
#ifndef _MANAGED
CHECK_EQ(*reference_time, time);
#endif
}
}
parameters.tmax = tmax;
parameters.Δt = Δt;
parameters.sampling_period = sampling_period;
dynamic_cast<const SPRKIntegrator<Length, Speed>*>(&integrator)->Solve(
std::bind(&NBodySystem::ComputeGravitationalAccelerations, this,
std::placeholders::_1,
std::placeholders::_2,
std::placeholders::_3),
&ComputeGravitationalVelocities,
parameters, &solution);
#ifndef _MANAGED
// TODO(phl): Ignoring errors for now.
CHECK_EQ(solution.position.size(), solution.momentum.size());
#endif
std::vector<Time> const& t = solution.time.quantities;
// Loop over the bodies.
// TODO(phl): It looks like we are transposing in the integrator and then
// transposing here again.
for (size_t i = 0; i < solution.position.size(); i += 3) {
Body<InertialFrame>* body = (*bodies_)[i / 3];
std::vector<Length> const& q0 = solution.position[i + 0].quantities;
std::vector<Length> const& q1 = solution.position[i + 1].quantities;
std::vector<Length> const& q2 = solution.position[i + 2].quantities;
std::vector<Speed> const& p0 = solution.momentum[i + 0].quantities;
std::vector<Speed> const& p1 = solution.momentum[i + 1].quantities;
std::vector<Speed> const& p2 = solution.momentum[i + 2].quantities;
#ifndef _MANAGED
CHECK_EQ(t.size(), q0.size());
CHECK_EQ(t.size(), q1.size());
CHECK_EQ(t.size(), q2.size());
CHECK_EQ(t.size(), p0.size());
CHECK_EQ(t.size(), p1.size());
CHECK_EQ(t.size(), p2.size());
#endif
for (size_t j = 0; j < t.size(); ++j) {
Vector<Length, InertialFrame> const position(
R3Element<Length>(q0[j], q1[j], q2[j]));
Vector<Speed, InertialFrame> const velocity(
R3Element<Speed>(p0[j], p1[j], p2[j]));
Time const time = t[j];
body->AppendToTrajectory(position, velocity, time);
}
}
}
template<typename InertialFrame>
void NBodySystem<InertialFrame>::ComputeGravitationalAccelerations(
Time const& t,
std::vector<Length> const& q,
std::vector<Acceleration>* result) const {
result->assign(result->size(), Acceleration());
// TODO(phl): Used to deal with proper accelerations here.
for (size_t b1 = 0, three_b1 = 0; b1 < bodies_->size(); ++b1, three_b1 += 3) {
Body<InertialFrame> const& body1 = *(*bodies_)[b1];
bool const body1_is_massless = body1.is_massless();
for (size_t b2 = b1 + 1; b2 < bodies_->size(); ++b2) {
Body<InertialFrame> const& body2 = *(*bodies_)[b2];
bool const body2_is_massless = body2.is_massless();
size_t const three_b2 = 3 * b2;
if (!body1_is_massless || !body2_is_massless) {
Length const Δq0 = q[three_b1] - q[three_b2];
Length const Δq1 = q[three_b1 + 1] - q[three_b2 + 1];
Length const Δq2 = q[three_b1 + 2] - q[three_b2 + 2];
Exponentiation<Length, 2> const squared_distance =
Δq0 * Δq0 + Δq1 * Δq1 + Δq2 * Δq2;
Exponentiation<Length, -3> const multiplier =
Sqrt(squared_distance) / (squared_distance * squared_distance);
if (!body2_is_massless) {
auto const μ2OverRSquared =
body2.gravitational_parameter() * multiplier;
(*result)[three_b1] -= Δq0 * μ2OverRSquared;
(*result)[three_b1 + 1] -= Δq1 * μ2OverRSquared;
(*result)[three_b1 + 2] -= Δq2 * μ2OverRSquared;
}
// Lex. III. Actioni contrariam semper & æqualem esse reactionem:
// sive corporum duorum actiones in se mutuo semper esse æquales &
// in partes contrarias dirigi.
if (!body1_is_massless) {
auto const μ1OverRSquared =
body1.gravitational_parameter() * multiplier;
(*result)[three_b2] += Δq0 * μ1OverRSquared;
(*result)[three_b2 + 1] += Δq1 * μ1OverRSquared;
(*result)[three_b2 + 2] += Δq2 * μ1OverRSquared;
}
}
}
}
}
template<typename InertialFrame>
void NBodySystem<InertialFrame>::ComputeGravitationalVelocities(
std::vector<Speed> const& p,
std::vector<Speed>* result) {
*result = p;
}
} // namespace physics
} // namespace principia
<|endoftext|>
|
<commit_before><commit_msg>bugfix<commit_after><|endoftext|>
|
<commit_before>#include "physics/n_body_system.hpp"
#include <map>
#include <memory>
#include <string>
#include <vector>
#include "geometry/grassmann.hpp"
#include "geometry/point.hpp"
#include "gmock/gmock.h"
#include "gtest/gtest.h"
#include "physics/body.hpp"
#include "physics/trajectory.hpp"
#include "quantities/constants.hpp"
#include "quantities/numbers.hpp"
#include "testing_utilities/almost_equals.hpp"
#include "testing_utilities/death_message.hpp"
using principia::constants::GravitationalConstant;
using principia::geometry::Barycentre;
using principia::geometry::Point;
using principia::geometry::Vector;
using principia::quantities::Pow;
using principia::quantities::SIUnit;
using principia::testing_utilities::AlmostEquals;
using principia::testing_utilities::DeathMessage;
using testing::Eq;
using testing::Lt;
namespace principia {
namespace physics {
class NBodySystemTest : public testing::Test {
protected:
struct EarthMoonBarycentricFrame;
void SetUp() override {
integrator_.Initialize(integrator_.Order5Optimal());
// The Earth-Moon system, roughly, with a circular orbit with velocities
// in the center-of-mass frame.
body1_ = std::make_unique<Body>(6E24 * SIUnit<Mass>());
body2_ = std::make_unique<Body>(7E22 * SIUnit<Mass>());
// A massless probe.
body3_ = std::make_unique<Body>(0 * SIUnit<Mass>());
trajectory1_ =
std::make_unique<Trajectory<EarthMoonBarycentricFrame>>(*body1_);
trajectory2_ =
std::make_unique<Trajectory<EarthMoonBarycentricFrame>>(*body2_);
trajectory3_ =
std::make_unique<Trajectory<EarthMoonBarycentricFrame>>(*body3_);
Point<Vector<Length, EarthMoonBarycentricFrame>> const
q1(Vector<Length, EarthMoonBarycentricFrame>({0 * SIUnit<Length>(),
0 * SIUnit<Length>(),
0 * SIUnit<Length>()}));
Point<Vector<Length, EarthMoonBarycentricFrame>> const
q2(Vector<Length, EarthMoonBarycentricFrame>({0 * SIUnit<Length>(),
4E8 * SIUnit<Length>(),
0 * SIUnit<Length>()}));
Point<Vector<Length, EarthMoonBarycentricFrame>> const centre_of_mass =
Barycentre(q1, body1_->mass(), q2, body2_->mass());
Length const semi_major_axis = (q1 - q2).Norm();
period_ = 2 * π * Sqrt(Pow<3>(semi_major_axis) /
(body1_->gravitational_parameter() +
body2_->gravitational_parameter()));
Point<Vector<Speed, EarthMoonBarycentricFrame>> const
v1(Vector<Speed, EarthMoonBarycentricFrame>({
-2 * π * (q1 - centre_of_mass).Norm() / period_,
0 * SIUnit<Speed>(),
0 * SIUnit<Speed>()}));
Point<Vector<Speed, EarthMoonBarycentricFrame>> const
v2(Vector<Speed, EarthMoonBarycentricFrame>({
2 * π * (q2 - centre_of_mass).Norm() / period_,
0 * SIUnit<Speed>(),
0 * SIUnit<Speed>()}));
Point<Vector<Speed, EarthMoonBarycentricFrame>> const overall_velocity =
Barycentre(v1, body1_->mass(), v2, body2_->mass());
trajectory1_->Append(0 * SIUnit<Time>(),
{q1 - centre_of_mass, v1 - overall_velocity});
trajectory2_->Append(0 * SIUnit<Time>(),
{q2 - centre_of_mass, v2 - overall_velocity});
system_ = std::make_unique<NBodySystem<EarthMoonBarycentricFrame>>();
}
template<typename Scalar, typename Frame>
std::string ToMathematicaString(Vector<Scalar, Frame> const& vector) {
R3Element<Scalar> const& coordinates = vector.coordinates();
std::string result = "{";
result += quantities::DebugString(coordinates.x);
result += ",";
result += quantities::DebugString(coordinates.y);
result += ",";
result += quantities::DebugString(coordinates.z);
result += "}";
return result;
}
template<typename Scalar, typename Frame>
std::string ToMathematicaString(
std::vector<Vector<Scalar, Frame>> const& vectors) {
static std::string const mathematica_line =
"\n(*****************************************************)\n";
std::string result = mathematica_line;
result += "ToExpression[StringReplace[\"\n{";
std::string separator = "";
for (const auto& vector : vectors) {
result += separator;
result += ToMathematicaString(vector);
separator = ",\n";
}
result +=
"}\",\n{\" m\"->\"\",\"e\"->\"*^\", \"\\n\"->\"\", \" \"->\"\"}]];";
result += mathematica_line;
return result;
}
template<typename T1, typename T2>
std::vector<T2> ValuesOf(std::map<T1, T2> const& m) {
std::vector<T2> result;
for (auto const it : m) {
result.push_back(it.second);
}
return result;
}
std::unique_ptr<Body> body1_;
std::unique_ptr<Body> body2_;
std::unique_ptr<Body> body3_;
std::unique_ptr<Trajectory<EarthMoonBarycentricFrame>> trajectory1_;
std::unique_ptr<Trajectory<EarthMoonBarycentricFrame>> trajectory2_;
std::unique_ptr<Trajectory<EarthMoonBarycentricFrame>> trajectory3_;
SPRKIntegrator<Length, Speed> integrator_;
Time period_;
std::unique_ptr<NBodySystem<EarthMoonBarycentricFrame>> system_;
};
typedef NBodySystemTest NBodySystemDeathTest;
TEST_F(NBodySystemDeathTest, IntegrateError) {
EXPECT_DEATH({
system_->Integrate(integrator_,
period_,
period_ / 100,
1,
{trajectory1_.get(),
trajectory2_.get(),
trajectory1_.get()});
}, DeathMessage("Multiple trajectories"));
EXPECT_DEATH({
std::unique_ptr<Trajectory<EarthMoonBarycentricFrame>> trajectory(
new Trajectory<EarthMoonBarycentricFrame>(*body2_));
trajectory->Append(1 * SIUnit<Time>(),
{Vector<Length, EarthMoonBarycentricFrame>(),
Vector<Speed, EarthMoonBarycentricFrame>()});
system_->Integrate(integrator_,
period_,
period_ / 100,
1,
{trajectory1_.get(), trajectory.get()});
}, DeathMessage("Inconsistent last time"));
}
// The canonical Earth-Moon system, tuned to produce circular orbits.
TEST_F(NBodySystemTest, EarthMoon) {
std::vector<Vector<Length, EarthMoonBarycentricFrame>> positions;
system_->Integrate(integrator_,
period_,
period_ / 100,
1,
{trajectory1_.get(), trajectory2_.get()});
positions = ValuesOf(trajectory1_->Positions());
EXPECT_THAT(positions.size(), Eq(101));
LOG(INFO) << ToMathematicaString(positions);
EXPECT_THAT(Abs(positions[25].coordinates().y), Lt(3E-2 * SIUnit<Length>()));
EXPECT_THAT(Abs(positions[50].coordinates().x), Lt(3E-2 * SIUnit<Length>()));
EXPECT_THAT(Abs(positions[75].coordinates().y), Lt(3E-2 * SIUnit<Length>()));
EXPECT_THAT(Abs(positions[100].coordinates().x), Lt(3E-2 * SIUnit<Length>()));
positions = ValuesOf(trajectory2_->Positions());
LOG(INFO) << ToMathematicaString(positions);
EXPECT_THAT(positions.size(), Eq(101));
EXPECT_THAT(Abs(positions[25].coordinates().y), Lt(2 * SIUnit<Length>()));
EXPECT_THAT(Abs(positions[50].coordinates().x), Lt(2 * SIUnit<Length>()));
EXPECT_THAT(Abs(positions[75].coordinates().y), Lt(2 * SIUnit<Length>()));
EXPECT_THAT(Abs(positions[100].coordinates().x), Lt(2 * SIUnit<Length>()));
}
// Same as above, but the trajectories are passed in the reverse order.
TEST_F(NBodySystemTest, MoonEarth) {
std::vector<Vector<Length, EarthMoonBarycentricFrame>> positions;
system_->Integrate(integrator_,
period_,
period_ / 100,
1,
{trajectory2_.get(), trajectory1_.get()});
positions = ValuesOf(trajectory1_->Positions());
EXPECT_THAT(positions.size(), Eq(101));
LOG(INFO) << ToMathematicaString(positions);
EXPECT_THAT(Abs(positions[25].coordinates().y), Lt(3E-2 * SIUnit<Length>()));
EXPECT_THAT(Abs(positions[50].coordinates().x), Lt(3E-2 * SIUnit<Length>()));
EXPECT_THAT(Abs(positions[75].coordinates().y), Lt(3E-2 * SIUnit<Length>()));
EXPECT_THAT(Abs(positions[100].coordinates().x), Lt(3E-2 * SIUnit<Length>()));
positions = ValuesOf(trajectory2_->Positions());
LOG(INFO) << ToMathematicaString(positions);
EXPECT_THAT(positions.size(), Eq(101));
EXPECT_THAT(Abs(positions[25].coordinates().y), Lt(2 * SIUnit<Length>()));
EXPECT_THAT(Abs(positions[50].coordinates().x), Lt(2 * SIUnit<Length>()));
EXPECT_THAT(Abs(positions[75].coordinates().y), Lt(2 * SIUnit<Length>()));
EXPECT_THAT(Abs(positions[100].coordinates().x), Lt(2 * SIUnit<Length>()));
}
// The Moon alone. It moves in straight line.
TEST_F(NBodySystemTest, Moon) {
system_->Integrate(integrator_,
period_,
period_ / 100,
1,
{trajectory2_.get()});
Length const q2 = trajectory2_->last_position().coordinates().y;
Speed const v2 = trajectory2_->last_velocity().coordinates().x;
std::vector<Vector<Length, EarthMoonBarycentricFrame>> const positions =
ValuesOf(trajectory2_->Positions());
LOG(INFO) << ToMathematicaString(positions);
EXPECT_THAT(positions.size(), Eq(101));
EXPECT_THAT(positions[25].coordinates().x, Eq(0.25 * period_ * v2));
EXPECT_THAT(positions[25].coordinates().y, Eq(q2));
EXPECT_THAT(positions[50].coordinates().x, Eq(0.50 * period_ * v2));
EXPECT_THAT(positions[50].coordinates().y, Eq(q2));
EXPECT_THAT(positions[75].coordinates().x,
AlmostEquals(0.75 * period_ * v2, 1));
EXPECT_THAT(positions[75].coordinates().y, Eq(q2));
EXPECT_THAT(positions[100].coordinates().x, Eq(1.00 * period_ * v2));
EXPECT_THAT(positions[100].coordinates().y, Eq(q2));
}
// The Earth and a massless probe 1 billion meters away, with the same velocity,
// and an acceleration which exactly compensates gravitational attraction. Both
// bodies move in straight lines.
TEST_F(NBodySystemTest, EarthProbe) {
Length const distance = 1E9 * SIUnit<Length>();
trajectory3_->Append(trajectory1_->last_time(),
{trajectory1_->last_position() +
Vector<Length, EarthMoonBarycentricFrame>(
{0 * SIUnit<Length>(),
distance,
0 * SIUnit<Length>()}),
trajectory1_->last_velocity()});
trajectory3_->set_intrinsic_acceleration(
[this, distance](Time const& t) {
return Vector<Acceleration, EarthMoonBarycentricFrame>(
{0 * SIUnit<Acceleration>(),
body1_->gravitational_parameter() / (distance * distance),
0 * SIUnit<Acceleration>()});});
system_->Integrate(integrator_,
period_,
period_ / 100,
1,
{trajectory1_.get(), trajectory3_.get()});
Length const q1 = trajectory1_->last_position().coordinates().y;
Speed const v1 = trajectory1_->last_velocity().coordinates().x;
std::vector<Vector<Length, EarthMoonBarycentricFrame>> const positions1 =
ValuesOf(trajectory1_->Positions());
LOG(INFO) << ToMathematicaString(positions1);
EXPECT_THAT(positions1.size(), Eq(101));
EXPECT_THAT(positions1[25].coordinates().x,
AlmostEquals(0.25 * period_ * v1, 1));
EXPECT_THAT(positions1[25].coordinates().y, Eq(q1));
EXPECT_THAT(positions1[50].coordinates().x,
AlmostEquals(0.50 * period_ * v1, 1));
EXPECT_THAT(positions1[50].coordinates().y, Eq(q1));
EXPECT_THAT(positions1[75].coordinates().x,
AlmostEquals(0.75 * period_ * v1, 1));
EXPECT_THAT(positions1[75].coordinates().y, Eq(q1));
EXPECT_THAT(positions1[100].coordinates().x,
AlmostEquals(1.00 * period_ * v1, 1));
EXPECT_THAT(positions1[100].coordinates().y, Eq(q1));
Length const q3 = trajectory3_->last_position().coordinates().y;
Speed const v3 = trajectory3_->last_velocity().coordinates().x;
std::vector<Vector<Length, EarthMoonBarycentricFrame>> const positions3 =
ValuesOf(trajectory3_->Positions());
LOG(INFO) << ToMathematicaString(positions3);
EXPECT_THAT(positions3.size(), Eq(101));
EXPECT_THAT(positions3[25].coordinates().x,
AlmostEquals(0.25 * period_ * v3, 1));
EXPECT_THAT(positions3[25].coordinates().y, AlmostEquals(q3, 2));
EXPECT_THAT(positions3[50].coordinates().x,
AlmostEquals(0.50 * period_ * v3, 1));
EXPECT_THAT(positions3[50].coordinates().y, AlmostEquals(q3, 2));
EXPECT_THAT(positions3[75].coordinates().x,
AlmostEquals(0.75 * period_ * v3, 1));
EXPECT_THAT(positions3[75].coordinates().y, AlmostEquals(q3, 1));
EXPECT_THAT(positions3[100].coordinates().x,
AlmostEquals(1.00 * period_ * v3, 1));
EXPECT_THAT(positions3[100].coordinates().y, Eq(q3));
}
} // namespace physics
} // namespace principia
<commit_msg>Fix test (partially).<commit_after>#include "physics/n_body_system.hpp"
#include <map>
#include <memory>
#include <string>
#include <vector>
#include "geometry/grassmann.hpp"
#include "geometry/point.hpp"
#include "gmock/gmock.h"
#include "gtest/gtest.h"
#include "physics/body.hpp"
#include "physics/trajectory.hpp"
#include "quantities/constants.hpp"
#include "quantities/numbers.hpp"
#include "testing_utilities/almost_equals.hpp"
#include "testing_utilities/death_message.hpp"
using principia::constants::GravitationalConstant;
using principia::geometry::Barycentre;
using principia::geometry::Point;
using principia::geometry::Vector;
using principia::quantities::Pow;
using principia::quantities::SIUnit;
using principia::testing_utilities::AlmostEquals;
using principia::testing_utilities::DeathMessage;
using testing::Eq;
using testing::Lt;
namespace principia {
namespace physics {
class NBodySystemTest : public testing::Test {
protected:
struct EarthMoonBarycentricFrame;
void SetUp() override {
integrator_.Initialize(integrator_.Order5Optimal());
// The Earth-Moon system, roughly, with a circular orbit with velocities
// in the center-of-mass frame.
body1_ = std::make_unique<Body>(6E24 * SIUnit<Mass>());
body2_ = std::make_unique<Body>(7E22 * SIUnit<Mass>());
// A massless probe.
body3_ = std::make_unique<Body>(0 * SIUnit<Mass>());
trajectory1_ =
std::make_unique<Trajectory<EarthMoonBarycentricFrame>>(*body1_);
trajectory2_ =
std::make_unique<Trajectory<EarthMoonBarycentricFrame>>(*body2_);
trajectory3_ =
std::make_unique<Trajectory<EarthMoonBarycentricFrame>>(*body3_);
Point<Vector<Length, EarthMoonBarycentricFrame>> const
q1(Vector<Length, EarthMoonBarycentricFrame>({0 * SIUnit<Length>(),
0 * SIUnit<Length>(),
0 * SIUnit<Length>()}));
Point<Vector<Length, EarthMoonBarycentricFrame>> const
q2(Vector<Length, EarthMoonBarycentricFrame>({0 * SIUnit<Length>(),
4E8 * SIUnit<Length>(),
0 * SIUnit<Length>()}));
Point<Vector<Length, EarthMoonBarycentricFrame>> const centre_of_mass =
Barycentre<Vector<Length, EarthMoonBarycentricFrame>, Mass>(
{q1, q2}, {body1_->mass(), body2_->mass()});
Length const semi_major_axis = (q1 - q2).Norm();
period_ = 2 * π * Sqrt(Pow<3>(semi_major_axis) /
(body1_->gravitational_parameter() +
body2_->gravitational_parameter()));
Point<Vector<Speed, EarthMoonBarycentricFrame>> const
v1(Vector<Speed, EarthMoonBarycentricFrame>({
-2 * π * (q1 - centre_of_mass).Norm() / period_,
0 * SIUnit<Speed>(),
0 * SIUnit<Speed>()}));
Point<Vector<Speed, EarthMoonBarycentricFrame>> const
v2(Vector<Speed, EarthMoonBarycentricFrame>({
2 * π * (q2 - centre_of_mass).Norm() / period_,
0 * SIUnit<Speed>(),
0 * SIUnit<Speed>()}));
Point<Vector<Speed, EarthMoonBarycentricFrame>> const overall_velocity =
Barycentre<Vector<Speed, EarthMoonBarycentricFrame>, Mass>(
{v1, v2}, {body1_->mass(), body2_->mass()});
trajectory1_->Append(0 * SIUnit<Time>(), {q1, v1});
trajectory2_->Append(0 * SIUnit<Time>(), {q2, v2});
system_ = std::make_unique<NBodySystem<EarthMoonBarycentricFrame>>();
}
template<typename Scalar, typename Frame>
std::string ToMathematicaString(Vector<Scalar, Frame> const& vector) {
R3Element<Scalar> const& coordinates = vector.coordinates();
std::string result = "{";
result += quantities::DebugString(coordinates.x);
result += ",";
result += quantities::DebugString(coordinates.y);
result += ",";
result += quantities::DebugString(coordinates.z);
result += "}";
return result;
}
template<typename Scalar, typename Frame>
std::string ToMathematicaString(
std::vector<Vector<Scalar, Frame>> const& vectors) {
static std::string const mathematica_line =
"\n(*****************************************************)\n";
std::string result = mathematica_line;
result += "ToExpression[StringReplace[\"\n{";
std::string separator = "";
for (const auto& vector : vectors) {
result += separator;
result += ToMathematicaString(vector);
separator = ",\n";
}
result +=
"}\",\n{\" m\"->\"\",\"e\"->\"*^\", \"\\n\"->\"\", \" \"->\"\"}]];";
result += mathematica_line;
return result;
}
template<typename T1, typename T2>
std::vector<T2> ValuesOf(std::map<T1, T2> const& m) {
std::vector<T2> result;
for (auto const it : m) {
result.push_back(it.second);
}
return result;
}
std::unique_ptr<Body> body1_;
std::unique_ptr<Body> body2_;
std::unique_ptr<Body> body3_;
std::unique_ptr<Trajectory<EarthMoonBarycentricFrame>> trajectory1_;
std::unique_ptr<Trajectory<EarthMoonBarycentricFrame>> trajectory2_;
std::unique_ptr<Trajectory<EarthMoonBarycentricFrame>> trajectory3_;
SPRKIntegrator<Length, Speed> integrator_;
Time period_;
std::unique_ptr<NBodySystem<EarthMoonBarycentricFrame>> system_;
};
typedef NBodySystemTest NBodySystemDeathTest;
TEST_F(NBodySystemDeathTest, IntegrateError) {
EXPECT_DEATH({
system_->Integrate(integrator_,
period_,
period_ / 100,
1,
{trajectory1_.get(),
trajectory2_.get(),
trajectory1_.get()});
}, DeathMessage("Multiple trajectories"));
EXPECT_DEATH({
std::unique_ptr<Trajectory<EarthMoonBarycentricFrame>> trajectory(
new Trajectory<EarthMoonBarycentricFrame>(*body2_));
trajectory->Append(1 * SIUnit<Time>(),
{Point<Vector<Length, EarthMoonBarycentricFrame>>(),
Point<Vector<Speed, EarthMoonBarycentricFrame>>()});
system_->Integrate(integrator_,
period_,
period_ / 100,
1,
{trajectory1_.get(), trajectory.get()});
}, DeathMessage("Inconsistent last time"));
}
// The canonical Earth-Moon system, tuned to produce circular orbits.
TEST_F(NBodySystemTest, EarthMoon) {
std::vector<Vector<Length, EarthMoonBarycentricFrame>> positions;
system_->Integrate(integrator_,
period_,
period_ / 100,
1,
{trajectory1_.get(), trajectory2_.get()});
positions = ValuesOf(trajectory1_->Positions());
EXPECT_THAT(positions.size(), Eq(101));
LOG(INFO) << ToMathematicaString(positions);
EXPECT_THAT(Abs(positions[25].coordinates().y), Lt(3E-2 * SIUnit<Length>()));
EXPECT_THAT(Abs(positions[50].coordinates().x), Lt(3E-2 * SIUnit<Length>()));
EXPECT_THAT(Abs(positions[75].coordinates().y), Lt(3E-2 * SIUnit<Length>()));
EXPECT_THAT(Abs(positions[100].coordinates().x), Lt(3E-2 * SIUnit<Length>()));
positions = ValuesOf(trajectory2_->Positions());
LOG(INFO) << ToMathematicaString(positions);
EXPECT_THAT(positions.size(), Eq(101));
EXPECT_THAT(Abs(positions[25].coordinates().y), Lt(2 * SIUnit<Length>()));
EXPECT_THAT(Abs(positions[50].coordinates().x), Lt(2 * SIUnit<Length>()));
EXPECT_THAT(Abs(positions[75].coordinates().y), Lt(2 * SIUnit<Length>()));
EXPECT_THAT(Abs(positions[100].coordinates().x), Lt(2 * SIUnit<Length>()));
}
// Same as above, but the trajectories are passed in the reverse order.
TEST_F(NBodySystemTest, MoonEarth) {
std::vector<Vector<Length, EarthMoonBarycentricFrame>> positions;
system_->Integrate(integrator_,
period_,
period_ / 100,
1,
{trajectory2_.get(), trajectory1_.get()});
positions = ValuesOf(trajectory1_->Positions());
EXPECT_THAT(positions.size(), Eq(101));
LOG(INFO) << ToMathematicaString(positions);
EXPECT_THAT(Abs(positions[25].coordinates().y), Lt(3E-2 * SIUnit<Length>()));
EXPECT_THAT(Abs(positions[50].coordinates().x), Lt(3E-2 * SIUnit<Length>()));
EXPECT_THAT(Abs(positions[75].coordinates().y), Lt(3E-2 * SIUnit<Length>()));
EXPECT_THAT(Abs(positions[100].coordinates().x), Lt(3E-2 * SIUnit<Length>()));
positions = ValuesOf(trajectory2_->Positions());
LOG(INFO) << ToMathematicaString(positions);
EXPECT_THAT(positions.size(), Eq(101));
EXPECT_THAT(Abs(positions[25].coordinates().y), Lt(2 * SIUnit<Length>()));
EXPECT_THAT(Abs(positions[50].coordinates().x), Lt(2 * SIUnit<Length>()));
EXPECT_THAT(Abs(positions[75].coordinates().y), Lt(2 * SIUnit<Length>()));
EXPECT_THAT(Abs(positions[100].coordinates().x), Lt(2 * SIUnit<Length>()));
}
// The Moon alone. It moves in straight line.
TEST_F(NBodySystemTest, Moon) {
system_->Integrate(integrator_,
period_,
period_ / 100,
1,
{trajectory2_.get()});
Length const q2 = trajectory2_->last_position().coordinates().y;
Speed const v2 = trajectory2_->last_velocity().coordinates().x;
std::vector<Vector<Length, EarthMoonBarycentricFrame>> const positions =
ValuesOf(trajectory2_->Positions());
LOG(INFO) << ToMathematicaString(positions);
EXPECT_THAT(positions.size(), Eq(101));
EXPECT_THAT(positions[25].coordinates().x, Eq(0.25 * period_ * v2));
EXPECT_THAT(positions[25].coordinates().y, Eq(q2));
EXPECT_THAT(positions[50].coordinates().x, Eq(0.50 * period_ * v2));
EXPECT_THAT(positions[50].coordinates().y, Eq(q2));
EXPECT_THAT(positions[75].coordinates().x,
AlmostEquals(0.75 * period_ * v2, 1));
EXPECT_THAT(positions[75].coordinates().y, Eq(q2));
EXPECT_THAT(positions[100].coordinates().x, Eq(1.00 * period_ * v2));
EXPECT_THAT(positions[100].coordinates().y, Eq(q2));
}
// The Earth and a massless probe 1 billion meters away, with the same velocity,
// and an acceleration which exactly compensates gravitational attraction. Both
// bodies move in straight lines.
TEST_F(NBodySystemTest, EarthProbe) {
Length const distance = 1E9 * SIUnit<Length>();
trajectory3_->Append(trajectory1_->last_time(),
{trajectory1_->last_position() +
Vector<Length, EarthMoonBarycentricFrame>(
{0 * SIUnit<Length>(),
distance,
0 * SIUnit<Length>()}),
trajectory1_->last_velocity()});
trajectory3_->set_intrinsic_acceleration(
[this, distance](Time const& t) {
return Vector<Acceleration, EarthMoonBarycentricFrame>(
{0 * SIUnit<Acceleration>(),
body1_->gravitational_parameter() / (distance * distance),
0 * SIUnit<Acceleration>()});});
system_->Integrate(integrator_,
period_,
period_ / 100,
1,
{trajectory1_.get(), trajectory3_.get()});
Length const q1 = trajectory1_->last_position().coordinates().y;
Speed const v1 = trajectory1_->last_velocity().coordinates().x;
std::vector<Vector<Length, EarthMoonBarycentricFrame>> const positions1 =
ValuesOf(trajectory1_->Positions());
LOG(INFO) << ToMathematicaString(positions1);
EXPECT_THAT(positions1.size(), Eq(101));
EXPECT_THAT(positions1[25].coordinates().x,
AlmostEquals(0.25 * period_ * v1, 1));
EXPECT_THAT(positions1[25].coordinates().y, Eq(q1));
EXPECT_THAT(positions1[50].coordinates().x,
AlmostEquals(0.50 * period_ * v1, 1));
EXPECT_THAT(positions1[50].coordinates().y, Eq(q1));
EXPECT_THAT(positions1[75].coordinates().x,
AlmostEquals(0.75 * period_ * v1, 1));
EXPECT_THAT(positions1[75].coordinates().y, Eq(q1));
EXPECT_THAT(positions1[100].coordinates().x,
AlmostEquals(1.00 * period_ * v1, 1));
EXPECT_THAT(positions1[100].coordinates().y, Eq(q1));
Length const q3 = trajectory3_->last_position().coordinates().y;
Speed const v3 = trajectory3_->last_velocity().coordinates().x;
std::vector<Vector<Length, EarthMoonBarycentricFrame>> const positions3 =
ValuesOf(trajectory3_->Positions());
LOG(INFO) << ToMathematicaString(positions3);
EXPECT_THAT(positions3.size(), Eq(101));
EXPECT_THAT(positions3[25].coordinates().x,
AlmostEquals(0.25 * period_ * v3, 1));
EXPECT_THAT(positions3[25].coordinates().y, AlmostEquals(q3, 2));
EXPECT_THAT(positions3[50].coordinates().x,
AlmostEquals(0.50 * period_ * v3, 1));
EXPECT_THAT(positions3[50].coordinates().y, AlmostEquals(q3, 2));
EXPECT_THAT(positions3[75].coordinates().x,
AlmostEquals(0.75 * period_ * v3, 1));
EXPECT_THAT(positions3[75].coordinates().y, AlmostEquals(q3, 1));
EXPECT_THAT(positions3[100].coordinates().x,
AlmostEquals(1.00 * period_ * v3, 1));
EXPECT_THAT(positions3[100].coordinates().y, Eq(q3));
}
} // namespace physics
} // namespace principia
<|endoftext|>
|
<commit_before>/*
* LocationController.cpp
*
* Created on: 29-07-2014
* Author: szsz
*/
#include <log4cxx/propertyconfigurator.h>
#include <boost/program_options.hpp>
#include <string>
#include <cmath>
#include <stdio.h>
#include "LocationCommon.h"
#include "LocationController.h"
using namespace std;
using namespace boost;
using namespace boost::interprocess;
using namespace boost::program_options;
using namespace log4cxx;
using namespace amber;
LoggerPtr LocationController::_logger(Logger::getLogger("LocationController"));
LocationController::LocationController(int pipeInFd, int pipeOutFd, const char *confFilename)
{
LOG4CXX_INFO(_logger, "LocationController");
parseConfigurationFile(confFilename);
_amberPipes = new AmberPipes(this, pipeInFd, pipeOutFd);
//char* mapPath = "/home/szsz/git/Lokalizacja/Lokalizacja/Debug/labNowe3.roson";
//char* mapPath = "/home//panda//Lokalizacja//Lokalizacja//labNowe3.roson";
char* mapPath = new char[_configuration->mapPath.length()];
strcpy(mapPath,_configuration->mapPath.c_str());
unsigned int numberParticles = _configuration->NumberParticles;
double epsilon = _configuration->epsilon;
int generation = _configuration->generation;
unsigned int ilosc_losowanych_nowych_czastek = _configuration->ilosc_losowanych_nowych_czastek;
unsigned int przlieczenie_dla_pomiaru_skanera = _configuration->przlieczenie_dla_pomiaru_skanera;
char* sIPPart = new char[_configuration->sIPPart.length()];
strcpy(sIPPart,_configuration->sIPPart.c_str());
lok = new Location(_logger,mapPath,numberParticles,epsilon,generation,ilosc_losowanych_nowych_czastek,przlieczenie_dla_pomiaru_skanera,sIPPart);
locationThread = new boost::thread(boost::bind(&LocationController::locationMathod, this));
}
LocationController::~LocationController() {
LOG4CXX_INFO(_logger, "Stopping controller.");
delete _amberPipes;
delete lok;
}
void LocationController::handleDataMsg(amber::DriverHdr *driverHdr, amber::DriverMsg *driverMsg)
{
if (_logger->isDebugEnabled()) {
LOG4CXX_DEBUG(_logger, "Message came");
}
int clientId = driverHdr->clientids_size() > 0 ? driverHdr->clientids(0) : 0;
// DataRequest
if (driverMsg->HasExtension(location_proto::get_location))
{
if (!driverMsg->has_synnum()) {
LOG4CXX_WARN(_logger, "Got CurrentLocationRequest, but syn num not set. Ignoring.");
return;
}
if (driverMsg->GetExtension(location_proto::get_location))
{
handleCurrentLocationRequest(clientId, driverMsg->synnum());
}
}
}
void LocationController::handleClientDiedMsg(int clientID) {
LOG4CXX_INFO(_logger, "Client " << clientID << " died");
}
void LocationController::operator()() {
_amberPipes->operator ()();
}
amber::DriverMsg *LocationController::buildCurrentLocationMsg()
{
LOG4CXX_INFO(_logger, "build current location msg");
amber::DriverMsg *message = new amber::DriverMsg();
message->set_type(amber::DriverMsg_MsgType_DATA);
location_proto::Location *currentLocation = message->MutableExtension(location_proto::currentLocation);
location_mutex.lock();
currentLocation->set_x(lok->Pos_X);
currentLocation->set_y(lok->Pos_Y);
currentLocation->set_p(lok->Prop);
currentLocation->set_alfa(lok->Pos_Alfa);
currentLocation->set_timestamp(lok->timeStamp);
location_mutex.unlock();
return message;
}
void LocationController::sendCurrentLocationMsg(int receiver, int ackNum)
{
if (_logger->isDebugEnabled()) {
LOG4CXX_DEBUG(_logger, "Sending currentLocationRequest message");
}
amber::DriverMsg *currentLocationMsg = buildCurrentLocationMsg();
currentLocationMsg->set_acknum(ackNum);
amber::DriverHdr *header = new amber::DriverHdr();
header->add_clientids(receiver);
_amberPipes->writeMsgToPipe(header, currentLocationMsg);
delete currentLocationMsg;
delete header;
}
void LocationController::handleCurrentLocationRequest(int sender, int synNum)
{
if (_logger->isDebugEnabled()) {
LOG4CXX_DEBUG(_logger, "Handling currentLocationRequest message");
}
sendCurrentLocationMsg(sender, synNum);
}
void LocationController::parseConfigurationFile(const char *filename) {
LOG4CXX_INFO(_logger, "Parsing configuration file: " << filename);
_configuration = new LocationConfiguration();
// unsigned int front_rc_address;
//unsigned int rear_rc_address;
options_description desc("Location options");
desc.add_options()
("location.mapPath", value<string>(&_configuration->mapPath)->default_value("."))
("location.NumberParticles", value<unsigned int>(&_configuration->NumberParticles)->default_value(20))
("location.epsilon", value<double>(&_configuration->epsilon)->default_value(0.8))
("location.generation", value<int>(&_configuration->generation)->default_value(1))
("location.ilosc_losowanych_nowych_czastek", value<unsigned int>(&_configuration->ilosc_losowanych_nowych_czastek)->default_value(20))
("location.przlieczenie_dla_pomiaru_skanera", value<unsigned int>(&_configuration->przlieczenie_dla_pomiaru_skanera)->default_value(12))
("location.RandomWalkMaxDistance", value<double>(&_configuration->RandomWalkMaxDistance)->default_value(0.7))
("location.StandardDeviation", value<double>(&_configuration->StandardDeviation)->default_value(0.3))
("location.sIPPart", value<string>(&_configuration->sIPPart)->default_value("127.0.0.1"));
/*("roboclaw.motors_max_qpps", value<unsigned int>(&_configuration->motors_max_qpps)->default_value(13800))
("roboclaw.motors_p_const", value<unsigned int>(&_configuration->motors_p_const)->default_value(65536))
("roboclaw.motors_i_const", value<unsigned int>(&_configuration->motors_i_const)->default_value(32768))
("roboclaw.motors_d_const", value<unsigned int>(&_configuration->motors_d_const)->default_value(16384))
("roboclaw.pulses_per_revolution", value<unsigned int>(&_configuration->pulses_per_revolution)->default_value(1865))
("roboclaw.wheel_radius", value<unsigned int>(&_configuration->wheel_radius)->default_value(60))
("roboclaw.battery_monitor_interval", value<unsigned int>(&_configuration->battery_monitor_interval)->default_value(0))
("roboclaw.error_monitor_interval", value<unsigned int>(&_configuration->error_monitor_interval)->default_value(0))
("roboclaw.temperature_monitor_interval", value<unsigned int>(&_configuration->temperature_monitor_interval)->default_value(0))
("roboclaw.temperature_critical", value<__u16>(&_configuration->temperature_critical)->default_value(70))
("roboclaw.temperature_drop", value<__u16>(&_configuration->temperature_drop)->default_value(60))
("roboclaw.critical_read_repeats", value<unsigned int>(&_configuration->critical_read_repeats)->default_value(0));
*/
variables_map vm;
try {
store(parse_config_file<char>(filename, desc), vm);
notify(vm);
//_configuration->front_rc_address = (__u8) front_rc_address;
//_configuration->rear_rc_address = (__u8) rear_rc_address;
} catch (std::exception& e) {
LOG4CXX_ERROR(_logger, "Error in parsing configuration file: " << e.what());
exit(1);
}
}
void LocationController::locationMathod()
{
LOG4CXX_INFO(_logger, "Location Method -> RunLocation");
lok->RunLocation();
}
int main(int argc, char *argv[]) {
if (argc < 3) {
return 1;
}
const char *confFile = argv[1];
const char *logConfFile = argv[2];
PropertyConfigurator::configure(logConfFile);
// STDIN_FD = 0, STDOUT_FD = 1
// pipe_in_fd = 0, pipe_out_fd = 1
LoggerPtr logger(Logger::getLogger("main"));
LOG4CXX_INFO(logger, "-------------");
LOG4CXX_INFO(logger, "Creating controller, config_file: " << argv[1] << ", log_config_file: " << argv[2]);
LOG4CXX_INFO(logger, "jestem w main 3 ");
LocationController controller(0, 1, confFile);
controller();
}
<commit_msg>obsługa zmiany mapy<commit_after>/*
* LocationController.cpp
*
* Created on: 29-07-2014
* Author: szsz
*/
#include <log4cxx/propertyconfigurator.h>
#include <boost/program_options.hpp>
#include <string>
#include <cmath>
#include <stdio.h>
#include "LocationCommon.h"
#include "LocationController.h"
using namespace std;
using namespace boost;
using namespace boost::interprocess;
using namespace boost::program_options;
using namespace log4cxx;
using namespace amber;
LoggerPtr LocationController::_logger(Logger::getLogger("LocationController"));
LocationController::LocationController(int pipeInFd, int pipeOutFd, const char *confFilename)
{
LOG4CXX_INFO(_logger, "LocationController");
parseConfigurationFile(confFilename);
_amberPipes = new AmberPipes(this, pipeInFd, pipeOutFd);
initLocation();
}
void LocationController::initLocation()
{
//char* mapPath = "/home/szsz/git/Lokalizacja/Lokalizacja/Debug/labNowe3.roson";
//char* mapPath = "/home//panda//Lokalizacja//Lokalizacja//labNowe3.roson";
char* mapPath = new char[_configuration->mapPath.length()];
strcpy(mapPath,_configuration->mapPath.c_str());
initLocation(mapPath);
}
void LocationController::initLocation(char* mapPath)
{
unsigned int numberParticles = _configuration->NumberParticles;
double epsilon = _configuration->epsilon;
int generation = _configuration->generation;
unsigned int ilosc_losowanych_nowych_czastek = _configuration->ilosc_losowanych_nowych_czastek;
unsigned int przlieczenie_dla_pomiaru_skanera = _configuration->przlieczenie_dla_pomiaru_skanera;
char* sIPPart = new char[_configuration->sIPPart.length()];
strcpy(sIPPart,_configuration->sIPPart.c_str());
lok = new Location(_logger,mapPath,numberParticles,epsilon,generation,ilosc_losowanych_nowych_czastek,przlieczenie_dla_pomiaru_skanera,sIPPart);
locationThread = new boost::thread(boost::bind(&LocationController::locationMathod, this));
}
LocationController::~LocationController() {
LOG4CXX_INFO(_logger, "Stopping controller.");
delete _amberPipes;
delete lok;
}
void LocationController::handleDataMsg(amber::DriverHdr *driverHdr, amber::DriverMsg *driverMsg)
{
if (_logger->isDebugEnabled()) {
LOG4CXX_DEBUG(_logger, "Message came");
}
int clientId = driverHdr->clientids_size() > 0 ? driverHdr->clientids(0) : 0;
// DataRequest
if (driverMsg->HasExtension(location_proto::get_location))
{
if (!driverMsg->has_synnum()) {
LOG4CXX_WARN(_logger, "Got CurrentLocationRequest, but syn num not set. Ignoring.");
return;
}
if (driverMsg->GetExtension(location_proto::get_location))
{
handleCurrentLocationRequest(clientId, driverMsg->synnum());
}
}
else if(driverMsg->HasExtension(location_proto::upload_map))
{
if (!driverMsg->has_synnum()) {
LOG4CXX_WARN(_logger, "Got CurrentUploadMapRequest, but syn num not set. Ignoring.");
return;
}
else
{
::std::string ss = driverMsg->GetExtension(location_proto::upload_map);
}
}
}
void LocationController::handleClientDiedMsg(int clientID) {
LOG4CXX_INFO(_logger, "Client " << clientID << " died");
}
void LocationController::operator()() {
_amberPipes->operator ()();
}
amber::DriverMsg *LocationController::buildCurrentLocationMsg()
{
LOG4CXX_INFO(_logger, "build current location msg");
amber::DriverMsg *message = new amber::DriverMsg();
message->set_type(amber::DriverMsg_MsgType_DATA);
location_proto::Location *currentLocation = message->MutableExtension(location_proto::currentLocation);
location_mutex.lock();
currentLocation->set_x(lok->Pos_X);
currentLocation->set_y(lok->Pos_Y);
currentLocation->set_p(lok->Prop);
currentLocation->set_alfa(lok->Pos_Alfa);
currentLocation->set_timestamp(lok->timeStamp);
location_mutex.unlock();
return message;
}
void LocationController::sendCurrentLocationMsg(int receiver, int ackNum)
{
if (_logger->isDebugEnabled()) {
LOG4CXX_DEBUG(_logger, "Sending currentLocationRequest message");
}
amber::DriverMsg *currentLocationMsg = buildCurrentLocationMsg();
currentLocationMsg->set_acknum(ackNum);
amber::DriverHdr *header = new amber::DriverHdr();
header->add_clientids(receiver);
_amberPipes->writeMsgToPipe(header, currentLocationMsg);
delete currentLocationMsg;
delete header;
}
void LocationController::handleCurrentLocationRequest(int sender, int synNum)
{
if (_logger->isDebugEnabled()) {
LOG4CXX_DEBUG(_logger, "Handling currentLocationRequest message");
}
sendCurrentLocationMsg(sender, synNum);
}
void LocationController::handleCurrentUploadMapRequest(std::string sMap)
{
printf("%s\n",sMap.c_str());
}
void LocationController::parseConfigurationFile(const char *filename) {
LOG4CXX_INFO(_logger, "Parsing configuration file: " << filename);
_configuration = new LocationConfiguration();
// unsigned int front_rc_address;
//unsigned int rear_rc_address;
options_description desc("Location options");
desc.add_options()
("location.mapPath", value<string>(&_configuration->mapPath)->default_value("."))
("location.NumberParticles", value<unsigned int>(&_configuration->NumberParticles)->default_value(20))
("location.epsilon", value<double>(&_configuration->epsilon)->default_value(0.8))
("location.generation", value<int>(&_configuration->generation)->default_value(1))
("location.ilosc_losowanych_nowych_czastek", value<unsigned int>(&_configuration->ilosc_losowanych_nowych_czastek)->default_value(20))
("location.przlieczenie_dla_pomiaru_skanera", value<unsigned int>(&_configuration->przlieczenie_dla_pomiaru_skanera)->default_value(12))
("location.RandomWalkMaxDistance", value<double>(&_configuration->RandomWalkMaxDistance)->default_value(0.7))
("location.StandardDeviation", value<double>(&_configuration->StandardDeviation)->default_value(0.3))
("location.sIPPart", value<string>(&_configuration->sIPPart)->default_value("127.0.0.1"))
("location.uploadMapPath", value<string>(&_configuration->uploadMapPath)->default_value("."));
/*("roboclaw.motors_max_qpps", value<unsigned int>(&_configuration->motors_max_qpps)->default_value(13800))
("roboclaw.motors_p_const", value<unsigned int>(&_configuration->motors_p_const)->default_value(65536))
("roboclaw.motors_i_const", value<unsigned int>(&_configuration->motors_i_const)->default_value(32768))
("roboclaw.motors_d_const", value<unsigned int>(&_configuration->motors_d_const)->default_value(16384))
("roboclaw.pulses_per_revolution", value<unsigned int>(&_configuration->pulses_per_revolution)->default_value(1865))
("roboclaw.wheel_radius", value<unsigned int>(&_configuration->wheel_radius)->default_value(60))
("roboclaw.battery_monitor_interval", value<unsigned int>(&_configuration->battery_monitor_interval)->default_value(0))
("roboclaw.error_monitor_interval", value<unsigned int>(&_configuration->error_monitor_interval)->default_value(0))
("roboclaw.temperature_monitor_interval", value<unsigned int>(&_configuration->temperature_monitor_interval)->default_value(0))
("roboclaw.temperature_critical", value<__u16>(&_configuration->temperature_critical)->default_value(70))
("roboclaw.temperature_drop", value<__u16>(&_configuration->temperature_drop)->default_value(60))
("roboclaw.critical_read_repeats", value<unsigned int>(&_configuration->critical_read_repeats)->default_value(0));
*/
variables_map vm;
try {
store(parse_config_file<char>(filename, desc), vm);
notify(vm);
//_configuration->front_rc_address = (__u8) front_rc_address;
//_configuration->rear_rc_address = (__u8) rear_rc_address;
} catch (std::exception& e) {
LOG4CXX_ERROR(_logger, "Error in parsing configuration file: " << e.what());
exit(1);
}
}
void LocationController::locationMathod()
{
LOG4CXX_INFO(_logger, "Location Method -> RunLocation");
lok->RunLocation();
}
int main(int argc, char *argv[]) {
if (argc < 3) {
return 1;
}
const char *confFile = argv[1];
const char *logConfFile = argv[2];
PropertyConfigurator::configure(logConfFile);
// STDIN_FD = 0, STDOUT_FD = 1
// pipe_in_fd = 0, pipe_out_fd = 1
LoggerPtr logger(Logger::getLogger("main"));
LOG4CXX_INFO(logger, "-------------");
LOG4CXX_INFO(logger, "Creating controller, config_file: " << argv[1] << ", log_config_file: " << argv[2]);
LocationController controller(0, 1, confFile);
controller();
}
<|endoftext|>
|
<commit_before>#pragma once
//=====================================================================//
/*! @file
@brief イグナイター・クライアント・クラス
@author 平松邦仁 (hira@rvf-rc45.net)
@copyright Copyright (C) 2017, 2018 Kunihito Hiramatsu @n
Released under the MIT license @n
https://github.com/hirakuni45/RX/blob/master/LICENSE
*/
//=====================================================================//
#include <winsock2.h>
#include <string>
#include <queue>
#include "utils/format.hpp"
#include "utils/string_utils.hpp"
// デバッグ・エミュレーションを行う場合有効にする
// #define DEBUG_EMU
namespace net {
//+++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++//
/*!
@brief Ignitor Client クラス
*/
//+++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++//
class ign_client_tcp {
public:
static const uint32_t WAVE_BUFF_SIZE = 2048;
//=================================================================//
/*!
@brief モジュール・ステータス構造体
*/
//=================================================================//
struct mod_status {
uint32_t crm_id_;
uint32_t crcd_;
uint32_t crcd_id_;
uint32_t crrd_;
uint32_t crrd_id_;
uint32_t d2md_;
uint32_t d2md_id_;
uint32_t wdm_id_[4];
uint32_t treg_id_[2];
mod_status() :
crm_id_(0),
crcd_(0), crcd_id_(0),
crrd_(0), crrd_id_(0),
d2md_(0), d2md_id_(0),
wdm_id_{ 0 }, treg_id_{ 0 }
{ }
};
private:
bool startup_;
SOCKET sock_;
bool connect_;
std::string line_;
typedef std::queue<std::string> SQUEUE;
SQUEUE rmsg_;
mod_status mod_status_;
uint32_t wdm_ch_;
uint32_t wdm_pos_;
uint16_t wdm_buff_[WAVE_BUFF_SIZE * 4];
uint32_t treg_ch_;
uint32_t treg_pos_;
uint16_t treg_buff_[WAVE_BUFF_SIZE * 2];
public:
//-----------------------------------------------------------------//
/*!
@brief コンストラクター
*/
//-----------------------------------------------------------------//
ign_client_tcp() : startup_(false),
sock_(0),
connect_(false), mod_status_(),
wdm_ch_(0), wdm_pos_(0), wdm_buff_{ 0 },
treg_ch_(0), treg_pos_(0), treg_buff_{ 0 }
{
}
//-----------------------------------------------------------------//
/*!
@brief デストラクター
*/
//-----------------------------------------------------------------//
~ign_client_tcp()
{
if(startup_) {
WSACleanup();
}
}
//-----------------------------------------------------------------//
/*!
@brief モジュール・ステータスの取得
@return モジュール・ステータス
*/
//-----------------------------------------------------------------//
const mod_status& get_mod_status() const { return mod_status_; }
//-----------------------------------------------------------------//
/*!
@brief 波形の取得
@param[in] ch チャネル
@return 波形
*/
//-----------------------------------------------------------------//
const uint16_t* get_wdm(uint32_t ch) const {
return &wdm_buff_[WAVE_BUFF_SIZE * (ch & 3)];
}
//-----------------------------------------------------------------//
/*!
@brief 熱抵抗波形の取得
@param[in] ch チャネル(前半:0、後半:1)
@return 熱抵抗波形
*/
//-----------------------------------------------------------------//
const uint16_t* get_treg(uint32_t ch) const {
return &treg_buff_[WAVE_BUFF_SIZE * (ch & 1)];
}
//-----------------------------------------------------------------//
/*!
@brief 接続状態の確認
@return 接続なら「true」
*/
//-----------------------------------------------------------------//
bool probe() const { return connect_; }
//-----------------------------------------------------------------//
/*!
@brief 開始
@param[in] ip IP アドレス
@param[in] pn ポート番号
*/
//-----------------------------------------------------------------//
bool start(const std::string& ip, uint16_t pn)
{
#ifdef DEBUG_EMU
connect_ = true;
return true;
#endif
if(!startup_) {
WSADATA wsaData;
int res = WSAStartup(MAKEWORD(2,0), &wsaData);
if(res != NO_ERROR) {
std::cout << "WSAStartup function failed with error:" << std::endl;
return false;
}
}
// クライアントソケット作成
sock_ = socket(AF_INET, SOCK_STREAM, 0);
if(sock_ == INVALID_SOCKET) {
std::cout << "socket failed" << std::endl;
return false;
}
// struct sockaddr_in 作成
struct sockaddr_in cl;
cl.sin_family = PF_INET;
cl.sin_port = htons(pn);
// 接続先のアドレスを指定(指定しない事も可能)
cl.sin_addr.s_addr = inet_addr(ip.c_str());
// クライアントの接続を待つ
int ret = connect(sock_, (struct sockaddr *)&cl, sizeof(cl));
if(ret == SOCKET_ERROR) {
closesocket(sock_);
perror("TCP connect fail...");
return false;
}
connect_ = true;
// utils::format("TCP Client connect (%d)\n") % sock_;
u_long val = 1;
ioctlsocket(sock_, FIONBIO, &val);
return true;
}
//-----------------------------------------------------------------//
/*!
@brief サービス
*/
//-----------------------------------------------------------------//
void service()
{
#ifdef DEBUG_EMU
#else
if(!connect_) return;
char tmp[8192];
int n = recv(sock_, tmp, sizeof(tmp) - 1, 0);
if(n < 1) {
if(WSAGetLastError() == WSAEWOULDBLOCK) {
// まだ来ない。
} else {
std::cout << "recv error..." << std::endl;
}
} else {
for(int i = 0; i < n; ++i) {
auto ch = tmp[i];
line_ += ch;
if(ch == '\n') {
rmsg_.push(line_);
line_.clear();
}
}
}
// 読み込みデータ処理
while(!rmsg_.empty()) {
auto s = rmsg_.front();
rmsg_.pop();
if(s.find("CRCD") == 0) {
auto t = s.substr(4, 8);
int v = 0;
if((utils::input("%x", t.c_str()) % v).status()) {
mod_status_.crcd_ = v;
++mod_status_.crcd_id_;
++mod_status_.crm_id_;
}
} else if(s.find("CRRD") == 0) {
auto t = s.substr(4, 8);
int v = 0;
if((utils::input("%x", t.c_str()) % v).status()) {
mod_status_.crrd_ = v;
++mod_status_.crrd_id_;
++mod_status_.crm_id_;
}
} else if(s.find("D2MD") == 0) {
auto t = s.substr(4, 5);
int v = 0;
if((utils::input("%x", t.c_str()) % v).status()) {
mod_status_.d2md_ = v;
++mod_status_.d2md_id_;
}
} else if(s.find("WDCH") == 0) { // WDM チャネル
auto t = s.substr(4);
int v = 0;
utils::input("%d", t.c_str()) % v;
wdm_ch_ = v;
wdm_pos_ = 0;
// std::cout << "WDM capture CH: " << wdm_ch_ << std::endl;
} else if(s.find("WDMW") == 0) { // WDM 波形
auto t = s.substr(4);
while(t.size() > 4) {
auto d = t.substr(4);
t[4] = 0;
int v;
utils::input("%x", t.c_str()) % v;
auto pos = wdm_pos_ % WAVE_BUFF_SIZE;
wdm_buff_[(wdm_ch_ & 3) * WAVE_BUFF_SIZE + pos] = v;
++wdm_pos_;
if(wdm_pos_ >= WAVE_BUFF_SIZE) {
++mod_status_.wdm_id_[wdm_ch_ & 3];
}
t = d;
}
} else if(s.find("TRCH") == 0) { // 熱抵抗チャネル (0, 1)
auto t = s.substr(4);
int v = 0;
utils::input("%d", t.c_str()) % v;
treg_ch_ = v;
treg_pos_ = 0;
// std::cout << "TRCH: " << treg_ch_ << std::endl;
} else if(s.find("TRMW") == 0) { // 熱抵抗波形 (0, 1)
auto t = s.substr(4);
while(t.size() > 4) {
auto d = t.substr(4);
t[4] = 0;
int v;
utils::input("%x", t.c_str()) % v;
auto pos = treg_pos_ % WAVE_BUFF_SIZE;
treg_buff_[(treg_ch_ & 1) * WAVE_BUFF_SIZE + pos] = v;
++treg_pos_;
if(treg_pos_ >= WAVE_BUFF_SIZE) {
++mod_status_.treg_id_[treg_ch_ & 3];
// std::cout << "TRMW: " << treg_ch_ << std::endl;
}
t = d;
}
}
}
#endif
}
//-----------------------------------------------------------------//
/*!
@brief 送信
@param[in] text 送信文字列
*/
//-----------------------------------------------------------------//
void send_data(const std::string& text)
{
#ifdef DEBUG_EMU
if(text.find("CRR?1") != std::string::npos) {
double a = 50.0;
a *= 2.0;
a /= 778.2;
a *= 50.0;
a *= static_cast<double>(0x7FFFF) / 1.570798233;
mod_status_.crrd_ = 50 * 0x7ffff + static_cast<uint32_t>(a);
++mod_status_.crrd_id_;
++mod_status_.crm_id_;
} else if(text.find("CRC?1") != std::string::npos) {
double a = 0.33;
a /= 1e6;
a = 1.0 / (2.0 * 3.141592654 * 1000.0 * a);
a *= 2.0;
a /= 778.2 * 2.0; // 778.2 mV P-P
a *= 50.0;
a *= static_cast<double>(0x7FFFF) / 1.570798233;
mod_status_.crcd_ = 50 * 0x7ffff + static_cast<uint32_t>(a);
++mod_status_.crcd_id_;
++mod_status_.crm_id_;
} else if(text.find("wdm 20") != std::string::npos) {
++mod_status_.wdm_id_[2];
}
std::cout << text << std::endl;
return;
#else
if(send(sock_, text.c_str(), text.size(), 0) == SOCKET_ERROR) {
shutdown(sock_, 2);
closesocket(sock_);
connect_ = false;
}
#endif
}
};
}
<commit_msg>update: cleanup<commit_after>#pragma once
//=====================================================================//
/*! @file
@brief イグナイター・クライアント・クラス
@author 平松邦仁 (hira@rvf-rc45.net)
@copyright Copyright (C) 2017, 2018 Kunihito Hiramatsu @n
Released under the MIT license @n
https://github.com/hirakuni45/RX/blob/master/LICENSE
*/
//=====================================================================//
#include <winsock2.h>
#include <string>
#include <queue>
#include "utils/format.hpp"
#include "utils/string_utils.hpp"
// デバッグ・エミュレーションを行う場合有効にする
// #define DEBUG_EMU
namespace net {
//+++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++//
/*!
@brief Ignitor Client クラス
*/
//+++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++//
class ign_client_tcp {
public:
static const uint32_t WAVE_BUFF_SIZE = 2048;
//=================================================================//
/*!
@brief モジュール・ステータス構造体
*/
//=================================================================//
struct mod_status {
uint32_t crm_id_;
uint32_t crcd_;
uint32_t crcd_id_;
uint32_t crrd_;
uint32_t crrd_id_;
uint32_t d2md_;
uint32_t d2md_id_;
uint32_t wdm_id_[4];
uint32_t treg_id_[2];
mod_status() :
crm_id_(0),
crcd_(0), crcd_id_(0),
crrd_(0), crrd_id_(0),
d2md_(0), d2md_id_(0),
wdm_id_{ 0 }, treg_id_{ 0 }
{ }
};
private:
bool startup_;
SOCKET sock_;
bool connect_;
std::string line_;
typedef std::queue<std::string> SQUEUE;
SQUEUE rmsg_;
mod_status mod_status_;
uint32_t wdm_ch_;
uint32_t wdm_pos_;
uint16_t wdm_buff_[WAVE_BUFF_SIZE * 4];
uint32_t treg_ch_;
uint32_t treg_pos_;
uint16_t treg_buff_[WAVE_BUFF_SIZE * 2];
public:
//-----------------------------------------------------------------//
/*!
@brief コンストラクター
*/
//-----------------------------------------------------------------//
ign_client_tcp() : startup_(false),
sock_(0),
connect_(false), mod_status_(),
wdm_ch_(0), wdm_pos_(0), wdm_buff_{ 0 },
treg_ch_(0), treg_pos_(0), treg_buff_{ 0 }
{
}
//-----------------------------------------------------------------//
/*!
@brief デストラクター
*/
//-----------------------------------------------------------------//
~ign_client_tcp()
{
if(startup_) {
WSACleanup();
}
}
//-----------------------------------------------------------------//
/*!
@brief モジュール・ステータスの取得
@return モジュール・ステータス
*/
//-----------------------------------------------------------------//
const mod_status& get_mod_status() const { return mod_status_; }
//-----------------------------------------------------------------//
/*!
@brief 波形の取得
@param[in] ch チャネル
@return 波形
*/
//-----------------------------------------------------------------//
const uint16_t* get_wdm(uint32_t ch) const {
return &wdm_buff_[WAVE_BUFF_SIZE * (ch & 3)];
}
//-----------------------------------------------------------------//
/*!
@brief 熱抵抗波形の取得
@param[in] ch チャネル(前半:0、後半:1)
@return 熱抵抗波形
*/
//-----------------------------------------------------------------//
const uint16_t* get_treg(uint32_t ch) const {
return &treg_buff_[WAVE_BUFF_SIZE * (ch & 1)];
}
//-----------------------------------------------------------------//
/*!
@brief 接続状態の確認
@return 接続なら「true」
*/
//-----------------------------------------------------------------//
bool probe() const { return connect_; }
//-----------------------------------------------------------------//
/*!
@brief 開始
@param[in] ip IP アドレス
@param[in] pn ポート番号
*/
//-----------------------------------------------------------------//
bool start(const std::string& ip, uint16_t pn)
{
#ifdef DEBUG_EMU
connect_ = true;
return true;
#endif
if(!startup_) {
WSADATA wsaData;
int res = WSAStartup(MAKEWORD(2,0), &wsaData);
if(res != NO_ERROR) {
std::cout << "WSAStartup function failed with error:" << std::endl;
return false;
}
}
// クライアントソケット作成
sock_ = socket(AF_INET, SOCK_STREAM, 0);
if(sock_ == INVALID_SOCKET) {
std::cout << "socket failed" << std::endl;
return false;
}
// struct sockaddr_in 作成
struct sockaddr_in cl;
cl.sin_family = PF_INET;
cl.sin_port = htons(pn);
// 接続先のアドレスを指定(指定しない事も可能)
cl.sin_addr.s_addr = inet_addr(ip.c_str());
// クライアントの接続を待つ
int ret = connect(sock_, (struct sockaddr *)&cl, sizeof(cl));
if(ret == SOCKET_ERROR) {
closesocket(sock_);
perror("TCP connect fail...");
return false;
}
connect_ = true;
// utils::format("TCP Client connect (%d)\n") % sock_;
u_long val = 1;
ioctlsocket(sock_, FIONBIO, &val);
return true;
}
//-----------------------------------------------------------------//
/*!
@brief サービス
*/
//-----------------------------------------------------------------//
void service()
{
#ifdef DEBUG_EMU
#else
if(!connect_) return;
char tmp[8192];
int n = recv(sock_, tmp, sizeof(tmp) - 1, 0);
if(n < 1) {
if(WSAGetLastError() == WSAEWOULDBLOCK) {
// まだ来ない。
} else {
std::cout << "recv error..." << std::endl;
}
} else {
for(int i = 0; i < n; ++i) {
auto ch = tmp[i];
line_ += ch;
if(ch == '\n') {
rmsg_.push(line_);
line_.clear();
}
}
}
// 読み込みデータ処理
while(!rmsg_.empty()) {
auto s = rmsg_.front();
rmsg_.pop();
if(s.find("CRCD") == 0) {
auto t = s.substr(4, 8);
int v = 0;
if((utils::input("%x", t.c_str()) % v).status()) {
mod_status_.crcd_ = v;
++mod_status_.crcd_id_;
++mod_status_.crm_id_;
}
} else if(s.find("CRRD") == 0) {
auto t = s.substr(4, 8);
int v = 0;
if((utils::input("%x", t.c_str()) % v).status()) {
mod_status_.crrd_ = v;
++mod_status_.crrd_id_;
++mod_status_.crm_id_;
}
} else if(s.find("D2MD") == 0) {
auto t = s.substr(4, 5);
int v = 0;
if((utils::input("%x", t.c_str()) % v).status()) {
mod_status_.d2md_ = v;
++mod_status_.d2md_id_;
}
} else if(s.find("WDCH") == 0) { // WDM チャネル
auto t = s.substr(4);
int v = 0;
utils::input("%d", t.c_str()) % v;
wdm_ch_ = v;
wdm_pos_ = 0;
// std::cout << "WDM capture CH: " << wdm_ch_ << std::endl;
} else if(s.find("WDMW") == 0) { // WDM 波形
auto t = s.substr(4);
while(t.size() > 4) {
auto d = t.substr(4);
t[4] = 0;
int v;
utils::input("%x", t.c_str()) % v;
auto pos = wdm_pos_ % WAVE_BUFF_SIZE;
wdm_buff_[(wdm_ch_ & 3) * WAVE_BUFF_SIZE + pos] = v;
++wdm_pos_;
if(wdm_pos_ >= WAVE_BUFF_SIZE) {
++mod_status_.wdm_id_[wdm_ch_ & 3];
}
t = d;
}
} else if(s.find("TRCH") == 0) { // 熱抵抗チャネル (0, 1)
auto t = s.substr(4);
int v = 0;
utils::input("%d", t.c_str()) % v;
treg_ch_ = v;
treg_pos_ = 0;
// std::cout << "TRCH: " << treg_ch_ << std::endl;
} else if(s.find("TRMW") == 0) { // 熱抵抗波形 (0, 1)
auto t = s.substr(4);
while(t.size() > 4) {
auto d = t.substr(4);
t[4] = 0;
int v;
utils::input("%x", t.c_str()) % v;
auto pos = treg_pos_ % WAVE_BUFF_SIZE;
treg_buff_[(treg_ch_ & 1) * WAVE_BUFF_SIZE + pos] = v;
++treg_pos_;
if(treg_pos_ >= WAVE_BUFF_SIZE) {
++mod_status_.treg_id_[treg_ch_ & 1];
// std::cout << "TRMW: " << treg_ch_ << std::endl;
}
t = d;
}
}
}
#endif
}
//-----------------------------------------------------------------//
/*!
@brief 送信
@param[in] text 送信文字列
*/
//-----------------------------------------------------------------//
void send_data(const std::string& text)
{
#ifdef DEBUG_EMU
if(text.find("CRR?1") != std::string::npos) {
double a = 50.0;
a *= 2.0;
a /= 778.2;
a *= 50.0;
a *= static_cast<double>(0x7FFFF) / 1.570798233;
mod_status_.crrd_ = 50 * 0x7ffff + static_cast<uint32_t>(a);
++mod_status_.crrd_id_;
++mod_status_.crm_id_;
} else if(text.find("CRC?1") != std::string::npos) {
double a = 0.33;
a /= 1e6;
a = 1.0 / (2.0 * 3.141592654 * 1000.0 * a);
a *= 2.0;
a /= 778.2 * 2.0; // 778.2 mV P-P
a *= 50.0;
a *= static_cast<double>(0x7FFFF) / 1.570798233;
mod_status_.crcd_ = 50 * 0x7ffff + static_cast<uint32_t>(a);
++mod_status_.crcd_id_;
++mod_status_.crm_id_;
} else if(text.find("wdm 20") != std::string::npos) {
++mod_status_.wdm_id_[2];
}
std::cout << text << std::endl;
return;
#else
if(send(sock_, text.c_str(), text.size(), 0) == SOCKET_ERROR) {
shutdown(sock_, 2);
closesocket(sock_);
connect_ = false;
}
#endif
}
};
}
<|endoftext|>
|
<commit_before>/*
* Menu creation and other helper functions.
* By 2MB Solutions (https://2mb.solutions)
* Provided under the MIT license. See license.txt for details.
* Billy: https://stormdragon.tk
* Michael: https://michaeltaboada.me
*/
#include <dynamic_menu.h>
#include <string>
#include <vector>
#include <misc.h>
#include <soundplayer.h>
using std::string;
using std::vector;
dynamic_menu* create_menu(vector<string> items, vector<string> sounditems, vector<int(*)(dynamic_menu*, int, void*)> vec = vector<int(*)(dynamic_menu*, int, void*)>(), vector<void*> vec2 = vector<void*>()) {
int soundnumber = sounditems.size();
int numberofitems = items.size();
dynamic_menu* menu = new dynamic_menu((numberofitems > soundnumber)?numberofitems:soundnumber);
for(int x = 1; x <= numberofitems; x++) {
if(items[x-1] != "") {
menu->add_item_text(items[x-1], x, ((vec.size() >= x)?vec[x-1]:NULL), ((vec2.size() >= x)?vec2[x-1]:NULL));
}
}
for(int y = 1; y <= soundnumber; y++) {
if(sounditems[y-1] != "") {
menu->add_item_sound(sounditems[y-1], y, ((vec.size() >= y)?vec[y-1]:NULL), ((vec2.size() >= y)?vec2[y-1]:NULL));
}
}
return menu;
}
vector<string>* get_dir_children(string dir, int dir_or_file) {
ALLEGRO_FS_ENTRY *f = al_create_fs_entry((((string)(al_path_cstr(al_get_standard_path(ALLEGRO_RESOURCES_PATH), '/')))+dir).c_str());
if(!f) {
return NULL;
}
if(al_open_directory(f)) {
vector<string>* vec = new vector<string>();
ALLEGRO_FS_ENTRY *fs = al_read_directory(f);
while(fs) {
const char* fn = al_get_fs_entry_name(fs);
string fsn = "";
int x;
for(x = strlen(fn)-1; x >= 0; x--) {
if(fn[x] == '/' || fn[x] == '\\') {
break;
}
}
for(int y = x+1; y < strlen(fn); y++) {
fsn += fn[y];
}
if(dir_or_file == 0) {
vec->push_back(fsn);
}
else if(dir_or_file == 1 && (al_get_fs_entry_mode(fs) & ALLEGRO_FILEMODE_ISFILE) == ALLEGRO_FILEMODE_ISFILE) {
vec->push_back(fsn);
}
else if(dir_or_file == 2 && (al_get_fs_entry_mode(fs) & ALLEGRO_FILEMODE_ISDIR) == ALLEGRO_FILEMODE_ISDIR){
vec->push_back(fsn);
}
if(fs) {
al_destroy_fs_entry(fs);
}
fs = al_read_directory(f);
}
al_close_directory(f);
al_destroy_fs_entry(f);
return vec;
}
else {
al_destroy_fs_entry(f);
return NULL;
}
}
string generic_menu(vector<string> extra_items, string music = "") {
sound menu_music;
if(music != "") {
menu_music.load(music);
menu_music.play();
}
vector<string> real_items;
real_items.push_back("Play game");
real_items.push_back("View instructions");
real_items.push_back("Learn game sounds.");
for (int x = 0; x < extra_items.size(); x++) {
real_items.push_back(extra_items[x]);
}
real_items.push_back("view credits");
real_items.push_back("Exit game");
dynamic_menu* menu = create_menu(real_items, vector<string>());
int pos = -1;
do {
pos = menu->run_extended("", "Use your arrow keys to navigate the menu, and enter to select.", 1, true);
if(pos == 1) {
if(music != "")
fade(&menu_music);
return "play";
}
else if(pos == extra_items.size()+4) {
credits();
}
else if(pos == 2) {
instructions();
}
else if(pos == 3) {
if(music != "")
fade(&menu_music);
learn_sounds();
if(music != "") {
menu_music.set_gain(0);
menu_music.play();
}
}
else if (pos == extra_items.size()+5) {
if(music != "")
fade(&menu_music);
return "exit";
}
else {
if(music != "")
fade(&menu_music);
return extra_items[pos-3];
}
}
while (pos != -1 && pos != 0 & pos != extra_items.size()+5);
if(music != "")
menu_music.stop();
return "invalid";
}
<commit_msg>Make the menu music loop.<commit_after>/*
* Menu creation and other helper functions.
* By 2MB Solutions (https://2mb.solutions)
* Provided under the MIT license. See license.txt for details.
* Billy: https://stormdragon.tk
* Michael: https://michaeltaboada.me
*/
#include <dynamic_menu.h>
#include <string>
#include <vector>
#include <misc.h>
#include <soundplayer.h>
using std::string;
using std::vector;
dynamic_menu* create_menu(vector<string> items, vector<string> sounditems, vector<int(*)(dynamic_menu*, int, void*)> vec = vector<int(*)(dynamic_menu*, int, void*)>(), vector<void*> vec2 = vector<void*>()) {
int soundnumber = sounditems.size();
int numberofitems = items.size();
dynamic_menu* menu = new dynamic_menu((numberofitems > soundnumber)?numberofitems:soundnumber);
for(int x = 1; x <= numberofitems; x++) {
if(items[x-1] != "") {
menu->add_item_text(items[x-1], x, ((vec.size() >= x)?vec[x-1]:NULL), ((vec2.size() >= x)?vec2[x-1]:NULL));
}
}
for(int y = 1; y <= soundnumber; y++) {
if(sounditems[y-1] != "") {
menu->add_item_sound(sounditems[y-1], y, ((vec.size() >= y)?vec[y-1]:NULL), ((vec2.size() >= y)?vec2[y-1]:NULL));
}
}
return menu;
}
vector<string>* get_dir_children(string dir, int dir_or_file) {
ALLEGRO_FS_ENTRY *f = al_create_fs_entry((((string)(al_path_cstr(al_get_standard_path(ALLEGRO_RESOURCES_PATH), '/')))+dir).c_str());
if(!f) {
return NULL;
}
if(al_open_directory(f)) {
vector<string>* vec = new vector<string>();
ALLEGRO_FS_ENTRY *fs = al_read_directory(f);
while(fs) {
const char* fn = al_get_fs_entry_name(fs);
string fsn = "";
int x;
for(x = strlen(fn)-1; x >= 0; x--) {
if(fn[x] == '/' || fn[x] == '\\') {
break;
}
}
for(int y = x+1; y < strlen(fn); y++) {
fsn += fn[y];
}
if(dir_or_file == 0) {
vec->push_back(fsn);
}
else if(dir_or_file == 1 && (al_get_fs_entry_mode(fs) & ALLEGRO_FILEMODE_ISFILE) == ALLEGRO_FILEMODE_ISFILE) {
vec->push_back(fsn);
}
else if(dir_or_file == 2 && (al_get_fs_entry_mode(fs) & ALLEGRO_FILEMODE_ISDIR) == ALLEGRO_FILEMODE_ISDIR){
vec->push_back(fsn);
}
if(fs) {
al_destroy_fs_entry(fs);
}
fs = al_read_directory(f);
}
al_close_directory(f);
al_destroy_fs_entry(f);
return vec;
}
else {
al_destroy_fs_entry(f);
return NULL;
}
}
string generic_menu(vector<string> extra_items, string music = "") {
sound menu_music;
if(music != "") {
menu_music.load(music);
menu_music.set_loop(true);
menu_music.play();
}
vector<string> real_items;
real_items.push_back("Play game");
real_items.push_back("View instructions");
real_items.push_back("Learn game sounds.");
for (int x = 0; x < extra_items.size(); x++) {
real_items.push_back(extra_items[x]);
}
real_items.push_back("view credits");
real_items.push_back("Exit game");
dynamic_menu* menu = create_menu(real_items, vector<string>());
int pos = -1;
do {
pos = menu->run_extended("", "Use your arrow keys to navigate the menu, and enter to select.", 1, true);
if(pos == 1) {
if(music != "")
fade(&menu_music);
return "play";
}
else if(pos == extra_items.size()+4) {
credits();
}
else if(pos == 2) {
instructions();
}
else if(pos == 3) {
if(music != "")
fade(&menu_music);
learn_sounds();
if(music != "") {
menu_music.set_gain(0);
menu_music.play();
}
}
else if (pos == extra_items.size()+5) {
if(music != "")
fade(&menu_music);
return "exit";
}
else {
if(music != "")
fade(&menu_music);
return extra_items[pos-3];
}
}
while (pos != -1 && pos != 0 & pos != extra_items.size()+5);
if(music != "")
menu_music.stop();
return "invalid";
}
<|endoftext|>
|
<commit_before>// Copyright 2020 Google LLC
//
// Licensed under the Apache License, Version 2.0 (the "License");
// you may not use this file except in compliance with the License.
// You may obtain a copy of the License at
//
// http://www.apache.org/licenses/LICENSE-2.0
//
// Unless required by applicable law or agreed to in writing, software
// distributed under the License is distributed on an "AS IS" BASIS,
// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
// See the License for the specific language governing permissions and
// limitations under the License.
#include "google/cloud/functions/internal/framework.h"
#include <boost/asio/connect.hpp>
#include <boost/asio/ip/tcp.hpp>
#include <boost/beast.hpp>
#include <boost/filesystem.hpp>
#include <boost/process.hpp>
#include <gmock/gmock.h>
#include <chrono>
#include <string>
namespace google::cloud::functions_internal {
inline namespace FUNCTIONS_FRAMEWORK_CPP_NS {
namespace {
using ::testing::HasSubstr;
namespace bp = boost::process;
// Even with C++17, we have to use the Boost version because Boost.Process
// expects it.
namespace bfs = boost::filesystem;
namespace beast = boost::beast;
namespace http = beast::http;
using http_response = http::response<http::string_body>;
http_response HttpGet(std::string const& host, std::string const& port,
std::string const& target) {
using tcp = boost::asio::ip::tcp;
// Create a socket to make the HTTP request over
boost::asio::io_context ioc;
tcp::resolver resolver(ioc);
beast::tcp_stream stream(ioc);
auto const results = resolver.resolve(host, port);
stream.connect(results);
// Use Boost.Beast to make the HTTP request
auto constexpr kHttpVersion = 10; // 1.0 as Boost.Beast spells it
http::request<http::string_body> req{http::verb::get, target, kHttpVersion};
req.set(http::field::user_agent, BOOST_BEAST_VERSION_STRING);
req.set(http::field::host, host);
http::write(stream, req);
beast::flat_buffer buffer;
http_response res;
http::read(stream, buffer, res);
stream.socket().shutdown(tcp::socket::shutdown_both);
return res;
}
int WaitForServerReady(std::string const& host, std::string const& port) {
auto constexpr kInitialDelay = std::chrono::milliseconds(100);
auto constexpr kAttempts = 5;
auto delay = kInitialDelay;
for (int i = 0; i != kAttempts; ++i) {
std::this_thread::sleep_for(delay);
try {
(void)HttpGet(host, port, "/ok");
return 0;
} catch (std::exception const& ex) {
std::cerr << "WaitForServerReady[" << i << "]: failed with " << ex.what()
<< std::endl;
}
delay *= 2;
}
return -1;
}
char const* argv0 = nullptr;
TEST(RunIntegrationTest, Basic) {
auto constexpr kOkay = 200;
auto constexpr kNotFound = 404;
auto constexpr kInternalError = 500;
auto const exe = bfs::path(argv0).parent_path() / "echo_server";
auto server = bp::child(exe, "--port=8080");
auto result = WaitForServerReady("localhost", "8080");
ASSERT_EQ(result, 0);
auto actual = HttpGet("localhost", "8080", "/say/hello");
EXPECT_EQ(actual.result_int(), kOkay);
EXPECT_THAT(actual.body(), HasSubstr(R"js("target": "/say/hello")js"));
actual = HttpGet("localhost", "8080", "/error/" + std::to_string(kNotFound));
EXPECT_THAT(actual.result_int(), kNotFound);
actual = HttpGet("localhost", "8080", "/exception/");
EXPECT_THAT(actual.result_int(), kInternalError);
try {
(void)HttpGet("localhost", "8080", "/quit/program/0");
} catch (...) {
}
server.wait();
EXPECT_EQ(server.exit_code(), 0);
}
} // namespace
} // namespace FUNCTIONS_FRAMEWORK_CPP_NS
} // namespace google::cloud::functions_internal
int main(int argc, char* argv[]) {
::testing::InitGoogleMock(&argc, argv);
google::cloud::functions_internal::argv0 = argv[0];
return RUN_ALL_TESTS();
}
<commit_msg>test: verify exceptions are logged (#110)<commit_after>// Copyright 2020 Google LLC
//
// Licensed under the Apache License, Version 2.0 (the "License");
// you may not use this file except in compliance with the License.
// You may obtain a copy of the License at
//
// http://www.apache.org/licenses/LICENSE-2.0
//
// Unless required by applicable law or agreed to in writing, software
// distributed under the License is distributed on an "AS IS" BASIS,
// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
// See the License for the specific language governing permissions and
// limitations under the License.
#include "google/cloud/functions/internal/framework.h"
#include <boost/asio/connect.hpp>
#include <boost/asio/ip/tcp.hpp>
#include <boost/beast.hpp>
#include <boost/filesystem.hpp>
#include <boost/process.hpp>
#include <gmock/gmock.h>
#include <chrono>
#include <string>
namespace google::cloud::functions_internal {
inline namespace FUNCTIONS_FRAMEWORK_CPP_NS {
namespace {
using ::testing::HasSubstr;
namespace bp = boost::process;
// Even with C++17, we have to use the Boost version because Boost.Process
// expects it.
namespace bfs = boost::filesystem;
namespace beast = boost::beast;
namespace http = beast::http;
using http_response = http::response<http::string_body>;
http_response HttpGet(std::string const& host, std::string const& port,
std::string const& target) {
using tcp = boost::asio::ip::tcp;
// Create a socket to make the HTTP request over
boost::asio::io_context ioc;
tcp::resolver resolver(ioc);
beast::tcp_stream stream(ioc);
auto const results = resolver.resolve(host, port);
stream.connect(results);
// Use Boost.Beast to make the HTTP request
auto constexpr kHttpVersion = 10; // 1.0 as Boost.Beast spells it
http::request<http::string_body> req{http::verb::get, target, kHttpVersion};
req.set(http::field::user_agent, BOOST_BEAST_VERSION_STRING);
req.set(http::field::host, host);
http::write(stream, req);
beast::flat_buffer buffer;
http_response res;
http::read(stream, buffer, res);
stream.socket().shutdown(tcp::socket::shutdown_both);
return res;
}
int WaitForServerReady(std::string const& host, std::string const& port) {
auto constexpr kInitialDelay = std::chrono::milliseconds(100);
auto constexpr kAttempts = 5;
auto delay = kInitialDelay;
for (int i = 0; i != kAttempts; ++i) {
std::this_thread::sleep_for(delay);
try {
(void)HttpGet(host, port, "/ok");
return 0;
} catch (std::exception const& ex) {
std::cerr << "WaitForServerReady[" << i << "]: failed with " << ex.what()
<< std::endl;
}
delay *= 2;
}
return -1;
}
char const* argv0 = nullptr;
TEST(RunIntegrationTest, Basic) {
auto constexpr kOkay = 200;
auto constexpr kNotFound = 404;
auto constexpr kInternalError = 500;
auto const exe = bfs::path(argv0).parent_path() / "echo_server";
auto server = bp::child(exe, "--port=8080");
auto result = WaitForServerReady("localhost", "8080");
ASSERT_EQ(result, 0);
auto actual = HttpGet("localhost", "8080", "/say/hello");
EXPECT_EQ(actual.result_int(), kOkay);
EXPECT_THAT(actual.body(), HasSubstr(R"js("target": "/say/hello")js"));
actual = HttpGet("localhost", "8080", "/error/" + std::to_string(kNotFound));
EXPECT_THAT(actual.result_int(), kNotFound);
actual = HttpGet("localhost", "8080", "/exception/");
EXPECT_THAT(actual.result_int(), kInternalError);
try {
(void)HttpGet("localhost", "8080", "/quit/program/0");
} catch (...) {
}
server.wait();
EXPECT_EQ(server.exit_code(), 0);
}
TEST(RunIntegrationTest, ExceptionLogsToStderr) {
auto constexpr kInternalError = 500;
auto const exe = bfs::path(argv0).parent_path() / "echo_server";
bp::ipstream child_stderr;
auto server = bp::child(exe, "--port=8080", bp::std_err > child_stderr);
auto result = WaitForServerReady("localhost", "8080");
ASSERT_EQ(result, 0);
auto actual = HttpGet("localhost", "8080", "/exception/test-string");
EXPECT_THAT(actual.result_int(), kInternalError);
std::string line;
std::getline(child_stderr, line);
EXPECT_THAT(line, HasSubstr("standard C++ exception"));
EXPECT_THAT(line, HasSubstr("/exception/test-string"));
try {
(void)HttpGet("localhost", "8080", "/quit/program/0");
} catch (...) {
}
server.wait();
EXPECT_EQ(server.exit_code(), 0);
}
} // namespace
} // namespace FUNCTIONS_FRAMEWORK_CPP_NS
} // namespace google::cloud::functions_internal
int main(int argc, char* argv[]) {
::testing::InitGoogleMock(&argc, argv);
google::cloud::functions_internal::argv0 = argv[0];
return RUN_ALL_TESTS();
}
<|endoftext|>
|
<commit_before>/* IBM_PROLOG_BEGIN_TAG */
/* This is an automatically generated prolog. */
/* */
/* $Source: src/import/chips/ocmb/explorer/procedures/hwp/memory/lib/omi/exp_omi_utils.H $ */
/* */
/* OpenPOWER HostBoot Project */
/* */
/* Contributors Listed Below - COPYRIGHT 2018,2019 */
/* [+] International Business Machines Corp. */
/* */
/* */
/* Licensed under the Apache License, Version 2.0 (the "License"); */
/* you may not use this file except in compliance with the License. */
/* You may obtain a copy of the License at */
/* */
/* http://www.apache.org/licenses/LICENSE-2.0 */
/* */
/* Unless required by applicable law or agreed to in writing, software */
/* distributed under the License is distributed on an "AS IS" BASIS, */
/* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or */
/* implied. See the License for the specific language governing */
/* permissions and limitations under the License. */
/* */
/* IBM_PROLOG_END_TAG */
///
/// @file exp_omi_utils.H
/// @brief OMI utility functions
///
// *HWP HWP Owner: Andre Marin <aamarin@us.ibm.com>
// *HWP HWP Backup: Stephen Glancy <sglancy@us.ibm.com>
// *HWP Team: Memory
// *HWP Level: 3
// *HWP Consumed by: Memory
#ifndef EXP_OMI_UTILS_H_
#define EXP_OMI_UTILS_H_
#include <fapi2.H>
#include <generic/memory/lib/utils/c_str.H>
namespace mss
{
namespace exp
{
namespace omi
{
///
/// @brief Constants used for the OMI register fields
///
// TODO:RTC196850 Update Explorer code to use actual register addresses/names
enum fields
{
// Bit we set to put ourselves into enterprise mode
ENTERPRISE_SET_BIT = 0,
HALF_DIMM_MODE = 1,
// How the HW is actually configured in enterprise mode
ENTERPRISE_BIT_CONFIG = 2,
};
///
/// @brief Constants used for the OMI registers
///
// TODO:RTC196850 Update Explorer code to use actual register addresses/names
enum registers
{
// Bit we set to put ourselves into enterprise mode
MENTERP = 0x080108e4,
};
///////////////////////////////////////////////////////////////////////////////////
/// Bit Field Operations
///////////////////////////////////////////////////////////////////////////////////
///
/// @brief Gets the enterprise set bit
/// @param[in] i_data the register data
/// @return The register's ENTERPRISE_SET_BIT
///
inline bool get_enterprise_set_bit( const fapi2::buffer<uint64_t>& i_data )
{
return i_data.getBit<fields::ENTERPRISE_SET_BIT>();
}
///
/// @brief Sets the enterprise set bit
/// @param[in,out] io_data the register data
/// @param[in] i_is_enterprise true IFF we're in enterprise mode
///
inline void set_enterprise_set_bit( fapi2::buffer<uint64_t>& io_data, const bool i_is_enterprise )
{
io_data.writeBit<fields::ENTERPRISE_SET_BIT>(i_is_enterprise);
}
///
/// @brief Gets the half-DIMM mode
/// @param[in] i_data the register data
/// @return The register's HALF_DIMM_MODE
///
inline bool get_half_dimm_mode( const fapi2::buffer<uint64_t>& i_data )
{
return i_data.getBit<fields::HALF_DIMM_MODE>();
}
///
/// @brief Sets the half-DIMM mode
/// @param[in,out] io_data the register data
/// @param[in] i_is_half_dimm_mode true IFF we're in half_dimm_mode mode
///
inline void set_half_dimm_mode( fapi2::buffer<uint64_t>& io_data, const bool i_is_half_dimm_mode )
{
io_data.writeBit<fields::HALF_DIMM_MODE>(i_is_half_dimm_mode);
}
// Note: ENTERPRISE_BIT_CONFIG is a Read only bit, so no setting it
///
/// @brief Gets the enterprise config bit
/// @param[in] i_data the register data
/// @return The register's ENTERPRISE_BIT_CONFIG
/// @note This bit indicates whether the hardware is in enterprise mode
///
inline bool get_enterprise_config( const fapi2::buffer<uint64_t>& i_data )
{
return i_data.getBit<fields::ENTERPRISE_BIT_CONFIG>();
}
///
/// @brief Checks if the enterprise config bit is in the correct mode
/// @param[in] i_target target on which we are operating - for logging
/// @param[in] i_is_enterprise true if the chip should be in enterprise mode
/// @param[in] i_data data from the enterprise mode register
/// @return fapi2::ReturnCode - FAPI2_RC_SUCCESS iff everything is OK
///
inline fapi2::ReturnCode check_enterprise_mode( const fapi2::Target<fapi2::TARGET_TYPE_OCMB_CHIP>& i_target,
const bool i_is_enterprise,
fapi2::buffer<uint64_t>& i_data )
{
const bool l_actual = mss::exp::omi::get_enterprise_config(i_data);
FAPI_ASSERT(l_actual == i_is_enterprise,
fapi2::MSS_EXP_ENTERPRISE_SETUP_ERROR()
.set_EXPECTED(i_is_enterprise)
.set_ACTUAL(l_actual)
.set_REGISTER_DATA(i_data)
.set_OCMB_TARGET(i_target),
"%s failed to setup enterprise mode properly expected: %u actual: %u register data 0x%016lx",
mss::c_str(i_target), i_is_enterprise, l_actual, i_data);
fapi_try_exit:
return fapi2::current_err;
}
///////////////////////////////////////////////////////////////////////////////////
/// Register access operations
///////////////////////////////////////////////////////////////////////////////////
// The scom API should be able to distinguish between the need for i2c vs MMIO
///
/// @brief Reads the register using I2C
/// @param[in] i_target the OCMB target on which to operate
/// @param[out] o_data the register contents
/// @return fapi2::ReturnCode - FAPI2_RC_SUCCESS iff get is OK
///
inline fapi2::ReturnCode read_enterprise_config( const fapi2::Target<fapi2::TARGET_TYPE_OCMB_CHIP>& i_target,
fapi2::buffer<uint64_t>& o_data )
{
return fapi2::getScom(i_target, registers::MENTERP, o_data);
}
///
/// @brief Writes the register using I2C
/// @param[in] i_target the OCMB target on which to operate
/// @param[in] i_data the register contents
/// @return fapi2::ReturnCode - FAPI2_RC_SUCCESS iff get is OK
///
inline fapi2::ReturnCode write_enterprise_config( const fapi2::Target<fapi2::TARGET_TYPE_OCMB_CHIP>& i_target,
const fapi2::buffer<uint64_t>& i_data )
{
return fapi2::putScom(i_target, registers::MENTERP, i_data);
}
} // ns mss
} // ns exp
} // ns omi
#endif
<commit_msg>Adds explorer OMI training code<commit_after>/* IBM_PROLOG_BEGIN_TAG */
/* This is an automatically generated prolog. */
/* */
/* $Source: src/import/chips/ocmb/explorer/procedures/hwp/memory/lib/omi/exp_omi_utils.H $ */
/* */
/* OpenPOWER HostBoot Project */
/* */
/* Contributors Listed Below - COPYRIGHT 2018,2019 */
/* [+] International Business Machines Corp. */
/* */
/* */
/* Licensed under the Apache License, Version 2.0 (the "License"); */
/* you may not use this file except in compliance with the License. */
/* You may obtain a copy of the License at */
/* */
/* http://www.apache.org/licenses/LICENSE-2.0 */
/* */
/* Unless required by applicable law or agreed to in writing, software */
/* distributed under the License is distributed on an "AS IS" BASIS, */
/* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or */
/* implied. See the License for the specific language governing */
/* permissions and limitations under the License. */
/* */
/* IBM_PROLOG_END_TAG */
///
/// @file exp_omi_utils.H
/// @brief OMI utility functions
///
// *HWP HWP Owner: Andre Marin <aamarin@us.ibm.com>
// *HWP HWP Backup: Stephen Glancy <sglancy@us.ibm.com>
// *HWP Team: Memory
// *HWP Level: 3
// *HWP Consumed by: Memory
#ifndef EXP_OMI_UTILS_H_
#define EXP_OMI_UTILS_H_
#include <fapi2.H>
#include <generic/memory/lib/utils/c_str.H>
namespace mss
{
namespace exp
{
namespace omi
{
///
/// @brief Constants used for the OMI register fields
///
// TODO:RTC196850 Update Explorer code to use actual register addresses/names
enum fields
{
// Bit we set to put ourselves into enterprise mode
ENTERPRISE_SET_BIT = 0,
HALF_DIMM_MODE = 1,
// How the HW is actually configured in enterprise mode
ENTERPRISE_BIT_CONFIG = 2,
};
///
/// @brief Constants used for the OMI registers
///
// TODO:RTC196850 Update Explorer code to use actual register addresses/names
enum registers
{
// Bit we set to put ourselves into enterprise mode
MENTERP = 0x080108e4,
};
///////////////////////////////////////////////////////////////////////////////////
/// Bit Field Operations
///////////////////////////////////////////////////////////////////////////////////
///
/// @brief Gets the enterprise set bit
/// @param[in] i_data the register data
/// @return The register's ENTERPRISE_SET_BIT
///
inline bool get_enterprise_set_bit( const fapi2::buffer<uint64_t>& i_data )
{
return i_data.getBit<fields::ENTERPRISE_SET_BIT>();
}
///
/// @brief Sets the enterprise set bit
/// @param[in,out] io_data the register data
/// @param[in] i_is_enterprise true IFF we're in enterprise mode
///
inline void set_enterprise_set_bit( fapi2::buffer<uint64_t>& io_data, const bool i_is_enterprise )
{
io_data.writeBit<fields::ENTERPRISE_SET_BIT>(i_is_enterprise);
}
///
/// @brief Gets the half-DIMM mode
/// @param[in] i_data the register data
/// @return The register's HALF_DIMM_MODE
///
inline bool get_half_dimm_mode( const fapi2::buffer<uint64_t>& i_data )
{
return i_data.getBit<fields::HALF_DIMM_MODE>();
}
///
/// @brief Sets the half-DIMM mode
/// @param[in,out] io_data the register data
/// @param[in] i_is_half_dimm_mode true IFF we're in half_dimm_mode mode
///
inline void set_half_dimm_mode( fapi2::buffer<uint64_t>& io_data, const bool i_is_half_dimm_mode )
{
io_data.writeBit<fields::HALF_DIMM_MODE>(i_is_half_dimm_mode);
}
// Note: ENTERPRISE_BIT_CONFIG is a Read only bit, so no setting it
///
/// @brief Gets the enterprise config bit
/// @param[in] i_data the register data
/// @return The register's ENTERPRISE_BIT_CONFIG
/// @note This bit indicates whether the hardware is in enterprise mode
///
inline bool get_enterprise_config( const fapi2::buffer<uint64_t>& i_data )
{
return i_data.getBit<fields::ENTERPRISE_BIT_CONFIG>();
}
///
/// @brief Checks if the enterprise config bit is in the correct mode
/// @param[in] i_target target on which we are operating - for logging
/// @param[in] i_is_enterprise true if the chip should be in enterprise mode
/// @param[in] i_data data from the enterprise mode register
/// @return fapi2::ReturnCode - FAPI2_RC_SUCCESS iff everything is OK
///
inline fapi2::ReturnCode check_enterprise_mode( const fapi2::Target<fapi2::TARGET_TYPE_OCMB_CHIP>& i_target,
const bool i_is_enterprise,
fapi2::buffer<uint64_t>& i_data )
{
const bool l_actual = mss::exp::omi::get_enterprise_config(i_data);
FAPI_ASSERT(l_actual == i_is_enterprise,
fapi2::MSS_EXP_ENTERPRISE_SETUP_ERROR()
.set_EXPECTED(i_is_enterprise)
.set_ACTUAL(l_actual)
.set_REGISTER_DATA(i_data)
.set_OCMB_TARGET(i_target),
"%s failed to setup enterprise mode properly expected: %u actual: %u register data 0x%016lx",
mss::c_str(i_target), i_is_enterprise, l_actual, i_data);
fapi_try_exit:
return fapi2::current_err;
}
///////////////////////////////////////////////////////////////////////////////////
/// Register access operations
///////////////////////////////////////////////////////////////////////////////////
// The scom API should be able to distinguish between the need for i2c vs MMIO
///
/// @brief Reads the register using I2C
/// @param[in] i_target the OCMB target on which to operate
/// @param[out] o_data the register contents
/// @return fapi2::ReturnCode - FAPI2_RC_SUCCESS iff get is OK
///
inline fapi2::ReturnCode read_enterprise_config( const fapi2::Target<fapi2::TARGET_TYPE_OCMB_CHIP>& i_target,
fapi2::buffer<uint64_t>& o_data )
{
return fapi2::getScom(i_target, registers::MENTERP, o_data);
}
///
/// @brief Writes the register using I2C
/// @param[in] i_target the OCMB target on which to operate
/// @param[in] i_data the register contents
/// @return fapi2::ReturnCode - FAPI2_RC_SUCCESS iff get is OK
///
inline fapi2::ReturnCode write_enterprise_config( const fapi2::Target<fapi2::TARGET_TYPE_OCMB_CHIP>& i_target,
const fapi2::buffer<uint64_t>& i_data )
{
return fapi2::putScom(i_target, registers::MENTERP, i_data);
}
namespace train
{
///
/// @brief Sets up the OMI training
/// @param[in] i_target target on which the code is operating
/// @param[in] i_manufacturing_mode manufacturing mode control
/// @param[in] i_loopback_testing loopback testing control
/// @param[in] i_transport_layer transport layer configuration
/// @param[in] i_dl_layer DL layer boot mode
/// @param[in] i_boot_mode true if step-by-step mode
/// @param[in] i_lane_mode lane mode configuration
/// @param[in] i_serdes serdes frequency
/// @param[out] o_data data for the FW_BOOT_CONFIG
/// @return fapi2::ReturnCode - FAPI2_RC_SUCCESS iff get is OK
///
fapi2::ReturnCode setup_fw_boot_config( const fapi2::Target<fapi2::TARGET_TYPE_OCMB_CHIP>& i_target,
const uint8_t i_manufacturing_mode,
const uint8_t i_loopback_testing,
const uint8_t i_transport_layer,
const uint8_t i_dl_layer,
const uint8_t i_boot_mode,
const uint8_t i_lane_mode,
const uint8_t i_serdes,
std::vector<uint8_t>& o_data );
} // ns train
} // ns omi
} // ns exp
} // ns mss
#endif
<|endoftext|>
|
<commit_before>#ifndef BFC_AST_MOD_HPP
#define BFC_AST_MOD_HPP
#include "types.h"
#include "ast/base.hpp"
#include "ast/seq.hpp"
#include "ast/traits.hpp"
#include "ast/visitor.hpp"
#include "token.hpp"
#include <cstddef>
namespace bfc {
namespace ast {
/* NB: when adding visitable node types, make sure you add a forward
* declaration in "ast/visitor.hpp" and a visit overload on the visitor
* abstract class.
*/
class set :public base_crtp<set>, public arith {
public:
set(source_loc loc, ptrdiff_t offset, bf_value value) noexcept :
arith{std::move(loc), offset, value}
{}
};
class add : public base_crtp<add>, public arith {
public:
add(source_loc loc, ptrdiff_t offset, bf_value value) noexcept :
arith{std::move(loc), offset, value}
{}
};
class sub : public base_crtp<sub>, public arith {
public:
sub(source_loc loc, ptrdiff_t offset, bf_value value) noexcept :
arith{std::move(loc), offset, value}
{}
};
class mul : public base_crtp<mul>, public arith {
public:
mul(source_loc loc, ptrdiff_t offset, bf_value value) noexcept :
arith{std::move(loc), offset, value}
{}
};
class mov : public base_crtp<mov>, public ptr_op {
public:
mov(source_loc loc, ptrdiff_t offset) noexcept :
ptr_op{std::move(loc), offset}
{}
};
class program : public has_loc, public seq {
public:
program(source_loc loc, seq op_seq) noexcept :
has_loc{std::move(loc)}, seq{std::move(op_seq)}
{}
};
class loop : public has_loc, public seq {
public:
loop(source_loc begin_pos, seq op_seq) noexcept :
has_loc{begin_pos}, seq{std::move(op_seq)}
{}
};
class read : public io {
public:
read(source_loc loc, ptrdiff_t offset) noexcept :
io{std::move(loc), offset}
{}
};
class write : public io {
public:
write(source_loc loc, ptrdiff_t offset) noexcept :
io{std::move(loc), offset}
{}
};
}
}
#endif /* !BFC_AST_HPP */
<commit_msg>Fix ambiguous inheritance chains (diamond problem is bad).<commit_after>#ifndef BFC_AST_MOD_HPP
#define BFC_AST_MOD_HPP
#include "types.h"
#include "ast/base.hpp"
#include "ast/seq.hpp"
#include "ast/traits.hpp"
#include "ast/visitor.hpp"
#include "token.hpp"
#include <cstddef>
namespace bfc {
namespace ast {
/* NB: when adding visitable node types, make sure you add a forward
* declaration in "ast/visitor.hpp" and a visit overload on the visitor
* abstract class.
*/
class set : public base_crtp<set>, public arith {
public:
set(source_loc loc, ptrdiff_t offset, bf_value value) noexcept :
arith{std::move(loc), offset, value}
{}
};
class add : public base_crtp<add>, public arith {
public:
add(source_loc loc, ptrdiff_t offset, bf_value value) noexcept :
arith{std::move(loc), offset, value}
{}
};
class sub : public base_crtp<sub>, public arith {
public:
sub(source_loc loc, ptrdiff_t offset, bf_value value) noexcept :
arith{std::move(loc), offset, value}
{}
};
class mul : public base_crtp<mul>, public arith {
public:
mul(source_loc loc, ptrdiff_t offset, bf_value value) noexcept :
arith{std::move(loc), offset, value}
{}
};
class mov : public base_crtp<mov>, public ptr_op {
public:
mov(source_loc loc, ptrdiff_t offset) noexcept :
ptr_op{std::move(loc), offset}
{}
};
/* Cannot inherit from base_crtp because of the diamond problem. */
class program : public has_loc, public seq {
public:
program(source_loc loc, seq op_seq) noexcept :
has_loc{std::move(loc)}, seq{std::move(op_seq)}
{}
visitor::status accept(visitor &obj) override
{
return obj.visit(*this);
}
visitor::status accept(visitor &obj) const override
{
return obj.visit(*this);
}
private:
base *clone(void) const override
{
return new program{*this};
}
};
/* Cannot inherit from base_crtp because of the diamond problem. */
class loop : public has_loc, public seq {
public:
loop(source_loc begin_pos, seq op_seq) noexcept :
has_loc{begin_pos}, seq{std::move(op_seq)}
{}
visitor::status accept(visitor &obj) override
{
return obj.visit(*this);
}
visitor::status accept(visitor &obj) const override
{
return obj.visit(*this);
}
private:
base *clone(void) const override
{
return new loop{*this};
}
};
class read : public base_crtp<read>, public io {
public:
read(source_loc loc, ptrdiff_t offset) noexcept :
io{std::move(loc), offset}
{}
};
class write : public base_crtp<write>, public io {
public:
write(source_loc loc, ptrdiff_t offset) noexcept :
io{std::move(loc), offset}
{}
};
}
}
#endif /* !BFC_AST_HPP */
<|endoftext|>
|
<commit_before>/* IBM_PROLOG_BEGIN_TAG */
/* This is an automatically generated prolog. */
/* */
/* $Source: src/import/chips/ocmb/explorer/procedures/hwp/memory/lib/shared/exp_consts.H $ */
/* */
/* OpenPOWER HostBoot Project */
/* */
/* Contributors Listed Below - COPYRIGHT 2018,2019 */
/* [+] International Business Machines Corp. */
/* */
/* */
/* Licensed under the Apache License, Version 2.0 (the "License"); */
/* you may not use this file except in compliance with the License. */
/* You may obtain a copy of the License at */
/* */
/* http://www.apache.org/licenses/LICENSE-2.0 */
/* */
/* Unless required by applicable law or agreed to in writing, software */
/* distributed under the License is distributed on an "AS IS" BASIS, */
/* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or */
/* implied. See the License for the specific language governing */
/* permissions and limitations under the License. */
/* */
/* IBM_PROLOG_END_TAG */
<commit_msg>Added I2C fields, EXP_FW_STATUS API<commit_after>/* IBM_PROLOG_BEGIN_TAG */
/* This is an automatically generated prolog. */
/* */
/* $Source: src/import/chips/ocmb/explorer/procedures/hwp/memory/lib/shared/exp_consts.H $ */
/* */
/* OpenPOWER HostBoot Project */
/* */
/* Contributors Listed Below - COPYRIGHT 2018,2019 */
/* [+] International Business Machines Corp. */
/* */
/* */
/* Licensed under the Apache License, Version 2.0 (the "License"); */
/* you may not use this file except in compliance with the License. */
/* You may obtain a copy of the License at */
/* */
/* http://www.apache.org/licenses/LICENSE-2.0 */
/* */
/* Unless required by applicable law or agreed to in writing, software */
/* distributed under the License is distributed on an "AS IS" BASIS, */
/* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or */
/* implied. See the License for the specific language governing */
/* permissions and limitations under the License. */
/* */
/* IBM_PROLOG_END_TAG */
///
/// @file explorer_check_for_ready.H
/// @brief explorer_check_for_ready HWP declaration
///
// *HWP HWP Owner: Andre A. Marin <aamarin@us.ibm.com>
// *HWP HWP Backup: Louis Stermole <stermole@us.ibm.com>
// *HWP Team: Memory
// *HWP Level: 2
// *HWP Consumed by: CI
namespace mss
{
namespace exp
{
namespace i2c
{
///
/// @brief explorer ffdc codes
///
enum ffdc_codes
{
EXP_I2C_GET_FIELD = 0x0000,
EXP_I2C_SET_FIELD = 0x0001,
};
/// @brief List of explorer I2C commands
///
enum cmd_id : uint8_t
{
FW_BOOT_CONFIG = 0x01,
FW_STATUS = 0x02,
FW_REG_ADDR_LATCH = 0x03,
FW_REG_READ = 0x04,
FW_REG_WRITE = 0x05,
FW_DOWNLOAD = 0x06,
FW_CONT_REG_READ = 0x07,
FW_CONT_REG_WRITE = 0x08,
};
///
/// @brief common explorer sizes
///
enum sizes
{
// 32-bit commands
FW_BOOT_CONFIG_BYTE_LEN = 4,
FW_STATUS_BYTE_LEN = 4,
// Largest R/W length for bytes of data
MIN_DATA_BYTES_LEN = 1,
MAX_DATA_BYTES_LEN = 32,
};
///
/// @brief General I2C status codes
/// @note Shared I2C status codes for EXP_FW_REG_READ, EXP_FW_REG_WRITE,
/// EXP_FW_CONT_REG_READ, and EXP_FW_CONT_REG_WRITE
///
enum status_codes
{
SUCCESS = 0x00,
ADDRESS_OUT_OF_RANGE = 0x01,
ADDRESS_PROHIBITED = 0x02,
};
///
/// @brief status codes for FW_BOOT_CONFIG
///
enum fw_boot_cfg_status
{
FW_BOOT_CFG_SUCCESS = status_codes::SUCCESS,
// Loopback fail
FW_BOOT_CFG_LB_FAIL = 0x01,
// Transport layer fail
FW_BOOT_CFG_UNSUPPORTED_TL = 0x02,
// DL (data link) layer fail
FW_BOOT_CFG_UNSUPPORTED_DL = 0x03,
// SERDES (serializer/deserializer) FREQ fail
FW_BOOT_CFG_UNSUPPORTED_SERDES_FREQ = 0x04,
};
///
/// @brief I2C boot stage options
/// @note certain cmds work in certain boot stages
///
enum boot_stages
{
BOOT_ROM_STAGE = 0x01,
FW_UPGRADE_MODE = 0x02,
RUNTIME_FW = 0x03,
};
}// i2c
}// exp
}// mss
<|endoftext|>
|
<commit_before><commit_msg>bortli compression detection fixed<commit_after><|endoftext|>
|
<commit_before>/*
* Licensed to the Apache Software Foundation (ASF) under one
* or more contributor license agreements. See the NOTICE file
* distributed with this work for additional information
* regarding copyright ownership. The ASF licenses this file
* to you under the Apache License, Version 2.0 (the
* "License"); you may not use this file except in compliance
* with the License. You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing,
* software distributed under the License is distributed on an
* "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
* KIND, either express or implied. See the License for the
* specific language governing permissions and limitations
* under the License.
*/
/* cacheurl.cc - Plugin to modify the URL used as a cache key for certain
* requests, without modifying the URL used for actually fetching data from
* the origin server.
*/
#include <stdio.h>
#include <string.h>
#include "ink_config.h"
#ifdef HAVE_PCRE_PCRE_H
#include <pcre/pcre.h>
#else
#include <pcre.h>
#endif
#include "ts/ts.h"
#include "ts/remap.h"
#include "ink_defs.h"
#include <string>
#include <vector>
#define TOKENCOUNT 10
#define OVECOUNT 30
#define PLUGIN_NAME "cacheurl"
struct regex_info
{
pcre *re; /* Compiled regular expression */
int tokcount; /* Token count */
char *pattern; /* Pattern string */
char *replacement; /* Replacement string */
int *tokens; /* Array of $x token values */
int *tokenoffset; /* Array of $x token offsets */
};
struct pr_list
{
std::vector<regex_info*>pr;
pr_list()
{
}
~pr_list()
{
for (std::vector < regex_info * >::iterator info = this->pr.begin(); info != this->pr.end(); ++info) {
TSfree((*info)->tokens);
TSfree((*info)->tokenoffset);
pcre_free((*info)->re);
TSfree(*info);
}
}
};
static int
regex_substitute(char **buf, char *str, regex_info * info)
{
int matchcount;
int ovector[OVECOUNT]; /* Locations of matches in regex */
int replacelen; /* length of replacement string */
int i;
int offset;
int prev;
/* Perform the regex matching */
matchcount = pcre_exec(info->re, NULL, str, strlen(str), 0, 0, ovector, OVECOUNT);
if (matchcount < 0) {
switch (matchcount) {
case PCRE_ERROR_NOMATCH:
break;
default:
TSError("[%s] Matching error: %d\n", PLUGIN_NAME, matchcount);
break;
}
return 0;
}
/* Verify the replacement has the right number of matching groups */
for (i = 0; i < info->tokcount; i++) {
if (info->tokens[i] >= matchcount) {
TSError("[%s] Invalid reference int replacement: $%d\n", PLUGIN_NAME, info->tokens[i]);
return 0;
}
}
/* malloc the replacement string */
replacelen = strlen(info->replacement);
replacelen -= info->tokcount * 2; /* Subtract $1, $2 etc... */
for (i = 0; i < info->tokcount; i++) {
replacelen += (ovector[info->tokens[i] * 2 + 1] - ovector[info->tokens[i] * 2]);
}
replacelen++; /* Null terminator */
*buf = (char *) TSmalloc(replacelen);
/* perform string replacement */
offset = 0; /* Where we are adding new data in the string */
prev = 0;
for (i = 0; i < info->tokcount; i++) {
memcpy(*buf + offset, info->replacement + prev, info->tokenoffset[i] - prev);
offset += (info->tokenoffset[i] - prev);
prev = info->tokenoffset[i] + 2;
memcpy(*buf + offset, str + ovector[info->tokens[i] * 2],
ovector[info->tokens[i] * 2 + 1] - ovector[info->tokens[i] * 2]);
offset += (ovector[info->tokens[i] * 2 + 1] - ovector[info->tokens[i] * 2]);
}
memcpy(*buf + offset, info->replacement + prev, strlen(info->replacement) - prev);
offset += strlen(info->replacement) - prev;
(*buf)[offset] = 0; /* Null termination */
return 1;
}
static int
regex_compile(regex_info ** buf, char *pattern, char *replacement)
{
const char *reerror; /* Error string from pcre */
int reerroffset; /* Offset where any pcre error occured */
int tokcount;
int *tokens;
int *tokenoffset;
int status = 1; /* Status (return value) of the function */
regex_info *info = (regex_info *) TSmalloc(sizeof(regex_info));
/* Precompile the regular expression */
info->re = pcre_compile(pattern, 0, &reerror, &reerroffset, NULL);
if (!info->re) {
TSError("[%s] Compilation of regex '%s' failed at char %d: %s\n", PLUGIN_NAME, pattern, reerroffset, reerror);
status = 0;
}
/* Precalculate the location of $X tokens in the replacement */
tokcount = 0;
if (status) {
tokens = (int *) TSmalloc(sizeof(int) * TOKENCOUNT);
tokenoffset = (int *) TSmalloc(sizeof(int) * TOKENCOUNT);
for (unsigned i = 0; i < strlen(replacement); i++) {
if (replacement[i] == '$') {
if (tokcount >= TOKENCOUNT) {
TSError("[%s] Error: too many tokens in replacement " "string: %s\n", PLUGIN_NAME, replacement);
status = 0;
break;
} else if (replacement[i + 1] < '0' || replacement[i + 1] > '9') {
TSError("[%s] Error: Invalid replacement token $%c in %s: should be $0 - $9\n",
PLUGIN_NAME, replacement[i + 1], replacement);
status = 0;
break;
} else {
/* Store the location of the replacement */
/* Convert '0' to 0 */
tokens[tokcount] = replacement[i + 1] - '0';
tokenoffset[tokcount] = i;
tokcount++;
/* Skip the next char */
i++;
}
}
}
}
if (status) {
/* Everything went OK */
info->tokcount = tokcount;
info->tokens = tokens;
info->tokenoffset = tokenoffset;
info->pattern = TSstrdup(pattern);
info->replacement = TSstrdup(replacement);
*buf = info;
} else {
/* Something went wrong, clean up */
if (info->tokens)
TSfree(info->tokens);
if (info->tokenoffset)
TSfree(info->tokenoffset);
if (info->re)
pcre_free(info->re);
if (info)
TSfree(info);
}
return status;
}
static pr_list *
load_config_file(const char *config_file)
{
char buffer[1024];
std::string path;
TSFile fh;
pr_list *prl = new pr_list();
/* locations in a config file line, end of line, split start, split end */
char *eol, *spstart, *spend;
int lineno = 0;
int retval;
regex_info *info = 0;
if (config_file == NULL) {
/* Default config file of plugins/cacheurl.config */
path = TSPluginDirGet();
path += "/cacheurl.config";
} else if (*config_file != '/') {
// Relative paths are relative to the config directory
path = TSConfigDirGet();
path += "/";
path += config_file;
} else {
// Absolute path ...
path = config_file;
}
TSDebug(PLUGIN_NAME, "Opening config file: %s", path.c_str());
fh = TSfopen(path.c_str(), "r");
if (!fh) {
TSError("[%s] Unable to open %s. No patterns will be loaded\n", PLUGIN_NAME, path.c_str());
return prl;
}
while (TSfgets(fh, buffer, sizeof(buffer) - 1)) {
lineno++;
if (*buffer == '#') {
/* # Comments, only at line beginning */
continue;
}
eol = strstr(buffer, "\n");
if (eol) {
*eol = 0; /* Terminate string at newline */
} else {
/* Malformed line - skip */
continue;
}
/* Split line into two parts based on whitespace */
/* Find first whitespace */
spstart = strstr(buffer, " ");
if (!spstart) {
spstart = strstr(buffer, "\t");
}
if (!spstart) {
TSError("[%s] ERROR: Invalid format on line %d. Skipping\n", PLUGIN_NAME, lineno);
continue;
}
/* Find part of the line after any whitespace */
spend = spstart + 1;
while (*spend == ' ' || *spend == '\t') {
spend++;
}
if (*spend == 0) {
/* We reached the end of the string without any non-whitepace */
TSError("[%s] ERROR: Invalid format on line %d. Skipping\n", PLUGIN_NAME, lineno);
continue;
}
*spstart = 0;
/* We have the pattern/replacement, now do precompilation.
* buffer is the first part of the line. spend is the second part just
* after the whitespace */
TSDebug(PLUGIN_NAME, "Adding pattern/replacement pair: '%s' -> '%s'", buffer, spend);
retval = regex_compile(&info, buffer, spend);
if (!retval) {
TSError("[%s] Error precompiling regex/replacement. Skipping.\n", PLUGIN_NAME);
}
prl->pr.push_back(info);
}
TSfclose(fh);
TSDebug(PLUGIN_NAME, "loaded %u regexes", (unsigned) prl->pr.size());
return prl;
}
static int
rewrite_cacheurl(pr_list * prl, TSHttpTxn txnp)
{
int ok = 1;
char *newurl = 0;
int retval;
char *url;
int url_length;
url = TSHttpTxnEffectiveUrlStringGet(txnp, &url_length);
if (!url) {
TSError("[%s] couldn't retrieve request url\n", PLUGIN_NAME);
ok = 0;
}
if (ok) {
for (std::vector<regex_info*>::iterator info = prl->pr.begin(); info != prl->pr.end(); ++info) {
retval = regex_substitute(&newurl, url, *info);
if (retval) {
/* Successful match/substitution */
break;
}
}
if (newurl) {
TSDebug(PLUGIN_NAME, "Rewriting cache URL for %s to %s", url, newurl);
if (TSCacheUrlSet(txnp, newurl, strlen(newurl))
!= TS_SUCCESS) {
TSError("[%s] Unable to modify cache url from " "%s to %s\n", PLUGIN_NAME, url, newurl);
ok = 0;
}
}
}
/* Clean up */
if (url)
TSfree(url);
if (newurl)
TSfree(newurl);
return ok;
}
static int
handle_hook(TSCont contp, TSEvent event, void *edata)
{
TSHttpTxn txnp = (TSHttpTxn) edata;
pr_list *prl;
int ok = 1;
prl = (pr_list *) TSContDataGet(contp);
switch (event) {
case TS_EVENT_HTTP_READ_REQUEST_HDR:
ok = rewrite_cacheurl(prl, txnp);
TSHttpTxnReenable(txnp, TS_EVENT_HTTP_CONTINUE);
break;
default:
TSAssert(!"Unexpected event");
ok = 0;
break;
}
return ok;
}
/* Generic error message function for errors in plugin initialization */
static void
initialization_error(const char *msg)
{
TSError("[%s] %s\n", PLUGIN_NAME, msg);
TSError("[%s] Unable to initialize plugin (disabled).\n", PLUGIN_NAME);
}
TSReturnCode
TSRemapInit(TSRemapInterface * api_info, char *errbuf, int errbuf_size)
{
if (!api_info) {
strncpy(errbuf, "[tsremap_init] Invalid TSRemapInterface argument", errbuf_size - 1);
return TS_ERROR;
}
if (api_info->size < sizeof(TSRemapInterface)) {
strncpy(errbuf, "[tsremap_init] Incorrect size of TSRemapInterface structure", errbuf_size - 1);
return TS_ERROR;
}
if (api_info->tsremap_version < TSREMAP_VERSION) {
snprintf(errbuf, errbuf_size - 1, "[tsremap_init] Incorrect API version %ld.%ld",
api_info->tsremap_version >> 16, (api_info->tsremap_version & 0xffff));
return TS_ERROR;
}
TSDebug(PLUGIN_NAME, "remap plugin is successfully initialized");
return TS_SUCCESS;
}
TSReturnCode
TSRemapNewInstance(int argc, char *argv[], void **ih, char *errbuf ATS_UNUSED, int errbuf_size ATS_UNUSED)
{
*ih = load_config_file(argc > 2 ? argv[2] : NULL);
return TS_SUCCESS;
}
void
TSRemapDeleteInstance(void *ih)
{
pr_list *prl = (pr_list *) ih;
TSDebug(PLUGIN_NAME, "Deleting remap instance");
delete prl;
}
TSRemapStatus
TSRemapDoRemap(void *ih, TSHttpTxn rh, TSRemapRequestInfo * rri ATS_UNUSED)
{
int ok;
ok = rewrite_cacheurl((pr_list *) ih, rh);
if (ok) {
return TSREMAP_NO_REMAP;
} else {
return TSREMAP_ERROR;
}
}
void
TSPluginInit(int argc, const char *argv[])
{
TSPluginRegistrationInfo info;
TSCont contp;
pr_list *prl;
info.plugin_name = (char *) PLUGIN_NAME;
info.vendor_name = (char *) "Apache Software Foundation";
info.support_email = (char *) "dev@trafficserver.apache.org";
if (TSPluginRegister(TS_SDK_VERSION_3_0, &info) != TS_SUCCESS) {
initialization_error("Plugin registration failed.");
return;
}
prl = load_config_file(argc > 1 ? argv[1] : NULL);
contp = TSContCreate((TSEventFunc) handle_hook, NULL);
/* Store the pattern replacement list in the continuation */
TSContDataSet(contp, prl);
TSHttpHookAdd(TS_HTTP_READ_REQUEST_HDR_HOOK, contp);
}
<commit_msg>TS-1475: Coverity 120023 120024 - fix resource leak<commit_after>/*
* Licensed to the Apache Software Foundation (ASF) under one
* or more contributor license agreements. See the NOTICE file
* distributed with this work for additional information
* regarding copyright ownership. The ASF licenses this file
* to you under the Apache License, Version 2.0 (the
* "License"); you may not use this file except in compliance
* with the License. You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing,
* software distributed under the License is distributed on an
* "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
* KIND, either express or implied. See the License for the
* specific language governing permissions and limitations
* under the License.
*/
/* cacheurl.cc - Plugin to modify the URL used as a cache key for certain
* requests, without modifying the URL used for actually fetching data from
* the origin server.
*/
#include <stdio.h>
#include <string.h>
#include "ink_config.h"
#ifdef HAVE_PCRE_PCRE_H
#include <pcre/pcre.h>
#else
#include <pcre.h>
#endif
#include "ts/ts.h"
#include "ts/remap.h"
#include "ink_defs.h"
#include <string>
#include <vector>
#define TOKENCOUNT 10
#define OVECOUNT 30
#define PLUGIN_NAME "cacheurl"
struct regex_info
{
pcre *re; /* Compiled regular expression */
int tokcount; /* Token count */
char *pattern; /* Pattern string */
char *replacement; /* Replacement string */
int *tokens; /* Array of $x token values */
int *tokenoffset; /* Array of $x token offsets */
};
struct pr_list
{
std::vector<regex_info*>pr;
pr_list()
{
}
~pr_list()
{
for (std::vector < regex_info * >::iterator info = this->pr.begin(); info != this->pr.end(); ++info) {
TSfree((*info)->tokens);
TSfree((*info)->tokenoffset);
pcre_free((*info)->re);
TSfree(*info);
}
}
};
static int
regex_substitute(char **buf, char *str, regex_info * info)
{
int matchcount;
int ovector[OVECOUNT]; /* Locations of matches in regex */
int replacelen; /* length of replacement string */
int i;
int offset;
int prev;
/* Perform the regex matching */
matchcount = pcre_exec(info->re, NULL, str, strlen(str), 0, 0, ovector, OVECOUNT);
if (matchcount < 0) {
switch (matchcount) {
case PCRE_ERROR_NOMATCH:
break;
default:
TSError("[%s] Matching error: %d\n", PLUGIN_NAME, matchcount);
break;
}
return 0;
}
/* Verify the replacement has the right number of matching groups */
for (i = 0; i < info->tokcount; i++) {
if (info->tokens[i] >= matchcount) {
TSError("[%s] Invalid reference int replacement: $%d\n", PLUGIN_NAME, info->tokens[i]);
return 0;
}
}
/* malloc the replacement string */
replacelen = strlen(info->replacement);
replacelen -= info->tokcount * 2; /* Subtract $1, $2 etc... */
for (i = 0; i < info->tokcount; i++) {
replacelen += (ovector[info->tokens[i] * 2 + 1] - ovector[info->tokens[i] * 2]);
}
replacelen++; /* Null terminator */
*buf = (char *) TSmalloc(replacelen);
/* perform string replacement */
offset = 0; /* Where we are adding new data in the string */
prev = 0;
for (i = 0; i < info->tokcount; i++) {
memcpy(*buf + offset, info->replacement + prev, info->tokenoffset[i] - prev);
offset += (info->tokenoffset[i] - prev);
prev = info->tokenoffset[i] + 2;
memcpy(*buf + offset, str + ovector[info->tokens[i] * 2],
ovector[info->tokens[i] * 2 + 1] - ovector[info->tokens[i] * 2]);
offset += (ovector[info->tokens[i] * 2 + 1] - ovector[info->tokens[i] * 2]);
}
memcpy(*buf + offset, info->replacement + prev, strlen(info->replacement) - prev);
offset += strlen(info->replacement) - prev;
(*buf)[offset] = 0; /* Null termination */
return 1;
}
static int
regex_compile(regex_info ** buf, char *pattern, char *replacement)
{
const char *reerror; /* Error string from pcre */
int reerroffset; /* Offset where any pcre error occured */
int tokcount;
int *tokens = NULL;
int *tokenoffset = NULL;
int status = 1; /* Status (return value) of the function */
regex_info *info = (regex_info *) TSmalloc(sizeof(regex_info));
/* Precompile the regular expression */
info->re = pcre_compile(pattern, 0, &reerror, &reerroffset, NULL);
if (!info->re) {
TSError("[%s] Compilation of regex '%s' failed at char %d: %s\n", PLUGIN_NAME, pattern, reerroffset, reerror);
status = 0;
}
/* Precalculate the location of $X tokens in the replacement */
tokcount = 0;
if (status) {
tokens = (int *) TSmalloc(sizeof(int) * TOKENCOUNT);
tokenoffset = (int *) TSmalloc(sizeof(int) * TOKENCOUNT);
for (unsigned i = 0; i < strlen(replacement); i++) {
if (replacement[i] == '$') {
if (tokcount >= TOKENCOUNT) {
TSError("[%s] Error: too many tokens in replacement " "string: %s\n", PLUGIN_NAME, replacement);
status = 0;
break;
} else if (replacement[i + 1] < '0' || replacement[i + 1] > '9') {
TSError("[%s] Error: Invalid replacement token $%c in %s: should be $0 - $9\n",
PLUGIN_NAME, replacement[i + 1], replacement);
status = 0;
break;
} else {
/* Store the location of the replacement */
/* Convert '0' to 0 */
tokens[tokcount] = replacement[i + 1] - '0';
tokenoffset[tokcount] = i;
tokcount++;
/* Skip the next char */
i++;
}
}
}
}
if (status) {
/* Everything went OK */
info->tokcount = tokcount;
info->tokens = tokens;
info->tokenoffset = tokenoffset;
info->pattern = TSstrdup(pattern);
info->replacement = TSstrdup(replacement);
*buf = info;
} else {
/* Something went wrong, clean up */
TSfree(tokens);
TSfree(tokenoffset);
if (info->re)
pcre_free(info->re);
TSfree(info);
}
return status;
}
static pr_list *
load_config_file(const char *config_file)
{
char buffer[1024];
std::string path;
TSFile fh;
pr_list *prl = new pr_list();
/* locations in a config file line, end of line, split start, split end */
char *eol, *spstart, *spend;
int lineno = 0;
int retval;
regex_info *info = 0;
if (config_file == NULL) {
/* Default config file of plugins/cacheurl.config */
path = TSPluginDirGet();
path += "/cacheurl.config";
} else if (*config_file != '/') {
// Relative paths are relative to the config directory
path = TSConfigDirGet();
path += "/";
path += config_file;
} else {
// Absolute path ...
path = config_file;
}
TSDebug(PLUGIN_NAME, "Opening config file: %s", path.c_str());
fh = TSfopen(path.c_str(), "r");
if (!fh) {
TSError("[%s] Unable to open %s. No patterns will be loaded\n", PLUGIN_NAME, path.c_str());
return prl;
}
while (TSfgets(fh, buffer, sizeof(buffer) - 1)) {
lineno++;
if (*buffer == '#') {
/* # Comments, only at line beginning */
continue;
}
eol = strstr(buffer, "\n");
if (eol) {
*eol = 0; /* Terminate string at newline */
} else {
/* Malformed line - skip */
continue;
}
/* Split line into two parts based on whitespace */
/* Find first whitespace */
spstart = strstr(buffer, " ");
if (!spstart) {
spstart = strstr(buffer, "\t");
}
if (!spstart) {
TSError("[%s] ERROR: Invalid format on line %d. Skipping\n", PLUGIN_NAME, lineno);
continue;
}
/* Find part of the line after any whitespace */
spend = spstart + 1;
while (*spend == ' ' || *spend == '\t') {
spend++;
}
if (*spend == 0) {
/* We reached the end of the string without any non-whitepace */
TSError("[%s] ERROR: Invalid format on line %d. Skipping\n", PLUGIN_NAME, lineno);
continue;
}
*spstart = 0;
/* We have the pattern/replacement, now do precompilation.
* buffer is the first part of the line. spend is the second part just
* after the whitespace */
TSDebug(PLUGIN_NAME, "Adding pattern/replacement pair: '%s' -> '%s'", buffer, spend);
retval = regex_compile(&info, buffer, spend);
if (!retval) {
TSError("[%s] Error precompiling regex/replacement. Skipping.\n", PLUGIN_NAME);
}
prl->pr.push_back(info);
}
TSfclose(fh);
TSDebug(PLUGIN_NAME, "loaded %u regexes", (unsigned) prl->pr.size());
return prl;
}
static int
rewrite_cacheurl(pr_list * prl, TSHttpTxn txnp)
{
int ok = 1;
char *newurl = 0;
int retval;
char *url;
int url_length;
url = TSHttpTxnEffectiveUrlStringGet(txnp, &url_length);
if (!url) {
TSError("[%s] couldn't retrieve request url\n", PLUGIN_NAME);
ok = 0;
}
if (ok) {
for (std::vector<regex_info*>::iterator info = prl->pr.begin(); info != prl->pr.end(); ++info) {
retval = regex_substitute(&newurl, url, *info);
if (retval) {
/* Successful match/substitution */
break;
}
}
if (newurl) {
TSDebug(PLUGIN_NAME, "Rewriting cache URL for %s to %s", url, newurl);
if (TSCacheUrlSet(txnp, newurl, strlen(newurl))
!= TS_SUCCESS) {
TSError("[%s] Unable to modify cache url from " "%s to %s\n", PLUGIN_NAME, url, newurl);
ok = 0;
}
}
}
/* Clean up */
if (url)
TSfree(url);
if (newurl)
TSfree(newurl);
return ok;
}
static int
handle_hook(TSCont contp, TSEvent event, void *edata)
{
TSHttpTxn txnp = (TSHttpTxn) edata;
pr_list *prl;
int ok = 1;
prl = (pr_list *) TSContDataGet(contp);
switch (event) {
case TS_EVENT_HTTP_READ_REQUEST_HDR:
ok = rewrite_cacheurl(prl, txnp);
TSHttpTxnReenable(txnp, TS_EVENT_HTTP_CONTINUE);
break;
default:
TSAssert(!"Unexpected event");
ok = 0;
break;
}
return ok;
}
/* Generic error message function for errors in plugin initialization */
static void
initialization_error(const char *msg)
{
TSError("[%s] %s\n", PLUGIN_NAME, msg);
TSError("[%s] Unable to initialize plugin (disabled).\n", PLUGIN_NAME);
}
TSReturnCode
TSRemapInit(TSRemapInterface * api_info, char *errbuf, int errbuf_size)
{
if (!api_info) {
strncpy(errbuf, "[tsremap_init] Invalid TSRemapInterface argument", errbuf_size - 1);
return TS_ERROR;
}
if (api_info->size < sizeof(TSRemapInterface)) {
strncpy(errbuf, "[tsremap_init] Incorrect size of TSRemapInterface structure", errbuf_size - 1);
return TS_ERROR;
}
if (api_info->tsremap_version < TSREMAP_VERSION) {
snprintf(errbuf, errbuf_size - 1, "[tsremap_init] Incorrect API version %ld.%ld",
api_info->tsremap_version >> 16, (api_info->tsremap_version & 0xffff));
return TS_ERROR;
}
TSDebug(PLUGIN_NAME, "remap plugin is successfully initialized");
return TS_SUCCESS;
}
TSReturnCode
TSRemapNewInstance(int argc, char *argv[], void **ih, char *errbuf ATS_UNUSED, int errbuf_size ATS_UNUSED)
{
*ih = load_config_file(argc > 2 ? argv[2] : NULL);
return TS_SUCCESS;
}
void
TSRemapDeleteInstance(void *ih)
{
pr_list *prl = (pr_list *) ih;
TSDebug(PLUGIN_NAME, "Deleting remap instance");
delete prl;
}
TSRemapStatus
TSRemapDoRemap(void *ih, TSHttpTxn rh, TSRemapRequestInfo * rri ATS_UNUSED)
{
int ok;
ok = rewrite_cacheurl((pr_list *) ih, rh);
if (ok) {
return TSREMAP_NO_REMAP;
} else {
return TSREMAP_ERROR;
}
}
void
TSPluginInit(int argc, const char *argv[])
{
TSPluginRegistrationInfo info;
TSCont contp;
pr_list *prl;
info.plugin_name = (char *) PLUGIN_NAME;
info.vendor_name = (char *) "Apache Software Foundation";
info.support_email = (char *) "dev@trafficserver.apache.org";
if (TSPluginRegister(TS_SDK_VERSION_3_0, &info) != TS_SUCCESS) {
initialization_error("Plugin registration failed.");
return;
}
prl = load_config_file(argc > 1 ? argv[1] : NULL);
contp = TSContCreate((TSEventFunc) handle_hook, NULL);
/* Store the pattern replacement list in the continuation */
TSContDataSet(contp, prl);
TSHttpHookAdd(TS_HTTP_READ_REQUEST_HDR_HOOK, contp);
}
<|endoftext|>
|
<commit_before>/**
* Copyright (c) 2014-present, Facebook, Inc.
* All rights reserved.
*
* This source code is licensed in accordance with the terms specified in
* the LICENSE file found in the root directory of this source tree.
*/
#include <sys/stat.h>
#include <rocksdb/db.h>
#include <rocksdb/env.h>
#include <rocksdb/options.h>
#include <osquery/filesystem/fileops.h>
#include <osquery/filesystem/filesystem.h>
#include <osquery/flags.h>
#include <osquery/logger.h>
#include <osquery/registry_factory.h>
#include <osquery/utils/conversions/tryto.h>
#include <plugins/database/rocksdb.h>
namespace fs = boost::filesystem;
namespace osquery {
/// Hidden flags created for internal stress testing.
HIDDEN_FLAG(int32, rocksdb_write_buffer, 16, "Max write buffer number");
HIDDEN_FLAG(int32, rocksdb_merge_number, 4, "Min write buffer number to merge");
HIDDEN_FLAG(int32, rocksdb_background_flushes, 4, "Max background flushes");
HIDDEN_FLAG(uint64, rocksdb_buffer_blocks, 256, "Write buffer blocks (4k)");
DECLARE_string(database_path);
/**
* @brief Track external systems marking the RocksDB database as corrupted.
*
* This can be set using the RocksDBDatabasePlugin's static methods.
* The two primary external systems are the RocksDB logger plugin and tests.
*/
std::atomic<bool> kRocksDBCorruptionIndicator{false};
/// Backing-storage provider for osquery internal/core.
REGISTER_INTERNAL(RocksDBDatabasePlugin, "database", "rocksdb");
void GlogRocksDBLogger::Logv(const char* format, va_list ap) {
// Convert RocksDB log to string and check if header or level-ed log.
std::string log_line;
{
char buffer[501] = {0};
vsnprintf(buffer, 500, format, ap);
va_end(ap);
if (buffer[0] != '[' || (buffer[1] != 'E' && buffer[1] != 'W')) {
return;
}
log_line = buffer;
}
// There is a spurious warning on first open.
if (log_line.find("Error when reading") == std::string::npos) {
// RocksDB calls are non-reentrant. Since this callback is made in the
// context of a RocksDB API call, turn log forwarding off to prevent the
// logger from trying to make a call back into RocksDB and causing a
// deadlock.
LOG(INFO) << "RocksDB: " << log_line;
}
// If the callback includes 'Corruption' then set the corruption indicator.
if (log_line.find("Corruption:") != std::string::npos) {
RocksDBDatabasePlugin::setCorrupted();
}
}
Status RocksDBDatabasePlugin::setUp() {
if (!DatabasePlugin::kDBAllowOpen) {
LOG(WARNING) << RLOG(1629) << "Not allowed to set up database plugin";
}
if (!initialized_) {
initialized_ = true;
options_.OptimizeForSmallDb();
// Set meta-data (mostly) handling options.
options_.create_if_missing = true;
options_.create_missing_column_families = true;
options_.info_log_level = rocksdb::ERROR_LEVEL;
options_.log_file_time_to_roll = 0;
options_.keep_log_file_num = 10;
options_.max_log_file_size = 1024 * 1024 * 1;
options_.max_open_files = 128;
options_.stats_dump_period_sec = 0;
options_.max_manifest_file_size = 1024 * 500;
// Performance and optimization settings.
// Use rocksdb::kZSTD to use ZSTD database compression
options_.compression = rocksdb::kNoCompression;
options_.compaction_style = rocksdb::kCompactionStyleLevel;
options_.arena_block_size = (4 * 1024);
options_.write_buffer_size = (4 * 1024) * FLAGS_rocksdb_buffer_blocks;
options_.max_write_buffer_number =
static_cast<int>(FLAGS_rocksdb_write_buffer);
options_.min_write_buffer_number_to_merge =
static_cast<int>(FLAGS_rocksdb_merge_number);
options_.max_background_flushes =
static_cast<int>(FLAGS_rocksdb_background_flushes);
// Create an environment to replace the default logger.
if (logger_ == nullptr) {
logger_ = std::make_shared<GlogRocksDBLogger>();
}
options_.info_log = logger_;
column_families_.push_back(rocksdb::ColumnFamilyDescriptor(
rocksdb::kDefaultColumnFamilyName, options_));
for (const auto& cf_name : kDomains) {
column_families_.push_back(
rocksdb::ColumnFamilyDescriptor(cf_name, options_));
}
}
// Consume the current settings.
// A configuration update may change them, but that does not affect state.
path_ = fs::path(FLAGS_database_path).make_preferred().string();
if (pathExists(path_).ok() && !isReadable(path_).ok()) {
return Status(1, "Cannot read RocksDB path: " + path_);
}
if (!DatabasePlugin::kDBChecking) {
VLOG(1) << "Opening RocksDB handle: " << path_;
}
// Tests may trash calls to setUp, make sure subsequent calls do not leak.
close();
// Attempt to create a RocksDB instance and handles.
auto s =
rocksdb::DB::Open(options_, path_, column_families_, &handles_, &db_);
if (s.IsCorruption()) {
// The database is corrupt - try to repair it
repairDB();
s = rocksdb::DB::Open(options_, path_, column_families_, &handles_, &db_);
}
if (!s.ok() || db_ == nullptr) {
LOG(INFO) << "Rocksdb open failed (" << s.code() << ":" << s.subcode()
<< ") " << s.ToString();
if (kDBRequireWrite) {
// A failed open in R/W mode is a runtime error.
return Status(1, s.ToString());
}
if (!DatabasePlugin::kDBChecking) {
LOG(INFO) << "Opening RocksDB failed: Continuing with read-only support";
}
// Also disable event publishers.
Flag::updateValue("disable_events", "true");
read_only_ = true;
}
// RocksDB may not create/append a directory with acceptable permissions.
if (!read_only_ && platformSetSafeDbPerms(path_) == false) {
return Status(1, "Cannot set permissions on RocksDB path: " + path_);
}
return Status(0);
}
void RocksDBDatabasePlugin::tearDown() {
close();
}
void RocksDBDatabasePlugin::close() {
WriteLock lock(close_mutex_);
for (auto handle : handles_) {
delete handle;
}
handles_.clear();
if (db_ != nullptr) {
delete db_;
db_ = nullptr;
}
if (isCorrupted()) {
repairDB();
setCorrupted(false);
}
}
bool RocksDBDatabasePlugin::isCorrupted() {
return kRocksDBCorruptionIndicator;
}
void RocksDBDatabasePlugin::setCorrupted(bool corrupted) {
kRocksDBCorruptionIndicator = corrupted;
}
void RocksDBDatabasePlugin::repairDB() {
// Try to backup the existing database.
auto bpath = path_ + ".backup";
if (pathExists(bpath).ok()) {
if (!removePath(bpath).ok()) {
LOG(ERROR) << "Cannot remove previous RocksDB database backup: " << bpath;
return;
} else {
LOG(WARNING) << "Removed previous RocksDB database backup: " << bpath;
}
}
if (movePath(path_, bpath).ok()) {
LOG(WARNING) << "Backing up RocksDB database: " << bpath;
} else {
LOG(ERROR) << "Cannot backup the RocksDB database: " << bpath;
return;
}
// ROCKSDB_LITE does not have a RepairDB method.
LOG(WARNING) << "Destroying RocksDB database due to corruption";
}
rocksdb::DB* RocksDBDatabasePlugin::getDB() const {
return db_;
}
rocksdb::ColumnFamilyHandle* RocksDBDatabasePlugin::getHandleForColumnFamily(
const std::string& cf) const {
size_t i = std::find(kDomains.begin(), kDomains.end(), cf) - kDomains.begin();
if (i != kDomains.size()) {
return handles_[i];
} else {
return nullptr;
}
}
Status RocksDBDatabasePlugin::get(const std::string& domain,
const std::string& key,
std::string& value) const {
if (getDB() == nullptr) {
return Status(1, "Database not opened");
}
auto cfh = getHandleForColumnFamily(domain);
if (cfh == nullptr) {
return Status(1, "Could not get column family for " + domain);
}
auto s = getDB()->Get(rocksdb::ReadOptions(), cfh, key, &value);
return Status(s.code(), s.ToString());
}
Status RocksDBDatabasePlugin::get(const std::string& domain,
const std::string& key,
int& value) const {
std::string result;
auto s = this->get(domain, key, result);
if (s.ok()) {
auto expectedValue = tryTo<int>(result);
if (expectedValue.isError()) {
return Status::failure("Could not deserialize str to int");
} else {
value = expectedValue.take();
}
}
return s;
}
Status RocksDBDatabasePlugin::put(const std::string& domain,
const std::string& key,
const std::string& value) {
return putBatch(domain, {std::make_pair(key, value)});
}
Status RocksDBDatabasePlugin::putBatch(const std::string& domain,
const DatabaseStringValueList& data) {
if (read_only_) {
return Status::success();
}
auto cfh = getHandleForColumnFamily(domain);
if (cfh == nullptr) {
return Status(1, "Could not get column family for " + domain);
}
// Events should be fast, and do not need to force syncs.
auto options = rocksdb::WriteOptions();
if (kEvents == domain) {
options.disableWAL = true;
} else {
options.sync = true;
}
rocksdb::WriteBatch batch;
for (const auto& p : data) {
const auto& key = p.first;
const auto& value = p.second;
batch.Put(cfh, key, value);
}
auto s = getDB()->Write(options, &batch);
if (s.code() != 0 && s.IsIOError()) {
// An error occurred, check if it is an IO error and remove the offending
// specific filename or log name.
std::string error_string = s.ToString();
size_t error_pos = error_string.find_last_of(":");
if (error_pos != std::string::npos) {
return Status(s.code(), "IOError: " + error_string.substr(error_pos + 2));
}
}
return Status(s.code(), s.ToString());
}
Status RocksDBDatabasePlugin::put(const std::string& domain,
const std::string& key,
int value) {
return putBatch(domain, {std::make_pair(key, std::to_string(value))});
}
void RocksDBDatabasePlugin::dumpDatabase() const {}
Status RocksDBDatabasePlugin::remove(const std::string& domain,
const std::string& key) {
if (read_only_) {
return Status::success();
}
auto cfh = getHandleForColumnFamily(domain);
if (cfh == nullptr) {
return Status(1, "Could not get column family for " + domain);
}
auto options = rocksdb::WriteOptions();
// We could sync here, but large deletes will cause multi-syncs.
// For example: event record expirations found in an expired index.
if (kEvents != domain) {
options.sync = true;
}
auto s = getDB()->Delete(options, cfh, key);
return Status(s.code(), s.ToString());
}
Status RocksDBDatabasePlugin::removeRange(const std::string& domain,
const std::string& low,
const std::string& high) {
if (read_only_) {
return Status::success();
}
auto cfh = getHandleForColumnFamily(domain);
if (cfh == nullptr) {
return Status(1, "Could not get column family for " + domain);
}
auto options = rocksdb::WriteOptions();
// We could sync here, but large deletes will cause multi-syncs.
// For example: event record expirations found in an expired index.
if (kEvents != domain) {
options.sync = true;
}
auto s = getDB()->DeleteRange(options, cfh, low, high);
if (low <= high) {
s = getDB()->Delete(options, cfh, high);
}
return Status(s.code(), s.ToString());
}
Status RocksDBDatabasePlugin::scan(const std::string& domain,
std::vector<std::string>& results,
const std::string& prefix,
size_t max) const {
if (getDB() == nullptr) {
return Status(1, "Database not opened");
}
auto cfh = getHandleForColumnFamily(domain);
if (cfh == nullptr) {
return Status(1, "Could not get column family for " + domain);
}
auto options = rocksdb::ReadOptions();
options.verify_checksums = false;
options.fill_cache = false;
auto it = getDB()->NewIterator(options, cfh);
if (it == nullptr) {
return Status(1, "Could not get iterator for " + domain);
}
size_t count = 0;
for (it->SeekToFirst(); it->Valid(); it->Next()) {
auto key = it->key().ToString();
if (key.find(prefix) == 0) {
results.push_back(std::move(key));
if (max > 0 && ++count >= max) {
break;
}
}
}
delete it;
return Status::success();
}
} // namespace osquery
<commit_msg>rocksdb: Remove use of OptimizeForSmallDB in rocksdb plugin (#5797)<commit_after>/**
* Copyright (c) 2014-present, Facebook, Inc.
* All rights reserved.
*
* This source code is licensed in accordance with the terms specified in
* the LICENSE file found in the root directory of this source tree.
*/
#include <sys/stat.h>
#include <rocksdb/db.h>
#include <rocksdb/env.h>
#include <rocksdb/options.h>
#include <osquery/filesystem/fileops.h>
#include <osquery/filesystem/filesystem.h>
#include <osquery/flags.h>
#include <osquery/logger.h>
#include <osquery/registry_factory.h>
#include <osquery/utils/conversions/tryto.h>
#include <plugins/database/rocksdb.h>
namespace fs = boost::filesystem;
namespace osquery {
/// Hidden flags created for internal stress testing.
HIDDEN_FLAG(int32, rocksdb_write_buffer, 16, "Max write buffer number");
HIDDEN_FLAG(int32, rocksdb_merge_number, 4, "Min write buffer number to merge");
HIDDEN_FLAG(int32, rocksdb_background_flushes, 4, "Max background flushes");
HIDDEN_FLAG(uint64, rocksdb_buffer_blocks, 256, "Write buffer blocks (4k)");
DECLARE_string(database_path);
/**
* @brief Track external systems marking the RocksDB database as corrupted.
*
* This can be set using the RocksDBDatabasePlugin's static methods.
* The two primary external systems are the RocksDB logger plugin and tests.
*/
std::atomic<bool> kRocksDBCorruptionIndicator{false};
/// Backing-storage provider for osquery internal/core.
REGISTER_INTERNAL(RocksDBDatabasePlugin, "database", "rocksdb");
void GlogRocksDBLogger::Logv(const char* format, va_list ap) {
// Convert RocksDB log to string and check if header or level-ed log.
std::string log_line;
{
char buffer[501] = {0};
vsnprintf(buffer, 500, format, ap);
va_end(ap);
if (buffer[0] != '[' || (buffer[1] != 'E' && buffer[1] != 'W')) {
return;
}
log_line = buffer;
}
// There is a spurious warning on first open.
if (log_line.find("Error when reading") == std::string::npos) {
// RocksDB calls are non-reentrant. Since this callback is made in the
// context of a RocksDB API call, turn log forwarding off to prevent the
// logger from trying to make a call back into RocksDB and causing a
// deadlock.
LOG(INFO) << "RocksDB: " << log_line;
}
// If the callback includes 'Corruption' then set the corruption indicator.
if (log_line.find("Corruption:") != std::string::npos) {
RocksDBDatabasePlugin::setCorrupted();
}
}
Status RocksDBDatabasePlugin::setUp() {
if (!DatabasePlugin::kDBAllowOpen) {
LOG(WARNING) << RLOG(1629) << "Not allowed to set up database plugin";
}
if (!initialized_) {
initialized_ = true;
// Set meta-data (mostly) handling options.
options_.create_if_missing = true;
options_.create_missing_column_families = true;
options_.info_log_level = rocksdb::ERROR_LEVEL;
options_.log_file_time_to_roll = 0;
options_.keep_log_file_num = 10;
options_.max_log_file_size = 1024 * 1024 * 1;
options_.max_open_files = 128;
options_.stats_dump_period_sec = 0;
options_.max_manifest_file_size = 1024 * 500;
// Performance and optimization settings.
// Use rocksdb::kZSTD to use ZSTD database compression
options_.compression = rocksdb::kNoCompression;
options_.compaction_style = rocksdb::kCompactionStyleLevel;
options_.arena_block_size = (4 * 1024);
options_.write_buffer_size = (4 * 1024) * FLAGS_rocksdb_buffer_blocks;
options_.max_write_buffer_number =
static_cast<int>(FLAGS_rocksdb_write_buffer);
options_.min_write_buffer_number_to_merge =
static_cast<int>(FLAGS_rocksdb_merge_number);
options_.max_background_flushes =
static_cast<int>(FLAGS_rocksdb_background_flushes);
// Create an environment to replace the default logger.
if (logger_ == nullptr) {
logger_ = std::make_shared<GlogRocksDBLogger>();
}
options_.info_log = logger_;
column_families_.push_back(rocksdb::ColumnFamilyDescriptor(
rocksdb::kDefaultColumnFamilyName, options_));
for (const auto& cf_name : kDomains) {
column_families_.push_back(
rocksdb::ColumnFamilyDescriptor(cf_name, options_));
}
}
// Consume the current settings.
// A configuration update may change them, but that does not affect state.
path_ = fs::path(FLAGS_database_path).make_preferred().string();
if (pathExists(path_).ok() && !isReadable(path_).ok()) {
return Status(1, "Cannot read RocksDB path: " + path_);
}
if (!DatabasePlugin::kDBChecking) {
VLOG(1) << "Opening RocksDB handle: " << path_;
}
// Tests may trash calls to setUp, make sure subsequent calls do not leak.
close();
// Attempt to create a RocksDB instance and handles.
auto s =
rocksdb::DB::Open(options_, path_, column_families_, &handles_, &db_);
if (s.IsCorruption()) {
// The database is corrupt - try to repair it
repairDB();
s = rocksdb::DB::Open(options_, path_, column_families_, &handles_, &db_);
}
if (!s.ok() || db_ == nullptr) {
LOG(INFO) << "Rocksdb open failed (" << s.code() << ":" << s.subcode()
<< ") " << s.ToString();
if (kDBRequireWrite) {
// A failed open in R/W mode is a runtime error.
return Status(1, s.ToString());
}
if (!DatabasePlugin::kDBChecking) {
LOG(INFO) << "Opening RocksDB failed: Continuing with read-only support";
}
// Also disable event publishers.
Flag::updateValue("disable_events", "true");
read_only_ = true;
}
// RocksDB may not create/append a directory with acceptable permissions.
if (!read_only_ && platformSetSafeDbPerms(path_) == false) {
return Status(1, "Cannot set permissions on RocksDB path: " + path_);
}
return Status(0);
}
void RocksDBDatabasePlugin::tearDown() {
close();
}
void RocksDBDatabasePlugin::close() {
WriteLock lock(close_mutex_);
for (auto handle : handles_) {
delete handle;
}
handles_.clear();
if (db_ != nullptr) {
delete db_;
db_ = nullptr;
}
if (isCorrupted()) {
repairDB();
setCorrupted(false);
}
}
bool RocksDBDatabasePlugin::isCorrupted() {
return kRocksDBCorruptionIndicator;
}
void RocksDBDatabasePlugin::setCorrupted(bool corrupted) {
kRocksDBCorruptionIndicator = corrupted;
}
void RocksDBDatabasePlugin::repairDB() {
// Try to backup the existing database.
auto bpath = path_ + ".backup";
if (pathExists(bpath).ok()) {
if (!removePath(bpath).ok()) {
LOG(ERROR) << "Cannot remove previous RocksDB database backup: " << bpath;
return;
} else {
LOG(WARNING) << "Removed previous RocksDB database backup: " << bpath;
}
}
if (movePath(path_, bpath).ok()) {
LOG(WARNING) << "Backing up RocksDB database: " << bpath;
} else {
LOG(ERROR) << "Cannot backup the RocksDB database: " << bpath;
return;
}
// ROCKSDB_LITE does not have a RepairDB method.
LOG(WARNING) << "Destroying RocksDB database due to corruption";
}
rocksdb::DB* RocksDBDatabasePlugin::getDB() const {
return db_;
}
rocksdb::ColumnFamilyHandle* RocksDBDatabasePlugin::getHandleForColumnFamily(
const std::string& cf) const {
size_t i = std::find(kDomains.begin(), kDomains.end(), cf) - kDomains.begin();
if (i != kDomains.size()) {
return handles_[i];
} else {
return nullptr;
}
}
Status RocksDBDatabasePlugin::get(const std::string& domain,
const std::string& key,
std::string& value) const {
if (getDB() == nullptr) {
return Status(1, "Database not opened");
}
auto cfh = getHandleForColumnFamily(domain);
if (cfh == nullptr) {
return Status(1, "Could not get column family for " + domain);
}
auto s = getDB()->Get(rocksdb::ReadOptions(), cfh, key, &value);
return Status(s.code(), s.ToString());
}
Status RocksDBDatabasePlugin::get(const std::string& domain,
const std::string& key,
int& value) const {
std::string result;
auto s = this->get(domain, key, result);
if (s.ok()) {
auto expectedValue = tryTo<int>(result);
if (expectedValue.isError()) {
return Status::failure("Could not deserialize str to int");
} else {
value = expectedValue.take();
}
}
return s;
}
Status RocksDBDatabasePlugin::put(const std::string& domain,
const std::string& key,
const std::string& value) {
return putBatch(domain, {std::make_pair(key, value)});
}
Status RocksDBDatabasePlugin::putBatch(const std::string& domain,
const DatabaseStringValueList& data) {
if (read_only_) {
return Status::success();
}
auto cfh = getHandleForColumnFamily(domain);
if (cfh == nullptr) {
return Status(1, "Could not get column family for " + domain);
}
// Events should be fast, and do not need to force syncs.
auto options = rocksdb::WriteOptions();
if (kEvents == domain) {
options.disableWAL = true;
} else {
options.sync = true;
}
rocksdb::WriteBatch batch;
for (const auto& p : data) {
const auto& key = p.first;
const auto& value = p.second;
batch.Put(cfh, key, value);
}
auto s = getDB()->Write(options, &batch);
if (s.code() != 0 && s.IsIOError()) {
// An error occurred, check if it is an IO error and remove the offending
// specific filename or log name.
std::string error_string = s.ToString();
size_t error_pos = error_string.find_last_of(":");
if (error_pos != std::string::npos) {
return Status(s.code(), "IOError: " + error_string.substr(error_pos + 2));
}
}
return Status(s.code(), s.ToString());
}
Status RocksDBDatabasePlugin::put(const std::string& domain,
const std::string& key,
int value) {
return putBatch(domain, {std::make_pair(key, std::to_string(value))});
}
void RocksDBDatabasePlugin::dumpDatabase() const {}
Status RocksDBDatabasePlugin::remove(const std::string& domain,
const std::string& key) {
if (read_only_) {
return Status::success();
}
auto cfh = getHandleForColumnFamily(domain);
if (cfh == nullptr) {
return Status(1, "Could not get column family for " + domain);
}
auto options = rocksdb::WriteOptions();
// We could sync here, but large deletes will cause multi-syncs.
// For example: event record expirations found in an expired index.
if (kEvents != domain) {
options.sync = true;
}
auto s = getDB()->Delete(options, cfh, key);
return Status(s.code(), s.ToString());
}
Status RocksDBDatabasePlugin::removeRange(const std::string& domain,
const std::string& low,
const std::string& high) {
if (read_only_) {
return Status::success();
}
auto cfh = getHandleForColumnFamily(domain);
if (cfh == nullptr) {
return Status(1, "Could not get column family for " + domain);
}
auto options = rocksdb::WriteOptions();
// We could sync here, but large deletes will cause multi-syncs.
// For example: event record expirations found in an expired index.
if (kEvents != domain) {
options.sync = true;
}
auto s = getDB()->DeleteRange(options, cfh, low, high);
if (low <= high) {
s = getDB()->Delete(options, cfh, high);
}
return Status(s.code(), s.ToString());
}
Status RocksDBDatabasePlugin::scan(const std::string& domain,
std::vector<std::string>& results,
const std::string& prefix,
size_t max) const {
if (getDB() == nullptr) {
return Status(1, "Database not opened");
}
auto cfh = getHandleForColumnFamily(domain);
if (cfh == nullptr) {
return Status(1, "Could not get column family for " + domain);
}
auto options = rocksdb::ReadOptions();
options.verify_checksums = false;
options.fill_cache = false;
auto it = getDB()->NewIterator(options, cfh);
if (it == nullptr) {
return Status(1, "Could not get iterator for " + domain);
}
size_t count = 0;
for (it->SeekToFirst(); it->Valid(); it->Next()) {
auto key = it->key().ToString();
if (key.find(prefix) == 0) {
results.push_back(std::move(key));
if (max > 0 && ++count >= max) {
break;
}
}
}
delete it;
return Status::success();
}
} // namespace osquery
<|endoftext|>
|
<commit_before><commit_msg>fixed a bug with produced items<commit_after><|endoftext|>
|
<commit_before>/* IBM_PROLOG_BEGIN_TAG */
/* This is an automatically generated prolog. */
/* */
/* $Source: src/import/chips/p9/procedures/hwp/memory/p9_mss_draminit_mc.C $ */
/* */
/* OpenPOWER HostBoot Project */
/* */
/* Contributors Listed Below - COPYRIGHT 2015,2019 */
/* [+] International Business Machines Corp. */
/* */
/* */
/* Licensed under the Apache License, Version 2.0 (the "License"); */
/* you may not use this file except in compliance with the License. */
/* You may obtain a copy of the License at */
/* */
/* http://www.apache.org/licenses/LICENSE-2.0 */
/* */
/* Unless required by applicable law or agreed to in writing, software */
/* distributed under the License is distributed on an "AS IS" BASIS, */
/* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or */
/* implied. See the License for the specific language governing */
/* permissions and limitations under the License. */
/* */
/* IBM_PROLOG_END_TAG */
///
/// @file p9_mss_draminit_mc.C
/// @brief Initialize the memory controller to take over the DRAM
///
// *HWP HWP Owner: Brian Silver <bsilver@us.ibm.com>
// *HWP HWP Backup: Andre Marin <aamarin@us.ibm.com>
// *HWP FW Owner: Brian Silver <bsilver@us.ibm.com>
// *HWP Team: Memory
// *HWP Level: 1
// *HWP Consumed by: FSP:HB
#include <fapi2.H>
using fapi2::TARGET_TYPE_MCBIST;
extern "C"
{
///
/// @brief Initialize the MC now that DRAM is up
/// @param[in] i_target, the McBIST of the ports of the dram you're training
/// @return FAPI2_RC_SUCCESS iff ok
///
fapi2::ReturnCode p9_mss_draminit_mc( const fapi2::Target<TARGET_TYPE_MCBIST>& i_target )
{
FAPI_INF("Start draminit MC");
FAPI_INF("End draminit MC");
return fapi2::FAPI2_RC_SUCCESS;
}
}
<commit_msg>Include .H files in their respective C files to avoid compilation error<commit_after>/* IBM_PROLOG_BEGIN_TAG */
/* This is an automatically generated prolog. */
/* */
/* $Source: src/import/chips/p9/procedures/hwp/memory/p9_mss_draminit_mc.C $ */
/* */
/* OpenPOWER HostBoot Project */
/* */
/* Contributors Listed Below - COPYRIGHT 2015,2019 */
/* [+] International Business Machines Corp. */
/* */
/* */
/* Licensed under the Apache License, Version 2.0 (the "License"); */
/* you may not use this file except in compliance with the License. */
/* You may obtain a copy of the License at */
/* */
/* http://www.apache.org/licenses/LICENSE-2.0 */
/* */
/* Unless required by applicable law or agreed to in writing, software */
/* distributed under the License is distributed on an "AS IS" BASIS, */
/* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or */
/* implied. See the License for the specific language governing */
/* permissions and limitations under the License. */
/* */
/* IBM_PROLOG_END_TAG */
///
/// @file p9_mss_draminit_mc.C
/// @brief Initialize the memory controller to take over the DRAM
///
// *HWP HWP Owner: Brian Silver <bsilver@us.ibm.com>
// *HWP HWP Backup: Andre Marin <aamarin@us.ibm.com>
// *HWP FW Owner: Brian Silver <bsilver@us.ibm.com>
// *HWP Team: Memory
// *HWP Level: 1
// *HWP Consumed by: FSP:HB
#include <fapi2.H>
#include "p9_mss_draminit_mc.H"
using fapi2::TARGET_TYPE_MCBIST;
extern "C"
{
///
/// @brief Initialize the MC now that DRAM is up
/// @param[in] i_target, the McBIST of the ports of the dram you're training
/// @return FAPI2_RC_SUCCESS iff ok
///
fapi2::ReturnCode p9_mss_draminit_mc( const fapi2::Target<TARGET_TYPE_MCBIST>& i_target )
{
FAPI_INF("Start draminit MC");
FAPI_INF("End draminit MC");
return fapi2::FAPI2_RC_SUCCESS;
}
}
<|endoftext|>
|
<commit_before>/* IBM_PROLOG_BEGIN_TAG */
/* This is an automatically generated prolog. */
/* */
/* $Source: src/import/generic/memory/lib/spd/rdimm/ddr4/rdimm_raw_cards.C $ */
/* */
/* OpenPOWER HostBoot Project */
/* */
/* Contributors Listed Below - COPYRIGHT 2016,2019 */
/* [+] International Business Machines Corp. */
/* */
/* */
/* Licensed under the Apache License, Version 2.0 (the "License"); */
/* you may not use this file except in compliance with the License. */
/* You may obtain a copy of the License at */
/* */
/* http://www.apache.org/licenses/LICENSE-2.0 */
/* */
/* Unless required by applicable law or agreed to in writing, software */
/* distributed under the License is distributed on an "AS IS" BASIS, */
/* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or */
/* implied. See the License for the specific language governing */
/* permissions and limitations under the License. */
/* */
/* IBM_PROLOG_END_TAG */
///
/// @file raw_cards.C
/// @brief RDIMM raw card data structure
/// Contains RCW settings per raw card rev
///
// *HWP HWP Owner: Andre Marin <aamarin@us.ibm.com>
// *HWP HWP Backup: Jacob Harvey <jlharvey@us.ibm.com>
// *HWP Team: Memory
// *HWP Level: 3
// *HWP Consumed by: FSP:HB
// std lib
#include <vector>
// fapi2
#include <fapi2.H>
// mss lib
#include <generic/memory/lib/spd/rdimm/ddr4/rdimm_raw_cards.H>
namespace mss
{
///
/// @brief raw card A1 settings
///
rcw_settings rdimm_rc_a1( 0x02, // RC00
0x00, // RC01
0x0F, // RC06_07
0x0C, // RC09
0x0E, // RC0B
0x00, // RC0C
0x00, // RC0F
0x00, // RC1X
0x00, // RC2X
0x00, // RC4X
0x00, // RC5X
0x00, // RC6X
0x00, // RC8X
0x00, // RC9X
0x00); // RCAX
///
/// @brief raw card B1 settings
/// @note need to verify, copy from b2, need to verify with b1 annex
///
rcw_settings rdimm_rc_b1( 0x02, // RC00
0x00, // RC01
0x0F, // RC06_07
0x0C, // RC09 Could be set in eff_config for CKE power DOWN mode
0x0E, // RC0B
0x00, // RC0C
0x00, // RC0F
0x00, // RC1X
0x00, // RC2X
0x00, // RC4X
0x00, // RC5X
0x00, // RC6X
0x00, // RC8X
0x00, // RC9X
0x00);// RCAX
///
/// @brief raw card B2 settings
///
rcw_settings rdimm_rc_b2( 0x02, // RC00
0x00, // RC01
0x0F, // RC06_07
0x0C, // RC09
0x0E, // RC0B
0x00, // RC0C
0x00, // RC0F
0x00, // RC1X
0x00, // RC2X
0x00, // RC4X
0x00, // RC5X
0x00, // RC6X
0x00, // RC8X
0x00, // RC9X
0x00);// RCAX
///
/// @brief raw card C1 settings
///
rcw_settings rdimm_rc_c1( 0x02, // RC00
0x0C, // RC01
0x0F, // RC06_07
0x0C, // RC09
0x0E, // RC0B
0x00, // RC0C
0x00, // RC0F
0x00, // RC1X
0x00, // RC2X
0x00, // RC4X
0x00, // RC5X
0x00, // RC6X
0x00, // RC8X
0x00, // RC9X
0x00); // RCAX
///
/// @brief raw card C2 settings
/// @note same settings as C1
///
rcw_settings rdimm_rc_c2( 0x02, // RC00
0x0C, // RC01
0x0F, // RC06_07
0x0C, // RC09
0x0E, // RC0B
0x00, // RC0C
0x00, // RC0F
0x00, // RC1X
0x00, // RC2X
0x00, // RC4X
0x00, // RC5X
0x00, // RC6X
0x00, // RC8X
0x00, // RC9X
0x00); // RCAX
////
/// @brief raw card for custom dimms
///
rcw_settings rdimm_rc_custom ( 0x02, // RC00
0x00, // RC01
0x0F, // RC06_07
0x0C, // RC09
0x0E, // RC0B
0x00, // RC0C
0x00, // RC0F
0x00, // RC1X
0x00, // RC2X
0x00, // RC4X
0x00, // RC5X
0x00, // RC6X
0x00, // RC8X
0x00, // RC9X
0x00);// RCAX
////
/// @brief raw card for NVDIMMs
///
rcw_settings rdimm_rc_nvdimm ( 0x00, // RC00
0x00, // RC01
0x0F, // RC06_07
0x00, // RC09
0x0E, // RC0B
0x00, // RC0C
0x00, // RC0F
0x00, // RC1X
0x00, // RC2X
0x00, // RC4X
0x00, // RC5X
0x00, // RC6X
0x00, // RC8X
0x00, // RC9X
0x00); // RCAX
///
/// @brief raw card VBU settings
///
rcw_settings rdimm_rc_vbu( 0x02, // RC00
0x00, // RC01
0x0F, // RC06_07
0x0C, // RC09
0x0E, // RC0B
0x00, // RC0C
0x00, // RC0F
0x00, // RC1X
0x00, // RC2X
0x00, // RC4X
0x00, // RC5X
0x00, // RC6X
0x00, // RC8X
0x00, // RC9X
0x00); // RCAX
namespace rdimm
{
const std::vector< std::pair< uint8_t , rcw_settings> > RAW_CARDS =
{
// I expect this to grow as Warren M. expects us to have
// settings for every raw card that JEDEC puts out. Openpower
// can't break due to a missing raw card...
// Note: This list needs to be kept in numerical order of the raw_card_rev
{raw_card_rev::NVDIMM, rdimm_rc_nvdimm},
{raw_card_rev::A1, rdimm_rc_a1},
{raw_card_rev::B1, rdimm_rc_b1},
{raw_card_rev::C1, rdimm_rc_c1},
{raw_card_rev::VBU, rdimm_rc_vbu},
{raw_card_rev::B2, rdimm_rc_b2},
{raw_card_rev::C2, rdimm_rc_c2},
{raw_card_rev::CUSTOM, rdimm_rc_custom},
};
}// rdimm
}// mss
<commit_msg>Updates RCD power settings<commit_after>/* IBM_PROLOG_BEGIN_TAG */
/* This is an automatically generated prolog. */
/* */
/* $Source: src/import/generic/memory/lib/spd/rdimm/ddr4/rdimm_raw_cards.C $ */
/* */
/* OpenPOWER HostBoot Project */
/* */
/* Contributors Listed Below - COPYRIGHT 2016,2019 */
/* [+] International Business Machines Corp. */
/* */
/* */
/* Licensed under the Apache License, Version 2.0 (the "License"); */
/* you may not use this file except in compliance with the License. */
/* You may obtain a copy of the License at */
/* */
/* http://www.apache.org/licenses/LICENSE-2.0 */
/* */
/* Unless required by applicable law or agreed to in writing, software */
/* distributed under the License is distributed on an "AS IS" BASIS, */
/* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or */
/* implied. See the License for the specific language governing */
/* permissions and limitations under the License. */
/* */
/* IBM_PROLOG_END_TAG */
///
/// @file raw_cards.C
/// @brief RDIMM raw card data structure
/// Contains RCW settings per raw card rev
///
// *HWP HWP Owner: Andre Marin <aamarin@us.ibm.com>
// *HWP HWP Backup: Jacob Harvey <jlharvey@us.ibm.com>
// *HWP Team: Memory
// *HWP Level: 3
// *HWP Consumed by: FSP:HB
// std lib
#include <vector>
// fapi2
#include <fapi2.H>
// mss lib
#include <generic/memory/lib/spd/rdimm/ddr4/rdimm_raw_cards.H>
namespace mss
{
///
/// @brief raw card A1 settings
///
rcw_settings rdimm_rc_a1( 0x02, // RC00
0x00, // RC01
0x0F, // RC06_07
0x0C, // RC09
0x0E, // RC0B
0x00, // RC0C
0x00, // RC0F
0x00, // RC1X
0x00, // RC2X
0x00, // RC4X
0x00, // RC5X
0x00, // RC6X
0x00, // RC8X
0x00, // RC9X
0x00); // RCAX
///
/// @brief raw card B1 settings
/// @note need to verify, copy from b2, need to verify with b1 annex
///
rcw_settings rdimm_rc_b1( 0x02, // RC00
0x00, // RC01
0x0F, // RC06_07
0x0C, // RC09 Could be set in eff_config for CKE power DOWN mode
0x0E, // RC0B
0x00, // RC0C
0x00, // RC0F
0x00, // RC1X
0x00, // RC2X
0x00, // RC4X
0x00, // RC5X
0x00, // RC6X
0x00, // RC8X
0x00, // RC9X
0x00);// RCAX
///
/// @brief raw card B2 settings
///
rcw_settings rdimm_rc_b2( 0x02, // RC00
0x00, // RC01
0x0F, // RC06_07
0x0C, // RC09
0x0E, // RC0B
0x00, // RC0C
0x00, // RC0F
0x00, // RC1X
0x00, // RC2X
0x00, // RC4X
0x00, // RC5X
0x00, // RC6X
0x00, // RC8X
0x00, // RC9X
0x00);// RCAX
///
/// @brief raw card C1 settings
///
rcw_settings rdimm_rc_c1( 0x02, // RC00
0x0C, // RC01
0x0F, // RC06_07
0x0C, // RC09
0x0E, // RC0B
0x00, // RC0C
0x00, // RC0F
0x00, // RC1X
0x00, // RC2X
0x00, // RC4X
0x00, // RC5X
0x00, // RC6X
0x00, // RC8X
0x00, // RC9X
0x00); // RCAX
///
/// @brief raw card C2 settings
/// @note same settings as C1
///
rcw_settings rdimm_rc_c2( 0x02, // RC00
0x0C, // RC01
0x0F, // RC06_07
0x0C, // RC09
0x0E, // RC0B
0x00, // RC0C
0x00, // RC0F
0x00, // RC1X
0x00, // RC2X
0x00, // RC4X
0x00, // RC5X
0x00, // RC6X
0x00, // RC8X
0x00, // RC9X
0x00); // RCAX
////
/// @brief raw card for custom dimms
///
rcw_settings rdimm_rc_custom ( 0x02, // RC00
0x00, // RC01
0x0F, // RC06_07
0x0C, // RC09
0x0E, // RC0B
0x00, // RC0C
0x00, // RC0F
0x00, // RC1X
0x00, // RC2X
0x00, // RC4X
0x00, // RC5X
0x00, // RC6X
0x00, // RC8X
0x00, // RC9X
0x00);// RCAX
////
/// @brief raw card for NVDIMMs
///
rcw_settings rdimm_rc_nvdimm ( 0x00, // RC00
0x00, // RC01
0x0F, // RC06_07
0x0C, // RC09
0x0E, // RC0B
0x00, // RC0C
0x00, // RC0F
0x00, // RC1X
0x00, // RC2X
0x00, // RC4X
0x00, // RC5X
0x00, // RC6X
0x00, // RC8X
0x00, // RC9X
0x00); // RCAX
///
/// @brief raw card VBU settings
///
rcw_settings rdimm_rc_vbu( 0x02, // RC00
0x00, // RC01
0x0F, // RC06_07
0x0C, // RC09
0x0E, // RC0B
0x00, // RC0C
0x00, // RC0F
0x00, // RC1X
0x00, // RC2X
0x00, // RC4X
0x00, // RC5X
0x00, // RC6X
0x00, // RC8X
0x00, // RC9X
0x00); // RCAX
namespace rdimm
{
const std::vector< std::pair< uint8_t , rcw_settings> > RAW_CARDS =
{
// I expect this to grow as Warren M. expects us to have
// settings for every raw card that JEDEC puts out. Openpower
// can't break due to a missing raw card...
// Note: This list needs to be kept in numerical order of the raw_card_rev
{raw_card_rev::NVDIMM, rdimm_rc_nvdimm},
{raw_card_rev::A1, rdimm_rc_a1},
{raw_card_rev::B1, rdimm_rc_b1},
{raw_card_rev::C1, rdimm_rc_c1},
{raw_card_rev::VBU, rdimm_rc_vbu},
{raw_card_rev::B2, rdimm_rc_b2},
{raw_card_rev::C2, rdimm_rc_c2},
{raw_card_rev::CUSTOM, rdimm_rc_custom},
};
}// rdimm
}// mss
<|endoftext|>
|
<commit_before>using namespace GeFiCa;
// draw V, E distributions saved in an input ROOT file
void drawFields(const char *input="ppc.root")
{
// Get data from input file
TFile *file = new TFile(input, "update"); // "update" allows creation of TH3
PointContactDZ *detector = (PointContactDZ*) file->Get("pcdz");
TTree *t = detector->GetTree(true);
const int n = t->GetEntries();
// fine tune margins, etc.
gStyle->SetTitleOffset(0.6,"Y");
gStyle->SetPadRightMargin(0.12);
gStyle->SetPadLeftMargin(0.07);
// generate plots
TCanvas *cv = new TCanvas;
//cv->SetLogz();
t->Draw("c1:c2:v","","goff");
TGraph2D *gv = new TGraph2D(n, t->GetV1(), t->GetV2(), t->GetV3());
gv->SetName("gv"); gv->SetNpx(500); gv->SetNpy(500); // fine bin histogram
TH2D *hv = gv->GetHistogram();
hv->SetTitle(";Radius [cm];Height [cm];Potential [V]");
hv->GetZaxis()->CenterTitle();
hv->Draw("colz");
TCanvas *ce = new TCanvas;
ce->SetLogz();
t->Draw("c1:c2:e","","goff");
TGraph2D *ge = new TGraph2D(n, t->GetV1(), t->GetV2(), t->GetV3());
ge->SetName("ge"); ge->SetNpx(500); ge->SetNpy(500); // fine bin histogram
TH2D *he = ge->GetHistogram();
he->SetTitle(";Radius [cm];Height [cm];E [V/cm]");
he->GetZaxis()->CenterTitle();
he->Draw("colz");
gDebug=1;
TGraph *g1 = detector->GetFieldLineFrom(3*cm, 1*cm);
std::cout<<detector->GetE1(3,1);
g1->Draw("pl");
}
<commit_msg>added E lines<commit_after>using namespace GeFiCa;
// draw V, E distributions saved in an input ROOT file
void drawFields(const char *input="ppc.root")
{
// Get data from input file
TFile *file = new TFile(input, "update"); // "update" allows creation of TH3
PointContactDZ *detector = (PointContactDZ*) file->Get("pcdz");
TTree *t = detector->GetTree(true);
const int n = t->GetEntries();
// fine tune margins, etc.
gStyle->SetTitleOffset(0.75,"Y");
gStyle->SetPadRightMargin(0.12);
gStyle->SetPadLeftMargin(0.08);
// generate plots
t->Draw("c1:c2:v","","goff");
TGraph2D *gv = new TGraph2D(n, t->GetV1(), t->GetV2(), t->GetV3());
gv->SetName("gv"); gv->SetNpx(500); gv->SetNpy(500); // fine bin histogram
TH2D *hv = gv->GetHistogram();
hv->SetTitle(";Radius [cm];Height [cm];Potential [V]");
hv->GetZaxis()->CenterTitle();
hv->Draw("colz");
// draw E field lines
const int np=12;
TGraph *gl[np];
double x[np] = {-25, 0.01, 25, -4, -3, -2, -1, 0.01, 1, 2, 3, 4};
double y[np] = {49.9, 24.9, 49.9, 2, 2, 2, 2, 2, 2, 2, 2, 2};
bool positive[np] = {0, 0, 0, 1, 1, 1, 1, 1, 1, 1, 1, 1};
for (int i=0; i<np; i++) {
gDebug=1;
gl[i] = detector->GetFieldLineFrom(x[i]*mm, y[i]*mm, positive[i]);
gDebug=0;
gl[i]->Draw("l");
}
TCanvas *ce = new TCanvas;
ce->SetLogz();
t->Draw("c1:c2:e","","goff");
TGraph2D *ge = new TGraph2D(n, t->GetV1(), t->GetV2(), t->GetV3());
ge->SetName("ge"); ge->SetNpx(500); ge->SetNpy(500); // fine bin histogram
TH2D *he = ge->GetHistogram();
he->SetTitle(";Radius [cm];Height [cm];E [V/cm]");
he->GetZaxis()->CenterTitle();
he->Draw("colz");
for (int i=0; i<np; i++) gl[i]->Draw("p");
}
<|endoftext|>
|
<commit_before>/// @file
/// @version 2.5
///
/// @section LICENSE
///
/// This program is free software; you can redistribute it and/or modify it under
/// the terms of the BSD license: http://opensource.org/licenses/BSD-3-Clause
#include <hltypes/hexception.h>
#include <hltypes/hmap.h>
#include <hltypes/hlog.h>
#include <hltypes/hsbase.h>
#include <hltypes/hstream.h>
#include <hltypes/hstring.h>
#include <hltypes/hversion.h>
#include <hlxml/Document.h>
#include <hlxml/Node.h>
#include <hlxml/Property.h>
#include "Deserialize.h"
#include "DeserializeXml.h"
#include "liteser.h"
#include "Serializable.h"
#include "Serialize.h"
#include "SerializeXml.h"
#include "Utility.h"
#include "Variable.h"
#define _LS_HEADER_0 'L'
#define _LS_HEADER_1 'S'
#define HEADER_SIZE 4
#define XML_HEADER "<?xml version=\"1.0\" encoding=\"utf-8\"?>"
#define LITESER_XML_ROOT_BEGIN hsprintf("<Liteser version=\"%d.%d\">\n\t", _LS_VERSION_MAJOR, _LS_VERSION_MINOR)
#define LITESER_XML_ROOT_END "\t\n</Liteser>"
#define DECLARE_HARRAY_SERIALIZER(type) \
bool serialize ## suffix(hsbase* stream, harray<type>& value) \
{ \
if (!stream->isOpen()) \
{ \
throw FileNotOpenException("Liteser Stream"); \
} \
_start(stream); \
stream->writeRaw(header, HEADER_SIZE); \
Type dumpType; \
dumpType.assign((VPtr<type>*)NULL); \
_dumpType(Type::HARRAY); \
stream->dump(1u); \
_dumpType(dumpType.value); \
_dumpHarray(&value); \
_finish(stream); \
return true; \
}
#define DECLARE_HARRAY_DESERIALIZER(type) \
bool deserialize(hsbase* stream, harray<type>* value) \
{ \
if (!stream->isOpen()) \
{ \
throw FileNotOpenException("Liteser Stream"); \
} \
if (value->size() > 0) \
{ \
throw Exception("Output harray is not empty!"); \
} \
_start(stream); \
unsigned char readHeader[HEADER_SIZE]; \
stream->readRaw(readHeader, HEADER_SIZE); \
if (readHeader[0] != _LS_HEADER_0 || readHeader[1] != _LS_HEADER_1) \
{ \
throw Exception("Invalid header!"); \
} \
unsigned char major = readHeader[2]; \
unsigned char minor = readHeader[3]; \
_checkVersion(major, minor); \
if (major > 2 || major == 2 && minor >= 7) \
{ \
if (_loadType() != Type::HARRAY) \
{ \
_finish(stream); \
throw Exception("Cannot load object from file that does not contain a harray<" #type ">!"); \
} \
if (stream->loadUint32() != 1) \
{ \
_finish(stream); \
throw Exception("Cannot load object from file that does not contain a harray<" #type ">!"); \
} \
Type subType; \
subType.assign((VPtr<type>*)NULL); \
if (_loadType() != subType.value) \
{ \
_finish(stream); \
throw Exception("Cannot load object from file that does not contain a harray<" #type ">!"); \
} \
} \
_loadHarray(value); \
_finish(stream); \
return true; \
}
#define DECLARE_HARRAY_SERIALIZER_XML(type) \
bool serialize(hsbase* stream, harray<type>& value) \
{ \
if (!stream->isOpen()) \
{ \
throw FileNotOpenException("Liteser XML Stream"); \
} \
_start(stream); \
stream->writeLine(XML_HEADER); \
stream->writeLine(LITESER_XML_ROOT_BEGIN); \
Type subType; \
subType.assign((VPtr<type>*)NULL); \
stream->writeLine("\t<Container type=\"" + hstr(Type::HARRAY) + "\" sub_types=\"" + hstr(subType.value) + "\">"); \
_indent += "\t"; \
xml::_dumpHarray(&value); \
_indent = _indent(0, _indent.size() - 1); \
stream->writeLine("\t</Container>"); \
stream->writeLine(LITESER_XML_ROOT_END); \
_finish(stream); \
return true; \
}
#define DECLARE_HARRAY_DESERIALIZER_XML(type) \
bool deserialize(hsbase* stream, harray<type>* value) \
{ \
if (!stream->isOpen()) \
{ \
throw FileNotOpenException("Liteser Stream"); \
} \
if (value->size() > 0) \
{ \
throw Exception("Output harray is not empty!"); \
} \
_start(stream); \
hlxml::Document doc(*stream); \
hlxml::Node* root = doc.root(); \
if (*root != "Liteser") \
{ \
throw Exception("Invalid header!"); \
} \
hstr versionString = root->pstr("version", ""); \
if (versionString.count(".") != 1) \
{ \
throw Exception("Invalid header!"); \
} \
hstr majorString; \
hstr minorString; \
if (!versionString.split('.', majorString, minorString)) \
{ \
throw Exception("Invalid header!"); \
} \
unsigned char major = (unsigned char)(int)majorString; \
unsigned char minor = (unsigned char)(int)minorString; \
_checkVersion(major, minor); \
hlxml::Node* node = root; \
if (major > 2 || major == 2 && minor >= 7) \
{ \
node = root->iterChildren(); \
if (node->next() != NULL || *node != "Container" || node->pstr("type", "00").unhex() != Type::HARRAY) \
{ \
_finish(stream); \
throw Exception("Cannot load object from file that does not contain a harray<\"" #type "\">!"); \
} \
Type subType; \
subType.assign((VPtr<type>*)NULL); \
harray<hstr> subTypes = node->pstr("sub_types", "00").split(',', -1, true); \
if (subTypes.size() != 1 || subTypes.first().unhex() != subType.value) \
{ \
_finish(stream); \
throw Exception("Cannot load object from file that does not contain a harray<" #type ">!"); \
} \
} \
xml::_loadHarray(node, value); \
_finish(stream); \
return true; \
}
namespace liteser
{
char header[4] = {_LS_HEADER_0, _LS_HEADER_1, (char)_LS_VERSION_MAJOR, (char)_LS_VERSION_MINOR};
hstr logTag = "liteser";
bool serialize(hsbase* stream, Serializable* object)
{
if (!stream->isOpen())
{
throw FileNotOpenException("Liteser Stream");
}
// TODO - add exception handling
_start(stream);
stream->writeRaw(header, HEADER_SIZE);
_dumpType(Type::OBJPTR);
_dump(&object);
_finish(stream);
return true;
}
DECLARE_HARRAY_SERIALIZER(Serializable*);
DECLARE_HARRAY_SERIALIZER(char);
DECLARE_HARRAY_SERIALIZER(unsigned char);
DECLARE_HARRAY_SERIALIZER(short);
DECLARE_HARRAY_SERIALIZER(unsigned short);
DECLARE_HARRAY_SERIALIZER(int);
DECLARE_HARRAY_SERIALIZER(unsigned int);
DECLARE_HARRAY_SERIALIZER(int64_t);
DECLARE_HARRAY_SERIALIZER(uint64_t);
DECLARE_HARRAY_SERIALIZER(float);
DECLARE_HARRAY_SERIALIZER(double);
DECLARE_HARRAY_SERIALIZER(hstr);
DECLARE_HARRAY_SERIALIZER(hversion);
DECLARE_HARRAY_SERIALIZER(henum);
DECLARE_HARRAY_SERIALIZER(grect);
DECLARE_HARRAY_SERIALIZER(gvec2);
DECLARE_HARRAY_SERIALIZER(gvec3);
bool deserialize(hsbase* stream, Serializable** object)
{
if (!stream->isOpen())
{
throw FileNotOpenException("Liteser Stream");
}
if (*object != NULL)
{
throw Exception("Given pointer to object for deserialization is not NULL.");
}
// TODO - add exception handling
_start(stream);
unsigned char readHeader[HEADER_SIZE];
stream->readRaw(readHeader, HEADER_SIZE);
if (readHeader[0] != _LS_HEADER_0 || readHeader[1] != _LS_HEADER_1)
{
throw Exception("Invalid header!");
}
unsigned char major = readHeader[2];
unsigned char minor = readHeader[3];
_checkVersion(major, minor);
if (major > 2 || major == 2 && minor >= 7)
{
Type::Value type = _loadType();
if (type != Type::OBJPTR)
{
_finish(stream);
throw Exception("Cannot load object from file that does not contain an object!");
}
}
_load(object);
_finish(stream);
return true;
}
DECLARE_HARRAY_DESERIALIZER(Serializable*);
DECLARE_HARRAY_DESERIALIZER(char);
DECLARE_HARRAY_DESERIALIZER(unsigned char);
DECLARE_HARRAY_DESERIALIZER(short);
DECLARE_HARRAY_DESERIALIZER(unsigned short);
DECLARE_HARRAY_DESERIALIZER(int);
DECLARE_HARRAY_DESERIALIZER(unsigned int);
DECLARE_HARRAY_DESERIALIZER(int64_t);
DECLARE_HARRAY_DESERIALIZER(uint64_t);
DECLARE_HARRAY_DESERIALIZER(float);
DECLARE_HARRAY_DESERIALIZER(double);
DECLARE_HARRAY_DESERIALIZER(hstr);
DECLARE_HARRAY_DESERIALIZER(hversion);
DECLARE_HARRAY_DESERIALIZER(henum);
DECLARE_HARRAY_DESERIALIZER(grect);
DECLARE_HARRAY_DESERIALIZER(gvec2);
DECLARE_HARRAY_DESERIALIZER(gvec3);
namespace xml
{
bool serialize(hsbase* stream, Serializable* object)
{
if (!stream->isOpen())
{
throw FileNotOpenException("Liteser Stream");
}
// TODO - add exception handling
_start(stream);
stream->writeLine(XML_HEADER);
stream->writeLine(LITESER_XML_ROOT_BEGIN);
xml::_dump(&object);
stream->writeLine(LITESER_XML_ROOT_END);
_finish(stream);
return true;
}
DECLARE_HARRAY_SERIALIZER_XML(Serializable*);
DECLARE_HARRAY_SERIALIZER_XML(char);
DECLARE_HARRAY_SERIALIZER_XML(unsigned char);
DECLARE_HARRAY_SERIALIZER_XML(short);
DECLARE_HARRAY_SERIALIZER_XML(unsigned short);
DECLARE_HARRAY_SERIALIZER_XML(int);
DECLARE_HARRAY_SERIALIZER_XML(unsigned int);
DECLARE_HARRAY_SERIALIZER_XML(int64_t);
DECLARE_HARRAY_SERIALIZER_XML(uint64_t);
DECLARE_HARRAY_SERIALIZER_XML(float);
DECLARE_HARRAY_SERIALIZER_XML(double);
DECLARE_HARRAY_SERIALIZER_XML(hstr);
DECLARE_HARRAY_SERIALIZER_XML(hversion);
DECLARE_HARRAY_SERIALIZER_XML(henum);
DECLARE_HARRAY_SERIALIZER_XML(grect);
DECLARE_HARRAY_SERIALIZER_XML(gvec2);
DECLARE_HARRAY_SERIALIZER_XML(gvec3);
bool deserialize(hsbase* stream, Serializable** object)
{
if (!stream->isOpen())
{
throw FileNotOpenException("Liteser Stream");
}
if (*object != NULL)
{
throw Exception("Given pointer to object for deserialization is not NULL.");
}
// TODO - add exception handling
_start(stream);
hlxml::Document doc(*stream);
hlxml::Node* root = doc.root();
if (*root != "Liteser")
{
throw Exception("Invalid header!");
}
hstr versionString = root->pstr("version", "");
if (versionString.count(".") != 1)
{
throw Exception("Invalid header!");
}
hstr majorString;
hstr minorString;
if (!versionString.split('.', majorString, minorString))
{
throw Exception("Invalid header!");
}
unsigned char major = (unsigned char)(int)majorString;
unsigned char minor = (unsigned char)(int)minorString;
_checkVersion(major, minor);
hlxml::Node* node = root->iterChildren();
if (major > 2 || major == 2 && minor >= 7)
{
if (node->next() != NULL || *node != "Object")
{
_finish(stream);
throw Exception("Cannot load object from file that does not contain an object!");
}
}
xml::_load(node, object);
_finish(stream);
return true;
}
DECLARE_HARRAY_DESERIALIZER_XML(Serializable*);
DECLARE_HARRAY_DESERIALIZER_XML(char);
DECLARE_HARRAY_DESERIALIZER_XML(unsigned char);
DECLARE_HARRAY_DESERIALIZER_XML(short);
DECLARE_HARRAY_DESERIALIZER_XML(unsigned short);
DECLARE_HARRAY_DESERIALIZER_XML(int);
DECLARE_HARRAY_DESERIALIZER_XML(unsigned int);
DECLARE_HARRAY_DESERIALIZER_XML(int64_t);
DECLARE_HARRAY_DESERIALIZER_XML(uint64_t);
DECLARE_HARRAY_DESERIALIZER_XML(float);
DECLARE_HARRAY_DESERIALIZER_XML(double);
DECLARE_HARRAY_DESERIALIZER_XML(hstr);
DECLARE_HARRAY_DESERIALIZER_XML(hversion);
DECLARE_HARRAY_DESERIALIZER_XML(henum);
DECLARE_HARRAY_DESERIALIZER_XML(grect);
DECLARE_HARRAY_DESERIALIZER_XML(gvec2);
DECLARE_HARRAY_DESERIALIZER_XML(gvec3);
}
bool clone(Serializable* input, Serializable** output)
{
if (*output != NULL)
{
throw Exception("Output does not point to NULL!");
}
hstream stream;
_start(&stream);
_dump(&input);
_finish(&stream);
stream.rewind();
_start(&stream);
_load(output);
_finish(&stream);
return true;
}
}
<commit_msg>- small fix<commit_after>/// @file
/// @version 2.5
///
/// @section LICENSE
///
/// This program is free software; you can redistribute it and/or modify it under
/// the terms of the BSD license: http://opensource.org/licenses/BSD-3-Clause
#include <hltypes/hexception.h>
#include <hltypes/hmap.h>
#include <hltypes/hlog.h>
#include <hltypes/hsbase.h>
#include <hltypes/hstream.h>
#include <hltypes/hstring.h>
#include <hltypes/hversion.h>
#include <hlxml/Document.h>
#include <hlxml/Node.h>
#include <hlxml/Property.h>
#include "Deserialize.h"
#include "DeserializeXml.h"
#include "liteser.h"
#include "Serializable.h"
#include "Serialize.h"
#include "SerializeXml.h"
#include "Utility.h"
#include "Variable.h"
#define _LS_HEADER_0 'L'
#define _LS_HEADER_1 'S'
#define HEADER_SIZE 4
#define XML_HEADER "<?xml version=\"1.0\" encoding=\"utf-8\"?>"
#define LITESER_XML_ROOT_BEGIN hsprintf("<Liteser version=\"%d.%d\">\n\t", _LS_VERSION_MAJOR, _LS_VERSION_MINOR)
#define LITESER_XML_ROOT_END "\t\n</Liteser>"
#define DECLARE_HARRAY_SERIALIZER(type) \
bool serialize(hsbase* stream, harray<type>& value) \
{ \
if (!stream->isOpen()) \
{ \
throw FileNotOpenException("Liteser Stream"); \
} \
_start(stream); \
stream->writeRaw(header, HEADER_SIZE); \
Type dumpType; \
dumpType.assign((VPtr<type>*)NULL); \
_dumpType(Type::HARRAY); \
stream->dump(1u); \
_dumpType(dumpType.value); \
_dumpHarray(&value); \
_finish(stream); \
return true; \
}
#define DECLARE_HARRAY_DESERIALIZER(type) \
bool deserialize(hsbase* stream, harray<type>* value) \
{ \
if (!stream->isOpen()) \
{ \
throw FileNotOpenException("Liteser Stream"); \
} \
if (value->size() > 0) \
{ \
throw Exception("Output harray is not empty!"); \
} \
_start(stream); \
unsigned char readHeader[HEADER_SIZE]; \
stream->readRaw(readHeader, HEADER_SIZE); \
if (readHeader[0] != _LS_HEADER_0 || readHeader[1] != _LS_HEADER_1) \
{ \
throw Exception("Invalid header!"); \
} \
unsigned char major = readHeader[2]; \
unsigned char minor = readHeader[3]; \
_checkVersion(major, minor); \
if (major > 2 || major == 2 && minor >= 7) \
{ \
if (_loadType() != Type::HARRAY) \
{ \
_finish(stream); \
throw Exception("Cannot load object from file that does not contain a harray<" #type ">!"); \
} \
if (stream->loadUint32() != 1) \
{ \
_finish(stream); \
throw Exception("Cannot load object from file that does not contain a harray<" #type ">!"); \
} \
Type subType; \
subType.assign((VPtr<type>*)NULL); \
if (_loadType() != subType.value) \
{ \
_finish(stream); \
throw Exception("Cannot load object from file that does not contain a harray<" #type ">!"); \
} \
} \
_loadHarray(value); \
_finish(stream); \
return true; \
}
#define DECLARE_HARRAY_SERIALIZER_XML(type) \
bool serialize(hsbase* stream, harray<type>& value) \
{ \
if (!stream->isOpen()) \
{ \
throw FileNotOpenException("Liteser XML Stream"); \
} \
_start(stream); \
stream->writeLine(XML_HEADER); \
stream->writeLine(LITESER_XML_ROOT_BEGIN); \
Type subType; \
subType.assign((VPtr<type>*)NULL); \
stream->writeLine("\t<Container type=\"" + hstr(Type::HARRAY) + "\" sub_types=\"" + hstr(subType.value) + "\">"); \
_indent += "\t"; \
xml::_dumpHarray(&value); \
_indent = _indent(0, _indent.size() - 1); \
stream->writeLine("\t</Container>"); \
stream->writeLine(LITESER_XML_ROOT_END); \
_finish(stream); \
return true; \
}
#define DECLARE_HARRAY_DESERIALIZER_XML(type) \
bool deserialize(hsbase* stream, harray<type>* value) \
{ \
if (!stream->isOpen()) \
{ \
throw FileNotOpenException("Liteser Stream"); \
} \
if (value->size() > 0) \
{ \
throw Exception("Output harray is not empty!"); \
} \
_start(stream); \
hlxml::Document doc(*stream); \
hlxml::Node* root = doc.root(); \
if (*root != "Liteser") \
{ \
throw Exception("Invalid header!"); \
} \
hstr versionString = root->pstr("version", ""); \
if (versionString.count(".") != 1) \
{ \
throw Exception("Invalid header!"); \
} \
hstr majorString; \
hstr minorString; \
if (!versionString.split('.', majorString, minorString)) \
{ \
throw Exception("Invalid header!"); \
} \
unsigned char major = (unsigned char)(int)majorString; \
unsigned char minor = (unsigned char)(int)minorString; \
_checkVersion(major, minor); \
hlxml::Node* node = root; \
if (major > 2 || major == 2 && minor >= 7) \
{ \
node = root->iterChildren(); \
if (node->next() != NULL || *node != "Container" || node->pstr("type", "00").unhex() != Type::HARRAY) \
{ \
_finish(stream); \
throw Exception("Cannot load object from file that does not contain a harray<\"" #type "\">!"); \
} \
Type subType; \
subType.assign((VPtr<type>*)NULL); \
harray<hstr> subTypes = node->pstr("sub_types", "00").split(',', -1, true); \
if (subTypes.size() != 1 || subTypes.first().unhex() != subType.value) \
{ \
_finish(stream); \
throw Exception("Cannot load object from file that does not contain a harray<" #type ">!"); \
} \
} \
xml::_loadHarray(node, value); \
_finish(stream); \
return true; \
}
namespace liteser
{
char header[4] = {_LS_HEADER_0, _LS_HEADER_1, (char)_LS_VERSION_MAJOR, (char)_LS_VERSION_MINOR};
hstr logTag = "liteser";
bool serialize(hsbase* stream, Serializable* object)
{
if (!stream->isOpen())
{
throw FileNotOpenException("Liteser Stream");
}
// TODO - add exception handling
_start(stream);
stream->writeRaw(header, HEADER_SIZE);
_dumpType(Type::OBJPTR);
_dump(&object);
_finish(stream);
return true;
}
DECLARE_HARRAY_SERIALIZER(Serializable*);
DECLARE_HARRAY_SERIALIZER(char);
DECLARE_HARRAY_SERIALIZER(unsigned char);
DECLARE_HARRAY_SERIALIZER(short);
DECLARE_HARRAY_SERIALIZER(unsigned short);
DECLARE_HARRAY_SERIALIZER(int);
DECLARE_HARRAY_SERIALIZER(unsigned int);
DECLARE_HARRAY_SERIALIZER(int64_t);
DECLARE_HARRAY_SERIALIZER(uint64_t);
DECLARE_HARRAY_SERIALIZER(float);
DECLARE_HARRAY_SERIALIZER(double);
DECLARE_HARRAY_SERIALIZER(hstr);
DECLARE_HARRAY_SERIALIZER(hversion);
DECLARE_HARRAY_SERIALIZER(henum);
DECLARE_HARRAY_SERIALIZER(grect);
DECLARE_HARRAY_SERIALIZER(gvec2);
DECLARE_HARRAY_SERIALIZER(gvec3);
bool deserialize(hsbase* stream, Serializable** object)
{
if (!stream->isOpen())
{
throw FileNotOpenException("Liteser Stream");
}
if (*object != NULL)
{
throw Exception("Given pointer to object for deserialization is not NULL.");
}
// TODO - add exception handling
_start(stream);
unsigned char readHeader[HEADER_SIZE];
stream->readRaw(readHeader, HEADER_SIZE);
if (readHeader[0] != _LS_HEADER_0 || readHeader[1] != _LS_HEADER_1)
{
throw Exception("Invalid header!");
}
unsigned char major = readHeader[2];
unsigned char minor = readHeader[3];
_checkVersion(major, minor);
if (major > 2 || (major == 2 && minor >= 7))
{
Type::Value type = _loadType();
if (type != Type::OBJPTR)
{
_finish(stream);
throw Exception("Cannot load object from file that does not contain an object!");
}
}
_load(object);
_finish(stream);
return true;
}
DECLARE_HARRAY_DESERIALIZER(Serializable*);
DECLARE_HARRAY_DESERIALIZER(char);
DECLARE_HARRAY_DESERIALIZER(unsigned char);
DECLARE_HARRAY_DESERIALIZER(short);
DECLARE_HARRAY_DESERIALIZER(unsigned short);
DECLARE_HARRAY_DESERIALIZER(int);
DECLARE_HARRAY_DESERIALIZER(unsigned int);
DECLARE_HARRAY_DESERIALIZER(int64_t);
DECLARE_HARRAY_DESERIALIZER(uint64_t);
DECLARE_HARRAY_DESERIALIZER(float);
DECLARE_HARRAY_DESERIALIZER(double);
DECLARE_HARRAY_DESERIALIZER(hstr);
DECLARE_HARRAY_DESERIALIZER(hversion);
DECLARE_HARRAY_DESERIALIZER(henum);
DECLARE_HARRAY_DESERIALIZER(grect);
DECLARE_HARRAY_DESERIALIZER(gvec2);
DECLARE_HARRAY_DESERIALIZER(gvec3);
namespace xml
{
bool serialize(hsbase* stream, Serializable* object)
{
if (!stream->isOpen())
{
throw FileNotOpenException("Liteser Stream");
}
// TODO - add exception handling
_start(stream);
stream->writeLine(XML_HEADER);
stream->writeLine(LITESER_XML_ROOT_BEGIN);
xml::_dump(&object);
stream->writeLine(LITESER_XML_ROOT_END);
_finish(stream);
return true;
}
DECLARE_HARRAY_SERIALIZER_XML(Serializable*);
DECLARE_HARRAY_SERIALIZER_XML(char);
DECLARE_HARRAY_SERIALIZER_XML(unsigned char);
DECLARE_HARRAY_SERIALIZER_XML(short);
DECLARE_HARRAY_SERIALIZER_XML(unsigned short);
DECLARE_HARRAY_SERIALIZER_XML(int);
DECLARE_HARRAY_SERIALIZER_XML(unsigned int);
DECLARE_HARRAY_SERIALIZER_XML(int64_t);
DECLARE_HARRAY_SERIALIZER_XML(uint64_t);
DECLARE_HARRAY_SERIALIZER_XML(float);
DECLARE_HARRAY_SERIALIZER_XML(double);
DECLARE_HARRAY_SERIALIZER_XML(hstr);
DECLARE_HARRAY_SERIALIZER_XML(hversion);
DECLARE_HARRAY_SERIALIZER_XML(henum);
DECLARE_HARRAY_SERIALIZER_XML(grect);
DECLARE_HARRAY_SERIALIZER_XML(gvec2);
DECLARE_HARRAY_SERIALIZER_XML(gvec3);
bool deserialize(hsbase* stream, Serializable** object)
{
if (!stream->isOpen())
{
throw FileNotOpenException("Liteser Stream");
}
if (*object != NULL)
{
throw Exception("Given pointer to object for deserialization is not NULL.");
}
// TODO - add exception handling
_start(stream);
hlxml::Document doc(*stream);
hlxml::Node* root = doc.root();
if (*root != "Liteser")
{
throw Exception("Invalid header!");
}
hstr versionString = root->pstr("version", "");
if (versionString.count(".") != 1)
{
throw Exception("Invalid header!");
}
hstr majorString;
hstr minorString;
if (!versionString.split('.', majorString, minorString))
{
throw Exception("Invalid header!");
}
unsigned char major = (unsigned char)(int)majorString;
unsigned char minor = (unsigned char)(int)minorString;
_checkVersion(major, minor);
hlxml::Node* node = root->iterChildren();
if (major > 2 || (major == 2 && minor >= 7))
{
if (node->next() != NULL || *node != "Object")
{
_finish(stream);
throw Exception("Cannot load object from file that does not contain an object!");
}
}
xml::_load(node, object);
_finish(stream);
return true;
}
DECLARE_HARRAY_DESERIALIZER_XML(Serializable*);
DECLARE_HARRAY_DESERIALIZER_XML(char);
DECLARE_HARRAY_DESERIALIZER_XML(unsigned char);
DECLARE_HARRAY_DESERIALIZER_XML(short);
DECLARE_HARRAY_DESERIALIZER_XML(unsigned short);
DECLARE_HARRAY_DESERIALIZER_XML(int);
DECLARE_HARRAY_DESERIALIZER_XML(unsigned int);
DECLARE_HARRAY_DESERIALIZER_XML(int64_t);
DECLARE_HARRAY_DESERIALIZER_XML(uint64_t);
DECLARE_HARRAY_DESERIALIZER_XML(float);
DECLARE_HARRAY_DESERIALIZER_XML(double);
DECLARE_HARRAY_DESERIALIZER_XML(hstr);
DECLARE_HARRAY_DESERIALIZER_XML(hversion);
DECLARE_HARRAY_DESERIALIZER_XML(henum);
DECLARE_HARRAY_DESERIALIZER_XML(grect);
DECLARE_HARRAY_DESERIALIZER_XML(gvec2);
DECLARE_HARRAY_DESERIALIZER_XML(gvec3);
}
bool clone(Serializable* input, Serializable** output)
{
if (*output != NULL)
{
throw Exception("Output does not point to NULL!");
}
hstream stream;
_start(&stream);
_dump(&input);
_finish(&stream);
stream.rewind();
_start(&stream);
_load(output);
_finish(&stream);
return true;
}
}
<|endoftext|>
|
<commit_before>/*=========================================================================
Program: Medical Imaging & Interaction Toolkit
Module: $RCSfile$
Language: C++
Date: $Date$
Version: $Revision$
Copyright (c) German Cancer Research Center, Division of Medical and
Biological Informatics. All rights reserved.
See MITKCopyright.txt or http://www.mitk.org/copyright.html for details.
This software is distributed WITHOUT ANY WARRANTY; without even
the implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR
PURPOSE. See the above copyright notices for more information.
=========================================================================*/
#include "QmitkProgressBar.h"
#include <qprogressbar.h>
#include <mitkProgressBar.h>
#include <qmainwindow.h>
#include <itkObjectFactory.h>
/**
* Reset the progress bar. The progress bar "rewinds" and shows no progress.
*/
void QmitkProgressBar::Reset()
{
this->reset();
this->hide();
m_TotalSteps = 0;
m_Progress = 0;
}
/**
* Sets whether the current progress value is displayed.
*/
void QmitkProgressBar::SetPercentageVisible(bool visible)
{
this->setPercentageVisible(visible);
}
/**
*Documentation
*@brief Adds steps to totalSteps.
*/
void QmitkProgressBar::AddStepsToDo(unsigned int steps)
{
m_TotalSteps += steps;
this->setProgress(m_Progress, m_TotalSteps);
this->show();
}
/**
*Documentation
*@brief Sets the current amount of progress to current progress + steps.
*@param: steps the number of steps done since last Progress(int steps) call.
*/
void QmitkProgressBar::Progress(unsigned int steps)
{
m_Progress += steps;
this->setProgress(m_Progress);
this->show();
if (m_Progress >= m_TotalSteps)
Reset();
}
QmitkProgressBar::QmitkProgressBar(QWidget * parent, const char * name, WFlags f)
:QProgressBar(parent, name, f), ProgressBarImplementation()
{
m_TotalSteps = 0;
m_Progress = 0;
this->hide();
this->SetPercentageVisible(true);
mitk::ProgressBar::SetImplementationInstance(this);
}
QmitkProgressBar::~QmitkProgressBar()
{
}
<commit_msg>Add qApp->processEvents(), trying to fix bug #357<commit_after>/*=========================================================================
Program: Medical Imaging & Interaction Toolkit
Module: $RCSfile$
Language: C++
Date: $Date$
Version: $Revision$
Copyright (c) German Cancer Research Center, Division of Medical and
Biological Informatics. All rights reserved.
See MITKCopyright.txt or http://www.mitk.org/copyright.html for details.
This software is distributed WITHOUT ANY WARRANTY; without even
the implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR
PURPOSE. See the above copyright notices for more information.
=========================================================================*/
#include "QmitkProgressBar.h"
#include <qprogressbar.h>
#include <mitkProgressBar.h>
//#include <qmainwindow.h>
#include <qapplication.h>
//#include <itkObjectFactory.h>
/**
* Reset the progress bar. The progress bar "rewinds" and shows no progress.
*/
void QmitkProgressBar::Reset()
{
this->reset();
this->hide();
m_TotalSteps = 0;
m_Progress = 0;
}
/**
* Sets whether the current progress value is displayed.
*/
void QmitkProgressBar::SetPercentageVisible(bool visible)
{
this->setPercentageVisible(visible);
}
/**
*Documentation
*@brief Adds steps to totalSteps.
*/
void QmitkProgressBar::AddStepsToDo(unsigned int steps)
{
m_TotalSteps += steps;
this->setProgress(m_Progress, m_TotalSteps);
this->show();
qApp->processEvents();
}
/**
*Documentation
*@brief Sets the current amount of progress to current progress + steps.
*@param: steps the number of steps done since last Progress(int steps) call.
*/
void QmitkProgressBar::Progress(unsigned int steps)
{
m_Progress += steps;
this->setProgress(m_Progress);
this->show();
if (m_Progress >= m_TotalSteps)
Reset();
qApp->processEvents();
}
QmitkProgressBar::QmitkProgressBar(QWidget * parent, const char * name, WFlags f)
:QProgressBar(parent, name, f), ProgressBarImplementation()
{
m_TotalSteps = 0;
m_Progress = 0;
this->hide();
this->SetPercentageVisible(true);
mitk::ProgressBar::SetImplementationInstance(this);
}
QmitkProgressBar::~QmitkProgressBar()
{
}
<|endoftext|>
|
<commit_before>// Copyright 2019 Intel Corporation.
#include "pmlc/dialect/tile/gradient.h"
#include "llvm/ADT/SetVector.h"
#include "llvm/Support/FormatVariadic.h"
#include "mlir/Support/DebugStringHelper.h"
#include "base/util/logging.h"
#include "pmlc/dialect/tile/builder.h"
#include "pmlc/dialect/tile/ops.h"
#include "pmlc/util/slice.h"
namespace pmlc::dialect::tile {
Gradient::Gradient(mlir::Value* loss, TileBuilder* builder) : builder_(builder) {
IVLOG(3, "Gradient::Gradient> loss: " << mlir::debugString(*loss));
grads_[loss] = builder_->MakeScalarConstantOp(1.0);
llvm::SetVector<mlir::Value*> loss_setvec;
loss_setvec.insert(loss);
auto defs = util::getBackwardSlice(loss_setvec, false, std::function<bool(mlir::Value*)>{[](mlir::Value* val) {
auto op = val->getDefiningOp();
// TODO: This is an ad hoc list of what to filter out; make it principled
return !mlir::isa<AffineConstraintsOp>(op) && !mlir::isa<AffineMapOp>(op) &&
!mlir::isa<AffineIndexOp>(op) && !mlir::isa<DimOp>(op) &&
!mlir::isa<AffineConstantOp>(op) && !mlir::isa<AffineAddOp>(op) &&
!mlir::isa<AffineDivOp>(op) && !mlir::isa<AffineMulOp>(op) &&
!mlir::isa<AffineNegOp>(op) && !mlir::isa<AffineSubOp>(op) &&
!mlir::isa<AffineMaxOp>(op) && !mlir::isa<AffineMinOp>(op) &&
!mlir::isa<eltwise::ScalarConstantOp>(op);
}});
for (auto def = defs.rbegin(); def != defs.rend(); def++) {
ComputeOperandDerivs(*def);
}
if (VLOG_IS_ON(5)) {
IVLOG(5, "Gradient::Gradient> Computed the following gradients: ");
for (auto [key, value] : grads_) {
IVLOG(5, " key is " << mlir::debugString(*key) << "\n for val " << mlir::debugString(*value));
}
}
}
void Gradient::AddToGradient(Value* source_op, Value* deriv) {
// Adds the gradient `deriv` computed for one use of `source_op` to the overall gradient of `source_op`
if (!grads_.count(source_op)) {
grads_[source_op] = deriv;
} else {
grads_[source_op] = builder_->MakePrimitiveOp("add", {grads_[source_op], deriv});
}
}
void Gradient::ComputeOperandDerivs(mlir::Value* val) {
IVLOG(4, "Gradient::ComputeDerivative> " << mlir::debugString(*val));
// TODO: Throw on ops with multiple results?
auto op = val->getDefiningOp();
if (mlir::isa<AffineConstraintsOp>(op) || mlir::isa<AffineMapOp>(op) || mlir::isa<AffineIndexOp>(op) ||
mlir::isa<PrngOp>(op) || mlir::isa<ShapeOp>(op)) {
// TODO: Make the list of which ops these are more principled. Also, should these all be caught in the backwards
// slice filter? If so, probably throw here.
IVLOG(6, "Gradient::ComputeDerivative> Skipping computing derivatives for op "
<< mlir::debugString(*op) << ", as it is not a type of op for which gradients apply");
return;
}
if (!grads_.count(val)) {
IVLOG(1, "Gradient::ComputeOperandDerivs> Called on Value which has not itself been differentiated: "
<< mlir::debugString(*val));
throw std::runtime_error("Unexpected missing derivative in ComputeOperandDerivs");
}
if (mlir::isa<eltwise::EltwiseOp>(op)) {
size_t idx = 0; // Need to track which operand we're at
for (const auto& operand : op->getOperands()) {
auto dop = DeriveEltwise(grads_[val], val, idx);
AddToGradient(operand, dop);
idx++;
}
// TODO: if grads_[operand] has rank > 0, call a simple_reduce
} else if (auto cion_op = mlir::dyn_cast<SymbolicContractionOp>(op)) {
{
// TODO: I discussed this with Jeremy and I think the below notes are wrong, but we need another discussion.
// TODO: Do `init` deriv right: we should passthrough on plus, conditional against result on max/min, throw on
// product
// TODO: This is a temporary hack!
AddToGradient(cion_op.init(), grads_[val]);
}
size_t idx = 0; // Need to track which operand we're at
for (auto src : cion_op.srcs()) {
auto dop = DeriveContraction(grads_[val], val, idx);
AddToGradient(src, dop);
idx++;
}
} else if (auto gather_op = mlir::dyn_cast<GatherOp>(op)) {
auto tensor_input = gather_op.tensor();
auto dims_input = gather_op.dims();
auto dop = builder_->MakePrimitiveOp("scatter", {grads_[val], dims_input, tensor_input});
auto zero_op = builder_->MakeScalarConstantOp(0.);
AddToGradient(tensor_input, dop);
AddToGradient(dims_input, zero_op);
} else if (mlir::isa<ScatterOp>(op)) {
// TODO
throw std::runtime_error("TODO: Derivs of Scatter not yet implemented");
} else if (auto reshape_op = mlir::dyn_cast<ReshapeOp>(op)) {
auto tensor_input = reshape_op.tensor();
std::vector<mlir::Value*> args{grads_[val]};
for (size_t i = 0; i < tensor_input->getType().dyn_cast<RankedTensorType>().getRank(); ++i) {
args.push_back(builder_->MakeDimOp(tensor_input, i));
}
auto dop = builder_->MakePrimitiveOp("reshape", args);
AddToGradient(tensor_input, dop);
} else if (mlir::isa<SpecialOp>(op)) {
throw std::runtime_error("Unrecognized special operation, unable to differentiate");
} else if (mlir::isa<DimOp>(op) || mlir::isa<eltwise::ScalarConstantOp>(op)) {
auto dop = builder_->MakeScalarConstantOp(0.);
for (const auto& operand : op->getOperands()) {
AddToGradient(operand, dop);
}
} else if (auto tmap_op = mlir::dyn_cast<AffineTensorMapOp>(op)) {
// Just forward the gradient in a tmap to the tensor
AddToGradient(tmap_op.tensor(), grads_[val]);
} else {
if (op->getNumOperands()) {
throw std::runtime_error("Unexpected Operation type in ComputeOperandDerivs! Operation is " +
mlir::debugString(*op));
}
// If it has no operands, it doesn't matter whether we can differentiate it, so we do nothing
}
}
mlir::Value* Gradient::GetDerivative(mlir::Value* val) {
IVLOG(5, "Gradient::GetDerivative> " << mlir::debugString(*val));
auto it = grads_.find(val);
if (it != grads_.end()) {
IVLOG(6, " Gradient::GetDerivative> Derivative retrieved: " << mlir::debugString(*it->second));
return it->second;
}
// TODO:
// In the long run, this should probably just return 0 or otherwise indicate a continuation
// For now, I want to know if we hit this (as we shouldn't in most cases)
IVLOG(1, "Gradient::GetDerivative> The requested derivative of " << mlir::debugString(*val) << " was not computed!");
throw std::runtime_error("TODO: requested derivative not from getBackwardSlice");
}
mlir::Value* Gradient::DeriveEltwise(mlir::Value* dout, mlir::Value* out, size_t idx) {
auto op = out->getDefiningOp();
IVLOG(5, "Gradient::DeriveEltwise> dout=" << mlir::debugString(*dout) << ", op=" << mlir::debugString(*op)
<< ", idx=" << idx);
auto deriv = DerivRegistry::Instance()->Resolve(op->getName().getStringRef());
llvm::SmallVector<mlir::Value*, 3> operands{op->getOperands()}; // TODO: Size
// TODO: Need to add simple_reduce here, unless done in the "if isa EltwiseOp" block above
return deriv.fn(out, dout, operands, deriv.user_fn, deriv.user_ctx)[idx];
}
mlir::Value* Gradient::DeriveContraction(mlir::Value* dout, mlir::Value* out, size_t idx) {
IVLOG(5, "Gradient::DeriveContraction> dout=" << mlir::debugString(*dout) << ", out=" << mlir::debugString(*out)
<< ", idx=" << idx);
auto op = llvm::dyn_cast_or_null<SymbolicContractionOp>(out->getDefiningOp());
if (!op) {
throw std::runtime_error("DeriveContraction called on non-contraction");
}
if (op.combo() == util::CombinationKind::eq) {
// TODO: What type should this 0 be?
return builder_->MakeScalarConstantOp(0.);
}
auto combo_kind = util::CombinationKind::none; // This may be reset later if necessary
std::vector<Value*> new_srcs;
Value* target_src = nullptr;
switch (op.agg()) {
case util::AggregationKind::max:
case util::AggregationKind::min: {
size_t i = 0;
// TODO: Is there a better option to do "Get the unique src (or throw if not unique)"?
for (auto src : op.srcs()) {
if (i == idx) {
combo_kind = util::CombinationKind::cond;
auto src_op = mlir::dyn_cast_or_null<AffineTensorMapOp>(src->getDefiningOp());
if (!src_op) {
throw std::runtime_error("src_op as cast is null");
}
new_srcs.push_back(src_op);
std::vector<Value*> dout_idxs;
for (const auto& dim : llvm::cast<AffineMapOp>(op.sink()->getDefiningOp()).dims()) {
dout_idxs.push_back(dim);
}
new_srcs.push_back(builder_->MakeAffineSourceIndexMapOp(op, dout_idxs));
new_srcs.push_back(builder_->MakeAffineSourceIndexMapOp(dout, dout_idxs));
// Also track that this is the differentiated source for later use
target_src = src;
} else {
throw std::runtime_error("Cannot differentiate max/min contractions with multiple input tensors");
}
i++;
}
} break;
case util::AggregationKind::add:
case util::AggregationKind::assign: {
size_t i = 0;
for (auto src : op.srcs()) {
if (i == idx) {
// This is the differentiated input; so swap in dout here to create the new op
std::vector<Value*> dout_idxs;
for (const auto& dim : llvm::cast<AffineMapOp>(op.sink()->getDefiningOp()).dims()) {
dout_idxs.push_back(dim);
}
new_srcs.push_back(builder_->MakeAffineSourceIndexMapOp(dout, dout_idxs));
// Also track that this is the differentiated source for later use
target_src = src;
} else {
// This is the non-differentiated input; behavior depends on combo op
switch (op.combo()) {
case util::CombinationKind::none:
IVLOG(1, "About to fail on a NONE combo, with idx==" << idx << ", and i==" << i);
throw std::runtime_error(
"Unexpected multiple inputs found when differentiating contraction with NONE combination op");
break;
case util::CombinationKind::add:
// For +, we ignore the non-differentiated input
combo_kind = util::CombinationKind::none;
break;
case util::CombinationKind::cond:
throw std::runtime_error("Gradient of sum of conditionals not supported");
break;
case util::CombinationKind::eq:
throw std::logic_error("Gradient unexpectedly failed to detect combo op as equality");
break;
case util::CombinationKind::mul:
// For *, we multiply by the non-differentiated input
new_srcs.push_back(src);
combo_kind = util::CombinationKind::mul;
break;
default:
throw std::runtime_error("Failed to recognize combination op during differentiation");
}
}
i++;
}
} break;
case util::AggregationKind::mul:
throw std::runtime_error("Cannot differentiate multiplication aggregations");
break;
default:
throw std::runtime_error("Did not recognize aggregation operation when differentiating " +
mlir::debugString(*out));
}
if (!target_src) {
throw std::runtime_error(
llvm::formatv("Trying to derive contraction at out of range index (requested source operand {0})", idx).str());
}
auto target_src_op = llvm::cast<AffineTensorMapOp>(target_src->getDefiningOp());
std::vector<mlir::Value*> sizes;
for (size_t i = 0; i < target_src_op.tensor()->getType().dyn_cast<RankedTensorType>().getRank(); ++i) {
sizes.push_back(builder_->MakeDimOp(target_src_op.tensor(), i));
}
std::vector<mlir::Value*> dsrc_idxs;
for (const auto& dim : target_src_op.dims()) {
dsrc_idxs.push_back(dim);
}
std::string new_name;
// TODO: Currently names are broken
// auto src_name = op.name();
// if (src_name) {
// new_name = llvm::formatv("d{0}", op.name()).str();
// } // else use the empty string (already initialized by default ctor)
auto dop_val = builder_->MakeContractionOp( //
util::AggregationKind::add, //
combo_kind, //
new_srcs, //
builder_->MakeAffineSinkIndexMapOp(dsrc_idxs), //
builder_->MakeAffineSizeMapOp(sizes), //
new_name);
// Copy the constraints from the forward pass contraction
auto src_cons = llvm::dyn_cast<AffineConstraintsOp>(op.cons()->getDefiningOp());
auto dop = llvm::dyn_cast<SymbolicContractionOp>(dop_val->getDefiningOp());
auto dst_cons = llvm::dyn_cast<AffineConstraintsOp>(dop.cons()->getDefiningOp());
mlir::SmallVector<mlir::Value*, 6> pairs{src_cons.pairs()};
for (const auto& pair : src_cons.pairs()) {
pairs.emplace_back(pair);
}
dst_cons.getOperation()->setOperands(pairs);
return dop_val;
}
mlir::Value* Gradient::DeriveSpecial(const mlir::Value* dout, SpecialOp* op, size_t idx) {
throw std::runtime_error("Made it to DeriveSpecial!");
}
} // namespace pmlc::dialect::tile
<commit_msg>Fix signedness for compiler<commit_after>// Copyright 2019 Intel Corporation.
#include "pmlc/dialect/tile/gradient.h"
#include "llvm/ADT/SetVector.h"
#include "llvm/Support/FormatVariadic.h"
#include "mlir/Support/DebugStringHelper.h"
#include "base/util/logging.h"
#include "pmlc/dialect/tile/builder.h"
#include "pmlc/dialect/tile/ops.h"
#include "pmlc/util/slice.h"
namespace pmlc::dialect::tile {
Gradient::Gradient(mlir::Value* loss, TileBuilder* builder) : builder_(builder) {
IVLOG(3, "Gradient::Gradient> loss: " << mlir::debugString(*loss));
grads_[loss] = builder_->MakeScalarConstantOp(1.0);
llvm::SetVector<mlir::Value*> loss_setvec;
loss_setvec.insert(loss);
auto defs = util::getBackwardSlice(loss_setvec, false, std::function<bool(mlir::Value*)>{[](mlir::Value* val) {
auto op = val->getDefiningOp();
// TODO: This is an ad hoc list of what to filter out; make it principled
return !mlir::isa<AffineConstraintsOp>(op) && !mlir::isa<AffineMapOp>(op) &&
!mlir::isa<AffineIndexOp>(op) && !mlir::isa<DimOp>(op) &&
!mlir::isa<AffineConstantOp>(op) && !mlir::isa<AffineAddOp>(op) &&
!mlir::isa<AffineDivOp>(op) && !mlir::isa<AffineMulOp>(op) &&
!mlir::isa<AffineNegOp>(op) && !mlir::isa<AffineSubOp>(op) &&
!mlir::isa<AffineMaxOp>(op) && !mlir::isa<AffineMinOp>(op) &&
!mlir::isa<eltwise::ScalarConstantOp>(op);
}});
for (auto def = defs.rbegin(); def != defs.rend(); def++) {
ComputeOperandDerivs(*def);
}
if (VLOG_IS_ON(5)) {
IVLOG(5, "Gradient::Gradient> Computed the following gradients: ");
for (auto [key, value] : grads_) {
IVLOG(5, " key is " << mlir::debugString(*key) << "\n for val " << mlir::debugString(*value));
}
}
}
void Gradient::AddToGradient(Value* source_op, Value* deriv) {
// Adds the gradient `deriv` computed for one use of `source_op` to the overall gradient of `source_op`
if (!grads_.count(source_op)) {
grads_[source_op] = deriv;
} else {
grads_[source_op] = builder_->MakePrimitiveOp("add", {grads_[source_op], deriv});
}
}
void Gradient::ComputeOperandDerivs(mlir::Value* val) {
IVLOG(4, "Gradient::ComputeDerivative> " << mlir::debugString(*val));
// TODO: Throw on ops with multiple results?
auto op = val->getDefiningOp();
if (mlir::isa<AffineConstraintsOp>(op) || mlir::isa<AffineMapOp>(op) || mlir::isa<AffineIndexOp>(op) ||
mlir::isa<PrngOp>(op) || mlir::isa<ShapeOp>(op)) {
// TODO: Make the list of which ops these are more principled. Also, should these all be caught in the backwards
// slice filter? If so, probably throw here.
IVLOG(6, "Gradient::ComputeDerivative> Skipping computing derivatives for op "
<< mlir::debugString(*op) << ", as it is not a type of op for which gradients apply");
return;
}
if (!grads_.count(val)) {
IVLOG(1, "Gradient::ComputeOperandDerivs> Called on Value which has not itself been differentiated: "
<< mlir::debugString(*val));
throw std::runtime_error("Unexpected missing derivative in ComputeOperandDerivs");
}
if (mlir::isa<eltwise::EltwiseOp>(op)) {
size_t idx = 0; // Need to track which operand we're at
for (const auto& operand : op->getOperands()) {
auto dop = DeriveEltwise(grads_[val], val, idx);
AddToGradient(operand, dop);
idx++;
}
// TODO: if grads_[operand] has rank > 0, call a simple_reduce
} else if (auto cion_op = mlir::dyn_cast<SymbolicContractionOp>(op)) {
{
// TODO: I discussed this with Jeremy and I think the below notes are wrong, but we need another discussion.
// TODO: Do `init` deriv right: we should passthrough on plus, conditional against result on max/min, throw on
// product
// TODO: This is a temporary hack!
AddToGradient(cion_op.init(), grads_[val]);
}
size_t idx = 0; // Need to track which operand we're at
for (auto src : cion_op.srcs()) {
auto dop = DeriveContraction(grads_[val], val, idx);
AddToGradient(src, dop);
idx++;
}
} else if (auto gather_op = mlir::dyn_cast<GatherOp>(op)) {
auto tensor_input = gather_op.tensor();
auto dims_input = gather_op.dims();
auto dop = builder_->MakePrimitiveOp("scatter", {grads_[val], dims_input, tensor_input});
auto zero_op = builder_->MakeScalarConstantOp(0.);
AddToGradient(tensor_input, dop);
AddToGradient(dims_input, zero_op);
} else if (mlir::isa<ScatterOp>(op)) {
// TODO
throw std::runtime_error("TODO: Derivs of Scatter not yet implemented");
} else if (auto reshape_op = mlir::dyn_cast<ReshapeOp>(op)) {
auto tensor_input = reshape_op.tensor();
std::vector<mlir::Value*> args{grads_[val]};
for (int i = 0; i < tensor_input->getType().dyn_cast<RankedTensorType>().getRank(); ++i) {
args.push_back(builder_->MakeDimOp(tensor_input, i));
}
auto dop = builder_->MakePrimitiveOp("reshape", args);
AddToGradient(tensor_input, dop);
} else if (mlir::isa<SpecialOp>(op)) {
throw std::runtime_error("Unrecognized special operation, unable to differentiate");
} else if (mlir::isa<DimOp>(op) || mlir::isa<eltwise::ScalarConstantOp>(op)) {
auto dop = builder_->MakeScalarConstantOp(0.);
for (const auto& operand : op->getOperands()) {
AddToGradient(operand, dop);
}
} else if (auto tmap_op = mlir::dyn_cast<AffineTensorMapOp>(op)) {
// Just forward the gradient in a tmap to the tensor
AddToGradient(tmap_op.tensor(), grads_[val]);
} else {
if (op->getNumOperands()) {
throw std::runtime_error("Unexpected Operation type in ComputeOperandDerivs! Operation is " +
mlir::debugString(*op));
}
// If it has no operands, it doesn't matter whether we can differentiate it, so we do nothing
}
}
mlir::Value* Gradient::GetDerivative(mlir::Value* val) {
IVLOG(5, "Gradient::GetDerivative> " << mlir::debugString(*val));
auto it = grads_.find(val);
if (it != grads_.end()) {
IVLOG(6, " Gradient::GetDerivative> Derivative retrieved: " << mlir::debugString(*it->second));
return it->second;
}
// TODO:
// In the long run, this should probably just return 0 or otherwise indicate a continuation
// For now, I want to know if we hit this (as we shouldn't in most cases)
IVLOG(1, "Gradient::GetDerivative> The requested derivative of " << mlir::debugString(*val) << " was not computed!");
throw std::runtime_error("TODO: requested derivative not from getBackwardSlice");
}
mlir::Value* Gradient::DeriveEltwise(mlir::Value* dout, mlir::Value* out, size_t idx) {
auto op = out->getDefiningOp();
IVLOG(5, "Gradient::DeriveEltwise> dout=" << mlir::debugString(*dout) << ", op=" << mlir::debugString(*op)
<< ", idx=" << idx);
auto deriv = DerivRegistry::Instance()->Resolve(op->getName().getStringRef());
llvm::SmallVector<mlir::Value*, 3> operands{op->getOperands()}; // TODO: Size
// TODO: Need to add simple_reduce here, unless done in the "if isa EltwiseOp" block above
return deriv.fn(out, dout, operands, deriv.user_fn, deriv.user_ctx)[idx];
}
mlir::Value* Gradient::DeriveContraction(mlir::Value* dout, mlir::Value* out, size_t idx) {
IVLOG(5, "Gradient::DeriveContraction> dout=" << mlir::debugString(*dout) << ", out=" << mlir::debugString(*out)
<< ", idx=" << idx);
auto op = llvm::dyn_cast_or_null<SymbolicContractionOp>(out->getDefiningOp());
if (!op) {
throw std::runtime_error("DeriveContraction called on non-contraction");
}
if (op.combo() == util::CombinationKind::eq) {
// TODO: What type should this 0 be?
return builder_->MakeScalarConstantOp(0.);
}
auto combo_kind = util::CombinationKind::none; // This may be reset later if necessary
std::vector<Value*> new_srcs;
Value* target_src = nullptr;
switch (op.agg()) {
case util::AggregationKind::max:
case util::AggregationKind::min: {
size_t i = 0;
// TODO: Is there a better option to do "Get the unique src (or throw if not unique)"?
for (auto src : op.srcs()) {
if (i == idx) {
combo_kind = util::CombinationKind::cond;
auto src_op = mlir::dyn_cast_or_null<AffineTensorMapOp>(src->getDefiningOp());
if (!src_op) {
throw std::runtime_error("src_op as cast is null");
}
new_srcs.push_back(src_op);
std::vector<Value*> dout_idxs;
for (const auto& dim : llvm::cast<AffineMapOp>(op.sink()->getDefiningOp()).dims()) {
dout_idxs.push_back(dim);
}
new_srcs.push_back(builder_->MakeAffineSourceIndexMapOp(op, dout_idxs));
new_srcs.push_back(builder_->MakeAffineSourceIndexMapOp(dout, dout_idxs));
// Also track that this is the differentiated source for later use
target_src = src;
} else {
throw std::runtime_error("Cannot differentiate max/min contractions with multiple input tensors");
}
i++;
}
} break;
case util::AggregationKind::add:
case util::AggregationKind::assign: {
size_t i = 0;
for (auto src : op.srcs()) {
if (i == idx) {
// This is the differentiated input; so swap in dout here to create the new op
std::vector<Value*> dout_idxs;
for (const auto& dim : llvm::cast<AffineMapOp>(op.sink()->getDefiningOp()).dims()) {
dout_idxs.push_back(dim);
}
new_srcs.push_back(builder_->MakeAffineSourceIndexMapOp(dout, dout_idxs));
// Also track that this is the differentiated source for later use
target_src = src;
} else {
// This is the non-differentiated input; behavior depends on combo op
switch (op.combo()) {
case util::CombinationKind::none:
IVLOG(1, "About to fail on a NONE combo, with idx==" << idx << ", and i==" << i);
throw std::runtime_error(
"Unexpected multiple inputs found when differentiating contraction with NONE combination op");
break;
case util::CombinationKind::add:
// For +, we ignore the non-differentiated input
combo_kind = util::CombinationKind::none;
break;
case util::CombinationKind::cond:
throw std::runtime_error("Gradient of sum of conditionals not supported");
break;
case util::CombinationKind::eq:
throw std::logic_error("Gradient unexpectedly failed to detect combo op as equality");
break;
case util::CombinationKind::mul:
// For *, we multiply by the non-differentiated input
new_srcs.push_back(src);
combo_kind = util::CombinationKind::mul;
break;
default:
throw std::runtime_error("Failed to recognize combination op during differentiation");
}
}
i++;
}
} break;
case util::AggregationKind::mul:
throw std::runtime_error("Cannot differentiate multiplication aggregations");
break;
default:
throw std::runtime_error("Did not recognize aggregation operation when differentiating " +
mlir::debugString(*out));
}
if (!target_src) {
throw std::runtime_error(
llvm::formatv("Trying to derive contraction at out of range index (requested source operand {0})", idx).str());
}
auto target_src_op = llvm::cast<AffineTensorMapOp>(target_src->getDefiningOp());
std::vector<mlir::Value*> sizes;
for (int i = 0; i < target_src_op.tensor()->getType().dyn_cast<RankedTensorType>().getRank(); ++i) {
sizes.push_back(builder_->MakeDimOp(target_src_op.tensor(), i));
}
std::vector<mlir::Value*> dsrc_idxs;
for (const auto& dim : target_src_op.dims()) {
dsrc_idxs.push_back(dim);
}
std::string new_name;
// TODO: Currently names are broken
// auto src_name = op.name();
// if (src_name) {
// new_name = llvm::formatv("d{0}", op.name()).str();
// } // else use the empty string (already initialized by default ctor)
auto dop_val = builder_->MakeContractionOp( //
util::AggregationKind::add, //
combo_kind, //
new_srcs, //
builder_->MakeAffineSinkIndexMapOp(dsrc_idxs), //
builder_->MakeAffineSizeMapOp(sizes), //
new_name);
// Copy the constraints from the forward pass contraction
auto src_cons = llvm::dyn_cast<AffineConstraintsOp>(op.cons()->getDefiningOp());
auto dop = llvm::dyn_cast<SymbolicContractionOp>(dop_val->getDefiningOp());
auto dst_cons = llvm::dyn_cast<AffineConstraintsOp>(dop.cons()->getDefiningOp());
mlir::SmallVector<mlir::Value*, 6> pairs{src_cons.pairs()};
for (const auto& pair : src_cons.pairs()) {
pairs.emplace_back(pair);
}
dst_cons.getOperation()->setOperands(pairs);
return dop_val;
}
mlir::Value* Gradient::DeriveSpecial(const mlir::Value* dout, SpecialOp* op, size_t idx) {
throw std::runtime_error("Made it to DeriveSpecial!");
}
} // namespace pmlc::dialect::tile
<|endoftext|>
|
<commit_before>// DeceiverPlayer by Sxntk
// PPCG: http://codegolf.stackexchange.com/a/104972/11933
// DeceiverPlayer.hpp
// If we have two shoots, better shoot one by one
#ifndef __DECEPTIVE_PLAYER_HPP__
#define __DECEPTIVE_PLAYER_HPP__
#include "Player.hpp"
class DeceptivePlayer final : public Player
{
public:
DeceptivePlayer(size_t opponent = -1) : Player(opponent) {}
public:
virtual Action fight()
{
int ammo = getAmmo();
int opponentAmmo = getAmmoOpponent();
int turn = getTurn();
// Without ammo, always load
if (ammo == 0)
{
return load();
}
// Every 10 turns the Deceiver goes crazy
if (turn % 10)
{
// Generate random integer in [0, 5)
int random = GetRandomInteger() % 5;
switch (random)
{
case 0:
return bullet();
case 1:
return metal();
case 2:
if (ammo == 1)
{
return bullet();
}
return plasma();
case 3:
return thermal();
case 4:
return load();
}
}
// The Deceiver shoots one bullet
if (ammo == 2)
{
return bullet();
}
// Protect until we can get bullet 2
if (opponentAmmo == 0)
{
return load();
}
if (opponentAmmo == 1)
{
return metal();
}
if (opponentAmmo == 2)
{
return thermal();
}
}
};
#endif // !__DECEPTIVE_PLAYER_HPP__<commit_msg>Update DeceptivePlayer according to main post.<commit_after>// DeceiverPlayer by Sxntk
// PPCG: http://codegolf.stackexchange.com/a/104972/11933
// DeceiverPlayer.hpp
// If we have two shoots, better shoot one by one
#ifndef __DECEIVER_PLAYER_HPP__
#define __DECEPTIVE_PLAYER_HPP__
#include "Player.hpp"
class DeceptivePlayer final : public Player
{
public:
DeceptivePlayer(size_t opponent = -1) : Player(opponent) {}
public:
virtual Action fight()
{
int ammo = getAmmo();
int opponentAmmo = getAmmoOpponent();
int turn = getTurn();
// Without ammo, always load
if (ammo == 0)
{
return load();
}
// Every 10 turns the Deceiver goes crazy
if (turn % 10 || opponentAmmo >= 3)
{
// Generate random integer in [0, 5)
int random = GetRandomInteger() % 5;
switch (random)
{
case 0:
return bullet();
case 1:
return metal();
case 2:
if (ammo == 1)
{
return bullet();
}
return plasma();
case 3:
return thermal();
case 4:
return load();
}
}
// The Deceiver shoots one bullet
if (ammo == 2)
{
return bullet();
}
// Protect until we can get bullet 2
if (opponentAmmo == 0)
{
return load();
}
if (opponentAmmo == 1)
{
return metal();
}
if (opponentAmmo == 2)
{
return thermal();
}
}
};
#endif // !__DECEPTIVE_PLAYER_HPP__<|endoftext|>
|
<commit_before>#include <iostream>
#include <cstdio>
#include <QApplication>
#include <QtUiTools>
#include "med.hpp"
using namespace std;
class MainUi : public QObject {
Q_OBJECT
public:
MainUi() {
loadUiFiles();
}
Med med;
private slots:
void onProcessClicked() {
med.listProcesses();
processDialog->show();
//Get the tree widget
QTreeWidget* procTreeWidget = chooseProc->findChild<QTreeWidget*>("procTreeWidget");
procTreeWidget->clear(); //Remove all items
//Add all the process into the tree widget
for(int i=med.processes.size()-1;i>=0;i--) {
QTreeWidgetItem* item = new QTreeWidgetItem(procTreeWidget);
item->setText(0, med.processes[i].pid.c_str());
item->setText(1, med.processes[i].cmdline.c_str());
}
}
void onProcItemDblClicked(QTreeWidgetItem* item, int column) {
int index = item->treeWidget()->indexOfTopLevelItem(item); //Get the current row index
med.selectedProcess = med.processes[med.processes.size() -1 - index];
//Make changes to the selectedProc and hide the window
QLineEdit* line = this->mainWindow->findChild<QLineEdit*>("selectedProc");
line->setText(QString::fromLatin1((med.selectedProcess.pid + " " + med.selectedProcess.cmdline).c_str())); //Do not use fromStdString(), it will append with some unknown characters
processDialog->hide();
}
void onScanClicked() {
QTreeWidget* scanTreeWidget = mainWindow->findChild<QTreeWidget*>("scanTreeWidget");
scanTreeWidget->clear();
//Get scanned type
string scanType = mainWindow->findChild<QComboBox*>("scanType")->currentText().toStdString();
string scanValue = mainWindow->findChild<QLineEdit*>("scanEntry")->text().toStdString();
if(med.selectedProcess.pid == "") {
cerr << "No process seelcted " <<endl;
return;
}
try {
med.scanEqual(scanValue, scanType);
} catch(string e) {
cerr << "scan: "<<e<<endl;
}
if(med.scanAddresses.size() <= 800) {
addressToScanTreeWidget(med, scanType, scanTreeWidget);
}
updateNumberOfAddresses(mainWindow);
}
void onFilterClicked() {
QTreeWidget* scanTreeWidget = mainWindow->findChild<QTreeWidget*>("scanTreeWidget");
scanTreeWidget->clear();
//Get scanned type
string scanType = mainWindow->findChild<QComboBox*>("scanType")->currentText().toStdString();
string scanValue = mainWindow->findChild<QLineEdit*>("scanEntry")->text().toStdString();
med.scanFilter(scanValue, scanType);
if(med.scanAddresses.size() <= 800)
addressToScanTreeWidget(med, scanType, scanTreeWidget);
updateNumberOfAddresses(mainWindow);
}
void onClearClicked() {
mainWindow->findChild<QTreeWidget*>("scanTreeWidget")->clear();
med.scanAddresses.clear();
mainWindow->findChild<QStatusBar*>("statusbar")->showMessage("Scan cleared");
}
private:
QWidget* mainWindow;
QWidget* chooseProc;
QDialog* processDialog;
void loadUiFiles() {
QUiLoader loader;
QFile file("./main-qt.ui");
file.open(QFile::ReadOnly);
mainWindow = loader.load(&file);
file.close();
//Cannot put the followings to another method
processDialog = new QDialog(mainWindow); //If put this to another method, then I cannot set the mainWindow as the parent
QFile processFile("./process.ui");
processFile.open(QFile::ReadOnly);
chooseProc = loader.load(&processFile, processDialog);
processFile.close();
QVBoxLayout* layout = new QVBoxLayout();
layout->addWidget(chooseProc);
processDialog->setLayout(layout);
processDialog->setModal(true);
processDialog->resize(400, 400);
//Statusbar meesage
QStatusBar* statusBar = mainWindow->findChild<QStatusBar*>("statusbar");
statusBar->showMessage("Tips: Left panel is scanned address. Right panel is stored address.");
//Add signal
QTreeWidget* procTreeWidget = chooseProc->findChild<QTreeWidget*>("procTreeWidget");
QObject::connect(procTreeWidget, SIGNAL(itemDoubleClicked(QTreeWidgetItem*, int)), this, SLOT(onProcItemDblClicked(QTreeWidgetItem*, int)));
procTreeWidget->installEventFilter(this);
//TODO: center
mainWindow->show();
//Add signal to the process
QWidget* process = mainWindow->findChild<QWidget*>("process");
QObject::connect(process, SIGNAL(clicked()), this, SLOT(onProcessClicked()));
//Add signal to scan
QWidget* scanButton = mainWindow->findChild<QWidget*>("scanButton");
QObject::connect(scanButton, SIGNAL(clicked()), this, SLOT(onScanClicked()));
QWidget* filterButton = mainWindow->findChild<QWidget*>("filterButton");
QObject::connect(filterButton, SIGNAL(clicked()), this, SLOT(onFilterClicked()));
QObject::connect(
mainWindow->findChild<QWidget*>("scanClear"),
SIGNAL(clicked()),
this,
SLOT(onClearClicked())
);
}
bool eventFilter(QObject* obj, QEvent* ev) {
QTreeWidget* procTreeWidget = chooseProc->findChild<QTreeWidget*>("procTreeWidget");
if(obj == procTreeWidget && ev->type() == QEvent::KeyRelease) {
if(static_cast<QKeyEvent*>(ev)->key() == Qt::Key_Return) { //Use Return instead of Enter
onProcItemDblClicked(procTreeWidget->currentItem(), 0); //Just use the first column
}
}
}
void addressToScanTreeWidget(Med med, string scanType, QTreeWidget* scanTreeWidget) {
for(int i=0;i<med.scanAddresses.size();i++) {
char address[32];
sprintf(address, "%p", (void*)(med.scanAddresses[i].address));
//Get the value from address and type
string value = med.getScanAddressValueByIndex(i, scanType);
QTreeWidgetItem* item = new QTreeWidgetItem(scanTreeWidget);
item->setText(0, address);
item->setText(1, scanType.c_str());
item->setText(2, value.c_str());
}
}
void updateNumberOfAddresses(QWidget* mainWindow) {
char message[128];
sprintf(message, "%ld addresses found", med.scanAddresses.size());
mainWindow->findChild<QStatusBar*>("statusbar")->showMessage(message);
}
};
int main(int argc, char **argv) {
QApplication app(argc, argv);
MainUi* mainUi = new MainUi();
return app.exec();
}
#include "main-qt.moc"
<commit_msg>Edit scan value<commit_after>#include <iostream>
#include <cstdio>
#include <QApplication>
#include <QtUiTools>
#include "med.hpp"
using namespace std;
class MainUi : public QObject {
Q_OBJECT
public:
MainUi() {
loadUiFiles();
}
Med med;
private slots:
void onProcessClicked() {
med.listProcesses();
processDialog->show();
//Get the tree widget
QTreeWidget* procTreeWidget = chooseProc->findChild<QTreeWidget*>("procTreeWidget");
procTreeWidget->clear(); //Remove all items
//Add all the process into the tree widget
for(int i=med.processes.size()-1;i>=0;i--) {
QTreeWidgetItem* item = new QTreeWidgetItem(procTreeWidget);
item->setText(0, med.processes[i].pid.c_str());
item->setText(1, med.processes[i].cmdline.c_str());
}
}
void onProcItemDblClicked(QTreeWidgetItem* item, int column) {
int index = item->treeWidget()->indexOfTopLevelItem(item); //Get the current row index
med.selectedProcess = med.processes[med.processes.size() -1 - index];
//Make changes to the selectedProc and hide the window
QLineEdit* line = this->mainWindow->findChild<QLineEdit*>("selectedProc");
line->setText(QString::fromLatin1((med.selectedProcess.pid + " " + med.selectedProcess.cmdline).c_str())); //Do not use fromStdString(), it will append with some unknown characters
processDialog->hide();
}
void onScanClicked() {
QTreeWidget* scanTreeWidget = mainWindow->findChild<QTreeWidget*>("scanTreeWidget");
scanTreeWidget->clear();
//Get scanned type
string scanType = mainWindow->findChild<QComboBox*>("scanType")->currentText().toStdString();
string scanValue = mainWindow->findChild<QLineEdit*>("scanEntry")->text().toStdString();
if(med.selectedProcess.pid == "") {
cerr << "No process seelcted " <<endl;
return;
}
try {
med.scanEqual(scanValue, scanType);
} catch(string e) {
cerr << "scan: "<<e<<endl;
}
if(med.scanAddresses.size() <= 800) {
addressToScanTreeWidget(med, scanType, scanTreeWidget);
}
updateNumberOfAddresses(mainWindow);
}
void onFilterClicked() {
QTreeWidget* scanTreeWidget = mainWindow->findChild<QTreeWidget*>("scanTreeWidget");
scanTreeWidget->clear();
//Get scanned type
string scanType = mainWindow->findChild<QComboBox*>("scanType")->currentText().toStdString();
string scanValue = mainWindow->findChild<QLineEdit*>("scanEntry")->text().toStdString();
med.scanFilter(scanValue, scanType);
if(med.scanAddresses.size() <= 800)
addressToScanTreeWidget(med, scanType, scanTreeWidget);
updateNumberOfAddresses(mainWindow);
}
void onClearClicked() {
mainWindow->findChild<QTreeWidget*>("scanTreeWidget")->clear();
med.scanAddresses.clear();
mainWindow->findChild<QStatusBar*>("statusbar")->showMessage("Scan cleared");
}
void onScanItemChanged(QTreeWidgetItem* item, int column) {
switch(column) {
case 2:
editScanValue(item, column);
break;
}
}
private:
QWidget* mainWindow;
QWidget* chooseProc;
QDialog* processDialog;
void loadUiFiles() {
QUiLoader loader;
QFile file("./main-qt.ui");
file.open(QFile::ReadOnly);
mainWindow = loader.load(&file);
file.close();
//Cannot put the followings to another method
processDialog = new QDialog(mainWindow); //If put this to another method, then I cannot set the mainWindow as the parent
QFile processFile("./process.ui");
processFile.open(QFile::ReadOnly);
chooseProc = loader.load(&processFile, processDialog);
processFile.close();
QVBoxLayout* layout = new QVBoxLayout();
layout->addWidget(chooseProc);
processDialog->setLayout(layout);
processDialog->setModal(true);
processDialog->resize(400, 400);
//Statusbar meesage
QStatusBar* statusBar = mainWindow->findChild<QStatusBar*>("statusbar");
statusBar->showMessage("Tips: Left panel is scanned address. Right panel is stored address.");
//Add signal
QTreeWidget* procTreeWidget = chooseProc->findChild<QTreeWidget*>("procTreeWidget");
QObject::connect(procTreeWidget, SIGNAL(itemDoubleClicked(QTreeWidgetItem*, int)), this, SLOT(onProcItemDblClicked(QTreeWidgetItem*, int)));
procTreeWidget->installEventFilter(this);
//TODO: center
mainWindow->show();
//Add signal to the process
QWidget* process = mainWindow->findChild<QWidget*>("process");
QObject::connect(process, SIGNAL(clicked()), this, SLOT(onProcessClicked()));
//Add signal to scan
QWidget* scanButton = mainWindow->findChild<QWidget*>("scanButton");
QObject::connect(scanButton, SIGNAL(clicked()), this, SLOT(onScanClicked()));
QWidget* filterButton = mainWindow->findChild<QWidget*>("filterButton");
QObject::connect(filterButton, SIGNAL(clicked()), this, SLOT(onFilterClicked()));
QObject::connect(mainWindow->findChild<QWidget*>("scanClear"),
SIGNAL(clicked()),
this,
SLOT(onClearClicked())
);
//Add signal
QObject::connect(mainWindow->findChild<QTreeWidget*>("scanTreeWidget"),
SIGNAL(itemChanged(QTreeWidgetItem*, int)),
this,
SLOT(onScanItemChanged(QTreeWidgetItem*, int))
);
}
bool eventFilter(QObject* obj, QEvent* ev) {
QTreeWidget* procTreeWidget = chooseProc->findChild<QTreeWidget*>("procTreeWidget");
if(obj == procTreeWidget && ev->type() == QEvent::KeyRelease) {
if(static_cast<QKeyEvent*>(ev)->key() == Qt::Key_Return) { //Use Return instead of Enter
onProcItemDblClicked(procTreeWidget->currentItem(), 0); //Just use the first column
}
}
}
void addressToScanTreeWidget(Med med, string scanType, QTreeWidget* scanTreeWidget) {
for(int i=0;i<med.scanAddresses.size();i++) {
char address[32];
sprintf(address, "%p", (void*)(med.scanAddresses[i].address));
//Get the value from address and type
string value = med.getScanAddressValueByIndex(i, scanType);
QTreeWidgetItem* item = new QTreeWidgetItem(scanTreeWidget);
item->setText(0, address);
item->setText(1, scanType.c_str());
item->setText(2, value.c_str());
item->setFlags(item->flags() | (Qt::ItemIsEditable));
}
}
void updateNumberOfAddresses(QWidget* mainWindow) {
char message[128];
sprintf(message, "%ld addresses found", med.scanAddresses.size());
mainWindow->findChild<QStatusBar*>("statusbar")->showMessage(message);
}
void editScanValue(QTreeWidgetItem* item, int column) {
int index = item->treeWidget()->indexOfTopLevelItem(item);
string text = item->text(column).toStdString();
if(med.selectedProcess.pid == "") {
cerr<< "No PID" <<endl;
return;
}
try {
med.setValueByAddress(med.scanAddresses[index].address,
text,
med.scanAddresses[index].getScanType());
} catch(string e) {
cerr << "editScanValue: "<<e<<endl;
}
}
};
int main(int argc, char **argv) {
QApplication app(argc, argv);
MainUi* mainUi = new MainUi();
return app.exec();
}
#include "main-qt.moc"
<|endoftext|>
|
<commit_before>#include <iostream>
#include <sstream>
#include <string>
#include <sys/types.h>
#include <sys/stat.h>
#include <unistd.h>
#include "classifierio.hpp"
using namespace std;
ClassifierIO::ClassifierIO(int dirNum, int stageNum)
{
_dirNum = dirNum;
_stageNum = stageNum;
}
// given a directory number generate a filename for that dir
// if it exists - if it doesnt, return an empty string
string ClassifierIO::getClassifierDir() const
{
struct stat fileStat;
stringstream ss;
ss << "/cygdrive/a/2015VisionCode/cascade_training/classifier_bin_";
ss << _dirNum;
if ((stat(ss.str().c_str(), &fileStat) == 0) && S_ISDIR(fileStat.st_mode))
return string(ss.str());
return string();
}
// given a directory number and stage within that directory
// generate a filename to load the cascade from. Check that
// the file exists - if it doesnt, return an empty string
string ClassifierIO::getClassifierName() const
{
struct stat fileStat;
stringstream ss;
string dirName = getClassifierDir();
if (!dirName.length())
return string();
ss << dirName;
ss << "/cascade_oldformat_";
ss << _stageNum;
ss << ".xml";
if ((stat(ss.str().c_str(), &fileStat) == 0) && (fileStat.st_size > 5000))
return string(ss.str());
// Try the non-oldformat one next
ss.str(string());
ss.clear();
ss << dirName;
ss << "/cascade_";
ss << _stageNum;
ss << ".xml";
if ((stat(ss.str().c_str(), &fileStat) == 0) && (fileStat.st_size > 5000))
return string(ss.str());
// Found neither? Return an empty string
return string();
}
// Find the next valid classifier. Since some .xml input
// files crash the GPU we've deleted them. Skip over missing
// files in the sequence
bool ClassifierIO::findNextClassifierStage(bool increment)
{
int adder = increment ? 1 : -1;
int num = _stageNum + adder;
bool found;
for (found = false; !found && ((num > 0) && (num < 100)); num += adder)
{
ClassifierIO tempClassifier(_dirNum, num);
if (tempClassifier.getClassifierName().length())
{
*this = tempClassifier;
found = true;
}
}
return found;
}
// Find the next valid classifier dir. Start with current stage in that
// directory and work down until a classifier is found
bool ClassifierIO::findNextClassifierDir(bool increment)
{
int adder = increment ? 1 : -1;
int dnum = _dirNum + adder;
bool found;
for (found = false; !found && ((dnum > 0) && (dnum < 100)); dnum += adder)
{
ClassifierIO tempClassifier(dnum, _stageNum+1);
if (tempClassifier.getClassifierDir().length())
{
// Try to find a valid classifier in this dir, counting
// down from the current stage number
if (tempClassifier.findNextClassifierStage(false))
{
*this = tempClassifier;
found = true;
}
}
}
return found;
}
int ClassifierIO::dirNum(void) const
{
return _dirNum;
}
int ClassifierIO::stageNum(void) const
{
return _stageNum;
}
<commit_msg>Fix path to classifier info<commit_after>#include <iostream>
#include <sstream>
#include <string>
#include <sys/types.h>
#include <sys/stat.h>
#include <unistd.h>
#include "classifierio.hpp"
using namespace std;
ClassifierIO::ClassifierIO(int dirNum, int stageNum)
{
_dirNum = dirNum;
_stageNum = stageNum;
}
// given a directory number generate a filename for that dir
// if it exists - if it doesnt, return an empty string
string ClassifierIO::getClassifierDir() const
{
struct stat fileStat;
stringstream ss;
ss << "/home/ubuntu/2015VisionCode/cascade_training/classifier_bin_";
ss << _dirNum;
if ((stat(ss.str().c_str(), &fileStat) == 0) && S_ISDIR(fileStat.st_mode))
return string(ss.str());
return string();
}
// given a directory number and stage within that directory
// generate a filename to load the cascade from. Check that
// the file exists - if it doesnt, return an empty string
string ClassifierIO::getClassifierName() const
{
struct stat fileStat;
stringstream ss;
string dirName = getClassifierDir();
if (!dirName.length())
return string();
ss << dirName;
ss << "/cascade_oldformat_";
ss << _stageNum;
ss << ".xml";
if ((stat(ss.str().c_str(), &fileStat) == 0) && (fileStat.st_size > 5000))
return string(ss.str());
// Try the non-oldformat one next
ss.str(string());
ss.clear();
ss << dirName;
ss << "/cascade_";
ss << _stageNum;
ss << ".xml";
if ((stat(ss.str().c_str(), &fileStat) == 0) && (fileStat.st_size > 5000))
return string(ss.str());
// Found neither? Return an empty string
return string();
}
// Find the next valid classifier. Since some .xml input
// files crash the GPU we've deleted them. Skip over missing
// files in the sequence
bool ClassifierIO::findNextClassifierStage(bool increment)
{
int adder = increment ? 1 : -1;
int num = _stageNum + adder;
bool found;
for (found = false; !found && ((num > 0) && (num < 100)); num += adder)
{
ClassifierIO tempClassifier(_dirNum, num);
if (tempClassifier.getClassifierName().length())
{
*this = tempClassifier;
found = true;
}
}
return found;
}
// Find the next valid classifier dir. Start with current stage in that
// directory and work down until a classifier is found
bool ClassifierIO::findNextClassifierDir(bool increment)
{
int adder = increment ? 1 : -1;
int dnum = _dirNum + adder;
bool found;
for (found = false; !found && ((dnum > 0) && (dnum < 100)); dnum += adder)
{
ClassifierIO tempClassifier(dnum, _stageNum+1);
if (tempClassifier.getClassifierDir().length())
{
// Try to find a valid classifier in this dir, counting
// down from the current stage number
if (tempClassifier.findNextClassifierStage(false))
{
*this = tempClassifier;
found = true;
}
}
}
return found;
}
int ClassifierIO::dirNum(void) const
{
return _dirNum;
}
int ClassifierIO::stageNum(void) const
{
return _stageNum;
}
<|endoftext|>
|
<commit_before>// =================================================================== //
// Copyright (C) 2021-2022 Kimura Ryo //
// //
// This Source Code Form is subject to the terms of the Mozilla Public //
// License, v. 2.0. If a copy of the MPL was not distributed with this //
// file, You can obtain one at http://mozilla.org/MPL/2.0/. //
// =================================================================== //
#include <libbsdf/Fitter/BrdfFitter.h>
#include <ceres/ceres.h>
#include <libbsdf/Common/SpectrumUtility.h>
#include <libbsdf/Common/Utility.h>
#include <libbsdf/Common/Xorshift.h>
using namespace lb;
BrdfFitter::Data::Data(const Brdf& brdf, int numSampling, const Vec3::Scalar& maxTheta)
{
const SampleSet* ss = brdf.getSampleSet();
const Vec3::Scalar threshold = std::cos(maxTheta);
if (numSampling <= 0 || maxTheta < toRadian(Vec3::Scalar(EPSILON_F))) {
for (int i0 = 0; i0 < ss->getNumAngles0(); ++i0) {
for (int i1 = 0; i1 < ss->getNumAngles1(); ++i1) {
for (int i2 = 0; i2 < ss->getNumAngles2(); ++i2) {
for (int i3 = 0; i3 < ss->getNumAngles3(); ++i3) {
Vec3 inDir, outDir;
brdf.toXyz(ss->getAngle0(i0),
ss->getAngle1(i1),
ss->getAngle2(i2),
ss->getAngle3(i3),
&inDir, &outDir);
if (inDir[2] < threshold || outDir[2] < threshold) continue;
Sample sample;
sample.inDir = inDir;
sample.outDir = outDir;
sample.value =
toSrgb<Vec3, SampleSet>(brdf.getSpectrum(sample.inDir, sample.outDir), *ss);
samples_.push_back(sample);
}}}}
}
else {
int count = 0;
Xorshift rnd;
while (count < numSampling) {
Sample sample;
sample.inDir = rnd.nextOnHemisphere<Vec3>();
sample.outDir = rnd.nextOnHemisphere<Vec3>();
if (sample.inDir[2] < threshold || sample.outDir[2] < threshold) continue;
sample.value =
toSrgb<Vec3, SampleSet>(brdf.getSpectrum(sample.inDir, sample.outDir), *ss);
samples_.push_back(sample);
++count;
}
}
}
bool BrdfFitter::setParameterBounds(ceres::Problem* problem,
double* parameter,
const ReflectanceModel::Parameter& bounds)
{
switch (bounds.getType()) {
case ReflectanceModel::Parameter::FLOAT_PARAMETER:
problem->SetParameterLowerBound(parameter, 0, *bounds.getMinFloat());
problem->SetParameterUpperBound(parameter, 0, *bounds.getMaxFloat());
break;
case ReflectanceModel::Parameter::VEC3_PARAMETER: {
const Vec3* minVec3 = bounds.getMinVec3();
const Vec3* maxVec3 = bounds.getMaxVec3();
problem->SetParameterLowerBound(parameter, 0, (*minVec3)[0]);
problem->SetParameterLowerBound(parameter, 1, (*minVec3)[1]);
problem->SetParameterLowerBound(parameter, 2, (*minVec3)[2]);
problem->SetParameterUpperBound(parameter, 0, (*maxVec3)[0]);
problem->SetParameterUpperBound(parameter, 1, (*maxVec3)[1]);
problem->SetParameterUpperBound(parameter, 2, (*maxVec3)[2]);
break;
}
case ReflectanceModel::Parameter::INT_PARAMETER:
break;
default:
lbError << "[BrdfFitter::setParameterBounds] Invalid parameter type: " << bounds.getType();
return false;
}
return true;
}
//Vec3::Scalar BrdfFitter::computeRmse(const ReflectanceModel& model, const Data& data)
//{
// Vec3d sum = Vec3d::Zero();
// for (auto& s : data.getSamples()) {
// Vec3 diff = model.getBrdfValue(s.inDir, s.outDir) - s.value;
// sum += diff.cwiseProduct(diff);
// }
//
// Vec3d avg = sum / data.getSamples().size();
// Vec3d rmse = avg.cwiseSqrt();
// return rmse.sum();
//}
Vec3::Scalar BrdfFitter::computeError(const ReflectanceModel& model, const Data& data)
{
Vec3d sum = Vec3d::Zero();
for (auto& s : data.getSamples()) {
Vec3 diff = toLogScale(model.getBrdfValue(s.inDir, s.outDir)) - toLogScale(s.value);
sum += diff.cwiseAbs();
}
Vec3d avg = sum / data.getSamples().size();
return avg.sum();
}
<commit_msg>Fixed function location issues<commit_after>// =================================================================== //
// Copyright (C) 2021-2022 Kimura Ryo //
// //
// This Source Code Form is subject to the terms of the Mozilla Public //
// License, v. 2.0. If a copy of the MPL was not distributed with this //
// file, You can obtain one at http://mozilla.org/MPL/2.0/. //
// =================================================================== //
#include <libbsdf/Fitter/BrdfFitter.h>
#include <ceres/ceres.h>
#include <libbsdf/Common/SpectrumUtility.h>
#include <libbsdf/Common/Utility.h>
#include <libbsdf/Common/Xorshift.h>
using namespace lb;
BrdfFitter::Data::Data(const Brdf& brdf, int numSampling, const Vec3::Scalar& maxTheta)
{
const SampleSet* ss = brdf.getSampleSet();
const Vec3::Scalar threshold = std::cos(maxTheta);
if (numSampling <= 0 || maxTheta < toRadian(Vec3::Scalar(EPSILON_F))) {
for (int i0 = 0; i0 < ss->getNumAngles0(); ++i0) {
for (int i1 = 0; i1 < ss->getNumAngles1(); ++i1) {
for (int i2 = 0; i2 < ss->getNumAngles2(); ++i2) {
for (int i3 = 0; i3 < ss->getNumAngles3(); ++i3) {
Vec3 inDir, outDir;
brdf.toXyz(ss->getAngle0(i0),
ss->getAngle1(i1),
ss->getAngle2(i2),
ss->getAngle3(i3),
&inDir, &outDir);
if (inDir[2] < threshold || outDir[2] < threshold) continue;
Sample sample;
sample.inDir = inDir;
sample.outDir = outDir;
sample.value = SpectrumUtility::toSrgb<Vec3, SampleSet>(
brdf.getSpectrum(sample.inDir, sample.outDir), *ss);
samples_.push_back(sample);
}}}}
}
else {
int count = 0;
Xorshift rnd;
while (count < numSampling) {
Sample sample;
sample.inDir = rnd.nextOnHemisphere<Vec3>();
sample.outDir = rnd.nextOnHemisphere<Vec3>();
if (sample.inDir[2] < threshold || sample.outDir[2] < threshold) continue;
sample.value = SpectrumUtility::toSrgb<Vec3, SampleSet>(
brdf.getSpectrum(sample.inDir, sample.outDir), *ss);
samples_.push_back(sample);
++count;
}
}
}
bool BrdfFitter::setParameterBounds(ceres::Problem* problem,
double* parameter,
const ReflectanceModel::Parameter& bounds)
{
switch (bounds.getType()) {
case ReflectanceModel::Parameter::FLOAT_PARAMETER:
problem->SetParameterLowerBound(parameter, 0, *bounds.getMinFloat());
problem->SetParameterUpperBound(parameter, 0, *bounds.getMaxFloat());
break;
case ReflectanceModel::Parameter::VEC3_PARAMETER: {
const Vec3* minVec3 = bounds.getMinVec3();
const Vec3* maxVec3 = bounds.getMaxVec3();
problem->SetParameterLowerBound(parameter, 0, (*minVec3)[0]);
problem->SetParameterLowerBound(parameter, 1, (*minVec3)[1]);
problem->SetParameterLowerBound(parameter, 2, (*minVec3)[2]);
problem->SetParameterUpperBound(parameter, 0, (*maxVec3)[0]);
problem->SetParameterUpperBound(parameter, 1, (*maxVec3)[1]);
problem->SetParameterUpperBound(parameter, 2, (*maxVec3)[2]);
break;
}
case ReflectanceModel::Parameter::INT_PARAMETER:
break;
default:
lbError << "[BrdfFitter::setParameterBounds] Invalid parameter type: " << bounds.getType();
return false;
}
return true;
}
//Vec3::Scalar BrdfFitter::computeRmse(const ReflectanceModel& model, const Data& data)
//{
// Vec3d sum = Vec3d::Zero();
// for (auto& s : data.getSamples()) {
// Vec3 diff = model.getBrdfValue(s.inDir, s.outDir) - s.value;
// sum += diff.cwiseProduct(diff);
// }
//
// Vec3d avg = sum / data.getSamples().size();
// Vec3d rmse = avg.cwiseSqrt();
// return rmse.sum();
//}
Vec3::Scalar BrdfFitter::computeError(const ReflectanceModel& model, const Data& data)
{
Vec3d sum = Vec3d::Zero();
for (auto& s : data.getSamples()) {
Vec3 diff = toLogScale(model.getBrdfValue(s.inDir, s.outDir)) - toLogScale(s.value);
sum += diff.cwiseAbs();
}
Vec3d avg = sum / data.getSamples().size();
return avg.sum();
}
<|endoftext|>
|
<commit_before>// Copyright Daniel Wallin 2006. Use, modification and distribution is
// subject to the Boost Software License, Version 1.0. (See accompanying
// file LICENSE_1_0.txt or copy at http://www.boost.org/LICENSE_1_0.txt)
#include <libtorrent/alert.hpp>
#include <libtorrent/alert_types.hpp>
#include <boost/python.hpp>
using namespace boost::python;
using namespace libtorrent;
extern char const* alert_doc;
extern char const* alert_msg_doc;
extern char const* alert_severity_doc;
extern char const* torrent_alert_doc;
extern char const* tracker_alert_doc;
extern char const* tracker_error_alert_doc;
extern char const* tracker_warning_alert_doc;
extern char const* tracker_reply_alert_doc;
extern char const* tracker_announce_alert_doc;
extern char const* hash_failed_alert_doc;
extern char const* peer_ban_alert_doc;
extern char const* peer_error_alert_doc;
extern char const* invalid_request_alert_doc;
extern char const* peer_request_doc;
extern char const* torrent_finished_alert_doc;
extern char const* piece_finished_alert_doc;
extern char const* block_finished_alert_doc;
extern char const* block_downloading_alert_doc;
extern char const* storage_moved_alert_doc;
extern char const* torrent_deleted_alert_doc;
extern char const* torrent_paused_alert_doc;
extern char const* torrent_checked_alert_doc;
extern char const* url_seed_alert_doc;
extern char const* file_error_alert_doc;
extern char const* metadata_failed_alert_doc;
extern char const* metadata_received_alert_doc;
extern char const* listen_failed_alert_doc;
extern char const* listen_succeeded_alert_doc;
extern char const* portmap_error_alert_doc;
extern char const* portmap_alert_doc;
extern char const* fastresume_rejected_alert_doc;
extern char const* peer_blocked_alert_doc;
extern char const* scrape_reply_alert_doc;
extern char const* scrape_failed_alert_doc;
extern char const* udp_error_alert_doc;
extern char const* external_ip_alert_doc;
extern char const* save_resume_data_alert_doc;
void bind_alert()
{
using boost::noncopyable;
{
scope alert_scope = class_<alert, noncopyable>("alert", alert_doc, no_init)
.def(
"msg", &alert::msg, return_value_policy<copy_const_reference>()
, alert_msg_doc
)
.def("severity", &alert::severity, alert_severity_doc)
.def(
"__str__", &alert::msg, return_value_policy<copy_const_reference>()
, alert_msg_doc
)
;
enum_<alert::severity_t>("severity_levels")
.value("debug", alert::debug)
.value("info", alert::info)
.value("warning", alert::warning)
.value("critical", alert::critical)
.value("fatal", alert::fatal)
.value("none", alert::none)
;
}
class_<torrent_alert, bases<alert>, noncopyable>(
"torrent_alert", torrent_alert_doc, no_init
)
.def_readonly("handle", &torrent_alert::handle)
;
class_<tracker_alert, bases<torrent_alert>, noncopyable>(
"tracker_alert", tracker_alert_doc, no_init
)
.def_readonly("url", &tracker_alert::url)
;
class_<tracker_error_alert, bases<tracker_alert>, noncopyable>(
"tracker_error_alert", tracker_error_alert_doc, no_init
)
.def_readonly("times_in_row", &tracker_error_alert::times_in_row)
.def_readonly("status_code", &tracker_error_alert::status_code)
;
class_<tracker_warning_alert, bases<tracker_alert>, noncopyable>(
"tracker_warning_alert", tracker_warning_alert_doc, no_init
);
class_<tracker_reply_alert, bases<tracker_alert>, noncopyable>(
"tracker_reply_alert", tracker_reply_alert_doc, no_init
)
.def_readonly("num_peers", &tracker_reply_alert::num_peers)
;
class_<tracker_announce_alert, bases<tracker_alert>, noncopyable>(
"tracker_announce_alert", tracker_announce_alert_doc, no_init
);
class_<hash_failed_alert, bases<torrent_alert>, noncopyable>(
"hash_failed_alert", hash_failed_alert_doc, no_init
)
.def_readonly("piece_index", &hash_failed_alert::piece_index)
;
class_<peer_ban_alert, bases<torrent_alert>, noncopyable>(
"peer_ban_alert", peer_ban_alert_doc, no_init
)
.def_readonly("ip", &peer_ban_alert::ip)
;
class_<peer_error_alert, bases<alert>, noncopyable>(
"peer_error_alert", peer_error_alert_doc, no_init
)
.def_readonly("ip", &peer_error_alert::ip)
.def_readonly("pid", &peer_error_alert::pid)
;
class_<invalid_request_alert, bases<torrent_alert>, noncopyable>(
"invalid_request_alert", invalid_request_alert_doc, no_init
)
.def_readonly("ip", &invalid_request_alert::ip)
.def_readonly("request", &invalid_request_alert::request)
.def_readonly("pid", &invalid_request_alert::pid)
;
class_<peer_request>("peer_request", peer_request_doc)
.def_readonly("piece", &peer_request::piece)
.def_readonly("start", &peer_request::start)
.def_readonly("length", &peer_request::length)
.def(self == self)
;
class_<torrent_finished_alert, bases<torrent_alert>, noncopyable>(
"torrent_finished_alert", torrent_finished_alert_doc, no_init
);
class_<piece_finished_alert, bases<torrent_alert>, noncopyable>(
"piece_finished_alert", piece_finished_alert_doc, no_init
)
.def_readonly("piece_index", &piece_finished_alert::piece_index)
;
class_<block_finished_alert, bases<torrent_alert>, noncopyable>(
"block_finished_alert", block_finished_alert_doc, no_init
)
.def_readonly("block_index", &block_finished_alert::block_index)
.def_readonly("piece_index", &block_finished_alert::piece_index)
;
class_<block_downloading_alert, bases<torrent_alert>, noncopyable>(
"block_downloading_alert", block_downloading_alert_doc, no_init
)
.def_readonly("peer_speedmsg", &block_downloading_alert::peer_speedmsg)
.def_readonly("block_index", &block_downloading_alert::block_index)
.def_readonly("piece_index", &block_downloading_alert::piece_index)
;
class_<storage_moved_alert, bases<torrent_alert>, noncopyable>(
"storage_moved_alert", storage_moved_alert_doc, no_init
);
class_<torrent_deleted_alert, bases<torrent_alert>, noncopyable>(
"torrent_deleted_alert", torrent_deleted_alert_doc, no_init
);
class_<torrent_paused_alert, bases<torrent_alert>, noncopyable>(
"torrent_paused_alert", torrent_paused_alert_doc, no_init
);
class_<torrent_checked_alert, bases<torrent_alert>, noncopyable>(
"torrent_checked_alert", torrent_checked_alert_doc, no_init
);
class_<url_seed_alert, bases<torrent_alert>, noncopyable>(
"url_seed_alert", url_seed_alert_doc, no_init
)
.def_readonly("url", &url_seed_alert::url)
;
class_<file_error_alert, bases<torrent_alert>, noncopyable>(
"file_error_alert", file_error_alert_doc, no_init
)
.def_readonly("file", &file_error_alert::file)
;
class_<metadata_failed_alert, bases<torrent_alert>, noncopyable>(
"metadata_failed_alert", metadata_failed_alert_doc, no_init
);
class_<metadata_received_alert, bases<torrent_alert>, noncopyable>(
"metadata_received_alert", metadata_received_alert_doc, no_init
);
class_<listen_failed_alert, bases<alert>, noncopyable>(
"listen_failed_alert", listen_failed_alert_doc, no_init
);
class_<listen_succeeded_alert, bases<alert>, noncopyable>(
"listen_succeeded_alert", listen_succeeded_alert_doc, no_init
)
.def_readonly("endpoint", &listen_succeeded_alert::endpoint)
;
class_<portmap_error_alert, bases<alert>, noncopyable>(
"portmap_error_alert", portmap_error_alert_doc, no_init
)
.def_readonly("mapping", &portmap_error_alert::mapping)
.def_readonly("type", &portmap_error_alert::type)
;
class_<portmap_alert, bases<alert>, noncopyable>(
"portmap_alert", portmap_alert_doc, no_init
)
.def_readonly("mapping", &portmap_alert::mapping)
.def_readonly("external_port", &portmap_alert::external_port)
.def_readonly("type", &portmap_alert::type)
;
class_<fastresume_rejected_alert, bases<torrent_alert>, noncopyable>(
"fastresume_rejected_alert", fastresume_rejected_alert_doc, no_init
);
class_<peer_blocked_alert, bases<alert>, noncopyable>(
"peer_blocked_alert", peer_blocked_alert_doc, no_init
)
.def_readonly("ip", &peer_blocked_alert::ip)
;
class_<scrape_reply_alert, bases<tracker_alert>, noncopyable>(
"scrape_reply_alert", scrape_reply_alert_doc, no_init
)
.def_readonly("incomplete", &scrape_reply_alert::incomplete)
.def_readonly("complete", &scrape_reply_alert::complete)
;
class_<scrape_failed_alert, bases<tracker_alert>, noncopyable>(
"scrape_failed_alert", scrape_failed_alert_doc, no_init
);
class_<udp_error_alert, bases<alert>, noncopyable>(
"udp_error_alert", udp_error_alert_doc, no_init
)
.def_readonly("endpoint", &udp_error_alert::endpoint)
;
class_<external_ip_alert, bases<alert>, noncopyable>(
"external_ip_alert", external_ip_alert_doc, no_init
)
.def_readonly("external_address", &external_ip_alert::external_address)
;
class_<save_resume_data_alert, bases<torrent_alert>, noncopyable>(
"save_resume_data_alert", save_resume_data_alert_doc, no_init
)
.def_readonly("resume_data", &save_resume_data_alert::resume_data)
;
class_<file_renamed_alert, bases<torrent_alert>, noncopyable>(
"file_renamed_alert", no_init
)
.def_readonly("name", &file_renamed_alert::name)
;
class_<torrent_resumed_alert, bases<torrent_alert>, noncopyable>(
"torrent_resumed_alert", no_init
);
}
<commit_msg>Add state_changed_alert to python bindings<commit_after>// Copyright Daniel Wallin 2006. Use, modification and distribution is
// subject to the Boost Software License, Version 1.0. (See accompanying
// file LICENSE_1_0.txt or copy at http://www.boost.org/LICENSE_1_0.txt)
#include <libtorrent/alert.hpp>
#include <libtorrent/alert_types.hpp>
#include <boost/python.hpp>
using namespace boost::python;
using namespace libtorrent;
extern char const* alert_doc;
extern char const* alert_msg_doc;
extern char const* alert_severity_doc;
extern char const* torrent_alert_doc;
extern char const* tracker_alert_doc;
extern char const* tracker_error_alert_doc;
extern char const* tracker_warning_alert_doc;
extern char const* tracker_reply_alert_doc;
extern char const* tracker_announce_alert_doc;
extern char const* hash_failed_alert_doc;
extern char const* peer_ban_alert_doc;
extern char const* peer_error_alert_doc;
extern char const* invalid_request_alert_doc;
extern char const* peer_request_doc;
extern char const* torrent_finished_alert_doc;
extern char const* piece_finished_alert_doc;
extern char const* block_finished_alert_doc;
extern char const* block_downloading_alert_doc;
extern char const* storage_moved_alert_doc;
extern char const* torrent_deleted_alert_doc;
extern char const* torrent_paused_alert_doc;
extern char const* torrent_checked_alert_doc;
extern char const* url_seed_alert_doc;
extern char const* file_error_alert_doc;
extern char const* metadata_failed_alert_doc;
extern char const* metadata_received_alert_doc;
extern char const* listen_failed_alert_doc;
extern char const* listen_succeeded_alert_doc;
extern char const* portmap_error_alert_doc;
extern char const* portmap_alert_doc;
extern char const* fastresume_rejected_alert_doc;
extern char const* peer_blocked_alert_doc;
extern char const* scrape_reply_alert_doc;
extern char const* scrape_failed_alert_doc;
extern char const* udp_error_alert_doc;
extern char const* external_ip_alert_doc;
extern char const* save_resume_data_alert_doc;
void bind_alert()
{
using boost::noncopyable;
{
scope alert_scope = class_<alert, noncopyable>("alert", alert_doc, no_init)
.def(
"msg", &alert::msg, return_value_policy<copy_const_reference>()
, alert_msg_doc
)
.def("severity", &alert::severity, alert_severity_doc)
.def(
"__str__", &alert::msg, return_value_policy<copy_const_reference>()
, alert_msg_doc
)
;
enum_<alert::severity_t>("severity_levels")
.value("debug", alert::debug)
.value("info", alert::info)
.value("warning", alert::warning)
.value("critical", alert::critical)
.value("fatal", alert::fatal)
.value("none", alert::none)
;
}
class_<torrent_alert, bases<alert>, noncopyable>(
"torrent_alert", torrent_alert_doc, no_init
)
.def_readonly("handle", &torrent_alert::handle)
;
class_<tracker_alert, bases<torrent_alert>, noncopyable>(
"tracker_alert", tracker_alert_doc, no_init
)
.def_readonly("url", &tracker_alert::url)
;
class_<tracker_error_alert, bases<tracker_alert>, noncopyable>(
"tracker_error_alert", tracker_error_alert_doc, no_init
)
.def_readonly("times_in_row", &tracker_error_alert::times_in_row)
.def_readonly("status_code", &tracker_error_alert::status_code)
;
class_<tracker_warning_alert, bases<tracker_alert>, noncopyable>(
"tracker_warning_alert", tracker_warning_alert_doc, no_init
);
class_<tracker_reply_alert, bases<tracker_alert>, noncopyable>(
"tracker_reply_alert", tracker_reply_alert_doc, no_init
)
.def_readonly("num_peers", &tracker_reply_alert::num_peers)
;
class_<tracker_announce_alert, bases<tracker_alert>, noncopyable>(
"tracker_announce_alert", tracker_announce_alert_doc, no_init
);
class_<hash_failed_alert, bases<torrent_alert>, noncopyable>(
"hash_failed_alert", hash_failed_alert_doc, no_init
)
.def_readonly("piece_index", &hash_failed_alert::piece_index)
;
class_<peer_ban_alert, bases<torrent_alert>, noncopyable>(
"peer_ban_alert", peer_ban_alert_doc, no_init
)
.def_readonly("ip", &peer_ban_alert::ip)
;
class_<peer_error_alert, bases<alert>, noncopyable>(
"peer_error_alert", peer_error_alert_doc, no_init
)
.def_readonly("ip", &peer_error_alert::ip)
.def_readonly("pid", &peer_error_alert::pid)
;
class_<invalid_request_alert, bases<torrent_alert>, noncopyable>(
"invalid_request_alert", invalid_request_alert_doc, no_init
)
.def_readonly("ip", &invalid_request_alert::ip)
.def_readonly("request", &invalid_request_alert::request)
.def_readonly("pid", &invalid_request_alert::pid)
;
class_<peer_request>("peer_request", peer_request_doc)
.def_readonly("piece", &peer_request::piece)
.def_readonly("start", &peer_request::start)
.def_readonly("length", &peer_request::length)
.def(self == self)
;
class_<torrent_finished_alert, bases<torrent_alert>, noncopyable>(
"torrent_finished_alert", torrent_finished_alert_doc, no_init
);
class_<piece_finished_alert, bases<torrent_alert>, noncopyable>(
"piece_finished_alert", piece_finished_alert_doc, no_init
)
.def_readonly("piece_index", &piece_finished_alert::piece_index)
;
class_<block_finished_alert, bases<torrent_alert>, noncopyable>(
"block_finished_alert", block_finished_alert_doc, no_init
)
.def_readonly("block_index", &block_finished_alert::block_index)
.def_readonly("piece_index", &block_finished_alert::piece_index)
;
class_<block_downloading_alert, bases<torrent_alert>, noncopyable>(
"block_downloading_alert", block_downloading_alert_doc, no_init
)
.def_readonly("peer_speedmsg", &block_downloading_alert::peer_speedmsg)
.def_readonly("block_index", &block_downloading_alert::block_index)
.def_readonly("piece_index", &block_downloading_alert::piece_index)
;
class_<storage_moved_alert, bases<torrent_alert>, noncopyable>(
"storage_moved_alert", storage_moved_alert_doc, no_init
);
class_<torrent_deleted_alert, bases<torrent_alert>, noncopyable>(
"torrent_deleted_alert", torrent_deleted_alert_doc, no_init
);
class_<torrent_paused_alert, bases<torrent_alert>, noncopyable>(
"torrent_paused_alert", torrent_paused_alert_doc, no_init
);
class_<torrent_checked_alert, bases<torrent_alert>, noncopyable>(
"torrent_checked_alert", torrent_checked_alert_doc, no_init
);
class_<url_seed_alert, bases<torrent_alert>, noncopyable>(
"url_seed_alert", url_seed_alert_doc, no_init
)
.def_readonly("url", &url_seed_alert::url)
;
class_<file_error_alert, bases<torrent_alert>, noncopyable>(
"file_error_alert", file_error_alert_doc, no_init
)
.def_readonly("file", &file_error_alert::file)
;
class_<metadata_failed_alert, bases<torrent_alert>, noncopyable>(
"metadata_failed_alert", metadata_failed_alert_doc, no_init
);
class_<metadata_received_alert, bases<torrent_alert>, noncopyable>(
"metadata_received_alert", metadata_received_alert_doc, no_init
);
class_<listen_failed_alert, bases<alert>, noncopyable>(
"listen_failed_alert", listen_failed_alert_doc, no_init
);
class_<listen_succeeded_alert, bases<alert>, noncopyable>(
"listen_succeeded_alert", listen_succeeded_alert_doc, no_init
)
.def_readonly("endpoint", &listen_succeeded_alert::endpoint)
;
class_<portmap_error_alert, bases<alert>, noncopyable>(
"portmap_error_alert", portmap_error_alert_doc, no_init
)
.def_readonly("mapping", &portmap_error_alert::mapping)
.def_readonly("type", &portmap_error_alert::type)
;
class_<portmap_alert, bases<alert>, noncopyable>(
"portmap_alert", portmap_alert_doc, no_init
)
.def_readonly("mapping", &portmap_alert::mapping)
.def_readonly("external_port", &portmap_alert::external_port)
.def_readonly("type", &portmap_alert::type)
;
class_<fastresume_rejected_alert, bases<torrent_alert>, noncopyable>(
"fastresume_rejected_alert", fastresume_rejected_alert_doc, no_init
);
class_<peer_blocked_alert, bases<alert>, noncopyable>(
"peer_blocked_alert", peer_blocked_alert_doc, no_init
)
.def_readonly("ip", &peer_blocked_alert::ip)
;
class_<scrape_reply_alert, bases<tracker_alert>, noncopyable>(
"scrape_reply_alert", scrape_reply_alert_doc, no_init
)
.def_readonly("incomplete", &scrape_reply_alert::incomplete)
.def_readonly("complete", &scrape_reply_alert::complete)
;
class_<scrape_failed_alert, bases<tracker_alert>, noncopyable>(
"scrape_failed_alert", scrape_failed_alert_doc, no_init
);
class_<udp_error_alert, bases<alert>, noncopyable>(
"udp_error_alert", udp_error_alert_doc, no_init
)
.def_readonly("endpoint", &udp_error_alert::endpoint)
;
class_<external_ip_alert, bases<alert>, noncopyable>(
"external_ip_alert", external_ip_alert_doc, no_init
)
.def_readonly("external_address", &external_ip_alert::external_address)
;
class_<save_resume_data_alert, bases<torrent_alert>, noncopyable>(
"save_resume_data_alert", save_resume_data_alert_doc, no_init
)
.def_readonly("resume_data", &save_resume_data_alert::resume_data)
;
class_<file_renamed_alert, bases<torrent_alert>, noncopyable>(
"file_renamed_alert", no_init
)
.def_readonly("name", &file_renamed_alert::name)
;
class_<torrent_resumed_alert, bases<torrent_alert>, noncopyable>(
"torrent_resumed_alert", no_init
);
class_<state_changed_alert, bases<torrent_alert>, noncopyable>(
"state_changed_alert", no_init
)
.def_readonly("state", &state_changed_alert::state)
;
}
<|endoftext|>
|
<commit_before>/* BEGIN_COMMON_COPYRIGHT_HEADER
* (c)LGPL2+
*
* LXDE-Qt - a lightweight, Qt based, desktop toolset
* http://razor-qt.org
*
* Copyright: 2011 Razor team
* Authors:
* Petr Vanek <petr@scribus.info>
*
* This program or library is free software; you can redistribute it
* and/or modify it under the terms of the GNU Lesser General Public
* License as published by the Free Software Foundation; either
* version 2.1 of the License, or (at your option) any later version.
*
* This library is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
* Lesser General Public License for more details.
* You should have received a copy of the GNU Lesser General
* Public License along with this library; if not, write to the
* Free Software Foundation, Inc., 51 Franklin Street, Fifth Floor,
* Boston, MA 02110-1301 USA
*
* END_COMMON_COPYRIGHT_HEADER */
#include "menudiskitem.h"
#include "popup.h"
#include <QDesktopServices>
#include <QEvent>
#include <QHBoxLayout>
#include <QUrl>
#include <QTimer>
#include <XdgIcon>
#include <Solid/StorageAccess>
#include <Solid/OpticalDrive>
#include <LXQt/Notification>
#include <QDebug>
MenuDiskItem::MenuDiskItem(Solid::Device device, Popup *popup):
QFrame(popup),
mPopup(popup),
mDevice(device),
mDiskButton(nullptr),
mEjectButton(nullptr),
mDiskButtonClicked(false),
mEjectButtonClicked(false)
{
Solid::StorageAccess * const iface = device.as<Solid::StorageAccess>();
Q_ASSERT(nullptr != iface);
mDiskButton = new QToolButton(this);
mDiskButton->setObjectName("DiskButton");
mDiskButton->setToolButtonStyle(Qt::ToolButtonTextBesideIcon);
mDiskButton->setSizePolicy(QSizePolicy::Expanding, QSizePolicy::Minimum);
connect(mDiskButton, &QToolButton::clicked, this, &MenuDiskItem::diskButtonClicked);
mEjectButton = new QToolButton(this);
mEjectButton->setObjectName("EjectButton");
mEjectButton->setIcon(XdgIcon::fromTheme("media-eject"));
connect(mEjectButton, &QToolButton::clicked, this, &MenuDiskItem::ejectButtonClicked);
QHBoxLayout *layout = new QHBoxLayout(this);
layout->addWidget(mDiskButton);
layout->addWidget(mEjectButton);
layout->setMargin(0);
layout->setSpacing(0);
setLayout(layout);
connect(device.as<Solid::StorageAccess>(), &Solid::StorageAccess::setupDone,
this, &MenuDiskItem::onMounted);
connect(iface, &Solid::StorageAccess::setupDone, this, &MenuDiskItem::onMounted);
connect(iface, &Solid::StorageAccess::teardownDone, this, &MenuDiskItem::onUnmounted);
connect(iface, &Solid::StorageAccess::accessibilityChanged, [this] (bool accessible, QString const &) {
updateMountStatus();
});
updateMountStatus();
}
MenuDiskItem::~MenuDiskItem()
{
}
void MenuDiskItem::setMountStatus(bool mounted)
{
mEjectButton->setEnabled(mounted);
}
void MenuDiskItem::updateMountStatus()
{
static const QIcon icon = XdgIcon::fromTheme(mDevice.icon(), QStringLiteral("drive-removable-media"));
if (mDevice.isValid())
{
mDiskButton->setIcon(icon);
mDiskButton->setText(mDevice.description());
setMountStatus(mDevice.as<Solid::StorageAccess>()->isAccessible() || !opticalParent().udi().isEmpty());
}
else
emit invalid(mDevice.udi());
}
Solid::Device MenuDiskItem::opticalParent() const
{
Solid::Device it;
if (mDevice.isValid())
{
it = mDevice;
// search for parent drive
for (; !it.udi().isEmpty(); it = it.parent())
if (it.is<Solid::OpticalDrive>())
break;
}
return it;
}
void MenuDiskItem::diskButtonClicked()
{
mDiskButtonClicked = true;
Solid::StorageAccess* di = mDevice.as<Solid::StorageAccess>();
if (!di->isAccessible())
di->setup();
else
onMounted(Solid::NoError, QString(), mDevice.udi());
mPopup->hide();
}
void MenuDiskItem::ejectButtonClicked()
{
mEjectButtonClicked = true;
Solid::StorageAccess* di = mDevice.as<Solid::StorageAccess>();
if (di->isAccessible())
di->teardown();
else
onUnmounted(Solid::NoError, QString(), mDevice.udi());
mPopup->hide();
}
void MenuDiskItem::onMounted(Solid::ErrorType error, QVariant resultData, const QString &udi)
{
if (mDiskButtonClicked)
{
mDiskButtonClicked = false;
if (Solid::NoError == error)
QDesktopServices::openUrl(QUrl(mDevice.as<Solid::StorageAccess>()->filePath()));
else
{
QString errorMsg = tr("Mounting of <b><nobr>\"%1\"</nobr></b> failed: %2");
errorMsg = errorMsg.arg(mDevice.description()).arg(resultData.toString());
LxQt::Notification::notify(tr("Removable media/devices manager"), errorMsg, mDevice.icon());
}
}
}
void MenuDiskItem::onUnmounted(Solid::ErrorType error, QVariant resultData, const QString &udi)
{
if (mEjectButtonClicked)
{
mEjectButtonClicked = false;
if (Solid::NoError == error)
{
Solid::Device opt_parent = opticalParent();
if (!opt_parent.udi().isEmpty())
opt_parent.as<Solid::OpticalDrive>()->eject();
}
else
{
QString errorMsg = tr("Unmounting of <strong><nobr>\"%1\"</nobr></strong> failed: %2");
errorMsg = errorMsg.arg(mDevice.description()).arg(resultData.toString());
LxQt::Notification::notify(tr("Removable media/devices manager"), errorMsg, mDevice.icon());
}
}
}
<commit_msg>plugin-mount: remove of doubled signal connection<commit_after>/* BEGIN_COMMON_COPYRIGHT_HEADER
* (c)LGPL2+
*
* LXDE-Qt - a lightweight, Qt based, desktop toolset
* http://razor-qt.org
*
* Copyright: 2011 Razor team
* Authors:
* Petr Vanek <petr@scribus.info>
*
* This program or library is free software; you can redistribute it
* and/or modify it under the terms of the GNU Lesser General Public
* License as published by the Free Software Foundation; either
* version 2.1 of the License, or (at your option) any later version.
*
* This library is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
* Lesser General Public License for more details.
* You should have received a copy of the GNU Lesser General
* Public License along with this library; if not, write to the
* Free Software Foundation, Inc., 51 Franklin Street, Fifth Floor,
* Boston, MA 02110-1301 USA
*
* END_COMMON_COPYRIGHT_HEADER */
#include "menudiskitem.h"
#include "popup.h"
#include <QDesktopServices>
#include <QEvent>
#include <QHBoxLayout>
#include <QUrl>
#include <QTimer>
#include <XdgIcon>
#include <Solid/StorageAccess>
#include <Solid/OpticalDrive>
#include <LXQt/Notification>
#include <QDebug>
MenuDiskItem::MenuDiskItem(Solid::Device device, Popup *popup):
QFrame(popup),
mPopup(popup),
mDevice(device),
mDiskButton(nullptr),
mEjectButton(nullptr),
mDiskButtonClicked(false),
mEjectButtonClicked(false)
{
Solid::StorageAccess * const iface = device.as<Solid::StorageAccess>();
Q_ASSERT(nullptr != iface);
mDiskButton = new QToolButton(this);
mDiskButton->setObjectName("DiskButton");
mDiskButton->setToolButtonStyle(Qt::ToolButtonTextBesideIcon);
mDiskButton->setSizePolicy(QSizePolicy::Expanding, QSizePolicy::Minimum);
connect(mDiskButton, &QToolButton::clicked, this, &MenuDiskItem::diskButtonClicked);
mEjectButton = new QToolButton(this);
mEjectButton->setObjectName("EjectButton");
mEjectButton->setIcon(XdgIcon::fromTheme("media-eject"));
connect(mEjectButton, &QToolButton::clicked, this, &MenuDiskItem::ejectButtonClicked);
QHBoxLayout *layout = new QHBoxLayout(this);
layout->addWidget(mDiskButton);
layout->addWidget(mEjectButton);
layout->setMargin(0);
layout->setSpacing(0);
setLayout(layout);
connect(iface, &Solid::StorageAccess::setupDone, this, &MenuDiskItem::onMounted);
connect(iface, &Solid::StorageAccess::teardownDone, this, &MenuDiskItem::onUnmounted);
connect(iface, &Solid::StorageAccess::accessibilityChanged, [this] (bool accessible, QString const &) {
updateMountStatus();
});
updateMountStatus();
}
MenuDiskItem::~MenuDiskItem()
{
}
void MenuDiskItem::setMountStatus(bool mounted)
{
mEjectButton->setEnabled(mounted);
}
void MenuDiskItem::updateMountStatus()
{
static const QIcon icon = XdgIcon::fromTheme(mDevice.icon(), QStringLiteral("drive-removable-media"));
if (mDevice.isValid())
{
mDiskButton->setIcon(icon);
mDiskButton->setText(mDevice.description());
setMountStatus(mDevice.as<Solid::StorageAccess>()->isAccessible() || !opticalParent().udi().isEmpty());
}
else
emit invalid(mDevice.udi());
}
Solid::Device MenuDiskItem::opticalParent() const
{
Solid::Device it;
if (mDevice.isValid())
{
it = mDevice;
// search for parent drive
for (; !it.udi().isEmpty(); it = it.parent())
if (it.is<Solid::OpticalDrive>())
break;
}
return it;
}
void MenuDiskItem::diskButtonClicked()
{
mDiskButtonClicked = true;
Solid::StorageAccess* di = mDevice.as<Solid::StorageAccess>();
if (!di->isAccessible())
di->setup();
else
onMounted(Solid::NoError, QString(), mDevice.udi());
mPopup->hide();
}
void MenuDiskItem::ejectButtonClicked()
{
mEjectButtonClicked = true;
Solid::StorageAccess* di = mDevice.as<Solid::StorageAccess>();
if (di->isAccessible())
di->teardown();
else
onUnmounted(Solid::NoError, QString(), mDevice.udi());
mPopup->hide();
}
void MenuDiskItem::onMounted(Solid::ErrorType error, QVariant resultData, const QString &udi)
{
if (mDiskButtonClicked)
{
mDiskButtonClicked = false;
if (Solid::NoError == error)
QDesktopServices::openUrl(QUrl(mDevice.as<Solid::StorageAccess>()->filePath()));
else
{
QString errorMsg = tr("Mounting of <b><nobr>\"%1\"</nobr></b> failed: %2");
errorMsg = errorMsg.arg(mDevice.description()).arg(resultData.toString());
LxQt::Notification::notify(tr("Removable media/devices manager"), errorMsg, mDevice.icon());
}
}
}
void MenuDiskItem::onUnmounted(Solid::ErrorType error, QVariant resultData, const QString &udi)
{
if (mEjectButtonClicked)
{
mEjectButtonClicked = false;
if (Solid::NoError == error)
{
Solid::Device opt_parent = opticalParent();
if (!opt_parent.udi().isEmpty())
opt_parent.as<Solid::OpticalDrive>()->eject();
}
else
{
QString errorMsg = tr("Unmounting of <strong><nobr>\"%1\"</nobr></strong> failed: %2");
errorMsg = errorMsg.arg(mDevice.description()).arg(resultData.toString());
LxQt::Notification::notify(tr("Removable media/devices manager"), errorMsg, mDevice.icon());
}
}
}
<|endoftext|>
|
<commit_before>/*
* Copyright (c) 2013 Akihiro Kaneda.
* All rights reserved.
*
* Redistribution and use in source and binary forms, with or without
* modification, are permitted provided that the following conditions are met:
*
* 1.Redistributions of source code must retain the above copyright notice,
* this list of conditions and the following disclaimer.
* 2.Redistributions in binary form must reproduce the above copyright notice,
* this list of conditions and the following disclaimer in the documentation
* and/or other materials provided with the distribution.
* 3.Neither the name of the Monochrome Soft nor the names of its contributors
* may be used to endorse or promote products derived from this software
* without specific prior written permission.
*
* THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS"
* AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE
* IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE
* ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT HOLDER OR CONTRIBUTORS BE
* LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR
* CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF
* SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS
* INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN
* CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE)
* ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE
* POSSIBILITY OF SUCH DAMAGE.
*/
/*!
@file AKOption.cpp
@brief オプションクラス
オプションを管理するクラスを定義する。
*/
#include "AKOption.h"
#include "AKEnemyShot.h"
using cocos2d::Node;
using cocos2d::Vector2;
/// オプションの画像ファイル名
static const char *kAKOptionImageFile = "Option_%02d";
/// シールドなし時のアニメーションフレーム数
static const int kAKOptionAnimationCountOfShieldOff = 2;
/// シールドあり時のアニメーションフレーム数
static const int kAKOptionAnimationCountOfShieldOn = 1;
/// 弾発射の間隔
static const int kAKOptionShotInterval = 12;
/// オプション間の距離
static const int kAKOptionSpace = 20;
/// オプションの当たり判定
static const int kAKOptionSize = 32;
/*!
@brief オブジェクト生成処理
オブジェクトの生成を行う。
指定されたオプションの個数分を再帰的に生成する。
@param count オプションの個数
@param parent 画像を配置する親ノード
@return 生成したオブジェクト。失敗時はnilを返す。
*/
AKOption::AKOption(int count, Node *parent)
{
// アニメーションフレームの個数を設定する
m_animationPattern = kAKOptionAnimationCountOfShieldOff;
// 画像名を設定する
char imageName[16] = "";
snprintf(imageName, sizeof(imageName), kAKOptionImageFile, 1);
setImageName(imageName);
// 弾発射までの残りフレーム数を設定する
m_shootFrame = kAKOptionShotInterval;
// ヒットポイントは1としておく
m_hitPoint = 1;
// オプションの当たり判定を設定する
// これはシールド時のみ使用する
m_size.width = kAKOptionSize;
m_size.height = kAKOptionSize;
// 初期状態はシールドなしとする
m_shield = false;
// 初期状態では画面には配置しない
m_isStaged = false;
getImage()->setVisible(false);
// 画像を親ノードに配置する
parent->addChild(getImage());
// オプション個数が指定されている場合は次のオプションを生成する
if (count > 0) {
m_next = new AKOption(count - 1, parent);
}
else {
m_next = NULL;
}
}
/*!
@brief デストラクタ
次のオプションを解放する。
*/
AKOption::~AKOption()
{
delete m_next;
}
/*!
@brief シールド有無設定
シールド有無を設定する。
画像の切り替えも行う。
次のオプションに対しても同様の設定を行う。
@param shield シールド有無
*/
void AKOption::setShiled(bool shield)
{
// メンバに設定する
m_shield = shield;
// シールド有無によって画像を切り替える
if (m_shield) {
AKLog(kAKLogOption_1, "シールドあり");
// 画像名を設定する
char imageName[16] = "";
snprintf(imageName, sizeof(imageName), kAKOptionImageFile, 2);
setImageName(imageName);
// アニメーションフレームの個数を設定する
m_animationPattern = kAKOptionAnimationCountOfShieldOn;
}
else {
AKLog(kAKLogOption_1, "シールドなし");
// 画像名を設定する
char imageName[16] = "";
snprintf(imageName, sizeof(imageName), kAKOptionImageFile, 1);
setImageName(imageName);
// アニメーションフレームの個数を設定する
m_animationPattern = kAKOptionAnimationCountOfShieldOn;
}
// 次のオプションがある場合は次のオプションにも設定する
if (m_next != NULL) {
m_next->setShiled(m_shield);
}
}
/*!
@brief オプション数設定
オプションの個数を設定する。
1以上が設定された場合は自分を配置状態に設定する。
0以下が設定された場合は自分を配置状態から外す。
次のオプションが存在する場合は個数を一つ減らして再帰的に呼び出す。
@param count オプション個数
@param position 初期配置位置
*/
void AKOption::setOptionCount(int count, const Vector2 &position)
{
AKLog(kAKLogOption_2, "count=%d", count);
// オプション個数が設定された場合はオプションを有効とする
if (count > 0) {
// 配置されていない場合は配置状態にして、初期配置位置に移動する
if (!m_isStaged) {
AKLog(kAKLogOption_1, "オプション配置");
m_isStaged = true;
getImage()->setVisible(true);
m_position = position;
// 初期表示時に前回の位置に表示されることを防ぐため、画像表示位置の更新も行う
updateImagePosition();
}
}
// オプション個数が0以下の場合はオプションを無効とする
else {
// 配置されている場合は配置状態を解除して、移動座標をすべてクリアする
if (m_isStaged) {
AKLog(kAKLogOption_1, "オプション削除");
m_isStaged = false;
getImage()->setVisible(false);
m_movePositions.clear();
}
}
// 自分の座標を初期座標として次のオプションを設定する
if (m_next != NULL) {
m_next->setOptionCount(count - 1, m_position);
}
}
/*!
@brief 移動座標設定
移動座標を設定する。オプションが付属している場合はオプションの移動も行う。
@param position 移動先座標
*/
void AKOption::setPosition(const Vector2 &position)
{
// オプションに自分の移動前の座標を通知する
if (m_next != NULL && m_next->isStaged()) {
m_next->setPosition(m_position);
}
// 移動先座標が間隔分溜まっている場合は先頭の座標に移動する
if (m_movePositions.size() >= kAKOptionSpace) {
// 先頭の要素を取得し、座標を移動する
std::vector<Vector2>::iterator start = m_movePositions.begin();
m_position = *start;
// 取得した要素を配列から取り除く
m_movePositions.erase(start);
}
// 移動先座標の配列の末尾に追加する
m_movePositions.push_back(position);
}
/*!
@brief オプション移動
オプションの移動を行う。自機クラスから呼び出される。
@param data ゲームデータ
*/
void AKOption::optionMove(AKPlayDataInterface *data)
{
move(data);
}
/*!
@brief 次のオプション取得
次のオプションを取得する。
最後のオプションの場合はNULLを返す。
@return 次のオプション
*/
AKOption* AKOption::getNext()
{
return m_next;
}
/*!
@brief キャラクター固有の動作
速度によって位置を移動する。オプションの表示位置は固定とする。
次のオプションの移動を行う。
@param data ゲームデータ
*/
void AKOption::action(AKPlayDataInterface *data)
{
// 弾発射までのフレーム数をカウントする
m_shootFrame--;
// 弾発射までの残りフレーム数が0になっている場合は弾を発射する
if (m_shootFrame <= 0) {
// オプション弾を生成する
data->createOptionShot(m_position);
// 弾発射までの残り時間をリセットする
m_shootFrame = kAKOptionShotInterval;
}
// 次のオプションの移動を行う
if (m_next != NULL) {
m_next->move(data);
}
}
/*!
@brief 衝突処理
衝突した時の処理。
反射弾を作成後、相手のHPを0にする。
@param character 衝突した相手
@param data ゲームデータ
*/
void AKOption::hit(AKCharacter *character, AKPlayDataInterface *data)
{
AKLog(kAKLogOption_1, "反射処理開始");
// 反射弾を作成する
data->createReflectShot(static_cast<AKEnemyShot*>(character));
// 相手のHPを0にする
character->setHitPoint(0);
}
<commit_msg>ひよこのアニメーション処理がシールド使用後に止まってしまうものを修正。<commit_after>/*
* Copyright (c) 2013 Akihiro Kaneda.
* All rights reserved.
*
* Redistribution and use in source and binary forms, with or without
* modification, are permitted provided that the following conditions are met:
*
* 1.Redistributions of source code must retain the above copyright notice,
* this list of conditions and the following disclaimer.
* 2.Redistributions in binary form must reproduce the above copyright notice,
* this list of conditions and the following disclaimer in the documentation
* and/or other materials provided with the distribution.
* 3.Neither the name of the Monochrome Soft nor the names of its contributors
* may be used to endorse or promote products derived from this software
* without specific prior written permission.
*
* THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS"
* AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE
* IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE
* ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT HOLDER OR CONTRIBUTORS BE
* LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR
* CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF
* SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS
* INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN
* CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE)
* ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE
* POSSIBILITY OF SUCH DAMAGE.
*/
/*!
@file AKOption.cpp
@brief オプションクラス
オプションを管理するクラスを定義する。
*/
#include "AKOption.h"
#include "AKEnemyShot.h"
using cocos2d::Node;
using cocos2d::Vector2;
/// オプションの画像ファイル名
static const char *kAKOptionImageFile = "Option_%02d";
/// シールドなし時のアニメーションフレーム数
static const int kAKOptionAnimationCountOfShieldOff = 2;
/// シールドあり時のアニメーションフレーム数
static const int kAKOptionAnimationCountOfShieldOn = 1;
/// 弾発射の間隔
static const int kAKOptionShotInterval = 12;
/// オプション間の距離
static const int kAKOptionSpace = 20;
/// オプションの当たり判定
static const int kAKOptionSize = 32;
/*!
@brief オブジェクト生成処理
オブジェクトの生成を行う。
指定されたオプションの個数分を再帰的に生成する。
@param count オプションの個数
@param parent 画像を配置する親ノード
@return 生成したオブジェクト。失敗時はnilを返す。
*/
AKOption::AKOption(int count, Node *parent)
{
// アニメーションフレームの個数を設定する
m_animationPattern = kAKOptionAnimationCountOfShieldOff;
// 画像名を設定する
char imageName[16] = "";
snprintf(imageName, sizeof(imageName), kAKOptionImageFile, 1);
setImageName(imageName);
// 弾発射までの残りフレーム数を設定する
m_shootFrame = kAKOptionShotInterval;
// ヒットポイントは1としておく
m_hitPoint = 1;
// オプションの当たり判定を設定する
// これはシールド時のみ使用する
m_size.width = kAKOptionSize;
m_size.height = kAKOptionSize;
// 初期状態はシールドなしとする
m_shield = false;
// 初期状態では画面には配置しない
m_isStaged = false;
getImage()->setVisible(false);
// 画像を親ノードに配置する
parent->addChild(getImage());
// オプション個数が指定されている場合は次のオプションを生成する
if (count > 0) {
m_next = new AKOption(count - 1, parent);
}
else {
m_next = NULL;
}
}
/*!
@brief デストラクタ
次のオプションを解放する。
*/
AKOption::~AKOption()
{
delete m_next;
}
/*!
@brief シールド有無設定
シールド有無を設定する。
画像の切り替えも行う。
次のオプションに対しても同様の設定を行う。
@param shield シールド有無
*/
void AKOption::setShiled(bool shield)
{
// メンバに設定する
m_shield = shield;
// シールド有無によって画像を切り替える
if (m_shield) {
AKLog(kAKLogOption_1, "シールドあり");
// 画像名を設定する
char imageName[16] = "";
snprintf(imageName, sizeof(imageName), kAKOptionImageFile, 2);
setImageName(imageName);
// アニメーションフレームの個数を設定する
m_animationPattern = kAKOptionAnimationCountOfShieldOn;
}
else {
AKLog(kAKLogOption_1, "シールドなし");
// 画像名を設定する
char imageName[16] = "";
snprintf(imageName, sizeof(imageName), kAKOptionImageFile, 1);
setImageName(imageName);
// アニメーションフレームの個数を設定する
m_animationPattern = kAKOptionAnimationCountOfShieldOff;
}
// 次のオプションがある場合は次のオプションにも設定する
if (m_next != NULL) {
m_next->setShiled(m_shield);
}
}
/*!
@brief オプション数設定
オプションの個数を設定する。
1以上が設定された場合は自分を配置状態に設定する。
0以下が設定された場合は自分を配置状態から外す。
次のオプションが存在する場合は個数を一つ減らして再帰的に呼び出す。
@param count オプション個数
@param position 初期配置位置
*/
void AKOption::setOptionCount(int count, const Vector2 &position)
{
AKLog(kAKLogOption_2, "count=%d", count);
// オプション個数が設定された場合はオプションを有効とする
if (count > 0) {
// 配置されていない場合は配置状態にして、初期配置位置に移動する
if (!m_isStaged) {
AKLog(kAKLogOption_1, "オプション配置");
m_isStaged = true;
getImage()->setVisible(true);
m_position = position;
// 初期表示時に前回の位置に表示されることを防ぐため、画像表示位置の更新も行う
updateImagePosition();
}
}
// オプション個数が0以下の場合はオプションを無効とする
else {
// 配置されている場合は配置状態を解除して、移動座標をすべてクリアする
if (m_isStaged) {
AKLog(kAKLogOption_1, "オプション削除");
m_isStaged = false;
getImage()->setVisible(false);
m_movePositions.clear();
}
}
// 自分の座標を初期座標として次のオプションを設定する
if (m_next != NULL) {
m_next->setOptionCount(count - 1, m_position);
}
}
/*!
@brief 移動座標設定
移動座標を設定する。オプションが付属している場合はオプションの移動も行う。
@param position 移動先座標
*/
void AKOption::setPosition(const Vector2 &position)
{
// オプションに自分の移動前の座標を通知する
if (m_next != NULL && m_next->isStaged()) {
m_next->setPosition(m_position);
}
// 移動先座標が間隔分溜まっている場合は先頭の座標に移動する
if (m_movePositions.size() >= kAKOptionSpace) {
// 先頭の要素を取得し、座標を移動する
std::vector<Vector2>::iterator start = m_movePositions.begin();
m_position = *start;
// 取得した要素を配列から取り除く
m_movePositions.erase(start);
}
// 移動先座標の配列の末尾に追加する
m_movePositions.push_back(position);
}
/*!
@brief オプション移動
オプションの移動を行う。自機クラスから呼び出される。
@param data ゲームデータ
*/
void AKOption::optionMove(AKPlayDataInterface *data)
{
move(data);
}
/*!
@brief 次のオプション取得
次のオプションを取得する。
最後のオプションの場合はNULLを返す。
@return 次のオプション
*/
AKOption* AKOption::getNext()
{
return m_next;
}
/*!
@brief キャラクター固有の動作
速度によって位置を移動する。オプションの表示位置は固定とする。
次のオプションの移動を行う。
@param data ゲームデータ
*/
void AKOption::action(AKPlayDataInterface *data)
{
// 弾発射までのフレーム数をカウントする
m_shootFrame--;
// 弾発射までの残りフレーム数が0になっている場合は弾を発射する
if (m_shootFrame <= 0) {
// オプション弾を生成する
data->createOptionShot(m_position);
// 弾発射までの残り時間をリセットする
m_shootFrame = kAKOptionShotInterval;
}
// 次のオプションの移動を行う
if (m_next != NULL) {
m_next->move(data);
}
}
/*!
@brief 衝突処理
衝突した時の処理。
反射弾を作成後、相手のHPを0にする。
@param character 衝突した相手
@param data ゲームデータ
*/
void AKOption::hit(AKCharacter *character, AKPlayDataInterface *data)
{
AKLog(kAKLogOption_1, "反射処理開始");
// 反射弾を作成する
data->createReflectShot(static_cast<AKEnemyShot*>(character));
// 相手のHPを0にする
character->setHitPoint(0);
}
<|endoftext|>
|
<commit_before>#ifdef HAVE_CONFIG_H
#include "config.h"
#endif
extern "C" {
#include "php.h"
}
#include "php_ini.h"
#include "ext/standard/info.h"
#include "php_mmseg.h"
#include <sys/stat.h>
using namespace std;
// SegmenterManager
ZEND_DECLARE_MODULE_GLOBALS(mmseg)
/* True global resources - no need for thread safety here */
static int le_mmseg;
// mmseg segmenter manager句柄
static int le_mmseg_descriptor;
/* {{{ PHP_INI
*/
PHP_INI_BEGIN()
PHP_INI_ENTRY("mmseg.dict_dir", "/opt/etc", PHP_INI_ALL, NULL)
PHP_INI_ENTRY("mmseg.autoreload", "1", PHP_INI_ALL, NULL)
PHP_INI_END()
/* }}} */
/* {{{ php_mmseg_init_globals
*/
/* Uncomment this function if you have INI entries
static void php_mmseg_init_globals(zend_mmseg_globals *mmseg_globals)
{
mmseg_globals->global_value = 0;
mmseg_globals->global_string = NULL;
}
*/
/* }}} */
/* {{{ PHP_MINIT_FUNCTION
*/
PHP_MINIT_FUNCTION(mmseg)
{
REGISTER_INI_ENTRIES();
// 初始化mmseg资源句柄
le_mmseg_descriptor = zend_register_list_destructors_ex(php_mmseg_descriptor_dtor, NULL, PHP_MMSEG_DESCRIPTOR_RES_NAME,module_number);
// 初始化,如果初始化失败,则返回失败信息,(XXX: 未来将改变为如果初始化失败, 可以在程序里面调用init初始化)
#ifdef ZTS
ts_allocate_id(&mmseg_globals_id, sizeof(zend_mmseg_globals),
php_mmseg_globals_ctor, php_mmseg_globals_dtor);
#else
php_mmseg_globals_ctor(&mmseg_globals TSRMLS_CC);
#endif
return SUCCESS;
}
/* }}} */
/* {{{ PHP_MSHUTDOWN_FUNCTION
*/
PHP_MSHUTDOWN_FUNCTION(mmseg)
{
UNREGISTER_INI_ENTRIES();
#ifndef ZTS
php_mmseg_globals_dtor(&mmseg_globals TSRMLS_CC);
#endif
return SUCCESS;
}
/* }}} */
/* Remove if there's nothing to do at request start */
/* {{{ PHP_RINIT_FUNCTION
*/
PHP_RINIT_FUNCTION(mmseg)
{
#if defined(COMPILE_DL_MMSEG) && defined(ZTS) && defined(ZEND_TSRMLS_CACHE_UPDATE)
ZEND_TSRMLS_CACHE_UPDATE();
#endif
return SUCCESS;
}
/* }}} */
/* Remove if there's nothing to do at request end */
/* {{{ PHP_RSHUTDOWN_FUNCTION
*/
PHP_RSHUTDOWN_FUNCTION(mmseg)
{
return SUCCESS;
}
/* }}} */
/* {{{ PHP_MINFO_FUNCTION
*/
PHP_MINFO_FUNCTION(mmseg)
{
php_info_print_table_start();
php_info_print_table_header(2, "mmseg support", "enabled");
php_info_print_table_end();
DISPLAY_INI_ENTRIES();
}
/* }}} */
/* {{{ mmseg_functions[]
*
* Every user visible function must have an entry in mmseg_functions[].
*/
const zend_function_entry mmseg_functions[] = {
PHP_FE(mmseg_segment, NULL)
PHP_FE(mmseg_open, NULL)
PHP_FE(mmseg_close, NULL)
PHP_FE(mmseg_gendict, NULL)
PHP_FE(mmseg_gensynonyms, NULL)
PHP_FE(mmseg_genthesaurus, NULL)
PHP_FE_END /* Must be the last line in mmseg_functions[] */
};
/* }}} */
/* {{{ mmseg_module_entry
*/
zend_module_entry mmseg_module_entry = {
STANDARD_MODULE_HEADER,
"mmseg",
mmseg_functions,
PHP_MINIT(mmseg),
PHP_MSHUTDOWN(mmseg),
PHP_RINIT(mmseg), /* Replace with NULL if there's nothing to do at request start */
PHP_RSHUTDOWN(mmseg), /* Replace with NULL if there's nothing to do at request end */
PHP_MINFO(mmseg),
PHP_MMSEG_VERSION,
STANDARD_MODULE_PROPERTIES
};
/* }}} */
#ifdef COMPILE_DL_MMSEG
#ifdef ZTS
ZEND_TSRMLS_CACHE_DEFINE()
#endif
BEGIN_EXTERN_C()
ZEND_GET_MODULE(mmseg)
END_EXTERN_C()
#endif
/* Triggered at the beginning of a thread */
static void php_mmseg_globals_ctor(zend_mmseg_globals *mmseg_globals TSRMLS_DC)
{
struct stat st;
SegmenterManager* mgr = (SegmenterManager*) mmseg_globals->mgr;
mgr = new SegmenterManager();
int nRet = 0;
mmseg_globals->dict_mtime = 0;
nRet = mgr->init(INI_STR("mmseg.dict_dir"));
if (nRet == 0) {
mmseg_globals->mgr = (void*) mgr;
// 记录最后一次字典文件更改的数值
string dict_file_path;
dict_file_path = INI_STR("mmseg.dict_dir");
dict_file_path.append("/uni.lib");
if (stat(dict_file_path.c_str(), &st) == 0) {
mmseg_globals->dict_mtime = st.st_mtime;
MMSEG_LOG(ctime(&st.st_mtime));
}
MMSEG_LOG("minit load dictionary");
return ;
} else {
if (mgr != NULL) {
delete mgr;
mgr = NULL;
}
mmseg_globals->mgr = NULL;
return ;
}
}
/* Triggered at the end of a thread */
static void php_mmseg_globals_dtor(zend_mmseg_globals *mmseg_globals TSRMLS_DC)
{
SegmenterManager* mgr = (SegmenterManager*) mmseg_globals->mgr;
if (mgr != NULL) {
delete mgr;
mgr = NULL;
}
}
// mmseg 句柄的dtor函数
static void php_mmseg_descriptor_dtor(zend_rsrc_list_entry *rsrc TSRMLS_DC)
{
SegmenterManager *mgr = (SegmenterManager*)rsrc->ptr;
if (mgr != NULL) {
delete mgr;
mgr = NULL;
}
}
/* The previous line is meant for vim and emacs, so it can correctly fold and
unfold functions in source code. See the corresponding marks just before
function definition, where the functions purpose is also documented. Please
follow this convention for the convenience of others editing your code.
*/
/* {{{ proto array mmseg_segment(string content)
*/
PHP_FUNCTION(mmseg_segment)
{
char *content = NULL;
int argc = ZEND_NUM_ARGS();
#if PHP_MAJOR_VERSION < 7
int content_len;
#else
size_t content_len;
#endif
SegmenterManager* mgr = NULL;
zval *mmseg_resource;
zend_bool autoreload = INI_BOOL("mmseg.autoreload");
// 判断传入参数的数量
if (argc == 1) {
struct stat st;
if (zend_parse_parameters(argc TSRMLS_CC, "s", &content, &content_len) == FAILURE)
return;
// 如果使用全局的字典文件,在这里看一下是否需要判断文件是否有改变
if (1 == autoreload) {
// 文件名
string dict_file_path;
dict_file_path = INI_STR("mmseg.dict_dir");
dict_file_path.append("/uni.lib");
if (stat(dict_file_path.c_str(), &st) == 0) {
if (st.st_mtime != MMSEG_G(dict_mtime)) {
MMSEG_G(dict_mtime) = st.st_mtime;
SegmenterManager* oldMgr = (SegmenterManager*)MMSEG_G(mgr);
SegmenterManager* newMgr;
newMgr = new SegmenterManager();
int nRet = 0;
nRet = newMgr->init(INI_STR("mmseg.dict_dir"));
if (nRet == 0) {
if (oldMgr) {
MMSEG_LOG("trying to delete old mgr");
delete oldMgr;
oldMgr = NULL;
}
MMSEG_LOG("load dictionary on change");
MMSEG_G(mgr) = newMgr;
} else {
// no change. still use oldMgr
MMSEG_LOG("no change, initialize new dict file failed");
newMgr = NULL;
}
} else {
MMSEG_LOG(ctime(&st.st_mtime));
MMSEG_LOG(ctime(&MMSEG_G(dict_mtime)));
MMSEG_LOG("no change, dict file no change");
// no change, still use old oldMgr
}
} else {
MMSEG_LOG("no change, stat new dict file failed");
}
} else {
MMSEG_LOG("no change, autoreload not set");
}
} else if (argc == 2){
if (zend_parse_parameters(argc TSRMLS_CC, "rs", &mmseg_resource, &content, &content_len) == FAILURE)
return;
#if PHP_MAJOR_VERSION < 7
ZEND_FETCH_RESOURCE(mgr,SegmenterManager*,&mmseg_resource,-1,PHP_MMSEG_DESCRIPTOR_RES_NAME,le_mmseg_descriptor);
#else
mgr = (SegmenterManager*) zend_fetch_resource(Z_RES_P(mmseg_resource), PHP_MMSEG_DESCRIPTOR_RES_NAME,le_mmseg_descriptor);
#endif
} else {
return;
}
mgr = (SegmenterManager*) MMSEG_G(mgr);
if (mgr == NULL) {
RETURN_NULL();
}
Segmenter* seg = mgr->getSegmenter();
u4 content_length = content_len;
seg->setBuffer((u1*)content, content_length);
array_init(return_value);
while(1)
{
u2 len = 0, symlen = 0;
char* tok = (char*)seg->peekToken(len,symlen);
if(!tok || !*tok || !len){
break;
}
//append new item
#if PHP_MAJOR_VERSION < 7
add_next_index_stringl(return_value, tok, len, 1);
#else
add_next_index_stringl(return_value, tok, len);
#endif
seg->popToken(len);
}
return ;
}
/* }}} */
PHP_FUNCTION(mmseg_open)
{
char *path = NULL;
int argc = ZEND_NUM_ARGS();
#if PHP_MAJOR_VERSION < 7
int path_len;
#else
size_t path_len;
#endif
if (zend_parse_parameters(argc TSRMLS_CC, "s", &path, &path_len) == FAILURE)
return;
// 生成新的对象
SegmenterManager* mgr = new SegmenterManager();
int nRet = 0;
nRet = mgr->init(path);
if (nRet == 0) {
// 注册这个资源
#if PHP_MAJOR_VERSION < 7
ZEND_REGISTER_RESOURCE(return_value,mgr,le_mmseg_descriptor);
#else
RETURN_RES(zend_register_resource(mgr, le_mmseg_descriptor));
#endif
} else {
RETURN_NULL();
}
}
PHP_FUNCTION(mmseg_close)
{
zval *mmseg_resource;
SegmenterManager* mgr;
int argc = ZEND_NUM_ARGS();
if (zend_parse_parameters(argc TSRMLS_CC, "r", &mmseg_resource) == FAILURE)
return;
#if PHP_MAJOR_VERSION < 7
ZEND_FETCH_RESOURCE(mgr,SegmenterManager*,&mmseg_resource,-1,PHP_MMSEG_DESCRIPTOR_RES_NAME,le_mmseg_descriptor);
zend_hash_index_del(&EG(regular_list),Z_RESVAL_P(mmseg_resource));
#else
mgr = (SegmenterManager*) zend_fetch_resource(Z_RES_P(mmseg_resource), PHP_MMSEG_DESCRIPTOR_RES_NAME,le_mmseg_descriptor);
zend_hash_index_del(&EG(regular_list),Z_RES_P(mmseg_resource)->handle);
#endif
RETURN_TRUE;
}
// 字典的生成
PHP_FUNCTION(mmseg_gendict)
{
int argc = ZEND_NUM_ARGS();
char *path = NULL;
char *target = NULL;
#if PHP_MAJOR_VERSION < 7
int target_len;
int path_len;
#else
size_t target_len;
size_t path_len;
#endif
zend_bool b_plainText = 0;
if (zend_parse_parameters(argc TSRMLS_CC, "ss", &path, &path_len, &target, &target_len) == FAILURE)
return;
UnigramCorpusReader ur;
ur.open(path,b_plainText?"plain":NULL);
UnigramDict ud;
int ret = ud.import(ur);
ud.save(target);
//check
int i = 0;
for(i=0;i<ur.count();i++)
{
UnigramRecord* rec = ur.getAt(i);
if(ud.exactMatch(rec->key.c_str()) == rec->count){
continue;
}else{
RETURN_FALSE;
}
}//end for
RETURN_TRUE;
}
// 特殊短语字典的生成
PHP_FUNCTION(mmseg_gensynonyms)
{
int argc = ZEND_NUM_ARGS();
char *path = NULL;
char *target = NULL;
#if PHP_MAJOR_VERSION < 7
int path_len;
int target_len;
#else
size_t path_len;
size_t target_len;
#endif
zend_bool b_plainText = 0;
if (zend_parse_parameters(argc TSRMLS_CC, "ss", &path, &path_len, &target, &target_len) == FAILURE)
return;
SynonymsDict dict;
dict.import(path);
if(target)
dict.save(target);
else
dict.save("synonyms.dat");
RETURN_TRUE;
}
// 同义词词典的生成
PHP_FUNCTION(mmseg_genthesaurus)
{
int argc = ZEND_NUM_ARGS();
char *path = NULL;
char *target = NULL;
#if PHP_MAJOR_VERSION < 7
int path_len;
int target_len;
#else
size_t path_len;
size_t target_len;
#endif
zend_bool b_plainText = 0;
if (zend_parse_parameters(argc TSRMLS_CC, "ss", &path, &path_len, &target, &target_len) == FAILURE)
return;
ThesaurusDict tdict;
tdict.import(path, target);
RETURN_TRUE;
}
/*
* Local variables:
* tab-width: 4
* c-basic-offset: 4
* End:
* vim600: noet sw=4 ts=4 fdm=marker
* vim<600: noet sw=4 ts=4
*/
<commit_msg>change static pos<commit_after>#ifdef HAVE_CONFIG_H
#include "config.h"
#endif
extern "C" {
#include "php.h"
}
#include "php_ini.h"
#include "ext/standard/info.h"
#include "php_mmseg.h"
#include <sys/stat.h>
using namespace std;
// SegmenterManager
ZEND_DECLARE_MODULE_GLOBALS(mmseg)
/* True global resources - no need for thread safety here */
static int le_mmseg;
// mmseg segmenter manager句柄
static int le_mmseg_descriptor;
/* {{{ PHP_INI
*/
PHP_INI_BEGIN()
PHP_INI_ENTRY("mmseg.dict_dir", "/opt/etc", PHP_INI_ALL, NULL)
PHP_INI_ENTRY("mmseg.autoreload", "1", PHP_INI_ALL, NULL)
PHP_INI_END()
/* }}} */
/* Triggered at the beginning of a thread */
static void php_mmseg_globals_ctor(zend_mmseg_globals *mmseg_globals TSRMLS_DC)
{
struct stat st;
SegmenterManager* mgr = (SegmenterManager*) mmseg_globals->mgr;
mgr = new SegmenterManager();
int nRet = 0;
mmseg_globals->dict_mtime = 0;
nRet = mgr->init(INI_STR("mmseg.dict_dir"));
if (nRet == 0) {
mmseg_globals->mgr = (void*) mgr;
// 记录最后一次字典文件更改的数值
string dict_file_path;
dict_file_path = INI_STR("mmseg.dict_dir");
dict_file_path.append("/uni.lib");
if (stat(dict_file_path.c_str(), &st) == 0) {
mmseg_globals->dict_mtime = st.st_mtime;
MMSEG_LOG(ctime(&st.st_mtime));
}
MMSEG_LOG("minit load dictionary");
return ;
} else {
if (mgr != NULL) {
delete mgr;
mgr = NULL;
}
mmseg_globals->mgr = NULL;
return ;
}
}
/* Triggered at the end of a thread */
static void php_mmseg_globals_dtor(zend_mmseg_globals *mmseg_globals TSRMLS_DC)
{
SegmenterManager* mgr = (SegmenterManager*) mmseg_globals->mgr;
if (mgr != NULL) {
delete mgr;
mgr = NULL;
}
}
// mmseg 句柄的dtor函数
static void php_mmseg_descriptor_dtor(zend_rsrc_list_entry *rsrc TSRMLS_DC)
{
SegmenterManager *mgr = (SegmenterManager*)rsrc->ptr;
if (mgr != NULL) {
delete mgr;
mgr = NULL;
}
}
/* {{{ PHP_MINIT_FUNCTION
*/
PHP_MINIT_FUNCTION(mmseg)
{
REGISTER_INI_ENTRIES();
// 初始化mmseg资源句柄
le_mmseg_descriptor = zend_register_list_destructors_ex(php_mmseg_descriptor_dtor, NULL, PHP_MMSEG_DESCRIPTOR_RES_NAME,module_number);
// 初始化,如果初始化失败,则返回失败信息,(XXX: 未来将改变为如果初始化失败, 可以在程序里面调用init初始化)
#ifdef ZTS
ts_allocate_id(&mmseg_globals_id, sizeof(zend_mmseg_globals),
php_mmseg_globals_ctor, php_mmseg_globals_dtor);
#else
php_mmseg_globals_ctor(&mmseg_globals TSRMLS_CC);
#endif
return SUCCESS;
}
/* }}} */
/* {{{ PHP_MSHUTDOWN_FUNCTION
*/
PHP_MSHUTDOWN_FUNCTION(mmseg)
{
UNREGISTER_INI_ENTRIES();
#ifndef ZTS
php_mmseg_globals_dtor(&mmseg_globals TSRMLS_CC);
#endif
return SUCCESS;
}
/* }}} */
/* Remove if there's nothing to do at request start */
/* {{{ PHP_RINIT_FUNCTION
*/
PHP_RINIT_FUNCTION(mmseg)
{
#if defined(COMPILE_DL_MMSEG) && defined(ZTS) && defined(ZEND_TSRMLS_CACHE_UPDATE)
ZEND_TSRMLS_CACHE_UPDATE();
#endif
return SUCCESS;
}
/* }}} */
/* Remove if there's nothing to do at request end */
/* {{{ PHP_RSHUTDOWN_FUNCTION
*/
PHP_RSHUTDOWN_FUNCTION(mmseg)
{
return SUCCESS;
}
/* }}} */
/* {{{ PHP_MINFO_FUNCTION
*/
PHP_MINFO_FUNCTION(mmseg)
{
php_info_print_table_start();
php_info_print_table_header(2, "mmseg support", "enabled");
php_info_print_table_end();
DISPLAY_INI_ENTRIES();
}
/* }}} */
/* {{{ mmseg_functions[]
*
* Every user visible function must have an entry in mmseg_functions[].
*/
const zend_function_entry mmseg_functions[] = {
PHP_FE(mmseg_segment, NULL)
PHP_FE(mmseg_open, NULL)
PHP_FE(mmseg_close, NULL)
PHP_FE(mmseg_gendict, NULL)
PHP_FE(mmseg_gensynonyms, NULL)
PHP_FE(mmseg_genthesaurus, NULL)
PHP_FE_END /* Must be the last line in mmseg_functions[] */
};
/* }}} */
/* {{{ mmseg_module_entry
*/
zend_module_entry mmseg_module_entry = {
STANDARD_MODULE_HEADER,
"mmseg",
mmseg_functions,
PHP_MINIT(mmseg),
PHP_MSHUTDOWN(mmseg),
PHP_RINIT(mmseg), /* Replace with NULL if there's nothing to do at request start */
PHP_RSHUTDOWN(mmseg), /* Replace with NULL if there's nothing to do at request end */
PHP_MINFO(mmseg),
PHP_MMSEG_VERSION,
STANDARD_MODULE_PROPERTIES
};
/* }}} */
#ifdef COMPILE_DL_MMSEG
#ifdef ZTS
ZEND_TSRMLS_CACHE_DEFINE()
#endif
BEGIN_EXTERN_C()
ZEND_GET_MODULE(mmseg)
END_EXTERN_C()
#endif
/* The previous line is meant for vim and emacs, so it can correctly fold and
unfold functions in source code. See the corresponding marks just before
function definition, where the functions purpose is also documented. Please
follow this convention for the convenience of others editing your code.
*/
/* {{{ proto array mmseg_segment(string content)
*/
PHP_FUNCTION(mmseg_segment)
{
char *content = NULL;
int argc = ZEND_NUM_ARGS();
#if PHP_MAJOR_VERSION < 7
int content_len;
#else
size_t content_len;
#endif
SegmenterManager* mgr = NULL;
zval *mmseg_resource;
zend_bool autoreload = INI_BOOL("mmseg.autoreload");
// 判断传入参数的数量
if (argc == 1) {
struct stat st;
if (zend_parse_parameters(argc TSRMLS_CC, "s", &content, &content_len) == FAILURE)
return;
// 如果使用全局的字典文件,在这里看一下是否需要判断文件是否有改变
if (1 == autoreload) {
// 文件名
string dict_file_path;
dict_file_path = INI_STR("mmseg.dict_dir");
dict_file_path.append("/uni.lib");
if (stat(dict_file_path.c_str(), &st) == 0) {
if (st.st_mtime != MMSEG_G(dict_mtime)) {
MMSEG_G(dict_mtime) = st.st_mtime;
SegmenterManager* oldMgr = (SegmenterManager*)MMSEG_G(mgr);
SegmenterManager* newMgr;
newMgr = new SegmenterManager();
int nRet = 0;
nRet = newMgr->init(INI_STR("mmseg.dict_dir"));
if (nRet == 0) {
if (oldMgr) {
MMSEG_LOG("trying to delete old mgr");
delete oldMgr;
oldMgr = NULL;
}
MMSEG_LOG("load dictionary on change");
MMSEG_G(mgr) = newMgr;
} else {
// no change. still use oldMgr
MMSEG_LOG("no change, initialize new dict file failed");
newMgr = NULL;
}
} else {
MMSEG_LOG(ctime(&st.st_mtime));
MMSEG_LOG(ctime(&MMSEG_G(dict_mtime)));
MMSEG_LOG("no change, dict file no change");
// no change, still use old oldMgr
}
} else {
MMSEG_LOG("no change, stat new dict file failed");
}
} else {
MMSEG_LOG("no change, autoreload not set");
}
} else if (argc == 2){
if (zend_parse_parameters(argc TSRMLS_CC, "rs", &mmseg_resource, &content, &content_len) == FAILURE)
return;
#if PHP_MAJOR_VERSION < 7
ZEND_FETCH_RESOURCE(mgr,SegmenterManager*,&mmseg_resource,-1,PHP_MMSEG_DESCRIPTOR_RES_NAME,le_mmseg_descriptor);
#else
mgr = (SegmenterManager*) zend_fetch_resource(Z_RES_P(mmseg_resource), PHP_MMSEG_DESCRIPTOR_RES_NAME,le_mmseg_descriptor);
#endif
} else {
return;
}
mgr = (SegmenterManager*) MMSEG_G(mgr);
if (mgr == NULL) {
RETURN_NULL();
}
Segmenter* seg = mgr->getSegmenter();
u4 content_length = content_len;
seg->setBuffer((u1*)content, content_length);
array_init(return_value);
while(1)
{
u2 len = 0, symlen = 0;
char* tok = (char*)seg->peekToken(len,symlen);
if(!tok || !*tok || !len){
break;
}
//append new item
#if PHP_MAJOR_VERSION < 7
add_next_index_stringl(return_value, tok, len, 1);
#else
add_next_index_stringl(return_value, tok, len);
#endif
seg->popToken(len);
}
return ;
}
/* }}} */
PHP_FUNCTION(mmseg_open)
{
char *path = NULL;
int argc = ZEND_NUM_ARGS();
#if PHP_MAJOR_VERSION < 7
int path_len;
#else
size_t path_len;
#endif
if (zend_parse_parameters(argc TSRMLS_CC, "s", &path, &path_len) == FAILURE)
return;
// 生成新的对象
SegmenterManager* mgr = new SegmenterManager();
int nRet = 0;
nRet = mgr->init(path);
if (nRet == 0) {
// 注册这个资源
#if PHP_MAJOR_VERSION < 7
ZEND_REGISTER_RESOURCE(return_value,mgr,le_mmseg_descriptor);
#else
RETURN_RES(zend_register_resource(mgr, le_mmseg_descriptor));
#endif
} else {
RETURN_NULL();
}
}
PHP_FUNCTION(mmseg_close)
{
zval *mmseg_resource;
SegmenterManager* mgr;
int argc = ZEND_NUM_ARGS();
if (zend_parse_parameters(argc TSRMLS_CC, "r", &mmseg_resource) == FAILURE)
return;
#if PHP_MAJOR_VERSION < 7
ZEND_FETCH_RESOURCE(mgr,SegmenterManager*,&mmseg_resource,-1,PHP_MMSEG_DESCRIPTOR_RES_NAME,le_mmseg_descriptor);
zend_hash_index_del(&EG(regular_list),Z_RESVAL_P(mmseg_resource));
#else
mgr = (SegmenterManager*) zend_fetch_resource(Z_RES_P(mmseg_resource), PHP_MMSEG_DESCRIPTOR_RES_NAME,le_mmseg_descriptor);
zend_hash_index_del(&EG(regular_list),Z_RES_P(mmseg_resource)->handle);
#endif
RETURN_TRUE;
}
// 字典的生成
PHP_FUNCTION(mmseg_gendict)
{
int argc = ZEND_NUM_ARGS();
char *path = NULL;
char *target = NULL;
#if PHP_MAJOR_VERSION < 7
int target_len;
int path_len;
#else
size_t target_len;
size_t path_len;
#endif
zend_bool b_plainText = 0;
if (zend_parse_parameters(argc TSRMLS_CC, "ss", &path, &path_len, &target, &target_len) == FAILURE)
return;
UnigramCorpusReader ur;
ur.open(path,b_plainText?"plain":NULL);
UnigramDict ud;
int ret = ud.import(ur);
ud.save(target);
//check
int i = 0;
for(i=0;i<ur.count();i++)
{
UnigramRecord* rec = ur.getAt(i);
if(ud.exactMatch(rec->key.c_str()) == rec->count){
continue;
}else{
RETURN_FALSE;
}
}//end for
RETURN_TRUE;
}
// 特殊短语字典的生成
PHP_FUNCTION(mmseg_gensynonyms)
{
int argc = ZEND_NUM_ARGS();
char *path = NULL;
char *target = NULL;
#if PHP_MAJOR_VERSION < 7
int path_len;
int target_len;
#else
size_t path_len;
size_t target_len;
#endif
zend_bool b_plainText = 0;
if (zend_parse_parameters(argc TSRMLS_CC, "ss", &path, &path_len, &target, &target_len) == FAILURE)
return;
SynonymsDict dict;
dict.import(path);
if(target)
dict.save(target);
else
dict.save("synonyms.dat");
RETURN_TRUE;
}
// 同义词词典的生成
PHP_FUNCTION(mmseg_genthesaurus)
{
int argc = ZEND_NUM_ARGS();
char *path = NULL;
char *target = NULL;
#if PHP_MAJOR_VERSION < 7
int path_len;
int target_len;
#else
size_t path_len;
size_t target_len;
#endif
zend_bool b_plainText = 0;
if (zend_parse_parameters(argc TSRMLS_CC, "ss", &path, &path_len, &target, &target_len) == FAILURE)
return;
ThesaurusDict tdict;
tdict.import(path, target);
RETURN_TRUE;
}
/*
* Local variables:
* tab-width: 4
* c-basic-offset: 4
* End:
* vim600: noet sw=4 ts=4 fdm=marker
* vim<600: noet sw=4 ts=4
*/
<|endoftext|>
|
<commit_before>// bdls_processutil.cpp -*-C++-*-
// ----------------------------------------------------------------------------
// NOTICE
//
// This component is not up to date with current BDE coding standards, and
// should not be used as an example for new development.
// ----------------------------------------------------------------------------
#include <bdls_processutil.h>
#include <bsls_ident.h>
BSLS_IDENT_RCSID(bdls_processutil_cpp,"$Id$ $CSID$")
#include <bsls_assert.h>
#include <bsls_platform.h>
#include <bsl_algorithm.h>
#include <bsl_iostream.h>
#if !defined BSLS_PLATFORM_OS_WINDOWS
# include <unistd.h> // getpid
# if defined BSLS_PLATFORM_OS_AIX
# include <bslma_allocator.h>
# include <bslma_deallocatorguard.h>
# include <bslma_default.h>
# include <bsl_algorithm.h>
# include <sys/procfs.h>
# include <sys/stat.h>
# include <sys/types.h>
# include <procinfo.h>
# include <stdio.h>
# elif defined BSLS_PLATFORM_OS_CYGWIN
# ifndef _REENTRANT
# define _REENTRANT
# endif
# include <bdlsb_memoutstreambuf.h>
# include <bsl_fstream.h>
# include <fcntl.h>
# include <procfs.h>
# elif defined BSLS_PLATFORM_OS_DARWIN
# include <bsl_algorithm.h>
# include <libproc.h>
# elif defined BSLS_PLATFORM_OS_HPUX
# include <sys/pstat.h>
# elif defined BSLS_PLATFORM_OS_LINUX
# include <bslma_allocator.h>
# include <bslma_deallocatorguard.h>
# include <bslma_default.h>
# include <bsls_types.h>
# include <bsl_algorithm.h>
# include <errno.h>
# include <sys/stat.h>
# include <sys/types.h>
# elif defined BSLS_PLATFORM_OS_SOLARIS
# include <stdlib.h>
# include <sys/stat.h>
# include <sys/types.h>
# include <stdio.h>
# else
# error Unrecognized Platform
# endif
#else // if defined BSLS_PLATFORM_OS_WINDOWS
# include <bdlde_charconvertutf16.h>
# include <bdlma_localsequentialallocator.h>
# include <windows.h>
#endif
namespace BloombergLP {
namespace bdls {
// ------------------
// struct ProcessUtil
// ------------------
// CLASS METHODS
int ProcessUtil::getProcessId()
{
#ifdef BSLS_PLATFORM_OS_WINDOWS
return static_cast<int>(GetCurrentProcessId());
#else
return static_cast<int>(::getpid());
#endif
}
int ProcessUtil::getProcessName(bsl::string *result)
{
BSLS_ASSERT(result);
result->clear();
#if defined BSLS_PLATFORM_OS_AIX
struct procentry64 procbuffer;
enum { k_BUF_LEN = 64 * 1024 };
bslma::Allocator *allocator = bslma::Default::defaultAllocator();
char *argsbuffer = static_cast<char *>(allocator->allocate(k_BUF_LEN));
char *end = argsbuffer + k_BUF_LEN;
bslma::DeallocatorGuard<bslma::Allocator> guard(argsbuffer, allocator);
procbuffer.pi_pid = ProcessUtil::getProcessId();
// '::getargs' should fill the beginning of 'argsbuffer' with
// null-terminated 'argv[0]', which might be a relative path.
if (0 == ::getargs(&procbuffer, sizeof(procbuffer), argsbuffer, k_BUF_LEN)
&& bsl::find(argsbuffer, end, '\0') < end) {
result->assign(argsbuffer);
}
struct stat s;
if (result->empty() ||
('/' != (*result)[0] && 0 != ::stat(result->c_str(), &s))) {
// Either 'getargs' failed, or the path is relative and the executable
// is not there. We have probably done a 'chdir' since program
// start-up. See if we can find the executable from "/proc".
char fileNameBuf[50];
snprintf(fileNameBuf,
sizeof(fileNameBuf),
"/proc/%d/object/a.out",
ProcessUtil::getProcessId());
if (0 == ::stat(fileNameBuf, &s)) {
result->assign(fileNameBuf);
}
}
#elif defined BSLS_PLATFORM_OS_CYGWIN
enum { NUM_ELEMENTS = 14 + 16 }; // "/proc/<pid>/cmdline"
bdlsb::MemOutStreamBuf osb(NUM_ELEMENTS);
bsl::ostream os(&osb);
os << "/proc/" << ProcessUtil::getProcessId() << "/cmdline" << bsl::ends;
const char *procfs = osb.data();
bsl::ifstream ifs;
ifs.open(procfs, bsl::ios_base::in | bsl::ios_base::binary);
if (ifs.fail()) {
return -1; // RETURN
}
ifs >> *result;
bsl::string::size_type pos = result->find_first_of('\0');
if (bsl::string::npos != pos) {
result->resize(pos);
}
#elif defined BSLS_PLATFORM_OS_DARWIN
enum { k_BUF_LEN = 4 * 1024 };
char buf[k_BUF_LEN];
if (proc_pidpath(ProcessUtil::getProcessId(), buf, k_BUF_LEN) <= 0) {
return -1; // RETURN
}
if (buf + k_BUF_LEN == bsl::find(buf + 0, buf + k_BUF_LEN, 0)) {
return -1; // RETURN
}
result->assign(buf);
#elif defined BSLS_PLATFORM_OS_HPUX
result->resize(1024);
int rc = pstat_getcommandline(&(*result->begin()),
result->size(),
1,
ProcessUtil::getProcessId());
if (rc < 0) {
return -1; // RETURN
}
bsl::string::size_type pos = result->find_first_of(' ');
if (bsl::string::npos != pos) {
result->resize(pos);
}
#elif defined BSLS_PLATFORM_OS_LINUX
// First, we attempt to get the executable name through the symlink
// "/proc/self/exe", because, if successful, that will yield a full path
// with symlinks resolved.
const char linkName[] = { "/proc/self/exe" };
struct stat s;
bsls::Types::Int64 rc = ::lstat(linkName, &s);
if (0 == rc && S_ISLNK(s.st_mode)) {
enum { k_BUF_LEN = 64 * 1024 };
bslma::Allocator *allocator = bslma::Default::defaultAllocator();
char *linkBuf = static_cast<char *>(allocator->allocate(k_BUF_LEN));
bslma::DeallocatorGuard<bslma::Allocator> guard(linkBuf, allocator);
rc = ::readlink(linkName, linkBuf, k_BUF_LEN);
if (0 < rc && rc < k_BUF_LEN && linkBuf + rc ==
bsl::find(linkBuf, linkBuf + rc + 1, 0)) {
result->assign(linkBuf);
}
}
if (result->empty()) {
// Reading the symlink failed, probably because "/proc" is sometimes
// unavailable. We fall back on reading '::program_invocation_name',
// which will just yield 'argv[0]', which may or may not be a relative
// path, a less optimal result. Note that this can still cope with the
// case where the path of the executable contains spaces.
result->assign(::program_invocation_name);
}
#elif defined BSLS_PLATFORM_OS_SOLARIS
// '::getexecname' will return an absolute path with symlinks resolved.
result->assign(::getexecname());
#elif defined BSLS_PLATFORM_OS_WINDOWS
// On Windows, 'argv[0]' is always an absolute path, even if it was
// specified on the cmd line as a relative path. The following code yields
// the full path.
static const size_t k_INITIAL_SIZE = MAX_PATH + 1;
bdlma::LocalSequentialAllocator<sizeof(wchar_t) * k_INITIAL_SIZE> la;
bsl::wstring wResult(MAX_PATH, L'\0', &la);
while (wResult.length() <= 4 * k_INITIAL_SIZE) {
DWORD length = GetModuleFileNameW(0, &wResult[0], wResult.length());
if (length == 0) { // Error
return 1; // RETURN
}
else if (length < wResult.length()) { // Success
wResult.resize(length);
return bdlde::CharConvertUtf16::utf16ToUtf8(result, wResult);
// RETURN
}
else { // Not enough space for the process name in 'wResult'
wResult.resize(wResult.length() * 2); // Make more space
}
}
return -1; // The path name is too long (more than 4 * k_INITIAL_SIZE)
#else
# error Unrecognized Platform
#endif
return result->empty(); // 'false' == 0 if success
}
} // close package namespace
} // close enterprise namespace
// ----------------------------------------------------------------------------
// Copyright 2015 Bloomberg Finance L.P.
//
// Licensed under the Apache License, Version 2.0 (the "License");
// you may not use this file except in compliance with the License.
// You may obtain a copy of the License at
//
// http://www.apache.org/licenses/LICENSE-2.0
//
// Unless required by applicable law or agreed to in writing, software
// distributed under the License is distributed on an "AS IS" BASIS,
// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
// See the License for the specific language governing permissions and
// limitations under the License.
// ----------------------------- END-OF-FILE ----------------------------------
<commit_msg>bdls_processutil: slight enhancement of Darwin<commit_after>// bdls_processutil.cpp -*-C++-*-
// ----------------------------------------------------------------------------
// NOTICE
//
// This component is not up to date with current BDE coding standards, and
// should not be used as an example for new development.
// ----------------------------------------------------------------------------
#include <bdls_processutil.h>
#include <bsls_ident.h>
BSLS_IDENT_RCSID(bdls_processutil_cpp,"$Id$ $CSID$")
#include <bsls_assert.h>
#include <bsls_platform.h>
#include <bsl_algorithm.h>
#include <bsl_iostream.h>
#if !defined BSLS_PLATFORM_OS_WINDOWS
# include <unistd.h> // getpid
# if defined BSLS_PLATFORM_OS_AIX
# include <bslma_allocator.h>
# include <bslma_deallocatorguard.h>
# include <bslma_default.h>
# include <bsl_algorithm.h>
# include <sys/procfs.h>
# include <sys/stat.h>
# include <sys/types.h>
# include <procinfo.h>
# include <stdio.h>
# elif defined BSLS_PLATFORM_OS_CYGWIN
# ifndef _REENTRANT
# define _REENTRANT
# endif
# include <bdlsb_memoutstreambuf.h>
# include <bsl_fstream.h>
# include <fcntl.h>
# include <procfs.h>
# elif defined BSLS_PLATFORM_OS_DARWIN
# include <bsl_algorithm.h>
# include <libproc.h>
# elif defined BSLS_PLATFORM_OS_HPUX
# include <sys/pstat.h>
# elif defined BSLS_PLATFORM_OS_LINUX
# include <bslma_allocator.h>
# include <bslma_deallocatorguard.h>
# include <bslma_default.h>
# include <bsls_types.h>
# include <bsl_algorithm.h>
# include <errno.h>
# include <sys/stat.h>
# include <sys/types.h>
# elif defined BSLS_PLATFORM_OS_SOLARIS
# include <stdlib.h>
# include <sys/stat.h>
# include <sys/types.h>
# include <stdio.h>
# else
# error Unrecognized Platform
# endif
#else // if defined BSLS_PLATFORM_OS_WINDOWS
# include <bdlde_charconvertutf16.h>
# include <bdlma_localsequentialallocator.h>
# include <windows.h>
#endif
namespace BloombergLP {
namespace bdls {
// ------------------
// struct ProcessUtil
// ------------------
// CLASS METHODS
int ProcessUtil::getProcessId()
{
#ifdef BSLS_PLATFORM_OS_WINDOWS
return static_cast<int>(GetCurrentProcessId());
#else
return static_cast<int>(::getpid());
#endif
}
int ProcessUtil::getProcessName(bsl::string *result)
{
BSLS_ASSERT(result);
result->clear();
#if defined BSLS_PLATFORM_OS_AIX
struct procentry64 procbuffer;
enum { k_BUF_LEN = 64 * 1024 };
bslma::Allocator *allocator = bslma::Default::defaultAllocator();
char *argsbuffer = static_cast<char *>(allocator->allocate(k_BUF_LEN));
char *end = argsbuffer + k_BUF_LEN;
bslma::DeallocatorGuard<bslma::Allocator> guard(argsbuffer, allocator);
procbuffer.pi_pid = ProcessUtil::getProcessId();
// '::getargs' should fill the beginning of 'argsbuffer' with
// null-terminated 'argv[0]', which might be a relative path.
if (0 == ::getargs(&procbuffer, sizeof(procbuffer), argsbuffer, k_BUF_LEN)
&& bsl::find(argsbuffer, end, '\0') < end) {
result->assign(argsbuffer);
}
struct stat s;
if (result->empty() ||
('/' != (*result)[0] && 0 != ::stat(result->c_str(), &s))) {
// Either 'getargs' failed, or the path is relative and the executable
// is not there. We have probably done a 'chdir' since program
// start-up. See if we can find the executable from "/proc".
char fileNameBuf[50];
snprintf(fileNameBuf,
sizeof(fileNameBuf),
"/proc/%d/object/a.out",
ProcessUtil::getProcessId());
if (0 == ::stat(fileNameBuf, &s)) {
result->assign(fileNameBuf);
}
}
#elif defined BSLS_PLATFORM_OS_CYGWIN
enum { NUM_ELEMENTS = 14 + 16 }; // "/proc/<pid>/cmdline"
bdlsb::MemOutStreamBuf osb(NUM_ELEMENTS);
bsl::ostream os(&osb);
os << "/proc/" << ProcessUtil::getProcessId() << "/cmdline" << bsl::ends;
const char *procfs = osb.data();
bsl::ifstream ifs;
ifs.open(procfs, bsl::ios_base::in | bsl::ios_base::binary);
if (ifs.fail()) {
return -1; // RETURN
}
ifs >> *result;
bsl::string::size_type pos = result->find_first_of('\0');
if (bsl::string::npos != pos) {
result->resize(pos);
}
#elif defined BSLS_PLATFORM_OS_DARWIN
// We empirically determined that 'proc_pidpath' won't tolerate a buffer
// much longer than 4K, and 4K is short enough not to be worth dynamically
// allocating.
enum { k_BUF_LEN = 4 * 1024 };
char buf[k_BUF_LEN];
bsl::fill(buf + 0, buf + k_BUF_LEN, '*');
if (proc_pidpath(ProcessUtil::getProcessId(), buf, k_BUF_LEN) <= 0) {
return -1; // RETURN
}
if (buf + k_BUF_LEN == bsl::find(buf + 0, buf + k_BUF_LEN, 0)) {
return -1; // RETURN
}
result->assign(buf);
#elif defined BSLS_PLATFORM_OS_HPUX
result->resize(1024);
int rc = pstat_getcommandline(&(*result->begin()),
result->size(),
1,
ProcessUtil::getProcessId());
if (rc < 0) {
return -1; // RETURN
}
bsl::string::size_type pos = result->find_first_of(' ');
if (bsl::string::npos != pos) {
result->resize(pos);
}
#elif defined BSLS_PLATFORM_OS_LINUX
// First, we attempt to get the executable name through the symlink
// "/proc/self/exe", because, if successful, that will yield a full path
// with symlinks resolved.
const char linkName[] = { "/proc/self/exe" };
struct stat s;
bsls::Types::Int64 rc = ::lstat(linkName, &s);
if (0 == rc && S_ISLNK(s.st_mode)) {
enum { k_BUF_LEN = 64 * 1024 };
bslma::Allocator *allocator = bslma::Default::defaultAllocator();
char *linkBuf = static_cast<char *>(allocator->allocate(k_BUF_LEN));
bslma::DeallocatorGuard<bslma::Allocator> guard(linkBuf, allocator);
rc = ::readlink(linkName, linkBuf, k_BUF_LEN);
if (0 < rc && rc < k_BUF_LEN && linkBuf + rc ==
bsl::find(linkBuf, linkBuf + rc + 1, 0)) {
result->assign(linkBuf);
}
}
if (result->empty()) {
// Reading the symlink failed, probably because "/proc" is sometimes
// unavailable. We fall back on reading '::program_invocation_name',
// which will just yield 'argv[0]', which may or may not be a relative
// path, a less optimal result. Note that this can still cope with the
// case where the path of the executable contains spaces.
result->assign(::program_invocation_name);
}
#elif defined BSLS_PLATFORM_OS_SOLARIS
// '::getexecname' will return an absolute path with symlinks resolved.
result->assign(::getexecname());
#elif defined BSLS_PLATFORM_OS_WINDOWS
// On Windows, 'argv[0]' is always an absolute path, even if it was
// specified on the cmd line as a relative path. The following code yields
// the full path.
static const size_t k_INITIAL_SIZE = MAX_PATH + 1;
bdlma::LocalSequentialAllocator<sizeof(wchar_t) * k_INITIAL_SIZE> la;
bsl::wstring wResult(MAX_PATH, L'\0', &la);
while (wResult.length() <= 4 * k_INITIAL_SIZE) {
DWORD length = GetModuleFileNameW(0, &wResult[0], wResult.length());
if (length == 0) { // Error
return 1; // RETURN
}
else if (length < wResult.length()) { // Success
wResult.resize(length);
return bdlde::CharConvertUtf16::utf16ToUtf8(result, wResult);
// RETURN
}
else { // Not enough space for the process name in 'wResult'
wResult.resize(wResult.length() * 2); // Make more space
}
}
return -1; // The path name is too long (more than 4 * k_INITIAL_SIZE)
#else
# error Unrecognized Platform
#endif
return result->empty(); // 'false' == 0 if success
}
} // close package namespace
} // close enterprise namespace
// ----------------------------------------------------------------------------
// Copyright 2015 Bloomberg Finance L.P.
//
// Licensed under the Apache License, Version 2.0 (the "License");
// you may not use this file except in compliance with the License.
// You may obtain a copy of the License at
//
// http://www.apache.org/licenses/LICENSE-2.0
//
// Unless required by applicable law or agreed to in writing, software
// distributed under the License is distributed on an "AS IS" BASIS,
// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
// See the License for the specific language governing permissions and
// limitations under the License.
// ----------------------------- END-OF-FILE ----------------------------------
<|endoftext|>
|
<commit_before>#include <string>
#include <iostream>
#include <windows.h>
#define MAXWAIT 10000
bool insertDll(DWORD procID, std::string dll);
BOOL InjectDLL(DWORD dwProcessId, LPCSTR lpszDLLPath);
bool InjectDll(char *dllName, DWORD ProcessID);
void main( int argc, char* argv[] )
{
InjectDLL( 6968, "c:\\src\\github\\Tagger\\playground\\HookSpy\\Debug\\HookSpyDll.dll" );
//InjectDll( "c:\\Program Files (x86)\\totalcmd\\CABRK.DLL", 6968 );
}
bool GimmePrivileges(){
HANDLE Token;
TOKEN_PRIVILEGES tp;
if(OpenProcessToken(GetCurrentProcess(), TOKEN_ADJUST_PRIVILEGES | TOKEN_QUERY, &Token) )
{
LookupPrivilegeValue(NULL, SE_DEBUG_NAME, &tp.Privileges[0].Luid);
tp.PrivilegeCount = 1;
tp.Privileges[0].Attributes = SE_PRIVILEGE_ENABLED;
AdjustTokenPrivileges(Token, 0, &tp, sizeof(tp), NULL, NULL);
return true;
}
return false;
}
BOOL InjectDLL(DWORD dwProcessId, LPCSTR lpszDLLPath)
{
HANDLE hProcess, hThread;
LPVOID lpBaseAddr, lpFuncAddr;
DWORD dwMemSize, dwExitCode;
BOOL bSuccess = FALSE;
HMODULE hUserDLL;
GimmePrivileges();
if((hProcess = OpenProcess(PROCESS_CREATE_THREAD|PROCESS_QUERY_INFORMATION|PROCESS_VM_OPERATION
|PROCESS_VM_WRITE|PROCESS_VM_READ, FALSE, dwProcessId)))
{
dwMemSize = lstrlenA(lpszDLLPath) + 1;
if(lpBaseAddr = VirtualAllocEx(hProcess, NULL, dwMemSize, MEM_COMMIT, PAGE_READWRITE))
{
if(WriteProcessMemory(hProcess, lpBaseAddr, lpszDLLPath, dwMemSize, NULL))
{
if(hUserDLL = LoadLibrary(TEXT("kernel32.dll")))
{
if(lpFuncAddr = GetProcAddress(hUserDLL, "LoadLibraryA"))
{
if(hThread = CreateRemoteThread(hProcess, NULL, 0, (LPTHREAD_START_ROUTINE)lpFuncAddr, lpBaseAddr, 0, NULL))
{
WaitForSingleObject(hThread, INFINITE);
if(GetExitCodeThread(hThread, &dwExitCode)) {
bSuccess = (dwExitCode != 0) ? TRUE : FALSE;
}
CloseHandle(hThread);
}
}
FreeLibrary(hUserDLL);
}
}
VirtualFreeEx(hProcess, lpBaseAddr, 0, MEM_RELEASE);
}
CloseHandle(hProcess);
}
return bSuccess;
}
bool InjectDll(char *dllName, DWORD ProcessID)
{
if (!GimmePrivileges ())
{
printf ("Error elivating privileges \n");
return false;
}
else
printf ("Privileges elivated \n");
//DWORD ProcessID = GetTargetProcessIdFromProcname (procName); //i didnt include this function because i know for a fact it works
HANDLE Proc;
HANDLE RemoteThread;
char buf[50]={0};
LPVOID RemoteString, LoadLibAddy;
if(!ProcessID)
return false;
Proc = OpenProcess(PROCESS_ALL_ACCESS, FALSE, ProcessID);
if(!Proc)
{
printf("OpenProcess() failed: %d \n", GetLastError());
return false;
}
LoadLibAddy = (LPVOID)GetProcAddress(GetModuleHandle(L"kernel32.dll"), "LoadLibraryA");
RemoteString = (LPVOID)VirtualAllocEx(Proc, NULL, strlen(dllName), MEM_RESERVE|MEM_COMMIT, PAGE_READWRITE);
if (!WriteProcessMemory(Proc, (LPVOID)RemoteString, dllName,strlen(dllName), NULL))
{
printf ("writeProcMem error: %d \n", GetLastError ());
return false;
}
RemoteThread = CreateRemoteThread(Proc, NULL, NULL, (LPTHREAD_START_ROUTINE)LoadLibAddy, (LPVOID)RemoteString, NULL, NULL);
if (RemoteThread == NULL)
{
printf ("CreateRemoteThread error: %d \n", GetLastError());
return false;
}
CloseHandle(Proc);
return true;
}<commit_msg>All call to WinAPI functions report error on fail. Graceful resource cleanup is not implemented yet.<commit_after>#include <string>
#include <iostream>
#include <windows.h>
#include <conio.h>
using namespace std;
void AddDebugPrivilege();
void InjectDll( DWORD dwProcessId, LPCSTR lpszDLLPath );
void main( int argc, char* argv[] )
{
cout << "Adding debug privilege to current process..." << endl;
AddDebugPrivilege();
int process = atoi( argv[1] );
LPCSTR injectedDll = argv[2];
cout << "Injecting dll: " << injectedDll << endl;
cout << "To process ID: " << process << endl;
InjectDll( process, injectedDll );
cout << "Dll was successfully injected." << endl;
_getch();
}
void AddDebugPrivilege()
{
HANDLE token;
HANDLE injector = GetCurrentProcess();
TOKEN_PRIVILEGES privileges;
if( 0 == OpenProcessToken( injector, TOKEN_ADJUST_PRIVILEGES | TOKEN_QUERY, &token ) )
{
cout << "OpenProcessToken failed with code: " << GetLastError() << endl;
exit( 1 );
}
if( 0 == LookupPrivilegeValue( NULL, SE_DEBUG_NAME, &privileges.Privileges[0].Luid ) )
{
cout << "LookupPrivilegeValue failed with code: " << GetLastError() << endl;
exit( 1 );
}
privileges.PrivilegeCount = 1;
privileges.Privileges[0].Attributes = SE_PRIVILEGE_ENABLED;
if( 0 == AdjustTokenPrivileges( token, 0, &privileges, sizeof(privileges), NULL, NULL ) )
{
cout << "AdjustTokenPrivileges failed with code: " << GetLastError() << endl;
exit( 1 );
}
}
void InjectDll( DWORD processId, LPCSTR dllPath )
{
HANDLE hProcess = OpenProcess(
PROCESS_CREATE_THREAD|
PROCESS_QUERY_INFORMATION|
PROCESS_VM_OPERATION|
PROCESS_VM_WRITE|
PROCESS_VM_READ,
FALSE,
processId);
if( NULL == hProcess )
{
cout << "OpenProcess failed with code: " << GetLastError() << endl;
exit(1);
}
DWORD dwMemSize = lstrlenA(dllPath) + 1;
LPVOID lpBaseAddr = VirtualAllocEx( hProcess, NULL, dwMemSize, MEM_COMMIT, PAGE_READWRITE );
if( NULL == lpBaseAddr )
{
cout << "VirtualAllocEx failed with code: " << GetLastError() << endl;
exit(1);
}
BOOL memoryWriteSuccess = WriteProcessMemory( hProcess, lpBaseAddr, dllPath, dwMemSize, NULL );
if( 0 == memoryWriteSuccess )
{
cout << "WriteProcessMemory failed with code: " << GetLastError() << endl;
exit(1);
}
HMODULE hUserDLL = LoadLibrary( TEXT("kernel32.dll") );
if( NULL == hUserDLL )
{
cout << "LoadLibrary failed with code: " << GetLastError() << endl;
exit(1);
}
LPVOID lpFuncAddr = GetProcAddress( hUserDLL, "LoadLibraryA" );
if( NULL == lpFuncAddr )
{
cout << "GetProcAddress failed with code: " << GetLastError() << endl;
exit(1);
}
HANDLE hThread = CreateRemoteThread( hProcess, NULL, 0, (LPTHREAD_START_ROUTINE)lpFuncAddr, lpBaseAddr, 0, NULL );
if( NULL == hThread )
{
cout << "CreateRemoteThread failed with code: " << GetLastError() << endl;
exit(1);
}
DWORD waitResult = WaitForSingleObject( hThread, INFINITE );
if( WAIT_OBJECT_0 != waitResult )
{
cout << "WaitForSingleObject failed. Status: " << waitResult << ". Last error: " << GetLastError() << endl;
exit(1);
}
DWORD dwExitCode;
BOOL exitThreadResult = GetExitCodeThread( hThread, &dwExitCode );
if( 0 == exitThreadResult )
{
cout << "GetExitCodeThread failed with code: " << GetLastError() << endl;
exit(1);
}
if( 0 == dwExitCode )
{
cout << "Remote LoadLibrary failed with code: " << GetLastError() << endl;
exit(1);
}
CloseHandle( hThread );
FreeLibrary( hUserDLL );
VirtualFreeEx( hProcess, lpBaseAddr, 0, MEM_RELEASE );
CloseHandle( hProcess );
}
<|endoftext|>
|
<commit_before>/*
* The MIT License (MIT)
*
* Copyright (c) 2017 Nathan Osman
*
* Permission is hereby granted, free of charge, to any person obtaining a copy
* of this software and associated documentation files (the "Software"), to
* deal in the Software without restriction, including without limitation the
* rights to use, copy, modify, merge, publish, distribute, sublicense, and/or
* sell copies of the Software, and to permit persons to whom the Software is
* furnished to do so, subject to the following conditions:
*
* The above copyright notice and this permission notice shall be included in
* all copies or substantial portions of the Software.
*
* THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
* IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
* FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
* AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
* LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING
* FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS
* IN THE SOFTWARE.
*/
#include <QLabel>
#include <QVBoxLayout>
#include "intropage.h"
IntroPage::IntroPage()
{
setTitle(tr("Introduction"));
setSubTitle(tr("Welcome to NitroShare"));
QLabel *label = new QLabel(tr(
"Thank you for installing NitroShare!\n\nThe application is designed "
"to make transferring information between devices as simple as "
"possible. Here are just some of the features included:\n\n"
"\u2022 Automatic peer discovery\n"
"\u2022 Extremely fast file transfers\n"
"\u2022 Compatibility with all major platforms\n\n"
"This wizard will guide you through the initial setup process to help "
"ensure NitroShare works exactly the way you want it to."
));
label->setWordWrap(true);
QVBoxLayout *vboxLayout = new QVBoxLayout;
vboxLayout->addWidget(label);
setLayout(vboxLayout);
}
<commit_msg>Replace Unicode characters that do not display correctly on Windows.<commit_after>/*
* The MIT License (MIT)
*
* Copyright (c) 2017 Nathan Osman
*
* Permission is hereby granted, free of charge, to any person obtaining a copy
* of this software and associated documentation files (the "Software"), to
* deal in the Software without restriction, including without limitation the
* rights to use, copy, modify, merge, publish, distribute, sublicense, and/or
* sell copies of the Software, and to permit persons to whom the Software is
* furnished to do so, subject to the following conditions:
*
* The above copyright notice and this permission notice shall be included in
* all copies or substantial portions of the Software.
*
* THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
* IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
* FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
* AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
* LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING
* FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS
* IN THE SOFTWARE.
*/
#include <QLabel>
#include <QVBoxLayout>
#include "intropage.h"
IntroPage::IntroPage()
{
setTitle(tr("Introduction"));
setSubTitle(tr("Welcome to NitroShare"));
QLabel *label = new QLabel(tr(
"Thank you for installing NitroShare!\n\nThe application is designed "
"to make transferring information between devices as simple as "
"possible. Here are just some of the features included:\n\n"
"- Automatic peer discovery\n"
"- Extremely fast file transfers\n"
"- Compatibility with all major platforms\n\n"
"This wizard will guide you through the initial setup process to help "
"ensure NitroShare works exactly the way you want it to."
));
label->setWordWrap(true);
QVBoxLayout *vboxLayout = new QVBoxLayout;
vboxLayout->addWidget(label);
setLayout(vboxLayout);
}
<|endoftext|>
|
<commit_before>/* -*- Mode: C++; tab-width: 4; c-basic-offset: 4; indent-tabs-mode: nil -*- */
#include "config.h"
#include "vbucket.hh"
#include "ep_engine.h"
#include "ep.hh"
#include "backfill.hh"
static bool isMemoryUsageTooHigh(EPStats &stats) {
double currentSize = static_cast<double>(stats.currentSize.get() + stats.memOverhead.get());
double maxSize = static_cast<double>(stats.maxDataSize.get());
return currentSize > (maxSize * BACKFILL_MEM_THRESHOLD);
}
/**
* Callback class used to process an item backfilled from disk and push it into
* the corresponding TAP queue.
*/
class BackfillDiskCallback : public Callback<GetValue> {
public:
BackfillDiskCallback(const std::string &n, TapConnMap &tcm, EventuallyPersistentEngine* e)
: tapConnName(n), connMap(tcm), engine(e) {
assert(engine);
}
void callback(GetValue &val);
private:
const std::string tapConnName;
TapConnMap &connMap;
EventuallyPersistentEngine *engine;
};
void BackfillDiskCallback::callback(GetValue &gv) {
ReceivedItemTapOperation tapop(true);
// if the tap connection is closed, then free an Item instance
if (!connMap.performTapOp(tapConnName, tapop, gv.getValue())) {
delete gv.getValue();
}
NotifyPausedTapOperation notifyOp;
connMap.performTapOp(tapConnName, notifyOp, engine);
}
bool BackfillDiskLoad::callback(Dispatcher &d, TaskId t) {
bool valid = false;
if (isMemoryUsageTooHigh(engine->getEpStats())) {
getLogger()->log(EXTENSION_LOG_INFO, NULL,
"VBucket %d backfill task from disk is temporarily suspended "
"because the current memory usage is too high.\n",
vbucket);
d.snooze(t, 1);
return true;
}
if (connMap.checkConnectivity(name) && !engine->getEpStore()->isFlushAllScheduled()) {
shared_ptr<Callback<GetValue> > backfill_cb(new BackfillDiskCallback(name, connMap, engine));
store->dump(vbucket, backfill_cb);
valid = true;
}
getLogger()->log(EXTENSION_LOG_INFO, NULL,
"VBucket %d backfill task from disk is completed.\n",
vbucket);
// Should decr the disk backfill counter regardless of the connectivity status
CompleteDiskBackfillTapOperation op;
connMap.performTapOp(name, op, static_cast<void*>(NULL));
if (valid && connMap.checkBackfillCompletion(name)) {
engine->notifyNotificationThread();
}
return false;
}
std::string BackfillDiskLoad::description() {
std::stringstream rv;
rv << "Loading TAP backfill from disk for vb " << vbucket;
return rv.str();
}
bool BackFillVisitor::visitBucket(RCPtr<VBucket> &vb) {
apply();
if (vBucketFilter(vb->getId())) {
VBucketVisitor::visitBucket(vb);
// If the current resident ratio for a given vbucket is below the resident threshold
// for memory backfill only, schedule the disk backfill for more efficient bg fetches.
double numItems = static_cast<double>(vb->ht.getNumItems());
double numNonResident = static_cast<double>(vb->ht.getNumNonResidentItems());
if (numItems == 0) {
return true;
}
double residentThreshold = engine->getTapConfig().getBackfillResidentThreshold();
residentRatioBelowThreshold =
((numItems - numNonResident) / numItems) < residentThreshold ? true : false;
if (efficientVBDump && residentRatioBelowThreshold) {
vbuckets.push_back(vb->getId());
ScheduleDiskBackfillTapOperation tapop;
engine->tapConnMap->performTapOp(name, tapop, static_cast<void*>(NULL));
}
// When the backfill is scheduled for a given vbucket, set the TAP cursor to
// the beginning of the open checkpoint.
engine->tapConnMap->SetCursorToOpenCheckpoint(name, vb->getId());
return true;
}
return false;
}
void BackFillVisitor::visit(StoredValue *v) {
// If efficient VBdump is supported and an item is not resident,
// skip the item as it will be fetched by the disk backfill.
if (efficientVBDump && residentRatioBelowThreshold && !v->isResident()) {
return;
}
std::string k = v->getKey();
queued_item qi(new QueuedItem(k, currentBucket->getId(), queue_op_set,
-1, v->getId()));
uint16_t shardId = engine->kvstore->getShardId(*qi);
found.push_back(std::make_pair(shardId, qi));
}
void BackFillVisitor::apply(void) {
// If efficient VBdump is supported, schedule all the disk backfill tasks.
if (efficientVBDump) {
std::vector<uint16_t>::iterator it = vbuckets.begin();
for (; it != vbuckets.end(); it++) {
Dispatcher *d(engine->epstore->getRODispatcher());
KVStore *underlying(engine->epstore->getROUnderlying());
assert(d);
getLogger()->log(EXTENSION_LOG_INFO, NULL,
"Schedule a full backfill from disk for vbucket %d.\n",
*it);
shared_ptr<DispatcherCallback> cb(new BackfillDiskLoad(name,
engine,
*engine->tapConnMap,
underlying,
*it,
validityToken));
d->schedule(cb, NULL, Priority::TapBgFetcherPriority);
}
vbuckets.clear();
}
setEvents();
}
void BackFillVisitor::setEvents() {
if (checkValidity()) {
if (!found.empty()) {
// Don't notify unless we've got some data..
TaggedQueuedItemComparator<uint16_t> comparator;
std::sort(found.begin(), found.end(), comparator);
std::vector<std::pair<uint16_t, queued_item> >::iterator it(found.begin());
for (; it != found.end(); ++it) {
queue->push_back(it->second);
}
found.clear();
engine->tapConnMap->setEvents(name, queue);
}
}
}
bool BackFillVisitor::pauseVisitor() {
bool pause(true);
ssize_t theSize(engine->tapConnMap->backfillQueueDepth(name));
if (!checkValidity() || theSize < 0) {
getLogger()->log(EXTENSION_LOG_WARNING, NULL,
"TapProducer %s went away. Stopping backfill.\n",
name.c_str());
valid = false;
return false;
}
ssize_t maxBackfillSize = engine->getTapConfig().getBackfillBacklogLimit();
pause = theSize > maxBackfillSize || isMemoryUsageTooHigh(engine->getEpStats());
if (pause) {
getLogger()->log(EXTENSION_LOG_INFO, NULL,
"Tap queue depth is too big for %s or memory usage too high, "
"Pausing temporarily...\n",
name.c_str());
}
return pause;
}
void BackFillVisitor::complete() {
apply();
CompleteBackfillTapOperation tapop;
engine->tapConnMap->performTapOp(name, tapop, static_cast<void*>(NULL));
if (engine->tapConnMap->checkBackfillCompletion(name)) {
engine->notifyNotificationThread();
}
getLogger()->log(EXTENSION_LOG_INFO, NULL,
"Backfill dispatcher task for TapProducer %s is completed.\n",
name.c_str());
}
bool BackFillVisitor::checkValidity() {
if (valid) {
valid = engine->tapConnMap->checkConnectivity(name);
if (!valid) {
getLogger()->log(EXTENSION_LOG_WARNING, NULL,
"Backfilling connectivity for %s went invalid. "
"Stopping backfill.\n",
name.c_str());
}
}
return valid;
}
bool BackfillTask::callback(Dispatcher &d, TaskId t) {
(void) t;
epstore->visit(bfv, "Backfill task", &d, Priority::BackfillTaskPriority, true, 1);
return false;
}
<commit_msg>Remove duplicate memory constraint checks on backfill.<commit_after>/* -*- Mode: C++; tab-width: 4; c-basic-offset: 4; indent-tabs-mode: nil -*- */
#include "config.h"
#include "vbucket.hh"
#include "ep_engine.h"
#include "ep.hh"
#include "backfill.hh"
static bool isMemoryUsageTooHigh(EPStats &stats) {
double currentSize = static_cast<double>(stats.currentSize.get() + stats.memOverhead.get());
double maxSize = static_cast<double>(stats.maxDataSize.get());
return currentSize > (maxSize * BACKFILL_MEM_THRESHOLD);
}
/**
* Callback class used to process an item backfilled from disk and push it into
* the corresponding TAP queue.
*/
class BackfillDiskCallback : public Callback<GetValue> {
public:
BackfillDiskCallback(const std::string &n, TapConnMap &tcm, EventuallyPersistentEngine* e)
: tapConnName(n), connMap(tcm), engine(e) {
assert(engine);
}
void callback(GetValue &val);
private:
const std::string tapConnName;
TapConnMap &connMap;
EventuallyPersistentEngine *engine;
};
void BackfillDiskCallback::callback(GetValue &gv) {
ReceivedItemTapOperation tapop(true);
// if the tap connection is closed, then free an Item instance
if (!connMap.performTapOp(tapConnName, tapop, gv.getValue())) {
delete gv.getValue();
}
NotifyPausedTapOperation notifyOp;
connMap.performTapOp(tapConnName, notifyOp, engine);
}
bool BackfillDiskLoad::callback(Dispatcher &, TaskId) {
bool valid = false;
if (connMap.checkConnectivity(name) && !engine->getEpStore()->isFlushAllScheduled()) {
shared_ptr<Callback<GetValue> > backfill_cb(new BackfillDiskCallback(name, connMap, engine));
store->dump(vbucket, backfill_cb);
valid = true;
}
getLogger()->log(EXTENSION_LOG_INFO, NULL,
"VBucket %d backfill task from disk is completed.\n",
vbucket);
// Should decr the disk backfill counter regardless of the connectivity status
CompleteDiskBackfillTapOperation op;
connMap.performTapOp(name, op, static_cast<void*>(NULL));
if (valid && connMap.checkBackfillCompletion(name)) {
engine->notifyNotificationThread();
}
return false;
}
std::string BackfillDiskLoad::description() {
std::stringstream rv;
rv << "Loading TAP backfill from disk for vb " << vbucket;
return rv.str();
}
bool BackFillVisitor::visitBucket(RCPtr<VBucket> &vb) {
apply();
if (vBucketFilter(vb->getId())) {
VBucketVisitor::visitBucket(vb);
// If the current resident ratio for a given vbucket is below the resident threshold
// for memory backfill only, schedule the disk backfill for more efficient bg fetches.
double numItems = static_cast<double>(vb->ht.getNumItems());
double numNonResident = static_cast<double>(vb->ht.getNumNonResidentItems());
if (numItems == 0) {
return true;
}
double residentThreshold = engine->getTapConfig().getBackfillResidentThreshold();
residentRatioBelowThreshold =
((numItems - numNonResident) / numItems) < residentThreshold ? true : false;
if (efficientVBDump && residentRatioBelowThreshold) {
vbuckets.push_back(vb->getId());
ScheduleDiskBackfillTapOperation tapop;
engine->tapConnMap->performTapOp(name, tapop, static_cast<void*>(NULL));
}
// When the backfill is scheduled for a given vbucket, set the TAP cursor to
// the beginning of the open checkpoint.
engine->tapConnMap->SetCursorToOpenCheckpoint(name, vb->getId());
return true;
}
return false;
}
void BackFillVisitor::visit(StoredValue *v) {
// If efficient VBdump is supported and an item is not resident,
// skip the item as it will be fetched by the disk backfill.
if (efficientVBDump && residentRatioBelowThreshold && !v->isResident()) {
return;
}
std::string k = v->getKey();
queued_item qi(new QueuedItem(k, currentBucket->getId(), queue_op_set,
-1, v->getId()));
uint16_t shardId = engine->kvstore->getShardId(*qi);
found.push_back(std::make_pair(shardId, qi));
}
void BackFillVisitor::apply(void) {
// If efficient VBdump is supported, schedule all the disk backfill tasks.
if (efficientVBDump) {
std::vector<uint16_t>::iterator it = vbuckets.begin();
for (; it != vbuckets.end(); it++) {
Dispatcher *d(engine->epstore->getRODispatcher());
KVStore *underlying(engine->epstore->getROUnderlying());
assert(d);
getLogger()->log(EXTENSION_LOG_INFO, NULL,
"Schedule a full backfill from disk for vbucket %d.\n",
*it);
shared_ptr<DispatcherCallback> cb(new BackfillDiskLoad(name,
engine,
*engine->tapConnMap,
underlying,
*it,
validityToken));
d->schedule(cb, NULL, Priority::TapBgFetcherPriority);
}
vbuckets.clear();
}
setEvents();
}
void BackFillVisitor::setEvents() {
if (checkValidity()) {
if (!found.empty()) {
// Don't notify unless we've got some data..
TaggedQueuedItemComparator<uint16_t> comparator;
std::sort(found.begin(), found.end(), comparator);
std::vector<std::pair<uint16_t, queued_item> >::iterator it(found.begin());
for (; it != found.end(); ++it) {
queue->push_back(it->second);
}
found.clear();
engine->tapConnMap->setEvents(name, queue);
}
}
}
bool BackFillVisitor::pauseVisitor() {
bool pause(true);
ssize_t theSize(engine->tapConnMap->backfillQueueDepth(name));
if (!checkValidity() || theSize < 0) {
getLogger()->log(EXTENSION_LOG_WARNING, NULL,
"TapProducer %s went away. Stopping backfill.\n",
name.c_str());
valid = false;
return false;
}
ssize_t maxBackfillSize = engine->getTapConfig().getBackfillBacklogLimit();
pause = theSize > maxBackfillSize || isMemoryUsageTooHigh(engine->getEpStats());
if (pause) {
getLogger()->log(EXTENSION_LOG_INFO, NULL,
"Tap queue depth is too big for %s or memory usage too high, "
"Pausing temporarily...\n",
name.c_str());
}
return pause;
}
void BackFillVisitor::complete() {
apply();
CompleteBackfillTapOperation tapop;
engine->tapConnMap->performTapOp(name, tapop, static_cast<void*>(NULL));
if (engine->tapConnMap->checkBackfillCompletion(name)) {
engine->notifyNotificationThread();
}
getLogger()->log(EXTENSION_LOG_INFO, NULL,
"Backfill dispatcher task for TapProducer %s is completed.\n",
name.c_str());
}
bool BackFillVisitor::checkValidity() {
if (valid) {
valid = engine->tapConnMap->checkConnectivity(name);
if (!valid) {
getLogger()->log(EXTENSION_LOG_WARNING, NULL,
"Backfilling connectivity for %s went invalid. "
"Stopping backfill.\n",
name.c_str());
}
}
return valid;
}
bool BackfillTask::callback(Dispatcher &d, TaskId t) {
(void) t;
epstore->visit(bfv, "Backfill task", &d, Priority::BackfillTaskPriority, true, 1);
return false;
}
<|endoftext|>
|
<commit_before>#include "gimbal_impl.h"
#include "global_include.h"
#include <functional>
namespace dronecode_sdk {
GimbalImpl::GimbalImpl(System &system) : PluginImplBase(system)
{
_parent->register_plugin(this);
}
GimbalImpl::~GimbalImpl()
{
_parent->unregister_plugin(this);
}
void GimbalImpl::init() {}
void GimbalImpl::deinit() {}
void GimbalImpl::enable() {}
void GimbalImpl::disable() {}
Gimbal::Result GimbalImpl::set_pitch_and_yaw(float pitch_deg, float yaw_deg)
{
const float roll_deg = 0.0f;
MAVLinkCommands::CommandLong command{};
command.command = MAV_CMD_DO_MOUNT_CONTROL;
command.params.param1 = pitch_deg;
command.params.param2 = roll_deg;
command.params.param3 = yaw_deg;
command.params.param7 = float(MAV_MOUNT_MODE_MAVLINK_TARGETING);
command.target_component_id = _parent->get_autopilot_id();
return gimbal_result_from_command_result(_parent->send_command(command));
}
void GimbalImpl::set_pitch_and_yaw_async(float pitch_deg,
float yaw_deg,
Gimbal::result_callback_t callback)
{
const float roll_deg = 0.0f;
MAVLinkCommands::CommandLong command{};
command.command = MAV_CMD_DO_MOUNT_CONTROL;
command.params.param1 = pitch_deg;
command.params.param2 = roll_deg;
command.params.param3 = yaw_deg;
command.params.param7 = float(MAV_MOUNT_MODE_MAVLINK_TARGETING);
command.target_component_id = _parent->get_autopilot_id();
_parent->send_command_async(
command, std::bind(&GimbalImpl::receive_command_result, std::placeholders::_1, callback));
}
Gimbal::Result
GimbalImpl::set_roi_location(double latitude_deg, double longitude_deg, float altitude_m)
{
MAVLinkCommands::CommandInt command{};
command.command = MAV_CMD_DO_SET_ROI_LOCATION;
command.params.x = int32_t(latitude_deg * 1e7);
command.params.y = int32_t(longitude_deg * 1e7);
command.params.z = altitude_m;
command.target_component_id = _parent->get_autopilot_id();
return gimbal_result_from_command_result(_parent->send_command(command));
}
void GimbalImpl::set_roi_location_async(double latitude_deg,
double longitude_deg,
float altitude_m,
Gimbal::result_callback_t callback)
{
MAVLinkCommands::CommandInt command{};
command.command = MAV_CMD_DO_SET_ROI_LOCATION;
command.params.x = int32_t(latitude_deg * 1e7);
command.params.y = int32_t(longitude_deg * 1e7);
command.params.z = altitude_m;
command.target_component_id = _parent->get_autopilot_id();
_parent->send_command_async(
command, std::bind(&GimbalImpl::receive_command_result, std::placeholders::_1, callback));
}
void GimbalImpl::receive_command_result(MAVLinkCommands::Result command_result,
const Gimbal::result_callback_t &callback)
{
Gimbal::Result gimbal_result = gimbal_result_from_command_result(command_result);
if (callback) {
callback(gimbal_result);
}
}
Gimbal::Result GimbalImpl::gimbal_result_from_command_result(MAVLinkCommands::Result command_result)
{
switch (command_result) {
case MAVLinkCommands::Result::SUCCESS:
return Gimbal::Result::SUCCESS;
case MAVLinkCommands::Result::TIMEOUT:
return Gimbal::Result::TIMEOUT;
case MAVLinkCommands::Result::NO_SYSTEM:
case MAVLinkCommands::Result::CONNECTION_ERROR:
case MAVLinkCommands::Result::BUSY:
case MAVLinkCommands::Result::COMMAND_DENIED:
default:
return Gimbal::Result::ERROR;
}
}
} // namespace dronecode_sdk
<commit_msg>gimbal: fix rounding<commit_after>#include "gimbal_impl.h"
#include "global_include.h"
#include <functional>
#include <cmath>
namespace dronecode_sdk {
GimbalImpl::GimbalImpl(System &system) : PluginImplBase(system)
{
_parent->register_plugin(this);
}
GimbalImpl::~GimbalImpl()
{
_parent->unregister_plugin(this);
}
void GimbalImpl::init() {}
void GimbalImpl::deinit() {}
void GimbalImpl::enable() {}
void GimbalImpl::disable() {}
Gimbal::Result GimbalImpl::set_pitch_and_yaw(float pitch_deg, float yaw_deg)
{
const float roll_deg = 0.0f;
MAVLinkCommands::CommandLong command{};
command.command = MAV_CMD_DO_MOUNT_CONTROL;
command.params.param1 = pitch_deg;
command.params.param2 = roll_deg;
command.params.param3 = yaw_deg;
command.params.param7 = float(MAV_MOUNT_MODE_MAVLINK_TARGETING);
command.target_component_id = _parent->get_autopilot_id();
return gimbal_result_from_command_result(_parent->send_command(command));
}
void GimbalImpl::set_pitch_and_yaw_async(float pitch_deg,
float yaw_deg,
Gimbal::result_callback_t callback)
{
const float roll_deg = 0.0f;
MAVLinkCommands::CommandLong command{};
command.command = MAV_CMD_DO_MOUNT_CONTROL;
command.params.param1 = pitch_deg;
command.params.param2 = roll_deg;
command.params.param3 = yaw_deg;
command.params.param7 = float(MAV_MOUNT_MODE_MAVLINK_TARGETING);
command.target_component_id = _parent->get_autopilot_id();
_parent->send_command_async(
command, std::bind(&GimbalImpl::receive_command_result, std::placeholders::_1, callback));
}
Gimbal::Result
GimbalImpl::set_roi_location(double latitude_deg, double longitude_deg, float altitude_m)
{
MAVLinkCommands::CommandInt command{};
command.command = MAV_CMD_DO_SET_ROI_LOCATION;
command.params.x = int32_t(std::round(latitude_deg * 1e7));
command.params.y = int32_t(std::round(longitude_deg * 1e7));
command.params.z = altitude_m;
command.target_component_id = _parent->get_autopilot_id();
return gimbal_result_from_command_result(_parent->send_command(command));
}
void GimbalImpl::set_roi_location_async(double latitude_deg,
double longitude_deg,
float altitude_m,
Gimbal::result_callback_t callback)
{
MAVLinkCommands::CommandInt command{};
command.command = MAV_CMD_DO_SET_ROI_LOCATION;
command.params.x = int32_t(std::round(latitude_deg * 1e7));
command.params.y = int32_t(std::round(longitude_deg * 1e7));
command.params.z = altitude_m;
command.target_component_id = _parent->get_autopilot_id();
_parent->send_command_async(
command, std::bind(&GimbalImpl::receive_command_result, std::placeholders::_1, callback));
}
void GimbalImpl::receive_command_result(MAVLinkCommands::Result command_result,
const Gimbal::result_callback_t &callback)
{
Gimbal::Result gimbal_result = gimbal_result_from_command_result(command_result);
if (callback) {
callback(gimbal_result);
}
}
Gimbal::Result GimbalImpl::gimbal_result_from_command_result(MAVLinkCommands::Result command_result)
{
switch (command_result) {
case MAVLinkCommands::Result::SUCCESS:
return Gimbal::Result::SUCCESS;
case MAVLinkCommands::Result::TIMEOUT:
return Gimbal::Result::TIMEOUT;
case MAVLinkCommands::Result::NO_SYSTEM:
case MAVLinkCommands::Result::CONNECTION_ERROR:
case MAVLinkCommands::Result::BUSY:
case MAVLinkCommands::Result::COMMAND_DENIED:
default:
return Gimbal::Result::ERROR;
}
}
} // namespace dronecode_sdk
<|endoftext|>
|
<commit_before>#include "lodmaker.h"
struct QVertex {
aten::vertex v;
uint32_t idx;
uint32_t grid[3];
uint64_t hash;
QVertex() {}
QVertex(
aten::vertex _v,
uint32_t i,
uint64_t h,
uint32_t gx, uint32_t gy, uint32_t gz)
: v(_v), idx(i), hash(h)
{
grid[0] = gx;
grid[1] = gy;
grid[2] = gz;
}
const QVertex& operator=(const QVertex& rhs)
{
v = rhs.v;
idx = rhs.idx;
grid[0] = rhs.grid[0];
grid[1] = rhs.grid[1];
grid[2] = rhs.grid[2];
hash = rhs.hash;
}
};
// NOTE
// gridX * gridY * gridZ uint64_t Ȃ悤ɂ
using qit = std::vector<QVertex>::iterator;
static void computeAverage(qit start, qit end)
{
aten::vec3 pos(start->v.pos);
aten::vec3 nml(start->v.nml);
aten::vec3 uv(start->v.uv);
uint32_t cnt = 1;
for (auto q = start + 1; q != end; q++) {
pos += q->v.pos;
nml += q->v.nml;
uv += q->v.uv;
cnt++;
}
real div = real(1) / cnt;
pos *= div;
nml *= div;
uv *= div;
nml = normalize(nml);
// vZʂ߂...
for (auto q = start; q != end; q++) {
q->v.pos = pos;
q->v.nml = nml;
q->v.uv = uv;
}
}
void LodMaker::make(
std::vector<aten::vertex>& dstVertices,
std::vector<std::vector<int>>& dstIndices,
const aten::aabb& bound,
const std::vector<aten::vertex>& vertices,
const std::vector<std::vector<aten::face*>>& triGroups,
int gridX,
int gridY,
int gridZ)
{
auto bmin = bound.minPos();
auto range = bound.size();
aten::vec3 scale(
(gridX - 1) / range.x,
(gridY - 1) / range.y,
(gridZ - 1) / range.z);
std::vector<std::vector<QVertex>> qvtxs(triGroups.size());
std::vector<std::vector<uint32_t>> sortedIndices(triGroups.size());
for (uint32_t i = 0; i < triGroups.size(); i++) {
const auto tris = triGroups[i];
qvtxs[i].reserve(tris.size());
for (uint32_t n = 0; n < tris.size(); n++) {
const auto tri = tris[n];
for (int t = 0; t < 3; t++) {
uint32_t idx = tri->param.idx[t];
const auto& v = vertices[idx];
auto grid = ((aten::vec3)v.pos - bmin) * scale + real(0.5);
uint32_t gx = (uint32_t)grid.x;
uint32_t gy = (uint32_t)grid.y;
uint32_t gz = (uint32_t)grid.z;
uint64_t hash = gz * (gridX * gridY) + gy * gridX + gx;
qvtxs[i].push_back(QVertex(v, idx, hash, gx, gy, gz));
}
}
}
// ObhɓĂ钸_̏ɂȂ悤Ƀ\[g.
for (uint32_t i = 0; i < qvtxs.size(); i++)
{
std::sort(
qvtxs[i].begin(), qvtxs[i].end(),
[](const QVertex& q0, const QVertex& q1)
{
return q0.hash > q1.hash;
});
sortedIndices.reserve(triGroups[i].size());
uint32_t num = (uint32_t)qvtxs[i].size();
// CfbNX_ɂ킹ĕבւ.
for (uint32_t n = 0; n < num; n++) {
const auto& q = qvtxs[i][n];
// X̃CfbNẌʒuɐVCfbNXl.
sortedIndices[i][q.idx] = n;
}
}
// ObhɓĂ钸_̕ϒlvZāAP̒_ɂĂ܂.
// UV͕邪AFZJ_oEXɎĝŁA͋CɂȂ.
for (uint32_t i = 0; i < qvtxs.size(); i++)
{
auto start = qvtxs[i].begin();
while (start != qvtxs[i].end())
{
auto end = start;
// ObhقȂ钸_ɂȂ܂ŒT.
while (end != qvtxs[i].end() && start->hash == end->hash) {
end++;
}
// TODO
// όvZ.
computeAverage(start, end);
for (auto q = start; q != end; q++) {
if (q == start) {
dstVertices.push_back(q->v);
}
else {
// قȂʒu̓_̏ꍇ.
// O̓_Ɣr.
auto prev = q - 1;
auto v0 = q->v.pos;
auto v1 = prev->v.pos;
bool isEqual = (memcmp(&v0, &v1, sizeof(v0)) == 0);
if (!isEqual) {
dstVertices.push_back(q->v);
}
}
// CfbNXXV.
q->idx = (uint32_t)dstVertices.size() - 1;
}
// ̊JnʒuXV
start = end;
}
}
// LODꂽʂ̃CfbNXi[.
dstIndices.resize(triGroups.size());
for (uint32_t i = 0; i < triGroups.size(); i++) {
const auto tris = triGroups[i];
dstIndices[i].reserve(tris.size() * 3);
for (uint32_t n = 0; n < tris.size(); n++) {
const auto tri = tris[n];
for (int t = 0; t < 3; t++) {
uint32_t idx = tri->param.idx[t];
auto sortedIdx = sortedIndices[i][idx];
auto newIdx = qvtxs[i][sortedIdx].idx;
dstIndices[i].push_back(newIdx);
}
}
}
}
<commit_msg>Fux build errors.<commit_after>#include "lodmaker.h"
struct QVertex {
aten::vertex v;
uint32_t idx;
uint32_t grid[3];
uint64_t hash;
QVertex() {}
QVertex(
aten::vertex _v,
uint32_t i,
uint64_t h,
uint32_t gx, uint32_t gy, uint32_t gz)
: v(_v), idx(i), hash(h)
{
grid[0] = gx;
grid[1] = gy;
grid[2] = gz;
}
const QVertex& operator=(const QVertex& rhs)
{
v = rhs.v;
idx = rhs.idx;
grid[0] = rhs.grid[0];
grid[1] = rhs.grid[1];
grid[2] = rhs.grid[2];
hash = rhs.hash;
return *this;
}
};
// NOTE
// gridX * gridY * gridZ uint64_t Ȃ悤ɂ
using qit = std::vector<QVertex>::iterator;
static void computeAverage(qit start, qit end)
{
aten::vec4 pos(start->v.pos);
aten::vec3 nml(start->v.nml);
aten::vec3 uv(start->v.uv);
uint32_t cnt = 1;
for (auto q = start + 1; q != end; q++) {
pos += q->v.pos;
nml += q->v.nml;
uv += q->v.uv;
cnt++;
}
real div = real(1) / cnt;
pos *= div;
nml *= div;
uv *= div;
pos.w = real(1);
nml = normalize(nml);
// vZʂ߂...
for (auto q = start; q != end; q++) {
q->v.pos = pos;
q->v.nml = nml;
q->v.uv = uv;
}
}
void LodMaker::make(
std::vector<aten::vertex>& dstVertices,
std::vector<std::vector<int>>& dstIndices,
const aten::aabb& bound,
const std::vector<aten::vertex>& vertices,
const std::vector<std::vector<aten::face*>>& triGroups,
int gridX,
int gridY,
int gridZ)
{
auto bmin = bound.minPos();
auto range = bound.size();
aten::vec3 scale(
(gridX - 1) / range.x,
(gridY - 1) / range.y,
(gridZ - 1) / range.z);
std::vector<std::vector<QVertex>> qvtxs(triGroups.size());
std::vector<std::vector<uint32_t>> sortedIndices(triGroups.size());
for (uint32_t i = 0; i < triGroups.size(); i++) {
const auto tris = triGroups[i];
qvtxs[i].reserve(tris.size());
for (uint32_t n = 0; n < tris.size(); n++) {
const auto tri = tris[n];
for (int t = 0; t < 3; t++) {
uint32_t idx = tri->param.idx[t];
const auto& v = vertices[idx];
auto grid = ((aten::vec3)v.pos - bmin) * scale + real(0.5);
uint32_t gx = (uint32_t)grid.x;
uint32_t gy = (uint32_t)grid.y;
uint32_t gz = (uint32_t)grid.z;
uint64_t hash = gz * (gridX * gridY) + gy * gridX + gx;
qvtxs[i].push_back(QVertex(v, idx, hash, gx, gy, gz));
}
}
}
// ObhɓĂ钸_̏ɂȂ悤Ƀ\[g.
for (uint32_t i = 0; i < qvtxs.size(); i++)
{
std::sort(
qvtxs[i].begin(), qvtxs[i].end(),
[](const QVertex& q0, const QVertex& q1)
{
return q0.hash > q1.hash;
});
sortedIndices.reserve(triGroups[i].size());
uint32_t num = (uint32_t)qvtxs[i].size();
// CfbNX_ɂ킹ĕבւ.
for (uint32_t n = 0; n < num; n++) {
const auto& q = qvtxs[i][n];
// X̃CfbNẌʒuɐVCfbNXl.
sortedIndices[i][q.idx] = n;
}
}
// ObhɓĂ钸_̕ϒlvZāAP̒_ɂĂ܂.
// UV͕邪AFZJ_oEXɎĝŁA͋CɂȂ.
for (uint32_t i = 0; i < qvtxs.size(); i++)
{
auto start = qvtxs[i].begin();
while (start != qvtxs[i].end())
{
auto end = start;
// ObhقȂ钸_ɂȂ܂ŒT.
while (end != qvtxs[i].end() && start->hash == end->hash) {
end++;
}
// TODO
// όvZ.
computeAverage(start, end);
for (auto q = start; q != end; q++) {
if (q == start) {
dstVertices.push_back(q->v);
}
else {
// قȂʒu̓_̏ꍇ.
// O̓_Ɣr.
auto prev = q - 1;
auto v0 = q->v.pos;
auto v1 = prev->v.pos;
bool isEqual = (memcmp(&v0, &v1, sizeof(v0)) == 0);
if (!isEqual) {
dstVertices.push_back(q->v);
}
}
// CfbNXXV.
q->idx = (uint32_t)dstVertices.size() - 1;
}
// ̊JnʒuXV
start = end;
}
}
// LODꂽʂ̃CfbNXi[.
dstIndices.resize(triGroups.size());
for (uint32_t i = 0; i < triGroups.size(); i++) {
const auto tris = triGroups[i];
dstIndices[i].reserve(tris.size() * 3);
for (uint32_t n = 0; n < tris.size(); n++) {
const auto tri = tris[n];
for (int t = 0; t < 3; t++) {
uint32_t idx = tri->param.idx[t];
auto sortedIdx = sortedIndices[i][idx];
auto newIdx = qvtxs[i][sortedIdx].idx;
dstIndices[i].push_back(newIdx);
}
}
}
}
<|endoftext|>
|
<commit_before>/*************************************************************************
*
* OpenOffice.org - a multi-platform office productivity suite
*
* $RCSfile: provider.cxx,v $
*
* $Revision: 1.18 $
*
* last change: $Author: rt $ $Date: 2005-09-09 12:20:03 $
*
* The Contents of this file are made available subject to
* the terms of GNU Lesser General Public License Version 2.1.
*
*
* GNU Lesser General Public License Version 2.1
* =============================================
* Copyright 2005 by Sun Microsystems, Inc.
* 901 San Antonio Road, Palo Alto, CA 94303, USA
*
* This library is free software; you can redistribute it and/or
* modify it under the terms of the GNU Lesser General Public
* License version 2.1, as published by the Free Software Foundation.
*
* This library is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
* Lesser General Public License for more details.
*
* You should have received a copy of the GNU Lesser General Public
* License along with this library; if not, write to the Free Software
* Foundation, Inc., 59 Temple Place, Suite 330, Boston,
* MA 02111-1307 USA
*
************************************************************************/
/**************************************************************************
TODO
**************************************************************************
*************************************************************************/
#include <stdio.h>
#ifndef _OSL_FILE_HXX_
#include <osl/file.hxx>
#endif
#ifndef _VOS_DIAGNOSE_HXX_
#include <vos/diagnose.hxx>
#endif
#ifndef _UCBHELPER_CONTENTIDENTIFIER_HXX
#include <ucbhelper/contentidentifier.hxx>
#endif
#ifndef _DATABASES_HXX_
#include <provider/databases.hxx>
#endif
#ifndef _PROVIDER_HXX
#include <provider/provider.hxx>
#endif
#ifndef _CONTENT_HXX
#include <provider/content.hxx>
#endif
#ifndef _DATABASES_HXX_
#include <provider/databases.hxx>
#endif
#ifndef _COM_SUN_STAR_FRAME_XCONFIGMANAGER_HPP_
#include <com/sun/star/frame/XConfigManager.hpp>
#endif
#ifndef _COM_SUN_STAR_BEANS_PROPERTYATTRIBBUTE_HPP_
#include <com/sun/star/beans/PropertyAttribute.hpp>
#endif
#ifndef _COM_SUN_STAR_BEANS_PROPERTYVALUE_HPP_
#include <com/sun/star/beans/PropertyValue.hpp>
#endif
#ifndef _COM_SUN_STAR_BEANS_PROPERTYSTATE_HPP_
#include <com/sun/star/beans/PropertyState.hpp>
#endif
#ifndef _COM_SUN_STAR_CONTAINER_XCONTAINER_HPP_
#include <com/sun/star/container/XContainer.hpp>
#endif
#ifndef _COM_SUN_STAR_CONTAINER_XNAMEACCESS_HPP_
#include <com/sun/star/container/XNameAccess.hpp>
#endif
#ifndef _COM_SUN_STAR_CONTAINER_XNAMEREPLACE_HPP_
#include <com/sun/star/container/XNameReplace.hpp>
#endif
using namespace com::sun::star::frame;
using namespace com::sun::star::beans;
using namespace com::sun::star::container;
using namespace com::sun::star::lang;
using namespace com::sun::star::ucb;
using namespace com::sun::star::uno;
using namespace rtl;
using namespace chelp;
//=========================================================================
//=========================================================================
//
// ContentProvider Implementation.
//
//=========================================================================
//=========================================================================
ContentProvider::ContentProvider( const Reference< XMultiServiceFactory >& rSMgr )
: ::ucb::ContentProviderImplHelper( rSMgr ),
isInitialized( false ),
m_aScheme( OUString::createFromAscii( MYUCP_URL_SCHEME ) ),
m_pDatabases( 0 )
{
}
//=========================================================================
// virtual
ContentProvider::~ContentProvider()
{
delete m_pDatabases;
}
//=========================================================================
//
// XInterface methods.
//
//=========================================================================
XINTERFACE_IMPL_6( ContentProvider,
XTypeProvider,
XServiceInfo,
XContentProvider,
XComponent,
XEventListener, /* base of XContainerListener */
XContainerListener);
//=========================================================================
//
// XTypeProvider methods.
//
//=========================================================================
XTYPEPROVIDER_IMPL_5( ContentProvider,
XTypeProvider,
XServiceInfo,
XContentProvider,
XComponent,
XContainerListener);
//=========================================================================
//
// XServiceInfo methods.
//
//=========================================================================
rtl::OUString SAL_CALL ContentProvider::getImplementationName()
throw( com::sun::star::uno::RuntimeException )
{
return getImplementationName_Static();
}
rtl::OUString ContentProvider::getImplementationName_Static()
{
return OUString::createFromAscii("CHelpContentProvider" );
}
sal_Bool SAL_CALL
ContentProvider::supportsService(const rtl::OUString& ServiceName )
throw( com::sun::star::uno::RuntimeException )
{
com::sun::star::uno::Sequence< rtl::OUString > aSNL =
getSupportedServiceNames();
const rtl::OUString* pArray = aSNL.getArray();
for( sal_Int32 i = 0; i < aSNL.getLength(); i++ )
{
if( pArray[ i ] == ServiceName )
return sal_True;
}
return sal_False;
}
com::sun::star::uno::Sequence< rtl::OUString > SAL_CALL
ContentProvider::getSupportedServiceNames()
throw( com::sun::star::uno::RuntimeException )
{
return getSupportedServiceNames_Static();
}
static com::sun::star::uno::Reference<
com::sun::star::uno::XInterface > SAL_CALL
ContentProvider_CreateInstance(
const com::sun::star::uno::Reference<
com::sun::star::lang::XMultiServiceFactory> & rSMgr )
throw( com::sun::star::uno::Exception )
{
com::sun::star::lang::XServiceInfo* pX =
(com::sun::star::lang::XServiceInfo*)new ContentProvider( rSMgr );
return com::sun::star::uno::Reference<
com::sun::star::uno::XInterface >::query( pX );
}
com::sun::star::uno::Sequence< rtl::OUString >
ContentProvider::getSupportedServiceNames_Static()
{
com::sun::star::uno::Sequence< rtl::OUString > aSNS( 2 );
aSNS.getArray()[ 0 ] =
OUString::createFromAscii(
MYUCP_CONTENT_PROVIDER_SERVICE_NAME1 );
aSNS.getArray()[ 1 ] =
OUString::createFromAscii(
MYUCP_CONTENT_PROVIDER_SERVICE_NAME2 );
return aSNS;
}
//=========================================================================
//
// Service factory implementation.
//
//=========================================================================
ONE_INSTANCE_SERVICE_FACTORY_IMPL( ContentProvider );
//=========================================================================
//
// XContentProvider methods.
//
//=========================================================================
// virtual
Reference< XContent > SAL_CALL ContentProvider::queryContent( const Reference< XContentIdentifier >& xCanonicId )
throw( IllegalIdentifierException, RuntimeException )
{
if ( ! xCanonicId->getContentProviderScheme().equalsIgnoreAsciiCase( m_aScheme ) )
{ // Wrong URL-scheme
throw IllegalIdentifierException();
}
{
osl::MutexGuard aGuard( m_aMutex );
if( ! isInitialized )
init();
}
if( ! m_pDatabases )
throw RuntimeException();
rtl::OUString aOUString( m_pDatabases->getInstallPathAsURL() );
rtl::OString aOString( aOUString.getStr(),
aOUString.getLength(),
RTL_TEXTENCODING_UTF8 );
// Check, if a content with given id already exists...
Reference< XContent > xContent
= queryExistingContent( xCanonicId ).getBodyPtr();
if ( xContent.is() )
return xContent;
xContent = new Content( m_xSMgr,this,xCanonicId,m_pDatabases );
// Further checks
if ( !xContent->getIdentifier().is() )
throw IllegalIdentifierException();
return xContent;
}
void SAL_CALL
ContentProvider::dispose()
throw ( com::sun::star::uno::RuntimeException)
{
if(m_xContainer.is())
{
m_xContainer->removeContainerListener(this);
m_xContainer = Reference<XContainer>(0);
}
}
#include <provider/debughelper.hxx>
void SAL_CALL
ContentProvider::elementReplaced(const ContainerEvent& Event)
throw (::com::sun::star::uno::RuntimeException)
{
if(!m_pDatabases)
return;
rtl::OUString accessor;
Event.Accessor >>= accessor;
if(accessor.compareToAscii("HelpStyleSheet"))
return;
rtl::OUString replacedElement,element;
Event.ReplacedElement >>= replacedElement;
Event.Element >>= element;
if(replacedElement == element)
return;
m_pDatabases->changeCSS(element);
}
void ContentProvider::init()
{
osl::MutexGuard aGuard( m_aMutex );
isInitialized = true;
Reference< XMultiServiceFactory > sProvider( getConfiguration() );
Reference< XHierarchicalNameAccess > xHierAccess( getHierAccess( sProvider,
"org.openoffice.Office.Common" ) );
rtl::OUString instPath( getKey( xHierAccess,"Path/Current/Help" ) );
if( ! instPath.getLength() )
// try to determine path from default
instPath = rtl::OUString::createFromAscii( "$(instpath)/help" );
// replace anything like $(instpath);
subst( instPath );
rtl::OUString stylesheet(getKey(xHierAccess,"Help/HelpStyleSheet"));
try {
// now adding as configuration change listener for the stylesheet
Reference<XNameAccess> xAccess(xHierAccess,UNO_QUERY);
if(xAccess.is()) {
Any aAny =
xAccess->getByName(rtl::OUString::createFromAscii("Help"));
aAny >>= m_xContainer;
if(m_xContainer.is())
m_xContainer->addContainerListener(this);
}
} catch(const com::sun::star::uno::Exception&) {
}
/**
* now determing
* productname,
* productversion,
* vendorname,
* vendorversion,
* vendorshort
*/
xHierAccess = getHierAccess( sProvider,
"org.openoffice.Setup" );
rtl::OUString productname( getKey( xHierAccess,"Product/ooName" ) );
rtl::OUString setupversion( getKey( xHierAccess,"Product/ooSetupVersion" ) );
rtl::OUString setupextension( getKey( xHierAccess,"Product/ooSetupExtension") );
rtl::OUString productversion( setupversion +
rtl::OUString::createFromAscii( " " ) +
setupextension );
xHierAccess = getHierAccess( sProvider,
"org.openoffice.Webtop.Common" );
rtl::OUString vendorname( getKey( xHierAccess,"Product/ooName" ) );
setupversion = rtl::OUString( getKey( xHierAccess,"Product/ooSetupVersion" ) );
setupextension = rtl::OUString ( getKey( xHierAccess,"Product/ooSetupExtension") );
rtl::OUString vendorversion( setupversion +
rtl::OUString::createFromAscii( " " ) +
setupextension );
rtl::OUString vendorshort = vendorname;
bool found = false;
xHierAccess = getHierAccess( sProvider,
"org.openoffice.Office.Common" );
rtl::OUString imageZip(getKey(xHierAccess,"Path/Current/UserConfig"));
subst(imageZip);
if(imageZip.getLength()) {
// test existence
if(1+imageZip.lastIndexOf('/') == imageZip.getLength())
imageZip += rtl::OUString::createFromAscii("images.zip");
else
imageZip += rtl::OUString::createFromAscii("/images.zip");
osl::DirectoryItem aDirItem;
if(osl::DirectoryItem::get(imageZip,aDirItem) == osl::FileBase::E_None)
found = true;
}
if(!found) {
imageZip = getKey(xHierAccess,"Path/Current/Config");
subst(imageZip);
if(1+imageZip.lastIndexOf('/') == imageZip.getLength())
imageZip += rtl::OUString::createFromAscii("images.zip");
else
imageZip += rtl::OUString::createFromAscii("/images.zip");
}
m_pDatabases = new Databases( instPath,
imageZip,
productname,
productversion,
vendorname,
vendorversion,
vendorshort,
stylesheet,
m_xSMgr );
}
Reference< XMultiServiceFactory > ContentProvider::getConfiguration() const
{
Reference< XMultiServiceFactory > sProvider;
if( m_xSMgr.is() )
{
Any aAny;
aAny <<= rtl::OUString::createFromAscii( "plugin" );
PropertyValue aProp( rtl::OUString::createFromAscii( "servertype" ),
-1,
aAny,
PropertyState_DIRECT_VALUE );
Sequence< Any > seq(1);
seq[0] <<= aProp;
try
{
rtl::OUString sProviderService =
rtl::OUString::createFromAscii(
"com.sun.star.configuration.ConfigurationProvider" );
sProvider =
Reference< XMultiServiceFactory >(
m_xSMgr->createInstanceWithArguments(
sProviderService,seq ),
UNO_QUERY );
}
catch( const com::sun::star::uno::Exception& )
{
OSL_ENSURE( sProvider.is(),"cant instantiate configuration" );
}
}
return sProvider;
}
Reference< XHierarchicalNameAccess >
ContentProvider::getHierAccess( const Reference< XMultiServiceFactory >& sProvider,
const char* file ) const
{
Reference< XHierarchicalNameAccess > xHierAccess;
if( sProvider.is() )
{
Sequence< Any > seq(1);
rtl::OUString sReaderService =
rtl::OUString::createFromAscii( "com.sun.star.configuration.ConfigurationAccess" );
seq[0] <<= rtl::OUString::createFromAscii( file );
try
{
xHierAccess =
Reference< XHierarchicalNameAccess >
( sProvider->createInstanceWithArguments( sReaderService,seq ),
UNO_QUERY );
}
catch( const com::sun::star::uno::Exception& )
{
}
}
return xHierAccess;
}
rtl::OUString
ContentProvider::getKey(const Reference<
XHierarchicalNameAccess >& xHierAccess,
const char* key) const
{
rtl::OUString instPath;
if( xHierAccess.is() )
{
Any aAny;
try
{
aAny =
xHierAccess->getByHierarchicalName(
rtl::OUString::createFromAscii(key));
}
catch( const com::sun::star::container::NoSuchElementException& )
{
}
aAny >>= instPath;
}
return instPath;
}
void ContentProvider::subst( rtl::OUString& instpath ) const
{
Reference< XConfigManager > xCfgMgr;
if( m_xSMgr.is() )
{
try
{
xCfgMgr =
Reference< XConfigManager >(
m_xSMgr->createInstance( rtl::OUString::createFromAscii( "com.sun.star.config.SpecialConfigManager" ) ),
UNO_QUERY );
}
catch( const com::sun::star::uno::Exception&)
{
OSL_ENSURE( xCfgMgr.is()," cant instantiate the special config manager " );
}
}
OSL_ENSURE( xCfgMgr.is(), "specialconfigmanager not found\n" );
if( xCfgMgr.is() )
instpath = xCfgMgr->substituteVariables( instpath );
}
<commit_msg>INTEGRATION: CWS c06 (1.17.48); FILE MERGED 2005/08/24 14:59:54 abi 1.17.48.1: #i53539# no basic help, if org.openoffice.Office.Common/Help/ShowBasic is set to false<commit_after>/*************************************************************************
*
* OpenOffice.org - a multi-platform office productivity suite
*
* $RCSfile: provider.cxx,v $
*
* $Revision: 1.19 $
*
* last change: $Author: rt $ $Date: 2005-11-11 12:17:07 $
*
* The Contents of this file are made available subject to
* the terms of GNU Lesser General Public License Version 2.1.
*
*
* GNU Lesser General Public License Version 2.1
* =============================================
* Copyright 2005 by Sun Microsystems, Inc.
* 901 San Antonio Road, Palo Alto, CA 94303, USA
*
* This library is free software; you can redistribute it and/or
* modify it under the terms of the GNU Lesser General Public
* License version 2.1, as published by the Free Software Foundation.
*
* This library is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
* Lesser General Public License for more details.
*
* You should have received a copy of the GNU Lesser General Public
* License along with this library; if not, write to the Free Software
* Foundation, Inc., 59 Temple Place, Suite 330, Boston,
* MA 02111-1307 USA
*
************************************************************************/
/**************************************************************************
TODO
**************************************************************************
*************************************************************************/
#include <stdio.h>
#ifndef _OSL_FILE_HXX_
#include <osl/file.hxx>
#endif
#ifndef _VOS_DIAGNOSE_HXX_
#include <vos/diagnose.hxx>
#endif
#ifndef _UCBHELPER_CONTENTIDENTIFIER_HXX
#include <ucbhelper/contentidentifier.hxx>
#endif
#ifndef _DATABASES_HXX_
#include <provider/databases.hxx>
#endif
#ifndef _PROVIDER_HXX
#include <provider/provider.hxx>
#endif
#ifndef _CONTENT_HXX
#include <provider/content.hxx>
#endif
#ifndef _DATABASES_HXX_
#include <provider/databases.hxx>
#endif
#ifndef _COM_SUN_STAR_FRAME_XCONFIGMANAGER_HPP_
#include <com/sun/star/frame/XConfigManager.hpp>
#endif
#ifndef _COM_SUN_STAR_BEANS_PROPERTYATTRIBBUTE_HPP_
#include <com/sun/star/beans/PropertyAttribute.hpp>
#endif
#ifndef _COM_SUN_STAR_BEANS_PROPERTYVALUE_HPP_
#include <com/sun/star/beans/PropertyValue.hpp>
#endif
#ifndef _COM_SUN_STAR_BEANS_PROPERTYSTATE_HPP_
#include <com/sun/star/beans/PropertyState.hpp>
#endif
#ifndef _COM_SUN_STAR_CONTAINER_XCONTAINER_HPP_
#include <com/sun/star/container/XContainer.hpp>
#endif
#ifndef _COM_SUN_STAR_CONTAINER_XNAMEACCESS_HPP_
#include <com/sun/star/container/XNameAccess.hpp>
#endif
#ifndef _COM_SUN_STAR_CONTAINER_XNAMEREPLACE_HPP_
#include <com/sun/star/container/XNameReplace.hpp>
#endif
using namespace com::sun::star::frame;
using namespace com::sun::star::beans;
using namespace com::sun::star::container;
using namespace com::sun::star::lang;
using namespace com::sun::star::ucb;
using namespace com::sun::star::uno;
using namespace rtl;
using namespace chelp;
//=========================================================================
//=========================================================================
//
// ContentProvider Implementation.
//
//=========================================================================
//=========================================================================
ContentProvider::ContentProvider( const Reference< XMultiServiceFactory >& rSMgr )
: ::ucb::ContentProviderImplHelper( rSMgr ),
isInitialized( false ),
m_aScheme( OUString::createFromAscii( MYUCP_URL_SCHEME ) ),
m_pDatabases( 0 )
{
}
//=========================================================================
// virtual
ContentProvider::~ContentProvider()
{
delete m_pDatabases;
}
//=========================================================================
//
// XInterface methods.
//
//=========================================================================
XINTERFACE_IMPL_6( ContentProvider,
XTypeProvider,
XServiceInfo,
XContentProvider,
XComponent,
XEventListener, /* base of XContainerListener */
XContainerListener);
//=========================================================================
//
// XTypeProvider methods.
//
//=========================================================================
XTYPEPROVIDER_IMPL_5( ContentProvider,
XTypeProvider,
XServiceInfo,
XContentProvider,
XComponent,
XContainerListener);
//=========================================================================
//
// XServiceInfo methods.
//
//=========================================================================
rtl::OUString SAL_CALL ContentProvider::getImplementationName()
throw( com::sun::star::uno::RuntimeException )
{
return getImplementationName_Static();
}
rtl::OUString ContentProvider::getImplementationName_Static()
{
return OUString::createFromAscii("CHelpContentProvider" );
}
sal_Bool SAL_CALL
ContentProvider::supportsService(const rtl::OUString& ServiceName )
throw( com::sun::star::uno::RuntimeException )
{
com::sun::star::uno::Sequence< rtl::OUString > aSNL =
getSupportedServiceNames();
const rtl::OUString* pArray = aSNL.getArray();
for( sal_Int32 i = 0; i < aSNL.getLength(); i++ )
{
if( pArray[ i ] == ServiceName )
return sal_True;
}
return sal_False;
}
com::sun::star::uno::Sequence< rtl::OUString > SAL_CALL
ContentProvider::getSupportedServiceNames()
throw( com::sun::star::uno::RuntimeException )
{
return getSupportedServiceNames_Static();
}
static com::sun::star::uno::Reference<
com::sun::star::uno::XInterface > SAL_CALL
ContentProvider_CreateInstance(
const com::sun::star::uno::Reference<
com::sun::star::lang::XMultiServiceFactory> & rSMgr )
throw( com::sun::star::uno::Exception )
{
com::sun::star::lang::XServiceInfo* pX =
(com::sun::star::lang::XServiceInfo*)new ContentProvider( rSMgr );
return com::sun::star::uno::Reference<
com::sun::star::uno::XInterface >::query( pX );
}
com::sun::star::uno::Sequence< rtl::OUString >
ContentProvider::getSupportedServiceNames_Static()
{
com::sun::star::uno::Sequence< rtl::OUString > aSNS( 2 );
aSNS.getArray()[ 0 ] =
OUString::createFromAscii(
MYUCP_CONTENT_PROVIDER_SERVICE_NAME1 );
aSNS.getArray()[ 1 ] =
OUString::createFromAscii(
MYUCP_CONTENT_PROVIDER_SERVICE_NAME2 );
return aSNS;
}
//=========================================================================
//
// Service factory implementation.
//
//=========================================================================
ONE_INSTANCE_SERVICE_FACTORY_IMPL( ContentProvider );
//=========================================================================
//
// XContentProvider methods.
//
//=========================================================================
// virtual
Reference< XContent > SAL_CALL ContentProvider::queryContent( const Reference< XContentIdentifier >& xCanonicId )
throw( IllegalIdentifierException, RuntimeException )
{
if ( ! xCanonicId->getContentProviderScheme().equalsIgnoreAsciiCase( m_aScheme ) )
{ // Wrong URL-scheme
throw IllegalIdentifierException();
}
{
osl::MutexGuard aGuard( m_aMutex );
if( ! isInitialized )
init();
}
if( ! m_pDatabases )
throw RuntimeException();
rtl::OUString aOUString( m_pDatabases->getInstallPathAsURL() );
rtl::OString aOString( aOUString.getStr(),
aOUString.getLength(),
RTL_TEXTENCODING_UTF8 );
// Check, if a content with given id already exists...
Reference< XContent > xContent
= queryExistingContent( xCanonicId ).getBodyPtr();
if ( xContent.is() )
return xContent;
xContent = new Content( m_xSMgr,this,xCanonicId,m_pDatabases );
// Further checks
if ( !xContent->getIdentifier().is() )
throw IllegalIdentifierException();
return xContent;
}
void SAL_CALL
ContentProvider::dispose()
throw ( com::sun::star::uno::RuntimeException)
{
if(m_xContainer.is())
{
m_xContainer->removeContainerListener(this);
m_xContainer = Reference<XContainer>(0);
}
}
#include <provider/debughelper.hxx>
void SAL_CALL
ContentProvider::elementReplaced(const ContainerEvent& Event)
throw (::com::sun::star::uno::RuntimeException)
{
if(!m_pDatabases)
return;
rtl::OUString accessor;
Event.Accessor >>= accessor;
if(accessor.compareToAscii("HelpStyleSheet"))
return;
rtl::OUString replacedElement,element;
Event.ReplacedElement >>= replacedElement;
Event.Element >>= element;
if(replacedElement == element)
return;
m_pDatabases->changeCSS(element);
}
void ContentProvider::init()
{
osl::MutexGuard aGuard( m_aMutex );
isInitialized = true;
Reference< XMultiServiceFactory > sProvider( getConfiguration() );
Reference< XHierarchicalNameAccess > xHierAccess( getHierAccess( sProvider,
"org.openoffice.Office.Common" ) );
rtl::OUString instPath( getKey( xHierAccess,"Path/Current/Help" ) );
if( ! instPath.getLength() )
// try to determine path from default
instPath = rtl::OUString::createFromAscii( "$(instpath)/help" );
// replace anything like $(instpath);
subst( instPath );
rtl::OUString stylesheet(getKey(xHierAccess,"Help/HelpStyleSheet"));
try {
// now adding as configuration change listener for the stylesheet
Reference<XNameAccess> xAccess(xHierAccess,UNO_QUERY);
if(xAccess.is()) {
Any aAny =
xAccess->getByName(rtl::OUString::createFromAscii("Help"));
aAny >>= m_xContainer;
if(m_xContainer.is())
m_xContainer->addContainerListener(this);
}
} catch(const com::sun::star::uno::Exception&) {
}
/**
* now determing
* productname,
* productversion,
* vendorname,
* vendorversion,
* vendorshort
*/
xHierAccess = getHierAccess( sProvider,
"org.openoffice.Setup" );
rtl::OUString productname( getKey( xHierAccess,"Product/ooName" ) );
rtl::OUString setupversion( getKey( xHierAccess,"Product/ooSetupVersion" ) );
rtl::OUString setupextension( getKey( xHierAccess,"Product/ooSetupExtension") );
rtl::OUString productversion( setupversion +
rtl::OUString::createFromAscii( " " ) +
setupextension );
xHierAccess = getHierAccess( sProvider,
"org.openoffice.Webtop.Common" );
rtl::OUString vendorname( getKey( xHierAccess,"Product/ooName" ) );
setupversion = rtl::OUString( getKey( xHierAccess,"Product/ooSetupVersion" ) );
setupextension = rtl::OUString ( getKey( xHierAccess,"Product/ooSetupExtension") );
rtl::OUString vendorversion( setupversion +
rtl::OUString::createFromAscii( " " ) +
setupextension );
rtl::OUString vendorshort = vendorname;
bool found = false;
xHierAccess = getHierAccess( sProvider,
"org.openoffice.Office.Common" );
rtl::OUString imageZip(getKey(xHierAccess,"Path/Current/UserConfig"));
subst(imageZip);
if(imageZip.getLength()) {
// test existence
if(1+imageZip.lastIndexOf('/') == imageZip.getLength())
imageZip += rtl::OUString::createFromAscii("images.zip");
else
imageZip += rtl::OUString::createFromAscii("/images.zip");
osl::DirectoryItem aDirItem;
if(osl::DirectoryItem::get(imageZip,aDirItem) == osl::FileBase::E_None)
found = true;
}
if(!found) {
imageZip = getKey(xHierAccess,"Path/Current/Config");
subst(imageZip);
if(1+imageZip.lastIndexOf('/') == imageZip.getLength())
imageZip += rtl::OUString::createFromAscii("images.zip");
else
imageZip += rtl::OUString::createFromAscii("/images.zip");
}
sal_Bool showBasic = getBooleanKey(xHierAccess,"Help/ShowBasic");
m_pDatabases = new Databases( showBasic,
instPath,
imageZip,
productname,
productversion,
vendorname,
vendorversion,
vendorshort,
stylesheet,
m_xSMgr );
}
Reference< XMultiServiceFactory > ContentProvider::getConfiguration() const
{
Reference< XMultiServiceFactory > sProvider;
if( m_xSMgr.is() )
{
Any aAny;
aAny <<= rtl::OUString::createFromAscii( "plugin" );
PropertyValue aProp( rtl::OUString::createFromAscii( "servertype" ),
-1,
aAny,
PropertyState_DIRECT_VALUE );
Sequence< Any > seq(1);
seq[0] <<= aProp;
try
{
rtl::OUString sProviderService =
rtl::OUString::createFromAscii(
"com.sun.star.configuration.ConfigurationProvider" );
sProvider =
Reference< XMultiServiceFactory >(
m_xSMgr->createInstanceWithArguments(
sProviderService,seq ),
UNO_QUERY );
}
catch( const com::sun::star::uno::Exception& )
{
OSL_ENSURE( sProvider.is(),"cant instantiate configuration" );
}
}
return sProvider;
}
Reference< XHierarchicalNameAccess >
ContentProvider::getHierAccess( const Reference< XMultiServiceFactory >& sProvider,
const char* file ) const
{
Reference< XHierarchicalNameAccess > xHierAccess;
if( sProvider.is() )
{
Sequence< Any > seq(1);
rtl::OUString sReaderService =
rtl::OUString::createFromAscii( "com.sun.star.configuration.ConfigurationAccess" );
seq[0] <<= rtl::OUString::createFromAscii( file );
try
{
xHierAccess =
Reference< XHierarchicalNameAccess >
( sProvider->createInstanceWithArguments( sReaderService,seq ),
UNO_QUERY );
}
catch( const com::sun::star::uno::Exception& )
{
}
}
return xHierAccess;
}
rtl::OUString
ContentProvider::getKey(const Reference<
XHierarchicalNameAccess >& xHierAccess,
const char* key) const
{
rtl::OUString instPath;
if( xHierAccess.is() )
{
Any aAny;
try
{
aAny =
xHierAccess->getByHierarchicalName(
rtl::OUString::createFromAscii(key));
}
catch( const com::sun::star::container::NoSuchElementException& )
{
}
aAny >>= instPath;
}
return instPath;
}
sal_Bool
ContentProvider::getBooleanKey(const Reference<
XHierarchicalNameAccess >& xHierAccess,
const char* key) const
{
sal_Bool ret = sal_False;
if( xHierAccess.is() )
{
Any aAny;
try
{
aAny =
xHierAccess->getByHierarchicalName(
rtl::OUString::createFromAscii(key));
}
catch( const com::sun::star::container::NoSuchElementException& )
{
}
aAny >>= ret;
}
return ret;
}
void ContentProvider::subst( rtl::OUString& instpath ) const
{
Reference< XConfigManager > xCfgMgr;
if( m_xSMgr.is() )
{
try
{
xCfgMgr =
Reference< XConfigManager >(
m_xSMgr->createInstance( rtl::OUString::createFromAscii( "com.sun.star.config.SpecialConfigManager" ) ),
UNO_QUERY );
}
catch( const com::sun::star::uno::Exception&)
{
OSL_ENSURE( xCfgMgr.is()," cant instantiate the special config manager " );
}
}
OSL_ENSURE( xCfgMgr.is(), "specialconfigmanager not found\n" );
if( xCfgMgr.is() )
instpath = xCfgMgr->substituteVariables( instpath );
}
<|endoftext|>
|
<commit_before>/*************************************************************************
*
* OpenOffice.org - a multi-platform office productivity suite
*
* $RCSfile: XMLChartStyleContext.cxx,v $
*
* $Revision: 1.11 $
*
* last change: $Author: hr $ $Date: 2007-06-27 14:51:11 $
*
* The Contents of this file are made available subject to
* the terms of GNU Lesser General Public License Version 2.1.
*
*
* GNU Lesser General Public License Version 2.1
* =============================================
* Copyright 2005 by Sun Microsystems, Inc.
* 901 San Antonio Road, Palo Alto, CA 94303, USA
*
* This library is free software; you can redistribute it and/or
* modify it under the terms of the GNU Lesser General Public
* License version 2.1, as published by the Free Software Foundation.
*
* This library is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
* Lesser General Public License for more details.
*
* You should have received a copy of the GNU Lesser General Public
* License along with this library; if not, write to the Free Software
* Foundation, Inc., 59 Temple Place, Suite 330, Boston,
* MA 02111-1307 USA
*
************************************************************************/
// MARKER(update_precomp.py): autogen include statement, do not remove
#include "precompiled_xmloff.hxx"
#include "XMLChartStyleContext.hxx"
#ifndef _XMLOFF_XMLTOKEN_HXX
#include <xmloff/xmltoken.hxx>
#endif
#ifndef _XMLOFF_XMLNMSPE_HXX
#include "xmlnmspe.hxx"
#endif
#ifndef _XMLOFF_XMLNUMFI_HXX
#include <xmloff/xmlnumfi.hxx>
#endif
#ifndef _XMLOFF_FAMILIES_HXX_
#include <xmloff/families.hxx>
#endif
#include "XMLChartPropertyContext.hxx"
using namespace com::sun::star;
using ::xmloff::token::IsXMLToken;
using ::xmloff::token::XML_DATA_STYLE_NAME;
using ::xmloff::token::XML_TEXT_PROPERTIES;
using ::xmloff::token::XML_PARAGRAPH_PROPERTIES;
using ::xmloff::token::XML_GRAPHIC_PROPERTIES;
using ::xmloff::token::XML_CHART_PROPERTIES;
TYPEINIT1( XMLChartStyleContext, XMLPropStyleContext );
// protected
void XMLChartStyleContext::SetAttribute(
sal_uInt16 nPrefixKey,
const ::rtl::OUString& rLocalName,
const ::rtl::OUString& rValue )
{
if( IsXMLToken( rLocalName, XML_DATA_STYLE_NAME ) )
{
msDataStyleName =rValue;
}
else
{
XMLShapeStyleContext::SetAttribute( nPrefixKey, rLocalName, rValue );
}
}
//public
// CTOR
XMLChartStyleContext::XMLChartStyleContext(
SvXMLImport& rImport, sal_uInt16 nPrfx,
const ::rtl::OUString& rLName,
const uno::Reference< xml::sax::XAttributeList > & xAttrList,
SvXMLStylesContext& rStyles, sal_uInt16 nFamily ) :
XMLShapeStyleContext( rImport, nPrfx, rLName, xAttrList, rStyles, nFamily ),
mrStyles( rStyles )
{}
// DTOR
XMLChartStyleContext::~XMLChartStyleContext()
{}
void XMLChartStyleContext::FillPropertySet(
const uno::Reference< beans::XPropertySet > & rPropSet )
{
try
{
XMLShapeStyleContext::FillPropertySet( rPropSet );
}
catch( beans::UnknownPropertyException& )
{
DBG_ASSERT( false, "unknown property exception -> shape style not completly imported for chart style" );
}
if( msDataStyleName.getLength())
{
SvXMLNumFormatContext* pStyle = (SvXMLNumFormatContext *)mrStyles.FindStyleChildContext(
XML_STYLE_FAMILY_DATA_STYLE, msDataStyleName, sal_True );
if( pStyle )
{
uno::Any aNumberFormat;
sal_Int32 nNumberFormat = pStyle->GetKey();
aNumberFormat <<= nNumberFormat;
rPropSet->setPropertyValue( rtl::OUString( RTL_CONSTASCII_USTRINGPARAM( "NumberFormat" )),
aNumberFormat );
}
}
}
SvXMLImportContext *XMLChartStyleContext::CreateChildContext(
sal_uInt16 nPrefix,
const ::rtl::OUString& rLocalName,
const uno::Reference< xml::sax::XAttributeList > & xAttrList )
{
SvXMLImportContext* pContext = NULL;
if( XML_NAMESPACE_STYLE == nPrefix )
{
sal_uInt32 nFamily = 0;
if( IsXMLToken( rLocalName, XML_TEXT_PROPERTIES ) )
nFamily = XML_TYPE_PROP_TEXT;
else if( IsXMLToken( rLocalName, XML_PARAGRAPH_PROPERTIES ) )
nFamily = XML_TYPE_PROP_PARAGRAPH;
else if( IsXMLToken( rLocalName, XML_GRAPHIC_PROPERTIES ) )
nFamily = XML_TYPE_PROP_GRAPHIC;
else if( IsXMLToken( rLocalName, XML_CHART_PROPERTIES ) )
nFamily = XML_TYPE_PROP_CHART;
if( nFamily )
{
UniReference < SvXMLImportPropertyMapper > xImpPrMap =
GetStyles()->GetImportPropertyMapper( GetFamily() );
if( xImpPrMap.is() )
pContext = new XMLChartPropertyContext(
GetImport(), nPrefix, rLocalName, xAttrList, nFamily,
GetProperties(), xImpPrMap );
}
}
if( !pContext )
pContext = XMLShapeStyleContext::CreateChildContext( nPrefix, rLocalName,
xAttrList );
return pContext;
}
<commit_msg>INTEGRATION: CWS chart14 (1.11.48); FILE MERGED 2007/08/10 21:58:04 iha 1.11.48.1: #i37792# number format for data labels<commit_after>/*************************************************************************
*
* OpenOffice.org - a multi-platform office productivity suite
*
* $RCSfile: XMLChartStyleContext.cxx,v $
*
* $Revision: 1.12 $
*
* last change: $Author: vg $ $Date: 2007-10-22 16:33:51 $
*
* The Contents of this file are made available subject to
* the terms of GNU Lesser General Public License Version 2.1.
*
*
* GNU Lesser General Public License Version 2.1
* =============================================
* Copyright 2005 by Sun Microsystems, Inc.
* 901 San Antonio Road, Palo Alto, CA 94303, USA
*
* This library is free software; you can redistribute it and/or
* modify it under the terms of the GNU Lesser General Public
* License version 2.1, as published by the Free Software Foundation.
*
* This library is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
* Lesser General Public License for more details.
*
* You should have received a copy of the GNU Lesser General Public
* License along with this library; if not, write to the Free Software
* Foundation, Inc., 59 Temple Place, Suite 330, Boston,
* MA 02111-1307 USA
*
************************************************************************/
// MARKER(update_precomp.py): autogen include statement, do not remove
#include "precompiled_xmloff.hxx"
#include "XMLChartStyleContext.hxx"
#ifndef _XMLOFF_XMLTOKEN_HXX
#include <xmloff/xmltoken.hxx>
#endif
#ifndef _XMLOFF_XMLNMSPE_HXX
#include "xmlnmspe.hxx"
#endif
#ifndef _XMLOFF_XMLNUMFI_HXX
#include <xmloff/xmlnumfi.hxx>
#endif
#ifndef _XMLOFF_FAMILIES_HXX_
#include <xmloff/families.hxx>
#endif
#include "XMLChartPropertyContext.hxx"
using namespace com::sun::star;
using ::xmloff::token::IsXMLToken;
using ::xmloff::token::XML_DATA_STYLE_NAME;
using ::xmloff::token::XML_PERCENTAGE_DATA_STYLE_NAME;
using ::xmloff::token::XML_TEXT_PROPERTIES;
using ::xmloff::token::XML_PARAGRAPH_PROPERTIES;
using ::xmloff::token::XML_GRAPHIC_PROPERTIES;
using ::xmloff::token::XML_CHART_PROPERTIES;
TYPEINIT1( XMLChartStyleContext, XMLPropStyleContext );
// protected
void XMLChartStyleContext::SetAttribute(
sal_uInt16 nPrefixKey,
const ::rtl::OUString& rLocalName,
const ::rtl::OUString& rValue )
{
if( IsXMLToken( rLocalName, XML_DATA_STYLE_NAME ) )
{
msDataStyleName =rValue;
}
if( IsXMLToken( rLocalName, XML_PERCENTAGE_DATA_STYLE_NAME ) )
{
msPercentageDataStyleName =rValue;
}
else
{
XMLShapeStyleContext::SetAttribute( nPrefixKey, rLocalName, rValue );
}
}
//public
// CTOR
XMLChartStyleContext::XMLChartStyleContext(
SvXMLImport& rImport, sal_uInt16 nPrfx,
const ::rtl::OUString& rLName,
const uno::Reference< xml::sax::XAttributeList > & xAttrList,
SvXMLStylesContext& rStyles, sal_uInt16 nFamily ) :
XMLShapeStyleContext( rImport, nPrfx, rLName, xAttrList, rStyles, nFamily ),
mrStyles( rStyles )
{}
// DTOR
XMLChartStyleContext::~XMLChartStyleContext()
{}
namespace
{
void lcl_NumberFormatStyleToProperty( const ::rtl::OUString& rStyleName, const ::rtl::OUString& rPropertyName,
const SvXMLStylesContext& rStylesContext,
const uno::Reference< beans::XPropertySet >& rPropSet )
{
if( rStyleName.getLength())
{
SvXMLNumFormatContext* pStyle = (SvXMLNumFormatContext *)rStylesContext.FindStyleChildContext(
XML_STYLE_FAMILY_DATA_STYLE, rStyleName, sal_True );
if( pStyle )
{
uno::Any aNumberFormat;
sal_Int32 nNumberFormat = pStyle->GetKey();
aNumberFormat <<= nNumberFormat;
rPropSet->setPropertyValue( rPropertyName, aNumberFormat );
}
}
}
}// anonymous namespace
void XMLChartStyleContext::FillPropertySet(
const uno::Reference< beans::XPropertySet > & rPropSet )
{
try
{
XMLShapeStyleContext::FillPropertySet( rPropSet );
}
catch( beans::UnknownPropertyException& )
{
DBG_ASSERT( false, "unknown property exception -> shape style not completly imported for chart style" );
}
lcl_NumberFormatStyleToProperty( msDataStyleName, rtl::OUString( RTL_CONSTASCII_USTRINGPARAM( "NumberFormat" )), mrStyles, rPropSet );
lcl_NumberFormatStyleToProperty( msPercentageDataStyleName, rtl::OUString( RTL_CONSTASCII_USTRINGPARAM( "PercentageNumberFormat" )), mrStyles, rPropSet );
}
SvXMLImportContext *XMLChartStyleContext::CreateChildContext(
sal_uInt16 nPrefix,
const ::rtl::OUString& rLocalName,
const uno::Reference< xml::sax::XAttributeList > & xAttrList )
{
SvXMLImportContext* pContext = NULL;
if( XML_NAMESPACE_STYLE == nPrefix )
{
sal_uInt32 nFamily = 0;
if( IsXMLToken( rLocalName, XML_TEXT_PROPERTIES ) )
nFamily = XML_TYPE_PROP_TEXT;
else if( IsXMLToken( rLocalName, XML_PARAGRAPH_PROPERTIES ) )
nFamily = XML_TYPE_PROP_PARAGRAPH;
else if( IsXMLToken( rLocalName, XML_GRAPHIC_PROPERTIES ) )
nFamily = XML_TYPE_PROP_GRAPHIC;
else if( IsXMLToken( rLocalName, XML_CHART_PROPERTIES ) )
nFamily = XML_TYPE_PROP_CHART;
if( nFamily )
{
UniReference < SvXMLImportPropertyMapper > xImpPrMap =
GetStyles()->GetImportPropertyMapper( GetFamily() );
if( xImpPrMap.is() )
pContext = new XMLChartPropertyContext(
GetImport(), nPrefix, rLocalName, xAttrList, nFamily,
GetProperties(), xImpPrMap );
}
}
if( !pContext )
pContext = XMLShapeStyleContext::CreateChildContext( nPrefix, rLocalName,
xAttrList );
return pContext;
}
<|endoftext|>
|
<commit_before>#pragma once
/*
* Covariant Script Version Info
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*
* Copyright (C) 2018 Michael Lee(李登淳)
* Email: mikecovlee@163.com
* Github: https://github.com/mikecovlee
*
* Version Format:
* 1 . 0 . 0 [Version Code](Preview/Unstable/Stable) Build 1
* | | | |
* | | Minor Status
* | Major
* Master
*
*/
#define COVSCRIPT_VERSION_NUM 3,0,0,6
#define COVSCRIPT_VERSION_STR "3.0.0 Pantholops hodgsonii(Stable) Build 6"
#define COVSCRIPT_STD_VERSION 190101
#define COVSCRIPT_ABI_VERSION 190101
#if defined(_WIN32) || defined(WIN32)
#define COVSCRIPT_PLATFORM_WIN32
#endif
<commit_msg>Update CovScript Version<commit_after>#pragma once
/*
* Covariant Script Version Info
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*
* Copyright (C) 2018 Michael Lee(李登淳)
* Email: mikecovlee@163.com
* Github: https://github.com/mikecovlee
*
* Version Format:
* 1 . 0 . 0 [Version Code](Preview/Unstable/Stable) Build 1
* | | | |
* | | Minor Status
* | Major
* Master
*
*/
#define COVSCRIPT_VERSION_NUM 3,0,1,1
#define COVSCRIPT_VERSION_STR "3.0.1 Acipenser sinensis(Unstable) Build 1"
#define COVSCRIPT_STD_VERSION 190101
#define COVSCRIPT_ABI_VERSION 190101
#if defined(_WIN32) || defined(WIN32)
#define COVSCRIPT_PLATFORM_WIN32
#endif
<|endoftext|>
|
<commit_before>#include <ros/ros.h>
#include <dynamic_reconfigure/server.h>
#include <geometry_msgs/Pose.h>
#include <geometry_msgs/PoseArray.h>
#include <geometry_msgs/PoseStamped.h>
#include <kinect_tomato_searcher/CalibrationConfig.h>
#include <algorithm>
#include <memory>
#include <vector>
struct Calibrator
{
double offset_x_;
double offset_y_;
double offset_z_;
geometry_msgs::Pose calibrate(geometry_msgs::Pose) const;
void callback(kinect_tomato_searcher::CalibrationConfig& config, uint32_t level);
};
class NearSelector
{
public:
geometry_msgs::Pose select(const geometry_msgs::PoseArray& pose_array);
private:
geometry_msgs::Pose last_pose_;
};
void callback(const geometry_msgs::PoseArray&);
double calcDiff(const geometry_msgs::Pose&, const geometry_msgs::Pose&);
ros::Publisher pub;
std::unique_ptr<Calibrator> calibrator;
int main(int argc, char** argv)
{
ros::init(argc, argv, "kinect_tomato_selector_node");
ros::NodeHandle tomato_nh {"tomato"};
auto sub = tomato_nh.subscribe("array", 1, &callback);
pub = tomato_nh.advertise<geometry_msgs::PoseStamped>("raw", 1);
ros::NodeHandle offset_nh {"~offset"};
double offset_x, offset_y, offset_z;
offset_nh.getParam("x", offset_x);
offset_nh.getParam("y", offset_y);
offset_nh.getParam("z", offset_z);
calibrator = std::unique_ptr<Calibrator> {new Calibrator {offset_x, offset_y, offset_z}};
ros::spin();
return 0;
}
inline geometry_msgs::Pose Calibrator::calibrate(geometry_msgs::Pose pose) const
{
pose.position.x += offset_x_;
pose.position.y += offset_y_;
pose.position.z += offset_z_;
return pose;
}
void Calibrator::callback(kinect_tomato_searcher::CalibrationConfig& config, uint32_t level)
{
offset_x_ = config.offset_x;
offset_y_ = config.offset_y;
offset_z_ = config.offset_z;
}
inline geometry_msgs::Pose NearSelector::select(const geometry_msgs::PoseArray& pose_array)
{
std::vector<double> diffs(pose_array.poses.size());
auto diff_it = diffs.begin();
for (auto pose : pose_array.poses) {
*diff_it = calcDiff(pose, last_pose_);
++diff_it;
}
auto min_diff_it = std::min_element(diffs.cbegin(), diffs.cend());
return pose_array.poses[min_diff_it - diffs.cbegin()];
}
/**
* This function calculate lie distance.
*
* @return diff linear difference. NOT real difference.
*/
inline double calcDiff(const geometry_msgs::Pose& target, const geometry_msgs::Pose& origin) {
double diff_x {target.position.x - origin.position.x};
double diff_y {target.position.y - origin.position.y};
double diff_z {target.position.z - origin.position.z};
return diff_x + diff_y + diff_z;
}
void callback(const geometry_msgs::PoseArray& pose_array)
{
static NearSelector selector {};
geometry_msgs::PoseStamped pub_msg;
pub_msg.header = pose_array.header;
pub_msg.pose = calibrator->calibrate(selector.select(pose_array));
pub.publish(pub_msg);
}
<commit_msg>Impliment dynamic_reconfigure<commit_after>#include <ros/ros.h>
#include <dynamic_reconfigure/server.h>
#include <geometry_msgs/Pose.h>
#include <geometry_msgs/PoseArray.h>
#include <geometry_msgs/PoseStamped.h>
#include <kinect_tomato_searcher/CalibrationConfig.h>
#include <algorithm>
#include <memory>
#include <vector>
struct Calibrator
{
Calibrator(double offset_x, double offset_y, double offset_z);
double offset_x_;
double offset_y_;
double offset_z_;
geometry_msgs::Pose calibrate(geometry_msgs::Pose) const;
private:
dynamic_reconfigure::Server<kinect_tomato_searcher::CalibrationConfig> server;
dynamic_reconfigure::Server<kinect_tomato_searcher::CalibrationConfig>::CallbackType f;
void callback(kinect_tomato_searcher::CalibrationConfig& config, uint32_t level);
};
class NearSelector
{
public:
geometry_msgs::Pose select(const geometry_msgs::PoseArray& pose_array);
private:
geometry_msgs::Pose last_pose_;
};
void callback(const geometry_msgs::PoseArray&);
double calcDiff(const geometry_msgs::Pose&, const geometry_msgs::Pose&);
ros::Publisher pub;
std::unique_ptr<Calibrator> calibrator;
int main(int argc, char** argv)
{
ros::init(argc, argv, "kinect_tomato_selector_node");
ros::NodeHandle tomato_nh {"tomato"};
auto sub = tomato_nh.subscribe("array", 1, &callback);
pub = tomato_nh.advertise<geometry_msgs::PoseStamped>("raw", 1);
ros::NodeHandle offset_nh {"~offset"};
double offset_x, offset_y, offset_z;
offset_nh.getParam("x", offset_x);
offset_nh.getParam("y", offset_y);
offset_nh.getParam("z", offset_z);
calibrator = std::unique_ptr<Calibrator> {new Calibrator {offset_x, offset_y, offset_z}};
ros::spin();
return 0;
}
Calibrator::Calibrator(double offset_x, double offset_y, double offset_z)
: offset_x_ {offset_x},
offset_y_ {offset_y},
offset_z_ {offset_z},
server {},
f(std::bind(&Calibrator::callback, this, std::placeholders::_1, std::placeholders::_2))
{
server.setCallback(f);
}
inline geometry_msgs::Pose Calibrator::calibrate(geometry_msgs::Pose pose) const
{
pose.position.x += offset_x_;
pose.position.y += offset_y_;
pose.position.z += offset_z_;
return pose;
}
void Calibrator::callback(kinect_tomato_searcher::CalibrationConfig& config, uint32_t level)
{
offset_x_ = config.offset_x;
offset_y_ = config.offset_y;
offset_z_ = config.offset_z;
}
inline geometry_msgs::Pose NearSelector::select(const geometry_msgs::PoseArray& pose_array)
{
std::vector<double> diffs(pose_array.poses.size());
auto diff_it = diffs.begin();
for (auto pose : pose_array.poses) {
*diff_it = calcDiff(pose, last_pose_);
++diff_it;
}
auto min_diff_it = std::min_element(diffs.cbegin(), diffs.cend());
return pose_array.poses[min_diff_it - diffs.cbegin()];
}
/**
* This function calculate lie distance.
*
* @return diff linear difference. NOT real difference.
*/
inline double calcDiff(const geometry_msgs::Pose& target, const geometry_msgs::Pose& origin) {
double diff_x {target.position.x - origin.position.x};
double diff_y {target.position.y - origin.position.y};
double diff_z {target.position.z - origin.position.z};
return diff_x + diff_y + diff_z;
}
void callback(const geometry_msgs::PoseArray& pose_array)
{
static NearSelector selector {};
geometry_msgs::PoseStamped pub_msg;
pub_msg.header = pose_array.header;
pub_msg.pose = calibrator->calibrate(selector.select(pose_array));
pub.publish(pub_msg);
}
<|endoftext|>
|
<commit_before>/*************************************************************************
*
* $RCSfile: NamedBoolPropertyHdl.cxx,v $
*
* $Revision: 1.2 $
*
* last change: $Author: sab $ $Date: 2001-03-16 14:37:07 $
*
* The Contents of this file are made available subject to the terms of
* either of the following licenses
*
* - GNU Lesser General Public License Version 2.1
* - Sun Industry Standards Source License Version 1.1
*
* Sun Microsystems Inc., October, 2000
*
* GNU Lesser General Public License Version 2.1
* =============================================
* Copyright 2000 by Sun Microsystems, Inc.
* 901 San Antonio Road, Palo Alto, CA 94303, USA
*
* This library is free software; you can redistribute it and/or
* modify it under the terms of the GNU Lesser General Public
* License version 2.1, as published by the Free Software Foundation.
*
* This library is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
* Lesser General Public License for more details.
*
* You should have received a copy of the GNU Lesser General Public
* License along with this library; if not, write to the Free Software
* Foundation, Inc., 59 Temple Place, Suite 330, Boston,
* MA 02111-1307 USA
*
*
* Sun Industry Standards Source License Version 1.1
* =================================================
* The contents of this file are subject to the Sun Industry Standards
* Source License Version 1.1 (the "License"); You may not use this file
* except in compliance with the License. You may obtain a copy of the
* License at http://www.openoffice.org/license.html.
*
* Software provided under this License is provided on an "AS IS" basis,
* WITHOUT WARRANTY OF ANY KIND, EITHER EXPRESSED OR IMPLIED, INCLUDING,
* WITHOUT LIMITATION, WARRANTIES THAT THE SOFTWARE IS FREE OF DEFECTS,
* MERCHANTABLE, FIT FOR A PARTICULAR PURPOSE, OR NON-INFRINGING.
* See the License for the specific provisions governing your rights and
* obligations concerning the Software.
*
* The Initial Developer of the Original Code is: Sun Microsystems, Inc.
*
* Copyright: 2000 by Sun Microsystems, Inc.
*
* All Rights Reserved.
*
* Contributor(s): _______________________________________
*
*
************************************************************************/
#ifndef _XMLOFF_NAMEDBOOLPROPERTYHANDLER_HXX
#include <NamedBoolPropertyHdl.hxx>
#endif
#ifndef _XMLOFF_XMLUCONV_HXX
#include "xmluconv.hxx"
#endif
#ifndef _COMPHELPER_EXTRACT_HXX_
#include <comphelper/extract.hxx>
#endif
#ifndef _RTL_USTRING_
#include <rtl/ustring>
#endif
#ifndef _RTL_USTRBUF_HXX_
#include <rtl/ustrbuf.hxx>
#endif
#ifndef _COM_SUN_STAR_UNO_ANY_HXX_
#include <com/sun/star/uno/Any.hxx>
#endif
using namespace ::rtl;
using namespace ::com::sun::star::uno;
///////////////////////////////////////////////////////////////////////////////
//
// class XMLNamedBoolPropertyHdl
//
XMLNamedBoolPropertyHdl::~XMLNamedBoolPropertyHdl()
{
// Nothing to do
}
sal_Bool XMLNamedBoolPropertyHdl::importXML( const OUString& rStrImpValue, Any& rValue, const SvXMLUnitConverter& rUnitConverter ) const
{
if( rStrImpValue == maTrueStr )
{
rValue = ::cppu::bool2any( sal_True );
return sal_True;
}
if( rStrImpValue == maFalseStr )
{
rValue = ::cppu::bool2any( sal_False );
return sal_True;
}
return sal_False;
}
sal_Bool XMLNamedBoolPropertyHdl::exportXML( OUString& rStrExpValue, const Any& rValue, const SvXMLUnitConverter& rUnitConverter ) const
{
if( ::cppu::any2bool( rValue ) )
{
rStrExpValue = maTrueStr;
}
else
{
rStrExpValue = maFalseStr;
}
return sal_True;
}
<commit_msg>INTEGRATION: CWS ooo19126 (1.2.642); FILE MERGED 2005/09/05 14:39:12 rt 1.2.642.1: #i54170# Change license header: remove SISSL<commit_after>/*************************************************************************
*
* OpenOffice.org - a multi-platform office productivity suite
*
* $RCSfile: NamedBoolPropertyHdl.cxx,v $
*
* $Revision: 1.3 $
*
* last change: $Author: rt $ $Date: 2005-09-09 14:25:04 $
*
* The Contents of this file are made available subject to
* the terms of GNU Lesser General Public License Version 2.1.
*
*
* GNU Lesser General Public License Version 2.1
* =============================================
* Copyright 2005 by Sun Microsystems, Inc.
* 901 San Antonio Road, Palo Alto, CA 94303, USA
*
* This library is free software; you can redistribute it and/or
* modify it under the terms of the GNU Lesser General Public
* License version 2.1, as published by the Free Software Foundation.
*
* This library is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
* Lesser General Public License for more details.
*
* You should have received a copy of the GNU Lesser General Public
* License along with this library; if not, write to the Free Software
* Foundation, Inc., 59 Temple Place, Suite 330, Boston,
* MA 02111-1307 USA
*
************************************************************************/
#ifndef _XMLOFF_NAMEDBOOLPROPERTYHANDLER_HXX
#include <NamedBoolPropertyHdl.hxx>
#endif
#ifndef _XMLOFF_XMLUCONV_HXX
#include "xmluconv.hxx"
#endif
#ifndef _COMPHELPER_EXTRACT_HXX_
#include <comphelper/extract.hxx>
#endif
#ifndef _RTL_USTRING_
#include <rtl/ustring>
#endif
#ifndef _RTL_USTRBUF_HXX_
#include <rtl/ustrbuf.hxx>
#endif
#ifndef _COM_SUN_STAR_UNO_ANY_HXX_
#include <com/sun/star/uno/Any.hxx>
#endif
using namespace ::rtl;
using namespace ::com::sun::star::uno;
///////////////////////////////////////////////////////////////////////////////
//
// class XMLNamedBoolPropertyHdl
//
XMLNamedBoolPropertyHdl::~XMLNamedBoolPropertyHdl()
{
// Nothing to do
}
sal_Bool XMLNamedBoolPropertyHdl::importXML( const OUString& rStrImpValue, Any& rValue, const SvXMLUnitConverter& rUnitConverter ) const
{
if( rStrImpValue == maTrueStr )
{
rValue = ::cppu::bool2any( sal_True );
return sal_True;
}
if( rStrImpValue == maFalseStr )
{
rValue = ::cppu::bool2any( sal_False );
return sal_True;
}
return sal_False;
}
sal_Bool XMLNamedBoolPropertyHdl::exportXML( OUString& rStrExpValue, const Any& rValue, const SvXMLUnitConverter& rUnitConverter ) const
{
if( ::cppu::any2bool( rValue ) )
{
rStrExpValue = maTrueStr;
}
else
{
rStrExpValue = maFalseStr;
}
return sal_True;
}
<|endoftext|>
|
<commit_before><commit_msg>adding glBindBuffer in opengl.hpp<commit_after>#ifndef ATEMA_OPENGL_HEADER
#define ATEMA_OPENGL_HEADER
#include <glad/glad.h>
// glBindBuffer
#undef glBindBuffer
GLAPI PFNGLBINDBUFFERPROC at_glBindBuffer;
#define glBindBuffer at_glBindBuffer
#endif<|endoftext|>
|
<commit_before>/*
Copyright (c) 2005, Arvid Norberg
All rights reserved.
Redistribution and use in source and binary forms, with or without
modification, are permitted provided that the following conditions
are met:
* Redistributions of source code must retain the above copyright
notice, this list of conditions and the following disclaimer.
* Redistributions in binary form must reproduce the above copyright
notice, this list of conditions and the following disclaimer in
the documentation and/or other materials provided with the distribution.
* Neither the name of the author nor the names of its
contributors may be used to endorse or promote products derived
from this software without specific prior written permission.
THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS"
AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE
IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE
ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT OWNER OR CONTRIBUTORS BE
LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR
CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF
SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS
INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN
CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE)
ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE
POSSIBILITY OF SUCH DAMAGE.
*/
#ifndef TORRENT_CONFIG_HPP_INCLUDED
#define TORRENT_CONFIG_HPP_INCLUDED
#include <boost/config.hpp>
#include <boost/version.hpp>
#if defined(__GNUC__) && __GNUC__ >= 4
#define TORRENT_DEPRECATED __attribute__ ((deprecated))
# if defined(TORRENT_BUILDING_SHARED) || defined(TORRENT_LINKING_SHARED)
# define TORRENT_EXPORT __attribute__ ((visibility("default")))
# else
# define TORRENT_EXPORT
# endif
#elif defined(__GNUC__)
# define TORRENT_EXPORT
#elif defined(BOOST_MSVC)
# if defined(TORRENT_BUILDING_SHARED)
# define TORRENT_EXPORT __declspec(dllexport)
# elif defined(TORRENT_LINKING_SHARED)
# define TORRENT_EXPORT __declspec(dllimport)
# else
# define TORRENT_EXPORT
# endif
#else
# define TORRENT_EXPORT
#endif
#ifndef TORRENT_DEPRECATED
#define TORRENT_DEPRECATED
#endif
// set up defines for target environments
#if (defined __APPLE__ && __MACH__) || defined __FreeBSD__ || defined __NetBSD__ \
|| defined __OpenBSD__ || defined __bsdi__ || defined __DragonFly__ \
|| defined __FreeBSD_kernel__
#define TORRENT_BSD
#elif defined __linux__
#define TORRENT_LINUX
#elif defined WIN32
#define TORRENT_WINDOWS
#elif defined sun || defined __sun
#define TORRENT_SOLARIS
#else
#warning unkown OS, assuming BSD
#define TORRENT_BSD
#endif
#define TORRENT_USE_IPV6 1
#define TORRENT_USE_MLOCK 1
#define TORRENT_USE_READV 1
#define TORRENT_USE_WRITEV 1
#define TORRENT_USE_IOSTREAM 1
// should wpath or path be used?
#if defined UNICODE && !defined BOOST_FILESYSTEM_NARROW_ONLY \
&& BOOST_VERSION >= 103400 && !defined __APPLE__
#define TORRENT_USE_WPATH 1
#else
#define TORRENT_USE_WPATH 0
#endif
#ifdef TORRENT_WINDOWS
// this is the maximum number of characters in a
// path element / filename on windows
#define NAME_MAX 255
#endif
#if (defined(TORRENT_LOGGING) || defined(TORRENT_VERBOSE_LOGGING)) && !defined (TORRENT_UPNP_LOGGING)
#define TORRENT_UPNP_LOGGING
#endif
#if !TORRENT_USE_WPATH && defined TORRENT_LINUX
// libiconv presnce, not implemented yet
#define TORRENT_USE_LOCALE_FILENAMES 1
#else
#define TORRENT_USE_LOCALE_FILENAMES 0
#endif
#endif // TORRENT_CONFIG_HPP_INCLUDED
<commit_msg>defines for snprintf and strtoll for windows<commit_after>/*
Copyright (c) 2005, Arvid Norberg
All rights reserved.
Redistribution and use in source and binary forms, with or without
modification, are permitted provided that the following conditions
are met:
* Redistributions of source code must retain the above copyright
notice, this list of conditions and the following disclaimer.
* Redistributions in binary form must reproduce the above copyright
notice, this list of conditions and the following disclaimer in
the documentation and/or other materials provided with the distribution.
* Neither the name of the author nor the names of its
contributors may be used to endorse or promote products derived
from this software without specific prior written permission.
THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS"
AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE
IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE
ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT OWNER OR CONTRIBUTORS BE
LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR
CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF
SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS
INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN
CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE)
ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE
POSSIBILITY OF SUCH DAMAGE.
*/
#ifndef TORRENT_CONFIG_HPP_INCLUDED
#define TORRENT_CONFIG_HPP_INCLUDED
#include <boost/config.hpp>
#include <boost/version.hpp>
#if defined(__GNUC__) && __GNUC__ >= 4
#define TORRENT_DEPRECATED __attribute__ ((deprecated))
# if defined(TORRENT_BUILDING_SHARED) || defined(TORRENT_LINKING_SHARED)
# define TORRENT_EXPORT __attribute__ ((visibility("default")))
# else
# define TORRENT_EXPORT
# endif
#elif defined(__GNUC__)
# define TORRENT_EXPORT
#elif defined(BOOST_MSVC)
# if defined(TORRENT_BUILDING_SHARED)
# define TORRENT_EXPORT __declspec(dllexport)
# elif defined(TORRENT_LINKING_SHARED)
# define TORRENT_EXPORT __declspec(dllimport)
# else
# define TORRENT_EXPORT
# endif
#else
# define TORRENT_EXPORT
#endif
#ifndef TORRENT_DEPRECATED
#define TORRENT_DEPRECATED
#endif
// set up defines for target environments
#if (defined __APPLE__ && __MACH__) || defined __FreeBSD__ || defined __NetBSD__ \
|| defined __OpenBSD__ || defined __bsdi__ || defined __DragonFly__ \
|| defined __FreeBSD_kernel__
#define TORRENT_BSD
#elif defined __linux__
#define TORRENT_LINUX
#elif defined WIN32
#define TORRENT_WINDOWS
#elif defined sun || defined __sun
#define TORRENT_SOLARIS
#else
#warning unkown OS, assuming BSD
#define TORRENT_BSD
#endif
#define TORRENT_USE_IPV6 1
#define TORRENT_USE_MLOCK 1
#define TORRENT_USE_READV 1
#define TORRENT_USE_WRITEV 1
#define TORRENT_USE_IOSTREAM 1
// should wpath or path be used?
#if defined UNICODE && !defined BOOST_FILESYSTEM_NARROW_ONLY \
&& BOOST_VERSION >= 103400 && !defined __APPLE__
#define TORRENT_USE_WPATH 1
#else
#define TORRENT_USE_WPATH 0
#endif
#ifdef TORRENT_WINDOWS
// this is the maximum number of characters in a
// path element / filename on windows
#define NAME_MAX 255
#define snprintf _snprintf_s
#define strtoll _strtoi64
#endif
#if (defined(TORRENT_LOGGING) || defined(TORRENT_VERBOSE_LOGGING)) && !defined (TORRENT_UPNP_LOGGING)
#define TORRENT_UPNP_LOGGING
#endif
#if !TORRENT_USE_WPATH && defined TORRENT_LINUX
// libiconv presnce, not implemented yet
#define TORRENT_USE_LOCALE_FILENAMES 1
#else
#define TORRENT_USE_LOCALE_FILENAMES 0
#endif
#endif // TORRENT_CONFIG_HPP_INCLUDED
<|endoftext|>
|
<commit_before>/* -*- Mode: C++; tab-width: 4; indent-tabs-mode: nil; c-basic-offset: 4 -*- */
/*
* This file is part of the LibreOffice project.
*
* This Source Code Form is subject to the terms of the Mozilla Public
* License, v. 2.0. If a copy of the MPL was not distributed with this
* file, You can obtain one at http://mozilla.org/MPL/2.0/.
*
* This file incorporates work covered by the following license notice:
*
* Licensed to the Apache Software Foundation (ASF) under one or more
* contributor license agreements. See the NOTICE file distributed
* with this work for additional information regarding copyright
* ownership. The ASF licenses this file to you under the Apache
* License, Version 2.0 (the "License"); you may not use this file
* except in compliance with the License. You may obtain a copy of
* the License at http://www.apache.org/licenses/LICENSE-2.0 .
*/
#ifndef INCLUDED_COMPHELPER_STL_TYPES_HXX
#define INCLUDED_COMPHELPER_STL_TYPES_HXX
#include <sal/config.h>
#include <stack>
#include <math.h>
#include <functional>
#include <rtl/ustring.hxx>
#include <rtl/ustrbuf.hxx>
#include <com/sun/star/uno/Reference.hxx>
#include <com/sun/star/beans/PropertyValue.hpp>
#include <com/sun/star/beans/NamedValue.hpp>
//... namespace comphelper ................................................
namespace comphelper
{
//.........................................................................
//========================================================================
// comparison functors
struct UStringMixLess : public ::std::binary_function< OUString, OUString, bool>
{
bool m_bCaseSensitive;
public:
UStringMixLess(bool bCaseSensitive = true):m_bCaseSensitive(bCaseSensitive){}
bool operator() (const OUString& x, const OUString& y) const
{
if (m_bCaseSensitive)
return rtl_ustr_compare(x.getStr(), y.getStr()) < 0 ? true : false;
else
return rtl_ustr_compareIgnoreAsciiCase(x.getStr(), y.getStr()) < 0 ? true : false;
}
bool isCaseSensitive() const {return m_bCaseSensitive;}
};
//------------------------------------------------------------------------
struct UStringEqual
{
sal_Bool operator() (const OUString& lhs, const OUString& rhs) const { return lhs.equals( rhs );}
};
//------------------------------------------------------------------------
struct UStringIEqual
{
sal_Bool operator() (const OUString& lhs, const OUString& rhs) const { return lhs.equalsIgnoreAsciiCase( rhs );}
};
//------------------------------------------------------------------------
class UStringMixEqual
{
sal_Bool m_bCaseSensitive;
public:
UStringMixEqual(sal_Bool bCaseSensitive = sal_True):m_bCaseSensitive(bCaseSensitive){}
sal_Bool operator() (const OUString& lhs, const OUString& rhs) const
{
return m_bCaseSensitive ? lhs.equals( rhs ) : lhs.equalsIgnoreAsciiCase( rhs );
}
sal_Bool isCaseSensitive() const {return m_bCaseSensitive;}
};
//------------------------------------------------------------------------
class TStringMixEqualFunctor : public ::std::binary_function< OUString,OUString,bool>
{
sal_Bool m_bCaseSensitive;
public:
TStringMixEqualFunctor(sal_Bool bCaseSensitive = sal_True)
:m_bCaseSensitive(bCaseSensitive)
{}
bool operator() (const OUString& lhs, const OUString& rhs) const
{
return !!(m_bCaseSensitive ? lhs.equals( rhs ) : lhs.equalsIgnoreAsciiCase( rhs ));
}
sal_Bool isCaseSensitive() const {return m_bCaseSensitive;}
};
//------------------------------------------------------------------------
class TPropertyValueEqualFunctor : public ::std::binary_function< ::com::sun::star::beans::PropertyValue,OUString,bool>
{
public:
TPropertyValueEqualFunctor()
{}
bool operator() (const ::com::sun::star::beans::PropertyValue& lhs, const OUString& rhs) const
{
return !!(lhs.Name == rhs);
}
};
//------------------------------------------------------------------------
class TNamedValueEqualFunctor : public ::std::binary_function< ::com::sun::star::beans::NamedValue,OUString,bool>
{
public:
TNamedValueEqualFunctor()
{}
bool operator() (const ::com::sun::star::beans::NamedValue& lhs, const OUString& rhs) const
{
return !!(lhs.Name == rhs);
}
};
//------------------------------------------------------------------------
class UStringMixHash
{
sal_Bool m_bCaseSensitive;
public:
UStringMixHash(sal_Bool bCaseSensitive = sal_True):m_bCaseSensitive(bCaseSensitive){}
size_t operator() (const OUString& rStr) const
{
return m_bCaseSensitive ? rStr.hashCode() : rStr.toAsciiUpperCase().hashCode();
}
sal_Bool isCaseSensitive() const {return m_bCaseSensitive;}
};
//=====================================================================
//= OInterfaceCompare
//=====================================================================
/** is stl-compliant structure for comparing Reference< <iface> > instances
*/
template < class IAFCE >
struct OInterfaceCompare
:public ::std::binary_function < ::com::sun::star::uno::Reference< IAFCE >
, ::com::sun::star::uno::Reference< IAFCE >
, bool
>
{
bool operator() (const ::com::sun::star::uno::Reference< IAFCE >& lhs, const ::com::sun::star::uno::Reference< IAFCE >& rhs) const
{
return lhs.get() < rhs.get();
// this does not make any sense if you see the semantics of the pointer returned by get:
// It's a pointer to a point in memory where an interface implementation lies.
// But for our purpose (provide a reliable less-operator which can be used with the STL), this is
// sufficient ....
}
};
template <class _Tp, class _Arg>
class mem_fun1_t : public ::std::binary_function<_Tp*,_Arg,void>
{
typedef void (_Tp::*_fun_type)(_Arg);
public:
explicit mem_fun1_t(_fun_type __pf) : _M_f(__pf) {}
void operator()(_Tp* __p, _Arg __x) const { (__p->*_M_f)(__x); }
private:
_fun_type _M_f;
};
template <class _Tp, class _Arg>
inline mem_fun1_t<_Tp,_Arg> mem_fun(void (_Tp::*__f)(_Arg))
{
return mem_fun1_t<_Tp,_Arg>(__f);
}
//.........................................................................
/** output iterator that appends OUStrings into an OUStringBuffer.
*/
class OUStringBufferAppender :
public ::std::iterator< ::std::output_iterator_tag, void, void, void, void>
{
public:
typedef OUStringBufferAppender Self;
typedef ::std::output_iterator_tag iterator_category;
typedef void value_type;
typedef void reference;
typedef void pointer;
typedef size_t difference_type;
OUStringBufferAppender(OUStringBuffer & i_rBuffer)
: m_rBuffer(i_rBuffer) { }
Self & operator=(OUString const & i_rStr)
{
m_rBuffer.append( i_rStr );
return *this;
}
Self & operator*() { return *this; } // so operator= works
Self & operator++() { return *this; }
Self & operator++(int) { return *this; }
private:
OUStringBuffer & m_rBuffer;
};
//.........................................................................
/** algorithm similar to std::copy, but inserts a separator between elements.
*/
template< typename ForwardIter, typename OutputIter, typename T >
OutputIter intersperse(
ForwardIter start, ForwardIter end, OutputIter out, T const & separator)
{
if (start != end) {
*out = *start;
++start;
++out;
}
while (start != end) {
*out = separator;
++out;
*out = *start;
++start;
++out;
}
return out;
}
//.........................................................................
}
//... namespace comphelper ................................................
#endif // INCLUDED_COMPHELPER_STL_TYPES_HXX
/* vim:set shiftwidth=4 softtabstop=4 expandtab: */
<commit_msg>Remove unused comphelper::UStringMixHash<commit_after>/* -*- Mode: C++; tab-width: 4; indent-tabs-mode: nil; c-basic-offset: 4 -*- */
/*
* This file is part of the LibreOffice project.
*
* This Source Code Form is subject to the terms of the Mozilla Public
* License, v. 2.0. If a copy of the MPL was not distributed with this
* file, You can obtain one at http://mozilla.org/MPL/2.0/.
*
* This file incorporates work covered by the following license notice:
*
* Licensed to the Apache Software Foundation (ASF) under one or more
* contributor license agreements. See the NOTICE file distributed
* with this work for additional information regarding copyright
* ownership. The ASF licenses this file to you under the Apache
* License, Version 2.0 (the "License"); you may not use this file
* except in compliance with the License. You may obtain a copy of
* the License at http://www.apache.org/licenses/LICENSE-2.0 .
*/
#ifndef INCLUDED_COMPHELPER_STL_TYPES_HXX
#define INCLUDED_COMPHELPER_STL_TYPES_HXX
#include <sal/config.h>
#include <stack>
#include <math.h>
#include <functional>
#include <rtl/ustring.hxx>
#include <rtl/ustrbuf.hxx>
#include <com/sun/star/uno/Reference.hxx>
#include <com/sun/star/beans/PropertyValue.hpp>
#include <com/sun/star/beans/NamedValue.hpp>
//... namespace comphelper ................................................
namespace comphelper
{
//.........................................................................
//========================================================================
// comparison functors
struct UStringMixLess : public ::std::binary_function< OUString, OUString, bool>
{
bool m_bCaseSensitive;
public:
UStringMixLess(bool bCaseSensitive = true):m_bCaseSensitive(bCaseSensitive){}
bool operator() (const OUString& x, const OUString& y) const
{
if (m_bCaseSensitive)
return rtl_ustr_compare(x.getStr(), y.getStr()) < 0 ? true : false;
else
return rtl_ustr_compareIgnoreAsciiCase(x.getStr(), y.getStr()) < 0 ? true : false;
}
bool isCaseSensitive() const {return m_bCaseSensitive;}
};
//------------------------------------------------------------------------
struct UStringEqual
{
sal_Bool operator() (const OUString& lhs, const OUString& rhs) const { return lhs.equals( rhs );}
};
//------------------------------------------------------------------------
struct UStringIEqual
{
sal_Bool operator() (const OUString& lhs, const OUString& rhs) const { return lhs.equalsIgnoreAsciiCase( rhs );}
};
//------------------------------------------------------------------------
class UStringMixEqual
{
sal_Bool m_bCaseSensitive;
public:
UStringMixEqual(sal_Bool bCaseSensitive = sal_True):m_bCaseSensitive(bCaseSensitive){}
sal_Bool operator() (const OUString& lhs, const OUString& rhs) const
{
return m_bCaseSensitive ? lhs.equals( rhs ) : lhs.equalsIgnoreAsciiCase( rhs );
}
sal_Bool isCaseSensitive() const {return m_bCaseSensitive;}
};
//------------------------------------------------------------------------
class TStringMixEqualFunctor : public ::std::binary_function< OUString,OUString,bool>
{
sal_Bool m_bCaseSensitive;
public:
TStringMixEqualFunctor(sal_Bool bCaseSensitive = sal_True)
:m_bCaseSensitive(bCaseSensitive)
{}
bool operator() (const OUString& lhs, const OUString& rhs) const
{
return !!(m_bCaseSensitive ? lhs.equals( rhs ) : lhs.equalsIgnoreAsciiCase( rhs ));
}
sal_Bool isCaseSensitive() const {return m_bCaseSensitive;}
};
//------------------------------------------------------------------------
class TPropertyValueEqualFunctor : public ::std::binary_function< ::com::sun::star::beans::PropertyValue,OUString,bool>
{
public:
TPropertyValueEqualFunctor()
{}
bool operator() (const ::com::sun::star::beans::PropertyValue& lhs, const OUString& rhs) const
{
return !!(lhs.Name == rhs);
}
};
//------------------------------------------------------------------------
class TNamedValueEqualFunctor : public ::std::binary_function< ::com::sun::star::beans::NamedValue,OUString,bool>
{
public:
TNamedValueEqualFunctor()
{}
bool operator() (const ::com::sun::star::beans::NamedValue& lhs, const OUString& rhs) const
{
return !!(lhs.Name == rhs);
}
};
//=====================================================================
//= OInterfaceCompare
//=====================================================================
/** is stl-compliant structure for comparing Reference< <iface> > instances
*/
template < class IAFCE >
struct OInterfaceCompare
:public ::std::binary_function < ::com::sun::star::uno::Reference< IAFCE >
, ::com::sun::star::uno::Reference< IAFCE >
, bool
>
{
bool operator() (const ::com::sun::star::uno::Reference< IAFCE >& lhs, const ::com::sun::star::uno::Reference< IAFCE >& rhs) const
{
return lhs.get() < rhs.get();
// this does not make any sense if you see the semantics of the pointer returned by get:
// It's a pointer to a point in memory where an interface implementation lies.
// But for our purpose (provide a reliable less-operator which can be used with the STL), this is
// sufficient ....
}
};
template <class _Tp, class _Arg>
class mem_fun1_t : public ::std::binary_function<_Tp*,_Arg,void>
{
typedef void (_Tp::*_fun_type)(_Arg);
public:
explicit mem_fun1_t(_fun_type __pf) : _M_f(__pf) {}
void operator()(_Tp* __p, _Arg __x) const { (__p->*_M_f)(__x); }
private:
_fun_type _M_f;
};
template <class _Tp, class _Arg>
inline mem_fun1_t<_Tp,_Arg> mem_fun(void (_Tp::*__f)(_Arg))
{
return mem_fun1_t<_Tp,_Arg>(__f);
}
//.........................................................................
/** output iterator that appends OUStrings into an OUStringBuffer.
*/
class OUStringBufferAppender :
public ::std::iterator< ::std::output_iterator_tag, void, void, void, void>
{
public:
typedef OUStringBufferAppender Self;
typedef ::std::output_iterator_tag iterator_category;
typedef void value_type;
typedef void reference;
typedef void pointer;
typedef size_t difference_type;
OUStringBufferAppender(OUStringBuffer & i_rBuffer)
: m_rBuffer(i_rBuffer) { }
Self & operator=(OUString const & i_rStr)
{
m_rBuffer.append( i_rStr );
return *this;
}
Self & operator*() { return *this; } // so operator= works
Self & operator++() { return *this; }
Self & operator++(int) { return *this; }
private:
OUStringBuffer & m_rBuffer;
};
//.........................................................................
/** algorithm similar to std::copy, but inserts a separator between elements.
*/
template< typename ForwardIter, typename OutputIter, typename T >
OutputIter intersperse(
ForwardIter start, ForwardIter end, OutputIter out, T const & separator)
{
if (start != end) {
*out = *start;
++start;
++out;
}
while (start != end) {
*out = separator;
++out;
*out = *start;
++start;
++out;
}
return out;
}
//.........................................................................
}
//... namespace comphelper ................................................
#endif // INCLUDED_COMPHELPER_STL_TYPES_HXX
/* vim:set shiftwidth=4 softtabstop=4 expandtab: */
<|endoftext|>
|
<commit_before>// File: QtxDockWindow.cxx
// Author: Sergey TELKOV
#include "QtxDockWindow.h"
#include <qlayout.h>
#include <qpixmap.h>
#include <qdockarea.h>
#include <qmainwindow.h>
#include <qapplication.h>
/*!
Class: QtxDockWindow::Watcher [Internal]
Descr: Internal object with event filter.
*/
class QtxDockWindow::Watcher : public QObject
{
public:
Watcher( QtxDockWindow* );
void shown( QtxDockWindow* );
void hided( QtxDockWindow* );
virtual bool eventFilter( QObject*, QEvent* );
protected:
virtual void customEvent( QCustomEvent* );
private:
void installFilters();
void showContainer();
void hideContainer();
void updateIcon();
void updateCaption();
void updateVisibility();
private:
QtxDockWindow* myCont;
bool myState;
bool myEmpty;
bool myVisible;
};
QtxDockWindow::Watcher::Watcher( QtxDockWindow* cont )
: QObject( cont ), myCont( cont ),
myState( true ),
myEmpty( true )
{
if ( myCont->mainWindow() )
myState = myCont->mainWindow()->appropriate( myCont );
myCont->installEventFilter( this );
myVisible = myCont->isVisibleTo( myCont->parentWidget() );
installFilters();
}
bool QtxDockWindow::Watcher::eventFilter( QObject* o, QEvent* e )
{
if ( o == myCont &&
( e->type() == QEvent::Show || e->type() == QEvent::ShowToParent ||
e->type() == QEvent::Hide || e->type() == QEvent::HideToParent ||
e->type() == QEvent::ChildInserted ) )
QApplication::postEvent( this, new QCustomEvent( QEvent::User ) );
if ( o != myCont && e->type() == QEvent::IconChange )
updateIcon();
if ( o != myCont && e->type() == QEvent::CaptionChange )
updateCaption();
if ( o != myCont &&
( e->type() == QEvent::Show || e->type() == QEvent::ShowToParent ||
e->type() == QEvent::Hide || e->type() == QEvent::HideToParent ||
e->type() == QEvent::ChildRemoved ) )
updateVisibility();
return false;
}
void QtxDockWindow::Watcher::shown( QtxDockWindow* dw )
{
if ( dw != myCont )
return;
myVisible = true;
}
void QtxDockWindow::Watcher::hided( QtxDockWindow* dw )
{
if ( dw != myCont )
return;
myVisible = false;
}
void QtxDockWindow::Watcher::showContainer()
{
if ( !myCont )
return;
QtxDockWindow* cont = myCont;
myCont = 0;
cont->show();
myCont = cont;
}
void QtxDockWindow::Watcher::hideContainer()
{
if ( !myCont )
return;
QtxDockWindow* cont = myCont;
myCont = 0;
cont->hide();
myCont = cont;
}
void QtxDockWindow::Watcher::customEvent( QCustomEvent* e )
{
installFilters();
updateIcon();
updateCaption();
updateVisibility();
}
void QtxDockWindow::Watcher::installFilters()
{
if ( !myCont )
return;
QBoxLayout* bl = myCont->boxLayout();
if ( !bl )
return;
for ( QLayoutIterator it = bl->iterator(); it.current(); ++it )
{
if ( it.current()->widget() )
it.current()->widget()->installEventFilter( this );
}
}
void QtxDockWindow::Watcher::updateVisibility()
{
if ( !myCont )
return;
QBoxLayout* bl = myCont->boxLayout();
if ( !bl )
return;
bool vis = false;
for ( QLayoutIterator it = bl->iterator(); it.current() && !vis; ++it )
vis = it.current()->widget() && it.current()->widget()->isVisibleTo( myCont );
QMainWindow* mw = myCont->mainWindow();
if ( mw && myEmpty == vis )
{
myEmpty = !vis;
if ( !myEmpty )
mw->setAppropriate( myCont, myState );
else
{
myState = mw->appropriate( myCont );
mw->setAppropriate( myCont, false );
}
}
vis = !myEmpty && myVisible;
if ( vis != myCont->isVisibleTo( myCont->parentWidget() ) )
vis ? showContainer() : hideContainer();
}
void QtxDockWindow::Watcher::updateIcon()
{
if ( !myCont || !myCont->widget() )
return;
const QPixmap* ico = myCont->widget()->icon();
myCont->setIcon( ico ? *ico : QPixmap() );
}
void QtxDockWindow::Watcher::updateCaption()
{
if ( myCont && myCont->widget() && !myCont->widget()->caption().isNull() )
myCont->setCaption( myCont->widget()->caption() );
}
/*!
Class: QtxDockWindow [Public]
Descr:
*/
QtxDockWindow::QtxDockWindow( Place p, QWidget* parent, const char* name, WFlags f )
: QDockWindow( p, parent, name, f ),
myWatcher( 0 ),
myStretch( false )
{
}
QtxDockWindow::QtxDockWindow( const bool watch, QWidget* parent, const char* name, WFlags f )
: QDockWindow( InDock, parent, name, f ),
myWatcher( 0 ),
myStretch( false )
{
if ( watch )
myWatcher = new Watcher( this );
}
QtxDockWindow::QtxDockWindow( QWidget* parent, const char* name, WFlags f )
: QDockWindow( InDock, parent, name, f ),
myWatcher( 0 ),
myStretch( false )
{
}
QtxDockWindow::~QtxDockWindow()
{
}
void QtxDockWindow::setWidget( QWidget* wid )
{
if ( wid )
wid->reparent( this, QPoint( 0, 0 ), wid->isVisibleTo( wid->parentWidget() ) );
QDockWindow::setWidget( wid );
}
bool QtxDockWindow::isStretchable() const
{
return myStretch;
}
void QtxDockWindow::setStretchable( const bool on )
{
if ( myStretch == on )
return;
myStretch = on;
boxLayout()->setStretchFactor( widget(), myStretch ? 1 : 0 );
if ( myStretch != isHorizontalStretchable() ||
myStretch != isVerticalStretchable() )
{
if ( orientation() == Horizontal )
setHorizontalStretchable( myStretch );
else
setVerticalStretchable( myStretch );
}
}
QSize QtxDockWindow::sizeHint() const
{
QSize sz = QDockWindow::sizeHint();
if ( place() == InDock && isStretchable() && area() )
{
if ( orientation() == Horizontal )
sz.setWidth( area()->width() );
else
sz.setHeight( area()->height() );
}
return sz;
}
QSize QtxDockWindow::minimumSizeHint() const
{
QSize sz = QDockWindow::minimumSizeHint();
if ( orientation() == Horizontal )
sz = QSize( 0, QDockWindow::minimumSizeHint().height() );
else
sz = QSize( QDockWindow::minimumSizeHint().width(), 0 );
if ( place() == InDock && isStretchable() && area() )
{
if ( orientation() == Horizontal )
sz.setWidth( area()->width() );
else
sz.setHeight( area()->height() );
}
return sz;
}
QMainWindow* QtxDockWindow::mainWindow() const
{
QMainWindow* mw = 0;
QWidget* wid = parentWidget();
while ( !mw && wid )
{
if ( wid->inherits( "QMainWindow" ) )
mw = (QMainWindow*)wid;
wid = wid->parentWidget();
}
return mw;
}
void QtxDockWindow::show()
{
if ( myWatcher )
myWatcher->shown( this );
QDockWindow::show();
}
void QtxDockWindow::hide()
{
if ( myWatcher )
myWatcher->hided( this );
QDockWindow::hide();
}
<commit_msg>Don't allow to show the empty dock window.<commit_after>// File: QtxDockWindow.cxx
// Author: Sergey TELKOV
#include "QtxDockWindow.h"
#include <qlayout.h>
#include <qpixmap.h>
#include <qdockarea.h>
#include <qmainwindow.h>
#include <qapplication.h>
/*!
Class: QtxDockWindow::Watcher [Internal]
Descr: Internal object with event filter.
*/
class QtxDockWindow::Watcher : public QObject
{
public:
Watcher( QtxDockWindow* );
void shown( QtxDockWindow* );
void hided( QtxDockWindow* );
virtual bool eventFilter( QObject*, QEvent* );
protected:
virtual void customEvent( QCustomEvent* );
private:
void installFilters();
void showContainer();
void hideContainer();
void updateIcon();
void updateCaption();
void updateVisibility();
private:
QtxDockWindow* myCont;
bool myState;
bool myEmpty;
bool myVisible;
};
QtxDockWindow::Watcher::Watcher( QtxDockWindow* cont )
: QObject( cont ), myCont( cont ),
myState( true ),
myEmpty( true )
{
if ( myCont->mainWindow() )
myState = myCont->mainWindow()->appropriate( myCont );
myCont->installEventFilter( this );
myVisible = myCont->isVisibleTo( myCont->parentWidget() );
installFilters();
}
bool QtxDockWindow::Watcher::eventFilter( QObject* o, QEvent* e )
{
if ( o == myCont &&
( e->type() == QEvent::Show || e->type() == QEvent::ShowToParent ||
e->type() == QEvent::Hide || e->type() == QEvent::HideToParent ||
e->type() == QEvent::ChildInserted ) )
QApplication::postEvent( this, new QCustomEvent( QEvent::User ) );
if ( o != myCont && e->type() == QEvent::IconChange )
updateIcon();
if ( o != myCont && e->type() == QEvent::CaptionChange )
updateCaption();
if ( ( o != myCont && ( e->type() == QEvent::Hide || e->type() == QEvent::HideToParent ) ) ||
( o == myCont && ( e->type() == QEvent::ChildRemoved ) ) ||
( e->type() == QEvent::Show || e->type() == QEvent::ShowToParent ) )
updateVisibility();
return false;
}
void QtxDockWindow::Watcher::shown( QtxDockWindow* dw )
{
if ( dw != myCont )
return;
myVisible = true;
}
void QtxDockWindow::Watcher::hided( QtxDockWindow* dw )
{
if ( dw != myCont )
return;
myVisible = false;
}
void QtxDockWindow::Watcher::showContainer()
{
if ( !myCont )
return;
QtxDockWindow* cont = myCont;
myCont = 0;
cont->show();
myCont = cont;
}
void QtxDockWindow::Watcher::hideContainer()
{
if ( !myCont )
return;
QtxDockWindow* cont = myCont;
myCont = 0;
cont->hide();
myCont = cont;
}
void QtxDockWindow::Watcher::customEvent( QCustomEvent* e )
{
installFilters();
updateIcon();
updateCaption();
updateVisibility();
}
void QtxDockWindow::Watcher::installFilters()
{
if ( !myCont )
return;
QBoxLayout* bl = myCont->boxLayout();
if ( !bl )
return;
for ( QLayoutIterator it = bl->iterator(); it.current(); ++it )
{
if ( it.current()->widget() )
it.current()->widget()->installEventFilter( this );
}
}
void QtxDockWindow::Watcher::updateVisibility()
{
if ( !myCont )
return;
QBoxLayout* bl = myCont->boxLayout();
if ( !bl )
return;
bool vis = false;
for ( QLayoutIterator it = bl->iterator(); it.current() && !vis; ++it )
vis = it.current()->widget() && it.current()->widget()->isVisibleTo( myCont );
QMainWindow* mw = myCont->mainWindow();
if ( mw && myEmpty == vis )
{
myEmpty = !vis;
if ( !myEmpty )
mw->setAppropriate( myCont, myState );
else
{
myState = mw->appropriate( myCont );
mw->setAppropriate( myCont, false );
}
}
vis = !myEmpty && myVisible;
if ( vis != myCont->isVisibleTo( myCont->parentWidget() ) )
vis ? showContainer() : hideContainer();
}
void QtxDockWindow::Watcher::updateIcon()
{
if ( !myCont || !myCont->widget() )
return;
const QPixmap* ico = myCont->widget()->icon();
myCont->setIcon( ico ? *ico : QPixmap() );
}
void QtxDockWindow::Watcher::updateCaption()
{
if ( myCont && myCont->widget() && !myCont->widget()->caption().isNull() )
myCont->setCaption( myCont->widget()->caption() );
}
/*!
Class: QtxDockWindow [Public]
Descr:
*/
QtxDockWindow::QtxDockWindow( Place p, QWidget* parent, const char* name, WFlags f )
: QDockWindow( p, parent, name, f ),
myWatcher( 0 ),
myStretch( false )
{
}
QtxDockWindow::QtxDockWindow( const bool watch, QWidget* parent, const char* name, WFlags f )
: QDockWindow( InDock, parent, name, f ),
myWatcher( 0 ),
myStretch( false )
{
if ( watch )
myWatcher = new Watcher( this );
}
QtxDockWindow::QtxDockWindow( QWidget* parent, const char* name, WFlags f )
: QDockWindow( InDock, parent, name, f ),
myWatcher( 0 ),
myStretch( false )
{
}
QtxDockWindow::~QtxDockWindow()
{
}
void QtxDockWindow::setWidget( QWidget* wid )
{
if ( wid )
wid->reparent( this, QPoint( 0, 0 ), wid->isVisibleTo( wid->parentWidget() ) );
QDockWindow::setWidget( wid );
}
bool QtxDockWindow::isStretchable() const
{
return myStretch;
}
void QtxDockWindow::setStretchable( const bool on )
{
if ( myStretch == on )
return;
myStretch = on;
boxLayout()->setStretchFactor( widget(), myStretch ? 1 : 0 );
if ( myStretch != isHorizontalStretchable() ||
myStretch != isVerticalStretchable() )
{
if ( orientation() == Horizontal )
setHorizontalStretchable( myStretch );
else
setVerticalStretchable( myStretch );
}
}
QSize QtxDockWindow::sizeHint() const
{
QSize sz = QDockWindow::sizeHint();
if ( place() == InDock && isStretchable() && area() )
{
if ( orientation() == Horizontal )
sz.setWidth( area()->width() );
else
sz.setHeight( area()->height() );
}
return sz;
}
QSize QtxDockWindow::minimumSizeHint() const
{
QSize sz = QDockWindow::minimumSizeHint();
if ( orientation() == Horizontal )
sz = QSize( 0, QDockWindow::minimumSizeHint().height() );
else
sz = QSize( QDockWindow::minimumSizeHint().width(), 0 );
if ( place() == InDock && isStretchable() && area() )
{
if ( orientation() == Horizontal )
sz.setWidth( area()->width() );
else
sz.setHeight( area()->height() );
}
return sz;
}
QMainWindow* QtxDockWindow::mainWindow() const
{
QMainWindow* mw = 0;
QWidget* wid = parentWidget();
while ( !mw && wid )
{
if ( wid->inherits( "QMainWindow" ) )
mw = (QMainWindow*)wid;
wid = wid->parentWidget();
}
return mw;
}
void QtxDockWindow::show()
{
if ( myWatcher )
myWatcher->shown( this );
QDockWindow::show();
}
void QtxDockWindow::hide()
{
if ( myWatcher )
myWatcher->hided( this );
QDockWindow::hide();
}
<|endoftext|>
|
<commit_before>/*
* This file is part of QZeitgeist.
*
* Copyright (C) 2013 David Rosca <nowrep@gmail.com>
*
* This library is free software; you can redistribute it and/or
* modify it under the terms of the GNU Lesser General Public
* License as published by the Free Software Foundation; either
* version 2.1 of the License, or (at your option) any later version.
*
* This library is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
* Lesser General Public License for more details.
*
* You should have received a copy of the GNU Lesser General Public
* License along with this library; if not, write to the Free Software
* Foundation, Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301 USA
*/
extern "C" {
#include <zeitgeist.h>
}
#include "monitor.h"
#include "resultset.h"
#include "tools.h"
namespace QZeitgeist
{
class MonitorPrivate
{
public:
MonitorPrivate(const TimeRange &timeRange, const QList<Event> &eventTemplates, Monitor *q_);
~MonitorPrivate();
void emitEventsDeleted(const TimeRange &tr, const QList<quint32> &ids);
void emitEventsInserted(const TimeRange &tr, const ResultSet &res);
Monitor *q;
ZeitgeistMonitor *monitor;
};
// callbacks
static void on_events_deleted(ZeitgeistMonitor *, ZeitgeistTimeRange *time_range,
guint32 *event_ids, int events_length, MonitorPrivate *monitor)
{
TimeRange tr = Tools::timeRangeFromHandle(time_range);
QList<quint32> ids;
for (int i = 0; i < events_length; ++i) {
ids.append(event_ids[i]);
}
monitor->emitEventsDeleted(tr, ids);
}
static void on_events_inserted(ZeitgeistMonitor *, ZeitgeistTimeRange *time_range,
ZeitgeistResultSet *events, MonitorPrivate *monitor)
{
TimeRange tr = Tools::timeRangeFromHandle(time_range);
ResultSet resultSet = ResultSet::fromHandle(events);
monitor->emitEventsInserted(tr, resultSet);
}
MonitorPrivate::MonitorPrivate(const TimeRange &timeRange, const QList<Event> &eventTemplates, Monitor *q_)
: q(q_)
{
ZeitgeistTimeRange *tr = (ZeitgeistTimeRange *)Tools::timeRangeCreateHandle(timeRange);
GPtrArray *templates = Tools::eventsToPtrArray(eventTemplates);
monitor = zeitgeist_monitor_new(tr, templates);
g_signal_connect(monitor, "events-deleted", G_CALLBACK(on_events_deleted), this);
g_signal_connect(monitor, "events-inserted", G_CALLBACK(on_events_inserted), this);
g_object_unref(tr);
g_ptr_array_unref(templates);
Q_ASSERT(monitor);
}
MonitorPrivate::~MonitorPrivate()
{
g_object_unref(monitor);
}
void MonitorPrivate::emitEventsDeleted(const TimeRange &tr, const QList<quint32> &ids)
{
Q_EMIT q->eventsDeleted(tr, ids);
}
void MonitorPrivate::emitEventsInserted(const TimeRange &tr, const ResultSet &res)
{
Q_EMIT q->eventsInserted(tr, res);
}
// class Monitor
Monitor::Monitor(const TimeRange &timeRange, const QList<Event> &eventTemplates, QObject *parent)
: QObject(parent)
, d(new MonitorPrivate(timeRange, eventTemplates, this))
{
}
Monitor::~Monitor()
{
delete d;
}
QList<Event> Monitor::eventTemplates() const
{
GPtrArray *templates = zeitgeist_monitor_get_event_templates(d->monitor);
return Tools::eventsFromPtrArray(templates);
}
void Monitor::setEventTemplates(const QList<Event> &eventTemplates)
{
GPtrArray *templates = Tools::eventsToPtrArray(eventTemplates);
zeitgeist_monitor_set_event_templates(d->monitor, templates);
g_ptr_array_unref(templates);
}
TimeRange Monitor::timeRange() const
{
ZeitgeistTimeRange *tr = zeitgeist_monitor_get_time_range(d->monitor);
return Tools::timeRangeFromHandle(tr);
}
void Monitor::setTimeRange(const TimeRange &timeRange)
{
ZeitgeistTimeRange *tr = (ZeitgeistTimeRange *)Tools::timeRangeCreateHandle(timeRange);
zeitgeist_monitor_set_time_range(d->monitor, tr);
g_object_unref(tr);
}
HANDLE Monitor::getHandle() const
{
return d->monitor;
}
} // namespace QZeitgeist
<commit_msg>Monitor: Fix crash when installing monitor into log<commit_after>/*
* This file is part of QZeitgeist.
*
* Copyright (C) 2013 David Rosca <nowrep@gmail.com>
*
* This library is free software; you can redistribute it and/or
* modify it under the terms of the GNU Lesser General Public
* License as published by the Free Software Foundation; either
* version 2.1 of the License, or (at your option) any later version.
*
* This library is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
* Lesser General Public License for more details.
*
* You should have received a copy of the GNU Lesser General Public
* License along with this library; if not, write to the Free Software
* Foundation, Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301 USA
*/
extern "C" {
#include <zeitgeist.h>
}
#include "monitor.h"
#include "resultset.h"
#include "tools.h"
namespace QZeitgeist
{
class MonitorPrivate
{
public:
MonitorPrivate(const TimeRange &timeRange, const QList<Event> &eventTemplates, Monitor *q_);
~MonitorPrivate();
void emitEventsDeleted(const TimeRange &tr, const QList<quint32> &ids);
void emitEventsInserted(const TimeRange &tr, const ResultSet &res);
Monitor *q;
ZeitgeistMonitor *monitor;
};
// callbacks
static void on_events_deleted(ZeitgeistMonitor *, ZeitgeistTimeRange *time_range,
guint32 *event_ids, int events_length, MonitorPrivate *monitor)
{
TimeRange tr = Tools::timeRangeFromHandle(time_range);
QList<quint32> ids;
for (int i = 0; i < events_length; ++i) {
ids.append(event_ids[i]);
}
monitor->emitEventsDeleted(tr, ids);
}
static void on_events_inserted(ZeitgeistMonitor *, ZeitgeistTimeRange *time_range,
ZeitgeistResultSet *events, MonitorPrivate *monitor)
{
TimeRange tr = Tools::timeRangeFromHandle(time_range);
ResultSet resultSet = ResultSet::fromHandle(events);
monitor->emitEventsInserted(tr, resultSet);
}
MonitorPrivate::MonitorPrivate(const TimeRange &timeRange, const QList<Event> &eventTemplates, Monitor *q_)
: q(q_)
{
ZeitgeistTimeRange *tr = (ZeitgeistTimeRange *)Tools::timeRangeCreateHandle(timeRange);
GPtrArray *templates = Tools::eventsToPtrArray(eventTemplates);
monitor = zeitgeist_monitor_new(tr, templates);
g_signal_connect(monitor, "events-deleted", G_CALLBACK(on_events_deleted), this);
g_signal_connect(monitor, "events-inserted", G_CALLBACK(on_events_inserted), this);
g_object_unref(tr);
Q_ASSERT(monitor);
}
MonitorPrivate::~MonitorPrivate()
{
g_object_unref(monitor);
}
void MonitorPrivate::emitEventsDeleted(const TimeRange &tr, const QList<quint32> &ids)
{
Q_EMIT q->eventsDeleted(tr, ids);
}
void MonitorPrivate::emitEventsInserted(const TimeRange &tr, const ResultSet &res)
{
Q_EMIT q->eventsInserted(tr, res);
}
// class Monitor
Monitor::Monitor(const TimeRange &timeRange, const QList<Event> &eventTemplates, QObject *parent)
: QObject(parent)
, d(new MonitorPrivate(timeRange, eventTemplates, this))
{
}
Monitor::~Monitor()
{
delete d;
}
QList<Event> Monitor::eventTemplates() const
{
GPtrArray *templates = zeitgeist_monitor_get_event_templates(d->monitor);
return Tools::eventsFromPtrArray(templates);
}
void Monitor::setEventTemplates(const QList<Event> &eventTemplates)
{
GPtrArray *templates = Tools::eventsToPtrArray(eventTemplates);
zeitgeist_monitor_set_event_templates(d->monitor, templates);
g_ptr_array_unref(templates);
}
TimeRange Monitor::timeRange() const
{
ZeitgeistTimeRange *tr = zeitgeist_monitor_get_time_range(d->monitor);
return Tools::timeRangeFromHandle(tr);
}
void Monitor::setTimeRange(const TimeRange &timeRange)
{
ZeitgeistTimeRange *tr = (ZeitgeistTimeRange *)Tools::timeRangeCreateHandle(timeRange);
zeitgeist_monitor_set_time_range(d->monitor, tr);
g_object_unref(tr);
}
HANDLE Monitor::getHandle() const
{
return d->monitor;
}
} // namespace QZeitgeist
<|endoftext|>
|
<commit_before>/*
* Copyright 2008 28msec, Inc.
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
#include <iostream>
#include <fstream>
#include <stdlib.h>
#include <libaws/aws.h>
using namespace aws;
bool createDomain (SDBConnectionPtr aSDB, const std::string &aDomainName) {
try {
CreateDomainResponsePtr lRes = aSDB->createDomain (aDomainName);
std::cout << "domain created successfully" << std::endl;
} catch (CreateDomainException &e) {
std::cerr << e.what() << std::endl;
return false;
}
return true;
}
bool deleteDomain (SDBConnectionPtr aSDB, const std::string &aDomainName) {
try {
DeleteDomainResponsePtr lRes = aSDB->deleteDomain (aDomainName);
std::cout << "delete domain successfully" << std::endl;
} catch (DeleteDomainException &e) {
std::cerr << e.what() << std::endl;
return false;
}
return true;
}
bool deleteAllDomains (SDBConnectionPtr aSDB, std::string aPrefix) {
try {
ListDomainsResponsePtr lRes = aSDB->listDomains();
std::cout << "start deleting" << std::endl;
lRes->open();
std::string lDomain;
while (lRes->next (lDomain)) {
if(aPrefix.length() == 0 || lDomain.compare(0, aPrefix.length(),aPrefix) == 0){
std::cout << " " << lDomain << std::endl;
aSDB->deleteDomain (lDomain);
}
}
lRes->close();
} catch (PutAttributesException &e) {
std::cerr << e.what() << std::endl;
return false;
}
return true;
}
bool listDomains (SDBConnectionPtr aSDB, int aMaxNumberOfDomains, const std::string& aNextToken) {
try {
ListDomainsResponsePtr lRes = aSDB->listDomains(aMaxNumberOfDomains, aNextToken);
std::cout << "list domains successfully" << std::endl;
lRes->open();
std::string lDomain;
while (lRes->next (lDomain)) {
std::cout << " Domain: " << lDomain << std::endl;
}
lRes->close();
} catch (ListDomainsException &e) {
std::cerr << e.what() << std::endl;
return false;
}
return true;
}
bool putAttribute (SDBConnectionPtr aSDB, const std::string& aDomainName, const std::string& aItemName,
const std::string& aKey, const std::string& aValue, bool aReplace) {
try {
std::vector<aws::Attribute> lAttrs;
aws::Attribute lAttr (aKey, aValue, aReplace);
lAttrs.push_back (lAttr);
PutAttributesResponsePtr lRes = aSDB->putAttributes (aDomainName, aItemName, lAttrs);
std::cout << "put attribute successfully" << std::endl;
} catch (PutAttributesException &e) {
std::cerr << e.what() << std::endl;
return false;
}
return true;
}
bool deleteAttribute (SDBConnectionPtr aSDB, const std::string& aDomainName, const std::string& aItemName,
const std::string& aKey, std::string aValue) {
try {
std::vector<aws::Attribute> lAttrs;
aws::Attribute lAttr (aKey, aValue, false);
lAttrs.push_back (lAttr);
DeleteAttributesResponsePtr lRes = aSDB->deleteAttributes (aDomainName, aItemName, lAttrs);
std::cout << "delete attribute successfully" << std::endl;
} catch (PutAttributesException &e) {
std::cerr << e.what() << std::endl;
return false;
}
return true;
}
bool getAttribute (SDBConnectionPtr aSDB, const std::string& aDomainName, const std::string& aItemName,
const std::string attributeName = "") {
try {
GetAttributesResponsePtr lRes = aSDB->getAttributes (aDomainName, aItemName, attributeName);
std::cout << "get attribute successfully" << std::endl;
lRes->open();
std::pair<std::string, std::string> lAttr;
while (lRes->next (lAttr)) {
std::cout << " Attr-Name: " << lAttr.first << "-> " << lAttr.second << std::endl;
}
lRes->close();
} catch (PutAttributesException &e) {
std::cerr << e.what() << std::endl;
return false;
}
return true;
}
bool listAll(SDBConnectionPtr aSDB){
try {
ListDomainsResponsePtr lRes = aSDB->listDomains();
std::cout << "list domains successfully" << std::endl;
lRes->open();
std::string lDomain;
while (lRes->next (lDomain)) {
std::cout << " Domain: " << lDomain << std::endl;
SDBQueryResponsePtr lRes = aSDB->query (lDomain, "");
int lCounter = 0;
lRes->open();
std::string lItem;
while (lRes->next (lItem)) {
std::cout << " " << ++lCounter << ". Item: " << lItem;
GetAttributesResponsePtr lRes = aSDB->getAttributes (lDomain, lItem);
lRes->open();
std::pair<std::string, std::string> lAttr;
while (lRes->next (lAttr)) {
std::cout << " " << lAttr.first << ":" << lAttr.second ;
}
lRes->close();
std::cout << std::endl;
}
lRes->close();
}
lRes->close();
} catch (ListDomainsException &e) {
std::cerr << e.what() << std::endl;
return false;
}
return true;
}
bool query (SDBConnectionPtr aSDB, const std::string& aDomainName, const std::string& aQueryExpression, int aMaxNumberOfItems = 0,
const std::string & aNextToken = "") {
try {
SDBQueryResponsePtr lRes = aSDB->query (aDomainName, aQueryExpression, aMaxNumberOfItems, aNextToken);
std::cout << "query successfully" << std::endl;
lRes->open();
std::string lItem;
while (lRes->next (lItem)) {
std::cout << " Item: " << lItem << std::endl;
}
lRes->close();
} catch (PutAttributesException &e) {
std::cerr << e.what() << std::endl;
return false;
}
return true;
}
int
main (int argc, char** argv) {
char* lAccessKeyId = 0;
char* lSecretAccessKey = 0;
char* lAction = 0;
char* lDomain = 0;
int lMaxItems = 0;
std::string lNextToken = "";
char lEmpty[] = { '\0' };
char* lNextTokenTmp = lEmpty;
char* lAttrName = 0;
char* lAttrValue = 0;
char* lItem = 0;
char* lQuery = 0;
bool lReplace = false;
int c;
opterr = 0;
AWSConnectionFactory* lFactory = AWSConnectionFactory::getInstance();
while ( (c = getopt (argc, argv, "hi:s:a:d:x:c:t:k:v:q:r")) != -1)
switch (c) {
case 'i':
lAccessKeyId = optarg;
break;
case 's':
lSecretAccessKey = optarg;
break;
case 'a':
lAction = optarg;
break;
case 'd':
lDomain = optarg;
break;
case 'x':
lMaxItems = atoi (optarg);
break;
case 'c':
lItem = optarg;
break;
case 't':
lNextToken = optarg;
break;
case 'k':
lAttrName = optarg;
break;
case 'v':
lAttrValue = optarg;
break;
case 'q':
lQuery = optarg;
break;
case 'r':
lReplace = true;
break;
case 'h': {
std::cout << "libaws version " << lFactory->getVersion() << std::endl;
std::cout << "Usage: sqs <options>" << std::endl;
std::cout << " -i: AWS Access Key Id" << std::endl;
std::cout << " -s: AWS Secret Access Key" << std::endl;
std::cout << " -a action: Action to perform" << std::endl;
std::cout << " create-domain" << std::endl;
std::cout << " delete-domain" << std::endl;
std::cout << " delete-all-domains" << std::endl;
std::cout << " list-domains" << std::endl;
std::cout << " put-attribute" << std::endl;
std::cout << " delete-attribute" << std::endl;
std::cout << " get-attribute" << std::endl;
std::cout << " query" << std::endl;
std::cout << " list-all" << std::endl;
std::cout << " -d domain: A Domain Name" << std::endl;
std::cout << " -c item/content: The item" << std::endl;
std::cout << " -x #items: Max number of items/domains" << std::endl;
std::cout << " -t next token: The next token" << std::endl;
std::cout << " -k key/attributes: An attribute" << std::endl;
std::cout << " -v value: An attribute value" << std::endl;
std::cout << " -q query: Replace Attribue" << std::endl;
std::cout << " -r replace: Replace Attribue" << std::endl;
std::cout << " -h help: display help" << std::endl;
exit (1);
}
case '?':
if (isprint (optopt))
fprintf (stderr, "Unknown option `-%c'.\n", optopt);
else
fprintf (stderr,
"Unknown option character `\\x%x'.\n",
optopt);
exit (1);
default:
exit (1);
}
if (!lAccessKeyId) {
lAccessKeyId = getenv ("AWS_ACCESS_KEY");
}
if (!lSecretAccessKey) {
lSecretAccessKey = getenv ("AWS_SECRET_ACCESS_KEY");
}
if (!lAccessKeyId) {
std::cerr << "No Access Key given" << std::endl;
std::cerr << "Either use -i as a command line argument or set AWS_ACCESS_KEY as an environmental variable" << std::endl;
exit (1);
}
if (!lSecretAccessKey) {
std::cerr << "No Secret Access Key given" << std::endl;
std::cerr << "Either use -s as a command line argument or set AWS_SECRET_ACCESS_KEY as an environmental variable" << std::endl;
exit (1);
}
SDBConnectionPtr lSDBRest;
lSDBRest = lFactory->createSDBConnection (lAccessKeyId, lSecretAccessKey);
if (!lAction) {
std::cerr << "No Action parameter specified." << std::endl;
std::cerr << "Use -a as a command line argument" << std::endl;
exit (1);
}
std::string lActionString (lAction);
if (lActionString.compare ("list-domains") == 0) {
listDomains (lSDBRest, lMaxItems, lNextTokenTmp);
exit (0);
}
if (lActionString.compare ("delete-all-domains") == 0) {
deleteAllDomains (lSDBRest, lQuery==0?"":lQuery);
exit (0);
}
if (lActionString.compare ("list-all") == 0) {
listAll (lSDBRest);
exit (0);
}
if (!lDomain) {
std::cerr << "No domain provided." << std::endl;
exit (1);
}
if (lActionString.compare ("create-domain") == 0) {
createDomain (lSDBRest, lDomain);
exit (0);
}
if (lActionString.compare ("delete-domain") == 0) {
deleteDomain (lSDBRest, lDomain);
exit (0);
}
if (lActionString.compare ("query") == 0) {
query (lSDBRest, lDomain, lQuery, lMaxItems, lNextTokenTmp);
exit(0);
}
if (!lItem) {
std::cerr << "No item provided." << std::endl;
exit (1);
}
if (lActionString.compare ("get-attribute") == 0) {
if (lAttrName) {
getAttribute (lSDBRest, lDomain, lItem, lAttrName);
} else {
getAttribute (lSDBRest, lDomain, lItem);
}
}
if (!lAttrName) {
std::cerr << "No attribute name provided." << std::endl;
exit (1);
}
if (!lAttrValue) {
std::cerr << "No attribute value provided." << std::endl;
exit (1);
}
if (lActionString.compare ("put-attribute") == 0) {
putAttribute (lSDBRest, lDomain, lItem, lAttrName, lAttrValue, lReplace);
} else if (lActionString.compare ("delete-attribute") == 0) {
deleteAttribute (lSDBRest, lDomain, lItem, lAttrName, lAttrValue);
} else {
std::cerr << "Command not recognized." << std::endl;
exit (1);
}
}
<commit_msg>copy & waste fixes<commit_after>/*
* Copyright 2008 28msec, Inc.
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
#include <iostream>
#include <fstream>
#include <stdlib.h>
#include <libaws/aws.h>
using namespace aws;
bool createDomain (SDBConnectionPtr aSDB, const std::string &aDomainName) {
try {
CreateDomainResponsePtr lRes = aSDB->createDomain (aDomainName);
std::cout << "domain created successfully" << std::endl;
} catch (CreateDomainException &e) {
std::cerr << e.what() << std::endl;
return false;
}
return true;
}
bool deleteDomain (SDBConnectionPtr aSDB, const std::string &aDomainName) {
try {
DeleteDomainResponsePtr lRes = aSDB->deleteDomain (aDomainName);
std::cout << "delete domain successfully" << std::endl;
} catch (DeleteDomainException &e) {
std::cerr << e.what() << std::endl;
return false;
}
return true;
}
bool deleteAllDomains (SDBConnectionPtr aSDB, std::string aPrefix) {
try {
ListDomainsResponsePtr lRes = aSDB->listDomains();
std::cout << "start deleting" << std::endl;
lRes->open();
std::string lDomain;
while (lRes->next (lDomain)) {
if(aPrefix.length() == 0 || lDomain.compare(0, aPrefix.length(),aPrefix) == 0){
std::cout << " " << lDomain << std::endl;
aSDB->deleteDomain (lDomain);
}
}
lRes->close();
} catch (PutAttributesException &e) {
std::cerr << e.what() << std::endl;
return false;
}
return true;
}
bool listDomains (SDBConnectionPtr aSDB, int aMaxNumberOfDomains, const std::string& aNextToken) {
try {
ListDomainsResponsePtr lRes = aSDB->listDomains(aMaxNumberOfDomains, aNextToken);
std::cout << "list domains successfully" << std::endl;
lRes->open();
std::string lDomain;
while (lRes->next (lDomain)) {
std::cout << " Domain: " << lDomain << std::endl;
}
lRes->close();
} catch (ListDomainsException &e) {
std::cerr << e.what() << std::endl;
return false;
}
return true;
}
bool putAttribute (SDBConnectionPtr aSDB, const std::string& aDomainName, const std::string& aItemName,
const std::string& aKey, const std::string& aValue, bool aReplace) {
try {
std::vector<aws::Attribute> lAttrs;
aws::Attribute lAttr (aKey, aValue, aReplace);
lAttrs.push_back (lAttr);
PutAttributesResponsePtr lRes = aSDB->putAttributes (aDomainName, aItemName, lAttrs);
std::cout << "put attribute successfully" << std::endl;
} catch (PutAttributesException &e) {
std::cerr << e.what() << std::endl;
return false;
}
return true;
}
bool deleteAttribute (SDBConnectionPtr aSDB, const std::string& aDomainName, const std::string& aItemName,
const std::string& aKey, std::string aValue) {
try {
std::vector<aws::Attribute> lAttrs;
aws::Attribute lAttr (aKey, aValue, false);
lAttrs.push_back (lAttr);
DeleteAttributesResponsePtr lRes = aSDB->deleteAttributes (aDomainName, aItemName, lAttrs);
std::cout << "delete attribute successfully" << std::endl;
} catch (PutAttributesException &e) {
std::cerr << e.what() << std::endl;
return false;
}
return true;
}
bool getAttribute (SDBConnectionPtr aSDB, const std::string& aDomainName, const std::string& aItemName,
const std::string attributeName = "") {
try {
GetAttributesResponsePtr lRes = aSDB->getAttributes (aDomainName, aItemName, attributeName);
std::cout << "get attribute successfully" << std::endl;
lRes->open();
std::pair<std::string, std::string> lAttr;
while (lRes->next (lAttr)) {
std::cout << " Attr-Name: " << lAttr.first << "-> " << lAttr.second << std::endl;
}
lRes->close();
} catch (PutAttributesException &e) {
std::cerr << e.what() << std::endl;
return false;
}
return true;
}
bool listAll(SDBConnectionPtr aSDB){
try {
ListDomainsResponsePtr lRes = aSDB->listDomains();
std::cout << "list domains successfully" << std::endl;
lRes->open();
std::string lDomain;
while (lRes->next (lDomain)) {
std::cout << " Domain: " << lDomain << std::endl;
SDBQueryResponsePtr lRes = aSDB->query (lDomain, "");
int lCounter = 0;
lRes->open();
std::string lItem;
while (lRes->next (lItem)) {
std::cout << " " << ++lCounter << ". Item: " << lItem;
GetAttributesResponsePtr lRes = aSDB->getAttributes (lDomain, lItem);
lRes->open();
std::pair<std::string, std::string> lAttr;
while (lRes->next (lAttr)) {
std::cout << " " << lAttr.first << ":" << lAttr.second ;
}
lRes->close();
std::cout << std::endl;
}
lRes->close();
}
lRes->close();
} catch (ListDomainsException &e) {
std::cerr << e.what() << std::endl;
return false;
}
return true;
}
bool query (SDBConnectionPtr aSDB, const std::string& aDomainName, const std::string& aQueryExpression, int aMaxNumberOfItems = 0,
const std::string & aNextToken = "") {
try {
SDBQueryResponsePtr lRes = aSDB->query (aDomainName, aQueryExpression, aMaxNumberOfItems, aNextToken);
std::cout << "query successfully" << std::endl;
lRes->open();
std::string lItem;
while (lRes->next (lItem)) {
std::cout << " Item: " << lItem << std::endl;
}
lRes->close();
} catch (PutAttributesException &e) {
std::cerr << e.what() << std::endl;
return false;
}
return true;
}
int
main (int argc, char** argv) {
char* lAccessKeyId = 0;
char* lSecretAccessKey = 0;
char* lAction = 0;
char* lDomain = 0;
int lMaxItems = 0;
std::string lNextToken = "";
char lEmpty[] = { '\0' };
char* lNextTokenTmp = lEmpty;
char* lAttrName = 0;
char* lAttrValue = 0;
char* lItem = 0;
char* lQuery = 0;
bool lReplace = false;
int c;
opterr = 0;
AWSConnectionFactory* lFactory = AWSConnectionFactory::getInstance();
while ( (c = getopt (argc, argv, "hi:s:a:d:x:c:t:k:v:q:r")) != -1)
switch (c) {
case 'i':
lAccessKeyId = optarg;
break;
case 's':
lSecretAccessKey = optarg;
break;
case 'a':
lAction = optarg;
break;
case 'd':
lDomain = optarg;
break;
case 'x':
lMaxItems = atoi (optarg);
break;
case 'c':
lItem = optarg;
break;
case 't':
lNextToken = optarg;
break;
case 'k':
lAttrName = optarg;
break;
case 'v':
lAttrValue = optarg;
break;
case 'q':
lQuery = optarg;
break;
case 'r':
lReplace = true;
break;
case 'h': {
std::cout << "libaws version " << lFactory->getVersion() << std::endl;
std::cout << "Usage: sdb <options>" << std::endl;
std::cout << " -i: AWS Access Key Id" << std::endl;
std::cout << " -s: AWS Secret Access Key" << std::endl;
std::cout << " -a action: Action to perform" << std::endl;
std::cout << " create-domain" << std::endl;
std::cout << " delete-domain" << std::endl;
std::cout << " delete-all-domains" << std::endl;
std::cout << " list-domains" << std::endl;
std::cout << " put-attribute" << std::endl;
std::cout << " delete-attribute" << std::endl;
std::cout << " get-attribute" << std::endl;
std::cout << " query" << std::endl;
std::cout << " list-all" << std::endl;
std::cout << " -d domain: A Domain Name" << std::endl;
std::cout << " -c item/content: The item" << std::endl;
std::cout << " -x #items: Max number of items/domains" << std::endl;
std::cout << " -t next token: The next token" << std::endl;
std::cout << " -k key/attributes: An attribute" << std::endl;
std::cout << " -v value: An attribute value" << std::endl;
std::cout << " -q query: Replace Attribue" << std::endl;
std::cout << " -r replace: Replace Attribue" << std::endl;
std::cout << " -h help: display help" << std::endl;
exit (1);
}
case '?':
if (isprint (optopt))
fprintf (stderr, "Unknown option `-%c'.\n", optopt);
else
fprintf (stderr,
"Unknown option character `\\x%x'.\n",
optopt);
exit (1);
default:
exit (1);
}
if (!lAccessKeyId) {
lAccessKeyId = getenv ("AWS_ACCESS_KEY");
}
if (!lSecretAccessKey) {
lSecretAccessKey = getenv ("AWS_SECRET_ACCESS_KEY");
}
if (!lAccessKeyId) {
std::cerr << "No Access Key given" << std::endl;
std::cerr << "Either use -i as a command line argument or set AWS_ACCESS_KEY as an environmental variable" << std::endl;
exit (1);
}
if (!lSecretAccessKey) {
std::cerr << "No Secret Access Key given" << std::endl;
std::cerr << "Either use -s as a command line argument or set AWS_SECRET_ACCESS_KEY as an environmental variable" << std::endl;
exit (1);
}
SDBConnectionPtr lSDBRest;
lSDBRest = lFactory->createSDBConnection (lAccessKeyId, lSecretAccessKey);
if (!lAction) {
std::cerr << "No Action parameter specified." << std::endl;
std::cerr << "Use -a as a command line argument" << std::endl;
exit (1);
}
std::string lActionString (lAction);
if (lActionString.compare ("list-domains") == 0) {
listDomains (lSDBRest, lMaxItems, lNextTokenTmp);
exit (0);
}
if (lActionString.compare ("delete-all-domains") == 0) {
deleteAllDomains (lSDBRest, lQuery==0?"":lQuery);
exit (0);
}
if (lActionString.compare ("list-all") == 0) {
listAll (lSDBRest);
exit (0);
}
if (!lDomain) {
std::cerr << "No domain provided." << std::endl;
exit (1);
}
if (lActionString.compare ("create-domain") == 0) {
createDomain (lSDBRest, lDomain);
exit (0);
}
if (lActionString.compare ("delete-domain") == 0) {
deleteDomain (lSDBRest, lDomain);
exit (0);
}
if (lActionString.compare ("query") == 0) {
query (lSDBRest, lDomain, lQuery, lMaxItems, lNextTokenTmp);
exit(0);
}
if (!lItem) {
std::cerr << "No item provided." << std::endl;
exit (1);
}
if (lActionString.compare ("get-attribute") == 0) {
if (lAttrName) {
getAttribute (lSDBRest, lDomain, lItem, lAttrName);
} else {
getAttribute (lSDBRest, lDomain, lItem);
}
}
if (!lAttrName) {
std::cerr << "No attribute name provided." << std::endl;
exit (1);
}
if (!lAttrValue) {
std::cerr << "No attribute value provided." << std::endl;
exit (1);
}
if (lActionString.compare ("put-attribute") == 0) {
putAttribute (lSDBRest, lDomain, lItem, lAttrName, lAttrValue, lReplace);
} else if (lActionString.compare ("delete-attribute") == 0) {
deleteAttribute (lSDBRest, lDomain, lItem, lAttrName, lAttrValue);
} else {
std::cerr << "Command not recognized." << std::endl;
exit (1);
}
}
<|endoftext|>
|
<commit_before>#pragma once
#include <random>
#include <distributions/common.hpp>
#include <distributions/special.hpp>
namespace distributions
{
//typedef std::default_random_engine rng_t;
//typedef std::mt19937 rng_t;
typedef std::ranlux48 rng_t;
inline int sample_int (int low, int high, rng_t & rng)
{
std::uniform_int_distribution<> sampler(low, high);
return sampler(rng);
}
inline float sample_unif01 (rng_t & rng)
{
std::uniform_real_distribution<float> sampler(0.0, 1.0);
return sampler(rng);
}
// HACK std::gamma_distribution<float> appears to be broken
//typedef std::gamma_distribution<float> gamma_distribution_t;
typedef std::gamma_distribution<double> gamma_distribution_t;
inline float sample_gamma (
float alpha,
float beta,
rng_t & rng)
{
gamma_distribution_t sampler;
gamma_distribution_t::param_type param(alpha, beta);
return sampler(rng, param);
}
void sample_dirichlet (
size_t dim,
const float * alphas,
float * ps,
rng_t & rng);
int sample_discrete (
size_t dim,
const float * ps,
rng_t & rng);
inline float fast_score_student_t (
float x,
float v,
float mean,
float lambda)
{
float p = 0.f;
p += fast_lgamma_nu(v);
p += 0.5f * fast_log(lambda / (M_PIf * v));
p += (-0.5f * v - 0.5f) * fast_log(1.f + (lambda * sqr(x - mean)) / v);
return p;
}
inline float score_student_t (
float x,
float v,
float mean,
float lambda)
{
float p = 0.f;
p += lgammaf(v * 0.5f + 0.5f) - lgammaf(v * 0.5f);
p += 0.5f * logf(lambda / (M_PIf * v));
p += (-0.5f * v - 0.5f) * logf(1.f + (lambda * sqr(x - mean)) / v);
return p;
}
} // namespace distributions
<commit_msg>Add sample_from_urn and sample_pair_from_urn<commit_after>#pragma once
#include <utility>
#include <random>
#include <distributions/common.hpp>
#include <distributions/special.hpp>
namespace distributions
{
//typedef std::default_random_engine rng_t;
//typedef std::mt19937 rng_t;
typedef std::ranlux48 rng_t;
inline int sample_int (int low, int high, rng_t & rng)
{
std::uniform_int_distribution<> sampler(low, high);
return sampler(rng);
}
inline float sample_unif01 (rng_t & rng)
{
std::uniform_real_distribution<float> sampler(0.0, 1.0);
return sampler(rng);
}
// HACK std::gamma_distribution<float> appears to be broken
//typedef std::gamma_distribution<float> gamma_distribution_t;
typedef std::gamma_distribution<double> gamma_distribution_t;
inline float sample_gamma (
float alpha,
float beta,
rng_t & rng)
{
gamma_distribution_t sampler;
gamma_distribution_t::param_type param(alpha, beta);
return sampler(rng, param);
}
void sample_dirichlet (
size_t dim,
const float * alphas,
float * ps,
rng_t & rng);
int sample_discrete (
size_t dim,
const float * ps,
rng_t & rng);
inline float fast_score_student_t (
float x,
float v,
float mean,
float lambda)
{
float p = 0.f;
p += fast_lgamma_nu(v);
p += 0.5f * fast_log(lambda / (M_PIf * v));
p += (-0.5f * v - 0.5f) * fast_log(1.f + (lambda * sqr(x - mean)) / v);
return p;
}
inline float score_student_t (
float x,
float v,
float mean,
float lambda)
{
float p = 0.f;
p += lgammaf(v * 0.5f + 0.5f) - lgammaf(v * 0.5f);
p += 0.5f * logf(lambda / (M_PIf * v));
p += (-0.5f * v - 0.5f) * logf(1.f + (lambda * sqr(x - mean)) / v);
return p;
}
template<class T>
inline T sample_from_urn (
const std::vector<T> & urn,
rng_t & rng)
{
DIST_ASSERT(urn.size() >= 1, "urn is too small to sample from");
size_t f = sample_int(0, urn.size() - 1, rng);
DIST_ASSERT(0 <= f and f < urn.size(), "bad value: " << f);
return urn[f];
}
template<class T>
inline std::pair<T, T> sample_pair_from_urn (
const std::vector<T> & urn,
rng_t & rng)
{
DIST_ASSERT(urn.size() >= 2, "urn is too small to sample pair from");
size_t f1 = sample_int(0, urn.size() - 1, rng);
size_t f2 = sample_int(0, urn.size() - 2, rng);
if (f2 >= f1) {
f2 += 1;
}
DIST_ASSERT(0 <= f1 and f1 < urn.size(), "bad value: " << f1);
DIST_ASSERT(0 <= f2 and f2 < urn.size(), "bad value: " << f2);
DIST_ASSERT(f1 != f2, "bad pair: " << f1 << ", " << f2);
return std::make_pair(urn[f1], urn[f2]);
}
} // namespace distributions
<|endoftext|>
|
<commit_before>#ifndef UTILS_FACTORY_HPP
#define UTILS_FACTORY_HPP
#include <cassert>
#include <map>
template <class Base, class ID, class... Args>
class Factory
{
public:
typedef Base*(*CreatorFunction)(Args...);
public:
template <class Derive>
static Base* defaultCreator(Args... args)
{
return new Derive(args...);
}
public:
// TODO: consider using rvalue references and std::forward
Base* create(const ID& id, Args&... args) const
{
assert(_makers.find(id) != _makers.end());
return _makers.find(id)->second(args...);
}
void add(const ID& id, CreatorFunction callback)
{
_makers[id] = callback;
}
template <class Derive>
void add(const ID& id)
{
add(id, defaultCreator<Derive>);
}
void del(const ID& id)
{
_makers.erase(id);
}
void clear()
{
_makers.clear();
}
size_t size() const
{
return _makers.size();
}
private:
std::map<ID, CreatorFunction> _makers;
};
#endif
<commit_msg>Add haskey function<commit_after>#ifndef UTILS_FACTORY_HPP
#define UTILS_FACTORY_HPP
#include <cassert>
#include <map>
template <class Base, class ID, class... Args>
class Factory
{
public:
typedef Base*(*CreatorFunction)(Args...);
public:
template <class Derive>
static Base* defaultCreator(Args... args)
{
return new Derive(args...);
}
public:
// TODO: consider using rvalue references and std::forward
Base* create(const ID& id, Args&... args) const
{
assert(_makers.find(id) != _makers.end());
return _makers.find(id)->second(args...);
}
void add(const ID& id, CreatorFunction callback)
{
_makers[id] = callback;
}
template <class Derive>
void add(const ID& id)
{
add(id, defaultCreator<Derive>);
}
void del(const ID& id)
{
_makers.erase(id);
}
bool haskey(const ID& id) const
{
return _makers.find(id) != _makers.end();
}
void clear()
{
_makers.clear();
}
size_t size() const
{
return _makers.size();
}
private:
std::map<ID, CreatorFunction> _makers;
};
#endif
<|endoftext|>
|
<commit_before>/*****************************************************************************
*
* This file is part of Mapnik (c++ mapping toolkit)
*
* Copyright (C) 2014 Artem Pavlenko
*
* This library is free software; you can redistribute it and/or
* modify it under the terms of the GNU Lesser General Public
* License as published by the Free Software Foundation; either
* version 2.1 of the License, or (at your option) any later version.
*
* This library is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
* Lesser General Public License for more details.
*
* You should have received a copy of the GNU Lesser General Public
* License along with this library; if not, write to the Free Software
* Foundation, Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301 USA
*
*****************************************************************************/
#ifndef MAPNIK_IMAGE_DATA_HPP
#define MAPNIK_IMAGE_DATA_HPP
// mapnik
#include <mapnik/global.hpp>
// stl
#include <algorithm>
#include <cassert>
#include <stdexcept>
namespace mapnik {
namespace detail {
struct buffer
{
explicit buffer(std::size_t size)
: size_(size),
data_(static_cast<unsigned char*>(size_ != 0 ? ::operator new(size_) : nullptr))
{}
buffer(buffer && rhs) noexcept = default;
buffer(buffer const& rhs)
: size_(rhs.size_),
data_(rhs.data_)
{
if (data_) std::copy(rhs.data_, rhs.data_ + rhs.size_, data_);
}
inline bool operator!() const { return (data_ == nullptr)? false : true; }
~buffer()
{
::operator delete(data_);
}
inline unsigned char* data() { return data_; }
inline unsigned char const* data() const { return data_; }
inline std::size_t size() const { return size_; }
std::size_t size_;
unsigned char* data_;
};
}
template <typename T>
class image_data
{
public:
using pixel_type = T;
static constexpr std::size_t pixel_size = sizeof(pixel_type);
image_data(std::size_t width, std::size_t height, bool initialize = true)
: width_(width),
height_(height),
buffer_(width_ * height_ * pixel_size),
pData_(reinterpret_cast<pixel_type*>(buffer_.data()))
{
if (pData_ && initialize) std::fill(pData_, pData_ + width_ * height_, 0);
}
image_data(image_data<pixel_type> const& rhs)
: width_(rhs.width_),
height_(rhs.height_),
buffer_(rhs.buffer_),
pData_(reinterpret_cast<pixel_type*>(buffer_.data()))
{}
image_data(image_data<pixel_type> && rhs) noexcept
: width_(rhs.width_),
height_(rhs.height_),
buffer_(std::move(rhs.buffer_)),
pData_(reinterpret_cast<pixel_type*>(buffer_.data()))
{
rhs.width_ = 0;
rhs.height_ = 0;
rhs.pData_ = nullptr;
}
image_data<pixel_type>& operator=(image_data<pixel_type> rhs)
{
swap(rhs);
return *this;
}
void swap(image_data<pixel_type> & rhs)
{
std::swap(width_, rhs.width_);
std::swap(height_, rhs.height_);
std::swap(buffer_, rhs.buffer_);
}
inline pixel_type& operator() (std::size_t i, std::size_t j)
{
assert(i<width_ && j<height_);
return pData_[j * width_ + i];
}
inline const pixel_type& operator() (std::size_t i, std::size_t j) const
{
assert(i < width_ && j < height_);
return pData_[j * width_ + i];
}
inline std::size_t width() const
{
return width_;
}
inline std::size_t height() const
{
return height_;
}
inline void set(pixel_type const& t)
{
std::fill(pData_, pData_ + width_ * height_, t);
}
inline const pixel_type* getData() const
{
return pData_;
}
inline pixel_type* getData()
{
return pData_;
}
inline const unsigned char* getBytes() const
{
return buffer_.data();
}
inline unsigned char* getBytes()
{
return buffer_.data();
}
inline const pixel_type* getRow(unsigned row) const
{
return pData_ + row * width_;
}
inline pixel_type* getRow(unsigned row)
{
return pData_ + row * width_;
}
inline void setRow(std::size_t row, pixel_type const* buf, std::size_t size)
{
assert(row < height_);
assert(size <= width_);
std::copy(buf, buf + size, pData_ + row * width_);
}
inline void setRow(std::size_t row, std::size_t x0, std::size_t x1, pixel_type const* buf)
{
std::copy(buf, buf + (x1 - x0), pData_ + row * width_);
}
private:
std::size_t width_;
std::size_t height_;
detail::buffer buffer_;
pixel_type *pData_;
};
using image_data_32 = image_data<std::uint32_t>;
using image_data_8 = image_data<byte> ;
}
#endif // MAPNIK_IMAGE_DATA_HPP
<commit_msg>port image_data fixes from image_data_any branch<commit_after>/*****************************************************************************
*
* This file is part of Mapnik (c++ mapping toolkit)
*
* Copyright (C) 2014 Artem Pavlenko
*
* This library is free software; you can redistribute it and/or
* modify it under the terms of the GNU Lesser General Public
* License as published by the Free Software Foundation; either
* version 2.1 of the License, or (at your option) any later version.
*
* This library is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
* Lesser General Public License for more details.
*
* You should have received a copy of the GNU Lesser General Public
* License along with this library; if not, write to the Free Software
* Foundation, Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301 USA
*
*****************************************************************************/
#ifndef MAPNIK_IMAGE_DATA_HPP
#define MAPNIK_IMAGE_DATA_HPP
// mapnik
#include <mapnik/global.hpp>
// stl
#include <algorithm>
#include <cassert>
#include <stdexcept>
namespace mapnik {
namespace detail {
struct buffer
{
explicit buffer(std::size_t size)
: size_(size),
data_(static_cast<unsigned char*>(size_ != 0 ? ::operator new(size_) : nullptr))
{}
buffer(buffer && rhs) noexcept
: size_(std::move(rhs.size_)),
data_(std::move(rhs.data_))
{
rhs.size_ = 0;
rhs.data_ = nullptr;
}
buffer(buffer const& rhs)
: size_(rhs.size_),
data_(static_cast<unsigned char*>(size_ != 0 ? ::operator new(size_) : nullptr))
{
if (data_) std::copy(rhs.data_, rhs.data_ + rhs.size_, data_);
}
inline bool operator!() const { return (data_ == nullptr)? false : true; }
~buffer()
{
::operator delete(data_);
}
inline unsigned char* data() { return data_; }
inline unsigned char const* data() const { return data_; }
inline std::size_t size() const { return size_; }
std::size_t size_;
unsigned char* data_;
};
}
template <typename T>
class image_data
{
public:
using pixel_type = T;
static constexpr std::size_t pixel_size = sizeof(pixel_type);
image_data(std::size_t width, std::size_t height, bool initialize = true)
: width_(width),
height_(height),
buffer_(width_ * height_ * pixel_size),
pData_(reinterpret_cast<pixel_type*>(buffer_.data()))
{
if (pData_ && initialize) std::fill(pData_, pData_ + width_ * height_, 0);
}
image_data(image_data<pixel_type> const& rhs)
: width_(rhs.width_),
height_(rhs.height_),
buffer_(rhs.buffer_),
pData_(reinterpret_cast<pixel_type*>(buffer_.data()))
{}
image_data(image_data<pixel_type> && rhs) noexcept
: width_(rhs.width_),
height_(rhs.height_),
buffer_(std::move(rhs.buffer_)),
pData_(reinterpret_cast<pixel_type*>(buffer_.data()))
{
rhs.width_ = 0;
rhs.height_ = 0;
rhs.pData_ = nullptr;
}
image_data<pixel_type>& operator=(image_data<pixel_type> rhs)
{
swap(rhs);
return *this;
}
void swap(image_data<pixel_type> & rhs)
{
std::swap(width_, rhs.width_);
std::swap(height_, rhs.height_);
std::swap(buffer_, rhs.buffer_);
}
inline pixel_type& operator() (std::size_t i, std::size_t j)
{
assert(i<width_ && j<height_);
return pData_[j * width_ + i];
}
inline const pixel_type& operator() (std::size_t i, std::size_t j) const
{
assert(i < width_ && j < height_);
return pData_[j * width_ + i];
}
inline std::size_t width() const
{
return width_;
}
inline std::size_t height() const
{
return height_;
}
inline void set(pixel_type const& t)
{
std::fill(pData_, pData_ + width_ * height_, t);
}
inline const pixel_type* getData() const
{
return pData_;
}
inline pixel_type* getData()
{
return pData_;
}
inline const unsigned char* getBytes() const
{
return buffer_.data();
}
inline unsigned char* getBytes()
{
return buffer_.data();
}
inline const pixel_type* getRow(unsigned row) const
{
return pData_ + row * width_;
}
inline pixel_type* getRow(unsigned row)
{
return pData_ + row * width_;
}
inline void setRow(std::size_t row, pixel_type const* buf, std::size_t size)
{
assert(row < height_);
assert(size <= width_);
std::copy(buf, buf + size, pData_ + row * width_);
}
inline void setRow(std::size_t row, std::size_t x0, std::size_t x1, pixel_type const* buf)
{
assert(row < height_);
assert ((x1 - x0) <= width_ );
std::copy(buf, buf + (x1 - x0), pData_ + row * width_ + x0);
}
private:
std::size_t width_;
std::size_t height_;
detail::buffer buffer_;
pixel_type *pData_;
};
using image_data_32 = image_data<std::uint32_t>;
using image_data_8 = image_data<byte> ;
}
#endif // MAPNIK_IMAGE_DATA_HPP
<|endoftext|>
|
<commit_before>#ifndef KGR_KANGARU_INCLUDE_KANGARU_DETAIL_ERROR_HPP
#define KGR_KANGARU_INCLUDE_KANGARU_DETAIL_ERROR_HPP
#include "traits.hpp"
#include "single.hpp"
#include "service_traits.hpp"
namespace kgr {
namespace detail {
template<typename T, typename... Args>
struct ServiceError {
template<typename Service = T, enable_if_t<
is_service<Service>::value &&
dependency_trait<is_override_convertible, Service>::value &&
!is_override_convertible<Service>::value, int> = 0>
ServiceError() {
static_assert(false_t<Service>::value,
"The service injected type cannot be converted to the overriding type. "
"Check if the service is overriding the right service and if types are compatible."
);
}
template<typename Arg, typename Service = T, enable_if_t<
is_service<Service>::value &&
dependency_trait<is_override_convertible, Service>::value &&
!is_override_convertible<Service>::value, int> = 0>
ServiceError(Arg&&) {
static_assert(false_t<Service>::value,
"The service injected type cannot be converted to the overriding type. "
"Check if the service is overriding the right service and if types are compatible."
);
}
template<typename Service = T, enable_if_t<
is_service<Service>::value &&
!dependency_trait<is_override_convertible, Service>::value, int> = 0>
ServiceError() {
static_assert(false_t<Service>::value,
"One or more dependencies injected type cannot be converted to one of it's overriding type. "
"Check if that service is overriding the right service and if types are compatible."
);
}
template<typename Arg, typename Service = T, enable_if_t<
is_service<Service>::value &&
!dependency_trait<is_override_convertible, Service>::value, int> = 0>
ServiceError(Arg&&) {
static_assert(false_t<Service>::value,
"One or more dependencies injected type cannot be converted to one of it's overriding type. "
"Check if that service is overriding the right service and if types are compatible."
);
}
//
template<typename Service = T, enable_if_t<
is_service<Service>::value &&
dependency_trait<is_default_service_valid, Service>::value &&
!is_default_service_valid<Service>::value &&
is_default_convertible<Service>::value &&
is_default_overrides_abstract<Service>::value, int> = 0>
ServiceError() {
static_assert(false_t<Service>::value,
"The default implementation of this abstract service is not a well defined service. "
"Please check that types are complete and exposing a valid service definition interface."
);
}
template<typename Arg, typename Service = T, enable_if_t<
is_service<Service>::value &&
dependency_trait<is_default_service_valid, Service>::value &&
!is_default_service_valid<Service>::value &&
is_default_convertible<Service>::value &&
is_default_overrides_abstract<Service>::value, int> = 0>
ServiceError(Arg&&) {
static_assert(false_t<Service>::value,
"The default implementation of this abstract service is not a well defined service. "
"Please check that types are complete and exposing a valid service definition interface."
);
}
template<typename Service = T, enable_if_t<
is_service<Service>::value &&
dependency_trait<is_default_service_valid, Service>::value &&
!is_default_service_valid<Service>::value &&
!is_default_convertible<Service>::value &&
is_default_overrides_abstract<Service>::value, int> = 0>
ServiceError() {
static_assert(false_t<Service>::value,
"The service type of the default implementation of this abstract service is not convertible to the abstract service type. "
"Please check that the service type of the default implementation of that abstract service is a compatible type."
);
}
template<typename Arg, typename Service = T, enable_if_t<
is_service<Service>::value &&
dependency_trait<is_default_service_valid, Service>::value &&
!is_default_service_valid<Service>::value &&
!is_default_convertible<Service>::value &&
is_default_overrides_abstract<Service>::value, int> = 0>
ServiceError(Arg&&) {
static_assert(false_t<Service>::value,
"The service type of the default implementation of this abstract service is not convertible to the abstract service type. "
"Please check that the service type of the default implementation of that abstract service is a compatible type."
);
}
template<typename Service = T, enable_if_t<
is_service<Service>::value &&
dependency_trait<is_default_service_valid, Service>::value &&
!is_default_service_valid<Service>::value &&
!is_default_overrides_abstract<Service>::value, int> = 0>
ServiceError() {
static_assert(false_t<Service>::value,
"The default implementation of this abstract service is not overriding that abstract service. "
"Ensure that the default implementation really override this abstract service."
);
}
template<typename Arg, typename Service = T, enable_if_t<
is_service<Service>::value &&
dependency_trait<is_default_service_valid, Service>::value &&
!is_default_service_valid<Service>::value &&
!is_default_overrides_abstract<Service>::value, int> = 0>
ServiceError(Arg&&) {
static_assert(false_t<Service>::value,
"The default implementation of this abstract service is not overriding that abstract service. "
"Ensure that the default implementation really override this abstract service."
);
}
template<typename Service = T, enable_if_t<
is_service<Service>::value &&
!dependency_trait<is_default_service_valid, Service>::value, int> = 0>
ServiceError() {
static_assert(false_t<Service>::value,
"The default implementation of a dependency is not valid. "
"Ensure that every default implementation are valid services that override properly thier abstract services."
);
}
template<typename Arg, typename Service = T, enable_if_t<
is_service<Service>::value &&
!dependency_trait<is_default_service_valid, Service>::value, int> = 0>
ServiceError(Arg&&) {
static_assert(false_t<Service>::value,
"The default implementation of a dependency is not valid. "
"Ensure that every default implementation are valid services that override properly thier abstract services."
);
}
//
template<typename Arg, typename Service = T, enable_if_t<
is_service<Arg>::value &&
dependency_trait<is_construct_function_callable, Service, Arg, Args...>::value &&
!dependency_trait<is_service_constructible, Service, Arg, Args...>::value &&
is_service_constructible<Service, Arg, Args...>::value, int> = 0>
ServiceError(Arg&&) {
static_assert(false_t<Arg>::value,
"One or more dependencies are not constructible with it's dependencies as constructor argument. "
"Please check that dependency's constructor and it's dependencies."
);
}
template<typename Service = T, enable_if_t<
is_service<Service>::value &&
dependency_trait<is_construct_function_callable, Service>::value &&
!dependency_trait<is_service_constructible, Service>::value &&
is_service_constructible<Service>::value, int> = 0>
ServiceError() {
static_assert(false_t<Service>::value,
"One or more dependencies are not constructible with it's dependencies as constructor argument. "
"Please check that dependency's constructor and dependencies."
);
}
template<typename Arg, typename Service = T, enable_if_t<
is_service<Arg>::value &&
!dependency_trait<is_construct_function_callable, Service, Arg, Args...>::value &&
is_construct_function_callable<Service, Arg, Args...>::value &&
is_service_constructible<Service, Arg, Args...>::value, int> = 0>
ServiceError(Arg&&) {
static_assert(false_t<Arg>::value,
"One or more dependencies construct function cannot be called when calling kgr::Container::service<Dependency>(). "
"Please check that dependency's construct function and ensure that is well formed."
);
}
template<typename Service = T, enable_if_t<
is_service<Service>::value &&
!dependency_trait<is_construct_function_callable, Service>::value &&
is_construct_function_callable<Service>::value &&
is_service_constructible<Service>::value, int> = 0>
ServiceError() {
static_assert(false_t<Service>::value,
"One or more dependencies construct function cannot be called when calling kgr::Container::service<Dependency>(). "
"Please check that dependency's construct function and ensure that is well formed."
);
}
template<typename Arg, typename Service = T, enable_if_t<
is_service<Service>::value &&
!is_service_constructible<Service, Arg, Args...>::value &&
!is_service_constructible<Service>::value, int> = 0>
ServiceError(Arg&&) {
static_assert(false_t<Arg>::value,
"The service type is not constructible given it's dependencies and passed arguments. "
"Ensure that dependencies are correctly configured and you pass the right set of parameters."
);
}
template<typename Arg, typename Service = T, enable_if_t<
is_service<Service>::value &&
!is_service_constructible<Service, Arg, Args...>::value &&
is_service_constructible<Service>::value, int> = 0>
ServiceError(Arg&&) {
static_assert(false_t<Arg>::value, "The service type is not constructible given passed arguments to kgr::Container::service(...).");
}
template<typename Service = T, enable_if_t<
is_service<Service>::value &&
is_construct_function_callable<Service>::value &&
!is_service_constructible<Service>::value, int> = 0>
ServiceError() {
static_assert(false_t<Service>::value,
"The service type is not constructible given it's dependencies. "
"Check if dependencies are configured correctly and if the service has the required constructor."
);
}
template<typename Service = T, enable_if_t<
is_service<Service>::value &&
is_single<Service>::value &&
!is_construct_function_callable<Service>::value, int> = 0>
ServiceError() {
static_assert(false_t<Service>::value,
"The service construct function cannot be called. "
"Check if the construct function is well formed, receive injected arguments first and additional parameters at the end."
);
}
template<typename Service = T, enable_if_t<
is_service<Service>::value &&
!is_single<Service>::value &&
!is_construct_function_callable<Service>::value, int> = 0>
ServiceError() {
static_assert(false_t<Service>::value,
"The service construct function cannot be called without arguments, or is not well formed. "
"Check if the construct function is well formed, receive injected arguments first and additional parameters at the end."
);
}
template<typename Arg, typename Service = T, enable_if_t<
is_service<Service>::value &&
!is_single<Service>::value &&
!is_construct_function_callable<Service, Arg, Args...>::value, int> = 0>
ServiceError(Arg&&) {
static_assert(false_t<Service>::value,
"The service construct function cannot be called. "
"Check if the construct function is well formed, receive injected arguments first and additional parameters at the end."
);
}
template<typename Service = T, enable_if_t<!is_service<Service>::value && !has_forward<Service>::value, int> = 0>
ServiceError() {
static_assert(false_t<Service>::value, "The type sent to kgr::Container::service(...) is not a service.");
}
template<typename Service = T, enable_if_t<!is_service<Service>::value && has_forward<Service>::value, int> = 0>
ServiceError() {
static_assert(false_t<Service>::value, "The service type must not not contain any virtual function or must be abstract.");
}
};
struct NotInvokableError {
template<typename T = void>
NotInvokableError(...) {
static_assert(false_t<T>::value,
"The function sent is not invokable. Ensure to include all services definitions "
"you need and that received parameters are correct."
);
}
};
} // namespace detail
} // namespace kgr
#endif // KGR_KANGARU_INCLUDE_KANGARU_DETAIL_ERROR_HPP
<commit_msg>fixed some error messages<commit_after>#ifndef KGR_KANGARU_INCLUDE_KANGARU_DETAIL_ERROR_HPP
#define KGR_KANGARU_INCLUDE_KANGARU_DETAIL_ERROR_HPP
#include "traits.hpp"
#include "single.hpp"
#include "service_traits.hpp"
namespace kgr {
namespace detail {
template<typename T, typename... Args>
struct ServiceError {
template<typename Service = T, enable_if_t<
is_service<Service>::value &&
!is_override_convertible<Service>::value, int> = 0>
ServiceError() {
static_assert(false_t<Service>::value,
"The service injected type cannot be converted to the overriding type. "
"Check if the service is overriding the right service and if types are compatible."
);
}
template<typename Arg, typename Service = T, enable_if_t<
is_service<Service>::value &&
!is_override_convertible<Service>::value, int> = 0>
ServiceError(Arg&&) {
static_assert(false_t<Service>::value,
"The service injected type cannot be converted to the overriding type. "
"Check if the service is overriding the right service and if types are compatible."
);
}
template<typename Service = T, enable_if_t<
is_service<Service>::value &&
!dependency_trait<is_override_convertible, Service>::value &&
is_service_constructible<Service>::value, int> = 0>
ServiceError() {
static_assert(false_t<Service>::value,
"One or more dependencies injected type cannot be converted to one of it's overriding type. "
"Check if that service is overriding the right service and if types are compatible."
);
}
template<typename Arg, typename Service = T, enable_if_t<
is_service<Service>::value &&
!dependency_trait<is_override_convertible, Service, Arg, Args...>::value &&
is_service_constructible<Service>::value, int> = 0>
ServiceError(Arg&&) {
static_assert(false_t<Service>::value,
"One or more dependencies injected type cannot be converted to one of it's overriding type. "
"Check if that service is overriding the right service and if types are compatible."
);
}
template<typename Service = T, enable_if_t<
is_service<Service>::value &&
dependency_trait<is_default_service_valid, Service>::value &&
!is_default_service_valid<Service>::value &&
is_default_convertible<Service>::value &&
is_default_overrides_abstract<Service>::value, int> = 0>
ServiceError() {
static_assert(false_t<Service>::value,
"The default implementation of this abstract service is not a well defined service. "
"Please check that types are complete and exposing a valid service definition interface."
);
}
template<typename Arg, typename Service = T, enable_if_t<
is_service<Service>::value &&
dependency_trait<is_default_service_valid, Service, Arg, Args...>::value &&
!is_default_service_valid<Service>::value &&
is_default_convertible<Service>::value &&
is_default_overrides_abstract<Service>::value, int> = 0>
ServiceError(Arg&&) {
static_assert(false_t<Service>::value,
"The default implementation of this abstract service is not a well defined service. "
"Please check that types are complete and exposing a valid service definition interface."
);
}
template<typename Service = T, enable_if_t<
is_service<Service>::value &&
dependency_trait<is_default_service_valid, Service>::value &&
!is_default_service_valid<Service>::value &&
!is_default_convertible<Service>::value &&
is_default_overrides_abstract<Service>::value, int> = 0>
ServiceError() {
static_assert(false_t<Service>::value,
"The service type of the default implementation of this abstract service is not convertible to the abstract service type. "
"Please check that the service type of the default implementation of that abstract service is a compatible type."
);
}
template<typename Arg, typename Service = T, enable_if_t<
is_service<Service>::value &&
dependency_trait<is_default_service_valid, Service, Arg, Args...>::value &&
!is_default_service_valid<Service>::value &&
!is_default_convertible<Service>::value &&
is_default_overrides_abstract<Service>::value, int> = 0>
ServiceError(Arg&&) {
static_assert(false_t<Service>::value,
"The service type of the default implementation of this abstract service is not convertible to the abstract service type. "
"Please check that the service type of the default implementation of that abstract service is a compatible type."
);
}
template<typename Service = T, enable_if_t<
is_service<Service>::value &&
dependency_trait<is_default_service_valid, Service>::value &&
!is_default_service_valid<Service>::value &&
!is_default_overrides_abstract<Service>::value, int> = 0>
ServiceError() {
static_assert(false_t<Service>::value,
"The default implementation of this abstract service is not overriding that abstract service. "
"Ensure that the default implementation really override this abstract service."
);
}
template<typename Arg, typename Service = T, enable_if_t<
is_service<Service>::value &&
dependency_trait<is_default_service_valid, Service, Arg, Args...>::value &&
!is_default_service_valid<Service>::value &&
!is_default_overrides_abstract<Service>::value, int> = 0>
ServiceError(Arg&&) {
static_assert(false_t<Service>::value,
"The default implementation of this abstract service is not overriding that abstract service. "
"Ensure that the default implementation really override this abstract service."
);
}
template<typename Service = T, enable_if_t<
is_service<Service>::value &&
!dependency_trait<is_default_service_valid, Service>::value, int> = 0>
ServiceError() {
static_assert(false_t<Service>::value,
"The default implementation of a dependency is not valid. "
"Ensure that every default implementation are valid services that override properly thier abstract services."
);
}
template<typename Arg, typename Service = T, enable_if_t<
is_service<Service>::value &&
!dependency_trait<is_default_service_valid, Service, Arg, Args...>::value, int> = 0>
ServiceError(Arg&&) {
static_assert(false_t<Service>::value,
"The default implementation of a dependency is not valid. "
"Ensure that every default implementation are valid services that override properly thier abstract services."
);
}
template<typename Arg, typename Service = T, enable_if_t<
is_service<Arg>::value &&
dependency_trait<is_construct_function_callable, Service, Arg, Args...>::value &&
!dependency_trait<is_service_constructible, Service, Arg, Args...>::value &&
is_service_constructible<Service, Arg, Args...>::value, int> = 0>
ServiceError(Arg&&) {
static_assert(false_t<Arg>::value,
"One or more dependencies are not constructible with it's dependencies as constructor argument. "
"Please check that dependency's constructor and it's dependencies."
);
}
template<typename Service = T, enable_if_t<
is_service<Service>::value &&
dependency_trait<is_construct_function_callable, Service>::value &&
!dependency_trait<is_service_constructible, Service>::value &&
is_service_constructible<Service>::value, int> = 0>
ServiceError() {
static_assert(false_t<Service>::value,
"One or more dependencies are not constructible with it's dependencies as constructor argument. "
"Please check that dependency's constructor and dependencies."
);
}
template<typename Arg, typename Service = T, enable_if_t<
is_service<Arg>::value &&
!dependency_trait<is_construct_function_callable, Service, Arg, Args...>::value &&
is_construct_function_callable<Service, Arg, Args...>::value &&
is_service_constructible<Service, Arg, Args...>::value, int> = 0>
ServiceError(Arg&&) {
static_assert(false_t<Arg>::value,
"One or more dependencies construct function cannot be called when calling kgr::Container::service<Dependency>(). "
"Please check that dependency's construct function and ensure that is well formed."
);
}
template<typename Service = T, enable_if_t<
is_service<Service>::value &&
!dependency_trait<is_construct_function_callable, Service>::value &&
is_construct_function_callable<Service>::value &&
is_service_constructible<Service>::value, int> = 0>
ServiceError() {
static_assert(false_t<Service>::value,
"One or more dependencies construct function cannot be called when calling kgr::Container::service<Dependency>(). "
"Please check that dependency's construct function and ensure that is well formed."
);
}
template<typename Arg, typename Service = T, enable_if_t<
is_service<Service>::value &&
!is_service_constructible<Service, Arg, Args...>::value &&
!is_service_constructible<Service>::value, int> = 0>
ServiceError(Arg&&) {
static_assert(false_t<Arg>::value,
"The service type is not constructible given it's dependencies and passed arguments. "
"Ensure that dependencies are correctly configured and you pass the right set of parameters."
);
}
template<typename Arg, typename Service = T, enable_if_t<
is_service<Service>::value &&
!is_service_constructible<Service, Arg, Args...>::value &&
is_service_constructible<Service>::value, int> = 0>
ServiceError(Arg&&) {
static_assert(false_t<Arg>::value, "The service type is not constructible given passed arguments to kgr::Container::service(...).");
}
template<typename Service = T, enable_if_t<
is_service<Service>::value &&
is_construct_function_callable<Service>::value &&
!is_service_constructible<Service>::value, int> = 0>
ServiceError() {
static_assert(false_t<Service>::value,
"The service type is not constructible given it's dependencies. "
"Check if dependencies are configured correctly and if the service has the required constructor."
);
}
template<typename Service = T, enable_if_t<
is_service<Service>::value &&
is_single<Service>::value &&
!is_construct_function_callable<Service>::value, int> = 0>
ServiceError() {
static_assert(false_t<Service>::value,
"The service construct function cannot be called. "
"Check if the construct function is well formed, receive injected arguments first and additional parameters at the end."
);
}
template<typename Service = T, enable_if_t<
is_service<Service>::value &&
!is_single<Service>::value &&
!is_construct_function_callable<Service>::value, int> = 0>
ServiceError() {
static_assert(false_t<Service>::value,
"The service construct function cannot be called without arguments, or is not well formed. "
"Check if the construct function is well formed, receive injected arguments first and additional parameters at the end."
);
}
template<typename Arg, typename Service = T, enable_if_t<
is_service<Service>::value &&
!is_single<Service>::value &&
!is_construct_function_callable<Service, Arg, Args...>::value, int> = 0>
ServiceError(Arg&&) {
static_assert(false_t<Service>::value,
"The service construct function cannot be called. "
"Check if the construct function is well formed, receive injected arguments first and additional parameters at the end."
);
}
template<typename Service = T, enable_if_t<!is_service<Service>::value && !has_forward<Service>::value, int> = 0>
ServiceError() {
static_assert(false_t<Service>::value, "The type sent to kgr::Container::service(...) is not a service.");
}
template<typename Service = T, enable_if_t<!is_service<Service>::value && has_forward<Service>::value, int> = 0>
ServiceError() {
static_assert(false_t<Service>::value, "The service type must not not contain any virtual function or must be abstract.");
}
};
struct NotInvokableError {
template<typename T = void>
NotInvokableError(...) {
static_assert(false_t<T>::value,
"The function sent is not invokable. Ensure to include all services definitions "
"you need and that received parameters are correct."
);
}
};
} // namespace detail
} // namespace kgr
#endif // KGR_KANGARU_INCLUDE_KANGARU_DETAIL_ERROR_HPP
<|endoftext|>
|
<commit_before>/* -*- Mode: C++; tab-width: 4; indent-tabs-mode: nil; c-basic-offset: 4 -*- */
/*************************************************************************
*
* Copyright (c) 2015 Kohei Yoshida
*
* Permission is hereby granted, free of charge, to any person
* obtaining a copy of this software and associated documentation
* files (the "Software"), to deal in the Software without
* restriction, including without limitation the rights to use,
* copy, modify, merge, publish, distribute, sublicense, and/or sell
* copies of the Software, and to permit persons to whom the
* Software is furnished to do so, subject to the following
* conditions:
*
* The above copyright notice and this permission notice shall be
* included in all copies or substantial portions of the Software.
*
* THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND,
* EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES
* OF MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND
* NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT
* HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY,
* WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING
* FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR
* OTHER DEALINGS IN THE SOFTWARE.
*
************************************************************************/
#include "mdds/global.hpp"
#include <cassert>
#include <algorithm>
#ifdef MDDS_TRIE_MAP_DEBUG
#include <iostream>
#endif
namespace mdds { namespace draft {
namespace detail {
struct trie_node
{
char key;
const void* value;
std::deque<trie_node> children;
trie_node(char _key) : key(_key), value(nullptr) {}
};
#ifdef MDDS_TRIE_MAP_DEBUG
template<typename _ValueT>
void dump_node(std::string& buffer, const trie_node& node)
{
using namespace std;
using value_type = _ValueT;
if (node.value)
{
// This node has value.
cout << buffer << ":" << *static_cast<const value_type*>(node.value) << endl;
}
std::for_each(node.children.begin(), node.children.end(),
[&](const trie_node& node)
{
buffer.push_back(node.key);
dump_node<value_type>(buffer, node);
buffer.pop_back();
}
);
}
template<typename _ValueT>
void dump_trie(const trie_node& root)
{
std::string buffer;
dump_node<_ValueT>(buffer, root);
}
template<typename _ValueT>
void dump_packed_trie(const std::vector<uintptr_t>& packed)
{
using namespace std;
using value_type = _ValueT;
cout << "packed size: " << packed.size() << endl;
size_t n = packed.size();
size_t i = 0;
cout << i << ": root node offset: " << packed[i] << endl;
++i;
while (i < n)
{
const value_type* value = reinterpret_cast<const value_type*>(packed[i]);
cout << i << ": node value pointer: " << value;
if (value)
cout << ", value: " << *value;
cout << endl;
++i;
size_t index_size = packed[i];
cout << i << ": index size: " << index_size << endl;
++i;
index_size /= 2;
for (size_t j = 0; j < index_size; ++j)
{
char key = packed[i];
cout << i << ": key: " << key << endl;
++i;
size_t offset = packed[i];
cout << i << ": offset: " << offset << endl;
++i;
}
}
}
#endif
template<typename _EntryT>
void traverse_range(
trie_node& root, const _EntryT* start, const _EntryT* end, size_t pos)
{
using namespace std;
using entry = _EntryT;
const entry* p = start;
const entry* range_start = start;
const entry* range_end = nullptr;
char range_char = 0;
size_t range_count = 0;
for (; p != end; ++p)
{
if (pos > p->keylen)
continue;
if (pos == p->keylen)
{
root.value = &p->value;
continue;
}
++range_count;
char c = p->key[pos];
if (!range_char)
range_char = c;
else if (range_char != c)
{
// End of current character range.
range_end = p;
root.children.emplace_back(range_char);
traverse_range(root.children.back(), range_start, range_end, pos+1);
range_start = range_end;
range_char = range_start->key[pos];
range_end = nullptr;
range_count = 1;
}
}
if (range_count)
{
assert(range_char);
root.children.emplace_back(range_char);
traverse_range(root.children.back(), range_start, end, pos+1);
}
}
inline size_t compact_node(std::vector<uintptr_t>& packed, const trie_node& node)
{
std::vector<std::tuple<size_t,char>> child_offsets;
child_offsets.reserve(node.children.size());
// Process child nodes first.
std::for_each(node.children.begin(), node.children.end(),
[&](const trie_node& node)
{
size_t child_offset = compact_node(packed, node);
child_offsets.emplace_back(child_offset, node.key);
}
);
// Process this node.
size_t offset = packed.size();
packed.push_back(uintptr_t(node.value));
packed.push_back(uintptr_t(child_offsets.size()*2));
std::for_each(child_offsets.begin(), child_offsets.end(),
[&](const std::tuple<size_t,char>& v)
{
char key = std::get<1>(v);
size_t child_offset = std::get<0>(v);
packed.push_back(key);
packed.push_back(offset-child_offset);
}
);
return offset;
}
inline void compact(std::vector<uintptr_t>& packed, const trie_node& root)
{
std::vector<uintptr_t> init(size_t(1), uintptr_t(0));
packed.swap(init);
size_t root_offset = compact_node(packed, root);
packed[0] = root_offset;
}
}
template<typename _ValueT>
trie_map<_ValueT>::trie_map(
const entry* entries, size_type entry_size, value_type null_value) :
m_null_value(null_value)
{
const entry* p = entries;
const entry* p_end = p + entry_size;
// Populate the normal tree first.
detail::trie_node root(0);
detail::traverse_range(root, p, p_end, 0);
#if defined(MDDS_TRIE_MAP_DEBUG) && defined(MDDS_TREI_MAP_DEBUG_DUMP_TRIE)
detail::dump_trie<value_type>(root);
#endif
// Compact the trie into a packed array.
detail::compact(m_packed, root);
#if defined(MDDS_TRIE_MAP_DEBUG) && defined(MDDS_TREI_MAP_DEBUG_DUMP_PACKED)
detail::dump_packed_trie<value_type>(m_packed);
#endif
}
#ifdef MDDS_TRIE_MAP_DEBUG
template<typename _ValueT>
void trie_map<_ValueT>::dump() const
{
if (m_packed.empty())
return;
std::string buffer;
size_t root_offset = m_packed[0];
const uintptr_t* p = m_packed.data() + root_offset;
dump_compact_trie_node(buffer, p);
}
template<typename _ValueT>
void trie_map<_ValueT>::dump_compact_trie_node(std::string& buffer, const uintptr_t* p) const
{
using namespace std;
const uintptr_t* p0 = p; // store the head offset position of this node.
const value_type* v = reinterpret_cast<const value_type*>(*p);
if (v)
cout << buffer << ":" << *v << endl;
++p;
size_t index_size = *p;
size_t n = index_size / 2;
++p;
for (size_t i = 0; i < n; ++i)
{
char key = *p++;
size_t offset = *p++;
buffer.push_back(key);
const uintptr_t* p_child = p0 - offset;
dump_compact_trie_node(buffer, p_child);
buffer.pop_back();
}
}
#endif
}}
/* vim:set shiftwidth=4 softtabstop=4 expandtab: */
<commit_msg>Make type entry type more specific.<commit_after>/* -*- Mode: C++; tab-width: 4; indent-tabs-mode: nil; c-basic-offset: 4 -*- */
/*************************************************************************
*
* Copyright (c) 2015 Kohei Yoshida
*
* Permission is hereby granted, free of charge, to any person
* obtaining a copy of this software and associated documentation
* files (the "Software"), to deal in the Software without
* restriction, including without limitation the rights to use,
* copy, modify, merge, publish, distribute, sublicense, and/or sell
* copies of the Software, and to permit persons to whom the
* Software is furnished to do so, subject to the following
* conditions:
*
* The above copyright notice and this permission notice shall be
* included in all copies or substantial portions of the Software.
*
* THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND,
* EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES
* OF MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND
* NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT
* HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY,
* WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING
* FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR
* OTHER DEALINGS IN THE SOFTWARE.
*
************************************************************************/
#include "mdds/global.hpp"
#include <cassert>
#include <algorithm>
#ifdef MDDS_TRIE_MAP_DEBUG
#include <iostream>
#endif
namespace mdds { namespace draft {
namespace detail {
struct trie_node
{
char key;
const void* value;
std::deque<trie_node> children;
trie_node(char _key) : key(_key), value(nullptr) {}
};
#ifdef MDDS_TRIE_MAP_DEBUG
template<typename _ValueT>
void dump_node(std::string& buffer, const trie_node& node)
{
using namespace std;
using value_type = _ValueT;
if (node.value)
{
// This node has value.
cout << buffer << ":" << *static_cast<const value_type*>(node.value) << endl;
}
std::for_each(node.children.begin(), node.children.end(),
[&](const trie_node& node)
{
buffer.push_back(node.key);
dump_node<value_type>(buffer, node);
buffer.pop_back();
}
);
}
template<typename _ValueT>
void dump_trie(const trie_node& root)
{
std::string buffer;
dump_node<_ValueT>(buffer, root);
}
template<typename _ValueT>
void dump_packed_trie(const std::vector<uintptr_t>& packed)
{
using namespace std;
using value_type = _ValueT;
cout << "packed size: " << packed.size() << endl;
size_t n = packed.size();
size_t i = 0;
cout << i << ": root node offset: " << packed[i] << endl;
++i;
while (i < n)
{
const value_type* value = reinterpret_cast<const value_type*>(packed[i]);
cout << i << ": node value pointer: " << value;
if (value)
cout << ", value: " << *value;
cout << endl;
++i;
size_t index_size = packed[i];
cout << i << ": index size: " << index_size << endl;
++i;
index_size /= 2;
for (size_t j = 0; j < index_size; ++j)
{
char key = packed[i];
cout << i << ": key: " << key << endl;
++i;
size_t offset = packed[i];
cout << i << ": offset: " << offset << endl;
++i;
}
}
}
#endif
template<typename _ValueT>
void traverse_range(
trie_node& root,
const typename trie_map<_ValueT>::entry* start,
const typename trie_map<_ValueT>::entry* end,
size_t pos)
{
using namespace std;
using entry = typename trie_map<_ValueT>::entry;
const entry* p = start;
const entry* range_start = start;
const entry* range_end = nullptr;
char range_char = 0;
size_t range_count = 0;
for (; p != end; ++p)
{
if (pos > p->keylen)
continue;
if (pos == p->keylen)
{
root.value = &p->value;
continue;
}
++range_count;
char c = p->key[pos];
if (!range_char)
range_char = c;
else if (range_char != c)
{
// End of current character range.
range_end = p;
root.children.emplace_back(range_char);
traverse_range<_ValueT>(root.children.back(), range_start, range_end, pos+1);
range_start = range_end;
range_char = range_start->key[pos];
range_end = nullptr;
range_count = 1;
}
}
if (range_count)
{
assert(range_char);
root.children.emplace_back(range_char);
traverse_range<_ValueT>(root.children.back(), range_start, end, pos+1);
}
}
inline size_t compact_node(std::vector<uintptr_t>& packed, const trie_node& node)
{
std::vector<std::tuple<size_t,char>> child_offsets;
child_offsets.reserve(node.children.size());
// Process child nodes first.
std::for_each(node.children.begin(), node.children.end(),
[&](const trie_node& node)
{
size_t child_offset = compact_node(packed, node);
child_offsets.emplace_back(child_offset, node.key);
}
);
// Process this node.
size_t offset = packed.size();
packed.push_back(uintptr_t(node.value));
packed.push_back(uintptr_t(child_offsets.size()*2));
std::for_each(child_offsets.begin(), child_offsets.end(),
[&](const std::tuple<size_t,char>& v)
{
char key = std::get<1>(v);
size_t child_offset = std::get<0>(v);
packed.push_back(key);
packed.push_back(offset-child_offset);
}
);
return offset;
}
inline void compact(std::vector<uintptr_t>& packed, const trie_node& root)
{
std::vector<uintptr_t> init(size_t(1), uintptr_t(0));
packed.swap(init);
size_t root_offset = compact_node(packed, root);
packed[0] = root_offset;
}
}
template<typename _ValueT>
trie_map<_ValueT>::trie_map(
const entry* entries, size_type entry_size, value_type null_value) :
m_null_value(null_value)
{
const entry* p = entries;
const entry* p_end = p + entry_size;
// Populate the normal tree first.
detail::trie_node root(0);
detail::traverse_range<value_type>(root, p, p_end, 0);
#if defined(MDDS_TRIE_MAP_DEBUG) && defined(MDDS_TREI_MAP_DEBUG_DUMP_TRIE)
detail::dump_trie<value_type>(root);
#endif
// Compact the trie into a packed array.
detail::compact(m_packed, root);
#if defined(MDDS_TRIE_MAP_DEBUG) && defined(MDDS_TREI_MAP_DEBUG_DUMP_PACKED)
detail::dump_packed_trie<value_type>(m_packed);
#endif
}
#ifdef MDDS_TRIE_MAP_DEBUG
template<typename _ValueT>
void trie_map<_ValueT>::dump() const
{
if (m_packed.empty())
return;
std::string buffer;
size_t root_offset = m_packed[0];
const uintptr_t* p = m_packed.data() + root_offset;
dump_compact_trie_node(buffer, p);
}
template<typename _ValueT>
void trie_map<_ValueT>::dump_compact_trie_node(std::string& buffer, const uintptr_t* p) const
{
using namespace std;
const uintptr_t* p0 = p; // store the head offset position of this node.
const value_type* v = reinterpret_cast<const value_type*>(*p);
if (v)
cout << buffer << ":" << *v << endl;
++p;
size_t index_size = *p;
size_t n = index_size / 2;
++p;
for (size_t i = 0; i < n; ++i)
{
char key = *p++;
size_t offset = *p++;
buffer.push_back(key);
const uintptr_t* p_child = p0 - offset;
dump_compact_trie_node(buffer, p_child);
buffer.pop_back();
}
}
#endif
}}
/* vim:set shiftwidth=4 softtabstop=4 expandtab: */
<|endoftext|>
|
<commit_before>#ifndef CRTIICS_NLL_HPP
#define CRTIICS_NLL_HPP
#include "critic.hpp"
namespace nnlib
{
/// \brief Negative log loss critic.
///
/// This critic requires matrix input and single-column matrix output.
template <typename T = double>
class NLL : public Critic<T>
{
public:
NLL(bool average = true);
bool average() const;
NLL &average(bool ave);
/// A convenience method for counting misclassifications, since we know the output will be categorical.
size_t misclassifications(const Tensor<T> &input, const Tensor<T> &target);
/// L = 1/n sum_i( -input(target(i)) )
virtual T forward(const Tensor<T> &input, const Tensor<T> &target) override;
/// dL/di = target == i ? -1/n : 0
virtual Tensor<T> &backward(const Tensor<T> &input, const Tensor<T> &target) override;
protected:
using Critic<T>::m_inGrad;
private:
bool m_average;
};
}
#ifdef NN_REAL_T
extern template class nnlib::NLL<NN_REAL_T>;
#else
#include "detail/nnl.tpp"
#endif
#endif
<commit_msg>Fixed a typo.<commit_after>#ifndef CRTIICS_NLL_HPP
#define CRTIICS_NLL_HPP
#include "critic.hpp"
namespace nnlib
{
/// \brief Negative log loss critic.
///
/// This critic requires matrix input and single-column matrix output.
template <typename T = double>
class NLL : public Critic<T>
{
public:
NLL(bool average = true);
bool average() const;
NLL &average(bool ave);
/// A convenience method for counting misclassifications, since we know the output will be categorical.
size_t misclassifications(const Tensor<T> &input, const Tensor<T> &target);
/// L = 1/n sum_i( -input(target(i)) )
virtual T forward(const Tensor<T> &input, const Tensor<T> &target) override;
/// dL/di = target == i ? -1/n : 0
virtual Tensor<T> &backward(const Tensor<T> &input, const Tensor<T> &target) override;
protected:
using Critic<T>::m_inGrad;
private:
bool m_average;
};
}
#ifdef NN_REAL_T
extern template class nnlib::NLL<NN_REAL_T>;
#else
#include "detail/nll.tpp"
#endif
#endif
<|endoftext|>
|
<commit_before>//============================================================================
// MCKL/include/mckl/random/threefry.hpp
//----------------------------------------------------------------------------
// MCKL: Monte Carlo Kernel Library
//----------------------------------------------------------------------------
// Copyright (c) 2013-2016, Yan Zhou
// All rights reserved.
//
// Redistribution and use in source and binary forms, with or without
// modification, are permitted provided that the following conditions are met:
//
// Redistributions of source code must retain the above copyright notice,
// this list of conditions and the following disclaimer.
//
// Redistributions in binary form must reproduce the above copyright notice,
// this list of conditions and the following disclaimer in the documentation
// and/or other materials provided with the distribution.
//
// THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS AS IS
// AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE
// IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE
// ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT HOLDER OR CONTRIBUTORS BE
// LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR
// CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF
// SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS
// INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN
// CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE)
// ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE
// POSSIBILITY OF SUCH DAMAGE.
//============================================================================
#ifndef MCKL_RANDOM_THREEFRY_HPP
#define MCKL_RANDOM_THREEFRY_HPP
#include <mckl/random/internal/common.hpp>
#include <mckl/random/internal/threefry_constants.hpp>
#include <mckl/random/internal/threefry_generic.hpp>
#include <mckl/random/counter.hpp>
#include <mckl/random/increment.hpp>
#if MCKL_HAS_SSE2
#include <mckl/random/internal/threefry_sse2.hpp>
#endif
#if MCKL_HAS_AVX2
#include <mckl/random/internal/threefry_avx2.hpp>
#endif
/// \brief ThreefryGenerator default rounds
/// \ingroup Config
#ifndef MCKL_THREEFRY_ROUNDS
#define MCKL_THREEFRY_ROUNDS 20
#endif
namespace mckl
{
namespace internal
{
#if MCKL_USE_AVX2
template <typename T, std::size_t K, std::size_t Rounds, typename Constants>
using ThreefryGeneratorImpl =
ThreefryGeneratorAVX2Impl<T, K, Rounds, Constants>;
#elif MCKL_USE_SSE2
template <typename T, std::size_t K, std::size_t Rounds, typename Constants>
using ThreefryGeneratorImpl =
ThreefryGeneratorSSE2Impl<T, K, Rounds, Constants>;
#else // MCKL_USE_AVX2
template <typename T, std::size_t K, std::size_t Rounds, typename Constants>
using ThreefryGeneratorImpl =
ThreefryGeneratorGeneric2Impl<T, K, Rounds, Constants>;
#endif // MCKL_USE_AVX2
} // namespace mckl::internal
/// \brief Threefry RNG generator
/// \ingroup Threefry
///
/// \tparam T State vector value type
/// \tparam K State vector length
/// \tparam Rounds The number of rounds
/// \tparam Constants A trait class that defines algorithm constants
template <typename T, std::size_t K, std::size_t Rounds = MCKL_THREEFRY_ROUNDS,
typename Constants = ThreefryConstants<T, K>>
class ThreefryGenerator
{
static_assert(std::is_unsigned<T>::value,
"**ThreefryGenerator** used with T other than unsigned integer types");
static_assert(K != 0 && K % 2 == 0,
"**ThreefryGenerator** used with K other than multiples of 2");
static_assert(
Rounds != 0, "**ThreefryGenerator** used with rounds equal to zero");
public:
using ctr_type = Counter<T, K>;
using key_type = std::array<T, K>;
static constexpr std::size_t size() { return sizeof(T) * K; }
key_type key() const
{
key_type key;
std::memcpy(key.data(), par_.data(), sizeof(T) * K);
return key;
}
void reset(const key_type &key)
{
constexpr T p = Constants::parity::value;
std::memcpy(par_.data(), key.data(), sizeof(T) * K);
std::get<K>(par_) = p;
for (std::size_t i = 0; i != key.size(); ++i)
std::get<K>(par_) ^= par_[i];
std::get<K + 1>(par_) = 0;
std::get<K + 2>(par_) = 0;
std::get<K + 3>(par_) = 0;
}
std::pair<T, T> tweak() const
{
return std::make_pair(std::get<K + 1>(par_), std::get<K + 2>(par_));
}
void tweak(T t0, T t1)
{
std::get<K + 1>(par_) = t0;
std::get<K + 2>(par_) = t1;
std::get<K + 3>(par_) = t0 ^ t1;
}
void operator()(const void *plain, void *cipher) const
{
internal::ThreefryGeneratorImpl<T, K, Rounds, Constants>::eval(
plain, cipher, par_);
}
template <typename ResultType>
void operator()(ctr_type &ctr, ResultType *r) const
{
internal::ThreefryGeneratorImpl<T, K, Rounds, Constants>::eval(
ctr, r, par_);
}
template <typename ResultType>
void operator()(ctr_type &ctr, std::size_t n, ResultType *r) const
{
internal::ThreefryGeneratorImpl<T, K, Rounds, Constants>::eval(
ctr, n, r, par_);
}
friend bool operator==(
const ThreefryGenerator<T, K, Rounds, Constants> &gen1,
const ThreefryGenerator<T, K, Rounds, Constants> &gen2)
{
return gen1.par_ == gen2.par_;
}
friend bool operator!=(
const ThreefryGenerator<T, K, Rounds, Constants> &gen1,
const ThreefryGenerator<T, K, Rounds, Constants> &gen2)
{
return !(gen1 == gen2);
}
template <typename CharT, typename Traits>
friend std::basic_ostream<CharT, Traits> &operator<<(
std::basic_ostream<CharT, Traits> &os,
const ThreefryGenerator<T, K, Rounds, Constants> &gen)
{
if (!os)
return os;
os << gen.par_;
return os;
}
template <typename CharT, typename Traits>
friend std::basic_istream<CharT, Traits> &operator>>(
std::basic_istream<CharT, Traits> &is,
ThreefryGenerator<T, K, Rounds, Constants> &gen)
{
if (!is)
return is;
ThreefryGenerator<T, K, Rounds, Constants> gen_tmp;
gen_tmp.par_.fill(0);
is >> std::ws >> gen_tmp.par_;
if (is)
gen = std::move(gen_tmp);
return is;
}
private:
std::array<T, K + 4> par_;
}; // class ThreefryGenerator
/// \brief Threefry RNG engine
/// \ingroup Threefry
template <typename ResultType, typename T, std::size_t K,
std::size_t Rounds = MCKL_THREEFRY_ROUNDS,
typename Constants = ThreefryConstants<T, K>>
using ThreefryEngine =
CounterEngine<ResultType, ThreefryGenerator<T, K, Rounds, Constants>>;
/// \brief Threefry2x32 RNG engine
/// \ingroup Threefry
template <typename ResultType>
using Threefry2x32Engine = ThreefryEngine<ResultType, std::uint32_t, 2>;
/// \brief Threefry4x32 RNG engine
/// \ingroup Threefry
template <typename ResultType>
using Threefry4x32Engine = ThreefryEngine<ResultType, std::uint32_t, 4>;
/// \brief Threefry2x64 RNG engine
/// \ingroup Threefry
template <typename ResultType>
using Threefry2x64Engine = ThreefryEngine<ResultType, std::uint64_t, 2>;
/// \brief Threefry4x64 RNG engine
/// \ingroup Threefry
template <typename ResultType>
using Threefry4x64Engine = ThreefryEngine<ResultType, std::uint64_t, 4>;
/// \brief Threefry8x64 RNG engine
/// \ingroup Threefry
template <typename ResultType>
using Threefry8x64Engine = ThreefryEngine<ResultType, std::uint64_t, 8>;
/// \brief Threefry16x64 RNG engine
/// \ingroup Threefry
template <typename ResultType>
using Threefry16x64Engine = ThreefryEngine<ResultType, std::uint64_t, 16>;
/// \brief Threefish-256 RNG engine
template <typename ResultType>
using Threefish256Engine = ThreefryEngine<ResultType, std::uint64_t, 4, 72>;
/// \brief Threefish-512 RNG engine
template <typename ResultType>
using Threefish512Engine = ThreefryEngine<ResultType, std::uint64_t, 8, 72>;
/// \brief Threefish-1024 RNG engine
template <typename ResultType>
using Threefish1024Engine = ThreefryEngine<ResultType, std::uint64_t, 16, 80>;
/// \brief Threefry2x32 RNG engine with 32-bit integer output
/// \ingroup Threefry
using Threefry2x32 = Threefry2x32Engine<std::uint32_t>;
/// \brief Threefry4x32 RNG engine with 32-bit integer output
/// \ingroup Threefry
using Threefry4x32 = Threefry4x32Engine<std::uint32_t>;
/// \brief Threefry2x64 RNG engine with 32-bit integer output
/// \ingroup Threefry
using Threefry2x64 = Threefry2x64Engine<std::uint32_t>;
/// \brief Threefry4x64 RNG engine with 32-bit integer output
/// \ingroup Threefry
using Threefry4x64 = Threefry4x64Engine<std::uint32_t>;
/// \brief Threefry8x64 RNG engine with 32-bit integer output
/// \ingroup Threefry
using Threefry8x64 = Threefry8x64Engine<std::uint32_t>;
/// \brief Threefry16x64 RNG engine with 32-bit integer output
/// \ingroup Threefry
using Threefry16x64 = Threefry16x64Engine<std::uint32_t>;
/// \brief Threefish-256 RNG engine with 32-bit integer output
/// \ingroup Threefry
using Threefish256 = Threefish256Engine<std::uint32_t>;
/// \brief Threefish-512 RNG engine with 32-bit integer output
/// \ingroup Threefry
using Threefish512 = Threefish512Engine<std::uint32_t>;
/// \brief Threefish-1024 RNG engine with 32-bit integer output
/// \ingroup Threefry
using Threefish1024 = Threefish1024Engine<std::uint32_t>;
/// \brief Threefry2x32 RNG engine with 64-bit integer output
/// \ingroup Threefry
using Threefry2x32_64 = Threefry2x32Engine<std::uint64_t>;
/// \brief Threefry4x32 RNG engine with 64-bit integer output
/// \ingroup Threefry
using Threefry4x32_64 = Threefry4x32Engine<std::uint64_t>;
/// \brief Threefry2x64 RNG engine with 64-bit integer output
/// \ingroup Threefry
using Threefry2x64_64 = Threefry2x64Engine<std::uint64_t>;
/// \brief Threefry4x64 RNG engine with 64-bit integer output
/// \ingroup Threefry
using Threefry4x64_64 = Threefry4x64Engine<std::uint64_t>;
/// \brief Threefry8x64 RNG engine with 64-bit integer output
/// \ingroup Threefry
using Threefry8x64_64 = Threefry8x64Engine<std::uint64_t>;
/// \brief Threefry16x64 RNG engine with 64-bit integer output
/// \ingroup Threefry
using Threefry16x64_64 = Threefry16x64Engine<std::uint64_t>;
/// \brief Threefish-256 RNG engine with 64-bit integer output
/// \ingroup Threefry
using Threefish256_64 = Threefish256Engine<std::uint64_t>;
/// \brief Threefish-512 RNG engine with 64-bit integer output
/// \ingroup Threefry
using Threefish512_64 = Threefish512Engine<std::uint64_t>;
/// \brief Threefish-1024 RNG engine with 64-bit integer output
/// \ingroup Threefry
using Threefish1024_64 = Threefish1024Engine<std::uint64_t>;
} // namespace mckl
#endif // MCKL_RANDOM_THREEFRY_HPP
<commit_msg>fix generic threefry<commit_after>//============================================================================
// MCKL/include/mckl/random/threefry.hpp
//----------------------------------------------------------------------------
// MCKL: Monte Carlo Kernel Library
//----------------------------------------------------------------------------
// Copyright (c) 2013-2016, Yan Zhou
// All rights reserved.
//
// Redistribution and use in source and binary forms, with or without
// modification, are permitted provided that the following conditions are met:
//
// Redistributions of source code must retain the above copyright notice,
// this list of conditions and the following disclaimer.
//
// Redistributions in binary form must reproduce the above copyright notice,
// this list of conditions and the following disclaimer in the documentation
// and/or other materials provided with the distribution.
//
// THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS AS IS
// AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE
// IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE
// ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT HOLDER OR CONTRIBUTORS BE
// LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR
// CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF
// SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS
// INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN
// CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE)
// ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE
// POSSIBILITY OF SUCH DAMAGE.
//============================================================================
#ifndef MCKL_RANDOM_THREEFRY_HPP
#define MCKL_RANDOM_THREEFRY_HPP
#include <mckl/random/internal/common.hpp>
#include <mckl/random/internal/threefry_constants.hpp>
#include <mckl/random/internal/threefry_generic.hpp>
#include <mckl/random/counter.hpp>
#include <mckl/random/increment.hpp>
#if MCKL_HAS_SSE2
#include <mckl/random/internal/threefry_sse2.hpp>
#endif
#if MCKL_HAS_AVX2
#include <mckl/random/internal/threefry_avx2.hpp>
#endif
/// \brief ThreefryGenerator default rounds
/// \ingroup Config
#ifndef MCKL_THREEFRY_ROUNDS
#define MCKL_THREEFRY_ROUNDS 20
#endif
namespace mckl
{
namespace internal
{
#if MCKL_USE_AVX2
template <typename T, std::size_t K, std::size_t Rounds, typename Constants>
using ThreefryGeneratorImpl =
ThreefryGeneratorAVX2Impl<T, K, Rounds, Constants>;
#elif MCKL_USE_SSE2
template <typename T, std::size_t K, std::size_t Rounds, typename Constants>
using ThreefryGeneratorImpl =
ThreefryGeneratorSSE2Impl<T, K, Rounds, Constants>;
#else // MCKL_USE_AVX2
template <typename T, std::size_t K, std::size_t Rounds, typename Constants>
using ThreefryGeneratorImpl =
ThreefryGeneratorGenericImpl<T, K, Rounds, Constants>;
#endif // MCKL_USE_AVX2
} // namespace mckl::internal
/// \brief Threefry RNG generator
/// \ingroup Threefry
///
/// \tparam T State vector value type
/// \tparam K State vector length
/// \tparam Rounds The number of rounds
/// \tparam Constants A trait class that defines algorithm constants
template <typename T, std::size_t K, std::size_t Rounds = MCKL_THREEFRY_ROUNDS,
typename Constants = ThreefryConstants<T, K>>
class ThreefryGenerator
{
static_assert(std::is_unsigned<T>::value,
"**ThreefryGenerator** used with T other than unsigned integer types");
static_assert(K != 0 && K % 2 == 0,
"**ThreefryGenerator** used with K other than multiples of 2");
static_assert(
Rounds != 0, "**ThreefryGenerator** used with rounds equal to zero");
public:
using ctr_type = Counter<T, K>;
using key_type = std::array<T, K>;
static constexpr std::size_t size() { return sizeof(T) * K; }
key_type key() const
{
key_type key;
std::memcpy(key.data(), par_.data(), sizeof(T) * K);
return key;
}
void reset(const key_type &key)
{
constexpr T p = Constants::parity::value;
std::memcpy(par_.data(), key.data(), sizeof(T) * K);
std::get<K>(par_) = p;
for (std::size_t i = 0; i != key.size(); ++i)
std::get<K>(par_) ^= par_[i];
std::get<K + 1>(par_) = 0;
std::get<K + 2>(par_) = 0;
std::get<K + 3>(par_) = 0;
}
std::pair<T, T> tweak() const
{
return std::make_pair(std::get<K + 1>(par_), std::get<K + 2>(par_));
}
void tweak(T t0, T t1)
{
std::get<K + 1>(par_) = t0;
std::get<K + 2>(par_) = t1;
std::get<K + 3>(par_) = t0 ^ t1;
}
void operator()(const void *plain, void *cipher) const
{
internal::ThreefryGeneratorImpl<T, K, Rounds, Constants>::eval(
plain, cipher, par_);
}
template <typename ResultType>
void operator()(ctr_type &ctr, ResultType *r) const
{
internal::ThreefryGeneratorImpl<T, K, Rounds, Constants>::eval(
ctr, r, par_);
}
template <typename ResultType>
void operator()(ctr_type &ctr, std::size_t n, ResultType *r) const
{
internal::ThreefryGeneratorImpl<T, K, Rounds, Constants>::eval(
ctr, n, r, par_);
}
friend bool operator==(
const ThreefryGenerator<T, K, Rounds, Constants> &gen1,
const ThreefryGenerator<T, K, Rounds, Constants> &gen2)
{
return gen1.par_ == gen2.par_;
}
friend bool operator!=(
const ThreefryGenerator<T, K, Rounds, Constants> &gen1,
const ThreefryGenerator<T, K, Rounds, Constants> &gen2)
{
return !(gen1 == gen2);
}
template <typename CharT, typename Traits>
friend std::basic_ostream<CharT, Traits> &operator<<(
std::basic_ostream<CharT, Traits> &os,
const ThreefryGenerator<T, K, Rounds, Constants> &gen)
{
if (!os)
return os;
os << gen.par_;
return os;
}
template <typename CharT, typename Traits>
friend std::basic_istream<CharT, Traits> &operator>>(
std::basic_istream<CharT, Traits> &is,
ThreefryGenerator<T, K, Rounds, Constants> &gen)
{
if (!is)
return is;
ThreefryGenerator<T, K, Rounds, Constants> gen_tmp;
gen_tmp.par_.fill(0);
is >> std::ws >> gen_tmp.par_;
if (is)
gen = std::move(gen_tmp);
return is;
}
private:
std::array<T, K + 4> par_;
}; // class ThreefryGenerator
/// \brief Threefry RNG engine
/// \ingroup Threefry
template <typename ResultType, typename T, std::size_t K,
std::size_t Rounds = MCKL_THREEFRY_ROUNDS,
typename Constants = ThreefryConstants<T, K>>
using ThreefryEngine =
CounterEngine<ResultType, ThreefryGenerator<T, K, Rounds, Constants>>;
/// \brief Threefry2x32 RNG engine
/// \ingroup Threefry
template <typename ResultType>
using Threefry2x32Engine = ThreefryEngine<ResultType, std::uint32_t, 2>;
/// \brief Threefry4x32 RNG engine
/// \ingroup Threefry
template <typename ResultType>
using Threefry4x32Engine = ThreefryEngine<ResultType, std::uint32_t, 4>;
/// \brief Threefry2x64 RNG engine
/// \ingroup Threefry
template <typename ResultType>
using Threefry2x64Engine = ThreefryEngine<ResultType, std::uint64_t, 2>;
/// \brief Threefry4x64 RNG engine
/// \ingroup Threefry
template <typename ResultType>
using Threefry4x64Engine = ThreefryEngine<ResultType, std::uint64_t, 4>;
/// \brief Threefry8x64 RNG engine
/// \ingroup Threefry
template <typename ResultType>
using Threefry8x64Engine = ThreefryEngine<ResultType, std::uint64_t, 8>;
/// \brief Threefry16x64 RNG engine
/// \ingroup Threefry
template <typename ResultType>
using Threefry16x64Engine = ThreefryEngine<ResultType, std::uint64_t, 16>;
/// \brief Threefish-256 RNG engine
template <typename ResultType>
using Threefish256Engine = ThreefryEngine<ResultType, std::uint64_t, 4, 72>;
/// \brief Threefish-512 RNG engine
template <typename ResultType>
using Threefish512Engine = ThreefryEngine<ResultType, std::uint64_t, 8, 72>;
/// \brief Threefish-1024 RNG engine
template <typename ResultType>
using Threefish1024Engine = ThreefryEngine<ResultType, std::uint64_t, 16, 80>;
/// \brief Threefry2x32 RNG engine with 32-bit integer output
/// \ingroup Threefry
using Threefry2x32 = Threefry2x32Engine<std::uint32_t>;
/// \brief Threefry4x32 RNG engine with 32-bit integer output
/// \ingroup Threefry
using Threefry4x32 = Threefry4x32Engine<std::uint32_t>;
/// \brief Threefry2x64 RNG engine with 32-bit integer output
/// \ingroup Threefry
using Threefry2x64 = Threefry2x64Engine<std::uint32_t>;
/// \brief Threefry4x64 RNG engine with 32-bit integer output
/// \ingroup Threefry
using Threefry4x64 = Threefry4x64Engine<std::uint32_t>;
/// \brief Threefry8x64 RNG engine with 32-bit integer output
/// \ingroup Threefry
using Threefry8x64 = Threefry8x64Engine<std::uint32_t>;
/// \brief Threefry16x64 RNG engine with 32-bit integer output
/// \ingroup Threefry
using Threefry16x64 = Threefry16x64Engine<std::uint32_t>;
/// \brief Threefish-256 RNG engine with 32-bit integer output
/// \ingroup Threefry
using Threefish256 = Threefish256Engine<std::uint32_t>;
/// \brief Threefish-512 RNG engine with 32-bit integer output
/// \ingroup Threefry
using Threefish512 = Threefish512Engine<std::uint32_t>;
/// \brief Threefish-1024 RNG engine with 32-bit integer output
/// \ingroup Threefry
using Threefish1024 = Threefish1024Engine<std::uint32_t>;
/// \brief Threefry2x32 RNG engine with 64-bit integer output
/// \ingroup Threefry
using Threefry2x32_64 = Threefry2x32Engine<std::uint64_t>;
/// \brief Threefry4x32 RNG engine with 64-bit integer output
/// \ingroup Threefry
using Threefry4x32_64 = Threefry4x32Engine<std::uint64_t>;
/// \brief Threefry2x64 RNG engine with 64-bit integer output
/// \ingroup Threefry
using Threefry2x64_64 = Threefry2x64Engine<std::uint64_t>;
/// \brief Threefry4x64 RNG engine with 64-bit integer output
/// \ingroup Threefry
using Threefry4x64_64 = Threefry4x64Engine<std::uint64_t>;
/// \brief Threefry8x64 RNG engine with 64-bit integer output
/// \ingroup Threefry
using Threefry8x64_64 = Threefry8x64Engine<std::uint64_t>;
/// \brief Threefry16x64 RNG engine with 64-bit integer output
/// \ingroup Threefry
using Threefry16x64_64 = Threefry16x64Engine<std::uint64_t>;
/// \brief Threefish-256 RNG engine with 64-bit integer output
/// \ingroup Threefry
using Threefish256_64 = Threefish256Engine<std::uint64_t>;
/// \brief Threefish-512 RNG engine with 64-bit integer output
/// \ingroup Threefry
using Threefish512_64 = Threefish512Engine<std::uint64_t>;
/// \brief Threefish-1024 RNG engine with 64-bit integer output
/// \ingroup Threefry
using Threefish1024_64 = Threefish1024Engine<std::uint64_t>;
} // namespace mckl
#endif // MCKL_RANDOM_THREEFRY_HPP
<|endoftext|>
|
<commit_before>#ifndef PROTOCOL_MESSAGES_HPP_
#define PROTOCOL_MESSAGES_HPP_
#include <cstdint>
namespace protocol {
namespace message {
struct heartbeat_message_t {
enum { ID = 0x00 };
std::uint8_t seq;
} __attribute__((packed));
struct log_message_t {
enum { ID = 0x01 };
uint32_t time;
char data[100];
} __attribute__((packed));
struct attitude_message_t {
enum { ID = 0x02 };
uint32_t time;
float dcm[9];
} __attribute__((packed));
struct set_arm_state_message_t {
enum { ID = 0x03 };
bool armed;
} __attribute__((packed));
struct set_control_mode_message_t {
enum { ID = 0x04 };
enum class ControlMode {
MANUAL,
OFFBOARD
};
ControlMode mode;
} __attribute__((packed));
struct offboard_attitude_control_message_t {
enum { ID = 0x05 };
float roll;
float pitch;
float yaw;
float throttle;
uint16_t buttons; // Bitfield of buttons
uint8_t mode;
} __attribute__((packed));
struct motor_throttle_message_t {
enum { ID = 0x06 };
uint32_t time;
float throttles[4];
} __attribute__((packed));
struct sensor_calibration_request_message_t {
enum { ID = 0x07 };
} __attribute__((packed));
struct sensor_calibration_response_message_t {
enum { ID = 0x08 };
enum class SensorType {
ACCEL,
GYRO,
MAG
};
SensorType type;
float offsets[3];
} __attribute__((packed));
struct location_message_t {
enum { ID = 0x09 };
uint32_t time;
float lat;
float lon;
float alt;
} __attribute__((packed));
struct imu_message_t {
enum { ID = 0x0a };
uint32_t time;
float gyro[3]; // Gyroscope
float accel[3]; // Accelerometer
} __attribute__((packed));
struct system_message_t {
enum { ID = 0x0b };
uint32_t time;
uint8_t state;
float motorDC; // TODO(yoos): Hack for esra test launch
} __attribute__((packed));
struct raw_1000_message_t {
enum { ID = 0x0c };
uint32_t time;
float accel[3]; // Accelerometer
float accelH[3]; // High-g accel
float gyro[3]; // Gyroscope
} __attribute__((packed));
struct raw_50_message_t {
enum { ID = 0x0d };
uint32_t time;
float bar; // Barometric pressure
float temp; // Temperature
float mag[3]; // Magnetometer
} __attribute((packed));
struct raw_10_message_t {
enum { ID = 0x0e };
uint32_t time;
bool gps_valid;
float lat;
float lon;
float utc; // UTC time
uint16_t geigerCount; // Number of blips counted since last report
} __attribute((packed));
struct fs_info_message_t {
enum { ID = 0x0f };
uint32_t time;
char fname[32];
uint32_t fsize;
} __attribute((packed));
inline std::uint16_t length(int id) {
// TODO(kyle): sizeof(empty struct) is 1 in C++...
switch(id) {
case heartbeat_message_t::ID:
return sizeof(heartbeat_message_t);
case log_message_t::ID:
return sizeof(log_message_t);
case attitude_message_t::ID:
return sizeof(attitude_message_t);
case set_arm_state_message_t::ID:
return sizeof(set_arm_state_message_t);
case set_control_mode_message_t::ID:
return sizeof(set_control_mode_message_t);
case offboard_attitude_control_message_t::ID:
return sizeof(offboard_attitude_control_message_t);
case motor_throttle_message_t::ID:
return sizeof(motor_throttle_message_t);
case sensor_calibration_request_message_t::ID:
return sizeof(sensor_calibration_request_message_t);
case sensor_calibration_response_message_t::ID:
return sizeof(sensor_calibration_response_message_t);
case location_message_t::ID:
return sizeof(location_message_t);
case imu_message_t::ID:
return sizeof(imu_message_t);
case system_message_t::ID:
return sizeof(system_message_t);
case raw_1000_message_t::ID:
return sizeof(raw_1000_message_t);
case raw_50_message_t::ID:
return sizeof(raw_50_message_t);
case raw_10_message_t::ID:
return sizeof(raw_10_message_t);
case fs_info_message_t::ID:
return sizeof(fs_info_message_t);
}
return 0; // TODO(kyle): Return something more meaningful?
}
}
}
#endif // MESSAGES_HPP_
<commit_msg>Comment message types.<commit_after>#ifndef PROTOCOL_MESSAGES_HPP_
#define PROTOCOL_MESSAGES_HPP_
#include <cstdint>
namespace protocol {
namespace message {
// NOTE: message types indicated with downlink/uplink use
// Heartbeat (down)
struct heartbeat_message_t {
enum { ID = 0x00 };
std::uint8_t seq;
} __attribute__((packed));
// Log (up)
// TODO(syoo): this is unused
struct log_message_t {
enum { ID = 0x01 };
uint32_t time;
char data[100];
} __attribute__((packed));
// Attitude in DCM (down)
struct attitude_message_t {
enum { ID = 0x02 };
uint32_t time;
float dcm[9];
} __attribute__((packed));
// Set arm state (up)
struct set_arm_state_message_t {
enum { ID = 0x03 };
bool armed;
} __attribute__((packed));
// Set control mode (up)
struct set_control_mode_message_t {
enum { ID = 0x04 };
enum class ControlMode {
MANUAL,
OFFBOARD
};
ControlMode mode;
} __attribute__((packed));
// Joystick input (up)
struct offboard_attitude_control_message_t {
enum { ID = 0x05 };
float roll;
float pitch;
float yaw;
float throttle;
uint16_t buttons; // Bitfield of buttons
uint8_t mode;
} __attribute__((packed));
// Throttle (down)
struct motor_throttle_message_t {
enum { ID = 0x06 };
uint32_t time;
float throttles[4];
} __attribute__((packed));
// Sensor calibration request (up)
struct sensor_calibration_request_message_t {
enum { ID = 0x07 };
} __attribute__((packed));
// Sensor calibration response (down)
struct sensor_calibration_response_message_t {
enum { ID = 0x08 };
enum class SensorType {
ACCEL,
GYRO,
MAG
};
SensorType type;
float offsets[3];
} __attribute__((packed));
// Location (down)
struct location_message_t {
enum { ID = 0x09 };
uint32_t time;
float lat;
float lon;
float alt;
} __attribute__((packed));
// IMU (down)
struct imu_message_t {
enum { ID = 0x0a };
uint32_t time;
float gyro[3]; // Gyroscope
float accel[3]; // Accelerometer
} __attribute__((packed));
// System (down)
struct system_message_t {
enum { ID = 0x0b };
uint32_t time;
uint8_t state;
float motorDC; // TODO(yoos): Hack for esra test launch
} __attribute__((packed));
// 1000 Hz stream (down)
struct raw_1000_message_t {
enum { ID = 0x0c };
uint32_t time;
float accel[3]; // Accelerometer
float accelH[3]; // High-g accel
float gyro[3]; // Gyroscope
} __attribute__((packed));
// 50 Hz stream (down)
struct raw_50_message_t {
enum { ID = 0x0d };
uint32_t time;
float bar; // Barometric pressure
float temp; // Temperature
float mag[3]; // Magnetometer
} __attribute((packed));
// 10 Hz stream (down)
struct raw_10_message_t {
enum { ID = 0x0e };
uint32_t time;
bool gps_valid;
float lat;
float lon;
float utc; // UTC time
uint16_t geigerCount; // Number of blips counted since last report
} __attribute((packed));
// Filesystem (down)
struct fs_info_message_t {
enum { ID = 0x0f };
uint32_t time;
char fname[32];
uint32_t fsize;
} __attribute((packed));
inline std::uint16_t length(int id) {
// TODO(kyle): sizeof(empty struct) is 1 in C++...
switch(id) {
case heartbeat_message_t::ID:
return sizeof(heartbeat_message_t);
case log_message_t::ID:
return sizeof(log_message_t);
case attitude_message_t::ID:
return sizeof(attitude_message_t);
case set_arm_state_message_t::ID:
return sizeof(set_arm_state_message_t);
case set_control_mode_message_t::ID:
return sizeof(set_control_mode_message_t);
case offboard_attitude_control_message_t::ID:
return sizeof(offboard_attitude_control_message_t);
case motor_throttle_message_t::ID:
return sizeof(motor_throttle_message_t);
case sensor_calibration_request_message_t::ID:
return sizeof(sensor_calibration_request_message_t);
case sensor_calibration_response_message_t::ID:
return sizeof(sensor_calibration_response_message_t);
case location_message_t::ID:
return sizeof(location_message_t);
case imu_message_t::ID:
return sizeof(imu_message_t);
case system_message_t::ID:
return sizeof(system_message_t);
case raw_1000_message_t::ID:
return sizeof(raw_1000_message_t);
case raw_50_message_t::ID:
return sizeof(raw_50_message_t);
case raw_10_message_t::ID:
return sizeof(raw_10_message_t);
case fs_info_message_t::ID:
return sizeof(fs_info_message_t);
}
return 0; // TODO(kyle): Return something more meaningful?
}
}
}
#endif // MESSAGES_HPP_
<|endoftext|>
|
<commit_before>/*************************************************************************
*
* Copyright (c) 2011-2012 Kohei Yoshida
*
* Permission is hereby granted, free of charge, to any person
* obtaining a copy of this software and associated documentation
* files (the "Software"), to deal in the Software without
* restriction, including without limitation the rights to use,
* copy, modify, merge, publish, distribute, sublicense, and/or sell
* copies of the Software, and to permit persons to whom the
* Software is furnished to do so, subject to the following
* conditions:
*
* The above copyright notice and this permission notice shall be
* included in all copies or substantial portions of the Software.
*
* THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND,
* EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES
* OF MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND
* NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT
* HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY,
* WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING
* FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR
* OTHER DEALINGS IN THE SOFTWARE.
*
************************************************************************/
#ifndef __MDDS_GRID_MAP_COLUMN_HPP__
#define __MDDS_GRID_MAP_COLUMN_HPP__
#include "mdds/default_deleter.hpp"
#include "mdds/compat/unique_ptr.hpp"
#include <vector>
#include <algorithm>
#include <cassert>
#include <boost/noncopyable.hpp>
namespace mdds { namespace __gridmap {
/**
* Each column consists of a series of blocks, and each block stores a
* series of non-empty cells of identical type.
*/
template<typename _Trait>
class column
{
public:
typedef typename _Trait::cell_type cell_type;
typedef typename _Trait::cell_category_type cell_category_type;
typedef typename _Trait::row_key_type row_key_type;
private:
typedef typename _Trait::cell_delete_handler cell_delete_handler;
/**
* Data for non-empty block. Cells are stored here.
*/
struct block_data : boost::noncopyable
{
cell_category_type m_type;
std::vector<cell_type*> m_cells;
block_data(cell_category_type _type, size_t _init_size = 0);
~block_data();
};
/**
* Empty or non-empty block.
*/
struct block : boost::noncopyable
{
row_key_type m_size;
block_data* mp_data;
bool m_empty;
block();
block(row_key_type _size);
~block();
};
column(); // disabled
public:
column(row_key_type max_row);
~column();
void set_cell(row_key_type row, cell_category_type cat, cell_type* cell);
const cell_type* get_cell(row_key_type row) const;
private:
std::vector<block*> m_blocks;
row_key_type m_max_row;
};
template<typename _Trait>
column<_Trait>::block_data::block_data(cell_category_type _type, size_t _init_size) :
m_type(_type), m_cells(_init_size, NULL) {}
template<typename _Trait>
column<_Trait>::block_data::~block_data()
{
std::for_each(m_cells.begin(), m_cells.end(), cell_delete_handler());
}
template<typename _Trait>
column<_Trait>::block::block() : m_size(0), m_empty(true), mp_data(NULL) {}
template<typename _Trait>
column<_Trait>::block::block(row_key_type _size) : m_size(_size), mp_data(NULL), m_empty(true) {}
template<typename _Trait>
column<_Trait>::block::~block()
{
delete mp_data;
}
template<typename _Trait>
column<_Trait>::column(row_key_type max_row) : m_max_row(max_row)
{
// Initialize with an empty block that spans from 0 to max.
m_blocks.push_back(new block(max_row));
}
template<typename _Trait>
column<_Trait>::~column()
{
std::for_each(m_blocks.begin(), m_blocks.end(), default_deleter<block>());
}
template<typename _Trait>
void column<_Trait>::set_cell(row_key_type row, cell_category_type cat, cell_type* cell)
{
unique_ptr<cell_type, cell_delete_handler> p(cell);
// Find the right block ID from the row ID.
row_key_type start_row = 0; // row ID of the first cell in a block.
row_key_type block_index = 0;
for (size_t i = 0, n = m_blocks.size(); i < n; ++i)
{
const block& blk = *m_blocks[i];
if (row < start_row + blk.m_size)
{
// Row is in this block.
block_index = i;
break;
}
// Specified row is not in this block.
start_row += blk.m_size;
}
block& blk = *m_blocks[block_index];
assert(blk.m_size > 0); // block size should never be zero at any time.
if (blk.m_empty)
{
// This is an empty block.
}
else if (blk.mp_data->m_type == cat)
{
// This block is of the same type as the cell being inserted.
}
else if (row == start_row)
{
// Insertion point is at the start of the block.
}
else if (row == (start_row + blk.m_size - 1))
{
// Insertion point is at the end of the block.
}
else
{
// Insertion point is somewhere in the middle of the block.
}
}
template<typename _Trait>
const typename column<_Trait>::cell_type*
column<_Trait>::get_cell(row_key_type row) const
{
row_key_type start_row = 0;
for (size_t i = 0, n = m_blocks.size(); i < n; ++i)
{
const block& blk = *m_blocks[i];
if (row >= start_row + blk.m_size)
{
// Specified row is not in this block.
start_row += blk.m_size;
continue;
}
if (blk.m_empty)
// empty cell block.
return NULL;
assert(row >= start_row);
assert(blk.mp_data); // data for non-empty blocks should never be NULL.
assert(blk.m_size == static_cast<row_key_type>(blk.mp_data->m_cells.size()));
row_key_type idx = row - start_row;
return blk.mp_data->m_cells[idx];
}
return NULL;
}
}}
#endif
<commit_msg>Insertion into a blcok of identical type.<commit_after>/*************************************************************************
*
* Copyright (c) 2011-2012 Kohei Yoshida
*
* Permission is hereby granted, free of charge, to any person
* obtaining a copy of this software and associated documentation
* files (the "Software"), to deal in the Software without
* restriction, including without limitation the rights to use,
* copy, modify, merge, publish, distribute, sublicense, and/or sell
* copies of the Software, and to permit persons to whom the
* Software is furnished to do so, subject to the following
* conditions:
*
* The above copyright notice and this permission notice shall be
* included in all copies or substantial portions of the Software.
*
* THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND,
* EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES
* OF MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND
* NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT
* HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY,
* WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING
* FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR
* OTHER DEALINGS IN THE SOFTWARE.
*
************************************************************************/
#ifndef __MDDS_GRID_MAP_COLUMN_HPP__
#define __MDDS_GRID_MAP_COLUMN_HPP__
#include "mdds/default_deleter.hpp"
#include "mdds/compat/unique_ptr.hpp"
#include <vector>
#include <algorithm>
#include <cassert>
#include <boost/noncopyable.hpp>
namespace mdds { namespace __gridmap {
/**
* Each column consists of a series of blocks, and each block stores a
* series of non-empty cells of identical type.
*/
template<typename _Trait>
class column
{
public:
typedef typename _Trait::cell_type cell_type;
typedef typename _Trait::cell_category_type cell_category_type;
typedef typename _Trait::row_key_type row_key_type;
private:
typedef typename _Trait::cell_delete_handler cell_delete_handler;
/**
* Data for non-empty block. Cells are stored here.
*/
struct block_data : boost::noncopyable
{
cell_category_type m_type;
std::vector<cell_type*> m_cells;
block_data(cell_category_type _type, size_t _init_size = 0);
~block_data();
};
/**
* Empty or non-empty block.
*/
struct block : boost::noncopyable
{
row_key_type m_size;
block_data* mp_data;
bool m_empty;
block();
block(row_key_type _size);
~block();
};
column(); // disabled
public:
column(row_key_type max_row);
~column();
void set_cell(row_key_type row, cell_category_type cat, cell_type* cell);
const cell_type* get_cell(row_key_type row) const;
private:
std::vector<block*> m_blocks;
row_key_type m_max_row;
};
template<typename _Trait>
column<_Trait>::block_data::block_data(cell_category_type _type, size_t _init_size) :
m_type(_type), m_cells(_init_size, NULL) {}
template<typename _Trait>
column<_Trait>::block_data::~block_data()
{
std::for_each(m_cells.begin(), m_cells.end(), cell_delete_handler());
}
template<typename _Trait>
column<_Trait>::block::block() : m_size(0), m_empty(true), mp_data(NULL) {}
template<typename _Trait>
column<_Trait>::block::block(row_key_type _size) : m_size(_size), mp_data(NULL), m_empty(true) {}
template<typename _Trait>
column<_Trait>::block::~block()
{
delete mp_data;
}
template<typename _Trait>
column<_Trait>::column(row_key_type max_row) : m_max_row(max_row)
{
// Initialize with an empty block that spans from 0 to max.
m_blocks.push_back(new block(max_row));
}
template<typename _Trait>
column<_Trait>::~column()
{
std::for_each(m_blocks.begin(), m_blocks.end(), default_deleter<block>());
}
template<typename _Trait>
void column<_Trait>::set_cell(row_key_type row, cell_category_type cat, cell_type* cell)
{
unique_ptr<cell_type, cell_delete_handler> p(cell);
// Find the right block ID from the row ID.
row_key_type start_row = 0; // row ID of the first cell in a block.
row_key_type block_index = 0;
for (size_t i = 0, n = m_blocks.size(); i < n; ++i)
{
const block& blk = *m_blocks[i];
if (row < start_row + blk.m_size)
{
// Row is in this block.
block_index = i;
break;
}
// Specified row is not in this block.
start_row += blk.m_size;
}
block& blk = *m_blocks[block_index];
assert(blk.m_size > 0); // block size should never be zero at any time.
if (blk.m_empty)
{
// This is an empty block.
}
else if (blk.mp_data->m_type == cat)
{
// This block is of the same type as the cell being inserted.
assert(blk.mp_data);
block_data& data = *blk.mp_data;
row_key_type i = row - start_row;
assert(data.m_cells.size() > static_cast<size_t>(i));
delete data.m_cells[i];
data.m_cells[i] = p.release();
}
else if (row == start_row)
{
// Insertion point is at the start of the block.
}
else if (row == (start_row + blk.m_size - 1))
{
// Insertion point is at the end of the block.
}
else
{
// Insertion point is somewhere in the middle of the block.
}
}
template<typename _Trait>
const typename column<_Trait>::cell_type*
column<_Trait>::get_cell(row_key_type row) const
{
row_key_type start_row = 0;
for (size_t i = 0, n = m_blocks.size(); i < n; ++i)
{
const block& blk = *m_blocks[i];
if (row >= start_row + blk.m_size)
{
// Specified row is not in this block.
start_row += blk.m_size;
continue;
}
if (blk.m_empty)
// empty cell block.
return NULL;
assert(row >= start_row);
assert(blk.mp_data); // data for non-empty blocks should never be NULL.
assert(blk.m_size == static_cast<row_key_type>(blk.mp_data->m_cells.size()));
row_key_type idx = row - start_row;
return blk.mp_data->m_cells[idx];
}
return NULL;
}
}}
#endif
<|endoftext|>
|
<commit_before>#ifndef _INCLUDED_INPUT_HPP
#define _INCLUDED_INPUT_HPP
#include <cstddef>
#include <cstdint>
#include <fstream>
#include <iostream>
#include <string>
#include <utility>
#include <vector>
#include <boost/utility/string_ref.hpp>
#include <boost/variant.hpp>
#include <tudocomp/util.h>
#include <tudocomp/io/IOUtil.hpp>
#include <tudocomp/io/ViewStream.hpp>
namespace tudocomp {
namespace io {
struct InputView;
struct InputStream;
/// Represents the input of an algorithm.
///
/// Can be used as either a istream or a memory buffer
/// with the as_stream or as_view methods.
class Input {
struct Memory {
const uint8_t* ptr;
size_t size;
};
struct File {
std::string path;
size_t offset;
};
friend class InputStream;
friend class InputView;
using Variant = boost::variant<Memory, File>;
std::unique_ptr<Variant> m_data;
public:
struct Path { std::string path; };
/// An empty Input
inline Input():
m_data(std::make_unique<Variant>(Memory { nullptr, 0 })) {}
/// Create an copy of the Input, with internal cursors
/// set to the current position
inline Input(const Input& other):
m_data(std::make_unique<Variant>(*other.m_data)) {}
/// Move constructor
inline Input(Input&& other):
m_data(std::move(other.m_data)) {}
/// An Input referring to the contents of a file
Input(Input::Path&& path):
m_data(std::make_unique<Variant>(File { std::move(path.path), 0 })) {}
/// An Input referring to the contents of an vector
Input(const std::vector<uint8_t>& buf):
m_data(std::make_unique<Variant>(Memory { &buf[0], buf.size() })) {}
/// An Input referring to the contents of an string
Input(const boost::string_ref buf):
m_data(std::make_unique<Variant>(
Memory { (const uint8_t*) &buf[0], buf.size() })) {}
Input& operator=(Input&& other) {
m_data = std::move(other.m_data);
return *this;
}
/// DEPRECATED
static Input from_path(std::string path) {
return Input(Path { path });
}
/// DEPRECATED
static Input from_memory(const std::vector<uint8_t>& buf) {
return Input(buf);
}
/// DEPRECATED
static Input from_memory(const boost::string_ref buf) {
return Input(buf);
}
inline InputView as_view();
inline InputStream as_stream();
inline size_t size();
};
struct InputView {
struct Memory {
const uint8_t* ptr;
const size_t size;
};
struct File {
std::vector<uint8_t> buffer;
};
boost::variant<Memory, File> data;
boost::string_ref operator* () {
struct visitor: public boost::static_visitor<boost::string_ref> {
boost::string_ref operator()(InputView::Memory& mem) const {
return boost::string_ref {
(char*) mem.ptr, mem.size
};
}
boost::string_ref operator()(InputView::File& mem) const {
return boost::string_ref {
(char*) mem.buffer.data(), mem.buffer.size()
};
}
};
return boost::apply_visitor(visitor(), data);
}
const uint8_t* mem_ptr() {
struct visitor: public boost::static_visitor<const uint8_t*> {
const uint8_t* operator()(InputView::Memory& mem) const {
return mem.ptr;
}
const uint8_t* operator()(InputView::File& mem) const {
return mem.buffer.data();
}
};
return boost::apply_visitor(visitor(), data);
}
size_t size() {
struct visitor: public boost::static_visitor<size_t> {
size_t operator()(InputView::Memory& mem) const {
return mem.size;
}
size_t operator()(InputView::File& mem) const {
return mem.buffer.size();
}
};
return boost::apply_visitor(visitor(), data);
}
InputView(const InputView* other) = delete;
InputView() = delete;
InputView(InputView::Memory&& mem): data(std::move(mem)) {}
InputView(InputView::File&& s): data(std::move(s)) {}
};
inline InputView Input::as_view() {
struct visitor: public boost::static_visitor<InputView> {
InputView operator()(Input::Memory& mem) const {
Input::Memory mem2 = mem;
// advance view into memory by its whole length
mem.ptr += mem.size;
mem.size = 0;
return InputView {
InputView::Memory { mem2.ptr, mem2.size }
};
}
InputView operator()(Input::File& mem) const {
// read file into buffer starting at current offset
auto buf = read_file_to_stl_byte_container<
std::vector<uint8_t>>(mem.path, mem.offset);
// We read the whole file, so skip it on next read.
mem.offset += buf.size();
return InputView {
InputView::File {
std::move(buf)
}
};
}
};
return boost::apply_visitor(visitor(), *m_data);
};
struct InputStream {
class Memory {
ViewStream m_stream;
Input::Memory* m_offset_back_ref;
size_t m_start_pos;
friend class InputStream;
public:
Memory(ViewStream&& stream, Input::Memory* offset_back_ref):
m_stream(std::move(stream))
{
m_offset_back_ref = offset_back_ref;
m_start_pos = m_stream.stream().tellg();
}
~Memory() {
size_t len = size_t(m_stream.stream().tellg()) - m_start_pos;
m_offset_back_ref->ptr += len;
m_offset_back_ref->size -= len;
}
};
class File {
std::string m_path;
std::unique_ptr<std::ifstream> stream;
Input::File* m_offset_back_ref;
size_t m_start_pos;
File(const File& other) = delete;
File() = delete;
friend class InputStream;
public:
File(std::string&& path,
Input::File* offset_back_ref,
size_t offset)
{
m_path = path;
stream = std::make_unique<std::ifstream>(
m_path, std::ios::in | std::ios::binary);
stream->seekg(offset, std::ios::beg);
m_start_pos = stream->tellg();
m_offset_back_ref = offset_back_ref;
}
File(File&& other) {
stream = std::move(other.stream);
m_offset_back_ref = other.m_offset_back_ref;
m_path = other.m_path;
m_start_pos = other.m_start_pos;
}
~File() {
if (stream != nullptr) {
auto len = size_t(stream->tellg()) - m_start_pos;
m_offset_back_ref->offset += len;
}
}
};
boost::variant<Memory, File> data;
std::istream& operator* () {
struct visitor: public boost::static_visitor<std::istream&> {
std::istream& operator()(InputStream::Memory& m) const {
return m.m_stream.stream();
}
std::istream& operator()(InputStream::File& m) const {
return *m.stream;
}
};
return boost::apply_visitor(visitor(), data);
}
InputStream(const InputStream* other) = delete;
InputStream() = delete;
InputStream(InputStream::Memory&& mem): data(std::move(mem)) {}
InputStream(InputStream::File&& f): data(std::move(f)) {}
};
inline InputStream Input::as_stream() {
struct visitor: public boost::static_visitor<InputStream> {
InputStream operator()(Input::Memory& mem) const {
return InputStream {
InputStream::Memory {
ViewStream {
(char*)mem.ptr,
mem.size
},
&mem
}
};
}
InputStream operator()(Input::File& f) const {
return InputStream {
InputStream::File {
std::string(f.path),
&f,
f.offset,
}
};
}
};
return boost::apply_visitor(visitor(), *m_data);
};
inline size_t Input::size() {
struct visitor: public boost::static_visitor<size_t> {
size_t operator()(Input::Memory& mem) const {
return mem.size;
}
size_t operator()(Input::File& f) const {
return read_file_size(f.path) - f.offset;
}
};
return boost::apply_visitor(visitor(), *m_data);
};
}}
#endif
<commit_msg>Try to fix possible error of move constructor not being picked<commit_after>#ifndef _INCLUDED_INPUT_HPP
#define _INCLUDED_INPUT_HPP
#include <cstddef>
#include <cstdint>
#include <fstream>
#include <iostream>
#include <string>
#include <utility>
#include <vector>
#include <boost/utility/string_ref.hpp>
#include <boost/variant.hpp>
#include <tudocomp/util.h>
#include <tudocomp/io/IOUtil.hpp>
#include <tudocomp/io/ViewStream.hpp>
namespace tudocomp {
namespace io {
struct InputView;
struct InputStream;
/// Represents the input of an algorithm.
///
/// Can be used as either a istream or a memory buffer
/// with the as_stream or as_view methods.
class Input {
struct Memory {
const uint8_t* ptr;
size_t size;
};
struct File {
std::string path;
size_t offset;
};
friend class InputStream;
friend class InputView;
using Variant = boost::variant<Memory, File>;
std::unique_ptr<Variant> m_data;
public:
struct Path { std::string path; };
/// An empty Input
inline Input():
m_data(std::make_unique<Variant>(Memory { nullptr, 0 })) {}
/// Create an copy of the Input, with internal cursors
/// set to the current position
inline Input(const Input& other):
m_data(std::make_unique<Variant>(*other.m_data)) {}
/// Move constructor
inline Input(Input&& other):
m_data(std::move(other.m_data)) {}
/// An Input referring to the contents of a file
Input(Input::Path&& path):
m_data(std::make_unique<Variant>(File { std::move(path.path), 0 })) {}
/// An Input referring to the contents of an vector
Input(const std::vector<uint8_t>& buf):
m_data(std::make_unique<Variant>(Memory { &buf[0], buf.size() })) {}
/// An Input referring to the contents of an string
Input(const boost::string_ref buf):
m_data(std::make_unique<Variant>(
Memory { (const uint8_t*) &buf[0], buf.size() })) {}
Input& operator=(Input&& other) {
m_data = std::move(other.m_data);
return *this;
}
/// DEPRECATED
static Input from_path(std::string path) {
return Input(Path { path });
}
/// DEPRECATED
static Input from_memory(const std::vector<uint8_t>& buf) {
return Input(buf);
}
/// DEPRECATED
static Input from_memory(const boost::string_ref buf) {
return Input(buf);
}
inline InputView as_view();
inline InputStream as_stream();
inline size_t size();
};
struct InputView {
struct Memory {
const uint8_t* ptr;
const size_t size;
};
struct File {
std::vector<uint8_t> buffer;
};
boost::variant<Memory, File> data;
boost::string_ref operator* () {
struct visitor: public boost::static_visitor<boost::string_ref> {
boost::string_ref operator()(InputView::Memory& mem) const {
return boost::string_ref {
(char*) mem.ptr, mem.size
};
}
boost::string_ref operator()(InputView::File& mem) const {
return boost::string_ref {
(char*) mem.buffer.data(), mem.buffer.size()
};
}
};
return boost::apply_visitor(visitor(), data);
}
const uint8_t* mem_ptr() {
struct visitor: public boost::static_visitor<const uint8_t*> {
const uint8_t* operator()(InputView::Memory& mem) const {
return mem.ptr;
}
const uint8_t* operator()(InputView::File& mem) const {
return mem.buffer.data();
}
};
return boost::apply_visitor(visitor(), data);
}
size_t size() {
struct visitor: public boost::static_visitor<size_t> {
size_t operator()(InputView::Memory& mem) const {
return mem.size;
}
size_t operator()(InputView::File& mem) const {
return mem.buffer.size();
}
};
return boost::apply_visitor(visitor(), data);
}
InputView(const InputView* other) = delete;
InputView() = delete;
InputView(InputView::Memory&& mem): data(std::move(mem)) {}
InputView(InputView::File&& s): data(std::move(s)) {}
};
inline InputView Input::as_view() {
struct visitor: public boost::static_visitor<InputView> {
InputView operator()(Input::Memory& mem) const {
Input::Memory mem2 = mem;
// advance view into memory by its whole length
mem.ptr += mem.size;
mem.size = 0;
return InputView {
InputView::Memory { mem2.ptr, mem2.size }
};
}
InputView operator()(Input::File& mem) const {
// read file into buffer starting at current offset
auto buf = read_file_to_stl_byte_container<
std::vector<uint8_t>>(mem.path, mem.offset);
// We read the whole file, so skip it on next read.
mem.offset += buf.size();
return InputView {
InputView::File {
std::move(buf)
}
};
}
};
return boost::apply_visitor(visitor(), *m_data);
};
struct InputStream {
class Memory {
ViewStream m_stream;
Input::Memory* m_offset_back_ref;
size_t m_start_pos;
friend class InputStream;
public:
Memory(ViewStream&& stream, Input::Memory* offset_back_ref):
m_stream(std::move(stream))
{
m_offset_back_ref = offset_back_ref;
m_start_pos = m_stream.stream().tellg();
}
~Memory() {
size_t len = size_t(m_stream.stream().tellg()) - m_start_pos;
m_offset_back_ref->ptr += len;
m_offset_back_ref->size -= len;
}
};
class File {
std::string m_path;
std::unique_ptr<std::ifstream> stream;
Input::File* m_offset_back_ref;
size_t m_start_pos;
File(const File& other) = delete;
File() = delete;
friend class InputStream;
public:
File(std::string&& path,
Input::File* offset_back_ref,
size_t offset)
{
m_path = path;
stream = std::make_unique<std::ifstream>(
m_path, std::ios::in | std::ios::binary);
stream->seekg(offset, std::ios::beg);
m_start_pos = stream->tellg();
m_offset_back_ref = offset_back_ref;
}
File(File&& other) {
stream = std::move(other.stream);
m_offset_back_ref = other.m_offset_back_ref;
m_path = other.m_path;
m_start_pos = other.m_start_pos;
}
~File() {
if (stream != nullptr) {
auto len = size_t(stream->tellg()) - m_start_pos;
m_offset_back_ref->offset += len;
}
}
};
boost::variant<Memory, File> data;
std::istream& operator* () {
struct visitor: public boost::static_visitor<std::istream&> {
std::istream& operator()(InputStream::Memory& m) const {
return m.m_stream.stream();
}
std::istream& operator()(InputStream::File& m) const {
return *m.stream;
}
};
return boost::apply_visitor(visitor(), data);
}
InputStream(const InputStream* other) = delete;
InputStream() = delete;
InputStream(InputStream::Memory&& mem): data(std::move(mem)) {}
InputStream(InputStream::File&& f): data(std::move(f)) {}
};
inline InputStream Input::as_stream() {
struct visitor: public boost::static_visitor<InputStream> {
InputStream operator()(Input::Memory& mem) const {
return InputStream {
InputStream::Memory {
ViewStream {
(char*)mem.ptr,
mem.size
},
&mem
}
};
}
InputStream operator()(Input::File& f) const {
return InputStream {
std::move(InputStream::File {
std::string(f.path),
&f,
f.offset,
})
};
}
};
return boost::apply_visitor(visitor(), *m_data);
};
inline size_t Input::size() {
struct visitor: public boost::static_visitor<size_t> {
size_t operator()(Input::Memory& mem) const {
return mem.size;
}
size_t operator()(Input::File& f) const {
return read_file_size(f.path) - f.offset;
}
};
return boost::apply_visitor(visitor(), *m_data);
};
}}
#endif
<|endoftext|>
|
<commit_before><commit_msg>Work around missing std::underlying_type in GCC 4.6<commit_after><|endoftext|>
|
<commit_before>#ifndef _INCLUDED_DS_LCP_ARRAY_HPP
#define _INCLUDED_DS_LCP_ARRAY_HPP
#include <tudocomp/util.h>
#include <sdsl/rank_support.hpp> // for the rank data structure
#include "forward.hh"
namespace tudocomp {
constexpr int bits = 0;
typedef size_t len_t;
template<class T>
class LCPArray {
typedef sdsl::int_vector<bits> iv_t;
public:
private:
iv_t m_lcp;
len_t m_max;
template <typename sa_t, int U = bits, typename std::enable_if<U == 0,int>::type = 0>
inline void construct_lcp_array(const iv_t& plcp, const sa_t& sa) {
const auto& n = sa.size();
m_max = *std::max_element(plcp.begin(),plcp.end());
m_lcp = iv_t(n, 0, bits_for(m_max));
for(len_t i = 0; i < n; i++) {
DCHECK_LT(sa[i], n);
m_lcp[i] = plcp[sa[i]];
}
for(size_t i = 0; i < m_lcp.size(); ++i) {
DCHECK_EQ(m_lcp[i], plcp[sa[i]]);
}
}
template <typename sa_t, int U = bits, typename std::enable_if<U != 0,int>::type = 0>
inline void construct_lcp_array(const iv_t& plcp, const sa_t& sa) {
const auto& n = sa.size();
m_max = bits_for(*std::max_element(plcp.begin(),plcp.end()));
m_lcp = iv_t(n);
for(len_t i = 0; i < n; i++) {
m_lcp[i] = plcp[sa[i]];
}
}
public:
/**
* Returns the maximum value of the LCP array
*/
inline len_t max_lcp() const {
return m_max;
}
inline iv_t& data() {
return m_lcp;
}
inline const iv_t& data() const {
return m_lcp;
}
inline iv_t::value_type operator[](iv_t::size_type i) const {
return m_lcp[i];
}
inline iv_t::size_type size() const {
return m_lcp.size();
}
inline void construct(T& t);
};
template<
typename T,
typename sa_t,
typename select_t = sdsl::select_support_mcl<1,1>>
class lcp_sada {
typedef sdsl::int_vector<bits> iv_t;
sa_t* sa;
sdsl::bit_vector bv;
select_t s;
public:
inline len_t operator[](len_t i) const;
inline void construct(T& t);
inline len_t size() const;
/**
* Returns the maximum value of the LCP array
*/
inline len_t max_lcp() const {
len_t max = (*this)[0];
for(len_t i = 1; i < sa->size(); ++i) {
max = std::max(max, (*this)[i]);
}
return max;
}
};
}//ns
#include <tudocomp/ds/SuffixArray.hpp>
#include <tudocomp/ds/PhiArray.hpp>
namespace tudocomp {
namespace LCP {
typedef sdsl::int_vector<bits> iv_t;
inline static sdsl::bit_vector construct_lcp_sada(const iv_t& plcp) {
const len_t n = plcp.size();
len_t len = 0;
for(len_t i = 0; i+1 < n; i++) {
DCHECK_GE(plcp[i+1]+1, plcp[i]);
len += plcp[i+1]-plcp[i]+1;
}
sdsl::bit_vector bv(len+2*n,0);
bv[0]=1;
len=0;
for(len_t i = 0; i+1 < n; i++) {
len += plcp[i+1]-plcp[i]+2;
DCHECK_LT(len, bv.size());
bv[len] = 1;
}
return bv;
}
template<typename T>
inline static iv_t phi_algorithm(T& t) {
auto& sa = t.require_sa();
const auto n = sa.size();
t.require_phi();
std::unique_ptr<PhiArray<T>> phi(std::move(t.release_phi()));
iv_t plcp(std::move(phi->data()));
for(len_t i = 0, l = 0; i < n - 1; ++i) {
const len_t phii = plcp[i];
DCHECK_LT(i+l, n);
DCHECK_LT(phii+l, n);
DCHECK_NE(i, phii);
while(t[i+l] == t[phii+l]) {
l++;
DCHECK_LT(i+l, n);
DCHECK_LT(phii+l, n);
}
plcp[i] = l;
if(l) {
--l;
}
}
return plcp;
}
}
template<typename T, typename sa_t, typename select_t>
inline len_t lcp_sada<T,sa_t,select_t>::operator[](len_t i) const {
const len_t idx = (*sa)[i];
return s.select(idx+1) - 2*idx;
}
template<typename T, typename sa_t, typename select_t>
inline void lcp_sada<T,sa_t,select_t>::construct(T& t) {
iv_t plcp(LCP::phi_algorithm(t));
bv(LCP::construct_lcp_sada(plcp));
s.set_vector(&bv);
}
template<typename T, typename sa_t, typename select_t>
inline len_t lcp_sada<T,sa_t,select_t>::size() const {
return sa->size();
}
template<class T>
inline void LCPArray<T>::construct(T& t) {
iv_t plcp(LCP::phi_algorithm(t));
construct_lcp_array(plcp, t.require_sa());
}
}
#endif
<commit_msg>Hotfix for undefined behaviour - Input needs to be *actually* extended by a \0 character, not only for SA generation<commit_after>#ifndef _INCLUDED_DS_LCP_ARRAY_HPP
#define _INCLUDED_DS_LCP_ARRAY_HPP
#include <tudocomp/util.h>
#include <sdsl/rank_support.hpp> // for the rank data structure
#include "forward.hh"
namespace tudocomp {
constexpr int bits = 0;
typedef size_t len_t;
template<class T>
class LCPArray {
typedef sdsl::int_vector<bits> iv_t;
public:
private:
iv_t m_lcp;
len_t m_max;
template <typename sa_t, int U = bits, typename std::enable_if<U == 0,int>::type = 0>
inline void construct_lcp_array(const iv_t& plcp, const sa_t& sa) {
const auto& n = sa.size();
m_max = *std::max_element(plcp.begin(),plcp.end());
m_lcp = iv_t(n, 0, bits_for(m_max));
for(len_t i = 1; i < n; i++) { //TODO: start at 0, see line 149
DCHECK_LT(sa[i], n);
m_lcp[i] = plcp[sa[i]];
}
for(size_t i = 1; i < m_lcp.size(); ++i) { //TODO: start at 0, see line 149
DCHECK_EQ(m_lcp[i], plcp[sa[i]]);
}
}
template <typename sa_t, int U = bits, typename std::enable_if<U != 0,int>::type = 0>
inline void construct_lcp_array(const iv_t& plcp, const sa_t& sa) {
const auto& n = sa.size();
m_max = bits_for(*std::max_element(plcp.begin(),plcp.end()));
m_lcp = iv_t(n);
for(len_t i = 1; i < n; i++) { //TODO: start at 0, see line 149
m_lcp[i] = plcp[sa[i]];
}
}
public:
/**
* Returns the maximum value of the LCP array
*/
inline len_t max_lcp() const {
return m_max;
}
inline iv_t& data() {
return m_lcp;
}
inline const iv_t& data() const {
return m_lcp;
}
inline iv_t::value_type operator[](iv_t::size_type i) const {
return m_lcp[i];
}
inline iv_t::size_type size() const {
return m_lcp.size();
}
inline void construct(T& t);
};
template<
typename T,
typename sa_t,
typename select_t = sdsl::select_support_mcl<1,1>>
class lcp_sada {
typedef sdsl::int_vector<bits> iv_t;
sa_t* sa;
sdsl::bit_vector bv;
select_t s;
public:
inline len_t operator[](len_t i) const;
inline void construct(T& t);
inline len_t size() const;
/**
* Returns the maximum value of the LCP array
*/
inline len_t max_lcp() const {
len_t max = (*this)[0];
for(len_t i = 1; i < sa->size(); ++i) {
max = std::max(max, (*this)[i]);
}
return max;
}
};
}//ns
#include <tudocomp/ds/SuffixArray.hpp>
#include <tudocomp/ds/PhiArray.hpp>
namespace tudocomp {
namespace LCP {
typedef sdsl::int_vector<bits> iv_t;
inline static sdsl::bit_vector construct_lcp_sada(const iv_t& plcp) {
const len_t n = plcp.size();
len_t len = 0;
for(len_t i = 0; i+1 < n; i++) {
DCHECK_GE(plcp[i+1]+1, plcp[i]);
len += plcp[i+1]-plcp[i]+1;
}
sdsl::bit_vector bv(len+2*n,0);
bv[0]=1;
len=0;
for(len_t i = 0; i+1 < n; i++) {
len += plcp[i+1]-plcp[i]+2;
DCHECK_LT(len, bv.size());
bv[len] = 1;
}
return bv;
}
template<typename T>
inline static iv_t phi_algorithm(T& t) {
t.require_phi();
std::unique_ptr<PhiArray<T>> phi(std::move(t.release_phi()));
size_t n = phi->size();
iv_t plcp(std::move(phi->data()));
for(len_t i = 0, l = 0; i < n - 1; ++i) {
const len_t phii = plcp[i];
DCHECK_LT(i+l, n);
DCHECK_LT(phii+l, n);
DCHECK_NE(i, phii);
while(t[i+l] == t[phii+l]) { // !!! UNDEFINED BEHAVIOUR, t[phi.size()-1] is not defined -> InputView needs to be checked
l++;
DCHECK_LT(i+l, n);
DCHECK_LT(phii+l, n);
}
plcp[i] = l;
if(l) {
--l;
}
}
return plcp;
}
}
template<typename T, typename sa_t, typename select_t>
inline len_t lcp_sada<T,sa_t,select_t>::operator[](len_t i) const {
const len_t idx = (*sa)[i];
return s.select(idx+1) - 2*idx;
}
template<typename T, typename sa_t, typename select_t>
inline void lcp_sada<T,sa_t,select_t>::construct(T& t) {
iv_t plcp(LCP::phi_algorithm(t));
bv(LCP::construct_lcp_sada(plcp));
s.set_vector(&bv);
}
template<typename T, typename sa_t, typename select_t>
inline len_t lcp_sada<T,sa_t,select_t>::size() const {
return sa->size();
}
template<class T>
inline void LCPArray<T>::construct(T& t) {
iv_t plcp(LCP::phi_algorithm(t));
construct_lcp_array(plcp, t.require_sa());
}
}
#endif
<|endoftext|>
|
<commit_before>/************************************************************************/
/* */
/* Copyright 1998-2002 by Ullrich Koethe */
/* */
/* This file is part of the VIGRA computer vision library. */
/* The VIGRA Website is */
/* http://hci.iwr.uni-heidelberg.de/vigra/ */
/* Please direct questions, bug reports, and contributions to */
/* ullrich.koethe@iwr.uni-heidelberg.de or */
/* vigra@informatik.uni-hamburg.de */
/* */
/* Permission is hereby granted, free of charge, to any person */
/* obtaining a copy of this software and associated documentation */
/* files (the "Software"), to deal in the Software without */
/* restriction, including without limitation the rights to use, */
/* copy, modify, merge, publish, distribute, sublicense, and/or */
/* sell copies of the Software, and to permit persons to whom the */
/* Software is furnished to do so, subject to the following */
/* conditions: */
/* */
/* The above copyright notice and this permission notice shall be */
/* included in all copies or substantial portions of the */
/* Software. */
/* */
/* THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND */
/* EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES */
/* OF MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND */
/* NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT */
/* HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, */
/* WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING */
/* FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR */
/* OTHER DEALINGS IN THE SOFTWARE. */
/* */
/************************************************************************/
#ifndef VIGRA_ITERATORFACADE_HXX
#define VIGRA_ITERATORFACADE_HXX
/*std*/
#include <iterator>
/*vigra*/
#include "metaprogramming.hxx"
namespace vigra {
// facade needs to make this class
// a friend class
class IteratorFacadeCoreAccess{
public:
template<class F>
static bool equal(const F & fa,const F & fb){
return fa.equal(fb);
}
template<class F,class REFERENCE>
static REFERENCE dereference(const F & f){
return f.dereference();
}
template<class F>
static void increment(F & f){
f.increment();
}
};
// see boost iterator facade
template<class FACADE,class VALUE_TYPE,bool IS_CONST = true>
class ForwardIteratorFacade{
private:
public:
typedef std::forward_iterator_tag iterator_category;
typedef typename UnqualifiedType<VALUE_TYPE>::type value_type;
typedef typename IfBool<IS_CONST, value_type const * , value_type *>::type pointer;
typedef typename IfBool<IS_CONST, const value_type & , value_type &>::type reference;
typedef std::ptrdiff_t difference_type;
FACADE & operator++()
{
IteratorFacadeCoreAccess::increment(getF());
return getF();
}
FACADE operator++(int)
{
FACADE res(getF());
IteratorFacadeCoreAccess::increment(getF());
return res;
}
bool operator ==(const FACADE & f)const{
return IteratorFacadeCoreAccess::equal(getF(),f);
}
bool operator !=(const FACADE & f)const{
return !IteratorFacadeCoreAccess::equal(getF(),f);
}
reference operator*()const{
return IteratorFacadeCoreAccess:: template dereference<FACADE,reference>(getF());
}
pointer operator->()const{
return &IteratorFacadeCoreAccess:: template dereference<FACADE,reference>(getF());
}
private:
const FACADE & getF()const{
return *static_cast<FACADE const *>(this);
}
FACADE & getF(){
return *static_cast<FACADE *>(this);
}
};
} // namespace vigra
#endif /* VIGRA_ITERATORFACADE_HXX */
<commit_msg>added key_begin() and key_end() to iterate over the keys of a std::map (similar to Python's iterkeys)<commit_after>/************************************************************************/
/* */
/* Copyright 1998-2002 by Ullrich Koethe */
/* */
/* This file is part of the VIGRA computer vision library. */
/* The VIGRA Website is */
/* http://hci.iwr.uni-heidelberg.de/vigra/ */
/* Please direct questions, bug reports, and contributions to */
/* ullrich.koethe@iwr.uni-heidelberg.de or */
/* vigra@informatik.uni-hamburg.de */
/* */
/* Permission is hereby granted, free of charge, to any person */
/* obtaining a copy of this software and associated documentation */
/* files (the "Software"), to deal in the Software without */
/* restriction, including without limitation the rights to use, */
/* copy, modify, merge, publish, distribute, sublicense, and/or */
/* sell copies of the Software, and to permit persons to whom the */
/* Software is furnished to do so, subject to the following */
/* conditions: */
/* */
/* The above copyright notice and this permission notice shall be */
/* included in all copies or substantial portions of the */
/* Software. */
/* */
/* THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND */
/* EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES */
/* OF MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND */
/* NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT */
/* HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, */
/* WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING */
/* FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR */
/* OTHER DEALINGS IN THE SOFTWARE. */
/* */
/************************************************************************/
#ifndef VIGRA_ITERATORFACADE_HXX
#define VIGRA_ITERATORFACADE_HXX
/*std*/
#include <iterator>
/*vigra*/
#include "metaprogramming.hxx"
namespace vigra {
// facade needs to make this class
// a friend class
class IteratorFacadeCoreAccess{
public:
template<class F>
static bool equal(const F & fa,const F & fb){
return fa.equal(fb);
}
template<class F,class REFERENCE>
static REFERENCE dereference(const F & f){
return f.dereference();
}
template<class F>
static void increment(F & f){
f.increment();
}
};
// see boost iterator facade
template<class FACADE,class VALUE_TYPE,bool IS_CONST = true>
class ForwardIteratorFacade{
private:
public:
typedef std::forward_iterator_tag iterator_category;
typedef typename UnqualifiedType<VALUE_TYPE>::type value_type;
typedef typename IfBool<IS_CONST, value_type const * , value_type *>::type pointer;
typedef typename IfBool<IS_CONST, const value_type & , value_type &>::type reference;
typedef std::ptrdiff_t difference_type;
FACADE & operator++()
{
IteratorFacadeCoreAccess::increment(getF());
return getF();
}
FACADE operator++(int)
{
FACADE res(getF());
IteratorFacadeCoreAccess::increment(getF());
return res;
}
bool operator ==(const FACADE & f)const{
return IteratorFacadeCoreAccess::equal(getF(),f);
}
bool operator !=(const FACADE & f)const{
return !IteratorFacadeCoreAccess::equal(getF(),f);
}
reference operator*()const{
return IteratorFacadeCoreAccess:: template dereference<FACADE,reference>(getF());
}
pointer operator->()const{
return &IteratorFacadeCoreAccess:: template dereference<FACADE,reference>(getF());
}
private:
const FACADE & getF()const{
return *static_cast<FACADE const *>(this);
}
FACADE & getF(){
return *static_cast<FACADE *>(this);
}
};
template<class MAP>
class MapKeyIterator
: public ForwardIteratorFacade<MapKeyIterator<MAP>,typename MAP::key_type,true>
{
public:
typedef ForwardIteratorFacade<MapKeyIterator<MAP>,typename MAP::key_type,true> BaseType;
typedef typename MAP::const_iterator InternalIterator;
typedef typename BaseType::value_type value_type;
typedef typename BaseType::reference reference;
typedef typename BaseType::pointer pointer;
MapKeyIterator(InternalIterator i)
: iter_(i)
{}
private:
friend class IteratorFacadeCoreAccess;
bool equal(const MapKeyIterator & other) const{
return iter_ == other.iter_;
}
void increment(){
++iter_;
}
reference dereference()const{
return iter_->first;
}
InternalIterator iter_;
};
template <class MAP>
inline MapKeyIterator<MAP>
key_begin(MAP const & m)
{
return MapKeyIterator<MAP>(m.begin());
}
template <class MAP>
inline MapKeyIterator<MAP>
key_end(MAP const & m)
{
return MapKeyIterator<MAP>(m.end());
}
} // namespace vigra
#endif /* VIGRA_ITERATORFACADE_HXX */
<|endoftext|>
|
<commit_before>#include "Python.h"
#include "DippyDecompAlgo.h"
#include "DippyDecompApp.h"
#include "DippyPythonUtils.h"
/**
* Perform branching
*
* This function should populate the (down|up)Branch(LB|UB) vectors with (indices, bound-value) pairs
* which define the branch.
*/
bool DippyAlgoMixin::chooseBranchSet(DecompAlgo *algo, std::vector< std::pair<int, double> > &downBranchLB,
std::vector< std::pair<int, double> > &downBranchUB,
std::vector< std::pair<int, double> > &upBranchLB,
std::vector< std::pair<int, double> > &upBranchUB){
bool ret_val;
if (!m_utilParam->GetSetting("pyBranchMethod", true))
return algo->DecompAlgo::chooseBranchSet(downBranchLB, downBranchUB, upBranchLB, upBranchUB);
DippyDecompApp * app = (DippyDecompApp *)algo->getDecompApp();
// copy the current solution into a Python list
const double *xhat = algo->getXhat();
PyObject *pSolutionList = pyTupleList_FromDoubleArray(xhat, app->m_colList);
// try to call chooseBranchSet on the DipProblem python object
PyObject* pResult = PyObject_CallMethod(m_pProb, "chooseBranchSet", "O", pSolutionList);
if (pResult == NULL) {
//something's gone wrong with the function call, a Python exception has been set
throw UtilException("Error calling method prob.chooseBranchSet()", "chooseBranchSet", "DippyDecompAlgo");
}
// need more error checking/assertion setting here
if (pResult == Py_None) {
// if chooseBranchSet returns None, do default branching for this algo
ret_val = algo->DecompAlgo::chooseBranchSet(downBranchLB, downBranchUB, upBranchLB, upBranchUB);
if (downBranchUB.size() > 0){
PyObject * downBranchVar, * upBranchVar;
pDownUB = PyDict_New();
downBranchVar = PyList_GetItem(app->m_colList, downBranchUB[0].first);
PyDict_SetItem(pDownUB, downBranchVar, PyInt_FromLong(static_cast<int>(round(downBranchUB[0].second))));
pUpLB = PyDict_New();
upBranchVar = PyList_GetItem(app->m_colList, upBranchLB[0].first);
PyDict_SetItem(pUpLB, upBranchVar, PyInt_FromLong(static_cast<int>(round(upBranchLB[0].second))));
assert(downBranchVar == upBranchVar);
}
return ret_val;
}else{
// or else, the function should have returned 4 lists of (name, value) tuples
pDownLB = PyTuple_GetItem(pResult, 0);
pDownUB = PyTuple_GetItem(pResult, 1);
pUpLB = PyTuple_GetItem(pResult, 2);
pUpUB = PyTuple_GetItem(pResult, 3);
// copy the python dictionaries into the result vectors
pyColDict_AsPairedVector(pDownLB, downBranchLB, app->m_colIndices);
pyColDict_AsPairedVector(pDownUB, downBranchUB, app->m_colIndices);
pyColDict_AsPairedVector(pUpLB, upBranchLB, app->m_colIndices);
pyColDict_AsPairedVector(pUpUB, upBranchUB, app->m_colIndices);
return true;
}
}
void DippyAlgoMixin::postProcessBranch(DecompAlgo *algo, DecompStatus decompStatus){
PyObject * pOutput = PyList_New(0);
if (!m_utilParam->GetSetting("pyPostProcessBranch", true))
return;
AlpsDecompTreeNode * node = (AlpsDecompTreeNode *)algo->getCurrentNode();
double quality = node->getQuality();
if (pDownLB != NULL)
addTupleToPyList(pOutput, PyString_FromString("pDownLB"), pDownLB);
if (pDownUB != NULL)
addTupleToPyList(pOutput, PyString_FromString("pDownUB"), pDownUB);
if (pUpLB != NULL)
addTupleToPyList(pOutput, PyString_FromString("pUpLB"), pUpLB);
if (pUpUB != NULL)
addTupleToPyList(pOutput, PyString_FromString("pUpUB"), pUpUB);
addTupleToPyList(pOutput, PyString_FromString("nodeIndex"), PyInt_FromLong(algo->getNodeIndex()));
addTupleToPyList(pOutput, PyString_FromString("nodeQuality"), PyFloat_FromDouble(quality));
PyObject* pResult = PyObject_CallMethod(m_pProb, "postProcessBranch", "O", pOutput);
}
void DippyAlgoMixin::postProcessNode(DecompAlgo * algo, DecompStatus decompStatus) {
if (!m_utilParam->GetSetting("pyPostProcessNode", true))
return;
PyObject * pOutput = pyTupleList_FromNode(algo, decompStatus);
PyObject* pResult = PyObject_CallMethod(m_pProb, "postProcessNode", "O", pOutput);
}
<commit_msg>Fixed bug that left old node bounds "hanging around" when default branch used in Dippy.<commit_after>#include "Python.h"
#include "DippyDecompAlgo.h"
#include "DippyDecompApp.h"
#include "DippyPythonUtils.h"
/**
* Perform branching
*
* This function should populate the (down|up)Branch(LB|UB) vectors with (indices, bound-value) pairs
* which define the branch.
*/
bool DippyAlgoMixin::chooseBranchSet(DecompAlgo *algo, std::vector< std::pair<int, double> > &downBranchLB,
std::vector< std::pair<int, double> > &downBranchUB,
std::vector< std::pair<int, double> > &upBranchLB,
std::vector< std::pair<int, double> > &upBranchUB){
bool ret_val;
if (!m_utilParam->GetSetting("pyBranchMethod", true))
return algo->DecompAlgo::chooseBranchSet(downBranchLB, downBranchUB, upBranchLB, upBranchUB);
DippyDecompApp * app = (DippyDecompApp *)algo->getDecompApp();
// copy the current solution into a Python list
const double *xhat = algo->getXhat();
PyObject *pSolutionList = pyTupleList_FromDoubleArray(xhat, app->m_colList);
// try to call chooseBranchSet on the DipProblem python object
PyObject* pResult = PyObject_CallMethod(m_pProb, "chooseBranchSet", "O", pSolutionList);
if (pResult == NULL) {
//something's gone wrong with the function call, a Python exception has been set
throw UtilException("Error calling method prob.chooseBranchSet()", "chooseBranchSet", "DippyDecompAlgo");
}
// need more error checking/assertion setting here
if (pResult == Py_None) {
// if chooseBranchSet returns None, do default branching for this algo
ret_val = algo->DecompAlgo::chooseBranchSet(downBranchLB, downBranchUB, upBranchLB, upBranchUB);
if (downBranchUB.size() > 0){
PyObject * downBranchVar, * upBranchVar;
pDownLB = PyDict_New(); // Down branch LBs is an empty dictionary
pDownUB = PyDict_New();
downBranchVar = PyList_GetItem(app->m_colList, downBranchUB[0].first);
PyDict_SetItem(pDownUB, downBranchVar, PyInt_FromLong(static_cast<int>(round(downBranchUB[0].second))));
pUpLB = PyDict_New();
upBranchVar = PyList_GetItem(app->m_colList, upBranchLB[0].first);
PyDict_SetItem(pUpLB, upBranchVar, PyInt_FromLong(static_cast<int>(round(upBranchLB[0].second))));
pUpUB = PyDict_New(); // Up branch UBs is an empty dictionary
assert(downBranchVar == upBranchVar);
}
return ret_val;
}else{
// or else, the function should have returned 4 lists of (name, value) tuples
pDownLB = PyTuple_GetItem(pResult, 0);
pDownUB = PyTuple_GetItem(pResult, 1);
pUpLB = PyTuple_GetItem(pResult, 2);
pUpUB = PyTuple_GetItem(pResult, 3);
// copy the python dictionaries into the result vectors
pyColDict_AsPairedVector(pDownLB, downBranchLB, app->m_colIndices);
pyColDict_AsPairedVector(pDownUB, downBranchUB, app->m_colIndices);
pyColDict_AsPairedVector(pUpLB, upBranchLB, app->m_colIndices);
pyColDict_AsPairedVector(pUpUB, upBranchUB, app->m_colIndices);
return true;
}
}
void DippyAlgoMixin::postProcessBranch(DecompAlgo *algo, DecompStatus decompStatus){
PyObject * pOutput = PyList_New(0);
if (!m_utilParam->GetSetting("pyPostProcessBranch", true))
return;
AlpsDecompTreeNode * node = (AlpsDecompTreeNode *)algo->getCurrentNode();
double quality = node->getQuality();
if (pDownLB != NULL)
addTupleToPyList(pOutput, PyString_FromString("pDownLB"), pDownLB);
if (pDownUB != NULL)
addTupleToPyList(pOutput, PyString_FromString("pDownUB"), pDownUB);
if (pUpLB != NULL)
addTupleToPyList(pOutput, PyString_FromString("pUpLB"), pUpLB);
if (pUpUB != NULL)
addTupleToPyList(pOutput, PyString_FromString("pUpUB"), pUpUB);
addTupleToPyList(pOutput, PyString_FromString("nodeIndex"), PyInt_FromLong(algo->getNodeIndex()));
addTupleToPyList(pOutput, PyString_FromString("nodeQuality"), PyFloat_FromDouble(quality));
PyObject* pResult = PyObject_CallMethod(m_pProb, "postProcessBranch", "O", pOutput);
}
void DippyAlgoMixin::postProcessNode(DecompAlgo * algo, DecompStatus decompStatus) {
if (!m_utilParam->GetSetting("pyPostProcessNode", true))
return;
PyObject * pOutput = pyTupleList_FromNode(algo, decompStatus);
PyObject* pResult = PyObject_CallMethod(m_pProb, "postProcessNode", "O", pOutput);
}
<|endoftext|>
|
<commit_before>/**
* @file llfloaterabout.cpp
* @author James Cook
* @brief The about box from Help->About
*
* $LicenseInfo:firstyear=2001&license=viewergpl$
*
* Copyright (c) 2001-2009, Linden Research, Inc.
*
* Second Life Viewer Source Code
* The source code in this file ("Source Code") is provided by Linden Lab
* to you under the terms of the GNU General Public License, version 2.0
* ("GPL"), unless you have obtained a separate licensing agreement
* ("Other License"), formally executed by you and Linden Lab. Terms of
* the GPL can be found in doc/GPL-license.txt in this distribution, or
* online at http://secondlifegrid.net/programs/open_source/licensing/gplv2
*
* There are special exceptions to the terms and conditions of the GPL as
* it is applied to this Source Code. View the full text of the exception
* in the file doc/FLOSS-exception.txt in this software distribution, or
* online at
* http://secondlifegrid.net/programs/open_source/licensing/flossexception
*
* By copying, modifying or distributing this software, you acknowledge
* that you have read and understood your obligations described above,
* and agree to abide by those obligations.
*
* ALL LINDEN LAB SOURCE CODE IS PROVIDED "AS IS." LINDEN LAB MAKES NO
* WARRANTIES, EXPRESS, IMPLIED OR OTHERWISE, REGARDING ITS ACCURACY,
* COMPLETENESS OR PERFORMANCE.
* $/LicenseInfo$
*/
#include "llviewerprecompiledheaders.h"
#include "llfloaterabout.h"
// Viewer includes
#include "llagent.h"
#include "llappviewer.h"
#include "llsecondlifeurls.h"
#include "lluictrlfactory.h"
#include "llviewertexteditor.h"
#include "llviewercontrol.h"
#include "llviewerstats.h"
#include "llviewerregion.h"
#include "llversionviewer.h"
#include "llviewerbuild.h"
#include "llweb.h"
// Linden library includes
#include "llaudioengine.h"
#include "llbutton.h"
#include "llcurl.h"
#include "llglheaders.h"
#include "llfloater.h"
#include "llfloaterreg.h"
#include "llimagej2c.h"
#include "llsys.h"
#include "lltrans.h"
#include "lluri.h"
#include "v3dmath.h"
#include "llwindow.h"
#include "stringize.h"
#include "llsdutil_math.h"
#if LL_WINDOWS
#include "lldxhardware.h"
#endif
extern LLMemoryInfo gSysMemory;
extern U32 gPacketsIn;
static std::string get_viewer_release_notes_url();
///----------------------------------------------------------------------------
/// Class LLFloaterAbout
///----------------------------------------------------------------------------
class LLFloaterAbout
: public LLFloater
{
friend class LLFloaterReg;
private:
LLFloaterAbout(const LLSD& key);
virtual ~LLFloaterAbout();
public:
/*virtual*/ BOOL postBuild();
/// Obtain the data used to fill out the contents string. This is
/// separated so that we can programmatically access the same info.
static LLSD getInfo();
void onClickCopyToClipboard();
};
// Default constructor
LLFloaterAbout::LLFloaterAbout(const LLSD& key)
: LLFloater(key)
{
//LLUICtrlFactory::getInstance()->buildFloater(this, "floater_about.xml");
}
// Destroys the object
LLFloaterAbout::~LLFloaterAbout()
{
}
BOOL LLFloaterAbout::postBuild()
{
center();
LLViewerTextEditor *support_widget =
getChild<LLViewerTextEditor>("support_editor", true);
LLViewerTextEditor *credits_widget =
getChild<LLViewerTextEditor>("credits_editor", true);
getChild<LLUICtrl>("copy_btn")->setCommitCallback(
boost::bind(&LLFloaterAbout::onClickCopyToClipboard, this));
#if LL_WINDOWS
getWindow()->incBusyCount();
getWindow()->setCursor(UI_CURSOR_ARROW);
#endif
LLSD info(getInfo());
#if LL_WINDOWS
getWindow()->decBusyCount();
getWindow()->setCursor(UI_CURSOR_ARROW);
#endif
std::ostringstream support;
// Render the LLSD from getInfo() as a format_map_t
LLStringUtil::format_map_t args;
// For reasons I don't yet understand, [ReleaseNotes] is not part of the
// default substitution strings whereas [APP_NAME] is. But it works to
// simply copy it into these specific args.
args["ReleaseNotes"] = LLTrans::getString("ReleaseNotes");
for (LLSD::map_const_iterator ii(info.beginMap()), iend(info.endMap());
ii != iend; ++ii)
{
if (! ii->second.isArray())
{
// Scalar value
if (ii->second.isUndefined())
{
args[ii->first] = getString("none");
}
else
{
// don't forget to render value asString()
args[ii->first] = ii->second.asString();
}
}
else
{
// array value: build KEY_0, KEY_1 etc. entries
for (LLSD::Integer n(0), size(ii->second.size()); n < size; ++n)
{
args[STRINGIZE(ii->first << '_' << n)] = ii->second[n].asString();
}
}
}
// Now build the various pieces
support << getString("AboutHeader", args);
if (info.has("COMPILER"))
{
support << "\n\n" << getString("AboutCompiler", args);
}
if (info.has("REGION"))
{
support << "\n\n" << getString("AboutPosition", args);
}
support << "\n\n" << getString("AboutSystem", args);
if (info.has("GRAPHICS_DRIVER_VERSION"))
{
support << "\n\n" << getString("AboutDriver", args);
}
support << "\n\n" << getString("AboutLibs", args);
if (info.has("PACKETS_IN"))
{
support << '\n' << getString("AboutTraffic", args);
}
support_widget->appendText(support.str(),
FALSE,
LLStyle::Params()
.color(LLUIColorTable::instance().getColor("TextFgReadOnlyColor")));
support_widget->blockUndo();
// Fix views
support_widget->setCursorPos(0);
support_widget->setEnabled(FALSE);
credits_widget->setCursorPos(0);
credits_widget->setEnabled(FALSE);
return TRUE;
}
// static
LLSD LLFloaterAbout::getInfo()
{
// The point of having one method build an LLSD info block and the other
// construct the user-visible About string is to ensure that the same info
// is available to a getInfo() caller as to the user opening
// LLFloaterAbout.
LLSD info;
LLSD version;
version.append(LL_VERSION_MAJOR);
version.append(LL_VERSION_MINOR);
version.append(LL_VERSION_PATCH);
version.append(LL_VERSION_BUILD);
info["VIEWER_VERSION"] = version;
info["VIEWER_VERSION_STR"] = STRINGIZE(version[0].asInteger() << '.' <<
version[1].asInteger() << '.' <<
version[2].asInteger() << '.' <<
version[3].asInteger());
info["BUILD_DATE"] = __DATE__;
info["BUILD_TIME"] = __TIME__;
info["CHANNEL"] = gSavedSettings.getString("VersionChannelName");
info["VIEWER_RELEASE_NOTES_URL"] = get_viewer_release_notes_url();
#if LL_MSVC
info["COMPILER"] = "MSVC";
info["COMPILER_VERSION"] = _MSC_VER;
#elif LL_GNUC
info["COMPILER"] = "GCC";
info["COMPILER_VERSION"] = GCC_VERSION;
#endif
// Position
LLViewerRegion* region = gAgent.getRegion();
if (region)
{
const LLVector3d &pos = gAgent.getPositionGlobal();
info["POSITION"] = ll_sd_from_vector3d(pos);
info["REGION"] = gAgent.getRegion()->getName();
info["HOSTNAME"] = gAgent.getRegion()->getHost().getHostName();
info["HOSTIP"] = gAgent.getRegion()->getHost().getString();
info["SERVER_VERSION"] = gLastVersionChannel;
info["SERVER_RELEASE_NOTES_URL"] = LLWeb::escapeURL(region->getCapability("ServerReleaseNotes"));
}
// CPU
info["CPU"] = gSysCPU.getCPUString();
info["MEMORY_MB"] = LLSD::Integer(gSysMemory.getPhysicalMemoryKB() / 1024);
// Moved hack adjustment to Windows memory size into llsys.cpp
info["OS_VERSION"] = LLAppViewer::instance()->getOSInfo().getOSString();
info["GRAPHICS_CARD_VENDOR"] = (const char*)(glGetString(GL_VENDOR));
info["GRAPHICS_CARD"] = (const char*)(glGetString(GL_RENDERER));
#if LL_WINDOWS
LLSD driver_info = gDXHardware.getDisplayInfo();
if (driver_info.has("DriverVersion"))
{
info["GRAPHICS_DRIVER_VERSION"] = driver_info["DriverVersion"];
}
#endif
info["OPENGL_VERSION"] = (const char*)(glGetString(GL_VERSION));
info["LIBCURL_VERSION"] = LLCurl::getVersionString();
info["J2C_VERSION"] = LLImageJ2C::getEngineInfo();
bool want_fullname = true;
info["AUDIO_DRIVER_VERSION"] = gAudiop ? LLSD(gAudiop->getDriverName(want_fullname)) : LLSD();
// TODO: Implement media plugin version query
info["QT_WEBKIT_VERSION"] = "4.5.2";
if (gPacketsIn > 0)
{
info["PACKETS_LOST"] = LLViewerStats::getInstance()->mPacketsLostStat.getCurrent();
info["PACKETS_IN"] = F32(gPacketsIn);
info["PACKETS_PCT"] = 100.f*info["PACKETS_LOST"].asReal() / info["PACKETS_IN"].asReal();
}
return info;
}
static std::string get_viewer_release_notes_url()
{
std::ostringstream version;
version << LL_VERSION_MAJOR << "."
<< LL_VERSION_MINOR << "."
<< LL_VERSION_PATCH << "."
<< LL_VERSION_BUILD;
LLSD query;
query["channel"] = gSavedSettings.getString("VersionChannelName");
query["version"] = version.str();
std::ostringstream url;
url << LLTrans::getString("RELEASE_NOTES_BASE_URL") << LLURI::mapToQueryString(query);
return LLWeb::escapeURL(url.str());
}
void LLFloaterAbout::onClickCopyToClipboard()
{
LLViewerTextEditor *support_widget =
getChild<LLViewerTextEditor>("support_editor", true);
support_widget->selectAll();
support_widget->copy();
support_widget->deselect();
}
///----------------------------------------------------------------------------
/// LLFloaterAboutUtil
///----------------------------------------------------------------------------
void LLFloaterAboutUtil::registerFloater()
{
LLFloaterReg::add("sl_about", "floater_about.xml",
&LLFloaterReg::build<LLFloaterAbout>);
}
<commit_msg>DEV-41929: implement event API to query About-box info<commit_after>/**
* @file llfloaterabout.cpp
* @author James Cook
* @brief The about box from Help->About
*
* $LicenseInfo:firstyear=2001&license=viewergpl$
*
* Copyright (c) 2001-2009, Linden Research, Inc.
*
* Second Life Viewer Source Code
* The source code in this file ("Source Code") is provided by Linden Lab
* to you under the terms of the GNU General Public License, version 2.0
* ("GPL"), unless you have obtained a separate licensing agreement
* ("Other License"), formally executed by you and Linden Lab. Terms of
* the GPL can be found in doc/GPL-license.txt in this distribution, or
* online at http://secondlifegrid.net/programs/open_source/licensing/gplv2
*
* There are special exceptions to the terms and conditions of the GPL as
* it is applied to this Source Code. View the full text of the exception
* in the file doc/FLOSS-exception.txt in this software distribution, or
* online at
* http://secondlifegrid.net/programs/open_source/licensing/flossexception
*
* By copying, modifying or distributing this software, you acknowledge
* that you have read and understood your obligations described above,
* and agree to abide by those obligations.
*
* ALL LINDEN LAB SOURCE CODE IS PROVIDED "AS IS." LINDEN LAB MAKES NO
* WARRANTIES, EXPRESS, IMPLIED OR OTHERWISE, REGARDING ITS ACCURACY,
* COMPLETENESS OR PERFORMANCE.
* $/LicenseInfo$
*/
#include "llviewerprecompiledheaders.h"
#include "llfloaterabout.h"
// Viewer includes
#include "llagent.h"
#include "llappviewer.h"
#include "llsecondlifeurls.h"
#include "lluictrlfactory.h"
#include "llviewertexteditor.h"
#include "llviewercontrol.h"
#include "llviewerstats.h"
#include "llviewerregion.h"
#include "llversionviewer.h"
#include "llviewerbuild.h"
#include "llweb.h"
// Linden library includes
#include "llaudioengine.h"
#include "llbutton.h"
#include "llcurl.h"
#include "llglheaders.h"
#include "llfloater.h"
#include "llfloaterreg.h"
#include "llimagej2c.h"
#include "llsys.h"
#include "lltrans.h"
#include "lluri.h"
#include "v3dmath.h"
#include "llwindow.h"
#include "stringize.h"
#include "llsdutil_math.h"
#include "lleventdispatcher.h"
#if LL_WINDOWS
#include "lldxhardware.h"
#endif
extern LLMemoryInfo gSysMemory;
extern U32 gPacketsIn;
static std::string get_viewer_release_notes_url();
///----------------------------------------------------------------------------
/// Class LLFloaterAbout
///----------------------------------------------------------------------------
class LLFloaterAbout
: public LLFloater
{
friend class LLFloaterReg;
private:
LLFloaterAbout(const LLSD& key);
virtual ~LLFloaterAbout();
public:
/*virtual*/ BOOL postBuild();
/// Obtain the data used to fill out the contents string. This is
/// separated so that we can programmatically access the same info.
static LLSD getInfo();
void onClickCopyToClipboard();
};
// Default constructor
LLFloaterAbout::LLFloaterAbout(const LLSD& key)
: LLFloater(key)
{
//LLUICtrlFactory::getInstance()->buildFloater(this, "floater_about.xml");
}
// Destroys the object
LLFloaterAbout::~LLFloaterAbout()
{
}
BOOL LLFloaterAbout::postBuild()
{
center();
LLViewerTextEditor *support_widget =
getChild<LLViewerTextEditor>("support_editor", true);
LLViewerTextEditor *credits_widget =
getChild<LLViewerTextEditor>("credits_editor", true);
getChild<LLUICtrl>("copy_btn")->setCommitCallback(
boost::bind(&LLFloaterAbout::onClickCopyToClipboard, this));
#if LL_WINDOWS
getWindow()->incBusyCount();
getWindow()->setCursor(UI_CURSOR_ARROW);
#endif
LLSD info(getInfo());
#if LL_WINDOWS
getWindow()->decBusyCount();
getWindow()->setCursor(UI_CURSOR_ARROW);
#endif
std::ostringstream support;
// Render the LLSD from getInfo() as a format_map_t
LLStringUtil::format_map_t args;
// For reasons I don't yet understand, [ReleaseNotes] is not part of the
// default substitution strings whereas [APP_NAME] is. But it works to
// simply copy it into these specific args.
args["ReleaseNotes"] = LLTrans::getString("ReleaseNotes");
for (LLSD::map_const_iterator ii(info.beginMap()), iend(info.endMap());
ii != iend; ++ii)
{
if (! ii->second.isArray())
{
// Scalar value
if (ii->second.isUndefined())
{
args[ii->first] = getString("none");
}
else
{
// don't forget to render value asString()
args[ii->first] = ii->second.asString();
}
}
else
{
// array value: build KEY_0, KEY_1 etc. entries
for (LLSD::Integer n(0), size(ii->second.size()); n < size; ++n)
{
args[STRINGIZE(ii->first << '_' << n)] = ii->second[n].asString();
}
}
}
// Now build the various pieces
support << getString("AboutHeader", args);
if (info.has("COMPILER"))
{
support << "\n\n" << getString("AboutCompiler", args);
}
if (info.has("REGION"))
{
support << "\n\n" << getString("AboutPosition", args);
}
support << "\n\n" << getString("AboutSystem", args);
if (info.has("GRAPHICS_DRIVER_VERSION"))
{
support << "\n\n" << getString("AboutDriver", args);
}
support << "\n\n" << getString("AboutLibs", args);
if (info.has("PACKETS_IN"))
{
support << '\n' << getString("AboutTraffic", args);
}
support_widget->appendText(support.str(),
FALSE,
LLStyle::Params()
.color(LLUIColorTable::instance().getColor("TextFgReadOnlyColor")));
support_widget->blockUndo();
// Fix views
support_widget->setCursorPos(0);
support_widget->setEnabled(FALSE);
credits_widget->setCursorPos(0);
credits_widget->setEnabled(FALSE);
return TRUE;
}
// static
LLSD LLFloaterAbout::getInfo()
{
// The point of having one method build an LLSD info block and the other
// construct the user-visible About string is to ensure that the same info
// is available to a getInfo() caller as to the user opening
// LLFloaterAbout.
LLSD info;
LLSD version;
version.append(LL_VERSION_MAJOR);
version.append(LL_VERSION_MINOR);
version.append(LL_VERSION_PATCH);
version.append(LL_VERSION_BUILD);
info["VIEWER_VERSION"] = version;
info["VIEWER_VERSION_STR"] = STRINGIZE(version[0].asInteger() << '.' <<
version[1].asInteger() << '.' <<
version[2].asInteger() << '.' <<
version[3].asInteger());
info["BUILD_DATE"] = __DATE__;
info["BUILD_TIME"] = __TIME__;
info["CHANNEL"] = gSavedSettings.getString("VersionChannelName");
info["VIEWER_RELEASE_NOTES_URL"] = get_viewer_release_notes_url();
#if LL_MSVC
info["COMPILER"] = "MSVC";
info["COMPILER_VERSION"] = _MSC_VER;
#elif LL_GNUC
info["COMPILER"] = "GCC";
info["COMPILER_VERSION"] = GCC_VERSION;
#endif
// Position
LLViewerRegion* region = gAgent.getRegion();
if (region)
{
const LLVector3d &pos = gAgent.getPositionGlobal();
info["POSITION"] = ll_sd_from_vector3d(pos);
info["REGION"] = gAgent.getRegion()->getName();
info["HOSTNAME"] = gAgent.getRegion()->getHost().getHostName();
info["HOSTIP"] = gAgent.getRegion()->getHost().getString();
info["SERVER_VERSION"] = gLastVersionChannel;
info["SERVER_RELEASE_NOTES_URL"] = LLWeb::escapeURL(region->getCapability("ServerReleaseNotes"));
}
// CPU
info["CPU"] = gSysCPU.getCPUString();
info["MEMORY_MB"] = LLSD::Integer(gSysMemory.getPhysicalMemoryKB() / 1024);
// Moved hack adjustment to Windows memory size into llsys.cpp
info["OS_VERSION"] = LLAppViewer::instance()->getOSInfo().getOSString();
info["GRAPHICS_CARD_VENDOR"] = (const char*)(glGetString(GL_VENDOR));
info["GRAPHICS_CARD"] = (const char*)(glGetString(GL_RENDERER));
#if LL_WINDOWS
LLSD driver_info = gDXHardware.getDisplayInfo();
if (driver_info.has("DriverVersion"))
{
info["GRAPHICS_DRIVER_VERSION"] = driver_info["DriverVersion"];
}
#endif
info["OPENGL_VERSION"] = (const char*)(glGetString(GL_VERSION));
info["LIBCURL_VERSION"] = LLCurl::getVersionString();
info["J2C_VERSION"] = LLImageJ2C::getEngineInfo();
bool want_fullname = true;
info["AUDIO_DRIVER_VERSION"] = gAudiop ? LLSD(gAudiop->getDriverName(want_fullname)) : LLSD();
// TODO: Implement media plugin version query
info["QT_WEBKIT_VERSION"] = "4.5.2";
if (gPacketsIn > 0)
{
info["PACKETS_LOST"] = LLViewerStats::getInstance()->mPacketsLostStat.getCurrent();
info["PACKETS_IN"] = F32(gPacketsIn);
info["PACKETS_PCT"] = 100.f*info["PACKETS_LOST"].asReal() / info["PACKETS_IN"].asReal();
}
return info;
}
static std::string get_viewer_release_notes_url()
{
std::ostringstream version;
version << LL_VERSION_MAJOR << "."
<< LL_VERSION_MINOR << "."
<< LL_VERSION_PATCH << "."
<< LL_VERSION_BUILD;
LLSD query;
query["channel"] = gSavedSettings.getString("VersionChannelName");
query["version"] = version.str();
std::ostringstream url;
url << LLTrans::getString("RELEASE_NOTES_BASE_URL") << LLURI::mapToQueryString(query);
return LLWeb::escapeURL(url.str());
}
class LLFloaterAboutListener: public LLDispatchListener
{
public:
LLFloaterAboutListener():
LLDispatchListener("LLFloaterAbout", "op")
{
add("getInfo", &LLFloaterAboutListener::getInfo, LLSD().insert("reply", LLSD()));
}
private:
void getInfo(const LLSD& request) const
{
LLReqID reqid(request);
LLSD reply(LLFloaterAbout::getInfo());
reqid.stamp(reply);
LLEventPumps::instance().obtain(request["reply"]).post(reply);
}
};
static LLFloaterAboutListener floaterAboutListener;
void LLFloaterAbout::onClickCopyToClipboard()
{
LLViewerTextEditor *support_widget =
getChild<LLViewerTextEditor>("support_editor", true);
support_widget->selectAll();
support_widget->copy();
support_widget->deselect();
}
///----------------------------------------------------------------------------
/// LLFloaterAboutUtil
///----------------------------------------------------------------------------
void LLFloaterAboutUtil::registerFloater()
{
LLFloaterReg::add("sl_about", "floater_about.xml",
&LLFloaterReg::build<LLFloaterAbout>);
}
<|endoftext|>
|
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.