text
stringlengths 54
60.6k
|
---|
<commit_before>// Copyright Verizon Media. Licensed under the terms of the Apache 2.0 license. See LICENSE in the project root.
#include "generic_reduce.h"
#include <vespa/eval/eval/value.h>
#include <vespa/eval/eval/wrap_param.h>
#include <vespa/eval/eval/array_array_map.h>
#include <vespa/vespalib/util/stash.h>
#include <vespa/vespalib/util/typify.h>
#include <vespa/vespalib/util/overload.h>
#include <vespa/vespalib/util/visit_ranges.h>
#include <cassert>
using namespace vespalib::eval::tensor_function;
namespace vespalib::eval::instruction {
using State = InterpretedFunction::State;
using Instruction = InterpretedFunction::Instruction;
namespace {
//-----------------------------------------------------------------------------
struct ReduceParam {
ValueType res_type;
SparseReducePlan sparse_plan;
DenseReducePlan dense_plan;
const ValueBuilderFactory &factory;
ReduceParam(const ValueType &type, const std::vector<vespalib::string> &dimensions,
const ValueBuilderFactory &factory_in)
: res_type(type.reduce(dimensions)),
sparse_plan(type, res_type),
dense_plan(type, res_type),
factory(factory_in)
{
assert(!res_type.is_error());
assert(dense_plan.in_size == type.dense_subspace_size());
assert(dense_plan.out_size == res_type.dense_subspace_size());
}
~ReduceParam();
};
ReduceParam::~ReduceParam() = default;
//-----------------------------------------------------------------------------
struct SparseReduceState {
std::vector<vespalib::stringref> full_address;
std::vector<vespalib::stringref*> fetch_address;
std::vector<vespalib::stringref*> keep_address;
size_t subspace;
SparseReduceState(const SparseReducePlan &plan)
: full_address(plan.keep_dims.size() + plan.num_reduce_dims),
fetch_address(full_address.size(), nullptr),
keep_address(plan.keep_dims.size(), nullptr),
subspace()
{
for (size_t i = 0; i < keep_address.size(); ++i) {
keep_address[i] = &full_address[plan.keep_dims[i]];
}
for (size_t i = 0; i < full_address.size(); ++i) {
fetch_address[i] = &full_address[i];
}
}
~SparseReduceState();
};
SparseReduceState::~SparseReduceState() = default;
template <typename ICT, typename OCT, typename AGGR>
Value::UP
generic_reduce(const Value &value, const ReduceParam ¶m) {
auto cells = value.cells().typify<ICT>();
ArrayArrayMap<vespalib::stringref,AGGR> map(param.sparse_plan.keep_dims.size(),
param.dense_plan.out_size,
value.index().size());
SparseReduceState sparse(param.sparse_plan);
auto full_view = value.index().create_view({});
full_view->lookup({});
ConstArrayRef<vespalib::stringref*> keep_addr(sparse.keep_address);
while (full_view->next_result(sparse.fetch_address, sparse.subspace)) {
auto [tag, ignore] = map.lookup_or_add_entry(keep_addr);
AGGR *dst = map.get_values(tag).begin();
auto sample = [&](size_t src_idx, size_t dst_idx) { dst[dst_idx].sample(cells[src_idx]); };
param.dense_plan.execute(sparse.subspace * param.dense_plan.in_size, sample);
}
auto builder = param.factory.create_value_builder<OCT>(param.res_type, param.sparse_plan.keep_dims.size(), param.dense_plan.out_size, map.size());
map.each_entry([&](const auto &keys, const auto &values)
{
OCT *dst = builder->add_subspace(keys).begin();
for (const AGGR &aggr: values) {
*dst++ = aggr.result();
}
});
if ((map.size() == 0) && param.sparse_plan.keep_dims.empty()) {
auto zero = builder->add_subspace({});
for (size_t i = 0; i < zero.size(); ++i) {
zero[i] = OCT{};
}
}
return builder->build(std::move(builder));
}
template <typename ICT, typename OCT, typename AGGR>
void my_generic_reduce_op(State &state, uint64_t param_in) {
const auto ¶m = unwrap_param<ReduceParam>(param_in);
const Value &value = state.peek(0);
auto up = generic_reduce<ICT, OCT, AGGR>(value, param);
auto &result = state.stash.create<std::unique_ptr<Value>>(std::move(up));
const Value &result_ref = *(result.get());
state.pop_push(result_ref);
};
template <typename ICT, typename OCT, typename AGGR>
void my_full_reduce_op(State &state, uint64_t) {
auto cells = state.peek(0).cells().typify<ICT>();
if (cells.size() > 0) {
AGGR aggr;
for (ICT value: cells) {
aggr.sample(value);
}
state.pop_push(state.stash.create<ScalarValue<OCT>>(aggr.result()));
} else {
state.pop_push(state.stash.create<ScalarValue<OCT>>(OCT{0}));
}
};
struct SelectGenericReduceOp {
template <typename ICT, typename OCT, typename AGGR> static auto invoke(const ReduceParam ¶m) {
if (param.res_type.is_scalar()) {
return my_full_reduce_op<ICT, OCT, typename AGGR::template templ<OCT>>;
}
return my_generic_reduce_op<ICT, OCT, typename AGGR::template templ<OCT>>;
}
};
struct PerformGenericReduce {
template <typename ICT, typename OCT, typename AGGR>
static auto invoke(const Value &input, const ReduceParam ¶m) {
return generic_reduce<ICT, OCT, typename AGGR::template templ<OCT>>(input, param);
}
};
//-----------------------------------------------------------------------------
} // namespace <unnamed>
//-----------------------------------------------------------------------------
DenseReducePlan::DenseReducePlan(const ValueType &type, const ValueType &res_type)
: in_size(1),
out_size(1),
loop_cnt(),
in_stride(),
out_stride()
{
enum class Case { NONE, KEEP, REDUCE };
Case prev_case = Case::NONE;
auto update_plan = [&](Case my_case, size_t my_size) {
if (my_case == prev_case) {
assert(!loop_cnt.empty());
loop_cnt.back() *= my_size;
} else {
loop_cnt.push_back(my_size);
in_stride.push_back(1);
out_stride.push_back((my_case == Case::KEEP) ? 1 : 0);
prev_case = my_case;
}
};
auto visitor = overload
{
[&](visit_ranges_either, const auto &a) { update_plan(Case::REDUCE, a.size); },
[&](visit_ranges_both, const auto &a, const auto &) { update_plan(Case::KEEP, a.size); }
};
auto in_dims = type.nontrivial_indexed_dimensions();
auto out_dims = res_type.nontrivial_indexed_dimensions();
visit_ranges(visitor, in_dims.begin(), in_dims.end(), out_dims.begin(), out_dims.end(),
[](const auto &a, const auto &b){ return (a.name < b.name); });
for (size_t i = loop_cnt.size(); i-- > 0; ) {
in_stride[i] = in_size;
in_size *= loop_cnt[i];
if (out_stride[i] != 0) {
out_stride[i] = out_size;
out_size *= loop_cnt[i];
}
}
for (size_t i = 1; i < loop_cnt.size(); ++i) {
for (size_t j = i; j > 0; --j) {
if ((out_stride[j] == 0) && (out_stride[j - 1] > 0)) {
std::swap(loop_cnt[j], loop_cnt[j - 1]);
std::swap(in_stride[j], in_stride[j - 1]);
std::swap(out_stride[j], out_stride[j - 1]);
}
}
}
}
DenseReducePlan::~DenseReducePlan() = default;
//-----------------------------------------------------------------------------
SparseReducePlan::SparseReducePlan(const ValueType &type, const ValueType &res_type)
: num_reduce_dims(0),
keep_dims()
{
auto dims = type.mapped_dimensions();
for (size_t i = 0; i < dims.size(); ++i) {
bool keep = (res_type.dimension_index(dims[i].name) != ValueType::Dimension::npos);
if (keep) {
keep_dims.push_back(i);
} else {
++num_reduce_dims;
}
}
}
SparseReducePlan::~SparseReducePlan() = default;
//-----------------------------------------------------------------------------
using ReduceTypify = TypifyValue<TypifyCellType,TypifyAggr>;
Instruction
GenericReduce::make_instruction(const ValueType &type, Aggr aggr, const std::vector<vespalib::string> &dimensions,
const ValueBuilderFactory &factory, Stash &stash)
{
auto ¶m = stash.create<ReduceParam>(type, dimensions, factory);
auto fun = typify_invoke<3,ReduceTypify,SelectGenericReduceOp>(type.cell_type(), param.res_type.cell_type(), aggr, param);
return Instruction(fun, wrap_param<ReduceParam>(param));
}
Value::UP
GenericReduce::perform_reduce(const Value &a, Aggr aggr,
const std::vector<vespalib::string> &dimensions,
const ValueBuilderFactory &factory)
{
ReduceParam param(a.type(), dimensions, factory);
return typify_invoke<3,ReduceTypify,PerformGenericReduce>(
a.type().cell_type(), param.res_type.cell_type(), aggr,
a, param);
}
} // namespace
<commit_msg>unroll full reduce inner loop<commit_after>// Copyright Verizon Media. Licensed under the terms of the Apache 2.0 license. See LICENSE in the project root.
#include "generic_reduce.h"
#include <vespa/eval/eval/value.h>
#include <vespa/eval/eval/wrap_param.h>
#include <vespa/eval/eval/array_array_map.h>
#include <vespa/vespalib/util/stash.h>
#include <vespa/vespalib/util/typify.h>
#include <vespa/vespalib/util/overload.h>
#include <vespa/vespalib/util/visit_ranges.h>
#include <cassert>
using namespace vespalib::eval::tensor_function;
namespace vespalib::eval::instruction {
using State = InterpretedFunction::State;
using Instruction = InterpretedFunction::Instruction;
namespace {
//-----------------------------------------------------------------------------
struct ReduceParam {
ValueType res_type;
SparseReducePlan sparse_plan;
DenseReducePlan dense_plan;
const ValueBuilderFactory &factory;
ReduceParam(const ValueType &type, const std::vector<vespalib::string> &dimensions,
const ValueBuilderFactory &factory_in)
: res_type(type.reduce(dimensions)),
sparse_plan(type, res_type),
dense_plan(type, res_type),
factory(factory_in)
{
assert(!res_type.is_error());
assert(dense_plan.in_size == type.dense_subspace_size());
assert(dense_plan.out_size == res_type.dense_subspace_size());
}
~ReduceParam();
};
ReduceParam::~ReduceParam() = default;
//-----------------------------------------------------------------------------
struct SparseReduceState {
std::vector<vespalib::stringref> full_address;
std::vector<vespalib::stringref*> fetch_address;
std::vector<vespalib::stringref*> keep_address;
size_t subspace;
SparseReduceState(const SparseReducePlan &plan)
: full_address(plan.keep_dims.size() + plan.num_reduce_dims),
fetch_address(full_address.size(), nullptr),
keep_address(plan.keep_dims.size(), nullptr),
subspace()
{
for (size_t i = 0; i < keep_address.size(); ++i) {
keep_address[i] = &full_address[plan.keep_dims[i]];
}
for (size_t i = 0; i < full_address.size(); ++i) {
fetch_address[i] = &full_address[i];
}
}
~SparseReduceState();
};
SparseReduceState::~SparseReduceState() = default;
template <typename ICT, typename OCT, typename AGGR>
Value::UP
generic_reduce(const Value &value, const ReduceParam ¶m) {
auto cells = value.cells().typify<ICT>();
ArrayArrayMap<vespalib::stringref,AGGR> map(param.sparse_plan.keep_dims.size(),
param.dense_plan.out_size,
value.index().size());
SparseReduceState sparse(param.sparse_plan);
auto full_view = value.index().create_view({});
full_view->lookup({});
ConstArrayRef<vespalib::stringref*> keep_addr(sparse.keep_address);
while (full_view->next_result(sparse.fetch_address, sparse.subspace)) {
auto [tag, ignore] = map.lookup_or_add_entry(keep_addr);
AGGR *dst = map.get_values(tag).begin();
auto sample = [&](size_t src_idx, size_t dst_idx) { dst[dst_idx].sample(cells[src_idx]); };
param.dense_plan.execute(sparse.subspace * param.dense_plan.in_size, sample);
}
auto builder = param.factory.create_value_builder<OCT>(param.res_type, param.sparse_plan.keep_dims.size(), param.dense_plan.out_size, map.size());
map.each_entry([&](const auto &keys, const auto &values)
{
OCT *dst = builder->add_subspace(keys).begin();
for (const AGGR &aggr: values) {
*dst++ = aggr.result();
}
});
if ((map.size() == 0) && param.sparse_plan.keep_dims.empty()) {
auto zero = builder->add_subspace({});
for (size_t i = 0; i < zero.size(); ++i) {
zero[i] = OCT{};
}
}
return builder->build(std::move(builder));
}
template <typename ICT, typename OCT, typename AGGR>
void my_generic_reduce_op(State &state, uint64_t param_in) {
const auto ¶m = unwrap_param<ReduceParam>(param_in);
const Value &value = state.peek(0);
auto up = generic_reduce<ICT, OCT, AGGR>(value, param);
auto &result = state.stash.create<std::unique_ptr<Value>>(std::move(up));
const Value &result_ref = *(result.get());
state.pop_push(result_ref);
};
template <typename ICT, typename OCT, typename AGGR>
void my_full_reduce_op(State &state, uint64_t) {
auto cells = state.peek(0).cells().typify<ICT>();
if (cells.size() >= 8) {
std::array<AGGR,8> aggrs = { AGGR(cells[0]), AGGR(cells[1]), AGGR(cells[2]), AGGR(cells[3]),
AGGR(cells[4]), AGGR(cells[5]), AGGR(cells[6]), AGGR(cells[7]) };
size_t i = 8;
for (; (i + 7) < cells.size(); i += 8) {
for (size_t j = 0; j < 8; ++j) {
aggrs[j].sample(cells[i + j]);
}
}
for (size_t j = 0; (i + j) < cells.size(); ++j) {
aggrs[j].sample(cells[i + j]);
}
aggrs[0].merge(aggrs[4]);
aggrs[1].merge(aggrs[5]);
aggrs[2].merge(aggrs[6]);
aggrs[3].merge(aggrs[7]);
aggrs[0].merge(aggrs[2]);
aggrs[1].merge(aggrs[3]);
aggrs[0].merge(aggrs[1]);
state.pop_push(state.stash.create<ScalarValue<OCT>>(aggrs[0].result()));
} else if (cells.size() > 0) {
AGGR aggr;
for (ICT value: cells) {
aggr.sample(value);
}
state.pop_push(state.stash.create<ScalarValue<OCT>>(aggr.result()));
} else {
state.pop_push(state.stash.create<ScalarValue<OCT>>(OCT{0}));
}
};
struct SelectGenericReduceOp {
template <typename ICT, typename OCT, typename AGGR> static auto invoke(const ReduceParam ¶m) {
if (param.res_type.is_scalar()) {
return my_full_reduce_op<ICT, OCT, typename AGGR::template templ<OCT>>;
}
return my_generic_reduce_op<ICT, OCT, typename AGGR::template templ<OCT>>;
}
};
struct PerformGenericReduce {
template <typename ICT, typename OCT, typename AGGR>
static auto invoke(const Value &input, const ReduceParam ¶m) {
return generic_reduce<ICT, OCT, typename AGGR::template templ<OCT>>(input, param);
}
};
//-----------------------------------------------------------------------------
} // namespace <unnamed>
//-----------------------------------------------------------------------------
DenseReducePlan::DenseReducePlan(const ValueType &type, const ValueType &res_type)
: in_size(1),
out_size(1),
loop_cnt(),
in_stride(),
out_stride()
{
enum class Case { NONE, KEEP, REDUCE };
Case prev_case = Case::NONE;
auto update_plan = [&](Case my_case, size_t my_size) {
if (my_case == prev_case) {
assert(!loop_cnt.empty());
loop_cnt.back() *= my_size;
} else {
loop_cnt.push_back(my_size);
in_stride.push_back(1);
out_stride.push_back((my_case == Case::KEEP) ? 1 : 0);
prev_case = my_case;
}
};
auto visitor = overload
{
[&](visit_ranges_either, const auto &a) { update_plan(Case::REDUCE, a.size); },
[&](visit_ranges_both, const auto &a, const auto &) { update_plan(Case::KEEP, a.size); }
};
auto in_dims = type.nontrivial_indexed_dimensions();
auto out_dims = res_type.nontrivial_indexed_dimensions();
visit_ranges(visitor, in_dims.begin(), in_dims.end(), out_dims.begin(), out_dims.end(),
[](const auto &a, const auto &b){ return (a.name < b.name); });
for (size_t i = loop_cnt.size(); i-- > 0; ) {
in_stride[i] = in_size;
in_size *= loop_cnt[i];
if (out_stride[i] != 0) {
out_stride[i] = out_size;
out_size *= loop_cnt[i];
}
}
for (size_t i = 1; i < loop_cnt.size(); ++i) {
for (size_t j = i; j > 0; --j) {
if ((out_stride[j] == 0) && (out_stride[j - 1] > 0)) {
std::swap(loop_cnt[j], loop_cnt[j - 1]);
std::swap(in_stride[j], in_stride[j - 1]);
std::swap(out_stride[j], out_stride[j - 1]);
}
}
}
}
DenseReducePlan::~DenseReducePlan() = default;
//-----------------------------------------------------------------------------
SparseReducePlan::SparseReducePlan(const ValueType &type, const ValueType &res_type)
: num_reduce_dims(0),
keep_dims()
{
auto dims = type.mapped_dimensions();
for (size_t i = 0; i < dims.size(); ++i) {
bool keep = (res_type.dimension_index(dims[i].name) != ValueType::Dimension::npos);
if (keep) {
keep_dims.push_back(i);
} else {
++num_reduce_dims;
}
}
}
SparseReducePlan::~SparseReducePlan() = default;
//-----------------------------------------------------------------------------
using ReduceTypify = TypifyValue<TypifyCellType,TypifyAggr>;
Instruction
GenericReduce::make_instruction(const ValueType &type, Aggr aggr, const std::vector<vespalib::string> &dimensions,
const ValueBuilderFactory &factory, Stash &stash)
{
auto ¶m = stash.create<ReduceParam>(type, dimensions, factory);
auto fun = typify_invoke<3,ReduceTypify,SelectGenericReduceOp>(type.cell_type(), param.res_type.cell_type(), aggr, param);
return Instruction(fun, wrap_param<ReduceParam>(param));
}
Value::UP
GenericReduce::perform_reduce(const Value &a, Aggr aggr,
const std::vector<vespalib::string> &dimensions,
const ValueBuilderFactory &factory)
{
ReduceParam param(a.type(), dimensions, factory);
return typify_invoke<3,ReduceTypify,PerformGenericReduce>(
a.type().cell_type(), param.res_type.cell_type(), aggr,
a, param);
}
} // namespace
<|endoftext|>
|
<commit_before>// Copyright Verizon Media. Licensed under the terms of the Apache 2.0 license. See LICENSE in the project root.
#include "generic_reduce.h"
#include <vespa/eval/eval/value.h>
#include <vespa/eval/eval/wrap_param.h>
#include <vespa/eval/eval/array_array_map.h>
#include <vespa/vespalib/util/stash.h>
#include <vespa/vespalib/util/typify.h>
#include <vespa/vespalib/util/overload.h>
#include <vespa/vespalib/util/visit_ranges.h>
#include <cassert>
using namespace vespalib::eval::tensor_function;
namespace vespalib::eval::instruction {
using State = InterpretedFunction::State;
using Instruction = InterpretedFunction::Instruction;
namespace {
//-----------------------------------------------------------------------------
struct ReduceParam {
ValueType res_type;
SparseReducePlan sparse_plan;
DenseReducePlan dense_plan;
const ValueBuilderFactory &factory;
ReduceParam(const ValueType &type, const std::vector<vespalib::string> &dimensions,
const ValueBuilderFactory &factory_in)
: res_type(type.reduce(dimensions)),
sparse_plan(type, res_type),
dense_plan(type, res_type),
factory(factory_in)
{
assert(!res_type.is_error());
assert(dense_plan.in_size == type.dense_subspace_size());
assert(dense_plan.out_size == res_type.dense_subspace_size());
}
~ReduceParam();
};
ReduceParam::~ReduceParam() = default;
//-----------------------------------------------------------------------------
struct SparseReduceState {
std::vector<vespalib::stringref> full_address;
std::vector<vespalib::stringref*> fetch_address;
std::vector<vespalib::stringref*> keep_address;
size_t subspace;
SparseReduceState(const SparseReducePlan &plan)
: full_address(plan.keep_dims.size() + plan.num_reduce_dims),
fetch_address(full_address.size(), nullptr),
keep_address(plan.keep_dims.size(), nullptr),
subspace()
{
for (size_t i = 0; i < keep_address.size(); ++i) {
keep_address[i] = &full_address[plan.keep_dims[i]];
}
for (size_t i = 0; i < full_address.size(); ++i) {
fetch_address[i] = &full_address[i];
}
}
~SparseReduceState();
};
SparseReduceState::~SparseReduceState() = default;
template <typename ICT, typename OCT, typename AGGR>
Value::UP
generic_reduce(const Value &value, const ReduceParam ¶m) {
auto cells = value.cells().typify<ICT>();
ArrayArrayMap<vespalib::stringref,AGGR> map(param.sparse_plan.keep_dims.size(),
param.dense_plan.out_size,
value.index().size());
SparseReduceState sparse(param.sparse_plan);
auto full_view = value.index().create_view({});
full_view->lookup({});
ConstArrayRef<vespalib::stringref*> keep_addr(sparse.keep_address);
while (full_view->next_result(sparse.fetch_address, sparse.subspace)) {
auto [tag, ignore] = map.lookup_or_add_entry(keep_addr);
AGGR *dst = map.get_values(tag).begin();
auto sample = [&](size_t src_idx, size_t dst_idx) { dst[dst_idx].sample(cells[src_idx]); };
param.dense_plan.execute(sparse.subspace * param.dense_plan.in_size, sample);
}
auto builder = param.factory.create_value_builder<OCT>(param.res_type, param.sparse_plan.keep_dims.size(), param.dense_plan.out_size, map.size());
map.each_entry([&](const auto &keys, const auto &values)
{
OCT *dst = builder->add_subspace(keys).begin();
for (const AGGR &aggr: values) {
*dst++ = aggr.result();
}
});
if ((map.size() == 0) && param.sparse_plan.keep_dims.empty()) {
auto zero = builder->add_subspace({});
for (size_t i = 0; i < zero.size(); ++i) {
zero[i] = OCT{};
}
}
return builder->build(std::move(builder));
}
template <typename ICT, typename OCT, typename AGGR>
void my_generic_reduce_op(State &state, uint64_t param_in) {
const auto ¶m = unwrap_param<ReduceParam>(param_in);
const Value &value = state.peek(0);
auto up = generic_reduce<ICT, OCT, AGGR>(value, param);
auto &result = state.stash.create<std::unique_ptr<Value>>(std::move(up));
const Value &result_ref = *(result.get());
state.pop_push(result_ref);
};
template <typename ICT, typename OCT, typename AGGR>
void my_full_reduce_op(State &state, uint64_t) {
auto cells = state.peek(0).cells().typify<ICT>();
if (cells.size() > 0) {
AGGR aggr;
for (ICT value: cells) {
aggr.sample(value);
}
state.pop_push(state.stash.create<ScalarValue<OCT>>(aggr.result()));
} else {
state.pop_push(state.stash.create<ScalarValue<OCT>>(OCT{0}));
}
};
struct SelectGenericReduceOp {
template <typename ICT, typename OCT, typename AGGR> static auto invoke(const ReduceParam ¶m) {
if (param.res_type.is_scalar()) {
return my_full_reduce_op<ICT, OCT, typename AGGR::template templ<ICT>>;
}
return my_generic_reduce_op<ICT, OCT, typename AGGR::template templ<ICT>>;
}
};
struct PerformGenericReduce {
template <typename ICT, typename OCT, typename AGGR>
static auto invoke(const Value &input, const ReduceParam ¶m) {
return generic_reduce<ICT, OCT, typename AGGR::template templ<ICT>>(input, param);
}
};
//-----------------------------------------------------------------------------
} // namespace <unnamed>
//-----------------------------------------------------------------------------
DenseReducePlan::DenseReducePlan(const ValueType &type, const ValueType &res_type)
: in_size(1),
out_size(1),
loop_cnt(),
in_stride(),
out_stride()
{
enum class Case { NONE, KEEP, REDUCE };
Case prev_case = Case::NONE;
auto update_plan = [&](Case my_case, size_t my_size) {
if (my_case == prev_case) {
assert(!loop_cnt.empty());
loop_cnt.back() *= my_size;
} else {
loop_cnt.push_back(my_size);
in_stride.push_back(1);
out_stride.push_back((my_case == Case::KEEP) ? 1 : 0);
prev_case = my_case;
}
};
auto visitor = overload
{
[&](visit_ranges_either, const auto &a) { update_plan(Case::REDUCE, a.size); },
[&](visit_ranges_both, const auto &a, const auto &) { update_plan(Case::KEEP, a.size); }
};
auto in_dims = type.nontrivial_indexed_dimensions();
auto out_dims = res_type.nontrivial_indexed_dimensions();
visit_ranges(visitor, in_dims.begin(), in_dims.end(), out_dims.begin(), out_dims.end(),
[](const auto &a, const auto &b){ return (a.name < b.name); });
for (size_t i = loop_cnt.size(); i-- > 0; ) {
in_stride[i] = in_size;
in_size *= loop_cnt[i];
if (out_stride[i] != 0) {
out_stride[i] = out_size;
out_size *= loop_cnt[i];
}
}
for (size_t i = 1; i < loop_cnt.size(); ++i) {
for (size_t j = i; j > 0; --j) {
if ((out_stride[j] == 0) && (out_stride[j - 1] > 0)) {
std::swap(loop_cnt[j], loop_cnt[j - 1]);
std::swap(in_stride[j], in_stride[j - 1]);
std::swap(out_stride[j], out_stride[j - 1]);
}
}
}
}
DenseReducePlan::~DenseReducePlan() = default;
//-----------------------------------------------------------------------------
SparseReducePlan::SparseReducePlan(const ValueType &type, const ValueType &res_type)
: num_reduce_dims(0),
keep_dims()
{
auto dims = type.mapped_dimensions();
for (size_t i = 0; i < dims.size(); ++i) {
bool keep = (res_type.dimension_index(dims[i].name) != ValueType::Dimension::npos);
if (keep) {
keep_dims.push_back(i);
} else {
++num_reduce_dims;
}
}
}
SparseReducePlan::~SparseReducePlan() = default;
//-----------------------------------------------------------------------------
using ReduceTypify = TypifyValue<TypifyCellType,TypifyAggr>;
Instruction
GenericReduce::make_instruction(const ValueType &type, Aggr aggr, const std::vector<vespalib::string> &dimensions,
const ValueBuilderFactory &factory, Stash &stash)
{
auto ¶m = stash.create<ReduceParam>(type, dimensions, factory);
auto fun = typify_invoke<3,ReduceTypify,SelectGenericReduceOp>(type.cell_type(), param.res_type.cell_type(), aggr, param);
return Instruction(fun, wrap_param<ReduceParam>(param));
}
Value::UP
GenericReduce::perform_reduce(const Value &a, Aggr aggr,
const std::vector<vespalib::string> &dimensions,
const ValueBuilderFactory &factory)
{
ReduceParam param(a.type(), dimensions, factory);
return typify_invoke<3,ReduceTypify,PerformGenericReduce>(
a.type().cell_type(), param.res_type.cell_type(), aggr,
a, param);
}
} // namespace
<commit_msg>template aggregator on output cell type<commit_after>// Copyright Verizon Media. Licensed under the terms of the Apache 2.0 license. See LICENSE in the project root.
#include "generic_reduce.h"
#include <vespa/eval/eval/value.h>
#include <vespa/eval/eval/wrap_param.h>
#include <vespa/eval/eval/array_array_map.h>
#include <vespa/vespalib/util/stash.h>
#include <vespa/vespalib/util/typify.h>
#include <vespa/vespalib/util/overload.h>
#include <vespa/vespalib/util/visit_ranges.h>
#include <cassert>
using namespace vespalib::eval::tensor_function;
namespace vespalib::eval::instruction {
using State = InterpretedFunction::State;
using Instruction = InterpretedFunction::Instruction;
namespace {
//-----------------------------------------------------------------------------
struct ReduceParam {
ValueType res_type;
SparseReducePlan sparse_plan;
DenseReducePlan dense_plan;
const ValueBuilderFactory &factory;
ReduceParam(const ValueType &type, const std::vector<vespalib::string> &dimensions,
const ValueBuilderFactory &factory_in)
: res_type(type.reduce(dimensions)),
sparse_plan(type, res_type),
dense_plan(type, res_type),
factory(factory_in)
{
assert(!res_type.is_error());
assert(dense_plan.in_size == type.dense_subspace_size());
assert(dense_plan.out_size == res_type.dense_subspace_size());
}
~ReduceParam();
};
ReduceParam::~ReduceParam() = default;
//-----------------------------------------------------------------------------
struct SparseReduceState {
std::vector<vespalib::stringref> full_address;
std::vector<vespalib::stringref*> fetch_address;
std::vector<vespalib::stringref*> keep_address;
size_t subspace;
SparseReduceState(const SparseReducePlan &plan)
: full_address(plan.keep_dims.size() + plan.num_reduce_dims),
fetch_address(full_address.size(), nullptr),
keep_address(plan.keep_dims.size(), nullptr),
subspace()
{
for (size_t i = 0; i < keep_address.size(); ++i) {
keep_address[i] = &full_address[plan.keep_dims[i]];
}
for (size_t i = 0; i < full_address.size(); ++i) {
fetch_address[i] = &full_address[i];
}
}
~SparseReduceState();
};
SparseReduceState::~SparseReduceState() = default;
template <typename ICT, typename OCT, typename AGGR>
Value::UP
generic_reduce(const Value &value, const ReduceParam ¶m) {
auto cells = value.cells().typify<ICT>();
ArrayArrayMap<vespalib::stringref,AGGR> map(param.sparse_plan.keep_dims.size(),
param.dense_plan.out_size,
value.index().size());
SparseReduceState sparse(param.sparse_plan);
auto full_view = value.index().create_view({});
full_view->lookup({});
ConstArrayRef<vespalib::stringref*> keep_addr(sparse.keep_address);
while (full_view->next_result(sparse.fetch_address, sparse.subspace)) {
auto [tag, ignore] = map.lookup_or_add_entry(keep_addr);
AGGR *dst = map.get_values(tag).begin();
auto sample = [&](size_t src_idx, size_t dst_idx) { dst[dst_idx].sample(cells[src_idx]); };
param.dense_plan.execute(sparse.subspace * param.dense_plan.in_size, sample);
}
auto builder = param.factory.create_value_builder<OCT>(param.res_type, param.sparse_plan.keep_dims.size(), param.dense_plan.out_size, map.size());
map.each_entry([&](const auto &keys, const auto &values)
{
OCT *dst = builder->add_subspace(keys).begin();
for (const AGGR &aggr: values) {
*dst++ = aggr.result();
}
});
if ((map.size() == 0) && param.sparse_plan.keep_dims.empty()) {
auto zero = builder->add_subspace({});
for (size_t i = 0; i < zero.size(); ++i) {
zero[i] = OCT{};
}
}
return builder->build(std::move(builder));
}
template <typename ICT, typename OCT, typename AGGR>
void my_generic_reduce_op(State &state, uint64_t param_in) {
const auto ¶m = unwrap_param<ReduceParam>(param_in);
const Value &value = state.peek(0);
auto up = generic_reduce<ICT, OCT, AGGR>(value, param);
auto &result = state.stash.create<std::unique_ptr<Value>>(std::move(up));
const Value &result_ref = *(result.get());
state.pop_push(result_ref);
};
template <typename ICT, typename OCT, typename AGGR>
void my_full_reduce_op(State &state, uint64_t) {
auto cells = state.peek(0).cells().typify<ICT>();
if (cells.size() > 0) {
AGGR aggr;
for (ICT value: cells) {
aggr.sample(value);
}
state.pop_push(state.stash.create<ScalarValue<OCT>>(aggr.result()));
} else {
state.pop_push(state.stash.create<ScalarValue<OCT>>(OCT{0}));
}
};
struct SelectGenericReduceOp {
template <typename ICT, typename OCT, typename AGGR> static auto invoke(const ReduceParam ¶m) {
if (param.res_type.is_scalar()) {
return my_full_reduce_op<ICT, OCT, typename AGGR::template templ<OCT>>;
}
return my_generic_reduce_op<ICT, OCT, typename AGGR::template templ<OCT>>;
}
};
struct PerformGenericReduce {
template <typename ICT, typename OCT, typename AGGR>
static auto invoke(const Value &input, const ReduceParam ¶m) {
return generic_reduce<ICT, OCT, typename AGGR::template templ<OCT>>(input, param);
}
};
//-----------------------------------------------------------------------------
} // namespace <unnamed>
//-----------------------------------------------------------------------------
DenseReducePlan::DenseReducePlan(const ValueType &type, const ValueType &res_type)
: in_size(1),
out_size(1),
loop_cnt(),
in_stride(),
out_stride()
{
enum class Case { NONE, KEEP, REDUCE };
Case prev_case = Case::NONE;
auto update_plan = [&](Case my_case, size_t my_size) {
if (my_case == prev_case) {
assert(!loop_cnt.empty());
loop_cnt.back() *= my_size;
} else {
loop_cnt.push_back(my_size);
in_stride.push_back(1);
out_stride.push_back((my_case == Case::KEEP) ? 1 : 0);
prev_case = my_case;
}
};
auto visitor = overload
{
[&](visit_ranges_either, const auto &a) { update_plan(Case::REDUCE, a.size); },
[&](visit_ranges_both, const auto &a, const auto &) { update_plan(Case::KEEP, a.size); }
};
auto in_dims = type.nontrivial_indexed_dimensions();
auto out_dims = res_type.nontrivial_indexed_dimensions();
visit_ranges(visitor, in_dims.begin(), in_dims.end(), out_dims.begin(), out_dims.end(),
[](const auto &a, const auto &b){ return (a.name < b.name); });
for (size_t i = loop_cnt.size(); i-- > 0; ) {
in_stride[i] = in_size;
in_size *= loop_cnt[i];
if (out_stride[i] != 0) {
out_stride[i] = out_size;
out_size *= loop_cnt[i];
}
}
for (size_t i = 1; i < loop_cnt.size(); ++i) {
for (size_t j = i; j > 0; --j) {
if ((out_stride[j] == 0) && (out_stride[j - 1] > 0)) {
std::swap(loop_cnt[j], loop_cnt[j - 1]);
std::swap(in_stride[j], in_stride[j - 1]);
std::swap(out_stride[j], out_stride[j - 1]);
}
}
}
}
DenseReducePlan::~DenseReducePlan() = default;
//-----------------------------------------------------------------------------
SparseReducePlan::SparseReducePlan(const ValueType &type, const ValueType &res_type)
: num_reduce_dims(0),
keep_dims()
{
auto dims = type.mapped_dimensions();
for (size_t i = 0; i < dims.size(); ++i) {
bool keep = (res_type.dimension_index(dims[i].name) != ValueType::Dimension::npos);
if (keep) {
keep_dims.push_back(i);
} else {
++num_reduce_dims;
}
}
}
SparseReducePlan::~SparseReducePlan() = default;
//-----------------------------------------------------------------------------
using ReduceTypify = TypifyValue<TypifyCellType,TypifyAggr>;
Instruction
GenericReduce::make_instruction(const ValueType &type, Aggr aggr, const std::vector<vespalib::string> &dimensions,
const ValueBuilderFactory &factory, Stash &stash)
{
auto ¶m = stash.create<ReduceParam>(type, dimensions, factory);
auto fun = typify_invoke<3,ReduceTypify,SelectGenericReduceOp>(type.cell_type(), param.res_type.cell_type(), aggr, param);
return Instruction(fun, wrap_param<ReduceParam>(param));
}
Value::UP
GenericReduce::perform_reduce(const Value &a, Aggr aggr,
const std::vector<vespalib::string> &dimensions,
const ValueBuilderFactory &factory)
{
ReduceParam param(a.type(), dimensions, factory);
return typify_invoke<3,ReduceTypify,PerformGenericReduce>(
a.type().cell_type(), param.res_type.cell_type(), aggr,
a, param);
}
} // namespace
<|endoftext|>
|
<commit_before>/**
* 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.
*/
#ifndef __STOUT_PATH_HPP__
#define __STOUT_PATH_HPP__
#include <string>
#include <utility>
#include <vector>
#include <stout/strings.hpp>
/**
* Represents a POSIX file systems path and offers common path
* manipulations.
*/
class Path
{
public:
explicit Path(const std::string& path)
: value(strings::remove(path, "file://", strings::PREFIX)) {}
// TODO(cmaloney): Add more useful operations such as 'absolute()',
// 'directoryname()', 'filename()', etc.
/**
* Extracts the component following the final '/'. Trailing '/'
* characters are not counted as part of the pathname.
*
* Like the standard '::basename()' except it is thread safe.
*
* The following list of examples (taken from SUSv2) shows the
* strings returned by basename() for different paths:
*
* path | basename
* ----------- | -----------
* "/usr/lib" | "lib"
* "/usr/" | "usr"
* "usr" | "usr"
* "/" | "/"
* "." | "."
* ".." | ".."
*
* @return The component following the final '/'. If Path does not
* contain a '/', this returns a copy of Path. If Path is the
* string "/", then this returns the string "/". If Path is an
* empty string, then it returns the string ".".
*/
inline std::string basename()
{
if (value.empty()) {
return std::string(".");
}
size_t end = value.size() - 1;
// Remove trailing slashes.
if (value[end] == '/') {
end = value.find_last_not_of('/', end);
// Paths containing only slashes result into "/".
if (end == std::string::npos) {
return std::string("/");
}
}
// 'start' should point towards the character after the last slash
// that is non trailing.
size_t start = value.find_last_of('/', end);
if (start == std::string::npos) {
start = 0;
} else {
start++;
}
return value.substr(start, end + 1 - start);
}
/**
* Extracts the component up to, but not including, the final '/'.
* Trailing '/' characters are not counted as part of the pathname.
*
* Like the standard '::dirname()' except it is thread safe.
*
* The following list of examples (taken from SUSv2) shows the
* strings returned by dirname() for different paths:
*
* path | dirname
* ----------- | -----------
* "/usr/lib" | "/usr"
* "/usr/" | "/"
* "usr" | "."
* "/" | "/"
* "." | "."
* ".." | "."
*
* @return The component up to, but not including, the final '/'. If
* Path does not contain a '/', then this returns the string ".".
* If Path is the string "/", then this returns the string "/".
* If Path is an empty string, then this returns the string ".".
*/
inline std::string dirname()
{
if (value.empty()) {
return std::string(".");
}
size_t end = value.size() - 1;
// Remove trailing slashes.
if (value[end] == '/') {
end = value.find_last_not_of('/', end);
}
// Remove anything trailing the last slash.
end = value.find_last_of('/', end);
// Paths containing no slashes result in ".".
if (end == std::string::npos) {
return std::string(".");
}
// Paths containing only slashes result in "/".
if (end == 0) {
return std::string("/");
}
// 'end' should point towards the last non slash character
// preceding the last slash.
end = value.find_last_not_of('/', end);
// Paths containing no non slash characters result in "/".
if (end == std::string::npos) {
return std::string("/");
}
return value.substr(0, end + 1);
}
// Implicit conversion from Path to string.
operator std::string () const
{
return value;
}
const std::string value;
};
inline std::ostream& operator << (
std::ostream& stream,
const Path& path)
{
return stream << path.value;
}
namespace path {
// Base case.
inline std::string join(const std::string& path1, const std::string& path2)
{
return strings::remove(path1, "/", strings::SUFFIX) + "/" +
strings::remove(path2, "/", strings::PREFIX);
}
template <typename... Paths>
inline std::string join(
const std::string& path1,
const std::string& path2,
Paths&&... paths)
{
return join(path1, join(path2, std::forward<Paths>(paths)...));
}
inline std::string join(const std::vector<std::string>& paths)
{
if (paths.empty()) {
return "";
}
std::string result = paths[0];
for (size_t i = 1; i < paths.size(); ++i) {
result = join(result, paths[i]);
}
return result;
}
} // namespace path {
#endif // __STOUT_PATH_HPP__
<commit_msg>Marked Path::basename and Path::dirname as being const.<commit_after>/**
* 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.
*/
#ifndef __STOUT_PATH_HPP__
#define __STOUT_PATH_HPP__
#include <string>
#include <utility>
#include <vector>
#include <stout/strings.hpp>
/**
* Represents a POSIX file systems path and offers common path
* manipulations.
*/
class Path
{
public:
explicit Path(const std::string& path)
: value(strings::remove(path, "file://", strings::PREFIX)) {}
// TODO(cmaloney): Add more useful operations such as 'absolute()',
// 'directoryname()', 'filename()', etc.
/**
* Extracts the component following the final '/'. Trailing '/'
* characters are not counted as part of the pathname.
*
* Like the standard '::basename()' except it is thread safe.
*
* The following list of examples (taken from SUSv2) shows the
* strings returned by basename() for different paths:
*
* path | basename
* ----------- | -----------
* "/usr/lib" | "lib"
* "/usr/" | "usr"
* "usr" | "usr"
* "/" | "/"
* "." | "."
* ".." | ".."
*
* @return The component following the final '/'. If Path does not
* contain a '/', this returns a copy of Path. If Path is the
* string "/", then this returns the string "/". If Path is an
* empty string, then it returns the string ".".
*/
inline std::string basename() const
{
if (value.empty()) {
return std::string(".");
}
size_t end = value.size() - 1;
// Remove trailing slashes.
if (value[end] == '/') {
end = value.find_last_not_of('/', end);
// Paths containing only slashes result into "/".
if (end == std::string::npos) {
return std::string("/");
}
}
// 'start' should point towards the character after the last slash
// that is non trailing.
size_t start = value.find_last_of('/', end);
if (start == std::string::npos) {
start = 0;
} else {
start++;
}
return value.substr(start, end + 1 - start);
}
/**
* Extracts the component up to, but not including, the final '/'.
* Trailing '/' characters are not counted as part of the pathname.
*
* Like the standard '::dirname()' except it is thread safe.
*
* The following list of examples (taken from SUSv2) shows the
* strings returned by dirname() for different paths:
*
* path | dirname
* ----------- | -----------
* "/usr/lib" | "/usr"
* "/usr/" | "/"
* "usr" | "."
* "/" | "/"
* "." | "."
* ".." | "."
*
* @return The component up to, but not including, the final '/'. If
* Path does not contain a '/', then this returns the string ".".
* If Path is the string "/", then this returns the string "/".
* If Path is an empty string, then this returns the string ".".
*/
inline std::string dirname() const
{
if (value.empty()) {
return std::string(".");
}
size_t end = value.size() - 1;
// Remove trailing slashes.
if (value[end] == '/') {
end = value.find_last_not_of('/', end);
}
// Remove anything trailing the last slash.
end = value.find_last_of('/', end);
// Paths containing no slashes result in ".".
if (end == std::string::npos) {
return std::string(".");
}
// Paths containing only slashes result in "/".
if (end == 0) {
return std::string("/");
}
// 'end' should point towards the last non slash character
// preceding the last slash.
end = value.find_last_not_of('/', end);
// Paths containing no non slash characters result in "/".
if (end == std::string::npos) {
return std::string("/");
}
return value.substr(0, end + 1);
}
// Implicit conversion from Path to string.
operator std::string () const
{
return value;
}
const std::string value;
};
inline std::ostream& operator << (
std::ostream& stream,
const Path& path)
{
return stream << path.value;
}
namespace path {
// Base case.
inline std::string join(const std::string& path1, const std::string& path2)
{
return strings::remove(path1, "/", strings::SUFFIX) + "/" +
strings::remove(path2, "/", strings::PREFIX);
}
template <typename... Paths>
inline std::string join(
const std::string& path1,
const std::string& path2,
Paths&&... paths)
{
return join(path1, join(path2, std::forward<Paths>(paths)...));
}
inline std::string join(const std::vector<std::string>& paths)
{
if (paths.empty()) {
return "";
}
std::string result = paths[0];
for (size_t i = 1; i < paths.size(); ++i) {
result = join(result, paths[i]);
}
return result;
}
} // namespace path {
#endif // __STOUT_PATH_HPP__
<|endoftext|>
|
<commit_before>#include "stdafx.h"
#include "AudioSessionEventsSink.h"
HRESULT GetAudioSessionEnumerator(IAudioSessionEnumerator **ppSessionEnumerator)
{
if (ppSessionEnumerator == nullptr) return E_POINTER;
CComPtr<IMMDeviceEnumerator> spEnumerator;
IF_FAIL_RET_HR(spEnumerator.CoCreateInstance(__uuidof(MMDeviceEnumerator), nullptr, CLSCTX_ALL));
CComPtr<IMMDevice> spDefaultDevice;
IF_FAIL_RET_HR(spEnumerator->GetDefaultAudioEndpoint(eRender, eConsole, &spDefaultDevice));
CComPtr<IAudioSessionManager2> spSessionManager;
IF_FAIL_RET_HR(spDefaultDevice->Activate(__uuidof(IAudioSessionManager2), CLSCTX_ALL, nullptr, (void**)&spSessionManager));
IF_FAIL_RET_HR(spSessionManager->GetSessionEnumerator(ppSessionEnumerator));
return S_OK;
}
HRESULT ListAudioSessionsOnPrimaryDevice()
{
CComPtr<IAudioSessionEnumerator> spSessionEnumerator;
IF_FAIL_RET_HR(GetAudioSessionEnumerator(&spSessionEnumerator));
auto sessionCount = 0;
IF_FAIL_RET_HR(spSessionEnumerator->GetCount(&sessionCount));
for (auto i = 0; i < sessionCount; ++i) {
CComPtr<IAudioSessionControl> spAudioSessionControl;
IF_FAIL_RET_HR(spSessionEnumerator->GetSession(i, &spAudioSessionControl));
CComPtr<IAudioSessionControl2> spAudioSessionControl2;
IF_FAIL_RET_HR(spAudioSessionControl->QueryInterface(&spAudioSessionControl2));
CComHeapPtr<wchar_t> displayName, iconPath;
auto sessionState = AudioSessionStateInactive;
IF_FAIL_RET_HR(spAudioSessionControl2->GetDisplayName(&displayName));
IF_FAIL_RET_HR(spAudioSessionControl2->GetState(&sessionState));
IF_FAIL_RET_HR(spAudioSessionControl2->GetIconPath(&iconPath));
wprintf(L"Session %d (%d): %ls (%ls)\r\n", i, sessionState, (LPWSTR)displayName, (LPWSTR)iconPath);
CComHeapPtr<wchar_t> sessionIdentifier, sessionInstanceIdentifier;
DWORD processId;
IF_FAIL_RET_HR(spAudioSessionControl2->GetSessionIdentifier(&sessionIdentifier));
IF_FAIL_RET_HR(spAudioSessionControl2->GetSessionInstanceIdentifier(&sessionInstanceIdentifier));
IF_FAIL_RET_HR(spAudioSessionControl2->GetProcessId(&processId));
wprintf(L"\tID: '%ls'\r\n\tInstance ID: '%ls'\r\n\tPID: %d\r\n", (LPWSTR)sessionIdentifier, (LPWSTR)sessionInstanceIdentifier, processId);
}
return S_OK;
}
HRESULT GetProcessIdForProcessName(const wchar_t *processName, DWORD *pid)
{
if (processName == nullptr || pid == nullptr) return E_POINTER;
DWORD bigPidArray[1024];
DWORD bytesReturned;
wchar_t imageFilePath[MAX_PATH + 1];
if (0 == EnumProcesses(bigPidArray, sizeof(bigPidArray) * ARRAYSIZE(bigPidArray), &bytesReturned))
{
return HRESULT_FROM_WIN32(GetLastError());
}
auto processCount = bytesReturned / sizeof(DWORD);
for (auto i = 0U; i < processCount; ++i) {
CHandle procHandle(OpenProcess(PROCESS_QUERY_LIMITED_INFORMATION, false, bigPidArray[i]));
if (procHandle == NULL) {
// This isn't really a condition worth worrying about; some processes we aren't allowed to open
continue;
}
DWORD imageFilePathSize = ARRAYSIZE(imageFilePath);
if (0 == QueryFullProcessImageName(procHandle, 0, imageFilePath, &imageFilePathSize)) {
printf("Couldn't get image name for PID = %d\r\n", bigPidArray[i]);
continue;
}
auto imageFileName = PathFindFileNameW(imageFilePath);
if (0 == _wcsicmp(processName, imageFileName)) {
*pid = bigPidArray[i];
return S_OK;
}
}
*pid = 0;
return S_FALSE;
}
HRESULT GetAudioSessionForProcessId(DWORD processId, IAudioSessionControl2 **ppSessionControl)
{
if (ppSessionControl == nullptr) return E_POINTER;
CComPtr<IAudioSessionEnumerator> spSessionEnumerator;
IF_FAIL_RET_HR(GetAudioSessionEnumerator(&spSessionEnumerator));
auto sessionCount = 0;
IF_FAIL_RET_HR(spSessionEnumerator->GetCount(&sessionCount));
for (auto i = 0; i < sessionCount; ++i) {
CComPtr<IAudioSessionControl> spAudioSessionControl;
IF_FAIL_RET_HR(spSessionEnumerator->GetSession(i, &spAudioSessionControl));
CComPtr<IAudioSessionControl2> spAudioSessionControl2;
IF_FAIL_RET_HR(spAudioSessionControl->QueryInterface(&spAudioSessionControl2));
DWORD sessionPid;
IF_FAIL_RET_HR(spAudioSessionControl2->GetProcessId(&sessionPid));
if (sessionPid == processId) {
*ppSessionControl = spAudioSessionControl2.Detach();
return S_OK;
}
}
*ppSessionControl = nullptr;
return S_FALSE;
}
// Assumes COM has been initialized.
HRESULT MainRoutine()
{
auto hr = S_OK;
if (FAILED(hr = ListAudioSessionsOnPrimaryDevice())) {
fprintf(stderr, "Failed to list audio sessions: %#010x\r\n", hr);
return hr;
}
DWORD chromePid, firefoxPid;
if (FAILED(hr = GetProcessIdForProcessName(L"chrome.exe", &chromePid))) {
fprintf(stderr, "Failed to get chrome.exe PID: %#010x\r\n", hr);
return hr;
}
printf("chrome.exe PID: %d\r\n", chromePid);
if (FAILED(hr = GetProcessIdForProcessName(L"firefox.exe", &firefoxPid))) {
fprintf(stderr, "Failed to get firefox.exe PID: %#010x\r\n", hr);
return hr;
}
printf("firefox.exe PID: %d\r\n", firefoxPid);
CComPtr<IAudioSessionControl2> spFirefoxSessionControl;
if (FAILED(hr = GetAudioSessionForProcessId(firefoxPid, &spFirefoxSessionControl))) {
fprintf(stderr, "Failed to get Firefox (PID %d) audio session control: %#010x\r\n", firefoxPid, hr);
return hr;
}
CComPtr<IAudioSessionControl2> spChromeSessionControl;
if (FAILED(hr = GetAudioSessionForProcessId(chromePid, &spChromeSessionControl))) {
fprintf(stderr, "Failed to get Chrome (PID %d) audio session control: %#010x\r\n", chromePid, hr);
return hr;
}
CComPtr<ISimpleAudioVolume> spChromeSimpleAudioVolume;
if (FAILED(hr = spChromeSessionControl->QueryInterface(&spChromeSimpleAudioVolume))) {
fprintf(stderr, "Failed to QI for ISimpleAudioVolume from Chrome session control: %#010x\r\n", hr);
return hr;
}
auto dimChromeWhenFirefoxIsActiveCallbackFn =
[spChromeSimpleAudioVolume](AudioSessionState newState)
{
if (newState == AudioSessionStateActive) {
// Firefox is active, so dim Chrome to 20%
if (FAILED(spChromeSimpleAudioVolume->SetMasterVolume(0.2f, nullptr))) {
fprintf(stderr, "Failed to set Chrome volume to 20%%\r\n");
}
else {
printf("Set Chrome volume to 20%%\r\n");
}
}
else if (newState == AudioSessionStateInactive) {
// Firefox is inactive, so set Chrome back to 100%
if (FAILED(spChromeSimpleAudioVolume->SetMasterVolume(1.0f, nullptr))) {
fprintf(stderr, "Failed to set Chrome volume to 100%%\r\n");
}
else {
printf("Set Chrome volume to 100%%\r\n");
}
}
};
CComPtr<IAudioSessionEvents> spFirefoxEventSink;
if (FAILED(hr = AudioSessionEventsSinkWithStateCallback::Create(&spFirefoxEventSink,
dimChromeWhenFirefoxIsActiveCallbackFn))) {
fprintf(stderr, "Failed to create new audio session events sink for Firefox: %#010x\r\n", hr);
return hr;
}
if (FAILED(hr = spFirefoxSessionControl->RegisterAudioSessionNotification(spFirefoxEventSink))) {
fprintf(stderr, "Failed to register for audio session notifications for Firefox: %#010x\r\n", hr);
return hr;
}
printf("Press Enter to exit.\r\n");
getchar();
if (FAILED(hr = spFirefoxSessionControl->UnregisterAudioSessionNotification(spFirefoxEventSink))) {
fprintf(stderr, "Failed to unregister for audio session notifications for Chrome: %#010x\r\n", hr);
return hr;
}
return hr;
}
int main()
{
auto hr = S_OK;
if (FAILED(hr = CoInitializeEx(nullptr, COINIT_MULTITHREADED))) {
fprintf(stderr, "Failed to initialize COM: %#010x\r\n", hr);
return 1;
}
hr = MainRoutine();
CoUninitialize();
return FAILED(hr) ? 1 : 0;
}
<commit_msg>Comments<commit_after>#include "stdafx.h"
#include "AudioSessionEventsSink.h"
HRESULT GetAudioSessionEnumerator(IAudioSessionEnumerator **ppSessionEnumerator)
{
if (ppSessionEnumerator == nullptr) return E_POINTER;
CComPtr<IMMDeviceEnumerator> spEnumerator;
IF_FAIL_RET_HR(spEnumerator.CoCreateInstance(__uuidof(MMDeviceEnumerator), nullptr, CLSCTX_ALL));
CComPtr<IMMDevice> spDefaultDevice;
IF_FAIL_RET_HR(spEnumerator->GetDefaultAudioEndpoint(eRender, eConsole, &spDefaultDevice));
CComPtr<IAudioSessionManager2> spSessionManager;
IF_FAIL_RET_HR(spDefaultDevice->Activate(__uuidof(IAudioSessionManager2), CLSCTX_ALL, nullptr, (void**)&spSessionManager));
IF_FAIL_RET_HR(spSessionManager->GetSessionEnumerator(ppSessionEnumerator));
return S_OK;
}
HRESULT ListAudioSessionsOnPrimaryDevice()
{
CComPtr<IAudioSessionEnumerator> spSessionEnumerator;
IF_FAIL_RET_HR(GetAudioSessionEnumerator(&spSessionEnumerator));
auto sessionCount = 0;
IF_FAIL_RET_HR(spSessionEnumerator->GetCount(&sessionCount));
for (auto i = 0; i < sessionCount; ++i) {
CComPtr<IAudioSessionControl> spAudioSessionControl;
IF_FAIL_RET_HR(spSessionEnumerator->GetSession(i, &spAudioSessionControl));
CComPtr<IAudioSessionControl2> spAudioSessionControl2;
IF_FAIL_RET_HR(spAudioSessionControl->QueryInterface(&spAudioSessionControl2));
CComHeapPtr<wchar_t> displayName, iconPath;
auto sessionState = AudioSessionStateInactive;
IF_FAIL_RET_HR(spAudioSessionControl2->GetDisplayName(&displayName));
IF_FAIL_RET_HR(spAudioSessionControl2->GetState(&sessionState));
IF_FAIL_RET_HR(spAudioSessionControl2->GetIconPath(&iconPath));
wprintf(L"Session %d (%d): %ls (%ls)\r\n", i, sessionState, (LPWSTR)displayName, (LPWSTR)iconPath);
CComHeapPtr<wchar_t> sessionIdentifier, sessionInstanceIdentifier;
DWORD processId;
IF_FAIL_RET_HR(spAudioSessionControl2->GetSessionIdentifier(&sessionIdentifier));
IF_FAIL_RET_HR(spAudioSessionControl2->GetSessionInstanceIdentifier(&sessionInstanceIdentifier));
IF_FAIL_RET_HR(spAudioSessionControl2->GetProcessId(&processId));
wprintf(L"\tID: '%ls'\r\n\tInstance ID: '%ls'\r\n\tPID: %d\r\n", (LPWSTR)sessionIdentifier, (LPWSTR)sessionInstanceIdentifier, processId);
}
return S_OK;
}
HRESULT GetProcessIdForProcessName(const wchar_t *processName, DWORD *pid)
{
if (processName == nullptr || pid == nullptr) return E_POINTER;
DWORD bigPidArray[1024];
DWORD bytesReturned;
wchar_t imageFilePath[MAX_PATH + 1];
if (0 == EnumProcesses(bigPidArray, sizeof(bigPidArray) * ARRAYSIZE(bigPidArray), &bytesReturned))
{
return HRESULT_FROM_WIN32(GetLastError());
}
auto processCount = bytesReturned / sizeof(DWORD);
for (auto i = 0U; i < processCount; ++i) {
CHandle procHandle(OpenProcess(PROCESS_QUERY_LIMITED_INFORMATION, false, bigPidArray[i]));
if (procHandle == NULL) {
// This isn't really a condition worth worrying about; some processes we aren't allowed to open
continue;
}
DWORD imageFilePathSize = ARRAYSIZE(imageFilePath);
if (0 == QueryFullProcessImageName(procHandle, 0, imageFilePath, &imageFilePathSize)) {
printf("Couldn't get image name for PID = %d\r\n", bigPidArray[i]);
continue;
}
auto imageFileName = PathFindFileNameW(imageFilePath);
if (0 == _wcsicmp(processName, imageFileName)) {
*pid = bigPidArray[i];
return S_OK;
}
}
*pid = 0;
return S_FALSE;
}
HRESULT GetAudioSessionForProcessId(DWORD processId, IAudioSessionControl2 **ppSessionControl)
{
if (ppSessionControl == nullptr) return E_POINTER;
CComPtr<IAudioSessionEnumerator> spSessionEnumerator;
IF_FAIL_RET_HR(GetAudioSessionEnumerator(&spSessionEnumerator));
auto sessionCount = 0;
IF_FAIL_RET_HR(spSessionEnumerator->GetCount(&sessionCount));
for (auto i = 0; i < sessionCount; ++i) {
CComPtr<IAudioSessionControl> spAudioSessionControl;
IF_FAIL_RET_HR(spSessionEnumerator->GetSession(i, &spAudioSessionControl));
CComPtr<IAudioSessionControl2> spAudioSessionControl2;
IF_FAIL_RET_HR(spAudioSessionControl->QueryInterface(&spAudioSessionControl2));
DWORD sessionPid;
IF_FAIL_RET_HR(spAudioSessionControl2->GetProcessId(&sessionPid));
if (sessionPid == processId) {
*ppSessionControl = spAudioSessionControl2.Detach();
return S_OK;
}
}
*ppSessionControl = nullptr;
return S_FALSE;
}
// Assumes COM has been initialized.
HRESULT MainRoutine()
{
auto hr = S_OK;
if (FAILED(hr = ListAudioSessionsOnPrimaryDevice())) {
fprintf(stderr, "Failed to list audio sessions: %#010x\r\n", hr);
return hr;
}
DWORD chromePid, firefoxPid;
if (FAILED(hr = GetProcessIdForProcessName(L"chrome.exe", &chromePid))) {
fprintf(stderr, "Failed to get chrome.exe PID: %#010x\r\n", hr);
return hr;
}
printf("chrome.exe PID: %d\r\n", chromePid);
if (FAILED(hr = GetProcessIdForProcessName(L"firefox.exe", &firefoxPid))) {
fprintf(stderr, "Failed to get firefox.exe PID: %#010x\r\n", hr);
return hr;
}
printf("firefox.exe PID: %d\r\n", firefoxPid);
CComPtr<IAudioSessionControl2> spFirefoxSessionControl;
if (FAILED(hr = GetAudioSessionForProcessId(firefoxPid, &spFirefoxSessionControl))) {
fprintf(stderr, "Failed to get Firefox (PID %d) audio session control: %#010x\r\n", firefoxPid, hr);
return hr;
}
CComPtr<IAudioSessionControl2> spChromeSessionControl;
if (FAILED(hr = GetAudioSessionForProcessId(chromePid, &spChromeSessionControl))) {
fprintf(stderr, "Failed to get Chrome (PID %d) audio session control: %#010x\r\n", chromePid, hr);
return hr;
}
// NOTE: This part (QI for ISimpleAudioVolume) is not supported by Microsoft and subject to breakage
// in a future release of Windows. However, it does seem to work at least as of Windows 10.0.14361.
CComPtr<ISimpleAudioVolume> spChromeSimpleAudioVolume;
if (FAILED(hr = spChromeSessionControl->QueryInterface(&spChromeSimpleAudioVolume))) {
fprintf(stderr, "Failed to QI for ISimpleAudioVolume from Chrome session control: %#010x\r\n", hr);
return hr;
}
auto dimChromeWhenFirefoxIsActiveCallbackFn =
[spChromeSimpleAudioVolume](AudioSessionState newState)
{
if (newState == AudioSessionStateActive) {
// Firefox is active, so dim Chrome to 20%
if (FAILED(spChromeSimpleAudioVolume->SetMasterVolume(0.2f, nullptr))) {
fprintf(stderr, "Failed to set Chrome volume to 20%%\r\n");
}
else {
printf("Set Chrome volume to 20%%\r\n");
}
}
else if (newState == AudioSessionStateInactive) {
// Firefox is inactive, so set Chrome back to 100%
if (FAILED(spChromeSimpleAudioVolume->SetMasterVolume(1.0f, nullptr))) {
fprintf(stderr, "Failed to set Chrome volume to 100%%\r\n");
}
else {
printf("Set Chrome volume to 100%%\r\n");
}
}
};
CComPtr<IAudioSessionEvents> spFirefoxEventSink;
if (FAILED(hr = AudioSessionEventsSinkWithStateCallback::Create(&spFirefoxEventSink,
dimChromeWhenFirefoxIsActiveCallbackFn))) {
fprintf(stderr, "Failed to create new audio session events sink for Firefox: %#010x\r\n", hr);
return hr;
}
if (FAILED(hr = spFirefoxSessionControl->RegisterAudioSessionNotification(spFirefoxEventSink))) {
fprintf(stderr, "Failed to register for audio session notifications for Firefox: %#010x\r\n", hr);
return hr;
}
printf("Press Enter to exit.\r\n");
getchar();
if (FAILED(hr = spFirefoxSessionControl->UnregisterAudioSessionNotification(spFirefoxEventSink))) {
fprintf(stderr, "Failed to unregister for audio session notifications for Chrome: %#010x\r\n", hr);
return hr;
}
return hr;
}
int main()
{
auto hr = S_OK;
if (FAILED(hr = CoInitializeEx(nullptr, COINIT_MULTITHREADED))) {
fprintf(stderr, "Failed to initialize COM: %#010x\r\n", hr);
return 1;
}
hr = MainRoutine();
CoUninitialize();
return FAILED(hr) ? 1 : 0;
}
<|endoftext|>
|
<commit_before>// Copyright 2015, Christopher J. Foster and the other displaz contributors.
// Use of this code is governed by the BSD-style license found in LICENSE.txt
#include "geometry.h"
#include "hcloudview.h"
#include "mesh.h"
#include "ply_io.h"
#include "pointarray.h"
#include <rply/rply.h>
/// Determine whether a ply file has mesh or line segment elements
///
/// (If not, assume it's a point cloud.)
static bool plyHasMesh(QString fileName)
{
std::unique_ptr<t_ply_, int(*)(p_ply)> ply(
ply_open(fileName.toUtf8().constData(), logRplyError, 0, NULL), ply_close);
if (!ply || !ply_read_header(ply.get()))
return false;
for (p_ply_element elem = ply_get_next_element(ply.get(), NULL);
elem != NULL; elem = ply_get_next_element(ply.get(), elem))
{
const char* name = 0;
long ninstances = 0;
if (!ply_get_element_info(elem, &name, &ninstances))
continue;
if (strcmp(name, "face") == 0 || strcmp(name, "triangle") == 0 ||
strcmp(name, "edge") == 0 || strcmp(name, "hullxy") == 0)
{
return true;
}
}
return false;
}
//------------------------------------------------------------------------------
Geometry::Geometry()
: m_fileName(),
m_offset(0,0,0),
m_centroid(0,0,0),
m_bbox()
{ }
std::shared_ptr<Geometry> Geometry::create(QString fileName)
{
if (fileName.endsWith(".ply") && plyHasMesh(fileName))
return std::shared_ptr<Geometry>(new TriMesh());
else if(fileName.endsWith(".hcloud"))
return std::shared_ptr<Geometry>(new HCloudView());
else
return std::shared_ptr<Geometry>(new PointArray());
}
bool Geometry::reloadFile(size_t maxVertexCount)
{
return loadFile(m_fileName, maxVertexCount);
}
<commit_msg>Detect ply files containing polygons as mesh data<commit_after>// Copyright 2015, Christopher J. Foster and the other displaz contributors.
// Use of this code is governed by the BSD-style license found in LICENSE.txt
#include "geometry.h"
#include "hcloudview.h"
#include "mesh.h"
#include "ply_io.h"
#include "pointarray.h"
#include <rply/rply.h>
/// Determine whether a ply file has mesh or line segment elements
///
/// (If not, assume it's a point cloud.)
static bool plyHasMesh(QString fileName)
{
std::unique_ptr<t_ply_, int(*)(p_ply)> ply(
ply_open(fileName.toUtf8().constData(), logRplyError, 0, NULL), ply_close);
if (!ply || !ply_read_header(ply.get()))
return false;
for (p_ply_element elem = ply_get_next_element(ply.get(), NULL);
elem != NULL; elem = ply_get_next_element(ply.get(), elem))
{
const char* name = 0;
long ninstances = 0;
if (!ply_get_element_info(elem, &name, &ninstances))
continue;
if (strcmp(name, "face") == 0 || strcmp(name, "triangle") == 0 ||
strcmp(name, "edge") == 0 || strcmp(name, "hullxy") == 0 ||
strcmp(name, "polygon") == 0)
{
return true;
}
}
return false;
}
//------------------------------------------------------------------------------
Geometry::Geometry()
: m_fileName(),
m_offset(0,0,0),
m_centroid(0,0,0),
m_bbox()
{ }
std::shared_ptr<Geometry> Geometry::create(QString fileName)
{
if (fileName.endsWith(".ply") && plyHasMesh(fileName))
return std::shared_ptr<Geometry>(new TriMesh());
else if(fileName.endsWith(".hcloud"))
return std::shared_ptr<Geometry>(new HCloudView());
else
return std::shared_ptr<Geometry>(new PointArray());
}
bool Geometry::reloadFile(size_t maxVertexCount)
{
return loadFile(m_fileName, maxVertexCount);
}
<|endoftext|>
|
<commit_before>#include <fstream>
#include <sstream>
#include <iostream>
#include <cstdlib>
#include <stdint.h>
#include <cstring>
#include <list>
#include <cmath>
std::stringstream *linestream;
std::string token = "";
const char *filename;
// return float from linestream
inline float getFloat() {
if (!getline(*linestream, token, ',')) {
std::cerr << "error: could not parse " << filename << std::endl ;
exit(1);
}
return atof(token.c_str());
}
// return unsigned long from linestream
inline float getUlong() {
if (!getline(*linestream, token, ',')) {
std::cerr << "error: could not parse " << filename << std::endl ;
exit(1);
}
return strtoul(token.c_str(),NULL,0);
}
// skip value from linestream
inline float skip() {
if (!getline(*linestream, token, ',')) {
std::cerr << "error: could not parse " << filename << std::endl ;
exit(1);
}
}
int main(int argc, char **argv) {
std::string line = "";
unsigned int index;
float depth, theta, phi;
int lon, lat;
float r=150.0; // webgl sphere radius
float fx,fy,fz;
std::list<float> sector[360][180];
float step=M_PI/180.0;
unsigned long i=0;
unsigned long nb_points=0;
if (argc!=2) {
std::cerr << "usage: " << argv[0] << " <json_file>" << std::endl ;
return 1;
}
// open json
filename=argv[1];
std::ifstream fs(filename);
if (!fs.is_open()) {
std::cerr << "could not open " << filename << std::endl ;
return 1;
}
// extract "nb_points" from json
while (getline(fs, line)) {
if (const char *pos=strstr(line.c_str(),"nb_points")) {
nb_points=strtoul(strchr(pos,':')+1,NULL,0);
break;
}
}
if (!nb_points) {
std::cerr << "error: could not parse" << filename << std::endl ;
return 1;
}
// remove input filename extension
std::string fname=std::string(filename);
fname.erase(fname.find_last_of("."),std::string::npos);
// create .bin output file
std::string outfname=fname+".bin";
std::ofstream outf;
outf.open(outfname.c_str());
if (!outf.is_open()) {
std::cerr << "could not open " << outfname << std::endl ;
return 1;
}
std::cerr << filename << ": parsing " << nb_points << " points" << std::endl;
// 1. parse lines beginning with [0-9] as a csv formatted as:
// "depth, index, theta, phi," (floats)
// 2. store cartesian coordinates in "sector" array as:
// float x, float y, float z
while (getline(fs, line)) {
if (line[0]<'0' || line[0]>'9') continue;
linestream=new std::stringstream(line);
depth=getFloat();
index=getUlong();
theta=getFloat();
phi=getFloat();
// convert to degrees
lon=((int)round(theta/step)+180)%360;
lat=round(phi/step);
if (lat<0) lat+=180;
lat=180-lat;
// reference particle in sector lon,lat
std::list<float> *_sector=§or[lon][lat];
phi=(phi-M_PI/2);
theta=theta-M_PI/2;
// compute cartesian coordinates
fx=depth*sin(phi)*cos(theta);
fz=depth*sin(phi)*sin(theta);
fy=-depth*cos(phi);
// store cartesian coordinates
_sector->push_back(fx);
_sector->push_back(fy);
_sector->push_back(fz);
}
// output positions formatted as list of x,y,z for each [lon][lat] pair
// and prepare a 360x180 array index formatted as offset,count
std::list<uint32_t> array_index;
for (lat=0; lat<180; ++lat) {
for (lon=0; lon<360; ++lon) {
std::list<float> *positions=§or[lon][lat];
// update array index
uint32_t particle_count=positions->size()/3;
if (particle_count) {
// particles in this sector: store offset and particle count
array_index.push_back(outf.tellp()/sizeof(fx));
array_index.push_back(particle_count);
} else {
// no particles here
array_index.push_back(0);
array_index.push_back(0);
continue;
}
// output particle positions for sector[lon][lat]
for (std::list<float>::iterator it=positions->begin(); it!=positions->end(); ++it) {
float value=*it;
outf.write((char*)&value,sizeof(value));
}
}
}
// check integrity
unsigned long positions_byteCount=outf.tellp();
std::cerr << filename << ": positions -> " << positions_byteCount << " bytes" << ((positions_byteCount%4)?" not a multiple of 4 !":"") << std::endl;
// output index formatted as:
// offset, particle_count
for (std::list<uint32_t>::iterator it=array_index.begin(); it!=array_index.end(); ++it) {
uint32_t value=*it;
outf.write((char*)&value,sizeof(value));
}
// check integrity
long unsigned int index_byteCount=(unsigned long)outf.tellp()-positions_byteCount;
std::cerr << filename << ": index -> " << index_byteCount << " bytes" << ((index_byteCount%4)?" not a multiple of 4 !":"") << std::endl;
outf.close();
return (positions_byteCount%4 + index_byteCount%4);
}
<commit_msg>stash<commit_after>#include <fstream>
#include <sstream>
#include <iostream>
#include <cstdlib>
#include <stdint.h>
#include <cstring>
#include <list>
#include <cmath>
#define FILE_MARKER "\xF0\xE1"
#define FILE_VERSION "fpcl.00001" // increment this number file format change !
std::stringstream *linestream;
std::string token = "";
const char *filename;
// return float from linestream
inline float getFloat() {
if (!getline(*linestream, token, ',')) {
std::cerr << "error: could not parse " << filename << std::endl ;
exit(1);
}
return atof(token.c_str());
}
// return unsigned long from linestream
inline float getUlong() {
if (!getline(*linestream, token, ',')) {
std::cerr << "error: could not parse " << filename << std::endl ;
exit(1);
}
return strtoul(token.c_str(),NULL,0);
}
// skip value from linestream
inline float skip() {
if (!getline(*linestream, token, ',')) {
std::cerr << "error: could not parse " << filename << std::endl ;
exit(1);
}
}
int main(int argc, char **argv) {
std::string line = "";
unsigned int index;
float depth, theta, phi, mn95_x, mn95_y, mn95_z;
int lon, lat;
float r=150.0; // webgl sphere radius
float fx,fy,fz;
std::list<uint32_t> sector[360][180];
float step=M_PI/180.0;
uint32_t point_index=0;
unsigned long nb_points=0;
if (argc!=2) {
std::cerr << "usage: " << argv[0] << " <json_file>" << std::endl ;
return 1;
}
// open json
filename=argv[1];
std::ifstream fs(filename);
if (!fs.is_open()) {
std::cerr << "could not open " << filename << std::endl ;
return 1;
}
// extract "nb_points" from json
while (getline(fs, line)) {
if (const char *pos=strstr(line.c_str(),"nb_points")) {
nb_points=strtoul(strchr(pos,':')+1,NULL,0);
break;
}
}
if (!nb_points) {
std::cerr << "error: could not parse" << filename << std::endl ;
return 1;
}
// remove input filename extension
std::string fname=std::string(filename);
fname.erase(fname.find_last_of("."),std::string::npos);
// create .bin output file
std::string outfname=fname+".bin";
std::ofstream outf;
outf.open(outfname.c_str());
if (!outf.is_open()) {
std::cerr << "could not open " << outfname << std::endl ;
return 1;
}
std::cerr << filename << ": parsing " << nb_points << " points" << std::endl;
// 1. parse lines beginning with [0-9] as a csv formatted as:
// "depth, index, theta, phi, mn95-x, mn95-y, mn95-z" (floats)
// 2. store cartesian coordinates in "sector" array as:
// float x, float y, float z
float *mn95=new float[nb_points*3];
float *positions=new float[nb_points*3];
while (getline(fs, line)) {
// skip line not beginning with [0-9]
if (line[0]<'0' || line[0]>'9') continue;
if (point_index>= nb_points) {
std::cerr << filename << ": error: nb_points is invalid ! " << std::endl;
return 1;
}
// read line
linestream=new std::stringstream(line);
// extract fields
depth=getFloat();
index=getUlong();
theta=getFloat();
phi=getFloat();
mn95_x=getFloat();
mn95_y=getFloat();
mn95_z=getFloat();
// compute sector location
lon=((int)round(theta/step)+180)%360;
lat=round(phi/step);
if (lat<0) lat+=180;
lat=(180-lat)%180;
// reference particle in sector lon,lat
sector[lon][lat].push_back(point_index);
// compute cartesian webgl coordinates
phi=(phi-M_PI/2);
theta=theta-M_PI/2;
fx=depth*sin(phi)*cos(theta);
fz=depth*sin(phi)*sin(theta);
fy=-depth*cos(phi);
// store cartesian coordinates
unsigned long k=point_index*3;
positions[k]=fx;
positions[k+1]=fy;
positions[k+2]=fz;
// store mn95 coordinates
mn95[k]=mn95_x;
mn95[k+1]=mn95_y;
mn95[k+2]=mn95_z;
++point_index;
}
if (point_index!=nb_points) {
std::cerr << filename << ": error: nb_points is invalid !" << std::endl;
return 1;
}
// output file marker and version number
outf.write((char*)FILE_MARKER,strlen(FILE_MARKER));
outf.write((char*)FILE_VERSION,strlen(FILE_VERSION));
std::cerr << filename << ": converting to file version " << FILE_VERSION << std::endl;
long int data_offset=outf.tellp();
// output positions formatted as list of x,y,z for each [lon][lat] pair
// and prepare a 360x180 array index formatted as offset,count
std::list<uint32_t> array_index;
for (lat=0; lat<180; ++lat) {
for (lon=0; lon<360; ++lon) {
std::list<uint32_t> *_sector=§or[lon][lat];
// update array index
uint32_t particle_count=_sector->size();
if (particle_count) {
// particles in this sector: store offset and particle count
array_index.push_back((outf.tellp()-data_offset)/sizeof(fx));
array_index.push_back(particle_count);
} else {
// no particles here
array_index.push_back(0);
array_index.push_back(0);
continue;
}
// output particle positions for sector[lon][lat]
for (std::list<uint32_t>::iterator it=_sector->begin(); it!=_sector->end(); ++it) {
uint32_t index=*it;
outf.write((char*)&positions[index*3],sizeof(*positions)*3);
}
}
}
// check integrity
unsigned long positions_byteCount=outf.tellp()-data_offset;
int failure=(positions_byteCount/nb_points!=sizeof(*positions)*3);
std::cerr << filename << ": positions -> " << positions_byteCount << " bytes" << (failure?" -> Invalid count !":"") << std::endl;
if (failure) {
return 1;
}
// output mn95 coordinates
for (lat=0; lat<180; ++lat) {
for (lon=0; lon<360; ++lon) {
std::list<uint32_t> *_sector=§or[lon][lat];
if (!_sector->size()) {
continue;
}
// output mn95 positions for sector[lon][lat]
for (std::list<uint32_t>::iterator it=_sector->begin(); it!=_sector->end(); ++it) {
uint32_t index=*it;
outf.write((char*)&mn95[index],sizeof(*mn95)*3);
}
}
}
// check integrity
long unsigned int mn95_byteCount=(unsigned long)outf.tellp()-data_offset-positions_byteCount;
failure=(mn95_byteCount!=positions_byteCount);
std::cerr << filename << ": mn95 -> " << mn95_byteCount << " bytes" << (failure?" -> Invalid count !":"") << std::endl;
if (failure) {
return 1;
}
// output index formatted as:
// offset, particle_count
for (std::list<uint32_t>::iterator it=array_index.begin(); it!=array_index.end(); ++it) {
uint32_t value=*it;
outf.write((char*)&value,sizeof(value));
}
// check integrity
flush(outf);
long unsigned int index_byteCount=(unsigned long)outf.tellp()-data_offset-positions_byteCount-mn95_byteCount;
failure=(index_byteCount%4);
std::cerr << filename << ": index -> " << index_byteCount << " bytes" << ((index_byteCount%4)?" -> not a multiple of 4 !":"") << std::endl;
if (failure) {
return 1;
}
outf.write((char*)FILE_MARKER,strlen(FILE_MARKER));
outf.close();
if (mn95_byteCount!=positions_byteCount) {
std::cerr << "error: mn95_byteCount != positions_byteCount ! " << std::endl;
return 1;
}
return 0;
}
<|endoftext|>
|
<commit_before>#include "rand.hpp"
#include "ui/menu.hpp"
#include "ui/event.hpp"
#include "ui/window.hpp"
#include "ui/keyboard/keyid.h"
#include "ui/keyboard/keytable.h"
#include "sys/resource.hpp"
#include "sys/config.hpp"
#include "sys/path.hpp"
#include <gtk/gtk.h>
#include <gtk/gtkgl.h>
#include <stdlib.h>
class GTKWindow : public UI::Window {
public:
virtual void close();
};
void GTKWindow::close()
{ }
static const unsigned int MAX_FPS = 100;
static const unsigned int MIN_FRAMETIME = 1000 / MAX_FPS;
static gboolean expose(GtkWidget *area, GdkEventConfigure *event,
gpointer user_data)
{
GdkGLContext *context = gtk_widget_get_gl_context(area);
GdkGLDrawable *drawable = gtk_widget_get_gl_drawable(area);
if (!gdk_gl_drawable_gl_begin(drawable, context)) {
fputs("Could not begin GL drawing\n", stderr);
exit(1);
}
GTKWindow *w = reinterpret_cast<GTKWindow *>(user_data);
w->draw();
if (gdk_gl_drawable_is_double_buffered(drawable))
gdk_gl_drawable_swap_buffers(drawable);
else
glFlush();
gdk_gl_drawable_gl_end(drawable);
return TRUE;
}
static gboolean update(gpointer user_data)
{
GtkWidget *area = GTK_WIDGET(user_data);
gdk_window_invalidate_rect(area->window, &area->allocation, FALSE);
gdk_window_process_updates(area->window, FALSE);
return TRUE;
}
static gboolean key(GtkWidget *widget, GdkEventKey *event,
gpointer user_data)
{
int code = event->hardware_keycode, hcode;
if (code < 0 || code > 255)
return true;
hcode = EVDEV_NATIVE_TO_HID[code];
printf("Key %d %s\n", code, keyid_name_from_code(hcode));
return false;
}
int main(int argc, char *argv[])
{
gboolean r;
GTKWindow w;
gtk_init(&argc, &argv);
gtk_gl_init(&argc, &argv);
Path::init();
w.setSize(768, 480);
Rand::global.seed();
w.setScreen(new UI::Menu);
GtkWidget *window = gtk_window_new(GTK_WINDOW_TOPLEVEL);
gtk_window_set_title(GTK_WINDOW(window), "Game");
gtk_window_set_default_size(GTK_WINDOW(window), 768, 480);
g_signal_connect_swapped(G_OBJECT(window), "destroy",
G_CALLBACK(gtk_main_quit), NULL);
GtkWidget *area = gtk_drawing_area_new();
gtk_container_add(GTK_CONTAINER(window), area);
gtk_widget_set_events(area, GDK_EXPOSURE_MASK);
gtk_widget_show(window);
GdkScreen *screen = gtk_window_get_screen(GTK_WINDOW(window));
static const int ATTRIB_1[] = {
GDK_GL_RGBA,
GDK_GL_DOUBLEBUFFER,
GDK_GL_RED_SIZE, 8,
GDK_GL_BLUE_SIZE, 8,
GDK_GL_GREEN_SIZE, 8,
GDK_GL_ALPHA_SIZE, 8,
GDK_GL_ATTRIB_LIST_NONE
};
static const int ATTRIB_2[] = {
GDK_GL_RGBA,
GDK_GL_DOUBLEBUFFER,
GDK_GL_RED_SIZE, 1,
GDK_GL_BLUE_SIZE, 1,
GDK_GL_GREEN_SIZE, 1,
GDK_GL_ALPHA_SIZE, 1,
GDK_GL_ATTRIB_LIST_NONE
};
const int *attrib[] = { ATTRIB_1, ATTRIB_2, 0 };
GdkGLConfig *config = 0;
for (unsigned int i = 0; !config && attrib[i]; ++i)
config = gdk_gl_config_new_for_screen(screen, attrib[i]);
if (!config) {
fputs("Could not initialize GdkGL\n", stderr);
return 1;
}
r = gtk_widget_set_gl_capability(
area, config, NULL, TRUE, GDK_GL_RGBA_TYPE);
if (!r) {
fputs("Could not assign GL capability\n", stderr);
return 1;
}
/*
g_signal_connect(area, "configure-event",
G_CALLBACK(configure), NULL);
*/
g_signal_connect(area, "expose-event",
G_CALLBACK(expose), &w);
g_signal_connect(window, "key-press-event", G_CALLBACK(key), &w);
g_signal_connect(window, "key-release-event", G_CALLBACK(key), &w);
gtk_widget_show_all(window);
g_timeout_add(10, update, area);
gtk_main();
return 0;
}
<commit_msg>Move GTK key events to drawing area<commit_after>#include "rand.hpp"
#include "ui/menu.hpp"
#include "ui/event.hpp"
#include "ui/window.hpp"
#include "ui/keyboard/keyid.h"
#include "ui/keyboard/keytable.h"
#include "sys/resource.hpp"
#include "sys/config.hpp"
#include "sys/path.hpp"
#include <gtk/gtk.h>
#include <gtk/gtkgl.h>
#include <stdlib.h>
class GTKWindow : public UI::Window {
public:
virtual void close();
};
void GTKWindow::close()
{ }
static const unsigned int MAX_FPS = 100;
static const unsigned int MIN_FRAMETIME = 1000 / MAX_FPS;
static gboolean expose(GtkWidget *area, GdkEventConfigure *event,
gpointer user_data)
{
GdkGLContext *context = gtk_widget_get_gl_context(area);
GdkGLDrawable *drawable = gtk_widget_get_gl_drawable(area);
if (!gdk_gl_drawable_gl_begin(drawable, context)) {
fputs("Could not begin GL drawing\n", stderr);
exit(1);
}
GTKWindow *w = reinterpret_cast<GTKWindow *>(user_data);
w->draw();
if (gdk_gl_drawable_is_double_buffered(drawable))
gdk_gl_drawable_swap_buffers(drawable);
else
glFlush();
gdk_gl_drawable_gl_end(drawable);
return TRUE;
}
static gboolean update(gpointer user_data)
{
GtkWidget *area = GTK_WIDGET(user_data);
gdk_window_invalidate_rect(area->window, &area->allocation, FALSE);
gdk_window_process_updates(area->window, FALSE);
return TRUE;
}
static gboolean key(GtkWidget *widget, GdkEventKey *event,
gpointer user_data)
{
int code = event->hardware_keycode, hcode;
if (code < 0 || code > 255)
return true;
hcode = EVDEV_NATIVE_TO_HID[code];
printf("Key %d %s\n", code, keyid_name_from_code(hcode));
return false;
}
int main(int argc, char *argv[])
{
gboolean r;
GTKWindow w;
gtk_init(&argc, &argv);
gtk_gl_init(&argc, &argv);
Path::init();
w.setSize(768, 480);
Rand::global.seed();
w.setScreen(new UI::Menu);
GtkWidget *window = gtk_window_new(GTK_WINDOW_TOPLEVEL);
gtk_window_set_title(GTK_WINDOW(window), "Game");
gtk_window_set_default_size(GTK_WINDOW(window), 768, 480);
g_signal_connect_swapped(G_OBJECT(window), "destroy",
G_CALLBACK(gtk_main_quit), NULL);
GtkWidget *area = gtk_drawing_area_new();
gtk_container_add(GTK_CONTAINER(window), area);
gtk_widget_set_can_focus(area, TRUE);
unsigned mask = GDK_EXPOSURE_MASK |
GDK_KEY_PRESS_MASK | GDK_KEY_RELEASE_MASK;
gtk_widget_set_events(area, mask);
gtk_widget_show(window);
gtk_widget_grab_focus(area);
GdkScreen *screen = gtk_window_get_screen(GTK_WINDOW(window));
static const int ATTRIB_1[] = {
GDK_GL_RGBA,
GDK_GL_DOUBLEBUFFER,
GDK_GL_RED_SIZE, 8,
GDK_GL_BLUE_SIZE, 8,
GDK_GL_GREEN_SIZE, 8,
GDK_GL_ALPHA_SIZE, 8,
GDK_GL_ATTRIB_LIST_NONE
};
static const int ATTRIB_2[] = {
GDK_GL_RGBA,
GDK_GL_DOUBLEBUFFER,
GDK_GL_RED_SIZE, 1,
GDK_GL_BLUE_SIZE, 1,
GDK_GL_GREEN_SIZE, 1,
GDK_GL_ALPHA_SIZE, 1,
GDK_GL_ATTRIB_LIST_NONE
};
const int *attrib[] = { ATTRIB_1, ATTRIB_2, 0 };
GdkGLConfig *config = 0;
for (unsigned int i = 0; !config && attrib[i]; ++i)
config = gdk_gl_config_new_for_screen(screen, attrib[i]);
if (!config) {
fputs("Could not initialize GdkGL\n", stderr);
return 1;
}
r = gtk_widget_set_gl_capability(
area, config, NULL, TRUE, GDK_GL_RGBA_TYPE);
if (!r) {
fputs("Could not assign GL capability\n", stderr);
return 1;
}
/*
g_signal_connect(area, "configure-event",
G_CALLBACK(configure), NULL);
*/
g_signal_connect(area, "expose-event",
G_CALLBACK(expose), &w);
g_signal_connect(area, "key-press-event", G_CALLBACK(key), &w);
g_signal_connect(area, "key-release-event", G_CALLBACK(key), &w);
gtk_widget_show_all(window);
g_timeout_add(10, update, area);
gtk_main();
return 0;
}
<|endoftext|>
|
<commit_before>///
/// @file LoadBalancerP2.cpp
/// @brief This load balancer assigns work to the threads in the
/// computation of the 2nd partial sieve function.
/// It is used by the P2(x, a) and B(x, y) functions.
///
/// Copyright (C) 2021 Kim Walisch, <[email protected]>
///
/// This file is distributed under the BSD License. See the COPYING
/// file in the top level directory.
///
#include <LoadBalancerP2.hpp>
#include <primecount-internal.hpp>
#include <imath.hpp>
#include <min.hpp>
#include <stdint.h>
#include <algorithm>
#include <cmath>
#include <iostream>
#include <iomanip>
using namespace std;
namespace primecount {
/// We need to sieve [sqrt(x), sieve_limit[
LoadBalancerP2::LoadBalancerP2(maxint_t x,
int64_t sieve_limit,
int threads,
bool is_print) :
low_(isqrt(x)),
sieve_limit_(sieve_limit),
precision_(get_status_precision(x)),
is_print_(is_print)
{
// Ensure that the thread initialization (i.e. the
// computation of PrimePi(low)) is at most 10%
// of the entire thread computation.
int64_t O_primepi = (int64_t) std::pow(sieve_limit, 2.0 / 3.0);
min_thread_dist_ = O_primepi * 10;
min_thread_dist_ = max(O_primepi, 1 << 22);
low_ = min(low_, sieve_limit_);
int64_t dist = sieve_limit_ - low_;
// For large sieving distances we can reduce the
// thread distance as the additional overhead becomes
// less of an issue. This improves load balancing and
// the status is updated more frequently.
int64_t log2_dist = ilog2(dist);
int64_t load_balancing_factor = (log2_dist / 8) + log2_dist - min(log2_dist, 30);
thread_dist_ = dist / (threads * max(load_balancing_factor, 1));
thread_dist_ = max(min_thread_dist_, thread_dist_);
threads_ = ideal_num_threads(threads, dist, thread_dist_);
}
int LoadBalancerP2::get_threads() const
{
return threads_;
}
/// The thread needs to sieve [low, high[
bool LoadBalancerP2::get_work(int64_t& low, int64_t& high)
{
LockGuard lockGuard(lock_);
print_status();
// Calculate the remaining sieving distance
low_ = min(low_, sieve_limit_);
int64_t dist = sieve_limit_ - low_;
if (threads_ == 1)
{
if (!is_print_)
thread_dist_ = dist;
}
else
{
int64_t max_thread_dist = dist / threads_;
// Reduce the thread distance near to end to keep all
// threads busy until the computation finishes.
if (thread_dist_ > max_thread_dist)
thread_dist_ = max(min_thread_dist_, max_thread_dist);
}
low = low_;
low_ += thread_dist_;
low_ = min(low_, sieve_limit_);
high = low_;
return low < sieve_limit_;
}
void LoadBalancerP2::print_status()
{
if (is_print_)
{
double time = get_time();
double old = time_;
double threshold = 0.1;
if (old == 0 || (time - old) >= threshold)
{
time_ = time;
cout << "\rStatus: " << fixed << setprecision(precision_)
<< get_percent(low_, sieve_limit_) << '%' << flush;
}
}
}
} // namespace
<commit_msg>Simplify load balancing<commit_after>///
/// @file LoadBalancerP2.cpp
/// @brief This load balancer assigns work to the threads in the
/// computation of the 2nd partial sieve function.
/// It is used by the P2(x, a) and B(x, y) functions.
///
/// Copyright (C) 2021 Kim Walisch, <[email protected]>
///
/// This file is distributed under the BSD License. See the COPYING
/// file in the top level directory.
///
#include <LoadBalancerP2.hpp>
#include <primecount-internal.hpp>
#include <imath.hpp>
#include <min.hpp>
#include <stdint.h>
#include <algorithm>
#include <cmath>
#include <iostream>
#include <iomanip>
using namespace std;
namespace primecount {
/// We need to sieve [sqrt(x), sieve_limit[
LoadBalancerP2::LoadBalancerP2(maxint_t x,
int64_t sieve_limit,
int threads,
bool is_print) :
low_(isqrt(x)),
sieve_limit_(sieve_limit),
precision_(get_status_precision(x)),
is_print_(is_print)
{
min_thread_dist_ = 1 << 22;
int64_t load_balancing_factor = 8;
// Ensure that the thread initialization (i.e. the
// computation of PrimePi(low)) is at most 10%
// of the entire thread computation.
int64_t O_primepi = (int64_t) std::pow(sieve_limit, 2.0 / 3.0);
min_thread_dist_ = O_primepi * 10;
min_thread_dist_ = max(min_thread_dist_, O_primepi);
low_ = min(low_, sieve_limit_);
int64_t dist = sieve_limit_ - low_;
thread_dist_ = dist / (threads * load_balancing_factor);
thread_dist_ = max(min_thread_dist_, thread_dist_);
threads_ = ideal_num_threads(threads, dist, thread_dist_);
}
int LoadBalancerP2::get_threads() const
{
return threads_;
}
/// The thread needs to sieve [low, high[
bool LoadBalancerP2::get_work(int64_t& low, int64_t& high)
{
LockGuard lockGuard(lock_);
print_status();
// Calculate the remaining sieving distance
low_ = min(low_, sieve_limit_);
int64_t dist = sieve_limit_ - low_;
// When a single thread is used (and printing is
// disabled) we can set thread_dist to the entire
// sieving distance as load balancing is only
// useful for multi-threading.
if (threads_ == 1)
{
if (!is_print_)
thread_dist_ = dist;
}
else
{
int64_t max_thread_dist = dist / threads_;
// Reduce the thread distance near to end to keep all
// threads busy until the computation finishes.
if (thread_dist_ > max_thread_dist)
thread_dist_ = max(min_thread_dist_, max_thread_dist);
}
low = low_;
low_ += thread_dist_;
low_ = min(low_, sieve_limit_);
high = low_;
return low < sieve_limit_;
}
void LoadBalancerP2::print_status()
{
if (is_print_)
{
double time = get_time();
double old = time_;
double threshold = 0.1;
if (old == 0 || (time - old) >= threshold)
{
time_ = time;
cout << "\rStatus: " << fixed << setprecision(precision_)
<< get_percent(low_, sieve_limit_) << '%' << flush;
}
}
}
} // namespace
<|endoftext|>
|
<commit_before>#include "Application.h"
#include <cstdio>
Application::Application()
: Application("Untitled Window")
{ }
Application::Application(std::string title)
: Application(title, 640, 480, false)
{ }
Application::Application(std::string title, unsigned int width, unsigned int height)
: Application(title, width, height, false)
{ }
Application::Application(std::string title, unsigned int width, unsigned int height, bool fullscreen)
: window(NULL),
renderer(NULL),
title(title),
windowWidth(640),
windowHeight(480),
isFullscreen(fullscreen),
backgroundColor({ 0xFF, 0xFF, 0xFF, 0xFF }),
quit(false)
{
}
Application::~Application()
{
printf("Closing...\n");
close();
}
void Application::Run()
{
//Event handler
SDL_Event e;
// Initialize the app
quit = !init();
if (quit)
printf("Initialization failed\n");
printf("Entering application loop...\n");
//While application is running
while (!quit)
{
//Handle events on queue
while (SDL_PollEvent(&e) != 0)
{
//User requests quit
if (e.type == SDL_QUIT)
quit = true;
// Quit if the user presses ESC when the window is fullscreen
if (isFullscreen && e.type == SDL_KEYDOWN && e.key.keysym.sym == SDLK_ESCAPE) {
quit = true;
}
}
// Update state
this->on_update();
// Perform rendering
this->draw();
// Wait for 100 ms
SDL_Delay(100);
}
}
bool Application::init()
{
//Initialize SDL
if (SDL_Init(SDL_INIT_VIDEO) < 0)
{
printf("SDL could not initialize! SDL Error: %s\n", SDL_GetError());
return false;
}
//Set texture filtering to linear
if (!SDL_SetHint(SDL_HINT_RENDER_SCALE_QUALITY, "1"))
{
printf("Warning: Linear texture filtering not enabled!");
}
//Create the window
int flags = SDL_WINDOW_SHOWN;
if (isFullscreen)
flags = SDL_WINDOW_SHOWN | SDL_WINDOW_FULLSCREEN;
window = SDL_CreateWindow(title.c_str(), SDL_WINDOWPOS_UNDEFINED, SDL_WINDOWPOS_UNDEFINED, windowWidth, windowHeight, flags);
if (window == NULL)
{
printf("Window could not be created! SDL Error: %s\n", SDL_GetError());
return false;
}
//Create renderer for window
renderer = SDL_CreateRenderer(window, -1, SDL_RENDERER_ACCELERATED);
if (renderer == NULL)
{
printf("Renderer could not be created! SDL Error: %s\n", SDL_GetError());
return false;
}
// Windows are ready, trigger the on_init event
this->on_init();
//Initialize renderer color (rgba) to background color
SDL_SetRenderDrawColor(renderer, backgroundColor.r, backgroundColor.g, backgroundColor.b, backgroundColor.a);
return true;
}
void Application::on_init()
{
printf("Initialization complete...\n");
}
void Application::close()
{
// Free resources & zero pointers
SDL_DestroyRenderer(renderer);
SDL_DestroyWindow(window);
window = NULL;
renderer = NULL;
// Quit
SDL_Quit();
}
void Application::on_update()
{
}
void Application::on_draw(SDL_Renderer* renderer)
{
}
void Application::draw()
{
//Clear screen using the background color
SDL_SetRenderDrawColor(renderer, backgroundColor.r, backgroundColor.g, backgroundColor.b, backgroundColor.a);
SDL_RenderClear(renderer);
// Trigger the on_draw event
on_draw(renderer);
// Update the screen
SDL_RenderPresent(renderer);
}
void Application::set_background_color(SDL_Color color)
{
this->backgroundColor = color;
}
<commit_msg>Wait for 10ms at the end of the gameloop<commit_after>#include "Application.h"
#include <cstdio>
Application::Application()
: Application("Untitled Window")
{ }
Application::Application(std::string title)
: Application(title, 640, 480, false)
{ }
Application::Application(std::string title, unsigned int width, unsigned int height)
: Application(title, width, height, false)
{ }
Application::Application(std::string title, unsigned int width, unsigned int height, bool fullscreen)
: window(NULL),
renderer(NULL),
title(title),
windowWidth(640),
windowHeight(480),
isFullscreen(fullscreen),
backgroundColor({ 0xFF, 0xFF, 0xFF, 0xFF }),
quit(false)
{
}
Application::~Application()
{
printf("Closing...\n");
close();
}
void Application::Run()
{
//Event handler
SDL_Event e;
// Initialize the app
quit = !init();
if (quit)
printf("Initialization failed\n");
printf("Entering application loop...\n");
//While application is running
while (!quit)
{
//Handle events on queue
while (SDL_PollEvent(&e) != 0)
{
//User requests quit
if (e.type == SDL_QUIT)
quit = true;
// Quit if the user presses ESC when the window is fullscreen
if (isFullscreen && e.type == SDL_KEYDOWN && e.key.keysym.sym == SDLK_ESCAPE) {
quit = true;
}
}
// Update state
this->on_update();
// Perform rendering
this->draw();
// Wait for 10 ms
SDL_Delay(10);
}
}
bool Application::init()
{
//Initialize SDL
if (SDL_Init(SDL_INIT_VIDEO) < 0)
{
printf("SDL could not initialize! SDL Error: %s\n", SDL_GetError());
return false;
}
//Set texture filtering to linear
if (!SDL_SetHint(SDL_HINT_RENDER_SCALE_QUALITY, "1"))
{
printf("Warning: Linear texture filtering not enabled!");
}
//Create the window
int flags = SDL_WINDOW_SHOWN;
if (isFullscreen)
flags = SDL_WINDOW_SHOWN | SDL_WINDOW_FULLSCREEN;
window = SDL_CreateWindow(title.c_str(), SDL_WINDOWPOS_UNDEFINED, SDL_WINDOWPOS_UNDEFINED, windowWidth, windowHeight, flags);
if (window == NULL)
{
printf("Window could not be created! SDL Error: %s\n", SDL_GetError());
return false;
}
//Create renderer for window
renderer = SDL_CreateRenderer(window, -1, SDL_RENDERER_ACCELERATED);
if (renderer == NULL)
{
printf("Renderer could not be created! SDL Error: %s\n", SDL_GetError());
return false;
}
// Windows are ready, trigger the on_init event
this->on_init();
//Initialize renderer color (rgba) to background color
SDL_SetRenderDrawColor(renderer, backgroundColor.r, backgroundColor.g, backgroundColor.b, backgroundColor.a);
return true;
}
void Application::on_init()
{
printf("Initialization complete...\n");
}
void Application::close()
{
// Free resources & zero pointers
SDL_DestroyRenderer(renderer);
SDL_DestroyWindow(window);
window = NULL;
renderer = NULL;
// Quit
SDL_Quit();
}
void Application::on_update()
{
}
void Application::on_draw(SDL_Renderer* renderer)
{
}
void Application::draw()
{
//Clear screen using the background color
SDL_SetRenderDrawColor(renderer, backgroundColor.r, backgroundColor.g, backgroundColor.b, backgroundColor.a);
SDL_RenderClear(renderer);
// Trigger the on_draw event
on_draw(renderer);
// Update the screen
SDL_RenderPresent(renderer);
}
void Application::set_background_color(SDL_Color color)
{
this->backgroundColor = color;
}
<|endoftext|>
|
<commit_before>#include <ros/ros.h>
#include <sensor_msgs/PointCloud2.h>
#include <pcl_ros/point_cloud.h>
#include <pcl/io/pcd_io.h>
#include <pcl/point_types.h>
#include <pcl/visualization/pcl_visualizer.h>
#include <boost/thread/thread.hpp>
#include "mongodb_store/SetParam.h"
#include <actionlib/server/simple_action_server.h>
#include <calibrate_chest/CalibrateCameraAction.h>
class CalibrateCameraServer {
private:
//bool do_calibrate; // register and unregister instead
ros::NodeHandle n;
actionlib::SimpleActionServer<calibrate_chest::CalibrateCameraAction> server;
std::string action_name;
ros::ServiceClient client;
//ros::Subscriber sub;
std::string camera_topic;
calibrate_chest::CalibrateCameraFeedback feedback;
calibrate_chest::CalibrateCameraResult result;
public:
CalibrateCameraServer(const std::string& name, const std::string& camera_name) :
//do_calibrate(false),
server(n, name, boost::bind(&CalibrateCameraServer::execute_cb, this, _1), false),
action_name(name),
client(n.serviceClient<mongodb_store::SetParam>("/config_manager/set_param")),
camera_topic(camera_name + "/depth/points")
{
//sub = n.subscribe(camera_topic, 1, &CalibrateCameraServer::msg_callback, this);
server.start();
}
private:
bool is_inlier(const Eigen::Vector3f& point, const Eigen::Vector4f plane, double threshold) const
{
return fabs(point.dot(plane.segment<3>(0)) + plane(3)) < threshold;
}
void plot_best_plane(const pcl::PointCloud<pcl::PointXYZ>& points, const Eigen::Vector4f plane, double threshold) const
{
pcl::PointCloud<pcl::PointXYZ>::Ptr inlier_cloud(new pcl::PointCloud<pcl::PointXYZ>());
pcl::PointCloud<pcl::PointXYZ>::Ptr outlier_cloud(new pcl::PointCloud<pcl::PointXYZ>());
for (int i = 0; i < points.size(); ++i) {
if (is_inlier(points[i].getVector3fMap(), plane, threshold)) {
inlier_cloud->push_back(points[i]);
}
else {
outlier_cloud->push_back(points[i]);
}
}
pcl::visualization::PCLVisualizer viewer("3D Viewer");
viewer.setBackgroundColor(0, 0, 0);
viewer.addCoordinateSystem(1.0);
viewer.initCameraParameters();
pcl::visualization::PointCloudColorHandlerCustom<pcl::PointXYZ> inlier_color_handler(inlier_cloud, 255, 0, 0);
viewer.addPointCloud(inlier_cloud, inlier_color_handler, "inliers");
pcl::visualization::PointCloudColorHandlerCustom<pcl::PointXYZ> outlier_color_handler(outlier_cloud, 0, 0, 255);
viewer.addPointCloud(outlier_cloud, outlier_color_handler, "outliers");
while (!viewer.wasStopped())
{
viewer.spinOnce(100);
boost::this_thread::sleep(boost::posix_time::microseconds(100000));
}
}
void compute_plane(Eigen::Vector4f& plane, const pcl::PointCloud<pcl::PointXYZ>& points, int* inds) const
{
Eigen::Vector3f first = points[inds[1]].getVector3fMap() - points[inds[0]].getVector3fMap();
Eigen::Vector3f second = points[inds[2]].getVector3fMap() - points[inds[0]].getVector3fMap();
Eigen::Vector3f normal = first.cross(second);
normal.normalize();
plane.segment<3>(0) = normal;
plane(3) = -normal.dot(points[inds[0]].getVector3fMap());
}
void extract_height_and_angle(const Eigen::Vector4f& plane)
{
feedback.status = "Checking and saving calibration...";
server.publishFeedback(feedback);
ROS_INFO("Ground plane: %f, %f, %f, %f", plane(0), plane(1), plane(2), plane(3));
double dist = fabs(plane(3)/plane(2)); // distance along z axis
double height = fabs(plane(3)/plane.segment<3>(0).squaredNorm()); // height
ROS_INFO("Distance to plane along camera axis: %f", dist);
ROS_INFO("Height above ground: %f", height);
double angle = asin(height/dist);
double angle_deg = 180.0f*angle/M_PI;
ROS_INFO("Angle radians: %f", angle);
ROS_INFO("Angle degrees: %f", angle_deg);
result.angle = angle_deg;
result.height = height;
if (fabs(45.0f - angle_deg) > 3.0f) {
result.status = "Angle not close enough to 45 degrees.";
server.setAborted(result);
return;
}
mongodb_store::SetParam srv;
char buffer[250];
// store height above ground in datacentre
ros::param::set("/chest_xtion_height", height);
sprintf(buffer, "{\"path\":\"/chest_xtion_height\",\"value\":%f}", height);
srv.request.param = buffer;
if (!client.call(srv)) {
ROS_ERROR("Failed to call set height, is config manager running?");
}
// store angle between camera and horizontal plane
ros::param::set("/chest_xtion_angle", angle);
sprintf(buffer, "{\"path\":\"/chest_xtion_angle\",\"value\":%f}", angle);
srv.request.param = buffer;
if (!client.call(srv)) {
ROS_ERROR("Failed to call set angle, is config manager running?");
}
result.status = "Successfully computed and saved calibration.";
server.setSucceeded(result);
}
public:
void msg_callback(const sensor_msgs::PointCloud2::ConstPtr& msg)
{
//if (!do_calibrate) {
// return;
//}
//do_calibrate = false;
feedback.status = "Calibrating...";
feedback.progress = 0.0f;
server.publishFeedback(feedback);
ROS_INFO("Got a pointcloud, calibrating...");
pcl::PointCloud<pcl::PointXYZ> cloud;
pcl::fromROSMsg(*msg, cloud);
int nbr = cloud.size();
int max = 1000; // ransac iterations
double threshold = 0.02; // threshold for plane inliers
Eigen::Vector4f best_plane; // best plane parameters found
int best_inliers = -1; // best number of inliers
int inds[3];
Eigen::Vector4f plane;
int inliers;
for (int i = 0; i < max; ++i) {
for (int j = 0; j < 3; ++j) {
inds[j] = rand() % nbr; // get a random point
}
// check that the points aren't the same
if (inds[0] == inds[1] || inds[0] == inds[2] || inds[1] == inds[2]) {
continue;
}
compute_plane(plane, cloud, inds);
inliers = 0;
for (int j = 0; j < nbr; j += 30) { // count number of inliers
if (is_inlier(cloud[j].getVector3fMap(), plane, threshold)) {
++inliers;
}
}
if (inliers > best_inliers) {
best_plane = plane;
best_inliers = inliers;
feedback.progress = float(i+1)/float(max);
server.publishFeedback(feedback);
}
}
extract_height_and_angle(best_plane); // find parameters and feed them to datacentre
//plot_best_plane(cloud, best_plane, threshold); // visually evaluate plane fit
}
void execute_cb(const calibrate_chest::CalibrateCameraGoalConstPtr& goal)
{
if (goal->command == "calibrate") {
sensor_msgs::PointCloud2::ConstPtr msg = ros::topic::waitForMessage<sensor_msgs::PointCloud2>(camera_topic, n);
if (msg) {
msg_callback(msg);
}
else {
result.status = "Did not receive any point cloud.";
server.setAborted(result);
}
}
else {
result.status = "Enter command \"calibrate\" or \"publish\".";
server.setAborted(result);
}
}
};
int main(int argc, char** argv)
{
ros::init(argc, argv, "calibrate_chest");
CalibrateCameraServer calibrate(ros::this_node::getName(), "chest_xtion");
ros::spin();
return 0;
}
<commit_msg>Added the publish option to the action server as well<commit_after>#include <ros/ros.h>
#include <sensor_msgs/PointCloud2.h>
#include <pcl_ros/point_cloud.h>
#include <pcl/io/pcd_io.h>
#include <pcl/point_types.h>
#include <pcl/visualization/pcl_visualizer.h>
#include <boost/thread/thread.hpp>
#include "mongodb_store/SetParam.h"
#include <actionlib/server/simple_action_server.h>
#include <calibrate_chest/CalibrateCameraAction.h>
#include <sensor_msgs/JointState.h>
class CalibrateCameraServer {
private:
//bool do_calibrate; // register and unregister instead
ros::NodeHandle n;
actionlib::SimpleActionServer<calibrate_chest::CalibrateCameraAction> server;
std::string action_name;
ros::ServiceClient client;
//ros::Subscriber sub;
std::string camera_topic;
calibrate_chest::CalibrateCameraFeedback feedback;
calibrate_chest::CalibrateCameraResult result;
public:
CalibrateCameraServer(const std::string& name, const std::string& camera_name) :
//do_calibrate(false),
server(n, name, boost::bind(&CalibrateCameraServer::execute_cb, this, _1), false),
action_name(name),
client(n.serviceClient<mongodb_store::SetParam>("/config_manager/set_param")),
camera_topic(camera_name + "/depth/points")
{
//sub = n.subscribe(camera_topic, 1, &CalibrateCameraServer::msg_callback, this);
server.start();
}
private:
bool is_inlier(const Eigen::Vector3f& point, const Eigen::Vector4f plane, double threshold) const
{
return fabs(point.dot(plane.segment<3>(0)) + plane(3)) < threshold;
}
void plot_best_plane(const pcl::PointCloud<pcl::PointXYZ>& points, const Eigen::Vector4f plane, double threshold) const
{
pcl::PointCloud<pcl::PointXYZ>::Ptr inlier_cloud(new pcl::PointCloud<pcl::PointXYZ>());
pcl::PointCloud<pcl::PointXYZ>::Ptr outlier_cloud(new pcl::PointCloud<pcl::PointXYZ>());
for (int i = 0; i < points.size(); ++i) {
if (is_inlier(points[i].getVector3fMap(), plane, threshold)) {
inlier_cloud->push_back(points[i]);
}
else {
outlier_cloud->push_back(points[i]);
}
}
pcl::visualization::PCLVisualizer viewer("3D Viewer");
viewer.setBackgroundColor(0, 0, 0);
viewer.addCoordinateSystem(1.0);
viewer.initCameraParameters();
pcl::visualization::PointCloudColorHandlerCustom<pcl::PointXYZ> inlier_color_handler(inlier_cloud, 255, 0, 0);
viewer.addPointCloud(inlier_cloud, inlier_color_handler, "inliers");
pcl::visualization::PointCloudColorHandlerCustom<pcl::PointXYZ> outlier_color_handler(outlier_cloud, 0, 0, 255);
viewer.addPointCloud(outlier_cloud, outlier_color_handler, "outliers");
while (!viewer.wasStopped())
{
viewer.spinOnce(100);
boost::this_thread::sleep(boost::posix_time::microseconds(100000));
}
}
void compute_plane(Eigen::Vector4f& plane, const pcl::PointCloud<pcl::PointXYZ>& points, int* inds) const
{
Eigen::Vector3f first = points[inds[1]].getVector3fMap() - points[inds[0]].getVector3fMap();
Eigen::Vector3f second = points[inds[2]].getVector3fMap() - points[inds[0]].getVector3fMap();
Eigen::Vector3f normal = first.cross(second);
normal.normalize();
plane.segment<3>(0) = normal;
plane(3) = -normal.dot(points[inds[0]].getVector3fMap());
}
void extract_height_and_angle(const Eigen::Vector4f& plane)
{
feedback.status = "Checking and saving calibration...";
server.publishFeedback(feedback);
ROS_INFO("Ground plane: %f, %f, %f, %f", plane(0), plane(1), plane(2), plane(3));
double dist = fabs(plane(3)/plane(2)); // distance along z axis
double height = fabs(plane(3)/plane.segment<3>(0).squaredNorm()); // height
ROS_INFO("Distance to plane along camera axis: %f", dist);
ROS_INFO("Height above ground: %f", height);
double angle = asin(height/dist);
double angle_deg = 180.0f*angle/M_PI;
ROS_INFO("Angle radians: %f", angle);
ROS_INFO("Angle degrees: %f", angle_deg);
result.angle = angle_deg;
result.height = height;
if (fabs(45.0f - angle_deg) > 3.0f) {
result.status = "Angle not close enough to 45 degrees.";
server.setAborted(result);
return;
}
mongodb_store::SetParam srv;
char buffer[250];
// store height above ground in datacentre
ros::param::set("/chest_xtion_height", height);
sprintf(buffer, "{\"path\":\"/chest_xtion_height\",\"value\":%f}", height);
srv.request.param = buffer;
if (!client.call(srv)) {
ROS_ERROR("Failed to call set height, is config manager running?");
}
// store angle between camera and horizontal plane
ros::param::set("/chest_xtion_angle", angle);
sprintf(buffer, "{\"path\":\"/chest_xtion_angle\",\"value\":%f}", angle);
srv.request.param = buffer;
if (!client.call(srv)) {
ROS_ERROR("Failed to call set angle, is config manager running?");
}
result.status = "Successfully computed and saved calibration.";
server.setSucceeded(result);
}
void publish_calibration()
{
feedback.status = "Publishing calibration...";
feedback.progress = 0.0f;
// get calibration with respect to ground plane from the calibrate_chest node
double height, angle;
n.param<double>("/chest_xtion_height", height, 1.10f); // get the height calibration
n.param<double>("/chest_xtion_angle", angle, 0.72f); // get the angle calibration
ros::Rate rate(1.0f);
ros::Publisher pub = n.advertise<sensor_msgs::JointState>("/chest_calibration_publisher/state", 1);
int counter = 0; // only publish for the first 10 secs, transforms will stay in tf
while (n.ok() && counter < 5) {
sensor_msgs::JointState joint_state;
joint_state.header.stamp = ros::Time::now();
joint_state.name.resize(2);
joint_state.position.resize(2);
joint_state.velocity.resize(2);
joint_state.name[0] = "chest_xtion_height_joint";
joint_state.name[1] = "chest_xtion_tilt_joint";
joint_state.position[0] = height;
joint_state.position[1] = angle;
joint_state.velocity[0] = 0;
joint_state.velocity[1] = 0;
pub.publish(joint_state);
rate.sleep();
++counter;
feedback.progress = float(counter+1)/5.0f;
server.publishFeedback(feedback);
}
ROS_INFO("Stopping to publish chest transform after 10 seconds, quitting...");
result.status = "Published calibration.";
result.angle = 180.0f/M_PI*angle;
result.height = height;
server.setSucceeded(result);
}
public:
void msg_callback(const sensor_msgs::PointCloud2::ConstPtr& msg)
{
//if (!do_calibrate) {
// return;
//}
//do_calibrate = false;
feedback.status = "Calibrating...";
feedback.progress = 0.0f;
server.publishFeedback(feedback);
ROS_INFO("Got a pointcloud, calibrating...");
pcl::PointCloud<pcl::PointXYZ> cloud;
pcl::fromROSMsg(*msg, cloud);
int nbr = cloud.size();
int max = 1000; // ransac iterations
double threshold = 0.02; // threshold for plane inliers
Eigen::Vector4f best_plane; // best plane parameters found
int best_inliers = -1; // best number of inliers
int inds[3];
Eigen::Vector4f plane;
int inliers;
for (int i = 0; i < max; ++i) {
for (int j = 0; j < 3; ++j) {
inds[j] = rand() % nbr; // get a random point
}
// check that the points aren't the same
if (inds[0] == inds[1] || inds[0] == inds[2] || inds[1] == inds[2]) {
continue;
}
compute_plane(plane, cloud, inds);
inliers = 0;
for (int j = 0; j < nbr; j += 30) { // count number of inliers
if (is_inlier(cloud[j].getVector3fMap(), plane, threshold)) {
++inliers;
}
}
if (inliers > best_inliers) {
best_plane = plane;
best_inliers = inliers;
}
if (i % 10 == 0) {
feedback.progress = float(i+1)/float(max);
server.publishFeedback(feedback);
}
}
extract_height_and_angle(best_plane); // find parameters and feed them to datacentre
//plot_best_plane(cloud, best_plane, threshold); // visually evaluate plane fit
}
void execute_cb(const calibrate_chest::CalibrateCameraGoalConstPtr& goal)
{
if (goal->command == "calibrate") {
sensor_msgs::PointCloud2::ConstPtr msg = ros::topic::waitForMessage<sensor_msgs::PointCloud2>(camera_topic, n);
if (msg) {
msg_callback(msg);
}
else {
result.status = "Did not receive any point cloud.";
server.setAborted(result);
}
}
else if (goal->command == "publish") {
publish_calibration();
}
else {
result.status = "Enter command \"calibrate\" or \"publish\".";
server.setAborted(result);
}
}
};
int main(int argc, char** argv)
{
ros::init(argc, argv, "calibrate_chest");
CalibrateCameraServer calibrate(ros::this_node::getName(), "chest_xtion");
ros::spin();
return 0;
}
<|endoftext|>
|
<commit_before>#include "jni_util.h"
extern "C" {
void helloworld(JNIEnv *env, jobject clazz, jstring jni_str) {
const char *str_utf8 = env->GetStringUTFChars(jni_str, nullptr);
//LOGI(str_utf8);
env->ReleaseStringUTFChars(jni_str, str_utf8);
}
}
JNINativeMethod g_helloworld_methods[] = {
{"say_hello", "(Ljava/lang/String;)V", (void *)helloworld}
};
extern "C" const int g_helloworld_methods_num = sizeof(g_helloworld_methods) / sizeof(g_helloworld_methods[0]);
<commit_msg>gcc werror=format-security<commit_after>#include "jni_util.h"
extern "C" {
void helloworld(JNIEnv *env, jobject clazz, jstring jni_str) {
const char *str_utf8 = env->GetStringUTFChars(jni_str, nullptr);
LOGI("%s", str_utf8);
env->ReleaseStringUTFChars(jni_str, str_utf8);
}
}
JNINativeMethod g_helloworld_methods[] = {
{"say_hello", "(Ljava/lang/String;)V", (void *)helloworld}
};
extern "C" const int g_helloworld_methods_num = sizeof(g_helloworld_methods) / sizeof(g_helloworld_methods[0]);
<|endoftext|>
|
<commit_before>
{{#global}}
#include <Servo.h>
{{/global}}
/*
A wrapper around the stock Servo object because we need to keep some details
which the original object hides in private fields. This over-protection leads
to increased RAM usage to duplicate the data. A pull request to the original
library asking to add field read methods would be nice.
*/
class XServo : public Servo {
protected:
// Here are the duplicates
uint8_t port;
int pulseMin;
int pulseMax;
public:
// Set pulse duration according the given `value` and set pulseMin, pulseMax
// The value is clipped to the [0; 1] range
void write01(Number value) {
ensureAttached();
int pseudoAngle = constrain((int)(value * 180), 0, 180);
this->write(pseudoAngle);
}
// Performs Servo::attach with the parameters set previously
void ensureAttached() {
if (this->attached())
return;
this->attach(port, pulseMin, pulseMax);
}
Number read01() const {
int us = this->readMicroseconds();
return (Number)(us - pulseMin) / (Number)(pulseMax - pulseMin);
}
void reattach(uint8_t port, int pulseMin, int pulseMax) {
this->port = port;
this->pulseMin = pulseMin;
this->pulseMax = pulseMax;
if (this->attached())
this->attach(port, pulseMin, pulseMax);
}
};
using State = XServo;
using Type = XServo*;
{{ GENERATED_CODE }}
void evaluate(Context ctx) {
State* servo = getState(ctx);
servo->reattach(
getValue<input_PORT>(ctx),
getValue<input_Pmin>(ctx),
getValue<input_Pmax>(ctx)
);
emitValue<output_DEV>(ctx, servo);
}
<commit_msg>fix(stdlib): do not mark XServo’s read01 method as const in xod-dev/servo/servo-device implementation<commit_after>
{{#global}}
#include <Servo.h>
{{/global}}
/*
A wrapper around the stock Servo object because we need to keep some details
which the original object hides in private fields. This over-protection leads
to increased RAM usage to duplicate the data. A pull request to the original
library asking to add field read methods would be nice.
*/
class XServo : public Servo {
protected:
// Here are the duplicates
uint8_t port;
int pulseMin;
int pulseMax;
public:
// Set pulse duration according the given `value` and set pulseMin, pulseMax
// The value is clipped to the [0; 1] range
void write01(Number value) {
ensureAttached();
int pseudoAngle = constrain((int)(value * 180), 0, 180);
this->write(pseudoAngle);
}
// Performs Servo::attach with the parameters set previously
void ensureAttached() {
if (this->attached())
return;
this->attach(port, pulseMin, pulseMax);
}
Number read01() {
int us = this->readMicroseconds();
return (Number)(us - pulseMin) / (Number)(pulseMax - pulseMin);
}
void reattach(uint8_t port, int pulseMin, int pulseMax) {
this->port = port;
this->pulseMin = pulseMin;
this->pulseMax = pulseMax;
if (this->attached())
this->attach(port, pulseMin, pulseMax);
}
};
using State = XServo;
using Type = XServo*;
{{ GENERATED_CODE }}
void evaluate(Context ctx) {
State* servo = getState(ctx);
servo->reattach(
getValue<input_PORT>(ctx),
getValue<input_Pmin>(ctx),
getValue<input_Pmax>(ctx)
);
emitValue<output_DEV>(ctx, servo);
}
<|endoftext|>
|
<commit_before>/*
*
* Copyright (c) 2021 Project CHIP 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.
*/
/**
* @file Contains shell commands for a ContentApp relating to Content App platform of the Video Player.
*/
#include "AppPlatformShellCommands.h"
#include "ControllerShellCommands.h"
#include <AppMain.h>
#include <inttypes.h>
#include <lib/core/CHIPCore.h>
#include <lib/shell/Commands.h>
#include <lib/shell/Engine.h>
#include <lib/shell/commands/Help.h>
#include <lib/support/CHIPArgParser.hpp>
#include <lib/support/CHIPMem.h>
#include <lib/support/CodeUtils.h>
#include <platform/CHIPDeviceLayer.h>
#if CHIP_DEVICE_CONFIG_APP_PLATFORM_ENABLED
#include <app/app-platform/ContentAppPlatform.h>
#endif // CHIP_DEVICE_CONFIG_APP_PLATFORM_ENABLED
using namespace ::chip::Controller;
#if CHIP_DEVICE_CONFIG_APP_PLATFORM_ENABLED
using namespace chip::AppPlatform;
#endif // CHIP_DEVICE_CONFIG_APP_PLATFORM_ENABLED
using namespace chip::app::Clusters;
#if CHIP_DEVICE_CONFIG_APP_PLATFORM_ENABLED
namespace chip {
namespace Shell {
static CHIP_ERROR pairApp(bool printHeader, size_t index)
{
streamer_t * sout = streamer_get();
if (printHeader)
{
streamer_printf(sout, "udc-commission %ld\r\n", index);
}
DeviceCommissioner * commissioner = GetDeviceCommissioner();
UDCClientState * state = commissioner->GetUserDirectedCommissioningServer()->GetUDCClients().GetUDCClientState(index);
if (state == nullptr)
{
streamer_printf(sout, "udc client[%d] null \r\n", index);
}
else
{
ContentApp * app = ContentAppPlatform::GetInstance().LoadContentAppByClient(state->GetVendorId(), state->GetProductId());
if (app == nullptr)
{
streamer_printf(sout, "no app found for vendor id=%d \r\n", state->GetVendorId());
return CHIP_ERROR_BAD_REQUEST;
}
if (app->GetAccountLoginDelegate() == nullptr)
{
streamer_printf(sout, "no AccountLogin cluster for app with vendor id=%d \r\n", state->GetVendorId());
return CHIP_ERROR_BAD_REQUEST;
}
char rotatingIdString[chip::Dnssd::kMaxRotatingIdLen * 2 + 1] = "";
Encoding::BytesToUppercaseHexString(state->GetRotatingId(), state->GetRotatingIdLength(), rotatingIdString,
sizeof(rotatingIdString));
CharSpan rotatingIdSpan = CharSpan(rotatingIdString, strlen(rotatingIdString));
static const size_t kSetupPinSize = 12;
char setupPin[kSetupPinSize];
app->GetAccountLoginDelegate()->GetSetupPin(setupPin, kSetupPinSize, rotatingIdSpan);
std::string pinString(setupPin);
char * eptr;
uint32_t pincode = (uint32_t) strtol(pinString.c_str(), &eptr, 10);
if (pincode == 0)
{
streamer_printf(sout, "udc no pin returned for vendor id=%d rotating ID=%s \r\n", state->GetVendorId(),
rotatingIdString);
return CHIP_ERROR_BAD_REQUEST;
}
return CommissionerPairUDC(pincode, index);
}
return CHIP_NO_ERROR;
}
static CHIP_ERROR PrintAllCommands()
{
streamer_t * sout = streamer_get();
streamer_printf(sout, " help Usage: app <subcommand>\r\n");
streamer_printf(sout, " add <vid> [<pid>] Add app with given vendor ID [1, 2, 9050]. Usage: app add 9050\r\n");
streamer_printf(sout, " remove <endpoint> Remove app at given endpoint [6, 7, etc]. Usage: app remove 6\r\n");
streamer_printf(sout,
" setpin <endpoint> <pincode> Set pincode for app with given endpoint ID. Usage: app setpin 6 34567890\r\n");
streamer_printf(sout,
" commission <udc-entry> Commission given udc-entry using given pincode from corresponding app. Usage: "
"app commission 0\r\n");
streamer_printf(sout, "\r\n");
return CHIP_NO_ERROR;
}
static CHIP_ERROR AppPlatformHandler(int argc, char ** argv)
{
CHIP_ERROR error = CHIP_NO_ERROR;
if (argc == 0 || strcmp(argv[0], "help") == 0)
{
return PrintAllCommands();
}
else if (strcmp(argv[0], "add") == 0)
{
if (argc < 2)
{
return PrintAllCommands();
}
char * eptr;
uint16_t vid = (uint16_t) strtol(argv[1], &eptr, 10);
uint16_t pid = 0;
if (argc >= 3)
{
pid = (uint16_t) strtol(argv[1], &eptr, 10);
}
ContentAppPlatform::GetInstance().LoadContentAppByClient(vid, pid);
ChipLogProgress(DeviceLayer, "added app");
return CHIP_NO_ERROR;
}
else if (strcmp(argv[0], "remove") == 0)
{
if (argc < 2)
{
return PrintAllCommands();
}
char * eptr;
uint16_t endpoint = (uint16_t) strtol(argv[1], &eptr, 10);
ContentApp * app = ContentAppPlatform::GetInstance().GetContentApp(endpoint);
if (app == nullptr)
{
ChipLogProgress(DeviceLayer, "app not found");
return CHIP_ERROR_BAD_REQUEST;
}
ContentAppPlatform::GetInstance().RemoveContentApp(app);
ChipLogProgress(DeviceLayer, "removed app");
return CHIP_NO_ERROR;
}
else if (strcmp(argv[0], "setpin") == 0)
{
if (argc < 3)
{
return PrintAllCommands();
}
char * eptr;
uint16_t endpoint = (uint16_t) strtol(argv[1], &eptr, 10);
char * pincode = argv[2];
ContentApp * app = ContentAppPlatform::GetInstance().GetContentApp(endpoint);
if (app == nullptr)
{
ChipLogProgress(DeviceLayer, "app not found");
return CHIP_ERROR_BAD_REQUEST;
}
if (app->GetAccountLoginDelegate() == nullptr)
{
ChipLogProgress(DeviceLayer, "no AccountLogin cluster for app with endpoint id=%d ", endpoint);
return CHIP_ERROR_BAD_REQUEST;
}
app->GetAccountLoginDelegate()->SetSetupPin(pincode);
ChipLogProgress(DeviceLayer, "set pin success");
return CHIP_NO_ERROR;
}
else if (strcmp(argv[0], "commission") == 0)
{
if (argc < 2)
{
return PrintAllCommands();
}
char * eptr;
size_t index = (size_t) strtol(argv[1], &eptr, 10);
return error = pairApp(true, index);
}
else
{
return CHIP_ERROR_INVALID_ARGUMENT;
}
return error;
}
void RegisterAppPlatformCommands()
{
static const shell_command_t sDeviceComand = { &AppPlatformHandler, "app", "App commands. Usage: app [command_name]" };
// Register the root `device` command with the top-level shell.
Engine::Root().RegisterCommands(&sDeviceComand, 1);
return;
}
} // namespace Shell
} // namespace chip
#endif // CHIP_DEVICE_CONFIG_APP_PLATFORM_ENABLED
<commit_msg>Bug fix to initialize pid correctly from 2nd shell argument (#17980)<commit_after>/*
*
* Copyright (c) 2021 Project CHIP 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.
*/
/**
* @file Contains shell commands for a ContentApp relating to Content App platform of the Video Player.
*/
#include "AppPlatformShellCommands.h"
#include "ControllerShellCommands.h"
#include <AppMain.h>
#include <inttypes.h>
#include <lib/core/CHIPCore.h>
#include <lib/shell/Commands.h>
#include <lib/shell/Engine.h>
#include <lib/shell/commands/Help.h>
#include <lib/support/CHIPArgParser.hpp>
#include <lib/support/CHIPMem.h>
#include <lib/support/CodeUtils.h>
#include <platform/CHIPDeviceLayer.h>
#if CHIP_DEVICE_CONFIG_APP_PLATFORM_ENABLED
#include <app/app-platform/ContentAppPlatform.h>
#endif // CHIP_DEVICE_CONFIG_APP_PLATFORM_ENABLED
using namespace ::chip::Controller;
#if CHIP_DEVICE_CONFIG_APP_PLATFORM_ENABLED
using namespace chip::AppPlatform;
#endif // CHIP_DEVICE_CONFIG_APP_PLATFORM_ENABLED
using namespace chip::app::Clusters;
#if CHIP_DEVICE_CONFIG_APP_PLATFORM_ENABLED
namespace chip {
namespace Shell {
static CHIP_ERROR pairApp(bool printHeader, size_t index)
{
streamer_t * sout = streamer_get();
if (printHeader)
{
streamer_printf(sout, "udc-commission %ld\r\n", index);
}
DeviceCommissioner * commissioner = GetDeviceCommissioner();
UDCClientState * state = commissioner->GetUserDirectedCommissioningServer()->GetUDCClients().GetUDCClientState(index);
if (state == nullptr)
{
streamer_printf(sout, "udc client[%d] null \r\n", index);
}
else
{
ContentApp * app = ContentAppPlatform::GetInstance().LoadContentAppByClient(state->GetVendorId(), state->GetProductId());
if (app == nullptr)
{
streamer_printf(sout, "no app found for vendor id=%d \r\n", state->GetVendorId());
return CHIP_ERROR_BAD_REQUEST;
}
if (app->GetAccountLoginDelegate() == nullptr)
{
streamer_printf(sout, "no AccountLogin cluster for app with vendor id=%d \r\n", state->GetVendorId());
return CHIP_ERROR_BAD_REQUEST;
}
char rotatingIdString[chip::Dnssd::kMaxRotatingIdLen * 2 + 1] = "";
Encoding::BytesToUppercaseHexString(state->GetRotatingId(), state->GetRotatingIdLength(), rotatingIdString,
sizeof(rotatingIdString));
CharSpan rotatingIdSpan = CharSpan(rotatingIdString, strlen(rotatingIdString));
static const size_t kSetupPinSize = 12;
char setupPin[kSetupPinSize];
app->GetAccountLoginDelegate()->GetSetupPin(setupPin, kSetupPinSize, rotatingIdSpan);
std::string pinString(setupPin);
char * eptr;
uint32_t pincode = (uint32_t) strtol(pinString.c_str(), &eptr, 10);
if (pincode == 0)
{
streamer_printf(sout, "udc no pin returned for vendor id=%d rotating ID=%s \r\n", state->GetVendorId(),
rotatingIdString);
return CHIP_ERROR_BAD_REQUEST;
}
return CommissionerPairUDC(pincode, index);
}
return CHIP_NO_ERROR;
}
static CHIP_ERROR PrintAllCommands()
{
streamer_t * sout = streamer_get();
streamer_printf(sout, " help Usage: app <subcommand>\r\n");
streamer_printf(sout, " add <vid> [<pid>] Add app with given vendor ID [1, 2, 9050]. Usage: app add 9050\r\n");
streamer_printf(sout, " remove <endpoint> Remove app at given endpoint [6, 7, etc]. Usage: app remove 6\r\n");
streamer_printf(sout,
" setpin <endpoint> <pincode> Set pincode for app with given endpoint ID. Usage: app setpin 6 34567890\r\n");
streamer_printf(sout,
" commission <udc-entry> Commission given udc-entry using given pincode from corresponding app. Usage: "
"app commission 0\r\n");
streamer_printf(sout, "\r\n");
return CHIP_NO_ERROR;
}
static CHIP_ERROR AppPlatformHandler(int argc, char ** argv)
{
CHIP_ERROR error = CHIP_NO_ERROR;
if (argc == 0 || strcmp(argv[0], "help") == 0)
{
return PrintAllCommands();
}
else if (strcmp(argv[0], "add") == 0)
{
if (argc < 2)
{
return PrintAllCommands();
}
char * eptr;
uint16_t vid = (uint16_t) strtol(argv[1], &eptr, 10);
uint16_t pid = 0;
if (argc >= 3)
{
pid = (uint16_t) strtol(argv[2], &eptr, 10);
}
ContentAppPlatform::GetInstance().LoadContentAppByClient(vid, pid);
ChipLogProgress(DeviceLayer, "added app");
return CHIP_NO_ERROR;
}
else if (strcmp(argv[0], "remove") == 0)
{
if (argc < 2)
{
return PrintAllCommands();
}
char * eptr;
uint16_t endpoint = (uint16_t) strtol(argv[1], &eptr, 10);
ContentApp * app = ContentAppPlatform::GetInstance().GetContentApp(endpoint);
if (app == nullptr)
{
ChipLogProgress(DeviceLayer, "app not found");
return CHIP_ERROR_BAD_REQUEST;
}
ContentAppPlatform::GetInstance().RemoveContentApp(app);
ChipLogProgress(DeviceLayer, "removed app");
return CHIP_NO_ERROR;
}
else if (strcmp(argv[0], "setpin") == 0)
{
if (argc < 3)
{
return PrintAllCommands();
}
char * eptr;
uint16_t endpoint = (uint16_t) strtol(argv[1], &eptr, 10);
char * pincode = argv[2];
ContentApp * app = ContentAppPlatform::GetInstance().GetContentApp(endpoint);
if (app == nullptr)
{
ChipLogProgress(DeviceLayer, "app not found");
return CHIP_ERROR_BAD_REQUEST;
}
if (app->GetAccountLoginDelegate() == nullptr)
{
ChipLogProgress(DeviceLayer, "no AccountLogin cluster for app with endpoint id=%d ", endpoint);
return CHIP_ERROR_BAD_REQUEST;
}
app->GetAccountLoginDelegate()->SetSetupPin(pincode);
ChipLogProgress(DeviceLayer, "set pin success");
return CHIP_NO_ERROR;
}
else if (strcmp(argv[0], "commission") == 0)
{
if (argc < 2)
{
return PrintAllCommands();
}
char * eptr;
size_t index = (size_t) strtol(argv[1], &eptr, 10);
return error = pairApp(true, index);
}
else
{
return CHIP_ERROR_INVALID_ARGUMENT;
}
return error;
}
void RegisterAppPlatformCommands()
{
static const shell_command_t sDeviceComand = { &AppPlatformHandler, "app", "App commands. Usage: app [command_name]" };
// Register the root `device` command with the top-level shell.
Engine::Root().RegisterCommands(&sDeviceComand, 1);
return;
}
} // namespace Shell
} // namespace chip
#endif // CHIP_DEVICE_CONFIG_APP_PLATFORM_ENABLED
<|endoftext|>
|
<commit_before>// Copyright 2014 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 "athena/home/public/home_card.h"
#include "athena/activity/public/activity_factory.h"
#include "athena/activity/public/activity_manager.h"
#include "athena/test/athena_test_base.h"
#include "athena/wm/public/window_manager.h"
#include "ui/events/test/event_generator.h"
namespace athena {
typedef test::AthenaTestBase HomeCardTest;
TEST_F(HomeCardTest, BasicTransition) {
EXPECT_EQ(HomeCard::VISIBLE_MINIMIZED, HomeCard::Get()->GetState());
WindowManager::GetInstance()->ToggleOverview();
EXPECT_EQ(HomeCard::VISIBLE_BOTTOM, HomeCard::Get()->GetState());
WindowManager::GetInstance()->ToggleOverview();
EXPECT_EQ(HomeCard::VISIBLE_MINIMIZED, HomeCard::Get()->GetState());
}
TEST_F(HomeCardTest, VirtualKeyboardTransition) {
// Minimized -> Hidden for virtual keyboard.
EXPECT_EQ(HomeCard::VISIBLE_MINIMIZED, HomeCard::Get()->GetState());
const gfx::Rect vk_bounds(0, 0, 100, 100);
HomeCard::Get()->UpdateVirtualKeyboardBounds(vk_bounds);
EXPECT_EQ(HomeCard::HIDDEN, HomeCard::Get()->GetState());
HomeCard::Get()->UpdateVirtualKeyboardBounds(gfx::Rect());
EXPECT_EQ(HomeCard::VISIBLE_MINIMIZED, HomeCard::Get()->GetState());
// bottom -> centered for virtual keyboard.
WindowManager::GetInstance()->ToggleOverview();
EXPECT_EQ(HomeCard::VISIBLE_BOTTOM, HomeCard::Get()->GetState());
HomeCard::Get()->UpdateVirtualKeyboardBounds(vk_bounds);
EXPECT_EQ(HomeCard::VISIBLE_CENTERED, HomeCard::Get()->GetState());
HomeCard::Get()->UpdateVirtualKeyboardBounds(gfx::Rect());
EXPECT_EQ(HomeCard::VISIBLE_BOTTOM, HomeCard::Get()->GetState());
// Overview mode has to finish before ending test, otherwise it crashes.
// TODO(mukai): fix this.
WindowManager::GetInstance()->ToggleOverview();
}
// Verify if the home card is correctly minimized after app launch.
// TODO(flackr): Fix memory leak and re-enable - http://crbug.com/399241
TEST_F(HomeCardTest, DISABLED_AppSelection) {
EXPECT_EQ(HomeCard::VISIBLE_MINIMIZED, HomeCard::Get()->GetState());
WindowManager::GetInstance()->ToggleOverview();
EXPECT_EQ(HomeCard::VISIBLE_BOTTOM, HomeCard::Get()->GetState());
athena::ActivityManager::Get()->AddActivity(
athena::ActivityFactory::Get()->CreateWebActivity(
NULL, GURL("http://www.google.com/")));
EXPECT_EQ(HomeCard::VISIBLE_MINIMIZED, HomeCard::Get()->GetState());
}
TEST_F(HomeCardTest, Accelerators) {
EXPECT_EQ(HomeCard::VISIBLE_MINIMIZED, HomeCard::Get()->GetState());
ui::test::EventGenerator generator(root_window());
generator.PressKey(ui::VKEY_L, ui::EF_CONTROL_DOWN);
EXPECT_EQ(HomeCard::VISIBLE_CENTERED, HomeCard::Get()->GetState());
generator.PressKey(ui::VKEY_L, ui::EF_CONTROL_DOWN);
EXPECT_EQ(HomeCard::VISIBLE_MINIMIZED, HomeCard::Get()->GetState());
// Do nothing for BOTTOM.
WindowManager::GetInstance()->ToggleOverview();
EXPECT_EQ(HomeCard::VISIBLE_BOTTOM, HomeCard::Get()->GetState());
generator.PressKey(ui::VKEY_L, ui::EF_CONTROL_DOWN);
EXPECT_EQ(HomeCard::VISIBLE_BOTTOM, HomeCard::Get()->GetState());
// Do nothing if the centered state is a temporary state.
HomeCard::Get()->UpdateVirtualKeyboardBounds(gfx::Rect(0, 0, 100, 100));
EXPECT_EQ(HomeCard::VISIBLE_CENTERED, HomeCard::Get()->GetState());
generator.PressKey(ui::VKEY_L, ui::EF_CONTROL_DOWN);
EXPECT_EQ(HomeCard::VISIBLE_CENTERED, HomeCard::Get()->GetState());
}
} // namespace athena
<commit_msg>Re-enable HomeCardTest.AppSelection.<commit_after>// Copyright 2014 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 "athena/home/public/home_card.h"
#include "athena/activity/public/activity_factory.h"
#include "athena/activity/public/activity_manager.h"
#include "athena/test/athena_test_base.h"
#include "athena/wm/public/window_manager.h"
#include "ui/events/test/event_generator.h"
namespace athena {
typedef test::AthenaTestBase HomeCardTest;
TEST_F(HomeCardTest, BasicTransition) {
EXPECT_EQ(HomeCard::VISIBLE_MINIMIZED, HomeCard::Get()->GetState());
WindowManager::GetInstance()->ToggleOverview();
EXPECT_EQ(HomeCard::VISIBLE_BOTTOM, HomeCard::Get()->GetState());
WindowManager::GetInstance()->ToggleOverview();
EXPECT_EQ(HomeCard::VISIBLE_MINIMIZED, HomeCard::Get()->GetState());
}
TEST_F(HomeCardTest, VirtualKeyboardTransition) {
// Minimized -> Hidden for virtual keyboard.
EXPECT_EQ(HomeCard::VISIBLE_MINIMIZED, HomeCard::Get()->GetState());
const gfx::Rect vk_bounds(0, 0, 100, 100);
HomeCard::Get()->UpdateVirtualKeyboardBounds(vk_bounds);
EXPECT_EQ(HomeCard::HIDDEN, HomeCard::Get()->GetState());
HomeCard::Get()->UpdateVirtualKeyboardBounds(gfx::Rect());
EXPECT_EQ(HomeCard::VISIBLE_MINIMIZED, HomeCard::Get()->GetState());
// bottom -> centered for virtual keyboard.
WindowManager::GetInstance()->ToggleOverview();
EXPECT_EQ(HomeCard::VISIBLE_BOTTOM, HomeCard::Get()->GetState());
HomeCard::Get()->UpdateVirtualKeyboardBounds(vk_bounds);
EXPECT_EQ(HomeCard::VISIBLE_CENTERED, HomeCard::Get()->GetState());
HomeCard::Get()->UpdateVirtualKeyboardBounds(gfx::Rect());
EXPECT_EQ(HomeCard::VISIBLE_BOTTOM, HomeCard::Get()->GetState());
// Overview mode has to finish before ending test, otherwise it crashes.
// TODO(mukai): fix this.
WindowManager::GetInstance()->ToggleOverview();
}
// Verify if the home card is correctly minimized after app launch.
TEST_F(HomeCardTest, AppSelection) {
EXPECT_EQ(HomeCard::VISIBLE_MINIMIZED, HomeCard::Get()->GetState());
WindowManager::GetInstance()->ToggleOverview();
EXPECT_EQ(HomeCard::VISIBLE_BOTTOM, HomeCard::Get()->GetState());
athena::ActivityManager::Get()->AddActivity(
athena::ActivityFactory::Get()->CreateWebActivity(
NULL, GURL("http://www.google.com/")));
EXPECT_EQ(HomeCard::VISIBLE_MINIMIZED, HomeCard::Get()->GetState());
}
TEST_F(HomeCardTest, Accelerators) {
EXPECT_EQ(HomeCard::VISIBLE_MINIMIZED, HomeCard::Get()->GetState());
ui::test::EventGenerator generator(root_window());
generator.PressKey(ui::VKEY_L, ui::EF_CONTROL_DOWN);
EXPECT_EQ(HomeCard::VISIBLE_CENTERED, HomeCard::Get()->GetState());
generator.PressKey(ui::VKEY_L, ui::EF_CONTROL_DOWN);
EXPECT_EQ(HomeCard::VISIBLE_MINIMIZED, HomeCard::Get()->GetState());
// Do nothing for BOTTOM.
WindowManager::GetInstance()->ToggleOverview();
EXPECT_EQ(HomeCard::VISIBLE_BOTTOM, HomeCard::Get()->GetState());
generator.PressKey(ui::VKEY_L, ui::EF_CONTROL_DOWN);
EXPECT_EQ(HomeCard::VISIBLE_BOTTOM, HomeCard::Get()->GetState());
// Do nothing if the centered state is a temporary state.
HomeCard::Get()->UpdateVirtualKeyboardBounds(gfx::Rect(0, 0, 100, 100));
EXPECT_EQ(HomeCard::VISIBLE_CENTERED, HomeCard::Get()->GetState());
generator.PressKey(ui::VKEY_L, ui::EF_CONTROL_DOWN);
EXPECT_EQ(HomeCard::VISIBLE_CENTERED, HomeCard::Get()->GetState());
}
} // namespace athena
<|endoftext|>
|
<commit_before>// $Id$
//
// Copyright (c) 2001-2006 greg Landrum and Rational Discovery LLC
//
// @@ All Rights Reserved @@
//
#include <iostream>
#include <RDBoost/Exceptions.h>
#include "ExplicitBitVect.h"
#include <RDGeneral/StreamOps.h>
#include "base64.h"
#include <sstream>
#include <limits>
#ifdef WIN32
#include <ios>
#endif
ExplicitBitVect::ExplicitBitVect(const std::string s)
{
d_size=0;dp_bits = 0;d_numOnBits=0;
InitFromText(s.c_str(),s.length());
}
ExplicitBitVect::ExplicitBitVect(const char *data,const unsigned int dataLen)
{
d_size=0;dp_bits = 0;d_numOnBits=0;
InitFromText(data,dataLen);
}
ExplicitBitVect::ExplicitBitVect(const ExplicitBitVect& other){
d_size = other.d_size;
dp_bits = new boost::dynamic_bitset<>(*(other.dp_bits));
d_numOnBits=other.d_numOnBits;
};
ExplicitBitVect& ExplicitBitVect::operator=(const ExplicitBitVect& other){
d_size = other.d_size;
dp_bits = new boost::dynamic_bitset<>(*(other.dp_bits));
d_numOnBits=other.d_numOnBits;
return *this;
};
bool ExplicitBitVect::operator[] (const unsigned int which) const {
if(which < 0 || which >= d_size){
throw IndexErrorException(which);
}
return (bool)(*dp_bits)[which];
};
bool ExplicitBitVect::SetBit(const unsigned int which){
if(which < 0 || which >= d_size){
throw IndexErrorException(which);
}
if((bool)(*dp_bits)[which]){
return true;
} else {
(*dp_bits)[which] = 1;
++d_numOnBits;
return false;
}
};
bool ExplicitBitVect::UnSetBit(const unsigned int which){
if(which < 0 || which >= d_size){
throw IndexErrorException(which);
}
if((bool)(*dp_bits)[which]){
(*dp_bits)[which] = 0;
--d_numOnBits;
return true;
} else {
return false;
}
};
bool ExplicitBitVect::GetBit(const unsigned int which) const {
if(which < 0 || which >= d_size){
throw IndexErrorException(which);
}
return((bool)(*dp_bits)[which]);
};
ExplicitBitVect ExplicitBitVect::operator^ (const ExplicitBitVect &other) const {
ExplicitBitVect ans(d_size);
*(ans.dp_bits) = (*dp_bits) ^ *(other.dp_bits);
ans.d_numOnBits=dp_bits->count();
return(ans);
};
ExplicitBitVect ExplicitBitVect::operator& (const ExplicitBitVect &other) const {
ExplicitBitVect ans(d_size);
*(ans.dp_bits) = (*dp_bits) & *(other.dp_bits);
ans.d_numOnBits=dp_bits->count();
return(ans);
};
ExplicitBitVect ExplicitBitVect::operator| (const ExplicitBitVect &other) const {
ExplicitBitVect ans(d_size);
*(ans.dp_bits) = (*dp_bits) | *(other.dp_bits);
ans.d_numOnBits=dp_bits->count();
return(ans);
};
ExplicitBitVect ExplicitBitVect::operator~ () const {
ExplicitBitVect ans(d_size);
*(ans.dp_bits) = ~(*dp_bits);
ans.d_numOnBits=dp_bits->count();
return(ans);
};
const unsigned int ExplicitBitVect::GetNumBits() const {
return d_size;
};
const unsigned int ExplicitBitVect::GetNumOnBits() const {
return d_numOnBits;
};
const unsigned int ExplicitBitVect::GetNumOffBits() const {
return d_size - d_numOnBits;
};
// the contents of v are blown out
void ExplicitBitVect::GetOnBits (IntVect& v) const {
unsigned int nOn = GetNumOnBits();
if(!v.empty()) IntVect().swap(v);
v.reserve(nOn);
for(unsigned int i=0;i<d_size;i++){
if((bool)(*dp_bits)[i]) v.push_back(i);
}
};
void ExplicitBitVect::_InitForSize(unsigned int size) {
d_size = size;
if(dp_bits) delete dp_bits;
dp_bits = new boost::dynamic_bitset<>(size);
d_numOnBits=0;
};
ExplicitBitVect::~ExplicitBitVect() {
if(dp_bits) delete dp_bits;
};
std::string
ExplicitBitVect::ToString() const
{
// This Function replaces the older version (version 16) of writing the onbits to
// a string
// the old version does not perform any run length encoding, it only checks to see if
// the length of the bitvect can be short ints and writes the on bits as shorts
// other wise the onbits are all written as ints
// here we do run length encoding and the version number has been bumped to 32 as well.
// only the reader needs to take care of readinf all legacy versions
// also in this scheme each bit number written to the string is checked to see how many
// bytes it needs
std::stringstream ss(std::ios_base::binary|std::ios_base::out|std::ios_base::in);
unsigned int nOnBits=GetNumOnBits();
int tVers = ci_BITVECT_VERSION*-1;
ss.write((const char *)&(tVers),sizeof(tVers));
ss.write((const char *)&d_size,sizeof(d_size));
ss.write((const char *)&nOnBits,sizeof(nOnBits));
int prev = -1;
unsigned int zeroes;
for(unsigned int i=0;i<d_size;i++){
if( (bool)(*dp_bits)[i] ){
zeroes = i - prev -1;
RDKit::appendPackedIntToStream(ss, zeroes);
prev = i;
}
}
zeroes = d_size - prev -1;
RDKit::appendPackedIntToStream(ss, zeroes);
std::string res(ss.str());
return res;
}
<commit_msg>onbit counts in results of operator&, operator|, operator^, etc. were incorrect<commit_after>// $Id$
//
// Copyright (c) 2001-2006 greg Landrum and Rational Discovery LLC
//
// @@ All Rights Reserved @@
//
#include <iostream>
#include <RDBoost/Exceptions.h>
#include "ExplicitBitVect.h"
#include <RDGeneral/StreamOps.h>
#include "base64.h"
#include <sstream>
#include <limits>
#ifdef WIN32
#include <ios>
#endif
ExplicitBitVect::ExplicitBitVect(const std::string s)
{
d_size=0;dp_bits = 0;d_numOnBits=0;
InitFromText(s.c_str(),s.length());
}
ExplicitBitVect::ExplicitBitVect(const char *data,const unsigned int dataLen)
{
d_size=0;dp_bits = 0;d_numOnBits=0;
InitFromText(data,dataLen);
}
ExplicitBitVect::ExplicitBitVect(const ExplicitBitVect& other){
d_size = other.d_size;
dp_bits = new boost::dynamic_bitset<>(*(other.dp_bits));
d_numOnBits=other.d_numOnBits;
};
ExplicitBitVect& ExplicitBitVect::operator=(const ExplicitBitVect& other){
d_size = other.d_size;
dp_bits = new boost::dynamic_bitset<>(*(other.dp_bits));
d_numOnBits=other.d_numOnBits;
return *this;
};
bool ExplicitBitVect::operator[] (const unsigned int which) const {
if(which < 0 || which >= d_size){
throw IndexErrorException(which);
}
return (bool)(*dp_bits)[which];
};
bool ExplicitBitVect::SetBit(const unsigned int which){
if(which < 0 || which >= d_size){
throw IndexErrorException(which);
}
if((bool)(*dp_bits)[which]){
return true;
} else {
(*dp_bits)[which] = 1;
++d_numOnBits;
return false;
}
};
bool ExplicitBitVect::UnSetBit(const unsigned int which){
if(which < 0 || which >= d_size){
throw IndexErrorException(which);
}
if((bool)(*dp_bits)[which]){
(*dp_bits)[which] = 0;
--d_numOnBits;
return true;
} else {
return false;
}
};
bool ExplicitBitVect::GetBit(const unsigned int which) const {
if(which < 0 || which >= d_size){
throw IndexErrorException(which);
}
return((bool)(*dp_bits)[which]);
};
ExplicitBitVect ExplicitBitVect::operator^ (const ExplicitBitVect &other) const {
ExplicitBitVect ans(d_size);
*(ans.dp_bits) = (*dp_bits) ^ *(other.dp_bits);
ans.d_numOnBits=ans.dp_bits->count();
return(ans);
};
ExplicitBitVect ExplicitBitVect::operator& (const ExplicitBitVect &other) const {
ExplicitBitVect ans(d_size);
*(ans.dp_bits) = (*dp_bits) & *(other.dp_bits);
ans.d_numOnBits=ans.dp_bits->count();
return(ans);
};
ExplicitBitVect ExplicitBitVect::operator| (const ExplicitBitVect &other) const {
ExplicitBitVect ans(d_size);
*(ans.dp_bits) = (*dp_bits) | *(other.dp_bits);
ans.d_numOnBits=ans.dp_bits->count();
return(ans);
};
ExplicitBitVect ExplicitBitVect::operator~ () const {
ExplicitBitVect ans(d_size);
*(ans.dp_bits) = ~(*dp_bits);
ans.d_numOnBits=ans.dp_bits->count();
return(ans);
};
const unsigned int ExplicitBitVect::GetNumBits() const {
return d_size;
};
const unsigned int ExplicitBitVect::GetNumOnBits() const {
return d_numOnBits;
};
const unsigned int ExplicitBitVect::GetNumOffBits() const {
return d_size - d_numOnBits;
};
// the contents of v are blown out
void ExplicitBitVect::GetOnBits (IntVect& v) const {
unsigned int nOn = GetNumOnBits();
if(!v.empty()) IntVect().swap(v);
v.reserve(nOn);
for(unsigned int i=0;i<d_size;i++){
if((bool)(*dp_bits)[i]) v.push_back(i);
}
};
void ExplicitBitVect::_InitForSize(unsigned int size) {
d_size = size;
if(dp_bits) delete dp_bits;
dp_bits = new boost::dynamic_bitset<>(size);
d_numOnBits=0;
};
ExplicitBitVect::~ExplicitBitVect() {
if(dp_bits) delete dp_bits;
};
std::string
ExplicitBitVect::ToString() const
{
// This Function replaces the older version (version 16) of writing the onbits to
// a string
// the old version does not perform any run length encoding, it only checks to see if
// the length of the bitvect can be short ints and writes the on bits as shorts
// other wise the onbits are all written as ints
// here we do run length encoding and the version number has been bumped to 32 as well.
// only the reader needs to take care of readinf all legacy versions
// also in this scheme each bit number written to the string is checked to see how many
// bytes it needs
std::stringstream ss(std::ios_base::binary|std::ios_base::out|std::ios_base::in);
unsigned int nOnBits=GetNumOnBits();
int tVers = ci_BITVECT_VERSION*-1;
ss.write((const char *)&(tVers),sizeof(tVers));
ss.write((const char *)&d_size,sizeof(d_size));
ss.write((const char *)&nOnBits,sizeof(nOnBits));
int prev = -1;
unsigned int zeroes;
for(unsigned int i=0;i<d_size;i++){
if( (bool)(*dp_bits)[i] ){
zeroes = i - prev -1;
RDKit::appendPackedIntToStream(ss, zeroes);
prev = i;
}
}
zeroes = d_size - prev -1;
RDKit::appendPackedIntToStream(ss, zeroes);
std::string res(ss.str());
return res;
}
<|endoftext|>
|
<commit_before>/*
* This program is free software; you can redistribute it and/or modify
* it under the terms of the GNU General Public License as published by
* the Free Software Foundation; either version 3 of the License, or
* (at your option) any later version.
*
* Written (W) 2012 Fernando José Iglesias García
* Copyright (C) 2012 Fernando José Iglesias García
*/
#include <shogun/base/init.h>
#include <shogun/classifier/QDA.h>
#include <shogun/features/DenseFeatures.h>
#include <shogun/io/SGIO.h>
#include <shogun/lib/common.h>
#include <shogun/mathematics/Math.h>
using namespace shogun;
#define NUM 100
#define DIMS 2
#define DIST 0.5
void gen_rand_data(SGVector< float64_t > lab, SGMatrix< float64_t > feat)
{
for (int32_t i = 0; i < NUM; i++)
{
if (i < NUM/2)
{
lab[i] = 0.0;
for (int32_t j = 0; j < DIMS; j++)
feat[i*DIMS + j] = CMath::random(0.0,1.0) + DIST;
}
else
{
lab[i] = 1.0;
for (int32_t j = 0; j < DIMS; j++)
feat[i*DIMS + j] = CMath::random(0.0,1.0) - DIST;
}
}
}
int main(int argc, char ** argv)
{
const int32_t feature_cache = 0;
init_shogun_with_defaults();
SGVector< float64_t > lab(NUM);
SGMatrix< float64_t > feat(DIMS, NUM);
gen_rand_data(lab, feat);
// Create train labels
CLabels* labels = new CLabels(lab);
// Create train features
CDenseFeatures< float64_t >* features = new CDenseFeatures< float64_t >(feature_cache);
// Create QDA classifier
CQDA* qda = new CQDA(features, labels);
SG_REF(qda);
qda->train();
// Classify and display output
CLabels* out_labels = qda->apply();
SG_REF(out_labels);
// Free memory
SG_UNREF(out_labels);
SG_UNREF(qda);
exit_shogun();
return 0;
}
<commit_msg>Fix classifier_qda example<commit_after>/*
* This program is free software; you can redistribute it and/or modify
* it under the terms of the GNU General Public License as published by
* the Free Software Foundation; either version 3 of the License, or
* (at your option) any later version.
*
* Written (W) 2012 Fernando José Iglesias García
* Copyright (C) 2012 Fernando José Iglesias García
*/
#include <shogun/base/init.h>
#include <shogun/classifier/QDA.h>
#include <shogun/features/DenseFeatures.h>
#include <shogun/io/SGIO.h>
#include <shogun/lib/common.h>
#include <shogun/mathematics/Math.h>
using namespace shogun;
#define NUM 100
#define DIMS 2
#define DIST 0.5
void gen_rand_data(SGVector< float64_t > lab, SGMatrix< float64_t > feat)
{
for (int32_t i = 0; i < NUM; i++)
{
if (i < NUM/2)
{
lab[i] = 0.0;
for (int32_t j = 0; j < DIMS; j++)
feat[i*DIMS + j] = CMath::random(0.0,1.0) + DIST;
}
else
{
lab[i] = 1.0;
for (int32_t j = 0; j < DIMS; j++)
feat[i*DIMS + j] = CMath::random(0.0,1.0) - DIST;
}
}
}
int main(int argc, char ** argv)
{
init_shogun_with_defaults();
SGVector< float64_t > lab(NUM);
SGMatrix< float64_t > feat(DIMS, NUM);
gen_rand_data(lab, feat);
// Create train labels
CLabels* labels = new CLabels(lab);
// Create train features
CDenseFeatures< float64_t >* features = new CDenseFeatures< float64_t >(feat);
// Create QDA classifier
CQDA* qda = new CQDA(features, labels);
SG_REF(qda);
qda->train();
// Classify and display output
CLabels* out_labels = qda->apply();
SG_REF(out_labels);
// Free memory
SG_UNREF(out_labels);
SG_UNREF(qda);
exit_shogun();
return 0;
}
<|endoftext|>
|
<commit_before>// $Id$
//
// Copyright (C) 2003-2006 greg Landrum and Rational Discovery LLC
//
// @@ All Rights Reserved @@
//
#include <DataStructs/BitVects.h>
#include <DataStructs/BitVectUtils.h>
#include <RDBoost/Wrap.h>
namespace python = boost::python;
ExplicitBitVect *createFromBitString(const std::string &bits){
ExplicitBitVect *res=new ExplicitBitVect(bits.length());
FromBitString(*res,bits);
return res;
}
struct Utils_wrapper {
static void wrap(){
python::def("ConvertToExplicit", convertToExplicit,
python::return_value_policy<python::manage_new_object>());
python::def("CreateFromBitString",createFromBitString,
python::return_value_policy<python::manage_new_object>());
python::def("InitFromDaylightString",
(void (*)(SparseBitVect &,std::string))FromDaylightString);
python::def("InitFromDaylightString",
(void (*)(ExplicitBitVect &,std::string))FromDaylightString,
"Fill a BitVect using an ASCII (Daylight) encoding of fingerprint.\n\
\n\
**Arguments**\n\
- bv: either a _SparseBitVect_ or an _ExplicitBitVect_\n\
- txt: a string with the Daylight encoding (this is the text that\n\
the Daylight tools put in the FP field of a TDT)\n\
\n");
}
};
void wrap_Utils() {
Utils_wrapper::wrap();
}
<commit_msg>doc update<commit_after>// $Id$
//
// Copyright (C) 2003-2006 greg Landrum and Rational Discovery LLC
//
// @@ All Rights Reserved @@
//
#include <DataStructs/BitVects.h>
#include <DataStructs/BitVectUtils.h>
#include <RDBoost/Wrap.h>
namespace python = boost::python;
ExplicitBitVect *createFromBitString(const std::string &bits){
ExplicitBitVect *res=new ExplicitBitVect(bits.length());
FromBitString(*res,bits);
return res;
}
struct Utils_wrapper {
static void wrap(){
python::def("ConvertToExplicit", convertToExplicit,
python::return_value_policy<python::manage_new_object>(),
"Converts a SparseBitVector to an ExplicitBitVector and returns the ExplicitBitVector");
python::def("CreateFromBitString",createFromBitString,
python::return_value_policy<python::manage_new_object>(),
"Creates an ExplicitBitVect from a bit string (string of 0s and 1s).");
python::def("InitFromDaylightString",
(void (*)(SparseBitVect &,std::string))FromDaylightString);
python::def("InitFromDaylightString",
(void (*)(ExplicitBitVect &,std::string))FromDaylightString,
"Fill a BitVect using an ASCII (Daylight) encoding of a fingerprint.\n\
\n\
**Arguments**\n\
- bv: either a _SparseBitVect_ or an _ExplicitBitVect_\n\
- txt: a string with the Daylight encoding (this is the text that\n\
the Daylight tools put in the FP field of a TDT)\n\
\n");
}
};
void wrap_Utils() {
Utils_wrapper::wrap();
}
<|endoftext|>
|
<commit_before>/*
* Copyright (C) 2003 Unai Garro <[email protected]>
*/
#include "pref.h"
#include "krecipes.h"
#include "krecipesview.h"
#include "dialogs/recipeviewdialog.h"
#include "dialogs/recipeinputdialog.h"
#include "dialogs/selectrecipedialog.h"
#include "dialogs/ingredientsdialog.h"
#include "dialogs/propertiesdialog.h"
#include "dialogs/shoppinglistdialog.h"
#include "dialogs/categorieseditordialog.h"
#include "dialogs/authorsdialog.h"
#include "dialogs/unitsdialog.h"
#include "dialogs/ingredientmatcherdialog.h"
#include "gui/pagesetupdialog.h"
#include "importers/kreimporter.h"
#include "importers/mmfimporter.h"
#include "importers/mx2importer.h"
#include "importers/mxpimporter.h"
#include "importers/nycgenericimporter.h"
#include "importers/recipemlimporter.h"
#include "importers/rezkonvimporter.h"
#include "recipe.h"
#include "DBBackend/recipedb.h"
#include <qdragobject.h>
#include <kprinter.h>
#include <qpainter.h>
#include <qpaintdevicemetrics.h>
#include <qmessagebox.h>
#include <kprogress.h>
#include <kmessagebox.h>
#include <kglobal.h>
#include <klocale.h>
#include <kiconloader.h>
#include <kmenubar.h>
#include <kstatusbar.h>
#include <kkeydialog.h>
#include <kaccel.h>
#include <kio/netaccess.h>
#include <kfiledialog.h>
#include <kconfig.h>
#include <kcursor.h>
#include <kedittoolbar.h>
#include <kstdaccel.h>
#include <kaction.h>
#include <kstdaction.h>
//Settings headers
#include <kdeversion.h>
Krecipes::Krecipes()
: KMainWindow( 0, "Krecipes" ),
m_view(new KrecipesView(this)),
m_printer(0)
{
// accept dnd
setAcceptDrops(true);
// tell the KMainWindow that this is indeed the main widget
setCentralWidget(m_view);
// then, setup our actions
setupActions();
// and a status bar
statusBar()->show();
// apply the saved mainwindow settings, if any, and ask the mainwindow
// to automatically save settings if changed: window size, toolbar
// position, icon size, etc.
setAutoSaveSettings();
// allow the view to change the statusbar and caption
connect(m_view, SIGNAL(signalChangeStatusbar(const QString&)),
this, SLOT(changeStatusbar(const QString&)));
connect(m_view, SIGNAL(signalChangeCaption(const QString&)),
this, SLOT(changeCaption(const QString&)));
connect(m_view, SIGNAL(panelShown(KrePanel,bool)),SLOT(updateActions(KrePanel,bool)));
// Enable/Disable the Save Button (Initialize disabled, and connect signal)
connect(this->m_view, SIGNAL(enableSaveOption(bool)), this, SLOT(enableSaveOption(bool)));
enableSaveOption(false); // Disables saving initially
parsing_file_dlg = new KDialog(this,"parsing_file_dlg",true,Qt::WX11BypassWM);
QLabel *parsing_file_dlg_label = new QLabel(i18n("Gathering recipe data from file.\nPlease wait..."),parsing_file_dlg);
parsing_file_dlg_label->setFrameStyle( QFrame::Box | QFrame::Raised );
(new QVBoxLayout(parsing_file_dlg))->addWidget( parsing_file_dlg_label );
parsing_file_dlg->adjustSize();
//parsing_file_dlg->setFixedSize(parsing_file_dlg->size());
}
Krecipes::~Krecipes()
{
}
void Krecipes::updateActions( KrePanel panel, bool show )
{
switch ( panel )
{
case RecipeView:
{
saveAsAction->setEnabled(show);
printAction->setEnabled(show);
reloadAction->setEnabled(show);
//can't edit when there are multiple recipes loaded
if ( show && m_view->viewPanel->recipesLoaded() == 1 ) {
editAction->setEnabled(true);
}
else
editAction->setEnabled(false);
break;
}
case SelectP:
{
saveAsAction->setEnabled(show);
editAction->setEnabled(show);
break;
}
default: break;
}
}
void Krecipes::setupActions()
{
KIconLoader il;
saveAsAction=KStdAction::saveAs(this, SLOT(fileSaveAs()), actionCollection());
printAction = KStdAction::print(this, SLOT(filePrint()), actionCollection());
reloadAction = new KAction(i18n("Reloa&d"), "reload", Key_F5, m_view, SLOT(reloadDisplay()), actionCollection(), "reload_action");
editAction = new KAction(i18n("&Edit Recipe"), "edit", CTRL+Key_E,
m_view, SLOT(editRecipe()),
actionCollection(), "edit_action");
KAction *action = KStdAction::openNew(this, SLOT(fileNew()), actionCollection());
action->setText(i18n("&New Recipe"));
saveAction=KStdAction::save(this, SLOT(fileSave()), actionCollection());
KStdAction::quit(kapp, SLOT(quit()), actionCollection());
m_toolbarAction = KStdAction::showToolbar(this, SLOT(optionsShowToolbar()), actionCollection());
m_statusbarAction = KStdAction::showStatusbar(this, SLOT(optionsShowStatusbar()), actionCollection());
KStdAction::keyBindings(this, SLOT(optionsConfigureKeys()), actionCollection());
KStdAction::configureToolbars(this, SLOT(optionsConfigureToolbars()), actionCollection());
KStdAction::preferences(this, SLOT(optionsPreferences()), actionCollection());
(void)new KAction(i18n("Import..."), CTRL+Key_I,
this, SLOT(import()),
actionCollection(), "import_action");
(void)new KAction(i18n("Page Setup..."), 0,
this, SLOT(pageSetupSlot()),
actionCollection(), "page_setup_action");
updateActions( SelectP, true );
updateActions( RecipeView, false );
createGUI();
}
void Krecipes::saveProperties(KConfig *)
{
// the 'config' object points to the session managed
// config file. anything you write here will be available
// later when this app is restored
//if (!m_view->currentURL().isNull())
// config->writeEntry("lastURL", m_view->currentURL());
}
void Krecipes::readProperties(KConfig *)
{
// the 'config' object points to the session managed
// config file. this function is automatically called whenever
// the app is being restored. read in here whatever you wrote
// in 'saveProperties'
//QString url = config->readEntry("lastURL");
//if (!url.isNull())
// m_view->openURL(KURL(url));
}
void Krecipes::dragEnterEvent(QDragEnterEvent *event)
{
// accept uri drops only
event->accept(QUriDrag::canDecode(event));
}
void Krecipes::fileNew()
{
// Create a new element (Element depends on active panel. New recipe by default)
m_view->createNewElement();
}
void Krecipes::fileOpen()
{
// this slot is called whenever the File->Open menu is selected,
// the Open shortcut is pressed (usually CTRL+O) or the Open toolbar
// button is clicked
/*
// this brings up the generic open dialog
KURL url = KURLRequesterDlg::getURL(QString::null, this, i18n("Open Location") );
*/
// standard filedialog
/*KURL url = KFileDialog::getOpenURL(QString::null, QString::null, this, i18n("Open Location"));
if (!url.isEmpty())
m_view->openURL(url);*/
}
void Krecipes::fileSave()
{
// this slot is called whenever the File->Save menu is selected,
// the Save shortcut is pressed (usually CTRL+S) or the Save toolbar
// button is clicked
m_view->save();
}
void Krecipes::fileSaveAs()
{
// this slot is called whenever the File->Save As menu is selected,
m_view->exportRecipe();
}
void Krecipes::filePrint()
{
m_view->print();
}
void Krecipes::import()
{
KFileDialog file_dialog( QString::null,
"*.kre *.kreml|Krecipes (*.kre, *.kreml)\n"
"*.mx2|MasterCook (*.mx2)\n"
"*.mxp *.txt|MasterCook Export (*.mxp, *.txt)\n"
"*.mmf *.txt|Meal-Master (*.mmf, *.txt)\n"
"*.txt|\"Now You're Cooking\" Generic Export (*.txt)\n"
"*.xml *.recipeml|RecipeML (*.xml, *.recipeml)\n"
"*.rk *.txt|Rezkonv (*.rk, *.txt)",
this,
"file_dialog",
true
);
file_dialog.setMode( KFile::Files );
if ( file_dialog.exec() == KFileDialog::Accepted )
{
QStringList warnings_list;
QString selected_filter = file_dialog.currentFilter();
BaseImporter *importer;
if ( selected_filter == "*.mxp *.txt" )
importer = new MXPImporter();
else if ( selected_filter == "*.mmf *.txt" )
importer = new MMFImporter();
else if ( selected_filter == "*.txt" )
importer = new NYCGenericImporter();
else if ( selected_filter == "*.mx2" )
importer = new MX2Importer();
else if ( selected_filter == "*.kre *.kreml" )
importer = new KreImporter();
else if ( selected_filter == "*.xml *.recipeml" )
importer = new RecipeMLImporter();
else if ( selected_filter == "*.rk *.txt" )
importer = new RezkonvImporter();
else
{
KMessageBox::sorry( this,
QString(i18n("Filter \"%1\" not recognized.\n"
"Please select one of the provided filters.")).arg(selected_filter),
i18n("Unrecognized Filter")
);
import(); //let's try again :)
return;
}
parsing_file_dlg->show(); KApplication::setOverrideCursor( KCursor::waitCursor() );
importer->parseFiles(file_dialog.selectedFiles());
parsing_file_dlg->hide(); KApplication::restoreOverrideCursor();
m_view->import( *importer );
if ( !importer->getMessages().isEmpty() )
{
KTextEdit *warningEdit = new KTextEdit( this );
warningEdit->setTextFormat( Qt::RichText );
warningEdit->setText( QString(i18n("NOTE: We recommend that all recipes generating warnings be checked to ensure that they were properly imported, and no loss of recipe data has occurred.<br><br>")) + importer->getMessages() );
warningEdit->setReadOnly(true);
KDialogBase showWarningsDlg( KDialogBase::Swallow, i18n("Import warnings"), KDialogBase::Ok, KDialogBase::Default, this );
showWarningsDlg.setMainWidget( warningEdit ); //KDialogBase will delete warningEdit for us
showWarningsDlg.resize( QSize(550,250) );
showWarningsDlg.exec();
}
delete importer;
KApplication::setOverrideCursor( KCursor::waitCursor() );
m_view->selectPanel->reload();
m_view->unitsPanel->reload();
m_view->shoppingListPanel->reload();
KApplication::restoreOverrideCursor();
}
}
void Krecipes::pageSetupSlot()
{
Recipe recipe;
m_view->selectPanel->getCurrentRecipe(&recipe);
PageSetupDialog *page_setup = new PageSetupDialog(this,recipe);
page_setup->exec();
delete page_setup;
}
//return true to close app
bool Krecipes::queryClose()
{
if ( !m_view->inputPanel->everythingSaved() )
{
switch( KMessageBox::questionYesNoCancel( this,
i18n("A recipe contains unsaved changes.\n"
"Do you want to save the changes before exiting?"),
i18n("Unsaved Changes") ) )
{
case KMessageBox::Yes: return m_view->save();
case KMessageBox::No: return true;
case KMessageBox::Cancel: return false;
default: return true;
}
}
else
return true;
}
void Krecipes::optionsShowToolbar()
{
// this is all very cut and paste code for showing/hiding the
// toolbar
if (m_toolbarAction->isChecked())
toolBar()->show();
else
toolBar()->hide();
}
void Krecipes::optionsShowStatusbar()
{
// this is all very cut and paste code for showing/hiding the
// statusbar
if (m_statusbarAction->isChecked())
statusBar()->show();
else
statusBar()->hide();
}
void Krecipes::optionsConfigureKeys()
{
#if KDE_IS_VERSION(3,1,92 )
// for KDE 3.2: KKeyDialog::configureKeys is deprecated
KKeyDialog::configure(actionCollection(), this, true);
#else
KKeyDialog::configureKeys(actionCollection(), "krecipesui.rc");
#endif
}
void Krecipes::optionsConfigureToolbars()
{
// use the standard toolbar editor
#if defined(KDE_MAKE_VERSION)
# if KDE_VERSION >= KDE_MAKE_VERSION(3,1,0)
saveMainWindowSettings(KGlobal::config(), autoSaveGroup());
# else
saveMainWindowSettings(KGlobal::config());
# endif
#else
saveMainWindowSettings(KGlobal::config());
#endif
KEditToolbar dlg(actionCollection());
connect(&dlg, SIGNAL(newToolbarConfig()), this, SLOT(newToolbarConfig()));
dlg.exec();
}
void Krecipes::newToolbarConfig()
{
// this slot is called when user clicks "Ok" or "Apply" in the toolbar editor.
// recreate our GUI, and re-apply the settings (e.g. "text under icons", etc.)
createGUI();
#if defined(KDE_MAKE_VERSION)
# if KDE_VERSION >= KDE_MAKE_VERSION(3,1,0)
applyMainWindowSettings(KGlobal::config(), autoSaveGroup());
# else
applyMainWindowSettings(KGlobal::config());
# endif
#else
applyMainWindowSettings(KGlobal::config());
#endif
}
void Krecipes::optionsPreferences()
{
// popup some sort of preference dialog, here
KrecipesPreferences dlg(this);
if (dlg.exec())
{}
}
void Krecipes::changeStatusbar(const QString& text)
{
// display the text on the statusbar
statusBar()->message(text);
}
void Krecipes::changeCaption(const QString& text)
{
// display the text on the caption
setCaption(text);
}
void Krecipes::enableSaveOption(bool en)
{
saveAction->setEnabled(en);
}
#include "krecipes.moc"
<commit_msg>-Take out unnecessary reloads after the import process<commit_after>/*
* Copyright (C) 2003 Unai Garro <[email protected]>
*/
#include "pref.h"
#include "krecipes.h"
#include "krecipesview.h"
#include "dialogs/recipeviewdialog.h"
#include "dialogs/recipeinputdialog.h"
#include "dialogs/selectrecipedialog.h"
#include "dialogs/ingredientsdialog.h"
#include "dialogs/propertiesdialog.h"
#include "dialogs/shoppinglistdialog.h"
#include "dialogs/categorieseditordialog.h"
#include "dialogs/authorsdialog.h"
#include "dialogs/unitsdialog.h"
#include "dialogs/ingredientmatcherdialog.h"
#include "gui/pagesetupdialog.h"
#include "importers/kreimporter.h"
#include "importers/mmfimporter.h"
#include "importers/mx2importer.h"
#include "importers/mxpimporter.h"
#include "importers/nycgenericimporter.h"
#include "importers/recipemlimporter.h"
#include "importers/rezkonvimporter.h"
#include "recipe.h"
#include "DBBackend/recipedb.h"
#include <qdragobject.h>
#include <kprinter.h>
#include <qpainter.h>
#include <qpaintdevicemetrics.h>
#include <qmessagebox.h>
#include <kprogress.h>
#include <kmessagebox.h>
#include <kglobal.h>
#include <klocale.h>
#include <kiconloader.h>
#include <kmenubar.h>
#include <kstatusbar.h>
#include <kkeydialog.h>
#include <kaccel.h>
#include <kio/netaccess.h>
#include <kfiledialog.h>
#include <kconfig.h>
#include <kcursor.h>
#include <kedittoolbar.h>
#include <kstdaccel.h>
#include <kaction.h>
#include <kstdaction.h>
//Settings headers
#include <kdeversion.h>
Krecipes::Krecipes()
: KMainWindow( 0, "Krecipes" ),
m_view(new KrecipesView(this)),
m_printer(0)
{
// accept dnd
setAcceptDrops(true);
// tell the KMainWindow that this is indeed the main widget
setCentralWidget(m_view);
// then, setup our actions
setupActions();
// and a status bar
statusBar()->show();
// apply the saved mainwindow settings, if any, and ask the mainwindow
// to automatically save settings if changed: window size, toolbar
// position, icon size, etc.
setAutoSaveSettings();
// allow the view to change the statusbar and caption
connect(m_view, SIGNAL(signalChangeStatusbar(const QString&)),
this, SLOT(changeStatusbar(const QString&)));
connect(m_view, SIGNAL(signalChangeCaption(const QString&)),
this, SLOT(changeCaption(const QString&)));
connect(m_view, SIGNAL(panelShown(KrePanel,bool)),SLOT(updateActions(KrePanel,bool)));
// Enable/Disable the Save Button (Initialize disabled, and connect signal)
connect(this->m_view, SIGNAL(enableSaveOption(bool)), this, SLOT(enableSaveOption(bool)));
enableSaveOption(false); // Disables saving initially
parsing_file_dlg = new KDialog(this,"parsing_file_dlg",true,Qt::WX11BypassWM);
QLabel *parsing_file_dlg_label = new QLabel(i18n("Gathering recipe data from file.\nPlease wait..."),parsing_file_dlg);
parsing_file_dlg_label->setFrameStyle( QFrame::Box | QFrame::Raised );
(new QVBoxLayout(parsing_file_dlg))->addWidget( parsing_file_dlg_label );
parsing_file_dlg->adjustSize();
//parsing_file_dlg->setFixedSize(parsing_file_dlg->size());
}
Krecipes::~Krecipes()
{
}
void Krecipes::updateActions( KrePanel panel, bool show )
{
switch ( panel )
{
case RecipeView:
{
saveAsAction->setEnabled(show);
printAction->setEnabled(show);
reloadAction->setEnabled(show);
//can't edit when there are multiple recipes loaded
if ( show && m_view->viewPanel->recipesLoaded() == 1 ) {
editAction->setEnabled(true);
}
else
editAction->setEnabled(false);
break;
}
case SelectP:
{
saveAsAction->setEnabled(show);
editAction->setEnabled(show);
break;
}
default: break;
}
}
void Krecipes::setupActions()
{
KIconLoader il;
saveAsAction=KStdAction::saveAs(this, SLOT(fileSaveAs()), actionCollection());
printAction = KStdAction::print(this, SLOT(filePrint()), actionCollection());
reloadAction = new KAction(i18n("Reloa&d"), "reload", Key_F5, m_view, SLOT(reloadDisplay()), actionCollection(), "reload_action");
editAction = new KAction(i18n("&Edit Recipe"), "edit", CTRL+Key_E,
m_view, SLOT(editRecipe()),
actionCollection(), "edit_action");
KAction *action = KStdAction::openNew(this, SLOT(fileNew()), actionCollection());
action->setText(i18n("&New Recipe"));
saveAction=KStdAction::save(this, SLOT(fileSave()), actionCollection());
KStdAction::quit(kapp, SLOT(quit()), actionCollection());
m_toolbarAction = KStdAction::showToolbar(this, SLOT(optionsShowToolbar()), actionCollection());
m_statusbarAction = KStdAction::showStatusbar(this, SLOT(optionsShowStatusbar()), actionCollection());
KStdAction::keyBindings(this, SLOT(optionsConfigureKeys()), actionCollection());
KStdAction::configureToolbars(this, SLOT(optionsConfigureToolbars()), actionCollection());
KStdAction::preferences(this, SLOT(optionsPreferences()), actionCollection());
(void)new KAction(i18n("Import..."), CTRL+Key_I,
this, SLOT(import()),
actionCollection(), "import_action");
(void)new KAction(i18n("Page Setup..."), 0,
this, SLOT(pageSetupSlot()),
actionCollection(), "page_setup_action");
updateActions( SelectP, true );
updateActions( RecipeView, false );
createGUI();
}
void Krecipes::saveProperties(KConfig *)
{
// the 'config' object points to the session managed
// config file. anything you write here will be available
// later when this app is restored
//if (!m_view->currentURL().isNull())
// config->writeEntry("lastURL", m_view->currentURL());
}
void Krecipes::readProperties(KConfig *)
{
// the 'config' object points to the session managed
// config file. this function is automatically called whenever
// the app is being restored. read in here whatever you wrote
// in 'saveProperties'
//QString url = config->readEntry("lastURL");
//if (!url.isNull())
// m_view->openURL(KURL(url));
}
void Krecipes::dragEnterEvent(QDragEnterEvent *event)
{
// accept uri drops only
event->accept(QUriDrag::canDecode(event));
}
void Krecipes::fileNew()
{
// Create a new element (Element depends on active panel. New recipe by default)
m_view->createNewElement();
}
void Krecipes::fileOpen()
{
// this slot is called whenever the File->Open menu is selected,
// the Open shortcut is pressed (usually CTRL+O) or the Open toolbar
// button is clicked
/*
// this brings up the generic open dialog
KURL url = KURLRequesterDlg::getURL(QString::null, this, i18n("Open Location") );
*/
// standard filedialog
/*KURL url = KFileDialog::getOpenURL(QString::null, QString::null, this, i18n("Open Location"));
if (!url.isEmpty())
m_view->openURL(url);*/
}
void Krecipes::fileSave()
{
// this slot is called whenever the File->Save menu is selected,
// the Save shortcut is pressed (usually CTRL+S) or the Save toolbar
// button is clicked
m_view->save();
}
void Krecipes::fileSaveAs()
{
// this slot is called whenever the File->Save As menu is selected,
m_view->exportRecipe();
}
void Krecipes::filePrint()
{
m_view->print();
}
void Krecipes::import()
{
KFileDialog file_dialog( QString::null,
"*.kre *.kreml|Krecipes (*.kre, *.kreml)\n"
"*.mx2|MasterCook (*.mx2)\n"
"*.mxp *.txt|MasterCook Export (*.mxp, *.txt)\n"
"*.mmf *.txt|Meal-Master (*.mmf, *.txt)\n"
"*.txt|\"Now You're Cooking\" Generic Export (*.txt)\n"
"*.xml *.recipeml|RecipeML (*.xml, *.recipeml)\n"
"*.rk *.txt|Rezkonv (*.rk, *.txt)",
this,
"file_dialog",
true
);
file_dialog.setMode( KFile::Files );
if ( file_dialog.exec() == KFileDialog::Accepted )
{
QStringList warnings_list;
QString selected_filter = file_dialog.currentFilter();
BaseImporter *importer;
if ( selected_filter == "*.mxp *.txt" )
importer = new MXPImporter();
else if ( selected_filter == "*.mmf *.txt" )
importer = new MMFImporter();
else if ( selected_filter == "*.txt" )
importer = new NYCGenericImporter();
else if ( selected_filter == "*.mx2" )
importer = new MX2Importer();
else if ( selected_filter == "*.kre *.kreml" )
importer = new KreImporter();
else if ( selected_filter == "*.xml *.recipeml" )
importer = new RecipeMLImporter();
else if ( selected_filter == "*.rk *.txt" )
importer = new RezkonvImporter();
else
{
KMessageBox::sorry( this,
QString(i18n("Filter \"%1\" not recognized.\n"
"Please select one of the provided filters.")).arg(selected_filter),
i18n("Unrecognized Filter")
);
import(); //let's try again :)
return;
}
parsing_file_dlg->show(); KApplication::setOverrideCursor( KCursor::waitCursor() );
importer->parseFiles(file_dialog.selectedFiles());
parsing_file_dlg->hide(); KApplication::restoreOverrideCursor();
m_view->import( *importer );
if ( !importer->getMessages().isEmpty() )
{
KTextEdit *warningEdit = new KTextEdit( this );
warningEdit->setTextFormat( Qt::RichText );
warningEdit->setText( QString(i18n("NOTE: We recommend that all recipes generating warnings be checked to ensure that they were properly imported, and no loss of recipe data has occurred.<br><br>")) + importer->getMessages() );
warningEdit->setReadOnly(true);
KDialogBase showWarningsDlg( KDialogBase::Swallow, i18n("Import warnings"), KDialogBase::Ok, KDialogBase::Default, this );
showWarningsDlg.setMainWidget( warningEdit ); //KDialogBase will delete warningEdit for us
showWarningsDlg.resize( QSize(550,250) );
showWarningsDlg.exec();
}
delete importer;
}
}
void Krecipes::pageSetupSlot()
{
Recipe recipe;
m_view->selectPanel->getCurrentRecipe(&recipe);
PageSetupDialog *page_setup = new PageSetupDialog(this,recipe);
page_setup->exec();
delete page_setup;
}
//return true to close app
bool Krecipes::queryClose()
{
if ( !m_view->inputPanel->everythingSaved() )
{
switch( KMessageBox::questionYesNoCancel( this,
i18n("A recipe contains unsaved changes.\n"
"Do you want to save the changes before exiting?"),
i18n("Unsaved Changes") ) )
{
case KMessageBox::Yes: return m_view->save();
case KMessageBox::No: return true;
case KMessageBox::Cancel: return false;
default: return true;
}
}
else
return true;
}
void Krecipes::optionsShowToolbar()
{
// this is all very cut and paste code for showing/hiding the
// toolbar
if (m_toolbarAction->isChecked())
toolBar()->show();
else
toolBar()->hide();
}
void Krecipes::optionsShowStatusbar()
{
// this is all very cut and paste code for showing/hiding the
// statusbar
if (m_statusbarAction->isChecked())
statusBar()->show();
else
statusBar()->hide();
}
void Krecipes::optionsConfigureKeys()
{
#if KDE_IS_VERSION(3,1,92 )
// for KDE 3.2: KKeyDialog::configureKeys is deprecated
KKeyDialog::configure(actionCollection(), this, true);
#else
KKeyDialog::configureKeys(actionCollection(), "krecipesui.rc");
#endif
}
void Krecipes::optionsConfigureToolbars()
{
// use the standard toolbar editor
#if defined(KDE_MAKE_VERSION)
# if KDE_VERSION >= KDE_MAKE_VERSION(3,1,0)
saveMainWindowSettings(KGlobal::config(), autoSaveGroup());
# else
saveMainWindowSettings(KGlobal::config());
# endif
#else
saveMainWindowSettings(KGlobal::config());
#endif
KEditToolbar dlg(actionCollection());
connect(&dlg, SIGNAL(newToolbarConfig()), this, SLOT(newToolbarConfig()));
dlg.exec();
}
void Krecipes::newToolbarConfig()
{
// this slot is called when user clicks "Ok" or "Apply" in the toolbar editor.
// recreate our GUI, and re-apply the settings (e.g. "text under icons", etc.)
createGUI();
#if defined(KDE_MAKE_VERSION)
# if KDE_VERSION >= KDE_MAKE_VERSION(3,1,0)
applyMainWindowSettings(KGlobal::config(), autoSaveGroup());
# else
applyMainWindowSettings(KGlobal::config());
# endif
#else
applyMainWindowSettings(KGlobal::config());
#endif
}
void Krecipes::optionsPreferences()
{
// popup some sort of preference dialog, here
KrecipesPreferences dlg(this);
if (dlg.exec())
{}
}
void Krecipes::changeStatusbar(const QString& text)
{
// display the text on the statusbar
statusBar()->message(text);
}
void Krecipes::changeCaption(const QString& text)
{
// display the text on the caption
setCaption(text);
}
void Krecipes::enableSaveOption(bool en)
{
saveAction->setEnabled(en);
}
#include "krecipes.moc"
<|endoftext|>
|
<commit_before>#include <headers/pbkdf2.h>
#include <iostream>
Pbkdf2::Pbkdf2(CryptoPP::HashTransformation* h):Hash(h){}
void Pbkdf2::compute(unsigned int iterations = 20000) {
CryptoPP::PKCS5_PBKDF2_HMAC<CryptoPP::SHA1> pbkdf2;
int passlen = plaintext.size();
int slen = salt.size();
byte password[passlen];
for(int i = 0; i < passlen; i++) {
password[i] = plaintext.data()[i];
}
byte saltBuf[slen];
for(int i = 0; i < slen; i++) {
saltBuf[i] = salt.data()[i];
}
byte derived[20];
pbkdf2.DeriveKey(derived, sizeof(derived), 0, password, passlen, saltBuf, slen, iterations);
std::string result;
CryptoPP::HexEncoder encoder(new CryptoPP::StringSink(result));
encoder.Put(derived, sizeof(derived));
encoder.MessageEnd();
digest = result;
/*
unsigned char bufOut[32]; //32 -> 256-bit output
int len = plaintext.length();
unsigned char bufIn[len];
std::cout << "\t\t"<<sizeof(bufOut)<<std::endl;
for(int i = 0; i < plaintext.length(); i++) {
bufIn[i] = (unsigned char)plaintext.at(i);
}
std::cout << "\t\t"<<sizeof(bufIn)<<" "<<len<<" "<<plaintext<<" ";
for(int i = 0; i < sizeof(bufIn); i++) {
std::cout << bufIn[i];
}
std::cout << std::endl;
const unsigned char* saltBuf = new unsigned char(saltlen);
saltBuf = (unsigned char*)salt.c_str();
pbkdf2.DeriveKey(bufOut, sizeof(bufOut), 0, bufIn, sizeof(bufIn), saltBuf, sizeof(saltBuf), iterations);
//hex encoding
digest = "";
using CryptoPP::StringSource;
using CryptoPP::StringSink;
using CryptoPP::HexEncoder;
StringSource ss(bufOut, sizeof(bufOut), true, new HexEncoder(new StringSink(digest)));
std::cout << "\t\tIn pbkdf2::compute() digest:" << digest << std::endl;
std::cout << "\t\t" << std::string((char*)bufOut);
for(int i = 0; i < digest.length(); i++) {
std::cout << (digest.at(i));
}
std::cout << std::endl<<"\t\t"<<sizeof(bufOut);
std::cout << std::endl<<"\t\t";
for(int i = 0; i < sizeof(bufOut); i++) {
std::cout << (bufOut[i]);
}
std::cout << std::endl;
*/
}
<commit_msg>minor fixes to pbkdf2<commit_after>#include <headers/pbkdf2.h>
#include <iostream>
Pbkdf2::Pbkdf2(CryptoPP::HashTransformation* h):Hash(h){}
void Pbkdf2::compute(unsigned int iterations = 20000) {
CryptoPP::PKCS5_PBKDF2_HMAC<CryptoPP::SHA1> pbkdf2;
int passlen = plaintext.size();
int slen = salt.size();
byte password[passlen];
for(int i = 0; i < passlen; i++) {
password[i] = plaintext.data()[i];
}
byte saltBuf[slen];
for(int i = 0; i < slen; i++) {
saltBuf[i] = salt.data()[i];
}
byte derived[20];
pbkdf2.DeriveKey(derived, sizeof(derived), 0, password, passlen, saltBuf, slen, iterations);
std::string result;
CryptoPP::HexEncoder encoder(new CryptoPP::StringSink(result));
encoder.Put(derived, sizeof(derived));
encoder.MessageEnd();
digest = result;
}
<|endoftext|>
|
<commit_before>#include <iostream>
#include <string>
#include <algorithm>
#include <vector>
#include <unordered_set>
using namespace std;
namespace leetcode
{
// Task: https://leetcode.com/problems/two-sum/
// Time to first submit: 20
// Time to last submit: 120
// Number of submits: 10 (did several optimizations)
// Errors: 5
// Debug: yes
vector<int> twoSum(vector<int>& nums, int target) {
unordered_set<int> hashed(begin(nums), end(nums));
for (int i = 0; i < nums.size(); ++i)
{
auto second = target - nums[i];
if (hashed.count(second) != 0)
{
auto found_it = find(begin(nums) + i + 1, end(nums), second);
if (found_it != end(nums))
{
int j = static_cast<int>(distance(begin(nums), found_it));
return { i,j };
}
}
}
return {};
}
struct ListNode {
int val;
ListNode* next;
ListNode(int x) : val(x), next(nullptr) {}
};
// Task: https://leetcode.com/problems/add-two-numbers/
// Time to first submit: 120
// Time to last submit: 140
// Number of submits: 5
// Errors: 9
// Debug: yes
ListNode* addTwoNumbers(ListNode* l1, ListNode* l2)
{
ListNode* tail = nullptr;
ListNode* head = nullptr;
int mem = 0;
while (l1 != nullptr && l2 != nullptr)
{
int val = l1->val + l2->val + mem;
if (val > 9)
{
mem = 1;
val %= 10;
}
else
{
mem = 0;
}
if (head == nullptr)
{
head = new ListNode(val);
tail = head;
}
else
{
tail->next = new ListNode(val);
tail = tail->next;
}
l1 = l1->next;
l2 = l2->next;
}
while (l1 != nullptr)
{
int val = l1->val + mem;
if (val > 9)
{
mem = 1;
val %= 10;
}
else
{
mem = 0;
}
tail->next = new ListNode(val);
tail = tail->next;
l1 = l1->next;
}
while (l2 != nullptr)
{
int val = l2->val + mem;
if (val > 9)
{
mem = 1;
val %= 10;
}
else
{
mem = 0;
}
tail->next = new ListNode(val);
tail = tail->next;
l2 = l2->next;
}
if (mem != 0)
{
tail->next = new ListNode(mem);
tail = tail->next;
}
return head;
}
// Task: https://leetcode.com/problems/longest-substring-without-repeating-characters/
// Time to first submit: 60
// Time to last submit: 150
// Number of submits: 5
// Errors: 6
// Not passed test cases: aab pwwkew aabaab!bb
// Debug: yes
int lengthOfLongestSubstring(string s)
{
// abcabcbb -> abc (3)
// pwwkew -> wke (3)
// wpwkew -> pwke (4)
// bbbbb -> b (1)
// aab -> ab (2)
unordered_set<char> unique;
int longest = 0;
int left = 0;
int len = 0;
for (int i = 0; i < s.size(); ++i)
{
if (unique.count(s[i]) == 0)
{
unique.insert(s[i]);
if (++len > longest)
{
longest = len;
}
}
else
{
if (left == i - 1) // 2 equal characters near
{
left = i;
len = 1;
unique = { s[i] };
}
else
{
while (s[left] != s[i])
{
unique.erase(s[left]);
++left;
}
++left;
len = i - left + 1;
}
}
}
return longest;
}
// Task: https://leetcode.com/problems/median-of-two-sorted-arrays/
// Time to first submit:
// Time to last submit: 0
// Number of submits: 0
// Errors: 0
// Not passed test cases:
// Debug:
// nums1 = [1, 2]
// nums2 = [3, 4]
// Median: (2 + 3) / 2 = 2.5
// nums1 = [1, 3]
// nums2 = [2]
// Median: 2.0
// Complexity should be O(log(m+n))
double findMedianSortedArrays(vector<int>& nums1, vector<int>& nums2)
{
return 0;
}
string strWithout3a3b(int A, int B)
{
string s;
int numA = 0;
int numB = 0;
bool aMax = false;
bool bMax = false;
const char a = 'a';
const char b = 'b';
for (int i = 0; i < A + B; ++i)
{
if (numA < A && aMax == false)
{
s.push_back(a);
++numA;
if (i > 0 && s[i - 1] == a)
{
aMax = true;
}
bMax = false;
}
else
{
s.push_back(b);
++numB;
if (i > 0 && s[i - 1] == b)
{
bMax = true;
}
aMax = false;
}
}
return s;
}
class TimeMap {
public:
/** Initialize your data structure here. */
TimeMap() {
}
void set(string key, string value, int timestamp) {
}
string get(string key, int timestamp) {
}
};
/**
* Your TimeMap object will be instantiated and called as such:
* TimeMap* obj = new TimeMap();
* obj->set(key,value,timestamp);
* string param_2 = obj->get(key,timestamp);
*/
int mincostTickets(vector<int>& days, vector<int>& costs)
{
}
int countTriplets(vector<int>& A)
{
int N = A.size();
int cntTriplets = 0;
for (int i = 0; i < N; ++i)
for (int j = 0; j < N; ++j)
for (int k = 0; k < N; ++k)
{
if ((A[i] & A[j] & A[k]) == 0)
{
++cntTriplets;
}
}
return cntTriplets;
}
} // namespace leetcode
int main()
{
using namespace leetcode;
vector<int> v = {2,1,3};
cout << countTriplets(v);
return 0;
}
<commit_msg>Current progress<commit_after>#include <iostream>
#include <string>
#include <algorithm>
#include <vector>
#include <unordered_set>
using namespace std;
namespace leetcode
{
// Task: https://leetcode.com/problems/two-sum/
// Time to first submit: 20
// Time to last submit: 120
// Number of submits: 10 (did several optimizations)
// Errors: 5
// Debug: yes
vector<int> twoSum(vector<int>& nums, int target) {
unordered_set<int> hashed(begin(nums), end(nums));
for (int i = 0; i < nums.size(); ++i)
{
auto second = target - nums[i];
if (hashed.count(second) != 0)
{
auto found_it = find(begin(nums) + i + 1, end(nums), second);
if (found_it != end(nums))
{
int j = static_cast<int>(distance(begin(nums), found_it));
return { i,j };
}
}
}
return {};
}
struct ListNode {
int val;
ListNode* next;
ListNode(int x) : val(x), next(nullptr) {}
};
// Task: https://leetcode.com/problems/add-two-numbers/
// Time to first submit: 120
// Time to last submit: 140
// Number of submits: 5
// Errors: 9
// Debug: yes
ListNode* addTwoNumbers(ListNode* l1, ListNode* l2)
{
ListNode* tail = nullptr;
ListNode* head = nullptr;
int mem = 0;
while (l1 != nullptr && l2 != nullptr)
{
int val = l1->val + l2->val + mem;
if (val > 9)
{
mem = 1;
val %= 10;
}
else
{
mem = 0;
}
if (head == nullptr)
{
head = new ListNode(val);
tail = head;
}
else
{
tail->next = new ListNode(val);
tail = tail->next;
}
l1 = l1->next;
l2 = l2->next;
}
while (l1 != nullptr)
{
int val = l1->val + mem;
if (val > 9)
{
mem = 1;
val %= 10;
}
else
{
mem = 0;
}
tail->next = new ListNode(val);
tail = tail->next;
l1 = l1->next;
}
while (l2 != nullptr)
{
int val = l2->val + mem;
if (val > 9)
{
mem = 1;
val %= 10;
}
else
{
mem = 0;
}
tail->next = new ListNode(val);
tail = tail->next;
l2 = l2->next;
}
if (mem != 0)
{
tail->next = new ListNode(mem);
tail = tail->next;
}
return head;
}
// Task: https://leetcode.com/problems/longest-substring-without-repeating-characters/
// Time to first submit: 60
// Time to last submit: 150
// Number of submits: 5
// Errors: 6
// Not passed test cases: aab pwwkew aabaab!bb
// Debug: yes
int lengthOfLongestSubstring(string s)
{
// abcabcbb -> abc (3)
// pwwkew -> wke (3)
// wpwkew -> pwke (4)
// bbbbb -> b (1)
// aab -> ab (2)
unordered_set<char> unique;
int longest = 0;
int left = 0;
int len = 0;
for (int i = 0; i < s.size(); ++i)
{
if (unique.count(s[i]) == 0)
{
unique.insert(s[i]);
if (++len > longest)
{
longest = len;
}
}
else
{
if (left == i - 1) // 2 equal characters near
{
left = i;
len = 1;
unique = { s[i] };
}
else
{
while (s[left] != s[i])
{
unique.erase(s[left]);
++left;
}
++left;
len = i - left + 1;
}
}
}
return longest;
}
// Task: https://leetcode.com/problems/median-of-two-sorted-arrays/
// Time to first submit:
// Time to last submit: 0
// Number of submits: 0
// Errors: 0
// Not passed test cases:
// Debug:
// nums1 = [1, 2]
// nums2 = [3, 4]
// Median: (2 + 3) / 2 = 2.5
// nums1 = [1, 3]
// nums2 = [2]
// Median: 2.0
// Complexity should be O(log(m+n))
double findMedianSortedArrays(vector<int>& nums1, vector<int>& nums2)
{
return 0;
}
// Task: https://leetcode.com/problems/string-without-aaa-or-bbb/
// Time to first submit:
// Time to last submit: 0
// Number of submits: 0
// Errors: 0
// Not passed test cases:
// Debug:
string strWithout3a3b(int A, int B)
{
string s;
int numA = 0;
int numB = 0;
bool aMax = false;
bool bMax = false;
const char a = 'a';
const char b = 'b';
for (int i = 0; i < A + B; ++i)
{
if (numA < A && aMax == false)
{
s.push_back(a);
++numA;
if (i > 0 && s[i - 1] == a)
{
aMax = true;
}
bMax = false;
}
else
{
s.push_back(b);
++numB;
if (i > 0 && s[i - 1] == b)
{
bMax = true;
}
aMax = false;
}
}
return s;
}
// Task: https://leetcode.com/problems/triples-with-bitwise-and-equal-to-zero/
// Time to first submit:
// Time to last submit: 0
// Number of submits: 0
// Errors: 0
// Not passed test cases:
// Debug:
int countTriplets(vector<int>& A)
{
int N = A.size();
int cntTriplets = 0;
for (int i = 0; i < N; ++i)
for (int j = 0; j < N; ++j)
for (int k = 0; k < N; ++k)
{
if ((A[i] & A[j] & A[k]) == 0)
{
++cntTriplets;
}
}
return cntTriplets;
}
} // namespace leetcode
int main()
{
using namespace leetcode;
vector<int> nums1 = { 1, 2 };
vector<int> nums2 = { 3, 4 };
cout << findMedianSortedArrays(nums1, nums2);
return 0;
}
<|endoftext|>
|
<commit_before>// $Id$
//
// Copyright (C) 2003-2008 Greg Landrum and Rational Discovery LLC
//
// @@ All Rights Reserved @@
//
#include <GraphMol/RDKitBase.h>
#include <GraphMol/SmilesParse/SmilesParse.h>
#include <GraphMol/SmilesParse/SmilesWrite.h>
#include <GraphMol/Fingerprints/Fingerprints.h>
#include <DataStructs/ExplicitBitVect.h>
#include <DataStructs/BitOps.h>
#include <RDGeneral/RDLog.h>
#include <string>
using namespace RDKit;
void test1(){
BOOST_LOG(rdInfoLog) <<"testing basics" << std::endl;
std::string smi = "C1=CC=CC=C1";
RWMol *m1 = SmilesToMol(smi);
TEST_ASSERT(m1->getNumAtoms()==6);
ExplicitBitVect *fp1=DaylightFingerprintMol(*m1);
ExplicitBitVect *fp2=DaylightFingerprintMol(*m1);
TEST_ASSERT(TanimotoSimilarity(*fp1,*fp2)==1.0);
TEST_ASSERT(TanimotoSimilarity(*fp1,*fp2)>=0.0);
smi = "C1=CC=CC=N1";
RWMol *m2 = SmilesToMol(smi);
delete fp2;
fp2=DaylightFingerprintMol(*m2);
TEST_ASSERT(TanimotoSimilarity(*fp1,*fp2)<1.0);
TEST_ASSERT(TanimotoSimilarity(*fp1,*fp2)>0.0);
delete m1;
delete m2;
delete fp1;
delete fp2;
BOOST_LOG(rdInfoLog) <<"done" << std::endl;
}
void test2(){
BOOST_LOG(rdInfoLog) <<"testing subgraph invariants" << std::endl;
std::string smi = "CC(=O)COC";
RWMol *m1 = SmilesToMol(smi);
TEST_ASSERT(m1->getNumAtoms()==6);
BOOST_LOG(rdInfoLog) <<"-------------------- fp1 " << std::endl;
ExplicitBitVect *fp1=DaylightFingerprintMol(*m1,1,4,2048,4,false);
BOOST_LOG(rdInfoLog) <<"-------------------- fp2 " << std::endl;
ExplicitBitVect *fp2=DaylightFingerprintMol(*m1,1,4,2048,4,false);
TEST_ASSERT(TanimotoSimilarity(*fp1,*fp2)==1.0);
INT_VECT::const_iterator i;
INT_VECT v1,v2;
fp1->GetOnBits(v1);
//for(i=v1.begin();i!=v1.end();i++){
// BOOST_LOG(rdInfoLog) <<*i << " ";
//}
//BOOST_LOG(rdInfoLog) <<std::endl;
RWMol *m2 = SmilesToMol("CC");
delete fp2;
BOOST_LOG(rdInfoLog) <<"-------------------- fp2 " << std::endl;
fp2=DaylightFingerprintMol(*m2,1,4,2048,4,false);
TEST_ASSERT(TanimotoSimilarity(*fp1,*fp2)<1.0);
TEST_ASSERT(TanimotoSimilarity(*fp1,*fp2)>0.0);
TEST_ASSERT(OnBitProjSimilarity(*fp2,*fp1)[0]==1.0);
delete m2;
m2 = SmilesToMol("CC=O");
delete fp2;
fp2=DaylightFingerprintMol(*m2,1,4,2048,4,false);
TEST_ASSERT(TanimotoSimilarity(*fp1,*fp2)<1.0);
TEST_ASSERT(TanimotoSimilarity(*fp1,*fp2)>0.0);
TEST_ASSERT(OnBitProjSimilarity(*fp2,*fp1)[0]==1.0);
delete m2;
m2 = SmilesToMol("CCCOC");
delete fp2;
fp2=DaylightFingerprintMol(*m2,1,4,2048,4,false);
TEST_ASSERT(TanimotoSimilarity(*fp1,*fp2)<1.0);
TEST_ASSERT(TanimotoSimilarity(*fp1,*fp2)>0.0);
TEST_ASSERT(OnBitProjSimilarity(*fp2,*fp1)[0]==1.0);
delete m1;
delete m2;
delete fp1;
delete fp2;
BOOST_LOG(rdInfoLog) <<"done" << std::endl;
}
void test3(){
BOOST_LOG(rdInfoLog) <<"testing auto folding" << std::endl;
RWMol *m = SmilesToMol("CCCOC");
ExplicitBitVect *fp1,*fp2;
fp1=DaylightFingerprintMol(*m,1,4,2048,4,false,
0.3,256);
TEST_ASSERT(fp1->GetNumBits()==256);
TEST_ASSERT(fp1->GetNumOnBits()==29);
delete m;
delete fp1;
m=SmilesToMol("CN(C)Cc1n-2c(nn1)CN=C(c1ccccc1)c1cc(Cl)ccc12");
fp1=DaylightFingerprintMol(*m,1,4,2048,4,false);
TEST_ASSERT(fp1->GetNumBits()==2048);
TEST_ASSERT(fp1->GetNumOnBits()==334);
fp2=DaylightFingerprintMol(*m,1,4,2048,4,false,0.3,256);
TEST_ASSERT(fp2->GetNumBits()==1024);
TEST_ASSERT(fp2->GetNumOnBits()==309);
delete m;
delete fp1;
delete fp2;
BOOST_LOG(rdInfoLog) <<"done" << std::endl;
}
void test1alg2(){
BOOST_LOG(rdInfoLog) <<"testing basics alg2" << std::endl;
std::string smi = "C1=CC=CC=C1";
RWMol *m1 = SmilesToMol(smi);
TEST_ASSERT(m1->getNumAtoms()==6);
ExplicitBitVect *fp1=RDKFingerprintMol(*m1);
ExplicitBitVect *fp2=RDKFingerprintMol(*m1);
TEST_ASSERT(TanimotoSimilarity(*fp1,*fp2)==1.0);
TEST_ASSERT(TanimotoSimilarity(*fp1,*fp2)>=0.0);
smi = "C1=CC=CC=N1";
RWMol *m2 = SmilesToMol(smi);
delete fp2;
fp2=RDKFingerprintMol(*m2);
TEST_ASSERT(TanimotoSimilarity(*fp1,*fp2)<1.0);
TEST_ASSERT(TanimotoSimilarity(*fp1,*fp2)>0.0);
delete m1;
delete m2;
delete fp1;
delete fp2;
BOOST_LOG(rdInfoLog) <<"done" << std::endl;
}
void test2alg2(){
BOOST_LOG(rdInfoLog) <<"testing subgraph invariants alg2" << std::endl;
std::string smi = "CC(=O)COC";
RWMol *m1 = SmilesToMol(smi);
TEST_ASSERT(m1->getNumAtoms()==6);
BOOST_LOG(rdInfoLog) <<"-------------------- fp1 " << std::endl;
ExplicitBitVect *fp1=RDKFingerprintMol(*m1,1,4,2048,4,false);
BOOST_LOG(rdInfoLog) <<"-------------------- fp2 " << std::endl;
ExplicitBitVect *fp2=RDKFingerprintMol(*m1,1,4,2048,4,false);
TEST_ASSERT(TanimotoSimilarity(*fp1,*fp2)==1.0);
INT_VECT::const_iterator i;
INT_VECT v1,v2;
fp1->GetOnBits(v1);
//for(i=v1.begin();i!=v1.end();i++){
// BOOST_LOG(rdInfoLog) <<*i << " ";
//}
//BOOST_LOG(rdInfoLog) <<std::endl;
RWMol *m2 = SmilesToMol("CC");
delete fp2;
BOOST_LOG(rdInfoLog) <<"-------------------- fp2 " << std::endl;
fp2=RDKFingerprintMol(*m2,1,4,2048,4,false);
TEST_ASSERT(TanimotoSimilarity(*fp1,*fp2)<1.0);
TEST_ASSERT(TanimotoSimilarity(*fp1,*fp2)>0.0);
TEST_ASSERT(OnBitProjSimilarity(*fp2,*fp1)[0]==1.0);
delete m2;
m2 = SmilesToMol("CC=O");
delete fp2;
fp2=RDKFingerprintMol(*m2,1,4,2048,4,false);
TEST_ASSERT(TanimotoSimilarity(*fp1,*fp2)<1.0);
TEST_ASSERT(TanimotoSimilarity(*fp1,*fp2)>0.0);
TEST_ASSERT(OnBitProjSimilarity(*fp2,*fp1)[0]==1.0);
delete m2;
m2 = SmilesToMol("CCCOC");
delete fp2;
fp2=RDKFingerprintMol(*m2,1,4,2048,4,false);
TEST_ASSERT(TanimotoSimilarity(*fp1,*fp2)<1.0);
TEST_ASSERT(TanimotoSimilarity(*fp1,*fp2)>0.0);
TEST_ASSERT(OnBitProjSimilarity(*fp2,*fp1)[0]==1.0);
delete m1;
delete m2;
delete fp1;
delete fp2;
BOOST_LOG(rdInfoLog) <<"done" << std::endl;
}
void test4Trends(){
BOOST_LOG(rdInfoLog) <<"testing similarity trends" << std::endl;
double sim1,sim2;
RWMol *m;
ExplicitBitVect *fp1,*fp2;
m = SmilesToMol("CCC");
fp1=RDKFingerprintMol(*m);
delete m;
m = SmilesToMol("C1CC1");
fp2=RDKFingerprintMol(*m);
sim1=TanimotoSimilarity(*fp1,*fp2);
delete m;
m = SmilesToMol("CCCC");
delete fp1;
fp1=RDKFingerprintMol(*m);
delete m;
m = SmilesToMol("C1CCC1");
delete fp2;
fp2=RDKFingerprintMol(*m);
sim2=TanimotoSimilarity(*fp1,*fp2);
TEST_ASSERT(sim2>sim1);
sim2=sim1;
delete m;
m = SmilesToMol("CCCCC");
delete fp1;
fp1=RDKFingerprintMol(*m);
delete m;
m = SmilesToMol("C1CCCC1");
delete fp2;
fp2=RDKFingerprintMol(*m);
sim2=TanimotoSimilarity(*fp1,*fp2);
TEST_ASSERT(sim2>sim1);
sim2=sim1;
delete m;
m = SmilesToMol("CCCCCC");
delete fp1;
fp1=RDKFingerprintMol(*m);
delete m;
m = SmilesToMol("C1CCCCC1");
delete fp2;
fp2=RDKFingerprintMol(*m);
sim2=TanimotoSimilarity(*fp1,*fp2);
TEST_ASSERT(sim2>sim1);
sim2=sim1;
delete m;
m = SmilesToMol("CCCCCCC");
delete fp1;
fp1=RDKFingerprintMol(*m);
delete m;
m = SmilesToMol("C1CCCCCC1");
delete fp2;
fp2=RDKFingerprintMol(*m);
sim2=TanimotoSimilarity(*fp1,*fp2);
TEST_ASSERT(sim2>sim1);
sim2=sim1;
delete m;
delete fp1;
delete fp2;
BOOST_LOG(rdInfoLog) <<"done" << std::endl;
}
int main(int argc,char *argv[]){
RDLog::InitLogs();
test1();
test2();
//test3();
test1alg2();
test2alg2();
test4Trends();
return 0;
}
<commit_msg>do an explicit backwards compatibility check with fingerprints<commit_after>// $Id$
//
// Copyright (C) 2003-2008 Greg Landrum and Rational Discovery LLC
//
// @@ All Rights Reserved @@
//
#include <GraphMol/RDKitBase.h>
#include <GraphMol/SmilesParse/SmilesParse.h>
#include <GraphMol/SmilesParse/SmilesWrite.h>
#include <GraphMol/Fingerprints/Fingerprints.h>
#include <DataStructs/ExplicitBitVect.h>
#include <DataStructs/BitOps.h>
#include <RDGeneral/RDLog.h>
#include <string>
using namespace RDKit;
void test1(){
BOOST_LOG(rdInfoLog) <<"testing basics" << std::endl;
std::string smi = "C1=CC=CC=C1";
RWMol *m1 = SmilesToMol(smi);
TEST_ASSERT(m1->getNumAtoms()==6);
ExplicitBitVect *fp1=DaylightFingerprintMol(*m1);
ExplicitBitVect *fp2=DaylightFingerprintMol(*m1);
TEST_ASSERT(TanimotoSimilarity(*fp1,*fp2)==1.0);
TEST_ASSERT(TanimotoSimilarity(*fp1,*fp2)>=0.0);
smi = "C1=CC=CC=N1";
RWMol *m2 = SmilesToMol(smi);
delete fp2;
fp2=DaylightFingerprintMol(*m2);
TEST_ASSERT(TanimotoSimilarity(*fp1,*fp2)<1.0);
TEST_ASSERT(TanimotoSimilarity(*fp1,*fp2)>0.0);
delete m1;
delete m2;
delete fp1;
delete fp2;
BOOST_LOG(rdInfoLog) <<"done" << std::endl;
}
void test2(){
BOOST_LOG(rdInfoLog) <<"testing subgraph invariants" << std::endl;
std::string smi = "CC(=O)COC";
RWMol *m1 = SmilesToMol(smi);
TEST_ASSERT(m1->getNumAtoms()==6);
BOOST_LOG(rdInfoLog) <<"-------------------- fp1 " << std::endl;
ExplicitBitVect *fp1=DaylightFingerprintMol(*m1,1,4,2048,4,false);
BOOST_LOG(rdInfoLog) <<"-------------------- fp2 " << std::endl;
ExplicitBitVect *fp2=DaylightFingerprintMol(*m1,1,4,2048,4,false);
TEST_ASSERT(TanimotoSimilarity(*fp1,*fp2)==1.0);
INT_VECT::const_iterator i;
INT_VECT v1,v2;
fp1->GetOnBits(v1);
//for(i=v1.begin();i!=v1.end();i++){
// BOOST_LOG(rdInfoLog) <<*i << " ";
//}
//BOOST_LOG(rdInfoLog) <<std::endl;
RWMol *m2 = SmilesToMol("CC");
delete fp2;
BOOST_LOG(rdInfoLog) <<"-------------------- fp2 " << std::endl;
fp2=DaylightFingerprintMol(*m2,1,4,2048,4,false);
TEST_ASSERT(TanimotoSimilarity(*fp1,*fp2)<1.0);
TEST_ASSERT(TanimotoSimilarity(*fp1,*fp2)>0.0);
TEST_ASSERT(OnBitProjSimilarity(*fp2,*fp1)[0]==1.0);
delete m2;
m2 = SmilesToMol("CC=O");
delete fp2;
fp2=DaylightFingerprintMol(*m2,1,4,2048,4,false);
TEST_ASSERT(TanimotoSimilarity(*fp1,*fp2)<1.0);
TEST_ASSERT(TanimotoSimilarity(*fp1,*fp2)>0.0);
TEST_ASSERT(OnBitProjSimilarity(*fp2,*fp1)[0]==1.0);
delete m2;
m2 = SmilesToMol("CCCOC");
delete fp2;
fp2=DaylightFingerprintMol(*m2,1,4,2048,4,false);
TEST_ASSERT(TanimotoSimilarity(*fp1,*fp2)<1.0);
TEST_ASSERT(TanimotoSimilarity(*fp1,*fp2)>0.0);
TEST_ASSERT(OnBitProjSimilarity(*fp2,*fp1)[0]==1.0);
delete m1;
delete m2;
delete fp1;
delete fp2;
BOOST_LOG(rdInfoLog) <<"done" << std::endl;
}
void test3(){
BOOST_LOG(rdInfoLog) <<"testing auto folding" << std::endl;
RWMol *m = SmilesToMol("CCCOC");
ExplicitBitVect *fp1,*fp2;
fp2=DaylightFingerprintMol(*m,1,4,2048,4,false,
0.3,256);
TEST_ASSERT(fp2->GetNumBits()==256);
delete m;
delete fp2;
m=SmilesToMol("CN(C)Cc1n-2c(nn1)CN=C(c1ccccc1)c1cc(Cl)ccc12");
fp1=DaylightFingerprintMol(*m,1,4,2048,4,false);
TEST_ASSERT(fp1->GetNumBits()==2048);
fp2=DaylightFingerprintMol(*m,1,4,2048,4,false,0.3,256);
TEST_ASSERT(fp2->GetNumBits()<fp1->GetNumBits());
delete m;
delete fp1;
delete fp2;
BOOST_LOG(rdInfoLog) <<"done" << std::endl;
}
void test1alg2(){
BOOST_LOG(rdInfoLog) <<"testing basics alg2" << std::endl;
std::string smi = "C1=CC=CC=C1";
RWMol *m1 = SmilesToMol(smi);
TEST_ASSERT(m1->getNumAtoms()==6);
ExplicitBitVect *fp1=RDKFingerprintMol(*m1);
ExplicitBitVect *fp2=RDKFingerprintMol(*m1);
TEST_ASSERT(TanimotoSimilarity(*fp1,*fp2)==1.0);
TEST_ASSERT(TanimotoSimilarity(*fp1,*fp2)>=0.0);
smi = "C1=CC=CC=N1";
RWMol *m2 = SmilesToMol(smi);
delete fp2;
fp2=RDKFingerprintMol(*m2);
TEST_ASSERT(TanimotoSimilarity(*fp1,*fp2)<1.0);
TEST_ASSERT(TanimotoSimilarity(*fp1,*fp2)>0.0);
delete m1;
delete m2;
delete fp1;
delete fp2;
BOOST_LOG(rdInfoLog) <<"done" << std::endl;
}
void test2alg2(){
BOOST_LOG(rdInfoLog) <<"testing subgraph invariants alg2" << std::endl;
std::string smi = "CC(=O)COC";
RWMol *m1 = SmilesToMol(smi);
TEST_ASSERT(m1->getNumAtoms()==6);
BOOST_LOG(rdInfoLog) <<"-------------------- fp1 " << std::endl;
ExplicitBitVect *fp1=RDKFingerprintMol(*m1,1,4,2048,4,false);
BOOST_LOG(rdInfoLog) <<"-------------------- fp2 " << std::endl;
ExplicitBitVect *fp2=RDKFingerprintMol(*m1,1,4,2048,4,false);
TEST_ASSERT(TanimotoSimilarity(*fp1,*fp2)==1.0);
INT_VECT::const_iterator i;
INT_VECT v1,v2;
fp1->GetOnBits(v1);
//for(i=v1.begin();i!=v1.end();i++){
// BOOST_LOG(rdInfoLog) <<*i << " ";
//}
//BOOST_LOG(rdInfoLog) <<std::endl;
RWMol *m2 = SmilesToMol("CC");
delete fp2;
BOOST_LOG(rdInfoLog) <<"-------------------- fp2 " << std::endl;
fp2=RDKFingerprintMol(*m2,1,4,2048,4,false);
TEST_ASSERT(TanimotoSimilarity(*fp1,*fp2)<1.0);
TEST_ASSERT(TanimotoSimilarity(*fp1,*fp2)>0.0);
TEST_ASSERT(OnBitProjSimilarity(*fp2,*fp1)[0]==1.0);
delete m2;
m2 = SmilesToMol("CC=O");
delete fp2;
fp2=RDKFingerprintMol(*m2,1,4,2048,4,false);
TEST_ASSERT(TanimotoSimilarity(*fp1,*fp2)<1.0);
TEST_ASSERT(TanimotoSimilarity(*fp1,*fp2)>0.0);
TEST_ASSERT(OnBitProjSimilarity(*fp2,*fp1)[0]==1.0);
delete m2;
m2 = SmilesToMol("CCCOC");
delete fp2;
fp2=RDKFingerprintMol(*m2,1,4,2048,4,false);
TEST_ASSERT(TanimotoSimilarity(*fp1,*fp2)<1.0);
TEST_ASSERT(TanimotoSimilarity(*fp1,*fp2)>0.0);
TEST_ASSERT(OnBitProjSimilarity(*fp2,*fp1)[0]==1.0);
delete m1;
delete m2;
delete fp1;
delete fp2;
BOOST_LOG(rdInfoLog) <<"done" << std::endl;
}
void test4Trends(){
BOOST_LOG(rdInfoLog) <<"testing similarity trends" << std::endl;
double sim1,sim2;
RWMol *m;
ExplicitBitVect *fp1,*fp2;
m = SmilesToMol("CCC");
fp1=RDKFingerprintMol(*m);
delete m;
m = SmilesToMol("C1CC1");
fp2=RDKFingerprintMol(*m);
sim1=TanimotoSimilarity(*fp1,*fp2);
delete m;
m = SmilesToMol("CCCC");
delete fp1;
fp1=RDKFingerprintMol(*m);
delete m;
m = SmilesToMol("C1CCC1");
delete fp2;
fp2=RDKFingerprintMol(*m);
sim2=TanimotoSimilarity(*fp1,*fp2);
TEST_ASSERT(sim2>sim1);
sim2=sim1;
delete m;
m = SmilesToMol("CCCCC");
delete fp1;
fp1=RDKFingerprintMol(*m);
delete m;
m = SmilesToMol("C1CCCC1");
delete fp2;
fp2=RDKFingerprintMol(*m);
sim2=TanimotoSimilarity(*fp1,*fp2);
TEST_ASSERT(sim2>sim1);
sim2=sim1;
delete m;
m = SmilesToMol("CCCCCC");
delete fp1;
fp1=RDKFingerprintMol(*m);
delete m;
m = SmilesToMol("C1CCCCC1");
delete fp2;
fp2=RDKFingerprintMol(*m);
sim2=TanimotoSimilarity(*fp1,*fp2);
TEST_ASSERT(sim2>sim1);
sim2=sim1;
delete m;
m = SmilesToMol("CCCCCCC");
delete fp1;
fp1=RDKFingerprintMol(*m),*fp2;;
delete m;
m = SmilesToMol("C1CCCCCC1");
delete fp2;
fp2=RDKFingerprintMol(*m);
sim2=TanimotoSimilarity(*fp1,*fp2);
TEST_ASSERT(sim2>sim1);
sim2=sim1;
delete m;
delete fp1;
delete fp2;
BOOST_LOG(rdInfoLog) <<"done" << std::endl;
}
void test5BackwardsCompatibility(){
BOOST_LOG(rdInfoLog) <<"testing backwards compatibility of fingerprints" << std::endl;
double sim1,sim2;
RWMol *m;
ExplicitBitVect *fp1;
m = SmilesToMol("CC");
fp1=RDKFingerprintMol(*m);
TEST_ASSERT(fp1->GetNumOnBits()==4);
TEST_ASSERT((*fp1)[951]);
TEST_ASSERT((*fp1)[961]);
TEST_ASSERT((*fp1)[1436]);
TEST_ASSERT((*fp1)[1590]);
delete fp1;
#if 0
// boost 1.35.0
fp1=DaylightFingerprintMol(*m);
CHECK_INVARIANT(fp1->GetNumOnBits()==4,"Fingerprint compatibility problem detected");
CHECK_INVARIANT((*fp1)[28],"Fingerprint compatibility problem detected");
CHECK_INVARIANT((*fp1)[1243],"Fingerprint compatibility problem detected");
CHECK_INVARIANT((*fp1)[1299],"Fingerprint compatibility problem detected");
CHECK_INVARIANT((*fp1)[1606],"Fingerprint compatibility problem detected");
delete fp1;
#else
// boost 1.34.1 and earlier
fp1=DaylightFingerprintMol(*m);
CHECK_INVARIANT(fp1->GetNumOnBits()==4,"Fingerprint compatibility problem detected");
CHECK_INVARIANT((*fp1)[1141],"Fingerprint compatibility problem detected");
CHECK_INVARIANT((*fp1)[1317],"Fingerprint compatibility problem detected");
CHECK_INVARIANT((*fp1)[1606],"Fingerprint compatibility problem detected");
CHECK_INVARIANT((*fp1)[1952],"Fingerprint compatibility problem detected");
delete fp1;
#endif
delete m;
BOOST_LOG(rdInfoLog) <<"done" << std::endl;
}
int main(int argc,char *argv[]){
RDLog::InitLogs();
test1();
test2();
test3();
test1alg2();
test2alg2();
test4Trends();
test5BackwardsCompatibility();
return 0;
}
<|endoftext|>
|
<commit_before>/*=============================================================================
Library: CppMicroServices
Copyright (c) German Cancer Research Center,
Division of Medical and Biological Informatics
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 <usLDAPFilter.h>
#include "usTestingMacros.h"
#include <usServiceInterface.h>
#include <usGetModuleContext.h>
#include <usModuleContext.h>
#include US_BASECLASS_HEADER
#include <stdexcept>
US_USE_NAMESPACE
struct ITestServiceA
{
virtual ~ITestServiceA() {}
};
US_DECLARE_SERVICE_INTERFACE(ITestServiceA, "org.cppmicroservices.testing.ITestServiceA")
int TestMultipleServiceRegistrations()
{
struct TestServiceA : public US_BASECLASS_NAME, public ITestServiceA
{
};
ModuleContext* context = GetModuleContext();
TestServiceA s1;
TestServiceA s2;
ServiceRegistration reg1 = context->RegisterService<ITestServiceA>(&s1);
ServiceRegistration reg2 = context->RegisterService<ITestServiceA>(&s2);
std::list<ServiceReference> refs = context->GetServiceReferences<ITestServiceA>();
US_TEST_CONDITION_REQUIRED(refs.size() == 2, "Testing for two registered ITestServiceA services")
reg2.Unregister();
refs = context->GetServiceReferences<ITestServiceA>();
US_TEST_CONDITION_REQUIRED(refs.size() == 1, "Testing for one registered ITestServiceA services")
reg1.Unregister();
refs = context->GetServiceReferences<ITestServiceA>();
US_TEST_CONDITION_REQUIRED(refs.empty(), "Testing for no ITestServiceA services")
return EXIT_SUCCESS;
}
int TestServicePropertiesUpdate()
{
struct TestServiceA : public US_BASECLASS_NAME, public ITestServiceA
{
};
ModuleContext* context = GetModuleContext();
TestServiceA s1;
ServiceProperties props;
props["string"] = std::string("A std::string");
props["bool"] = false;
const char* str = "A const char*";
props["const char*"] = str;
ServiceRegistration reg1 = context->RegisterService<ITestServiceA>(&s1, props);
ServiceReference ref1 = context->GetServiceReference<ITestServiceA>();
US_TEST_CONDITION_REQUIRED(context->GetServiceReferences("").size() == 1, "Testing service count")
US_TEST_CONDITION_REQUIRED(any_cast<bool>(ref1.GetProperty("bool")) == false, "Testing bool property")
// register second service with higher rank
TestServiceA s2;
ServiceProperties props2;
props2[ServiceConstants::SERVICE_RANKING()] = 50;
ServiceRegistration reg2 = context->RegisterService<ITestServiceA>(&s2, props2);
// Get the service with the highest rank, this should be s2.
ServiceReference ref2 = context->GetServiceReference<ITestServiceA>();
TestServiceA* service = dynamic_cast<TestServiceA*>(context->GetService<ITestServiceA>(ref2));
US_TEST_CONDITION_REQUIRED(service == &s2, "Testing highest service rank")
props["bool"] = true;
// change the service ranking
props[ServiceConstants::SERVICE_RANKING()] = 100;
reg1.SetProperties(props);
US_TEST_CONDITION_REQUIRED(context->GetServiceReferences("").size() == 2, "Testing service count")
US_TEST_CONDITION_REQUIRED(any_cast<bool>(ref1.GetProperty("bool")) == true, "Testing bool property")
US_TEST_CONDITION_REQUIRED(any_cast<int>(ref1.GetProperty(ServiceConstants::SERVICE_RANKING())) == 100, "Testing updated ranking")
// Service with the highest ranking should now be s1
service = dynamic_cast<TestServiceA*>(context->GetService<ITestServiceA>(ref1));
US_TEST_CONDITION_REQUIRED(service == &s1, "Testing highest service rank")
reg1.Unregister();
US_TEST_CONDITION_REQUIRED(context->GetServiceReferences("").size() == 1, "Testing service count")
service = dynamic_cast<TestServiceA*>(context->GetService<ITestServiceA>(ref2));
US_TEST_CONDITION_REQUIRED(service == &s2, "Testing highest service rank")
reg2.Unregister();
US_TEST_CONDITION_REQUIRED(context->GetServiceReferences("").empty(), "Testing service count")
return EXIT_SUCCESS;
}
int usServiceRegistryTest(int /*argc*/, char* /*argv*/[])
{
US_TEST_BEGIN("ServiceRegistryTest");
US_TEST_CONDITION(TestMultipleServiceRegistrations() == EXIT_SUCCESS, "Testing service registrations: ")
US_TEST_CONDITION(TestServicePropertiesUpdate() == EXIT_SUCCESS, "Testing service property update: ")
US_TEST_END()
}
<commit_msg>COMP: Test only for a specific service interface count.<commit_after>/*=============================================================================
Library: CppMicroServices
Copyright (c) German Cancer Research Center,
Division of Medical and Biological Informatics
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 <usLDAPFilter.h>
#include "usTestingMacros.h"
#include <usServiceInterface.h>
#include <usGetModuleContext.h>
#include <usModuleContext.h>
#include US_BASECLASS_HEADER
#include <stdexcept>
US_USE_NAMESPACE
struct ITestServiceA
{
virtual ~ITestServiceA() {}
};
US_DECLARE_SERVICE_INTERFACE(ITestServiceA, "org.cppmicroservices.testing.ITestServiceA")
int TestMultipleServiceRegistrations()
{
struct TestServiceA : public US_BASECLASS_NAME, public ITestServiceA
{
};
ModuleContext* context = GetModuleContext();
TestServiceA s1;
TestServiceA s2;
ServiceRegistration reg1 = context->RegisterService<ITestServiceA>(&s1);
ServiceRegistration reg2 = context->RegisterService<ITestServiceA>(&s2);
std::list<ServiceReference> refs = context->GetServiceReferences<ITestServiceA>();
US_TEST_CONDITION_REQUIRED(refs.size() == 2, "Testing for two registered ITestServiceA services")
reg2.Unregister();
refs = context->GetServiceReferences<ITestServiceA>();
US_TEST_CONDITION_REQUIRED(refs.size() == 1, "Testing for one registered ITestServiceA services")
reg1.Unregister();
refs = context->GetServiceReferences<ITestServiceA>();
US_TEST_CONDITION_REQUIRED(refs.empty(), "Testing for no ITestServiceA services")
return EXIT_SUCCESS;
}
int TestServicePropertiesUpdate()
{
struct TestServiceA : public US_BASECLASS_NAME, public ITestServiceA
{
};
ModuleContext* context = GetModuleContext();
TestServiceA s1;
ServiceProperties props;
props["string"] = std::string("A std::string");
props["bool"] = false;
const char* str = "A const char*";
props["const char*"] = str;
ServiceRegistration reg1 = context->RegisterService<ITestServiceA>(&s1, props);
ServiceReference ref1 = context->GetServiceReference<ITestServiceA>();
US_TEST_CONDITION_REQUIRED(context->GetServiceReferences<ITestServiceA>().size() == 1, "Testing service count")
US_TEST_CONDITION_REQUIRED(any_cast<bool>(ref1.GetProperty("bool")) == false, "Testing bool property")
// register second service with higher rank
TestServiceA s2;
ServiceProperties props2;
props2[ServiceConstants::SERVICE_RANKING()] = 50;
ServiceRegistration reg2 = context->RegisterService<ITestServiceA>(&s2, props2);
// Get the service with the highest rank, this should be s2.
ServiceReference ref2 = context->GetServiceReference<ITestServiceA>();
TestServiceA* service = dynamic_cast<TestServiceA*>(context->GetService<ITestServiceA>(ref2));
US_TEST_CONDITION_REQUIRED(service == &s2, "Testing highest service rank")
props["bool"] = true;
// change the service ranking
props[ServiceConstants::SERVICE_RANKING()] = 100;
reg1.SetProperties(props);
US_TEST_CONDITION_REQUIRED(context->GetServiceReferences<ITestServiceA>().size() == 2, "Testing service count")
US_TEST_CONDITION_REQUIRED(any_cast<bool>(ref1.GetProperty("bool")) == true, "Testing bool property")
US_TEST_CONDITION_REQUIRED(any_cast<int>(ref1.GetProperty(ServiceConstants::SERVICE_RANKING())) == 100, "Testing updated ranking")
// Service with the highest ranking should now be s1
service = dynamic_cast<TestServiceA*>(context->GetService<ITestServiceA>(ref1));
US_TEST_CONDITION_REQUIRED(service == &s1, "Testing highest service rank")
reg1.Unregister();
US_TEST_CONDITION_REQUIRED(context->GetServiceReferences<ITestServiceA>("").size() == 1, "Testing service count")
service = dynamic_cast<TestServiceA*>(context->GetService<ITestServiceA>(ref2));
US_TEST_CONDITION_REQUIRED(service == &s2, "Testing highest service rank")
reg2.Unregister();
US_TEST_CONDITION_REQUIRED(context->GetServiceReferences<ITestServiceA>().empty(), "Testing service count")
return EXIT_SUCCESS;
}
int usServiceRegistryTest(int /*argc*/, char* /*argv*/[])
{
US_TEST_BEGIN("ServiceRegistryTest");
US_TEST_CONDITION(TestMultipleServiceRegistrations() == EXIT_SUCCESS, "Testing service registrations: ")
US_TEST_CONDITION(TestServicePropertiesUpdate() == EXIT_SUCCESS, "Testing service property update: ")
US_TEST_END()
}
<|endoftext|>
|
<commit_before>#pragma once
#include <tuple>
#include <utility>
#include <type_traits>
#include <agency/coordinate.hpp>
#include <agency/detail/tuple_utility.hpp>
#include <agency/detail/point_size.hpp>
#include <agency/detail/tuple.hpp>
namespace agency
{
namespace detail
{
namespace shape_cast_detail
{
template<class T>
struct make
{
template<class... Args>
__AGENCY_ANNOTATION
T operator()(Args&&... args) const
{
return T{std::forward<Args>(args)...};
}
};
} // end shape_cast_detail
// reduces the dimensionality of x by eliding the last dimension
// and multiplying the second-to-last dimension by the last
template<class Point>
__AGENCY_ANNOTATION
rebind_point_size_t<
Point,
point_size<Point>::value - 1
> project_shape(const Point& x)
{
using result_type = rebind_point_size_t<Point,std::tuple_size<Point>::value-1>;
auto last = __tu::tuple_last(x);
// XXX WAR nvcc 7's issue with tuple_drop_invoke
//auto result = __tu::tuple_drop_invoke<1>(x, shape_cast_detail::make<result_type>());
auto result = __tu::tuple_take_invoke<std::tuple_size<Point>::value - 1>(x, shape_cast_detail::make<result_type>());
__tu::tuple_last(result) *= last;
return result;
}
// increases the dimensionality of x
// by appending a dimension (and setting it to 1)
template<class Point>
__AGENCY_ANNOTATION
rebind_point_size_t<
Point,
point_size<Point>::value + 1
> lift_shape(const Point& x)
{
// x could be a scalar, so create an intermediate which is at least a 1-element tuple
using intermediate_type = rebind_point_size_t<Point,point_size<Point>::value>;
intermediate_type intermediate{x};
using result_type = rebind_point_size_t<Point,point_size<Point>::value + 1>;
return __tu::tuple_append_invoke(intermediate, 1, shape_cast_detail::make<result_type>());
}
// shape_cast is recursive and has various overloads
// declare them here before their definitions
// Scalar -> Scalar (base case)
template<class ToShape, class FromShape>
__AGENCY_ANNOTATION
typename std::enable_if<
(point_size<ToShape>::value == point_size<FromShape>::value) &&
(point_size<ToShape>::value == 1),
ToShape
>::type
shape_cast(const FromShape& x);
// case for casting two shapes of equal size (recursive case)
template<class ToShape, class FromShape>
__AGENCY_ANNOTATION
typename std::enable_if<
(point_size<ToShape>::value == point_size<FromShape>::value) &&
(point_size<ToShape>::value > 1),
ToShape
>::type
shape_cast(const FromShape& x);
// downcast (recursive)
template<class ToShape, class FromShape>
__AGENCY_ANNOTATION
typename std::enable_if<
(point_size<ToShape>::value < point_size<FromShape>::value),
ToShape
>::type
shape_cast(const FromShape& x);
// upcast (recursive)
template<class ToShape, class FromShape>
__AGENCY_ANNOTATION
typename std::enable_if<
(point_size<ToShape>::value > point_size<FromShape>::value),
ToShape
>::type
shape_cast(const FromShape& x);
// definitions of shape_cast follow
// terminal case for casting shapes of size 1
template<class ToShape, class FromShape>
__AGENCY_ANNOTATION
typename std::enable_if<
(point_size<ToShape>::value == point_size<FromShape>::value) &&
(point_size<ToShape>::value == 1),
ToShape
>::type
shape_cast(const FromShape& x)
{
// x might not be a tuple, but instead a scalar type
// to ensure we can get the 0th value from x in a uniform way, lift it first
return static_cast<ToShape>(detail::get<0>(lift_shape(x)));
}
struct shape_cast_functor
{
template<class ToShape, class FromShape>
__AGENCY_ANNOTATION
auto operator()(const ToShape&, const FromShape& x)
-> decltype(
shape_cast<ToShape>(x)
)
{
return shape_cast<ToShape>(x);
}
};
// recursive case for casting to a shape of equal size
template<class ToShape, class FromShape>
__AGENCY_ANNOTATION
typename std::enable_if<
(point_size<ToShape>::value == point_size<FromShape>::value) &&
(point_size<ToShape>::value > 1),
ToShape
>::type
shape_cast(const FromShape& x)
{
return __tu::tuple_map_with_make(shape_cast_functor{}, shape_cast_detail::make<ToShape>{}, ToShape{}, x);
}
// recursive case for casting to a lower dimensional shape
template<class ToShape, class FromShape>
__AGENCY_ANNOTATION
typename std::enable_if<
(point_size<ToShape>::value < point_size<FromShape>::value),
ToShape
>::type
shape_cast(const FromShape& x)
{
return shape_cast<ToShape>(project_shape(x));
}
// recursive case for casting to a higher dimensional shape
template<class ToShape, class FromShape>
__AGENCY_ANNOTATION
typename std::enable_if<
(point_size<ToShape>::value > point_size<FromShape>::value),
ToShape
>::type
shape_cast(const FromShape& x)
{
return shape_cast<ToShape>(lift_shape(x));
}
} // end detail
} // end agency
<commit_msg>Make shape_cast() unwrap single-element tuples it returns<commit_after>#pragma once
#include <tuple>
#include <utility>
#include <type_traits>
#include <agency/coordinate.hpp>
#include <agency/detail/tuple_utility.hpp>
#include <agency/detail/point_size.hpp>
#include <agency/detail/tuple.hpp>
namespace agency
{
namespace detail
{
namespace shape_cast_detail
{
template<class T>
struct make
{
template<class... Args>
__AGENCY_ANNOTATION
T operator()(Args&&... args) const
{
return T{std::forward<Args>(args)...};
}
};
} // end shape_cast_detail
// reduces the dimensionality of x by eliding the last dimension
// and multiplying the second-to-last dimension by the last
// this function always returns a tuple, even if it's a one-element tuple
template<class Point>
__AGENCY_ANNOTATION
rebind_point_size_t<
Point,
point_size<Point>::value - 1
> project_shape_impl(const Point& x)
{
using result_type = rebind_point_size_t<Point,std::tuple_size<Point>::value-1>;
auto last = __tu::tuple_last(x);
auto result = __tu::tuple_drop_invoke<1>(x, shape_cast_detail::make<result_type>());
__tu::tuple_last(result) *= last;
return result;
}
// reduces the dimensionality of shape by eliding the last dimension
// and multiplying the second-to-last dimension by the last
// this function unwraps single element tuples
template<class ShapeTuple>
__AGENCY_ANNOTATION
auto project_shape(const ShapeTuple& shape)
-> typename std::decay<
decltype(
detail::unwrap_single_element_tuple(
detail::project_shape_impl(shape)
)
)
>::type
{
return detail::unwrap_single_element_tuple(detail::project_shape_impl(shape));
}
// increases the dimensionality of x
// by appending a dimension (and setting it to 1)
template<class Point>
__AGENCY_ANNOTATION
rebind_point_size_t<
Point,
point_size<Point>::value + 1
> lift_shape(const Point& x)
{
// x could be a scalar, so create an intermediate which is at least a 1-element tuple
using intermediate_type = rebind_point_size_t<Point,point_size<Point>::value>;
intermediate_type intermediate{x};
using result_type = rebind_point_size_t<Point,point_size<Point>::value + 1>;
return __tu::tuple_append_invoke(intermediate, 1, shape_cast_detail::make<result_type>());
}
// shape_cast is recursive and has various overloads
// declare them here before their definitions
// Scalar -> Scalar (base case)
template<class ToShape, class FromShape>
__AGENCY_ANNOTATION
typename std::enable_if<
(point_size<ToShape>::value == point_size<FromShape>::value) &&
(point_size<ToShape>::value == 1),
ToShape
>::type
shape_cast(const FromShape& x);
// case for casting two shapes of equal size (recursive case)
template<class ToShape, class FromShape>
__AGENCY_ANNOTATION
typename std::enable_if<
(point_size<ToShape>::value == point_size<FromShape>::value) &&
(point_size<ToShape>::value > 1),
ToShape
>::type
shape_cast(const FromShape& x);
// downcast (recursive)
template<class ToShape, class FromShape>
__AGENCY_ANNOTATION
typename std::enable_if<
(point_size<ToShape>::value < point_size<FromShape>::value),
ToShape
>::type
shape_cast(const FromShape& x);
// upcast (recursive)
template<class ToShape, class FromShape>
__AGENCY_ANNOTATION
typename std::enable_if<
(point_size<ToShape>::value > point_size<FromShape>::value),
ToShape
>::type
shape_cast(const FromShape& x);
// definitions of shape_cast follow
// terminal case for casting shapes of size 1
template<class ToShape, class FromShape>
__AGENCY_ANNOTATION
typename std::enable_if<
(point_size<ToShape>::value == point_size<FromShape>::value) &&
(point_size<ToShape>::value == 1),
ToShape
>::type
shape_cast(const FromShape& x)
{
// x might not be a tuple, but instead a scalar type
// to ensure we can get the 0th value from x in a uniform way, lift it first
return static_cast<ToShape>(detail::get<0>(lift_shape(x)));
}
struct shape_cast_functor
{
template<class ToShape, class FromShape>
__AGENCY_ANNOTATION
auto operator()(const ToShape&, const FromShape& x)
-> decltype(
shape_cast<ToShape>(x)
)
{
return shape_cast<ToShape>(x);
}
};
// recursive case for casting to a shape of equal size
template<class ToShape, class FromShape>
__AGENCY_ANNOTATION
typename std::enable_if<
(point_size<ToShape>::value == point_size<FromShape>::value) &&
(point_size<ToShape>::value > 1),
ToShape
>::type
shape_cast(const FromShape& x)
{
return __tu::tuple_map_with_make(shape_cast_functor{}, shape_cast_detail::make<ToShape>{}, ToShape{}, x);
}
// recursive case for casting to a lower dimensional shape
template<class ToShape, class FromShape>
__AGENCY_ANNOTATION
typename std::enable_if<
(point_size<ToShape>::value < point_size<FromShape>::value),
ToShape
>::type
shape_cast(const FromShape& x)
{
return shape_cast<ToShape>(project_shape(x));
}
// recursive case for casting to a higher dimensional shape
template<class ToShape, class FromShape>
__AGENCY_ANNOTATION
typename std::enable_if<
(point_size<ToShape>::value > point_size<FromShape>::value),
ToShape
>::type
shape_cast(const FromShape& x)
{
return shape_cast<ToShape>(lift_shape(x));
}
} // end detail
} // end agency
<|endoftext|>
|
<commit_before>/*************************************************************************
*
* OpenOffice.org - a multi-platform office productivity suite
*
* $RCSfile: cairo_spritecanvas.cxx,v $
*
* $Revision: 1.5 $
*
* last change: $Author: obo $ $Date: 2007-07-17 14:21:38 $
*
* 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_canvas.hxx"
#include <canvas/debug.hxx>
#include <canvas/verbosetrace.hxx>
#include <canvas/canvastools.hxx>
#include <osl/mutex.hxx>
#include <com/sun/star/registry/XRegistryKey.hpp>
#include <com/sun/star/lang/XSingleServiceFactory.hpp>
#include <com/sun/star/uno/XComponentContext.hpp>
#include <cppuhelper/factory.hxx>
#include <cppuhelper/implementationentry.hxx>
#include <comphelper/servicedecl.hxx>
#include <basegfx/matrix/b2dhommatrix.hxx>
#include <basegfx/point/b2dpoint.hxx>
#include <basegfx/tools/canvastools.hxx>
#include <basegfx/numeric/ftools.hxx>
#include "cairo_spritecanvas.hxx"
using namespace ::cairo;
using namespace ::com::sun::star;
#define SERVICE_NAME "com.sun.star.rendering.CairoCanvas"
namespace cairocanvas
{
SpriteCanvas::SpriteCanvas( const uno::Sequence< uno::Any >& aArguments,
const uno::Reference< uno::XComponentContext >& rxContext ) :
mxComponentContext( rxContext ),
mpBackgroundSurface( NULL ),
mpBackgroundCairo( NULL )
{
// #i64742# Only call initialize when not in probe mode
if( aArguments.getLength() != 0 )
initialize( aArguments );
}
void SpriteCanvas::initialize( const uno::Sequence< uno::Any >& aArguments )
{
VERBOSE_TRACE("SpriteCanvas created %p\n", this);
// At index 1, we expect a system window handle here,
// containing a pointer to a valid window, on which to output
// At index 2, we expect the current window bound rect
CHECK_AND_THROW( aArguments.getLength() >= 4 &&
aArguments[1].getValueTypeClass() == uno::TypeClass_LONG,
"SpriteCanvas::initialize: wrong number of arguments, or wrong types" );
awt::Rectangle aRect;
aArguments[2] >>= aRect;
sal_Bool bIsFullscreen( sal_False );
aArguments[3] >>= bIsFullscreen;
// TODO(Q2): This now works for Solaris, but still warns for gcc
Window* pOutputWindow = (Window*) *reinterpret_cast<const sal_Int64*>(aArguments[0].getValue());
Size aPixelSize( pOutputWindow->GetOutputSizePixel() );
const ::basegfx::B2ISize aSize( aPixelSize.Width(),
aPixelSize.Height() );
CHECK_AND_THROW( pOutputWindow != NULL,
"SpriteCanvas::initialize: invalid Window pointer" );
// setup helper
maDeviceHelper.init( *pOutputWindow,
*this,
aSize,
bIsFullscreen );
maCanvasHelper.init( maRedrawManager,
*this,
aSize );
}
void SAL_CALL SpriteCanvas::disposing()
{
::osl::MutexGuard aGuard( m_aMutex );
mxComponentContext.clear();
if( mpBackgroundCairo ) {
cairo_destroy( mpBackgroundCairo );
mpBackgroundCairo = NULL;
}
if( mpBackgroundSurface ) {
mpBackgroundSurface->Unref();
mpBackgroundSurface = NULL;
}
// forward to parent
SpriteCanvasBaseT::disposing();
}
::sal_Bool SAL_CALL SpriteCanvas::showBuffer( ::sal_Bool bUpdateAll ) throw (uno::RuntimeException)
{
::osl::MutexGuard aGuard( m_aMutex );
// avoid repaints on hidden window (hidden: not mapped to
// screen). Return failure, since the screen really has _not_
// been updated (caller should try again later)
return !mbIsVisible ? false : SpriteCanvasBaseT::showBuffer( bUpdateAll );
}
::sal_Bool SAL_CALL SpriteCanvas::switchBuffer( ::sal_Bool bUpdateAll ) throw (uno::RuntimeException)
{
::osl::MutexGuard aGuard( m_aMutex );
// avoid repaints on hidden window (hidden: not mapped to
// screen). Return failure, since the screen really has _not_
// been updated (caller should try again later)
return !mbIsVisible ? false : SpriteCanvasBaseT::switchBuffer( bUpdateAll );
}
sal_Bool SAL_CALL SpriteCanvas::updateScreen( sal_Bool bUpdateAll ) throw (uno::RuntimeException)
{
::osl::MutexGuard aGuard( m_aMutex );
// avoid repaints on hidden window (hidden: not mapped to
// screen). Return failure, since the screen really has _not_
// been updated (caller should try again later)
return !mbIsVisible ? false : maCanvasHelper.updateScreen(
::basegfx::unotools::b2IRectangleFromAwtRectangle(maBounds),
bUpdateAll,
mbSurfaceDirty );
// avoid repaints on hidden window (hidden: not mapped to
// screen). Return failure, since the screen really has _not_
// been updated (caller should try again later)
return !mbIsVisible ? false : SpriteCanvasBaseT::updateScreen( bUpdateAll );
}
::rtl::OUString SAL_CALL SpriteCanvas::getServiceName( ) throw (uno::RuntimeException)
{
return ::rtl::OUString( RTL_CONSTASCII_USTRINGPARAM( SERVICE_NAME ) );
}
Surface* SpriteCanvas::getSurface( const ::basegfx::B2ISize& rSize, Content aContent )
{
return maDeviceHelper.getSurface( rSize, aContent );
}
Surface* SpriteCanvas::getSurface( Content aContent )
{
return maDeviceHelper.getSurface( aContent );
}
Surface* SpriteCanvas::getSurface( Bitmap& rBitmap )
{
Surface *pSurface = NULL;
BitmapSystemData aData;
if( rBitmap.GetSystemData( aData ) ) {
const Size& rSize = rBitmap.GetSizePixel();
pSurface = maDeviceHelper.getSurface( aData, rSize );
}
return pSurface;
}
Surface* SpriteCanvas::getBufferSurface()
{
return maDeviceHelper.getBufferSurface();
}
Surface* SpriteCanvas::getWindowSurface()
{
return maDeviceHelper.getWindowSurface();
}
Surface* SpriteCanvas::getBackgroundSurface()
{
return mpBackgroundSurface;
}
const ::basegfx::B2ISize& SpriteCanvas::getSizePixel()
{
return maDeviceHelper.getSizePixel();
}
void SpriteCanvas::setSizePixel( const ::basegfx::B2ISize& /*rSize*/ )
{
if( mpBackgroundSurface )
{
mpBackgroundSurface->Unref();
}
mpBackgroundSurface = maDeviceHelper.getSurface( CAIRO_CONTENT_COLOR );
if( mpBackgroundCairo )
{
cairo_destroy( mpBackgroundCairo );
}
mpBackgroundCairo = mpBackgroundSurface->getCairo();
maCanvasHelper.setSurface( mpBackgroundSurface, false );
}
void SpriteCanvas::flush()
{
maDeviceHelper.flush();
}
bool SpriteCanvas::repaint( Surface* pSurface,
const rendering::ViewState& viewState,
const rendering::RenderState& renderState )
{
return maCanvasHelper.repaint( pSurface, viewState, renderState );
}
namespace sdecl = comphelper::service_decl;
#if defined (__GNUC__) && (__GNUC__ == 3 && __GNUC_MINOR__ <= 3)
sdecl::class_<SpriteCanvas, sdecl::with_args<true> > serviceImpl;
const sdecl::ServiceDecl cairoCanvasDecl(
serviceImpl,
#else
const sdecl::ServiceDecl cairoCanvasDecl(
sdecl::class_<SpriteCanvas, sdecl::with_args<true> >(),
#endif
"com.sun.star.comp.rendering.CairoCanvas",
SERVICE_NAME );
}
// The C shared lib entry points
COMPHELPER_SERVICEDECL_EXPORTS1(cairocanvas::cairoCanvasDecl)
<commit_msg>INTEGRATION: CWS transogl01 (1.5.6); FILE MERGED 2007/08/27 14:35:48 radekdoulik 1.5.6.1: Issue number: 78745 Submitted by: radekdoulik<commit_after>/*************************************************************************
*
* OpenOffice.org - a multi-platform office productivity suite
*
* $RCSfile: cairo_spritecanvas.cxx,v $
*
* $Revision: 1.6 $
*
* last change: $Author: rt $ $Date: 2007-11-09 10:14:15 $
*
* 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_canvas.hxx"
#include <canvas/debug.hxx>
#include <canvas/verbosetrace.hxx>
#include <canvas/canvastools.hxx>
#include <osl/mutex.hxx>
#include <com/sun/star/registry/XRegistryKey.hpp>
#include <com/sun/star/lang/XSingleServiceFactory.hpp>
#include <com/sun/star/uno/XComponentContext.hpp>
#include <cppuhelper/factory.hxx>
#include <cppuhelper/implementationentry.hxx>
#include <comphelper/servicedecl.hxx>
#include <basegfx/matrix/b2dhommatrix.hxx>
#include <basegfx/point/b2dpoint.hxx>
#include <basegfx/tools/canvastools.hxx>
#include <basegfx/numeric/ftools.hxx>
#include "cairo_spritecanvas.hxx"
using namespace ::cairo;
using namespace ::com::sun::star;
#define SERVICE_NAME "com.sun.star.rendering.CairoCanvas"
namespace cairocanvas
{
SpriteCanvas::SpriteCanvas( const uno::Sequence< uno::Any >& aArguments,
const uno::Reference< uno::XComponentContext >& rxContext ) :
mxComponentContext( rxContext ),
mpBackgroundSurface( NULL ),
mpBackgroundCairo( NULL )
{
// #i64742# Only call initialize when not in probe mode
if( aArguments.getLength() != 0 )
initialize( aArguments );
}
void SpriteCanvas::initialize( const uno::Sequence< uno::Any >& aArguments )
{
VERBOSE_TRACE("SpriteCanvas created %p\n", this);
// At index 1, we expect a system window handle here,
// containing a pointer to a valid window, on which to output
// At index 2, we expect the current window bound rect
CHECK_AND_THROW( aArguments.getLength() >= 4 &&
aArguments[1].getValueTypeClass() == uno::TypeClass_LONG,
"SpriteCanvas::initialize: wrong number of arguments, or wrong types" );
awt::Rectangle aRect;
aArguments[2] >>= aRect;
sal_Bool bIsFullscreen( sal_False );
aArguments[3] >>= bIsFullscreen;
// TODO(Q2): This now works for Solaris, but still warns for gcc
Window* pOutputWindow = (Window*) *reinterpret_cast<const sal_Int64*>(aArguments[0].getValue());
Size aPixelSize( pOutputWindow->GetOutputSizePixel() );
const ::basegfx::B2ISize aSize( aPixelSize.Width(),
aPixelSize.Height() );
CHECK_AND_THROW( pOutputWindow != NULL,
"SpriteCanvas::initialize: invalid Window pointer" );
// setup helper
maDeviceHelper.init( *pOutputWindow,
*this,
aSize,
bIsFullscreen );
maCanvasHelper.init( maRedrawManager,
*this,
aSize );
}
void SAL_CALL SpriteCanvas::disposing()
{
::osl::MutexGuard aGuard( m_aMutex );
mxComponentContext.clear();
if( mpBackgroundCairo ) {
cairo_destroy( mpBackgroundCairo );
mpBackgroundCairo = NULL;
}
if( mpBackgroundSurface ) {
mpBackgroundSurface->Unref();
mpBackgroundSurface = NULL;
}
// forward to parent
SpriteCanvasBaseT::disposing();
}
::sal_Bool SAL_CALL SpriteCanvas::showBuffer( ::sal_Bool bUpdateAll ) throw (uno::RuntimeException)
{
::osl::MutexGuard aGuard( m_aMutex );
// avoid repaints on hidden window (hidden: not mapped to
// screen). Return failure, since the screen really has _not_
// been updated (caller should try again later)
return !mbIsVisible ? false : SpriteCanvasBaseT::showBuffer( bUpdateAll );
}
::sal_Bool SAL_CALL SpriteCanvas::switchBuffer( ::sal_Bool bUpdateAll ) throw (uno::RuntimeException)
{
::osl::MutexGuard aGuard( m_aMutex );
// avoid repaints on hidden window (hidden: not mapped to
// screen). Return failure, since the screen really has _not_
// been updated (caller should try again later)
return !mbIsVisible ? false : SpriteCanvasBaseT::switchBuffer( bUpdateAll );
}
sal_Bool SAL_CALL SpriteCanvas::updateScreen( sal_Bool bUpdateAll ) throw (uno::RuntimeException)
{
::osl::MutexGuard aGuard( m_aMutex );
// avoid repaints on hidden window (hidden: not mapped to
// screen). Return failure, since the screen really has _not_
// been updated (caller should try again later)
return !mbIsVisible ? false : maCanvasHelper.updateScreen(
::basegfx::unotools::b2IRectangleFromAwtRectangle(maBounds),
bUpdateAll,
mbSurfaceDirty );
// avoid repaints on hidden window (hidden: not mapped to
// screen). Return failure, since the screen really has _not_
// been updated (caller should try again later)
return !mbIsVisible ? false : SpriteCanvasBaseT::updateScreen( bUpdateAll );
}
::rtl::OUString SAL_CALL SpriteCanvas::getServiceName( ) throw (uno::RuntimeException)
{
return ::rtl::OUString( RTL_CONSTASCII_USTRINGPARAM( SERVICE_NAME ) );
}
Surface* SpriteCanvas::getSurface( const ::basegfx::B2ISize& rSize, Content aContent )
{
return maDeviceHelper.getSurface( rSize, aContent );
}
Surface* SpriteCanvas::getSurface( Content aContent )
{
return maDeviceHelper.getSurface( aContent );
}
Surface* SpriteCanvas::getSurface( Bitmap& rBitmap )
{
Surface *pSurface = NULL;
BitmapSystemData aData;
if( rBitmap.GetSystemData( aData ) ) {
const Size& rSize = rBitmap.GetSizePixel();
pSurface = maDeviceHelper.getSurface( aData, rSize );
}
return pSurface;
}
Surface* SpriteCanvas::getBufferSurface()
{
return maDeviceHelper.getBufferSurface();
}
Surface* SpriteCanvas::getWindowSurface()
{
return maDeviceHelper.getWindowSurface();
}
Surface* SpriteCanvas::getBackgroundSurface()
{
return mpBackgroundSurface;
}
const ::basegfx::B2ISize& SpriteCanvas::getSizePixel()
{
return maDeviceHelper.getSizePixel();
}
void SpriteCanvas::setSizePixel( const ::basegfx::B2ISize& rSize )
{
if( mpBackgroundSurface )
{
mpBackgroundSurface->Unref();
}
mpBackgroundSurface = maDeviceHelper.getSurface( CAIRO_CONTENT_COLOR );
if( mpBackgroundCairo )
{
cairo_destroy( mpBackgroundCairo );
}
mpBackgroundCairo = mpBackgroundSurface->getCairo();
maCanvasHelper.setSize( rSize );
maCanvasHelper.setSurface( mpBackgroundSurface, false );
}
void SpriteCanvas::flush()
{
maDeviceHelper.flush();
}
bool SpriteCanvas::repaint( Surface* pSurface,
const rendering::ViewState& viewState,
const rendering::RenderState& renderState )
{
return maCanvasHelper.repaint( pSurface, viewState, renderState );
}
namespace sdecl = comphelper::service_decl;
#if defined (__GNUC__) && (__GNUC__ == 3 && __GNUC_MINOR__ <= 3)
sdecl::class_<SpriteCanvas, sdecl::with_args<true> > serviceImpl;
const sdecl::ServiceDecl cairoCanvasDecl(
serviceImpl,
#else
const sdecl::ServiceDecl cairoCanvasDecl(
sdecl::class_<SpriteCanvas, sdecl::with_args<true> >(),
#endif
"com.sun.star.comp.rendering.CairoCanvas",
SERVICE_NAME );
}
// The C shared lib entry points
COMPHELPER_SERVICEDECL_EXPORTS1(cairocanvas::cairoCanvasDecl)
<|endoftext|>
|
<commit_before>/*
* Copyright 2017-2019 Baidu 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 "openrasp.h"
#include "openrasp_ini.h"
#include "openrasp_utils.h"
#include "openrasp_log.h"
#include "utils/debug_trace.h"
extern "C"
{
#include "php_ini.h"
#include "php_main.h"
#include "php_streams.h"
#include "zend_smart_str.h"
#include "ext/pcre/php_pcre.h"
#include "ext/standard/url.h"
#include "ext/standard/file.h"
#include "ext/json/php_json.h"
#include "Zend/zend_builtin_functions.h"
}
#include <string>
using openrasp::DebugTrace;
static std::vector<DebugTrace> build_debug_trace(long limit)
{
zval trace_arr;
std::vector<DebugTrace> array;
zend_fetch_debug_backtrace(&trace_arr, 0, 0, 0);
if (Z_TYPE(trace_arr) == IS_ARRAY)
{
int i = 0;
HashTable *hash_arr = Z_ARRVAL(trace_arr);
zval *ele_value = NULL;
ZEND_HASH_FOREACH_VAL(hash_arr, ele_value)
{
if (++i > limit)
{
break;
}
if (Z_TYPE_P(ele_value) != IS_ARRAY)
{
continue;
}
DebugTrace trace_item;
zval *trace_ele;
if ((trace_ele = zend_hash_str_find(Z_ARRVAL_P(ele_value), ZEND_STRL("file"))) != NULL &&
Z_TYPE_P(trace_ele) == IS_STRING)
{
trace_item.set_file(Z_STRVAL_P(trace_ele));
}
if ((trace_ele = zend_hash_str_find(Z_ARRVAL_P(ele_value), ZEND_STRL("function"))) != NULL &&
Z_TYPE_P(trace_ele) == IS_STRING)
{
trace_item.set_function(Z_STRVAL_P(trace_ele));
}
if ((trace_ele = zend_hash_str_find(Z_ARRVAL_P(ele_value), ZEND_STRL("line"))) != NULL &&
Z_TYPE_P(trace_ele) == IS_LONG)
{
trace_item.set_line(Z_LVAL_P(trace_ele));
}
array.push_back(trace_item);
}
ZEND_HASH_FOREACH_END();
}
zval_dtor(&trace_arr);
return array;
}
std::string format_debug_backtrace_str()
{
std::vector<DebugTrace> trace = build_debug_trace(OPENRASP_CONFIG(log.maxstack));
std::string buffer;
for (DebugTrace &item : trace)
{
buffer.append(item.to_log_string() + "\n");
}
if (buffer.length() > 0)
{
buffer.pop_back();
}
return buffer;
}
void format_debug_backtrace_str(zval *backtrace_str)
{
auto trace = format_debug_backtrace_str();
ZVAL_STRINGL(backtrace_str, trace.c_str(), trace.length());
}
std::vector<std::string> format_source_code_arr()
{
std::vector<DebugTrace> trace = build_debug_trace(OPENRASP_CONFIG(log.maxstack));
std::vector<std::string> array;
for (DebugTrace &item : trace)
{
array.push_back(item.get_source_code());
}
return array;
}
void format_source_code_arr(zval *source_code_arr)
{
auto array = format_source_code_arr();
for (auto &str : array)
{
add_next_index_stringl(source_code_arr, str.c_str(), str.length());
}
}
std::vector<std::string> format_debug_backtrace_arr()
{
std::vector<DebugTrace> trace = build_debug_trace(OPENRASP_CONFIG(plugin.maxstack));
std::vector<std::string> array;
for (DebugTrace &item : trace)
{
array.push_back(item.to_plugin_string());
}
return array;
}
void format_debug_backtrace_arr(zval *backtrace_arr)
{
auto array = format_debug_backtrace_arr();
for (auto &str : array)
{
add_next_index_stringl(backtrace_arr, str.c_str(), str.length());
}
}
int recursive_mkdir(const char *path, int len, int mode)
{
struct stat sb;
if (VCWD_STAT(path, &sb) == 0 && (sb.st_mode & S_IFDIR) != 0)
{
return 1;
}
char *dirname = estrndup(path, len);
int dirlen = php_dirname(dirname, len);
int rst = recursive_mkdir(dirname, dirlen, mode);
efree(dirname);
if (rst)
{
#ifndef PHP_WIN32
mode_t oldmask = umask(0);
rst = VCWD_MKDIR(path, mode);
umask(oldmask);
#else
rst = VCWD_MKDIR(path, mode);
#endif
if (rst == 0 || EEXIST == errno)
{
return 1;
}
openrasp_error(LEVEL_WARNING, RUNTIME_ERROR, _("Could not create directory '%s': %s"), path, strerror(errno));
}
return 0;
}
const char *fetch_url_scheme(const char *filename)
{
if (nullptr == filename)
{
return nullptr;
}
const char *p;
for (p = filename; isalnum((int)*p) || *p == '+' || *p == '-' || *p == '.'; p++)
;
if ((*p == ':') && (p - filename > 1) && (p[1] == '/') && (p[2] == '/'))
{
return p;
}
return nullptr;
}
void openrasp_scandir(const std::string dir_abs, std::vector<std::string> &plugins, std::function<bool(const char *filename)> file_filter, bool use_abs_path)
{
DIR *dir;
std::string result;
struct dirent *ent;
if ((dir = opendir(dir_abs.c_str())) != NULL)
{
while ((ent = readdir(dir)) != NULL)
{
if (file_filter)
{
if (file_filter(ent->d_name))
{
plugins.push_back(use_abs_path ? (dir_abs + std::string(1, DEFAULT_SLASH) + std::string(ent->d_name)) : std::string(ent->d_name));
}
}
}
closedir(dir);
}
}
char *fetch_outmost_string_from_ht(HashTable *ht, const char *arKey)
{
zval *origin_zv;
if ((origin_zv = zend_hash_str_find(ht, arKey, strlen(arKey))) != nullptr &&
Z_TYPE_P(origin_zv) == IS_STRING)
{
return Z_STRVAL_P(origin_zv);
}
return nullptr;
}
bool get_entire_file_content(const char *file, std::string &content)
{
std::ifstream ifs(file, std::ifstream::in | std::ifstream::binary);
if (ifs.is_open() && ifs.good())
{
content = {std::istreambuf_iterator<char>(ifs), std::istreambuf_iterator<char>()};
return true;
}
return false;
}
std::string json_encode_from_zval(zval *value)
{
smart_str buf_json = {0};
php_json_encode(&buf_json, value, 0);
smart_str_0(&buf_json);
std::string result(ZSTR_VAL(buf_json.s));
smart_str_free(&buf_json);
return result;
}
zend_string *fetch_request_body(size_t max_len)
{
php_stream *stream = php_stream_open_wrapper("php://input", "rb", 0, NULL);
if (!stream)
{
return zend_string_init("", strlen(""), 0);
}
zend_string *buf = php_stream_copy_to_mem(stream, max_len, 0);
php_stream_close(stream);
if (!buf)
{
return zend_string_init("", strlen(""), 0);
}
return buf;
}
bool need_alloc_shm_current_sapi()
{
static const char *supported_sapis[] = {
"fpm-fcgi",
"apache2handler",
NULL};
const char **sapi_name;
if (sapi_module.name)
{
for (sapi_name = supported_sapis; *sapi_name; sapi_name++)
{
if (strcmp(sapi_module.name, *sapi_name) == 0)
{
return 1;
}
}
}
return 0;
}
std::string convert_to_header_key(char *key, size_t length)
{
if (key == nullptr ||
strncmp(key, "HTTP_", 5) != 0)
{
return "";
}
std::string result(key + 5, length - 5);
for (auto &ch : result)
{
if (ch == '_')
{
ch = '-';
}
else
{
ch = std::tolower(ch);
}
}
return result;
}
bool openrasp_parse_url(const std::string &origin_url, std::string &scheme, std::string &host, std::string &port)
{
php_url *url = php_url_parse_ex(origin_url.c_str(), origin_url.length());
if (url)
{
if (url->scheme)
{
scheme = std::string(url->scheme);
}
if (url->host)
{
#if (PHP_MINOR_VERSION < 3)
host = std::string(url->host);
#else
host = std::string(url->host->val, url->host->len);
#endif
port = std::to_string(url->port);
}
php_url_free(url);
return true;
}
return false;
}<commit_msg>[PHP7]兼容php7.3<commit_after>/*
* Copyright 2017-2019 Baidu 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 "openrasp.h"
#include "openrasp_ini.h"
#include "openrasp_utils.h"
#include "openrasp_log.h"
#include "utils/debug_trace.h"
extern "C"
{
#include "php_ini.h"
#include "php_main.h"
#include "php_streams.h"
#include "zend_smart_str.h"
#include "ext/pcre/php_pcre.h"
#include "ext/standard/url.h"
#include "ext/standard/file.h"
#include "ext/json/php_json.h"
#include "Zend/zend_builtin_functions.h"
}
#include <string>
using openrasp::DebugTrace;
static std::vector<DebugTrace> build_debug_trace(long limit)
{
zval trace_arr;
std::vector<DebugTrace> array;
zend_fetch_debug_backtrace(&trace_arr, 0, 0, 0);
if (Z_TYPE(trace_arr) == IS_ARRAY)
{
int i = 0;
HashTable *hash_arr = Z_ARRVAL(trace_arr);
zval *ele_value = NULL;
ZEND_HASH_FOREACH_VAL(hash_arr, ele_value)
{
if (++i > limit)
{
break;
}
if (Z_TYPE_P(ele_value) != IS_ARRAY)
{
continue;
}
DebugTrace trace_item;
zval *trace_ele;
if ((trace_ele = zend_hash_str_find(Z_ARRVAL_P(ele_value), ZEND_STRL("file"))) != NULL &&
Z_TYPE_P(trace_ele) == IS_STRING)
{
trace_item.set_file(Z_STRVAL_P(trace_ele));
}
if ((trace_ele = zend_hash_str_find(Z_ARRVAL_P(ele_value), ZEND_STRL("function"))) != NULL &&
Z_TYPE_P(trace_ele) == IS_STRING)
{
trace_item.set_function(Z_STRVAL_P(trace_ele));
}
if ((trace_ele = zend_hash_str_find(Z_ARRVAL_P(ele_value), ZEND_STRL("line"))) != NULL &&
Z_TYPE_P(trace_ele) == IS_LONG)
{
trace_item.set_line(Z_LVAL_P(trace_ele));
}
array.push_back(trace_item);
}
ZEND_HASH_FOREACH_END();
}
zval_dtor(&trace_arr);
return array;
}
std::string format_debug_backtrace_str()
{
std::vector<DebugTrace> trace = build_debug_trace(OPENRASP_CONFIG(log.maxstack));
std::string buffer;
for (DebugTrace &item : trace)
{
buffer.append(item.to_log_string() + "\n");
}
if (buffer.length() > 0)
{
buffer.pop_back();
}
return buffer;
}
void format_debug_backtrace_str(zval *backtrace_str)
{
auto trace = format_debug_backtrace_str();
ZVAL_STRINGL(backtrace_str, trace.c_str(), trace.length());
}
std::vector<std::string> format_source_code_arr()
{
std::vector<DebugTrace> trace = build_debug_trace(OPENRASP_CONFIG(log.maxstack));
std::vector<std::string> array;
for (DebugTrace &item : trace)
{
array.push_back(item.get_source_code());
}
return array;
}
void format_source_code_arr(zval *source_code_arr)
{
auto array = format_source_code_arr();
for (auto &str : array)
{
add_next_index_stringl(source_code_arr, str.c_str(), str.length());
}
}
std::vector<std::string> format_debug_backtrace_arr()
{
std::vector<DebugTrace> trace = build_debug_trace(OPENRASP_CONFIG(plugin.maxstack));
std::vector<std::string> array;
for (DebugTrace &item : trace)
{
array.push_back(item.to_plugin_string());
}
return array;
}
void format_debug_backtrace_arr(zval *backtrace_arr)
{
auto array = format_debug_backtrace_arr();
for (auto &str : array)
{
add_next_index_stringl(backtrace_arr, str.c_str(), str.length());
}
}
int recursive_mkdir(const char *path, int len, int mode)
{
struct stat sb;
if (VCWD_STAT(path, &sb) == 0 && (sb.st_mode & S_IFDIR) != 0)
{
return 1;
}
char *dirname = estrndup(path, len);
int dirlen = php_dirname(dirname, len);
int rst = recursive_mkdir(dirname, dirlen, mode);
efree(dirname);
if (rst)
{
#ifndef PHP_WIN32
mode_t oldmask = umask(0);
rst = VCWD_MKDIR(path, mode);
umask(oldmask);
#else
rst = VCWD_MKDIR(path, mode);
#endif
if (rst == 0 || EEXIST == errno)
{
return 1;
}
openrasp_error(LEVEL_WARNING, RUNTIME_ERROR, _("Could not create directory '%s': %s"), path, strerror(errno));
}
return 0;
}
const char *fetch_url_scheme(const char *filename)
{
if (nullptr == filename)
{
return nullptr;
}
const char *p;
for (p = filename; isalnum((int)*p) || *p == '+' || *p == '-' || *p == '.'; p++)
;
if ((*p == ':') && (p - filename > 1) && (p[1] == '/') && (p[2] == '/'))
{
return p;
}
return nullptr;
}
void openrasp_scandir(const std::string dir_abs, std::vector<std::string> &plugins, std::function<bool(const char *filename)> file_filter, bool use_abs_path)
{
DIR *dir;
std::string result;
struct dirent *ent;
if ((dir = opendir(dir_abs.c_str())) != NULL)
{
while ((ent = readdir(dir)) != NULL)
{
if (file_filter)
{
if (file_filter(ent->d_name))
{
plugins.push_back(use_abs_path ? (dir_abs + std::string(1, DEFAULT_SLASH) + std::string(ent->d_name)) : std::string(ent->d_name));
}
}
}
closedir(dir);
}
}
char *fetch_outmost_string_from_ht(HashTable *ht, const char *arKey)
{
zval *origin_zv;
if ((origin_zv = zend_hash_str_find(ht, arKey, strlen(arKey))) != nullptr &&
Z_TYPE_P(origin_zv) == IS_STRING)
{
return Z_STRVAL_P(origin_zv);
}
return nullptr;
}
bool get_entire_file_content(const char *file, std::string &content)
{
std::ifstream ifs(file, std::ifstream::in | std::ifstream::binary);
if (ifs.is_open() && ifs.good())
{
content = {std::istreambuf_iterator<char>(ifs), std::istreambuf_iterator<char>()};
return true;
}
return false;
}
std::string json_encode_from_zval(zval *value)
{
smart_str buf_json = {0};
php_json_encode(&buf_json, value, 0);
smart_str_0(&buf_json);
std::string result(ZSTR_VAL(buf_json.s));
smart_str_free(&buf_json);
return result;
}
zend_string *fetch_request_body(size_t max_len)
{
php_stream *stream = php_stream_open_wrapper("php://input", "rb", 0, NULL);
if (!stream)
{
return zend_string_init("", strlen(""), 0);
}
zend_string *buf = php_stream_copy_to_mem(stream, max_len, 0);
php_stream_close(stream);
if (!buf)
{
return zend_string_init("", strlen(""), 0);
}
return buf;
}
bool need_alloc_shm_current_sapi()
{
static const char *supported_sapis[] = {
"fpm-fcgi",
"apache2handler",
NULL};
const char **sapi_name;
if (sapi_module.name)
{
for (sapi_name = supported_sapis; *sapi_name; sapi_name++)
{
if (strcmp(sapi_module.name, *sapi_name) == 0)
{
return 1;
}
}
}
return 0;
}
std::string convert_to_header_key(char *key, size_t length)
{
if (key == nullptr ||
strncmp(key, "HTTP_", 5) != 0)
{
return "";
}
std::string result(key + 5, length - 5);
for (auto &ch : result)
{
if (ch == '_')
{
ch = '-';
}
else
{
ch = std::tolower(ch);
}
}
return result;
}
bool openrasp_parse_url(const std::string &origin_url, std::string &scheme, std::string &host, std::string &port)
{
php_url *url = php_url_parse_ex(origin_url.c_str(), origin_url.length());
if (url)
{
if (url->scheme)
{
#if (PHP_MINOR_VERSION < 3)
scheme = std::string(url->scheme);
#else
scheme = std::string(url->scheme->val, url->scheme->len);
#endif
}
if (url->host)
{
#if (PHP_MINOR_VERSION < 3)
host = std::string(url->host);
#else
host = std::string(url->host->val, url->host->len);
#endif
port = std::to_string(url->port);
}
php_url_free(url);
return true;
}
return false;
}<|endoftext|>
|
<commit_before>#include <vector>
#include <string>
#include <fstream>
#include <iostream>
#include <sstream>
#include <map>
#include <stdlib.h>
#include <cmath>
#include <iomanip>
//typedefs
typedef std::vector<std::vector<std::string> > STR_DOUBLE_VEC; //for the parsing
typedef std::map<std::string, int> STR_INT_MAP; //for the processed data
//definitons
void process_csv(std::istream&, STR_DOUBLE_VEC&); //processes the data provided
void usage(std::ostream&, std::string, std::string=""); //in the event program fails, print usage
void output_data(std::ostream&, const STR_INT_MAP&, int); //output the results
//main
int main(int argc, char* argv[]) {
if(argc < 3) { //not enough arguments provided
usage(std::cerr, argv[0]);
return 1;
}
std::ifstream file_stream(argv[1]); //load the file provided
if(!file_stream.good()) { //if the file is not valid
usage(std::cerr, argv[0], "Your file is invalid!");
return 1;
}
if(atoi(argv[2]) == 0) { //if the num of meetings is either 0 or NaN
usage(std::cerr, argv[0], "You haven't specified a valid number of meetings! (> 0)");
return 1;
}
int num_meetings = atoi(argv[2]); //otherwise, set it to that number
//num to pool is how many attendance lists to count from
int num_to_pool = (argc >= 4) ? atoi(argv[3]) : num_meetings;
if(num_to_pool < num_meetings) { //if the number of meetings is unreachable
usage(std::cerr, argv[0], "Your number to pool from must be greater than the number of needed meetings!");
return 1;
}
STR_DOUBLE_VEC contents; //to store the soon-to-be-parsed data
STR_INT_MAP attendance_record; //to track attendance record
process_csv(file_stream, contents); //get the data processed
//figure out where to start in the file
int x = (contents.size()-num_to_pool <= 0) ? 0 : contents.size()-num_to_pool;
for(; x<contents.size(); x++) { //crawl the vector and count attendance
for(int y=0; y<contents[x].size(); y++) {
attendance_record[contents[x][y]]++;
}
}
output_data(std::cout, attendance_record, num_meetings); //output the results, giving
return 0;
}
//functions
void usage(std::ostream& out, std::string exe_name, std::string custom_error) {
out << std::endl;
if(custom_error != "") out << custom_error << std::endl;
out << "USAGE: " << exe_name << " <file name> <number of meetings> [meetings to pool]" << std::endl;
out << std::endl;
}
void process_csv(std::istream& in_str, STR_DOUBLE_VEC& contents) {
std::string line, cell;
while(std::getline(in_str, line)) {
std::stringstream line_stream(line);
std::vector<std::string> t;
while(std::getline(line_stream,cell,','))
t.push_back(cell);
contents.push_back(t);
}
}
void output_data(std::ostream& out, const STR_INT_MAP& attendance_record, int num_meetings) {
int count = 0; //counter of total valid voting membership
//print the results (only those who qualify to vote)
for(STR_INT_MAP::const_iterator itr = attendance_record.begin(); itr != attendance_record.end(); ++itr) {
if(itr->second >= num_meetings) {
//print the member and number of meetings attended in pool range
out << itr->first << " (" << itr->second << ")" << std::endl;
++count;
}
}
out << std::endl;
if(count <= 0){
out << "No members qualify to vote." << std::endl;
return;
}
out << "A total of " << count << " members qualify to vote." << std::endl;
out << std::setw(28) << std::left << "Simple majority (.51)" << ceil((float)count*.51) << " / " << count << std::endl;
out << std::setw(28) << std::left << "Two-thirds majority (2/3)" << ceil((float)count*(2/(float)3)) << " / " << count << std::endl;
}<commit_msg>moved math into variable decls<commit_after>#include <vector>
#include <string>
#include <fstream>
#include <iostream>
#include <sstream>
#include <map>
#include <stdlib.h>
#include <cmath>
#include <iomanip>
//typedefs
typedef std::vector<std::vector<std::string> > STR_DOUBLE_VEC; //for the parsing
typedef std::map<std::string, int> STR_INT_MAP; //for the processed data
//definitons
void process_csv(std::istream&, STR_DOUBLE_VEC&); //processes the data provided
void usage(std::ostream&, std::string, std::string=""); //in the event program fails, print usage
void output_data(std::ostream&, const STR_INT_MAP&, int); //output the results
//main
int main(int argc, char* argv[]) {
if(argc < 3) { //not enough arguments provided
usage(std::cerr, argv[0]);
return 1;
}
std::ifstream file_stream(argv[1]); //load the file provided
if(!file_stream.good()) { //if the file is not valid
usage(std::cerr, argv[0], "Your file is invalid!");
return 1;
}
if(atoi(argv[2]) == 0) { //if the num of meetings is either 0 or NaN
usage(std::cerr, argv[0], "You haven't specified a valid number of meetings! (> 0)");
return 1;
}
int num_meetings = atoi(argv[2]); //otherwise, set it to that number
//num to pool is how many attendance lists to count from
int num_to_pool = (argc >= 4) ? atoi(argv[3]) : num_meetings;
if(num_to_pool < num_meetings) { //if the number of meetings is unreachable
usage(std::cerr, argv[0], "Your number to pool from must be greater than the number of needed meetings!");
return 1;
}
STR_DOUBLE_VEC contents; //to store the soon-to-be-parsed data
STR_INT_MAP attendance_record; //to track attendance record
process_csv(file_stream, contents); //get the data processed
//figure out where to start in the file
int x = (contents.size()-num_to_pool <= 0) ? 0 : contents.size()-num_to_pool;
for(; x<contents.size(); x++) { //crawl the vector and count attendance
for(int y=0; y<contents[x].size(); y++) {
attendance_record[contents[x][y]]++;
}
}
output_data(std::cout, attendance_record, num_meetings); //output the results, giving
return 0;
}
//functions
void usage(std::ostream& out, std::string exe_name, std::string custom_error) {
out << std::endl;
if(custom_error != "") out << custom_error << std::endl;
out << "USAGE: " << exe_name << " <file name> <number of meetings> [meetings to pool]" << std::endl;
out << std::endl;
}
void process_csv(std::istream& in_str, STR_DOUBLE_VEC& contents) {
std::string line, cell;
while(std::getline(in_str, line)) {
std::stringstream line_stream(line);
std::vector<std::string> t;
while(std::getline(line_stream,cell,','))
t.push_back(cell);
contents.push_back(t);
}
}
void output_data(std::ostream& out, const STR_INT_MAP& attendance_record, int num_meetings) {
int count = 0; //counter of total valid voting membership
//print the results (only those who qualify to vote)
for(STR_INT_MAP::const_iterator itr = attendance_record.begin(); itr != attendance_record.end(); ++itr) {
if(itr->second >= num_meetings) {
//print the member and number of meetings attended in pool range
out << itr->first << " (" << itr->second << ")" << std::endl;
++count;
}
}
out << std::endl;
if(count <= 0){
out << "No members qualify to vote." << std::endl;
return;
}
int simple_majority = floor((float)count * (.50)) + 1;
int two_thirds_majority = ceil((float)count * (2.0/3.0));
out << "A total of " << count << " members qualify to vote." << std::endl;
out << std::setw(28) << std::left << "Simple majority (50% + 1)" << simple_majority << " / " << count << std::endl;
out << std::setw(28) << std::left << "Two-thirds majority (2/3)" << two_thirds_majority << " / " << count << std::endl;
}<|endoftext|>
|
<commit_before>// Copyright 2016 The SwiftShader Authors. All Rights Reserved.
//
// 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 "ExecutableMemory.hpp"
#include "Debug.hpp"
#if defined(_WIN32)
#ifndef WIN32_LEAN_AND_MEAN
#define WIN32_LEAN_AND_MEAN
#endif
#include <windows.h>
#include <intrin.h>
#elif defined(__Fuchsia__)
#include <unistd.h>
#include <zircon/process.h>
#include <zircon/syscalls.h>
#else
#include <errno.h>
#include <sys/mman.h>
#include <stdlib.h>
#include <unistd.h>
#endif
#include <memory.h>
#undef allocate
#undef deallocate
#if (defined(__i386__) || defined(_M_IX86) || defined(__x86_64__) || defined (_M_X64)) && !defined(__x86__)
#define __x86__
#endif
namespace rr
{
namespace
{
struct Allocation
{
// size_t bytes;
unsigned char *block;
};
void *allocateRaw(size_t bytes, size_t alignment)
{
ASSERT((alignment & (alignment - 1)) == 0); // Power of 2 alignment.
#if defined(LINUX_ENABLE_NAMED_MMAP)
void *allocation;
int result = posix_memalign(&allocation, alignment, bytes);
if(result != 0)
{
errno = result;
allocation = nullptr;
}
return allocation;
#else
unsigned char *block = new unsigned char[bytes + sizeof(Allocation) + alignment];
unsigned char *aligned = nullptr;
if(block)
{
aligned = (unsigned char*)((uintptr_t)(block + sizeof(Allocation) + alignment - 1) & -(intptr_t)alignment);
Allocation *allocation = (Allocation*)(aligned - sizeof(Allocation));
// allocation->bytes = bytes;
allocation->block = block;
}
return aligned;
#endif
}
#if defined(LINUX_ENABLE_NAMED_MMAP)
// Create a file descriptor for anonymous memory with the given
// name. Returns -1 on failure.
// TODO: remove once libc wrapper exists.
int memfd_create(const char* name, unsigned int flags)
{
#if __aarch64__
#define __NR_memfd_create 279
#elif __arm__
#define __NR_memfd_create 279
#elif __powerpc64__
#define __NR_memfd_create 360
#elif __i386__
#define __NR_memfd_create 356
#elif __x86_64__
#define __NR_memfd_create 319
#endif /* __NR_memfd_create__ */
#ifdef __NR_memfd_create
// In the event of no system call this returns -1 with errno set
// as ENOSYS.
return syscall(__NR_memfd_create, name, flags);
#else
return -1;
#endif
}
// Returns a file descriptor for use with an anonymous mmap, if
// memfd_create fails, -1 is returned. Note, the mappings should be
// MAP_PRIVATE so that underlying pages aren't shared.
int anonymousFd()
{
static int fd = memfd_create("SwiftShader JIT", 0);
return fd;
}
// Ensure there is enough space in the "anonymous" fd for length.
void ensureAnonFileSize(int anonFd, size_t length)
{
static size_t fileSize = 0;
if(length > fileSize)
{
ftruncate(anonFd, length);
fileSize = length;
}
}
#endif // defined(LINUX_ENABLE_NAMED_MMAP)
} // anonymous namespace
size_t memoryPageSize()
{
static int pageSize = 0;
if(pageSize == 0)
{
#if defined(_WIN32)
SYSTEM_INFO systemInfo;
GetSystemInfo(&systemInfo);
pageSize = systemInfo.dwPageSize;
#else
pageSize = sysconf(_SC_PAGESIZE);
#endif
}
return pageSize;
}
void *allocate(size_t bytes, size_t alignment)
{
void *memory = allocateRaw(bytes, alignment);
if(memory)
{
memset(memory, 0, bytes);
}
return memory;
}
void deallocate(void *memory)
{
#if defined(LINUX_ENABLE_NAMED_MMAP)
free(memory);
#else
if(memory)
{
unsigned char *aligned = (unsigned char*)memory;
Allocation *allocation = (Allocation*)(aligned - sizeof(Allocation));
delete[] allocation->block;
}
#endif
}
// Rounds |x| up to a multiple of |m|, where |m| is a power of 2.
inline uintptr_t roundUp(uintptr_t x, uintptr_t m)
{
ASSERT(m > 0 && (m & (m - 1)) == 0); // |m| must be a power of 2.
return (x + m - 1) & ~(m - 1);
}
void *allocateExecutable(size_t bytes)
{
size_t pageSize = memoryPageSize();
size_t length = roundUp(bytes, pageSize);
void *mapping;
#if defined(LINUX_ENABLE_NAMED_MMAP)
// Try to name the memory region for the executable code,
// to aid profilers.
int anonFd = anonymousFd();
if(anonFd == -1)
{
mapping = mmap(nullptr, length, PROT_READ | PROT_WRITE,
MAP_PRIVATE | MAP_ANONYMOUS, -1, 0);
}
else
{
ensureAnonFileSize(anonFd, length);
mapping = mmap(nullptr, length, PROT_READ | PROT_WRITE,
MAP_PRIVATE, anonFd, 0);
}
if(mapping == MAP_FAILED)
{
mapping = nullptr;
}
#elif defined(__Fuchsia__)
zx_handle_t vmo;
if (zx_vmo_create(length, ZX_VMO_NON_RESIZABLE, &vmo) != ZX_OK) {
return nullptr;
}
zx_vaddr_t reservation;
zx_status_t status = zx_vmar_map(
zx_vmar_root_self(), ZX_VM_FLAG_PERM_READ | ZX_VM_FLAG_PERM_WRITE,
0, vmo, 0, length, &reservation);
zx_handle_close(vmo);
if (status != ZX_OK) {
return nullptr;
}
zx_vaddr_t alignedReservation = roundUp(reservation, pageSize);
mapping = reinterpret_cast<void*>(alignedReservation);
// Unmap extra memory reserved before the block.
if (alignedReservation != reservation) {
size_t prefix_size = alignedReservation - reservation;
status =
zx_vmar_unmap(zx_vmar_root_self(), reservation, prefix_size);
ASSERT(status == ZX_OK);
length -= prefix_size;
}
// Unmap extra memory at the end.
if (length > bytes) {
status = zx_vmar_unmap(
zx_vmar_root_self(), alignedReservation + bytes,
length - bytes);
ASSERT(status == ZX_OK);
}
#else
mapping = allocate(length, pageSize);
#endif
return mapping;
}
void markExecutable(void *memory, size_t bytes)
{
#if defined(_WIN32)
unsigned long oldProtection;
VirtualProtect(memory, bytes, PAGE_EXECUTE_READ, &oldProtection);
#elif defined(__Fuchsia__)
zx_status_t status = zx_vmar_protect(
zx_vmar_root_self(), ZX_VM_FLAG_PERM_READ | ZX_VM_FLAG_PERM_EXECUTE,
reinterpret_cast<zx_vaddr_t>(memory), bytes);
ASSERT(status != ZX_OK);
#else
mprotect(memory, bytes, PROT_READ | PROT_EXEC);
#endif
}
void deallocateExecutable(void *memory, size_t bytes)
{
#if defined(_WIN32)
unsigned long oldProtection;
VirtualProtect(memory, bytes, PAGE_READWRITE, &oldProtection);
deallocate(memory);
#elif defined(LINUX_ENABLE_NAMED_MMAP)
size_t pageSize = memoryPageSize();
size_t length = (bytes + pageSize - 1) & ~(pageSize - 1);
munmap(memory, length);
#elif defined(__Fuchsia__)
zx_vmar_unmap(zx_vmar_root_self(), reinterpret_cast<zx_vaddr_t>(memory),
bytes);
#else
mprotect(memory, bytes, PROT_READ | PROT_WRITE);
deallocate(memory);
#endif
}
}
<commit_msg>[Fuchsia] Use the read/write permission flag names when mapping VMOs.<commit_after>// Copyright 2016 The SwiftShader Authors. All Rights Reserved.
//
// 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 "ExecutableMemory.hpp"
#include "Debug.hpp"
#if defined(_WIN32)
#ifndef WIN32_LEAN_AND_MEAN
#define WIN32_LEAN_AND_MEAN
#endif
#include <windows.h>
#include <intrin.h>
#elif defined(__Fuchsia__)
#include <unistd.h>
#include <zircon/process.h>
#include <zircon/syscalls.h>
#else
#include <errno.h>
#include <sys/mman.h>
#include <stdlib.h>
#include <unistd.h>
#endif
#include <memory.h>
#undef allocate
#undef deallocate
#if (defined(__i386__) || defined(_M_IX86) || defined(__x86_64__) || defined (_M_X64)) && !defined(__x86__)
#define __x86__
#endif
namespace rr
{
namespace
{
struct Allocation
{
// size_t bytes;
unsigned char *block;
};
void *allocateRaw(size_t bytes, size_t alignment)
{
ASSERT((alignment & (alignment - 1)) == 0); // Power of 2 alignment.
#if defined(LINUX_ENABLE_NAMED_MMAP)
void *allocation;
int result = posix_memalign(&allocation, alignment, bytes);
if(result != 0)
{
errno = result;
allocation = nullptr;
}
return allocation;
#else
unsigned char *block = new unsigned char[bytes + sizeof(Allocation) + alignment];
unsigned char *aligned = nullptr;
if(block)
{
aligned = (unsigned char*)((uintptr_t)(block + sizeof(Allocation) + alignment - 1) & -(intptr_t)alignment);
Allocation *allocation = (Allocation*)(aligned - sizeof(Allocation));
// allocation->bytes = bytes;
allocation->block = block;
}
return aligned;
#endif
}
#if defined(LINUX_ENABLE_NAMED_MMAP)
// Create a file descriptor for anonymous memory with the given
// name. Returns -1 on failure.
// TODO: remove once libc wrapper exists.
int memfd_create(const char* name, unsigned int flags)
{
#if __aarch64__
#define __NR_memfd_create 279
#elif __arm__
#define __NR_memfd_create 279
#elif __powerpc64__
#define __NR_memfd_create 360
#elif __i386__
#define __NR_memfd_create 356
#elif __x86_64__
#define __NR_memfd_create 319
#endif /* __NR_memfd_create__ */
#ifdef __NR_memfd_create
// In the event of no system call this returns -1 with errno set
// as ENOSYS.
return syscall(__NR_memfd_create, name, flags);
#else
return -1;
#endif
}
// Returns a file descriptor for use with an anonymous mmap, if
// memfd_create fails, -1 is returned. Note, the mappings should be
// MAP_PRIVATE so that underlying pages aren't shared.
int anonymousFd()
{
static int fd = memfd_create("SwiftShader JIT", 0);
return fd;
}
// Ensure there is enough space in the "anonymous" fd for length.
void ensureAnonFileSize(int anonFd, size_t length)
{
static size_t fileSize = 0;
if(length > fileSize)
{
ftruncate(anonFd, length);
fileSize = length;
}
}
#endif // defined(LINUX_ENABLE_NAMED_MMAP)
} // anonymous namespace
size_t memoryPageSize()
{
static int pageSize = 0;
if(pageSize == 0)
{
#if defined(_WIN32)
SYSTEM_INFO systemInfo;
GetSystemInfo(&systemInfo);
pageSize = systemInfo.dwPageSize;
#else
pageSize = sysconf(_SC_PAGESIZE);
#endif
}
return pageSize;
}
void *allocate(size_t bytes, size_t alignment)
{
void *memory = allocateRaw(bytes, alignment);
if(memory)
{
memset(memory, 0, bytes);
}
return memory;
}
void deallocate(void *memory)
{
#if defined(LINUX_ENABLE_NAMED_MMAP)
free(memory);
#else
if(memory)
{
unsigned char *aligned = (unsigned char*)memory;
Allocation *allocation = (Allocation*)(aligned - sizeof(Allocation));
delete[] allocation->block;
}
#endif
}
// Rounds |x| up to a multiple of |m|, where |m| is a power of 2.
inline uintptr_t roundUp(uintptr_t x, uintptr_t m)
{
ASSERT(m > 0 && (m & (m - 1)) == 0); // |m| must be a power of 2.
return (x + m - 1) & ~(m - 1);
}
void *allocateExecutable(size_t bytes)
{
size_t pageSize = memoryPageSize();
size_t length = roundUp(bytes, pageSize);
void *mapping;
#if defined(LINUX_ENABLE_NAMED_MMAP)
// Try to name the memory region for the executable code,
// to aid profilers.
int anonFd = anonymousFd();
if(anonFd == -1)
{
mapping = mmap(nullptr, length, PROT_READ | PROT_WRITE,
MAP_PRIVATE | MAP_ANONYMOUS, -1, 0);
}
else
{
ensureAnonFileSize(anonFd, length);
mapping = mmap(nullptr, length, PROT_READ | PROT_WRITE,
MAP_PRIVATE, anonFd, 0);
}
if(mapping == MAP_FAILED)
{
mapping = nullptr;
}
#elif defined(__Fuchsia__)
zx_handle_t vmo;
if (zx_vmo_create(length, ZX_VMO_NON_RESIZABLE, &vmo) != ZX_OK) {
return nullptr;
}
zx_vaddr_t reservation;
zx_status_t status = zx_vmar_map(
zx_vmar_root_self(), ZX_VM_PERM_READ | ZX_VM_PERM_WRITE,
0, vmo, 0, length, &reservation);
zx_handle_close(vmo);
if (status != ZX_OK) {
return nullptr;
}
zx_vaddr_t alignedReservation = roundUp(reservation, pageSize);
mapping = reinterpret_cast<void*>(alignedReservation);
// Unmap extra memory reserved before the block.
if (alignedReservation != reservation) {
size_t prefix_size = alignedReservation - reservation;
status =
zx_vmar_unmap(zx_vmar_root_self(), reservation, prefix_size);
ASSERT(status == ZX_OK);
length -= prefix_size;
}
// Unmap extra memory at the end.
if (length > bytes) {
status = zx_vmar_unmap(
zx_vmar_root_self(), alignedReservation + bytes,
length - bytes);
ASSERT(status == ZX_OK);
}
#else
mapping = allocate(length, pageSize);
#endif
return mapping;
}
void markExecutable(void *memory, size_t bytes)
{
#if defined(_WIN32)
unsigned long oldProtection;
VirtualProtect(memory, bytes, PAGE_EXECUTE_READ, &oldProtection);
#elif defined(__Fuchsia__)
zx_status_t status = zx_vmar_protect(
zx_vmar_root_self(), ZX_VM_PERM_READ | ZX_VM_PERM_EXECUTE,
reinterpret_cast<zx_vaddr_t>(memory), bytes);
ASSERT(status != ZX_OK);
#else
mprotect(memory, bytes, PROT_READ | PROT_EXEC);
#endif
}
void deallocateExecutable(void *memory, size_t bytes)
{
#if defined(_WIN32)
unsigned long oldProtection;
VirtualProtect(memory, bytes, PAGE_READWRITE, &oldProtection);
deallocate(memory);
#elif defined(LINUX_ENABLE_NAMED_MMAP)
size_t pageSize = memoryPageSize();
size_t length = (bytes + pageSize - 1) & ~(pageSize - 1);
munmap(memory, length);
#elif defined(__Fuchsia__)
zx_vmar_unmap(zx_vmar_root_self(), reinterpret_cast<zx_vaddr_t>(memory),
bytes);
#else
mprotect(memory, bytes, PROT_READ | PROT_WRITE);
deallocate(memory);
#endif
}
}
<|endoftext|>
|
<commit_before>/*!
* \odom_covariance_converter.cpp
* \brief Adds covariance matrix to odometry message
*
* odom_covariance_converter adds a covariance matrix to odometry messages so they are compatible with robot_pose_efk.
*
* \author Steven Kordell, WPI - [email protected]
* \date June 16, 2014
*/
#include <nav_msgs/Odometry.h>
#include <ros/ros.h>
#include <carl_nav/odom_covariance_converter.h>
#include <boost/assign/list_of.hpp>
using namespace std;
odom_covariance_converter::odom_covariance_converter()
{
// create the ROS topics
odom_in = node.subscribe<nav_msgs::Odometry>("odom", 10, &odom_covariance_converter::convert_cback, this);
odom_out = node.advertise<nav_msgs::Odometry>("covariance_odom", 10);
ROS_INFO("Odometry covariance Converter Started");
}
void odom_covariance_converter::convert_cback(const nav_msgs::Odometry::ConstPtr& odom)
{
nav_msgs::Odometry odometry = *odom;
odometry.pose.covariance = boost::assign::list_of(1e-3) (0) (0) (0) (0) (0)
(0) (1e-3) (0) (0) (0) (0)
(0) (0) (1e6) (0) (0) (0)
(0) (0) (0) (1e6) (0) (0)
(0) (0) (0) (0) (1e6) (0)
(0) (0) (0) (0) (0) (1e3);
odometry.twist.covariance = boost::assign::list_of(1e-3) (0) (0) (0) (0) (0)
(0) (1e-3) (0) (0) (0) (0)
(0) (0) (1e6) (0) (0) (0)
(0) (0) (0) (1e6) (0) (0)
(0) (0) (0) (0) (1e6) (0)
(0) (0) (0) (0) (0) (1e3);
odom_out.publish(odom);
}
int main(int argc, char **argv)
{
// initialize ROS and the node
ros::init(argc, argv, "odom_covariance_converter");
// initialize the converter
odom_covariance_converter converter;
ros::spin();
return EXIT_SUCCESS;
}
<commit_msg>Added topic parameters<commit_after>/*!
* \odom_covariance_converter.cpp
* \brief Adds covariance matrix to odometry message
*
* odom_covariance_converter adds a covariance matrix to odometry messages so they are compatible with robot_pose_efk.
*
* \author Steven Kordell, WPI - [email protected]
* \date June 16, 2014
*/
#include <nav_msgs/Odometry.h>
#include <ros/ros.h>
#include <carl_nav/odom_covariance_converter.h>
#include <boost/assign/list_of.hpp>
using namespace std;
odom_covariance_converter::odom_covariance_converter()
{
// create the ROS topics
string odom_in_topic;
string odom_out_topic;
node.param("in_topic", odom_in_topic, odom_in_topic);
node.param("out_topic", odom_out_topic, odom_out_topic);
odom_in = node.subscribe<nav_msgs::Odometry>(odom_in_topic, 10, &odom_covariance_converter::convert_cback, this);
odom_out = node.advertise<nav_msgs::Odometry>(odom_out_topic, 10);
ROS_INFO("Odometry covariance Converter Started");
}
void odom_covariance_converter::convert_cback(const nav_msgs::Odometry::ConstPtr& odom)
{
nav_msgs::Odometry odometry = *odom;
odometry.pose.covariance = boost::assign::list_of(1e-3) (0) (0) (0) (0) (0)
(0) (1e-3) (0) (0) (0) (0)
(0) (0) (1e6) (0) (0) (0)
(0) (0) (0) (1e6) (0) (0)
(0) (0) (0) (0) (1e6) (0)
(0) (0) (0) (0) (0) (1e3);
odometry.twist.covariance = boost::assign::list_of(1e-3) (0) (0) (0) (0) (0)
(0) (1e-3) (0) (0) (0) (0)
(0) (0) (1e6) (0) (0) (0)
(0) (0) (0) (1e6) (0) (0)
(0) (0) (0) (0) (1e6) (0)
(0) (0) (0) (0) (0) (1e3);
odom_out.publish(odom);
}
int main(int argc, char **argv)
{
// initialize ROS and the node
ros::init(argc, argv, "odom_covariance_converter");
// initialize the converter
odom_covariance_converter converter;
ros::spin();
return EXIT_SUCCESS;
}
<|endoftext|>
|
<commit_before>// Barst.cpp : Defines the entry point for the console application.
//
#include "stdafx.h"
#include "cpl defs.h"
#include "named pipes.h"
#include "Log buffer.h"
#include "mem pool.h"
#include "ftdi device.h"
#include "rtv device.h"
#include "serial device.h"
CMainManager::CMainManager() : CDevice(_T("Main"))
{
m_pcComm= NULL;
m_pcMemPool= new CMemPool; // main program buffer pool
m_hClose= CreateEvent(NULL, TRUE, FALSE, NULL);
m_bError= false;
if (!m_hClose)
m_bError= true;
}
// when shutting down, first the pipe is disconnected.
CMainManager::~CMainManager()
{
if (m_pcComm)
m_pcComm->Close();
for (size_t i= 0; i<m_acManagers.size(); ++i)
delete m_acManagers[i];
CloseHandle(m_hClose);
delete m_pcComm;
delete m_pcMemPool;
}
// only one thread ever calls this since there's only thread in this communicator
void CMainManager::ProcessData(const void *pHead, DWORD dwSize, __int64 llId)
{
if (m_bError)
return;
SData sData;
sData.pDevice= this;
sData.dwSize= sizeof(SBaseIn);
SBaseIn sBase;
memset(&sBase, 0, sizeof(SBaseIn));
sBase.dwSize= sizeof(SBaseIn);
sBase.nChan= -1;
bool bRes= true;
if (!pHead || dwSize < sizeof(SBaseIn) || dwSize != ((SBaseIn*)pHead)->dwSize) // incorrect size read
{
sBase.nError= SIZE_MISSMATCH;
} else if (((SBaseIn*)pHead)->eType == eVersion && ((SBaseIn*)pHead)->dwSize == sizeof(SBaseIn) &&
((SBaseIn*)pHead)->nChan == -1) // send lib version
{
sBase.dwInfo= BARST_VERSION;
sBase.eType= eVersion;
} else if (((SBaseIn*)pHead)->eType == eDelete && ((SBaseIn*)pHead)->dwSize == sizeof(SBaseIn)) // close manager
{
if (((SBaseIn*)pHead)->nChan == -1) // close main program
SetEvent(m_hClose);
else if (((SBaseIn*)pHead)->nChan >= 0 && ((SBaseIn*)pHead)->nChan < m_acManagers.size() &&
m_acManagers[((SBaseIn*)pHead)->nChan]) // close other manager
{
delete m_acManagers[((SBaseIn*)pHead)->nChan];
m_acManagers[((SBaseIn*)pHead)->nChan]= NULL;
}
else
sBase.nError= INVALID_CHANN;
sBase.nChan= ((SBaseIn*)pHead)->nChan;
sBase.eType= eDelete;
} else if (((SBaseIn*)pHead)->eType == eSet && ((SBaseIn*)pHead)->dwSize == sizeof(SBaseIn)) // add a manager
{
// prepare array element for manager
size_t t= 0;
for (; t < m_acManagers.size() && m_acManagers[t]; ++t);
if (t == m_acManagers.size())
m_acManagers.push_back(NULL);
sBase.eType= eSet;
switch (((SBaseIn*)pHead)->eType2) // the device to open
{
case eFTDIMan:
{
int nPos= -1;
for (size_t i= 0; i < m_acManagers.size() && nPos == -1; ++i) // make sure it isn't open already
if (m_acManagers[i] && _tcscmp(FTDI_MAN_STR, m_acManagers[i]->m_csName.c_str()) == 0)
nPos= i;
if (nPos != -1) // found
{
sBase.nError= ALREADY_OPEN;
sBase.nChan= nPos;
break;
}
CManagerFTDI* pMan= new CManagerFTDI(m_pcComm, m_csPipe.c_str(), t, sBase.nError);
if (!sBase.nError)
{
sBase.nChan= t;
m_acManagers[t]= pMan;
} else
delete pMan;
break;
}
case eRTVMan:
{
int nPos= -1;
for (size_t i= 0; i < m_acManagers.size() && nPos == -1; ++i) // make sure it isn't open already
if (m_acManagers[i] && _tcscmp(RTV_MAN_STR, m_acManagers[i]->m_csName.c_str()) == 0)
nPos= i;
if (nPos != -1) // found
{
sBase.nError= ALREADY_OPEN;
sBase.nChan= nPos;
break;
}
CManagerRTV* pMan= new CManagerRTV(m_pcComm, m_csPipe.c_str(), t, sBase.nError);
if (!sBase.nError)
{
sBase.nChan= t;
m_acManagers[t]= pMan;
} else
delete pMan;
break;
}
case eSerialMan:
{
int nPos= -1;
for (size_t i= 0; i < m_acManagers.size() && nPos == -1; ++i) // make sure it isn't open already
if (m_acManagers[i] && _tcscmp(SERIAL_MAN_STR, m_acManagers[i]->m_csName.c_str()) == 0)
nPos= i;
if (nPos != -1) // found
{
sBase.nError= ALREADY_OPEN;
sBase.nChan= nPos;
break;
}
CManagerSerial* pMan= new CManagerSerial(m_pcComm, m_csPipe.c_str(), t, sBase.nError);
if (!sBase.nError)
{
sBase.nChan= t;
m_acManagers[t]= pMan;
} else
delete pMan;
break;
}
default:
sBase.nError= INVALID_MAN;
break;
}
} else if (((SBaseIn*)pHead)->nChan < 0 || ((SBaseIn*)pHead)->nChan >= m_acManagers.size() ||
!m_acManagers[((SBaseIn*)pHead)->nChan]) // verify manager exists
{
sBase.nError= INVALID_CHANN;
sBase.eType= ((SBaseIn*)pHead)->eType;
} else if (((SBaseIn*)pHead)->eType == eQuery && ((SBaseIn*)pHead)->dwSize == sizeof(SBaseIn)) // send info on this manager
{
bRes= false;
DWORD dwResSize= m_acManagers[((SBaseIn*)pHead)->nChan]->GetInfo(NULL, 0); // size of response
sData.pHead= m_pcMemPool->PoolAcquire(dwResSize);
if (sData.pHead)
{
m_acManagers[((SBaseIn*)pHead)->nChan]->GetInfo(sData.pHead, dwResSize); // get response
sData.dwSize= dwResSize;
m_pcComm->SendData(&sData, llId);
}
} else if (((SBaseIn*)pHead)->eType == ePassOn) // pass following data to manager
{
bRes= false;
m_acManagers[((SBaseIn*)pHead)->nChan]->ProcessData((char*)pHead + sizeof(SBaseIn), dwSize-sizeof(SBaseIn), llId);
} else
sBase.nError= INVALID_COMMAND;
if (bRes) // respond
{
sData.pHead= m_pcMemPool->PoolAcquire(sData.dwSize);
if (sData.pHead)
{
memcpy(sData.pHead, &sBase, sizeof(SBaseIn));
m_pcComm->SendData(&sData, llId);
}
}
}
int CMainManager::Run(int argc, TCHAR* argv[])
{
if (argc != 4)
return BAD_INPUT_PARAMS;
DWORD dwBuffSizeIn, dwBuffSizeOut; // size of pipe buffers
std::tstringstream in(argv[2]), out(argv[3]);
in >> dwBuffSizeIn; // user writing to pipe size
out >> dwBuffSizeOut; // user reading from pipe
m_csPipe= argv[1]; // pipe name to use
if (in.fail() || out.fail() || _tcschr(argv[2], _T('-'))
|| _tcschr(argv[3], _T('-'))) // cannot be negative #
return BAD_INPUT_PARAMS;
// check if it exists already
HANDLE hPipe= CreateFile(argv[1], GENERIC_WRITE, 0, NULL, OPEN_EXISTING, 0, NULL);
if (hPipe != INVALID_HANDLE_VALUE || GetLastError() == ERROR_PIPE_BUSY)
return ALREADY_OPEN;
CloseHandle(hPipe);
m_pcComm= new CPipeServer(); // main program pipe
int nRes;
// only use one thread to ensure thread safety
if (nRes= static_cast<CPipeServer*>(m_pcComm)->Init(argv[1], 1, dwBuffSizeIn, dwBuffSizeOut, this, NULL))
return nRes;
if (WAIT_OBJECT_0 != WaitForSingleObject(m_hClose, INFINITE)) // wait here until closing
return WIN_ERROR(GetLastError(), nRes);
return 0;
}
int _tmain(int argc, _TCHAR* argv[])
{
ShowWindow(GetConsoleWindow(), SW_HIDE);
CMainManager* pMainManager= new CMainManager;
int nRes= pMainManager->Run(argc, argv); // program sits here until stopped
delete pMainManager;
return nRes;
}
// WM_COPYDATA http://www.cplusplus.com/forum/windows/23232/
// http://msdn.microsoft.com/en-us/library/windows/desktop/ms633573%28v=vs.85%29.aspx
// http://msdn.microsoft.com/en-us/library/windows/desktop/ms632593%28v=vs.85%29.aspx<commit_msg>Add new mcdaq manager.<commit_after>// Barst.cpp : Defines the entry point for the console application.
//
#include "stdafx.h"
#include "cpl defs.h"
#include "named pipes.h"
#include "Log buffer.h"
#include "mem pool.h"
#include "ftdi device.h"
#include "rtv device.h"
#include "serial device.h"
#include "mcdaq_device.h"
CMainManager::CMainManager() : CDevice(_T("Main"))
{
m_pcComm= NULL;
m_pcMemPool= new CMemPool; // main program buffer pool
m_hClose= CreateEvent(NULL, TRUE, FALSE, NULL);
m_bError= false;
if (!m_hClose)
m_bError= true;
}
// when shutting down, first the pipe is disconnected.
CMainManager::~CMainManager()
{
if (m_pcComm)
m_pcComm->Close();
for (size_t i= 0; i<m_acManagers.size(); ++i)
delete m_acManagers[i];
CloseHandle(m_hClose);
delete m_pcComm;
delete m_pcMemPool;
}
// only one thread ever calls this since there's only thread in this communicator
void CMainManager::ProcessData(const void *pHead, DWORD dwSize, __int64 llId)
{
if (m_bError)
return;
SData sData;
sData.pDevice= this;
sData.dwSize= sizeof(SBaseIn);
SBaseIn sBase;
memset(&sBase, 0, sizeof(SBaseIn));
sBase.dwSize= sizeof(SBaseIn);
sBase.nChan= -1;
bool bRes= true;
if (!pHead || dwSize < sizeof(SBaseIn) || dwSize != ((SBaseIn*)pHead)->dwSize) // incorrect size read
{
sBase.nError= SIZE_MISSMATCH;
} else if (((SBaseIn*)pHead)->eType == eVersion && ((SBaseIn*)pHead)->dwSize == sizeof(SBaseIn) &&
((SBaseIn*)pHead)->nChan == -1) // send lib version
{
sBase.dwInfo= BARST_VERSION;
sBase.eType= eVersion;
} else if (((SBaseIn*)pHead)->eType == eDelete && ((SBaseIn*)pHead)->dwSize == sizeof(SBaseIn)) // close manager
{
if (((SBaseIn*)pHead)->nChan == -1) // close main program
SetEvent(m_hClose);
else if (((SBaseIn*)pHead)->nChan >= 0 && ((SBaseIn*)pHead)->nChan < m_acManagers.size() &&
m_acManagers[((SBaseIn*)pHead)->nChan]) // close other manager
{
delete m_acManagers[((SBaseIn*)pHead)->nChan];
m_acManagers[((SBaseIn*)pHead)->nChan]= NULL;
}
else
sBase.nError= INVALID_CHANN;
sBase.nChan= ((SBaseIn*)pHead)->nChan;
sBase.eType= eDelete;
} else if (((SBaseIn*)pHead)->eType == eSet && ((SBaseIn*)pHead)->dwSize == sizeof(SBaseIn)) // add a manager
{
// prepare array element for manager
size_t t= 0;
for (; t < m_acManagers.size() && m_acManagers[t]; ++t);
if (t == m_acManagers.size())
m_acManagers.push_back(NULL);
sBase.eType= eSet;
switch (((SBaseIn*)pHead)->eType2) // the device to open
{
case eFTDIMan:
{
int nPos= -1;
for (size_t i= 0; i < m_acManagers.size() && nPos == -1; ++i) // make sure it isn't open already
if (m_acManagers[i] && _tcscmp(FTDI_MAN_STR, m_acManagers[i]->m_csName.c_str()) == 0)
nPos= (int)i;
if (nPos != -1) // found
{
sBase.nError= ALREADY_OPEN;
sBase.nChan= nPos;
break;
}
CManagerFTDI* pMan= new CManagerFTDI(m_pcComm, m_csPipe.c_str(), (int)t, sBase.nError);
if (!sBase.nError)
{
sBase.nChan= (int)t;
m_acManagers[t]= pMan;
} else
delete pMan;
break;
}
case eRTVMan:
{
int nPos= -1;
for (size_t i= 0; i < m_acManagers.size() && nPos == -1; ++i) // make sure it isn't open already
if (m_acManagers[i] && _tcscmp(RTV_MAN_STR, m_acManagers[i]->m_csName.c_str()) == 0)
nPos= (int)i;
if (nPos != -1) // found
{
sBase.nError= ALREADY_OPEN;
sBase.nChan= nPos;
break;
}
CManagerRTV* pMan= new CManagerRTV(m_pcComm, m_csPipe.c_str(), (int)t, sBase.nError);
if (!sBase.nError)
{
sBase.nChan= (int)t;
m_acManagers[t]= pMan;
} else
delete pMan;
break;
}
case eSerialMan:
{
int nPos= -1;
for (size_t i= 0; i < m_acManagers.size() && nPos == -1; ++i) // make sure it isn't open already
if (m_acManagers[i] && _tcscmp(SERIAL_MAN_STR, m_acManagers[i]->m_csName.c_str()) == 0)
nPos= (int)i;
if (nPos != -1) // found
{
sBase.nError= ALREADY_OPEN;
sBase.nChan= nPos;
break;
}
CManagerSerial* pMan= new CManagerSerial(m_pcComm, m_csPipe.c_str(), (int)t, sBase.nError);
if (!sBase.nError)
{
sBase.nChan= (int)t;
m_acManagers[t]= pMan;
} else
delete pMan;
break;
}
case eMCDAQMan:
{
int nPos= -1;
for (size_t i= 0; i < m_acManagers.size() && nPos == -1; ++i) // make sure it isn't open already
if (m_acManagers[i] && _tcscmp(MCDAQ_MAN_STR, m_acManagers[i]->m_csName.c_str()) == 0)
nPos= (int)i;
if (nPos != -1) // found
{
sBase.nError= ALREADY_OPEN;
sBase.nChan= nPos;
break;
}
CManagerMCDAQ* pMan= new CManagerMCDAQ(m_pcComm, m_csPipe.c_str(), (int)t, sBase.nError);
if (!sBase.nError)
{
sBase.nChan= (int)t;
m_acManagers[t]= pMan;
} else
delete pMan;
break;
}
default:
sBase.nError= INVALID_MAN;
break;
}
} else if (((SBaseIn*)pHead)->nChan < 0 || ((SBaseIn*)pHead)->nChan >= m_acManagers.size() ||
!m_acManagers[((SBaseIn*)pHead)->nChan]) // verify manager exists
{
sBase.nError= INVALID_CHANN;
sBase.eType= ((SBaseIn*)pHead)->eType;
} else if (((SBaseIn*)pHead)->eType == eQuery && ((SBaseIn*)pHead)->dwSize == sizeof(SBaseIn)) // send info on this manager
{
bRes= false;
DWORD dwResSize= m_acManagers[((SBaseIn*)pHead)->nChan]->GetInfo(NULL, 0); // size of response
sData.pHead= m_pcMemPool->PoolAcquire(dwResSize);
if (sData.pHead)
{
m_acManagers[((SBaseIn*)pHead)->nChan]->GetInfo(sData.pHead, dwResSize); // get response
sData.dwSize= dwResSize;
m_pcComm->SendData(&sData, llId);
}
} else if (((SBaseIn*)pHead)->eType == ePassOn) // pass following data to manager
{
bRes= false;
m_acManagers[((SBaseIn*)pHead)->nChan]->ProcessData((char*)pHead + sizeof(SBaseIn), dwSize-sizeof(SBaseIn), llId);
} else
sBase.nError= INVALID_COMMAND;
if (bRes) // respond
{
sData.pHead= m_pcMemPool->PoolAcquire(sData.dwSize);
if (sData.pHead)
{
memcpy(sData.pHead, &sBase, sizeof(SBaseIn));
m_pcComm->SendData(&sData, llId);
}
}
}
int CMainManager::Run(int argc, TCHAR* argv[])
{
if (argc != 4)
return BAD_INPUT_PARAMS;
DWORD dwBuffSizeIn, dwBuffSizeOut; // size of pipe buffers
std::tstringstream in(argv[2]), out(argv[3]);
in >> dwBuffSizeIn; // user writing to pipe size
out >> dwBuffSizeOut; // user reading from pipe
m_csPipe= argv[1]; // pipe name to use
if (in.fail() || out.fail() || _tcschr(argv[2], _T('-'))
|| _tcschr(argv[3], _T('-'))) // cannot be negative #
return BAD_INPUT_PARAMS;
// check if it exists already
HANDLE hPipe= CreateFile(argv[1], GENERIC_WRITE, 0, NULL, OPEN_EXISTING, 0, NULL);
if (hPipe != INVALID_HANDLE_VALUE || GetLastError() == ERROR_PIPE_BUSY)
return ALREADY_OPEN;
CloseHandle(hPipe);
m_pcComm= new CPipeServer(); // main program pipe
int nRes;
// only use one thread to ensure thread safety
if (nRes= static_cast<CPipeServer*>(m_pcComm)->Init(argv[1], 1, dwBuffSizeIn, dwBuffSizeOut, this, NULL))
return nRes;
if (WAIT_OBJECT_0 != WaitForSingleObject(m_hClose, INFINITE)) // wait here until closing
return WIN_ERROR(GetLastError(), nRes);
return 0;
}
int _tmain(int argc, _TCHAR* argv[])
{
ShowWindow(GetConsoleWindow(), SW_HIDE);
CMainManager* pMainManager= new CMainManager;
int nRes= pMainManager->Run(argc, argv); // program sits here until stopped
delete pMainManager;
return nRes;
}
// WM_COPYDATA http://www.cplusplus.com/forum/windows/23232/
// http://msdn.microsoft.com/en-us/library/windows/desktop/ms633573%28v=vs.85%29.aspx
// http://msdn.microsoft.com/en-us/library/windows/desktop/ms632593%28v=vs.85%29.aspx
<|endoftext|>
|
<commit_before>//===- ExecutionEngineTest.cpp - Unit tests for ExecutionEngine -----------===//
//
// The LLVM Compiler Infrastructure
//
// This file is distributed under the University of Illinois Open Source
// License. See LICENSE.TXT for details.
//
//===----------------------------------------------------------------------===//
#include "llvm/DerivedTypes.h"
#include "llvm/GlobalVariable.h"
#include "llvm/LLVMContext.h"
#include "llvm/Module.h"
#include "llvm/ADT/OwningPtr.h"
#include "llvm/ExecutionEngine/Interpreter.h"
#include "gtest/gtest.h"
using namespace llvm;
namespace {
class ExecutionEngineTest : public testing::Test {
protected:
ExecutionEngineTest()
: M(new Module("<main>", getGlobalContext())),
Engine(EngineBuilder(M).create()) {
}
virtual void SetUp() {
ASSERT_TRUE(Engine.get() != NULL);
}
GlobalVariable *NewExtGlobal(Type *T, const Twine &Name) {
return new GlobalVariable(*M, T, false, // Not constant.
GlobalValue::ExternalLinkage, NULL, Name);
}
Module *const M;
const OwningPtr<ExecutionEngine> Engine;
};
TEST_F(ExecutionEngineTest, ForwardGlobalMapping) {
GlobalVariable *G1 =
NewExtGlobal(Type::getInt32Ty(getGlobalContext()), "Global1");
int32_t Mem1 = 3;
Engine->addGlobalMapping(G1, &Mem1);
EXPECT_EQ(&Mem1, Engine->getPointerToGlobalIfAvailable(G1));
int32_t Mem2 = 4;
Engine->updateGlobalMapping(G1, &Mem2);
EXPECT_EQ(&Mem2, Engine->getPointerToGlobalIfAvailable(G1));
Engine->updateGlobalMapping(G1, NULL);
EXPECT_EQ(NULL, Engine->getPointerToGlobalIfAvailable(G1));
Engine->updateGlobalMapping(G1, &Mem2);
EXPECT_EQ(&Mem2, Engine->getPointerToGlobalIfAvailable(G1));
GlobalVariable *G2 =
NewExtGlobal(Type::getInt32Ty(getGlobalContext()), "Global1");
EXPECT_EQ(NULL, Engine->getPointerToGlobalIfAvailable(G2))
<< "The NULL return shouldn't depend on having called"
<< " updateGlobalMapping(..., NULL)";
// Check that update...() can be called before add...().
Engine->updateGlobalMapping(G2, &Mem1);
EXPECT_EQ(&Mem1, Engine->getPointerToGlobalIfAvailable(G2));
EXPECT_EQ(&Mem2, Engine->getPointerToGlobalIfAvailable(G1))
<< "A second mapping shouldn't affect the first.";
}
TEST_F(ExecutionEngineTest, ReverseGlobalMapping) {
GlobalVariable *G1 =
NewExtGlobal(Type::getInt32Ty(getGlobalContext()), "Global1");
int32_t Mem1 = 3;
Engine->addGlobalMapping(G1, &Mem1);
EXPECT_EQ(G1, Engine->getGlobalValueAtAddress(&Mem1));
int32_t Mem2 = 4;
Engine->updateGlobalMapping(G1, &Mem2);
EXPECT_EQ(NULL, Engine->getGlobalValueAtAddress(&Mem1));
EXPECT_EQ(G1, Engine->getGlobalValueAtAddress(&Mem2));
GlobalVariable *G2 =
NewExtGlobal(Type::getInt32Ty(getGlobalContext()), "Global2");
Engine->updateGlobalMapping(G2, &Mem1);
EXPECT_EQ(G2, Engine->getGlobalValueAtAddress(&Mem1));
EXPECT_EQ(G1, Engine->getGlobalValueAtAddress(&Mem2));
Engine->updateGlobalMapping(G1, NULL);
EXPECT_EQ(G2, Engine->getGlobalValueAtAddress(&Mem1))
<< "Removing one mapping doesn't affect a different one.";
EXPECT_EQ(NULL, Engine->getGlobalValueAtAddress(&Mem2));
Engine->updateGlobalMapping(G2, &Mem2);
EXPECT_EQ(NULL, Engine->getGlobalValueAtAddress(&Mem1));
EXPECT_EQ(G2, Engine->getGlobalValueAtAddress(&Mem2))
<< "Once a mapping is removed, we can point another GV at the"
<< " now-free address.";
}
TEST_F(ExecutionEngineTest, ClearModuleMappings) {
GlobalVariable *G1 =
NewExtGlobal(Type::getInt32Ty(getGlobalContext()), "Global1");
int32_t Mem1 = 3;
Engine->addGlobalMapping(G1, &Mem1);
EXPECT_EQ(G1, Engine->getGlobalValueAtAddress(&Mem1));
Engine->clearGlobalMappingsFromModule(M);
EXPECT_EQ(NULL, Engine->getGlobalValueAtAddress(&Mem1));
GlobalVariable *G2 =
NewExtGlobal(Type::getInt32Ty(getGlobalContext()), "Global2");
// After clearing the module mappings, we can assign a new GV to the
// same address.
Engine->addGlobalMapping(G2, &Mem1);
EXPECT_EQ(G2, Engine->getGlobalValueAtAddress(&Mem1));
}
TEST_F(ExecutionEngineTest, DestructionRemovesGlobalMapping) {
GlobalVariable *G1 =
NewExtGlobal(Type::getInt32Ty(getGlobalContext()), "Global1");
int32_t Mem1 = 3;
Engine->addGlobalMapping(G1, &Mem1);
// Make sure the reverse mapping is enabled.
EXPECT_EQ(G1, Engine->getGlobalValueAtAddress(&Mem1));
// When the GV goes away, the ExecutionEngine should remove any
// mappings that refer to it.
G1->eraseFromParent();
EXPECT_EQ(NULL, Engine->getGlobalValueAtAddress(&Mem1));
}
}
<commit_msg>unittests: add ErrorStr to ExecutionEngine test<commit_after>//===- ExecutionEngineTest.cpp - Unit tests for ExecutionEngine -----------===//
//
// The LLVM Compiler Infrastructure
//
// This file is distributed under the University of Illinois Open Source
// License. See LICENSE.TXT for details.
//
//===----------------------------------------------------------------------===//
#include "llvm/DerivedTypes.h"
#include "llvm/GlobalVariable.h"
#include "llvm/LLVMContext.h"
#include "llvm/Module.h"
#include "llvm/ADT/OwningPtr.h"
#include "llvm/ExecutionEngine/Interpreter.h"
#include "gtest/gtest.h"
using namespace llvm;
namespace {
class ExecutionEngineTest : public testing::Test {
protected:
ExecutionEngineTest()
: M(new Module("<main>", getGlobalContext())), Error(""),
Engine(EngineBuilder(M).setErrorStr(&Error).create()) {
}
virtual void SetUp() {
ASSERT_TRUE(Engine.get() != NULL) << "EngineBuilder returned error: '"
<< Error << "'";
}
GlobalVariable *NewExtGlobal(Type *T, const Twine &Name) {
return new GlobalVariable(*M, T, false, // Not constant.
GlobalValue::ExternalLinkage, NULL, Name);
}
Module *const M;
std::string Error;
const OwningPtr<ExecutionEngine> Engine;
};
TEST_F(ExecutionEngineTest, ForwardGlobalMapping) {
GlobalVariable *G1 =
NewExtGlobal(Type::getInt32Ty(getGlobalContext()), "Global1");
int32_t Mem1 = 3;
Engine->addGlobalMapping(G1, &Mem1);
EXPECT_EQ(&Mem1, Engine->getPointerToGlobalIfAvailable(G1));
int32_t Mem2 = 4;
Engine->updateGlobalMapping(G1, &Mem2);
EXPECT_EQ(&Mem2, Engine->getPointerToGlobalIfAvailable(G1));
Engine->updateGlobalMapping(G1, NULL);
EXPECT_EQ(NULL, Engine->getPointerToGlobalIfAvailable(G1));
Engine->updateGlobalMapping(G1, &Mem2);
EXPECT_EQ(&Mem2, Engine->getPointerToGlobalIfAvailable(G1));
GlobalVariable *G2 =
NewExtGlobal(Type::getInt32Ty(getGlobalContext()), "Global1");
EXPECT_EQ(NULL, Engine->getPointerToGlobalIfAvailable(G2))
<< "The NULL return shouldn't depend on having called"
<< " updateGlobalMapping(..., NULL)";
// Check that update...() can be called before add...().
Engine->updateGlobalMapping(G2, &Mem1);
EXPECT_EQ(&Mem1, Engine->getPointerToGlobalIfAvailable(G2));
EXPECT_EQ(&Mem2, Engine->getPointerToGlobalIfAvailable(G1))
<< "A second mapping shouldn't affect the first.";
}
TEST_F(ExecutionEngineTest, ReverseGlobalMapping) {
GlobalVariable *G1 =
NewExtGlobal(Type::getInt32Ty(getGlobalContext()), "Global1");
int32_t Mem1 = 3;
Engine->addGlobalMapping(G1, &Mem1);
EXPECT_EQ(G1, Engine->getGlobalValueAtAddress(&Mem1));
int32_t Mem2 = 4;
Engine->updateGlobalMapping(G1, &Mem2);
EXPECT_EQ(NULL, Engine->getGlobalValueAtAddress(&Mem1));
EXPECT_EQ(G1, Engine->getGlobalValueAtAddress(&Mem2));
GlobalVariable *G2 =
NewExtGlobal(Type::getInt32Ty(getGlobalContext()), "Global2");
Engine->updateGlobalMapping(G2, &Mem1);
EXPECT_EQ(G2, Engine->getGlobalValueAtAddress(&Mem1));
EXPECT_EQ(G1, Engine->getGlobalValueAtAddress(&Mem2));
Engine->updateGlobalMapping(G1, NULL);
EXPECT_EQ(G2, Engine->getGlobalValueAtAddress(&Mem1))
<< "Removing one mapping doesn't affect a different one.";
EXPECT_EQ(NULL, Engine->getGlobalValueAtAddress(&Mem2));
Engine->updateGlobalMapping(G2, &Mem2);
EXPECT_EQ(NULL, Engine->getGlobalValueAtAddress(&Mem1));
EXPECT_EQ(G2, Engine->getGlobalValueAtAddress(&Mem2))
<< "Once a mapping is removed, we can point another GV at the"
<< " now-free address.";
}
TEST_F(ExecutionEngineTest, ClearModuleMappings) {
GlobalVariable *G1 =
NewExtGlobal(Type::getInt32Ty(getGlobalContext()), "Global1");
int32_t Mem1 = 3;
Engine->addGlobalMapping(G1, &Mem1);
EXPECT_EQ(G1, Engine->getGlobalValueAtAddress(&Mem1));
Engine->clearGlobalMappingsFromModule(M);
EXPECT_EQ(NULL, Engine->getGlobalValueAtAddress(&Mem1));
GlobalVariable *G2 =
NewExtGlobal(Type::getInt32Ty(getGlobalContext()), "Global2");
// After clearing the module mappings, we can assign a new GV to the
// same address.
Engine->addGlobalMapping(G2, &Mem1);
EXPECT_EQ(G2, Engine->getGlobalValueAtAddress(&Mem1));
}
TEST_F(ExecutionEngineTest, DestructionRemovesGlobalMapping) {
GlobalVariable *G1 =
NewExtGlobal(Type::getInt32Ty(getGlobalContext()), "Global1");
int32_t Mem1 = 3;
Engine->addGlobalMapping(G1, &Mem1);
// Make sure the reverse mapping is enabled.
EXPECT_EQ(G1, Engine->getGlobalValueAtAddress(&Mem1));
// When the GV goes away, the ExecutionEngine should remove any
// mappings that refer to it.
G1->eraseFromParent();
EXPECT_EQ(NULL, Engine->getGlobalValueAtAddress(&Mem1));
}
}
<|endoftext|>
|
<commit_before>#include "AudioRecorder.h"
#include <Tools/ThreadUtil.h>
#include "Tools/NaoTime.h"
#include <chrono>
#include <pulse/error.h>
using namespace std;
namespace naoth
{
AudioRecorder::AudioRecorder()
:
audioReadBuffer(BUFFER_SIZE_RX, 0),
recordingTimestamp(0),
capture(false),
running(false),
initialized(false),
resetting(false),
deinitCyclesCounter(0)
{
std::cout << "[INFO] AudioRecorder thread started" << std::endl;
audioRecorderThread = std::thread([this] {this->execute();});
ThreadUtil::setPriority(audioRecorderThread, ThreadUtil::Priority::lowest);
//The following parameters are used by bhuman:
//TODO implement them as controll in AudioData Representation
/*
(unsigned)(10) retries, // Number of tries to open device.
(unsigned)(500) retryDelay, //< Delay before a retry to open device.
(bool)(false) allChannels, //< Use all 4 channels, instead of only two
(unsigned)(8000) sampleRate, //< Sample rate to capture. This variable will contain the framerate the driver finally selected.
(unsigned)(5000) maxFrames, //< Maximum number of frames read in one cycle.
(bool)(true) onlySoundInSet, // If true, the module will not provide audio data in game states other than set
*/
}
AudioRecorder::~AudioRecorder()
{
if(audioRecorderThread.joinable())
{
audioRecorderThread.join();
}
if(initialized)
{
deinitAudio();
}
}
void AudioRecorder::execute()
{
running = true;
// return;
while(running)
{
int error = 0;
if(!initialized)
{
if(!resetting && capture)
{
std::cout << "[AudioRecorder] start recording" << std::endl;
initAudio();
}
else if(resetting)
{
usleep(128);
}
}
else
{
if(!capture)
{
// deinit audio device ~8 seconds after switch off command was set
// (recording has blocking behaviour 1024 samples equal 128 ms 63*128 equals ~8s
if(deinitCyclesCounter >= 63)
{
std::cout << "stop recording" << std::endl;
deinitAudio();
deinitCyclesCounter = 0;
usleep(128);
continue;
}
deinitCyclesCounter++;
}
}
if(!resetting && initialized)
{
//calculate amount of samples needed
int samplesToRead = SAMPLE_NEW_COUNT * numChannels;
int bytesToRead = samplesToRead * static_cast<int>(sizeof(short));
// Record some data
if (!paSimple || paSimple == NULL)
{
std::cerr << "[PulseAudio] pa_simple == NULL" << std::endl;
running = false;
}
//std::cout << "[AudioRecorder] bytesToRead: " << bytesToRead << std::endl;
if (pa_simple_read(paSimple, &audioReadBuffer[0], bytesToRead, &error) < 0)
{
std::cerr << "[PulseAudio] pa_simple_read() failed: " << pa_strerror(error) << std::endl;
running = false;
} else {
recordingTimestamp = NaoTime::getNaoTimeInMilliSeconds();
}
}
else
{
usleep(128);
continue;
}
} // end while
} // end execute
void AudioRecorder::set(const naoth::AudioControl& controlData)
{
std::unique_lock<std::mutex> lock(setMutex, std::try_to_lock);
if ( lock.owns_lock() )
{
if(capture != controlData.capture) {
capture = controlData.capture;
std::cout << "Capture: " << capture << std::endl;
}
if(activeChannels != controlData.activeChannels)
{
resetting = true;
if(initialized) {
deinitAudio();
}
//clearBuffers(); //TODO are there any buffers to clear?
activeChannels = controlData.activeChannels;
numChannels = controlData.numChannels;
sampleRate = controlData.sampleRate;
buffer_size = controlData.buffer_size;
resetting = false;
}
}
}
void AudioRecorder::get(AudioData& data)
{
if (initialized)
{
std::unique_lock<std::mutex> lock(getMutex, std::try_to_lock);
if ( lock.owns_lock() && recordingTimestamp > data.timestamp)
{
data.sampleRate = sampleRate;
data.numChannels = numChannels;
data.samples = audioReadBuffer;
data.timestamp = recordingTimestamp;
}
}
} // end AudioRecorder::get
void AudioRecorder::initAudio()
{
//clearBuffers(); probably not needed anymore
pa_sample_spec paSampleSpec;
paSampleSpec.format = PA_SAMPLE_S16LE;
paSampleSpec.rate = sampleRate;
paSampleSpec.channels = (uint8_t)numChannels;
// Create the recording stream
int error;
if (!(paSimple = pa_simple_new(NULL, "AudioRecorder", PA_STREAM_RECORD, NULL, "AudioRecorder", &paSampleSpec, NULL, NULL, &error)))
{
std::cerr << "[PulseAudio] pa_simple_new() failed: " << pa_strerror(error) << "\n" << std::endl;
paSimple = NULL;
}
else
{
std::cout << "[PulseAudio] device opened" << std::endl;
std::cout << "[PulseAudio] Rate: " << paSampleSpec.rate <<std::endl;
std::cout << "[PulseAudio] Channels: " << (int) paSampleSpec.channels <<std::endl;
std::cout << "[PulseAudio] Buffer Size: " << buffer_size <<std::endl;
initialized = true;
}
} //end initAudio
void AudioRecorder::deinitAudio()
{
if (paSimple != NULL)
{
initialized = false;
std::cout << "[PulseAudio] device closed" << std::endl;
pa_simple_free(paSimple);
paSimple = NULL;
}
} //end deinitAudio
}// end namespace<commit_msg>set running to false so that the thread can stop<commit_after>#include "AudioRecorder.h"
#include <Tools/ThreadUtil.h>
#include "Tools/NaoTime.h"
#include <chrono>
#include <pulse/error.h>
using namespace std;
namespace naoth
{
AudioRecorder::AudioRecorder()
:
audioReadBuffer(BUFFER_SIZE_RX, 0),
recordingTimestamp(0),
capture(false),
running(false),
initialized(false),
resetting(false),
deinitCyclesCounter(0)
{
std::cout << "[INFO] AudioRecorder thread started" << std::endl;
audioRecorderThread = std::thread([this] {this->execute();});
ThreadUtil::setPriority(audioRecorderThread, ThreadUtil::Priority::lowest);
//The following parameters are used by bhuman:
//TODO implement them as controll in AudioData Representation
/*
(unsigned)(10) retries, // Number of tries to open device.
(unsigned)(500) retryDelay, //< Delay before a retry to open device.
(bool)(false) allChannels, //< Use all 4 channels, instead of only two
(unsigned)(8000) sampleRate, //< Sample rate to capture. This variable will contain the framerate the driver finally selected.
(unsigned)(5000) maxFrames, //< Maximum number of frames read in one cycle.
(bool)(true) onlySoundInSet, // If true, the module will not provide audio data in game states other than set
*/
}
AudioRecorder::~AudioRecorder()
{
running = false;
if(audioRecorderThread.joinable()) {
audioRecorderThread.join();
}
if(initialized) {
deinitAudio();
}
}
void AudioRecorder::execute()
{
running = true;
// return;
while(running)
{
int error = 0;
if(!initialized)
{
if(!resetting && capture)
{
std::cout << "[AudioRecorder] start recording" << std::endl;
initAudio();
}
else if(resetting)
{
usleep(128);
}
}
else
{
if(!capture)
{
// deinit audio device ~8 seconds after switch off command was set
// (recording has blocking behaviour 1024 samples equal 128 ms 63*128 equals ~8s
if(deinitCyclesCounter >= 63)
{
std::cout << "stop recording" << std::endl;
deinitAudio();
deinitCyclesCounter = 0;
usleep(128);
continue;
}
deinitCyclesCounter++;
}
}
if(!resetting && initialized)
{
//calculate amount of samples needed
int samplesToRead = SAMPLE_NEW_COUNT * numChannels;
int bytesToRead = samplesToRead * static_cast<int>(sizeof(short));
// Record some data
if (!paSimple || paSimple == NULL)
{
std::cerr << "[PulseAudio] pa_simple == NULL" << std::endl;
running = false;
}
//std::cout << "[AudioRecorder] bytesToRead: " << bytesToRead << std::endl;
if (pa_simple_read(paSimple, &audioReadBuffer[0], bytesToRead, &error) < 0)
{
std::cerr << "[PulseAudio] pa_simple_read() failed: " << pa_strerror(error) << std::endl;
running = false;
} else {
recordingTimestamp = NaoTime::getNaoTimeInMilliSeconds();
}
}
else
{
usleep(128);
continue;
}
} // end while
} // end execute
void AudioRecorder::set(const naoth::AudioControl& controlData)
{
std::unique_lock<std::mutex> lock(setMutex, std::try_to_lock);
if ( lock.owns_lock() )
{
if(capture != controlData.capture) {
capture = controlData.capture;
std::cout << "Capture: " << capture << std::endl;
}
if(activeChannels != controlData.activeChannels)
{
resetting = true;
if(initialized) {
deinitAudio();
}
//clearBuffers(); //TODO are there any buffers to clear?
activeChannels = controlData.activeChannels;
numChannels = controlData.numChannels;
sampleRate = controlData.sampleRate;
buffer_size = controlData.buffer_size;
resetting = false;
}
}
}
void AudioRecorder::get(AudioData& data)
{
if (initialized)
{
std::unique_lock<std::mutex> lock(getMutex, std::try_to_lock);
if ( lock.owns_lock() && recordingTimestamp > data.timestamp)
{
data.sampleRate = sampleRate;
data.numChannels = numChannels;
data.samples = audioReadBuffer;
data.timestamp = recordingTimestamp;
}
}
} // end AudioRecorder::get
void AudioRecorder::initAudio()
{
//clearBuffers(); probably not needed anymore
pa_sample_spec paSampleSpec;
paSampleSpec.format = PA_SAMPLE_S16LE;
paSampleSpec.rate = sampleRate;
paSampleSpec.channels = (uint8_t)numChannels;
// Create the recording stream
int error;
if (!(paSimple = pa_simple_new(NULL, "AudioRecorder", PA_STREAM_RECORD, NULL, "AudioRecorder", &paSampleSpec, NULL, NULL, &error)))
{
std::cerr << "[PulseAudio] pa_simple_new() failed: " << pa_strerror(error) << "\n" << std::endl;
paSimple = NULL;
}
else
{
std::cout << "[PulseAudio] device opened" << std::endl;
std::cout << "[PulseAudio] Rate: " << paSampleSpec.rate <<std::endl;
std::cout << "[PulseAudio] Channels: " << (int) paSampleSpec.channels <<std::endl;
std::cout << "[PulseAudio] Buffer Size: " << buffer_size <<std::endl;
initialized = true;
}
} //end initAudio
void AudioRecorder::deinitAudio()
{
if (paSimple != NULL)
{
initialized = false;
std::cout << "[PulseAudio] device closed" << std::endl;
pa_simple_free(paSimple);
paSimple = NULL;
}
} //end deinitAudio
}// end namespace<|endoftext|>
|
<commit_before>/*
Basic Server code for CMPT 276, Spring 2016.
*/
#include <exception>
#include <iostream>
#include <memory>
#include <string>
#include <unordered_map>
#include <utility>
#include <vector>
#include <string>
#include <cpprest/base_uri.h>
#include <cpprest/http_listener.h>
#include <cpprest/json.h>
#include <pplx/pplxtasks.h>
#include <was/common.h>
#include <was/storage_account.h>
#include <was/table.h>
#include "TableCache.h"
#include "config.h"
#include "make_unique.h"
#include "azure_keys.h"
using azure::storage::cloud_storage_account;
using azure::storage::storage_credentials;
using azure::storage::storage_exception;
using azure::storage::cloud_table;
using azure::storage::cloud_table_client;
using azure::storage::edm_type;
using azure::storage::entity_property;
using azure::storage::table_entity;
using azure::storage::table_operation;
using azure::storage::table_query;
using azure::storage::table_query_iterator;
using azure::storage::table_result;
using azure::storage::access_condition;
using pplx::extensibility::critical_section_t;
using pplx::extensibility::scoped_critical_section_t;
using std::cin;
using std::cout;
using std::endl;
using std::getline;
using std::make_pair;
using std::pair;
using std::string;
using std::unordered_map;
using std::vector;
using web::http::http_headers;
using web::http::http_request;
using web::http::methods;
using web::http::status_codes;
using web::http::uri;
using web::json::value;
using web::http::experimental::listener::http_listener;
using prop_vals_t = vector<pair<string,value>>;
constexpr const char* def_url = "http://localhost:34568";
const string create_table {"CreateTable"};
const string delete_table {"DeleteTable"};
const string update_entity {"UpdateEntity"};
const string delete_entity {"DeleteEntity"};
/*
Cache of opened tables
*/
TableCache table_cache {storage_connection_string};
/*
Convert properties represented in Azure Storage type
to prop_vals_t type.
*/
prop_vals_t get_properties (const table_entity::properties_type& properties, prop_vals_t values = prop_vals_t {}) {
for (const auto v : properties) {
if (v.second.property_type() == edm_type::string) {
values.push_back(make_pair(v.first, value::string(v.second.string_value())));
}
else if (v.second.property_type() == edm_type::datetime) {
values.push_back(make_pair(v.first, value::string(v.second.str())));
}
else if(v.second.property_type() == edm_type::int32) {
values.push_back(make_pair(v.first, value::number(v.second.int32_value())));
}
else if(v.second.property_type() == edm_type::int64) {
values.push_back(make_pair(v.first, value::number(v.second.int64_value())));
}
else if(v.second.property_type() == edm_type::double_floating_point) {
values.push_back(make_pair(v.first, value::number(v.second.double_value())));
}
else if(v.second.property_type() == edm_type::boolean) {
values.push_back(make_pair(v.first, value::boolean(v.second.boolean_value())));
}
else {
values.push_back(make_pair(v.first, value::string(v.second.str())));
}
}
return values;
}
/*
Given an HTTP message with a JSON body, return the JSON
body as an unordered map of strings to strings.
Note that all types of JSON values are returned as strings.
Use C++ conversion utilities to convert to numbers or dates
as necessary.
*/
unordered_map<string,string> get_json_body(http_request message) {
unordered_map<string,string> results {};
const http_headers& headers {message.headers()};
auto content_type (headers.find("Content-Type"));
if (content_type == headers.end() ||
content_type->second != "application/json")
return results;
value json{};
message.extract_json(true)
.then([&json](value v) -> bool
{
json = v;
return true;
})
.wait();
if (json.is_object()) {
for (const auto& v : json.as_object()) {
if (v.second.is_string()) {
results[v.first] = v.second.as_string();
}
else {
results[v.first] = v.second.serialize();
}
}
}
return results;
}
/*
Top-level routine for processing all HTTP GET requests.
GET is the only request that has no command. All
operands specify the value(s) to be retrieved.
*/
void handle_get(http_request message) {
string path {uri::decode(message.relative_uri().path())};
cout << endl << "**** GET " << path << endl;
auto paths = uri::split_path(path);
// Need at least a table name
if (paths.size() < 1) {
message.reply(status_codes::BadRequest);
return;
}
cloud_table table {table_cache.lookup_table(paths[0])};
if ( ! table.exists()) {
message.reply(status_codes::NotFound);
return;
}
// GET all entries in table
if (paths.size() == 1) {
table_query query {};
table_query_iterator end;
table_query_iterator it = table.execute_query(query);
vector<value> key_vec;
while (it != end) {
cout << "Key: " << it->partition_key() << " / " << it->row_key() << endl;
prop_vals_t keys {
make_pair("Partition",value::string(it->partition_key())),
make_pair("Row", value::string(it->row_key()))};
keys = get_properties(it->properties(), keys);
key_vec.push_back(value::object(keys));
++it;
}
message.reply(status_codes::OK, value::array(key_vec));
return;
}
// GET specific entry: Partition == paths[1], Row == paths[2]
table_operation retrieve_operation {table_operation::retrieve_entity(paths[1], paths[2])};
table_result retrieve_result {table.execute(retrieve_operation)};
cout << "HTTP code: " << retrieve_result.http_status_code() << endl;
if (retrieve_result.http_status_code() == status_codes::NotFound) { // if the table does not exist
message.reply(status_codes::NotFound);
return;
}
table_entity entity {retrieve_result.entity()};
table_entity::properties_type properties {entity.properties()};
unordered_map<string,string> json_body {get_json_body (message)};
if (json_body.size () > 0) { // There was a body
std::vector<string> nameList;
for (const auto v : json_body) { // for every pair in json_body (unordered map)
// v is a pair<string,string> representing a property in the JSON object
if(v.second == "*"){
nameList.push_back(v.first);
}
}
// Do other things for the case where the message had a body
// creates query
table_query query {};
table_query_iterator end;
access_condition existing = azure::storage::access_condition::generate_empty_condition();
for(int i = 0 ; i < nameList.size() ; i++){
// Construct the query operation for all entities that fit the name
utility::string_t addition = azure::storage::table_query::generate_filter_condition ( "RowKey",
azure::storage::query_comparison_operator::equal, nameList[i]);
query.set_filter_string(query.combine_filter_conditions (exisiting,
utility::string_t azure::storage::query_logical_operator::op_and, addition));
}
// Execute Query
table_query_iterator it = table.execute_query(query);
vector<value> key_vec;
while (it != end) {
cout << "Key: " << it->partition_key() << endl;
prop_vals_t keys {
make_pair("Partition",value::string(it->partition_key()))};
keys = get_properties(it->properties(), keys);
key_vec.push_back(value::object(keys));
++it;
}
// message reply
message.reply(status_codes::OK, value::array(key_vec));
return;
}
// If the entity has any properties, return them as JSON
prop_vals_t values (get_properties(properties));
if (values.size() > 0)
message.reply(status_codes::OK, value::object(values));
else
message.reply(status_codes::OK);
}
/*
Top-level routine for processing all HTTP POST requests.
*/
void handle_post(http_request message) {
string path {uri::decode(message.relative_uri().path())};
cout << endl << "**** POST " << path << endl;
auto paths = uri::split_path(path);
// Need at least an operation and a table name
if (paths.size() < 2) {
message.reply(status_codes::BadRequest);
return;
}
string table_name {paths[1]};
cloud_table table {table_cache.lookup_table(table_name)};
// Create table (idempotent if table exists)
if (paths[0] == create_table) {
cout << "Create " << table_name << endl;
bool created {table.create_if_not_exists()};
cout << "Administrative table URI " << table.uri().primary_uri().to_string() << endl;
if (created)
message.reply(status_codes::Created);
else
message.reply(status_codes::Accepted);
}
else {
message.reply(status_codes::BadRequest);
}
}
/*
Top-level routine for processing all HTTP PUT requests.
*/
void handle_put(http_request message) {
string path {uri::decode(message.relative_uri().path())};
cout << endl << "**** PUT " << path << endl;
auto paths = uri::split_path(path);
// Need at least an operation, table name, partition, and row
if (paths.size() < 4) {
message.reply(status_codes::BadRequest);
return;
}
cloud_table table {table_cache.lookup_table(paths[1])};
if ( ! table.exists()) {
message.reply(status_codes::NotFound);
return;
}
table_entity entity {paths[2], paths[3]}; // partition and row
// Update entity
if (paths[0] == update_entity) {
cout << "Update " << entity.partition_key() << " / " << entity.row_key() << endl;
table_entity::properties_type& properties = entity.properties();
for (const auto v : get_json_body(message)) {
properties[v.first] = entity_property {v.second};
}
table_operation operation {table_operation::insert_or_merge_entity(entity)};
table_result op_result {table.execute(operation)};
message.reply(status_codes::OK);
}
else {
message.reply(status_codes::BadRequest);
}
}
/*
Top-level routine for processing all HTTP DELETE requests.
*/
void handle_delete(http_request message) {
string path {uri::decode(message.relative_uri().path())};
cout << endl << "**** DELETE " << path << endl;
auto paths = uri::split_path(path);
// Need at least an operation and table name
if (paths.size() < 2) {
message.reply(status_codes::BadRequest);
return;
}
string table_name {paths[1]};
cloud_table table {table_cache.lookup_table(table_name)};
// Delete table
if (paths[0] == delete_table) {
cout << "Delete " << table_name << endl;
if ( ! table.exists()) {
message.reply(status_codes::NotFound);
}
table.delete_table();
table_cache.delete_entry(table_name);
message.reply(status_codes::OK);
}
// Delete entity
else if (paths[0] == delete_entity) {
// For delete entity, also need partition and row
if (paths.size() < 4) {
message.reply(status_codes::BadRequest);
return;
}
table_entity entity {paths[2], paths[3]};
cout << "Delete " << entity.partition_key() << " / " << entity.row_key()<< endl;
table_operation operation {table_operation::delete_entity(entity)};
table_result op_result {table.execute(operation)};
int code {op_result.http_status_code()};
if (code == status_codes::OK ||
code == status_codes::NoContent)
message.reply(status_codes::OK);
else
message.reply(code);
}
else {
message.reply(status_codes::BadRequest);
}
}
/*
Main server routine
Install handlers for the HTTP requests and open the listener,
which processes each request asynchronously.
Wait for a carriage return, then shut the server down.
*/
int main (int argc, char const * argv[]) {
http_listener listener {def_url};
listener.support(methods::GET, &handle_get);
listener.support(methods::POST, &handle_post);
listener.support(methods::PUT, &handle_put);
listener.support(methods::DEL, &handle_delete);
listener.open().wait(); // Wait for listener to complete starting
cout << "Enter carriage return to stop server." << endl;
string line;
getline(std::cin, line);
// Shut it down
listener.close().wait();
cout << "Closed" << endl;
}
<commit_msg>New format not yet filled in with detailed modification<commit_after>/*
Basic Server code for CMPT 276, Spring 2016.
*/
#include <exception>
#include <iostream>
#include <memory>
#include <string>
#include <unordered_map>
#include <utility>
#include <vector>
#include <string>
#include <cpprest/base_uri.h>
#include <cpprest/http_listener.h>
#include <cpprest/json.h>
#include <pplx/pplxtasks.h>
#include <was/common.h>
#include <was/storage_account.h>
#include <was/table.h>
#include "TableCache.h"
#include "config.h"
#include "make_unique.h"
#include "azure_keys.h"
using azure::storage::cloud_storage_account;
using azure::storage::storage_credentials;
using azure::storage::storage_exception;
using azure::storage::cloud_table;
using azure::storage::cloud_table_client;
using azure::storage::edm_type;
using azure::storage::entity_property;
using azure::storage::table_entity;
using azure::storage::table_operation;
using azure::storage::table_query;
using azure::storage::table_query_iterator;
using azure::storage::table_result;
using pplx::extensibility::critical_section_t;
using pplx::extensibility::scoped_critical_section_t;
using std::cin;
using std::cout;
using std::endl;
using std::getline;
using std::make_pair;
using std::pair;
using std::string;
using std::unordered_map;
using std::vector;
using web::http::http_headers;
using web::http::http_request;
using web::http::methods;
using web::http::status_codes;
using web::http::uri;
using web::json::value;
using web::http::experimental::listener::http_listener;
using prop_vals_t = vector<pair<string,value>>;
constexpr const char* def_url = "http://localhost:34568";
const string create_table {"CreateTable"};
const string delete_table {"DeleteTable"};
const string update_entity {"UpdateEntity"};
const string delete_entity {"DeleteEntity"};
/*
Cache of opened tables
*/
TableCache table_cache {storage_connection_string};
/*
Convert properties represented in Azure Storage type
to prop_vals_t type.
*/
prop_vals_t get_properties (const table_entity::properties_type& properties, prop_vals_t values = prop_vals_t {}) {
for (const auto v : properties) {
if (v.second.property_type() == edm_type::string) {
values.push_back(make_pair(v.first, value::string(v.second.string_value())));
}
else if (v.second.property_type() == edm_type::datetime) {
values.push_back(make_pair(v.first, value::string(v.second.str())));
}
else if(v.second.property_type() == edm_type::int32) {
values.push_back(make_pair(v.first, value::number(v.second.int32_value())));
}
else if(v.second.property_type() == edm_type::int64) {
values.push_back(make_pair(v.first, value::number(v.second.int64_value())));
}
else if(v.second.property_type() == edm_type::double_floating_point) {
values.push_back(make_pair(v.first, value::number(v.second.double_value())));
}
else if(v.second.property_type() == edm_type::boolean) {
values.push_back(make_pair(v.first, value::boolean(v.second.boolean_value())));
}
else {
values.push_back(make_pair(v.first, value::string(v.second.str())));
}
}
return values;
}
/*
Given an HTTP message with a JSON body, return the JSON
body as an unordered map of strings to strings.
Note that all types of JSON values are returned as strings.
Use C++ conversion utilities to convert to numbers or dates
as necessary.
*/
unordered_map<string,string> get_json_body(http_request message) {
unordered_map<string,string> results {};
const http_headers& headers {message.headers()};
auto content_type (headers.find("Content-Type"));
if (content_type == headers.end() ||
content_type->second != "application/json")
return results;
value json{};
message.extract_json(true)
.then([&json](value v) -> bool
{
json = v;
return true;
})
.wait();
if (json.is_object()) {
for (const auto& v : json.as_object()) {
if (v.second.is_string()) {
results[v.first] = v.second.as_string();
}
else {
results[v.first] = v.second.serialize();
}
}
}
return results;
}
/*
Top-level routine for processing all HTTP GET requests.
GET is the only request that has no command. All
operands specify the value(s) to be retrieved.
*/
void handle_get(http_request message) {
string path {uri::decode(message.relative_uri().path())};
cout << endl << "**** GET " << path << endl;
auto paths = uri::split_path(path);
// Need at least a table name
if (paths.size() < 1) {
message.reply(status_codes::BadRequest);
return;
}
cloud_table table {table_cache.lookup_table(paths[0])};
if ( ! table.exists()) {
message.reply(status_codes::NotFound);
return;
}
// GET all entries in table
if (paths.size() == 1) {
unordered_map<string,string> json_body {get_json_body (message)};
if(json_body.size() > 0){
std::vector<string> nameList;
for (const auto v : json_body) { // for every pair in json_body (unordered map)
// v is a pair<string,string> representing a property in the JSON object
if(v.second == "*"){
nameList.push_back(v.first);
}
// creating vector for all properties to loop through later
table_query query {};
table_query_iterator end;
table_query_iterator it = table.execute_query(query);
vector<value> key_vec;
while (it != end) {
cout << "Key: " << it->partition_key() << " / " << it->row_key() << endl;
prop_vals_t keys {
make_pair("Partition",value::string(it->partition_key())),
make_pair("Row", value::string(it->row_key()))};
keys = get_properties(it->properties(), keys);
key_vec.push_back(value::object(keys));
++it;
}
/*for(int i = 0; i < nameList.size(); i++){
for
}*/
}
}
else{
table_query query {};
table_query_iterator end;
table_query_iterator it = table.execute_query(query);
vector<value> key_vec;
while (it != end) {
cout << "Key: " << it->partition_key() << " / " << it->row_key() << endl;
prop_vals_t keys {
make_pair("Partition",value::string(it->partition_key())),
make_pair("Row", value::string(it->row_key()))};
keys = get_properties(it->properties(), keys);
key_vec.push_back(value::object(keys));
++it;
}
}
//message.reply(status_codes::OK, value::array(key_vec));
return;
}
// GET specific entry: Partition == paths[1], Row == paths[2]
table_operation retrieve_operation {table_operation::retrieve_entity(paths[1], paths[2])};
table_result retrieve_result {table.execute(retrieve_operation)};
cout << "HTTP code: " << retrieve_result.http_status_code() << endl;
if (retrieve_result.http_status_code() == status_codes::NotFound) { // if the table does not exist
message.reply(status_codes::NotFound);
return;
}
table_entity entity {retrieve_result.entity()};
table_entity::properties_type properties {entity.properties()};
// If the entity has any properties, return them as JSON
prop_vals_t values (get_properties(properties));
if (values.size() > 0)
message.reply(status_codes::OK, value::object(values));
else
message.reply(status_codes::OK);
}
/*
Top-level routine for processing all HTTP POST requests.
*/
void handle_post(http_request message) {
string path {uri::decode(message.relative_uri().path())};
cout << endl << "**** POST " << path << endl;
auto paths = uri::split_path(path);
// Need at least an operation and a table name
if (paths.size() < 2) {
message.reply(status_codes::BadRequest);
return;
}
string table_name {paths[1]};
cloud_table table {table_cache.lookup_table(table_name)};
// Create table (idempotent if table exists)
if (paths[0] == create_table) {
cout << "Create " << table_name << endl;
bool created {table.create_if_not_exists()};
cout << "Administrative table URI " << table.uri().primary_uri().to_string() << endl;
if (created)
message.reply(status_codes::Created);
else
message.reply(status_codes::Accepted);
}
else {
message.reply(status_codes::BadRequest);
}
}
/*
Top-level routine for processing all HTTP PUT requests.
*/
void handle_put(http_request message) {
string path {uri::decode(message.relative_uri().path())};
cout << endl << "**** PUT " << path << endl;
auto paths = uri::split_path(path);
// Need at least an operation, table name, partition, and row
if (paths.size() < 4) {
message.reply(status_codes::BadRequest);
return;
}
cloud_table table {table_cache.lookup_table(paths[1])};
if ( ! table.exists()) {
message.reply(status_codes::NotFound);
return;
}
table_entity entity {paths[2], paths[3]}; // partition and row
// Update entity
if (paths[0] == update_entity) {
cout << "Update " << entity.partition_key() << " / " << entity.row_key() << endl;
table_entity::properties_type& properties = entity.properties();
for (const auto v : get_json_body(message)) {
properties[v.first] = entity_property {v.second};
}
table_operation operation {table_operation::insert_or_merge_entity(entity)};
table_result op_result {table.execute(operation)};
message.reply(status_codes::OK);
}
else {
message.reply(status_codes::BadRequest);
}
}
/*
Top-level routine for processing all HTTP DELETE requests.
*/
void handle_delete(http_request message) {
string path {uri::decode(message.relative_uri().path())};
cout << endl << "**** DELETE " << path << endl;
auto paths = uri::split_path(path);
// Need at least an operation and table name
if (paths.size() < 2) {
message.reply(status_codes::BadRequest);
return;
}
string table_name {paths[1]};
cloud_table table {table_cache.lookup_table(table_name)};
// Delete table
if (paths[0] == delete_table) {
cout << "Delete " << table_name << endl;
if ( ! table.exists()) {
message.reply(status_codes::NotFound);
}
table.delete_table();
table_cache.delete_entry(table_name);
message.reply(status_codes::OK);
}
// Delete entity
else if (paths[0] == delete_entity) {
// For delete entity, also need partition and row
if (paths.size() < 4) {
message.reply(status_codes::BadRequest);
return;
}
table_entity entity {paths[2], paths[3]};
cout << "Delete " << entity.partition_key() << " / " << entity.row_key()<< endl;
table_operation operation {table_operation::delete_entity(entity)};
table_result op_result {table.execute(operation)};
int code {op_result.http_status_code()};
if (code == status_codes::OK ||
code == status_codes::NoContent)
message.reply(status_codes::OK);
else
message.reply(code);
}
else {
message.reply(status_codes::BadRequest);
}
}
/*
Main server routine
Install handlers for the HTTP requests and open the listener,
which processes each request asynchronously.
Wait for a carriage return, then shut the server down.
*/
int main (int argc, char const * argv[]) {
http_listener listener {def_url};
listener.support(methods::GET, &handle_get);
listener.support(methods::POST, &handle_post);
listener.support(methods::PUT, &handle_put);
listener.support(methods::DEL, &handle_delete);
listener.open().wait(); // Wait for listener to complete starting
cout << "Enter carriage return to stop server." << endl;
string line;
getline(std::cin, line);
// Shut it down
listener.close().wait();
cout << "Closed" << endl;
}
<|endoftext|>
|
<commit_before>/* =======================================================================
Copyright (c) 2011-2014, Institute for Microelectronics, TU Wien
http://www.iue.tuwien.ac.at
-----------------
ViennaMini - The Vienna Device Simulator
-----------------
authors: Karl Rupp [email protected]
Josef Weinbub [email protected]
(add your name here)
license: see file LICENSE in the base directory
======================================================================= */
// ViennaMini includes
//
#include "viennamini/simulator.hpp"
#include "viennamini/device_collection.hpp"
// ViennaMesh includes
//
#include "viennamesh/viennamesh.hpp"
template<typename DeviceT>
void generate_1d_device(DeviceT& device)
{
typedef viennagrid::brep_1d_mesh GeometryMeshType;
typedef viennagrid::result_of::segmentation<GeometryMeshType>::type GeometrySegmentationType;
typedef viennagrid::result_of::segment_handle<GeometrySegmentationType>::type GeometrySegmentHandleType;
typedef viennagrid::segmented_mesh<GeometryMeshType, GeometrySegmentationType> SegmentedGeometryMeshType;
// Typedefing vertex handle and point type for geometry creation
typedef viennagrid::result_of::point<GeometryMeshType>::type PointType;
typedef viennagrid::result_of::vertex_handle<GeometryMeshType>::type GeometryVertexHandle;
// creating the geometry mesh
viennamesh::result_of::parameter_handle< SegmentedGeometryMeshType >::type geometry_handle = viennamesh::make_parameter<SegmentedGeometryMeshType>();
GeometryMeshType & geometry = geometry_handle().mesh;
GeometrySegmentationType & segmentation = geometry_handle().segmentation;
GeometryVertexHandle c11 = viennagrid::make_vertex( geometry, PointType(-0.5) );
GeometryVertexHandle c1 = viennagrid::make_vertex( geometry, PointType(0.0) );
GeometryVertexHandle i1 = viennagrid::make_vertex( geometry, PointType(1.0) );
GeometryVertexHandle i2 = viennagrid::make_vertex( geometry, PointType(2.0) );
GeometryVertexHandle c2 = viennagrid::make_vertex( geometry, PointType(3.0) );
GeometryVertexHandle c21 = viennagrid::make_vertex( geometry, PointType(3.5) );
GeometrySegmentHandleType segment1 = segmentation.make_segment();
viennagrid::add( segment1, c11 );
viennagrid::add( segment1, c1 );
GeometrySegmentHandleType segment2 = segmentation.make_segment();
viennagrid::add( segment2, c1 );
viennagrid::add( segment2, i1 );
GeometrySegmentHandleType segment3 = segmentation.make_segment();
viennagrid::add( segment3, i1 );
viennagrid::add( segment3, i2 );
GeometrySegmentHandleType segment4 = segmentation.make_segment();
viennagrid::add( segment4, i2 );
viennagrid::add( segment4, c2 );
GeometrySegmentHandleType segment5 = segmentation.make_segment();
viennagrid::add( segment5, c2 );
viennagrid::add( segment5, c21 );
viennamesh::algorithm_handle mesher( new viennamesh::make_line_mesh() );
mesher->set_input( "mesh", geometry_handle );
mesher->set_input( "cell_size", 0.005 );
mesher->set_input( "make_segmented_mesh", true );
mesher->set_input( "absolute_min_geometry_point_distance", 1e-10 );
mesher->set_input( "relative_min_geometry_point_distance", 1e-10 );
device.make_line1d();
mesher->set_output( "mesh", device.get_segmesh_line_1d() );
mesher->run();
}
int main()
{
// create the simulator object
//
viennamini::simulator mysim;
// read mesh and material input files
//
mysim.device().read_material_database("../../auxiliary/materials.xml");
mysim.device().read_unit_database("../../auxiliary/units.xml");
generate_1d_device(mysim.device());
// perform an optional scaling step
// e.g., transfer device dimensions to nm regime
//
// mysim.device().scale(1.0E-6);
// mysim.device().set_quantity(viennamini::id::temperature(), 223.15, "K"); // -50 degrees celsius
mysim.device().set_quantity(viennamini::id::temperature(), 273.15, "K"); // 0 degrees celsius
// mysim.device().set_quantity(viennamini::id::temperature(), 323.15, "K"); // 50 degrees celsius
// mysim.device().set_quantity(viennamini::id::temperature(), 273.15, "K"); // 0 degrees celsius
// mysim.device().set_quantity(viennamini::id::temperature(), 293.15, "K"); // 20 degrees celsius
// mysim.device().set_quantity(viennamini::id::temperature(), 313.15, "K"); // 40 degrees celsius
// setup auxiliary segment indices, aiding in identifying the individual
// device segments in the subsequent device setup step
//
const int left_contact = 0;
const int left_oxide = 1;
const int middle_oxide = 2;
const int right_oxide = 3;
const int right_contact = 4;
// setup the device by identifying the individual segments
//
mysim.device().make(viennamini::role::contact, left_contact, "left_contact", "Cu");
mysim.device().make(viennamini::role::oxide, left_oxide, "left_oxide", "SiO2");
mysim.device().make(viennamini::role::oxide, middle_oxide, "middle_oxide", "Greg1");
mysim.device().make(viennamini::role::oxide, right_oxide, "right_oxide", "SiO2");
mysim.device().make(viennamini::role::contact, right_contact, "right_contact", "Cu");
// set the simulation type by choosing the PDE set and the discretization
//
mysim.config().model().set_pdeset(viennamini::pdeset::laplace);
mysim.config().model().set_discretization(viennamini::discret::fvm);
// manually set the contact potentials
//
mysim.device().set_contact_quantity(viennamini::id::potential(), left_contact, 0.0, "V");
mysim.device().set_contact_quantity(viennamini::id::potential(), right_contact, 1.0E4, "V");
// perform the simulation
//
mysim.run();
return EXIT_SUCCESS;
}
<commit_msg>updated 1d capacitor example<commit_after>/* =======================================================================
Copyright (c) 2011-2014, Institute for Microelectronics, TU Wien
http://www.iue.tuwien.ac.at
-----------------
ViennaMini - The Vienna Device Simulator
-----------------
authors: Karl Rupp [email protected]
Josef Weinbub [email protected]
(add your name here)
license: see file LICENSE in the base directory
======================================================================= */
// ViennaMini includes
//
#include "viennamini/simulator.hpp"
#include "viennamini/device_collection.hpp"
// ViennaMesh includes
//
#include "viennamesh/viennamesh.hpp"
template<typename DeviceT>
void generate_1d_device(DeviceT& device)
{
typedef viennagrid::brep_1d_mesh GeometryMeshType;
typedef viennagrid::result_of::segmentation<GeometryMeshType>::type GeometrySegmentationType;
typedef viennagrid::result_of::segment_handle<GeometrySegmentationType>::type GeometrySegmentHandleType;
typedef viennagrid::segmented_mesh<GeometryMeshType, GeometrySegmentationType> SegmentedGeometryMeshType;
// Typedefing vertex handle and point type for geometry creation
typedef viennagrid::result_of::point<GeometryMeshType>::type PointType;
typedef viennagrid::result_of::vertex_handle<GeometryMeshType>::type GeometryVertexHandle;
// creating the geometry mesh
viennamesh::result_of::parameter_handle< SegmentedGeometryMeshType >::type geometry_handle = viennamesh::make_parameter<SegmentedGeometryMeshType>();
GeometryMeshType & geometry = geometry_handle().mesh;
GeometrySegmentationType & segmentation = geometry_handle().segmentation;
GeometryVertexHandle c11 = viennagrid::make_vertex( geometry, PointType(-0.5) );
GeometryVertexHandle c1 = viennagrid::make_vertex( geometry, PointType(0.0) );
GeometryVertexHandle i1 = viennagrid::make_vertex( geometry, PointType(1.0) );
GeometryVertexHandle i2 = viennagrid::make_vertex( geometry, PointType(2.0) );
GeometryVertexHandle c2 = viennagrid::make_vertex( geometry, PointType(3.0) );
GeometryVertexHandle c21 = viennagrid::make_vertex( geometry, PointType(3.5) );
GeometrySegmentHandleType segment1 = segmentation.make_segment();
viennagrid::add( segment1, c11 );
viennagrid::add( segment1, c1 );
GeometrySegmentHandleType segment2 = segmentation.make_segment();
viennagrid::add( segment2, c1 );
viennagrid::add( segment2, i1 );
GeometrySegmentHandleType segment3 = segmentation.make_segment();
viennagrid::add( segment3, i1 );
viennagrid::add( segment3, i2 );
GeometrySegmentHandleType segment4 = segmentation.make_segment();
viennagrid::add( segment4, i2 );
viennagrid::add( segment4, c2 );
GeometrySegmentHandleType segment5 = segmentation.make_segment();
viennagrid::add( segment5, c2 );
viennagrid::add( segment5, c21 );
viennamesh::algorithm_handle mesher( new viennamesh::make_line_mesh() );
mesher->set_input( "mesh", geometry_handle );
mesher->set_input( "cell_size", 0.005 );
mesher->set_input( "make_segmented_mesh", true );
mesher->set_input( "absolute_min_geometry_point_distance", 1e-10 );
mesher->set_input( "relative_min_geometry_point_distance", 1e-10 );
device.make_line1d();
mesher->set_output( "mesh", device.get_segmesh_line_1d() );
mesher->run();
}
int main()
{
// create the simulator object
//
viennamini::simulator mysim;
// read mesh and material input files
//
mysim.device().read_material_database("../../auxiliary/materials.xml");
mysim.device().read_unit_database("../../auxiliary/units.xml");
generate_1d_device(mysim.device());
// perform an optional scaling step
// e.g., transfer device dimensions to nm regime
//
// mysim.device().scale(1.0E-6);
// mysim.device().set_quantity(viennamini::id::temperature(), 223.15, "K"); // -50 degrees celsius
// mysim.device().set_quantity(viennamini::id::temperature(), 273.15, "K"); // 0 degrees celsius
mysim.device().set_quantity(viennamini::id::temperature(), 323.15, "K"); // 50 degrees celsius
// mysim.device().set_quantity(viennamini::id::temperature(), 273.15, "K"); // 0 degrees celsius
// mysim.device().set_quantity(viennamini::id::temperature(), 293.15, "K"); // 20 degrees celsius
// mysim.device().set_quantity(viennamini::id::temperature(), 313.15, "K"); // 40 degrees celsius
// setup auxiliary segment indices, aiding in identifying the individual
// device segments in the subsequent device setup step
//
const int left_contact = 0;
const int left_oxide = 1;
const int middle_oxide = 2;
const int right_oxide = 3;
const int right_contact = 4;
// setup the device by identifying the individual segments
//
mysim.device().make(viennamini::role::contact, left_contact, "left_contact", "Cu");
mysim.device().make(viennamini::role::oxide, left_oxide, "left_oxide", "Si");
mysim.device().make(viennamini::role::oxide, middle_oxide, "middle_oxide", "Greg1");
mysim.device().make(viennamini::role::oxide, right_oxide, "right_oxide", "Si");
mysim.device().make(viennamini::role::contact, right_contact, "right_contact", "Cu");
// set the simulation type by choosing the PDE set and the discretization
//
mysim.config().model().set_pdeset(viennamini::pdeset::laplace);
mysim.config().model().set_discretization(viennamini::discret::fvm);
// manually set the contact potentials
//
mysim.device().set_contact_quantity(viennamini::id::potential(), left_contact, 0.0, "V");
mysim.device().set_contact_quantity(viennamini::id::potential(), right_contact, 1.0, "V");
// perform the simulation
//
mysim.run();
return EXIT_SUCCESS;
}
<|endoftext|>
|
<commit_before>#include <gtest/gtest.h>
TEST(SimpleTest, TrueIsAlwaysAndForeverWillBeTrue)
{
EXPECT_EQ(true, true);
}
int main(int ac, char* av[])
{
testing::InitGoogleTest(&ac, av);
return RUN_ALL_TESTS();
}<commit_msg>Build should fail<commit_after>#include <gtest/gtest.h>
TEST(SimpleTest, TrueIsAlwaysAndForeverWillBeTrue)
{
EXPECT_EQ(true, false);
}
int main(int ac, char* av[])
{
testing::InitGoogleTest(&ac, av);
return RUN_ALL_TESTS();
}<|endoftext|>
|
<commit_before>// 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.
//
// 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
//
// Original work from OpenCascade Sketcher
// (http://sourceforge.net/projects/occsketcher/)
//
// Modifications for GEOM and OCAF
// Authored by : Sioutis Fotios ([email protected])
//------------------------------------------------------------------------------
#include "Sketcher_Object.hxx"
//------------------------------------------------------------------------------
#include <Standard_GUID.hxx>
#include <TDF_Label.hxx>
#include <TDF_Tool.hxx>
#include <TDocStd_Document.hxx>
#include <TDocStd_Owner.hxx>
#include <TDataStd_Integer.hxx>
#include <TDataStd_Real.hxx>
#include <TDataStd_UAttribute.hxx>
#include <TDataXtd_Plane.hxx>
#include <TNaming_Builder.hxx>
#include <TNaming_NamedShape.HXX>
#include <AIS_Shape.hxx>
#include <gp_Circ2d.hxx>
#include <gp_Pln.hxx>
#include <ElCLib.hxx>
#include <GeomAPI.hxx>
#include <Geom_Surface.hxx>
#include <Geom_CartesianPoint.hxx>
#include <Geom2d_CartesianPoint.hxx>
#include <Sketcher_Edge.hxx>
#include <Geom2d_Circle.hxx>
#include <Sketcher_Arc.hxx>
#include <Geom2d_BezierCurve.hxx>
#include <Geom2d_TrimmedCurve.hxx>
#include <TopoDS.hxx>
#include <TopoDS_Edge.hxx>
#include <BRep_Tool.hxx>
#include <BRepBuilderAPI_MakeEdge2d.hxx>
#include <BRepBuilderAPI_MakeEdge.hxx>
#include <BRepBuilderAPI_MakeVertex.hxx>
#include <TPrsStd_AISPresentation.hxx>
//------------------------------------------------------------------------------
#define GEOM2D_LABEL 1
#define GEOMTYPE_LABEL 2
#define METHOD_LABEL 3
#define TYPE_LABEL 4
//------------------------------------------------------------------------------
const Standard_GUID& Sketcher_Object::GetObjectID()
{
static Standard_GUID anObjectID("FF1BBB01-5D14-4df2-980B-DDDDDDDDDDDD");
return anObjectID;
}
//------------------------------------------------------------------------------
Handle(Sketcher_Object) Sketcher_Object::GetObject(TDF_Label& theLabel)
{
if (!theLabel.IsAttribute(GetObjectID()))
return NULL;
TCollection_AsciiString anEntry;
TDF_Tool::Entry(theLabel, anEntry);
Handle(TDocStd_Document) aDoc = TDocStd_Owner::GetDocument(theLabel.Data());
if (aDoc.IsNull())
return NULL;
return new Sketcher_Object(theLabel);
}
//------------------------------------------------------------------------------
Sketcher_Object::Sketcher_Object(const TDF_Label& theEntry)
:_Ax3(gp::XOY())
{
if (theEntry.IsAttribute(GetObjectID()))
_label = theEntry;
else
Standard_Failure::Raise("Label does not contain a valid Sketcher_Object");
}
//------------------------------------------------------------------------------
Sketcher_Object::Sketcher_Object(const TDF_Label& theEntry,
const Handle(Geom2d_Geometry)& theGeom2d_Geometry,
const Sketcher_ObjectGeometryType theGeometryType,
const Sketcher_ObjectTypeOfMethod theTypeOfMethod)
:_Ax3(gp::XOY())
{
_label = theEntry;
_geometry = theGeom2d_Geometry;
_label.ForgetAllAttributes(Standard_True);
TDataStd_UAttribute::Set(_label, GetObjectID());
TDataStd_Integer::Set(_label.FindChild(GEOMTYPE_LABEL), theGeometryType);
TDataStd_Integer::Set(_label.FindChild(METHOD_LABEL), theTypeOfMethod);
TDataStd_Integer::Set(_label.FindChild(TYPE_LABEL), MainSketcherType);
SaveGeometry(_geometry, theGeometryType);
}
//------------------------------------------------------------------------------
Sketcher_Object::~Sketcher_Object()
{
}
//------------------------------------------------------------------------------
void Sketcher_Object::Remove()
{
ErasePrs(Standard_True);
_label.ForgetAllAttributes(Standard_True);
}
//------------------------------------------------------------------------------
void Sketcher_Object::SetGeometry(const Handle(Geom2d_Geometry)& theGeom2d_Geometry)
{
_geometry = theGeom2d_Geometry;
_label.FindChild(GEOM2D_LABEL).ForgetAllAttributes(Standard_True);
SaveGeometry(_geometry, GetGeometryType());
if (HasPrs())
SaveUpdatePrs();
}
//------------------------------------------------------------------------------
Handle(Geom2d_Geometry) Sketcher_Object::GetGeometry()
{
if (!_geometry.IsNull())
return _geometry;
else {
TopoDS_Shape aShape;
TDF_Label aResultLabel = _label.FindChild(GEOM2D_LABEL);
Handle(TNaming_NamedShape) aNS;
if (!aResultLabel.FindAttribute(TNaming_NamedShape::GetID(), aNS))
return NULL;
Handle(Geom_Surface) surface;
TopLoc_Location location;
Standard_Real First, Last;
Handle_Geom2d_Curve aCrv;
BRep_Tool::CurveOnSurface(TopoDS::Edge(aNS->Get()), aCrv, surface,location,First,Last);
Sketcher_ObjectGeometryType theGeometryType = GetGeometryType();
if (theGeometryType == LineSketcherObject) {
Handle(Geom2d_Line) aLine = Handle(Geom2d_Line)::DownCast(aCrv);
Handle(Geom2d_TrimmedCurve) aTrm = new Geom2d_TrimmedCurve(aLine, First, Last);
Handle(Sketcher_Edge) anEdge = new Sketcher_Edge();
anEdge->SetPoints(aTrm->StartPoint(), aTrm->EndPoint());
_geometry = anEdge;
}
else if (theGeometryType == ArcSketcherObject) {
Handle(Geom2d_Circle) aCirc = Handle(Geom2d_Circle)::DownCast(aCrv);
Handle(Geom2d_TrimmedCurve) aTrm = new Geom2d_TrimmedCurve(aCirc, First, Last);
Handle(Sketcher_Arc) anArc = new Sketcher_Arc(aCirc->Circ2d());
gp_Pnt2d midPnt;
aTrm->D0(((Last - First) / 2.), midPnt);
anArc->SetParam(aTrm->StartPoint(), midPnt, aTrm->EndPoint());
_geometry = anArc;
}
else
_geometry = aCrv;
return _geometry;
}
}
//------------------------------------------------------------------------------
TopoDS_Shape Sketcher_Object::GetShape()
{
TopoDS_Shape aShape;
TDF_Label aResultLabel = _label.FindChild(GEOM2D_LABEL);
Handle(TNaming_NamedShape) aNS;
if (aResultLabel.FindAttribute(TNaming_NamedShape::GetID(), aNS))
aShape = aNS->Get();
return aShape;
}
//------------------------------------------------------------------------------
void Sketcher_Object::SaveGeometry(const Handle(Geom2d_Geometry)& theGeom2d_Geometry,const Sketcher_ObjectGeometryType theGeometryType)
{
TNaming_Builder aBuilder(_label.FindChild(GEOM2D_LABEL));
TopoDS_Shape aShp;
if (theGeometryType == PointSketcherObject) {
Handle(Geom2d_CartesianPoint) aPnt2d = Handle(Geom2d_CartesianPoint)::DownCast(theGeom2d_Geometry);
gp_Pnt a3dPnt(aPnt2d->X(), aPnt2d->Y(), 0.);
aShp = BRepBuilderAPI_MakeVertex(a3dPnt);
}
else if (theGeometryType == LineSketcherObject) {
Handle(Sketcher_Edge) anEdge = Handle(Sketcher_Edge)::DownCast(theGeom2d_Geometry);
Handle(Geom2d_TrimmedCurve) aTrm = new Geom2d_TrimmedCurve(anEdge, anEdge->StartParameter(), anEdge->EndParameter());
aShp = BRepBuilderAPI_MakeEdge2d(aTrm);
}
else if (theGeometryType == CircleSketcherObject) {
Handle(Geom2d_Circle) aCirc = Handle(Geom2d_Circle)::DownCast(theGeom2d_Geometry);
aShp = BRepBuilderAPI_MakeEdge2d(aCirc);
}
else if (theGeometryType == ArcSketcherObject) {
Handle(Sketcher_Arc) anArc = Handle(Sketcher_Arc)::DownCast(theGeom2d_Geometry);
Handle(Geom2d_TrimmedCurve) aTrm = new Geom2d_TrimmedCurve(anArc, anArc->FirstParameter(), anArc->LastParameter());
aShp = BRepBuilderAPI_MakeEdge2d(aTrm);
}
else if (theGeometryType == CurveSketcherObject) {
Handle(Geom2d_BezierCurve) aBez = Handle(Geom2d_BezierCurve)::DownCast(theGeom2d_Geometry);
aShp = BRepBuilderAPI_MakeEdge2d(aBez);
}
aBuilder.Generated(aShp);
}
//------------------------------------------------------------------------------
void Sketcher_Object::SetPlane(const gp_Ax3& theAx3)
{
_Ax3 = theAx3;
if (HasPrs())
SaveUpdatePrs();
}
//------------------------------------------------------------------------------
const gp_Ax3 Sketcher_Object::GetPlane()
{
return _Ax3;
}
//------------------------------------------------------------------------------
void Sketcher_Object::SetGeometryType(const Sketcher_ObjectGeometryType theGeometryType)
{
TDataStd_Integer::Set(_label.FindChild(GEOMTYPE_LABEL), theGeometryType);
}
//------------------------------------------------------------------------------
Sketcher_ObjectGeometryType Sketcher_Object::GetGeometryType()
{
Handle(TDataStd_Integer) aVal;
_label.FindChild(GEOMTYPE_LABEL).FindAttribute(TDataStd_Integer::GetID(),aVal);
return (Sketcher_ObjectGeometryType)aVal->Get();
}
//------------------------------------------------------------------------------
void Sketcher_Object::SetTypeOfMethod(const Sketcher_ObjectTypeOfMethod theTypeOfMethod)
{
TDataStd_Integer::Set(_label.FindChild(METHOD_LABEL), theTypeOfMethod);
}
//------------------------------------------------------------------------------
Sketcher_ObjectTypeOfMethod Sketcher_Object::GetTypeOfMethod()
{
Handle(TDataStd_Integer) aVal;
_label.FindChild(METHOD_LABEL).FindAttribute(TDataStd_Integer::GetID(),aVal);
return (Sketcher_ObjectTypeOfMethod)aVal->Get();
}
//------------------------------------------------------------------------------
void Sketcher_Object::SetType(const Sketcher_ObjectType theType)
{
TDataStd_Integer::Set(_label.FindChild(TYPE_LABEL), theType);
if (HasPrs())
SaveUpdatePrs();
}
//------------------------------------------------------------------------------
Sketcher_ObjectType Sketcher_Object::GetType()
{
Handle(TDataStd_Integer) aVal;
_label.FindChild(TYPE_LABEL).FindAttribute(TDataStd_Integer::GetID(),aVal);
return (Sketcher_ObjectType)aVal->Get();
}
//------------------------------------------------------------------------------
// GRAPHICS IMPLEMENTATION
Handle(AIS_InteractiveObject) Sketcher_Object::GetAIS_Object()
{
return Get_TPrsStd_AISPresentation()->GetAIS();
}
//------------------------------------------------------------------------------
Handle(TPrsStd_AISPresentation) Sketcher_Object::Get_TPrsStd_AISPresentation()
{
if (!HasPrs())
SaveUpdatePrs();
Handle(TPrsStd_AISPresentation) aPresentation;
_label.FindChild(GEOM2D_LABEL).FindAttribute(TPrsStd_AISPresentation::GetID(),aPresentation);
return aPresentation;
}
//------------------------------------------------------------------------------
void Sketcher_Object::DisplayPrs()
{
Get_TPrsStd_AISPresentation()->Display(Standard_False);
}
//------------------------------------------------------------------------------
void Sketcher_Object::ErasePrs(Standard_Boolean isRemove)
{
if (HasPrs()) {
Handle(TPrsStd_AISPresentation) aPresentation;
_label.FindChild(GEOM2D_LABEL).FindAttribute(TPrsStd_AISPresentation::GetID(),aPresentation);
aPresentation->Erase(isRemove);
if (isRemove)
_label.FindChild(GEOM2D_LABEL).ForgetAttribute(aPresentation);
}
}
//------------------------------------------------------------------------------
void Sketcher_Object::SaveUpdatePrs()
{
Handle(TPrsStd_AISPresentation) aPresentation = TPrsStd_AISPresentation::Set(_label.FindChild(GEOM2D_LABEL), TNaming_NamedShape::GetID());
gp_Trsf aTrs;
aTrs.SetDisplacement(gp::XOY(), GetPlane());
TopLoc_Location aLoc(aTrs);
aPresentation->Update();
aPresentation->GetAIS()->SetLocation(aLoc);
if (GetType() == AuxiliarySketcherType)
aPresentation->SetColor(Quantity_NOC_GRAY);
}
//------------------------------------------------------------------------------
bool Sketcher_Object::HasPrs()
{
Handle(TPrsStd_AISPresentation) aPresentation;
return (_label.FindChild(GEOM2D_LABEL).FindAttribute(TPrsStd_AISPresentation::GetID(),aPresentation));
}
//------------------------------------------------------------------------------
//------------------------------------------------------------------------------
IMPLEMENT_STANDARD_HANDLE(Sketcher_Object,MMgt_TShared)
IMPLEMENT_STANDARD_RTTI(Sketcher_Object)
IMPLEMENT_STANDARD_TYPE(Sketcher_Object)
IMPLEMENT_STANDARD_SUPERTYPE(MMgt_TShared)
IMPLEMENT_STANDARD_SUPERTYPE(Standard_Transient)
IMPLEMENT_STANDARD_SUPERTYPE_ARRAY()
IMPLEMENT_STANDARD_SUPERTYPE_ARRAY_ENTRY(MMgt_TShared)
IMPLEMENT_STANDARD_SUPERTYPE_ARRAY_ENTRY(Standard_Transient)
IMPLEMENT_STANDARD_SUPERTYPE_ARRAY_END()
IMPLEMENT_STANDARD_TYPE_END(Sketcher_Object)
//------------------------------------------------------------------------------
<commit_msg>Corrected case issue.<commit_after>// 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.
//
// 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
//
// Original work from OpenCascade Sketcher
// (http://sourceforge.net/projects/occsketcher/)
//
// Modifications for GEOM and OCAF
// Authored by : Sioutis Fotios ([email protected])
//------------------------------------------------------------------------------
#include "Sketcher_Object.hxx"
//------------------------------------------------------------------------------
#include <Standard_GUID.hxx>
#include <TDF_Label.hxx>
#include <TDF_Tool.hxx>
#include <TDocStd_Document.hxx>
#include <TDocStd_Owner.hxx>
#include <TDataStd_Integer.hxx>
#include <TDataStd_Real.hxx>
#include <TDataStd_UAttribute.hxx>
#include <TDataXtd_Plane.hxx>
#include <TNaming_Builder.hxx>
#include <TNaming_NamedShape.hxx>
#include <AIS_Shape.hxx>
#include <gp_Circ2d.hxx>
#include <gp_Pln.hxx>
#include <ElCLib.hxx>
#include <GeomAPI.hxx>
#include <Geom_Surface.hxx>
#include <Geom_CartesianPoint.hxx>
#include <Geom2d_CartesianPoint.hxx>
#include <Sketcher_Edge.hxx>
#include <Geom2d_Circle.hxx>
#include <Sketcher_Arc.hxx>
#include <Geom2d_BezierCurve.hxx>
#include <Geom2d_TrimmedCurve.hxx>
#include <TopoDS.hxx>
#include <TopoDS_Edge.hxx>
#include <BRep_Tool.hxx>
#include <BRepBuilderAPI_MakeEdge2d.hxx>
#include <BRepBuilderAPI_MakeEdge.hxx>
#include <BRepBuilderAPI_MakeVertex.hxx>
#include <TPrsStd_AISPresentation.hxx>
//------------------------------------------------------------------------------
#define GEOM2D_LABEL 1
#define GEOMTYPE_LABEL 2
#define METHOD_LABEL 3
#define TYPE_LABEL 4
//------------------------------------------------------------------------------
const Standard_GUID& Sketcher_Object::GetObjectID()
{
static Standard_GUID anObjectID("FF1BBB01-5D14-4df2-980B-DDDDDDDDDDDD");
return anObjectID;
}
//------------------------------------------------------------------------------
Handle(Sketcher_Object) Sketcher_Object::GetObject(TDF_Label& theLabel)
{
if (!theLabel.IsAttribute(GetObjectID()))
return NULL;
TCollection_AsciiString anEntry;
TDF_Tool::Entry(theLabel, anEntry);
Handle(TDocStd_Document) aDoc = TDocStd_Owner::GetDocument(theLabel.Data());
if (aDoc.IsNull())
return NULL;
return new Sketcher_Object(theLabel);
}
//------------------------------------------------------------------------------
Sketcher_Object::Sketcher_Object(const TDF_Label& theEntry)
:_Ax3(gp::XOY())
{
if (theEntry.IsAttribute(GetObjectID()))
_label = theEntry;
else
Standard_Failure::Raise("Label does not contain a valid Sketcher_Object");
}
//------------------------------------------------------------------------------
Sketcher_Object::Sketcher_Object(const TDF_Label& theEntry,
const Handle(Geom2d_Geometry)& theGeom2d_Geometry,
const Sketcher_ObjectGeometryType theGeometryType,
const Sketcher_ObjectTypeOfMethod theTypeOfMethod)
:_Ax3(gp::XOY())
{
_label = theEntry;
_geometry = theGeom2d_Geometry;
_label.ForgetAllAttributes(Standard_True);
TDataStd_UAttribute::Set(_label, GetObjectID());
TDataStd_Integer::Set(_label.FindChild(GEOMTYPE_LABEL), theGeometryType);
TDataStd_Integer::Set(_label.FindChild(METHOD_LABEL), theTypeOfMethod);
TDataStd_Integer::Set(_label.FindChild(TYPE_LABEL), MainSketcherType);
SaveGeometry(_geometry, theGeometryType);
}
//------------------------------------------------------------------------------
Sketcher_Object::~Sketcher_Object()
{
}
//------------------------------------------------------------------------------
void Sketcher_Object::Remove()
{
ErasePrs(Standard_True);
_label.ForgetAllAttributes(Standard_True);
}
//------------------------------------------------------------------------------
void Sketcher_Object::SetGeometry(const Handle(Geom2d_Geometry)& theGeom2d_Geometry)
{
_geometry = theGeom2d_Geometry;
_label.FindChild(GEOM2D_LABEL).ForgetAllAttributes(Standard_True);
SaveGeometry(_geometry, GetGeometryType());
if (HasPrs())
SaveUpdatePrs();
}
//------------------------------------------------------------------------------
Handle(Geom2d_Geometry) Sketcher_Object::GetGeometry()
{
if (!_geometry.IsNull())
return _geometry;
else {
TopoDS_Shape aShape;
TDF_Label aResultLabel = _label.FindChild(GEOM2D_LABEL);
Handle(TNaming_NamedShape) aNS;
if (!aResultLabel.FindAttribute(TNaming_NamedShape::GetID(), aNS))
return NULL;
Handle(Geom_Surface) surface;
TopLoc_Location location;
Standard_Real First, Last;
Handle_Geom2d_Curve aCrv;
BRep_Tool::CurveOnSurface(TopoDS::Edge(aNS->Get()), aCrv, surface,location,First,Last);
Sketcher_ObjectGeometryType theGeometryType = GetGeometryType();
if (theGeometryType == LineSketcherObject) {
Handle(Geom2d_Line) aLine = Handle(Geom2d_Line)::DownCast(aCrv);
Handle(Geom2d_TrimmedCurve) aTrm = new Geom2d_TrimmedCurve(aLine, First, Last);
Handle(Sketcher_Edge) anEdge = new Sketcher_Edge();
anEdge->SetPoints(aTrm->StartPoint(), aTrm->EndPoint());
_geometry = anEdge;
}
else if (theGeometryType == ArcSketcherObject) {
Handle(Geom2d_Circle) aCirc = Handle(Geom2d_Circle)::DownCast(aCrv);
Handle(Geom2d_TrimmedCurve) aTrm = new Geom2d_TrimmedCurve(aCirc, First, Last);
Handle(Sketcher_Arc) anArc = new Sketcher_Arc(aCirc->Circ2d());
gp_Pnt2d midPnt;
aTrm->D0(((Last - First) / 2.), midPnt);
anArc->SetParam(aTrm->StartPoint(), midPnt, aTrm->EndPoint());
_geometry = anArc;
}
else
_geometry = aCrv;
return _geometry;
}
}
//------------------------------------------------------------------------------
TopoDS_Shape Sketcher_Object::GetShape()
{
TopoDS_Shape aShape;
TDF_Label aResultLabel = _label.FindChild(GEOM2D_LABEL);
Handle(TNaming_NamedShape) aNS;
if (aResultLabel.FindAttribute(TNaming_NamedShape::GetID(), aNS))
aShape = aNS->Get();
return aShape;
}
//------------------------------------------------------------------------------
void Sketcher_Object::SaveGeometry(const Handle(Geom2d_Geometry)& theGeom2d_Geometry,const Sketcher_ObjectGeometryType theGeometryType)
{
TNaming_Builder aBuilder(_label.FindChild(GEOM2D_LABEL));
TopoDS_Shape aShp;
if (theGeometryType == PointSketcherObject) {
Handle(Geom2d_CartesianPoint) aPnt2d = Handle(Geom2d_CartesianPoint)::DownCast(theGeom2d_Geometry);
gp_Pnt a3dPnt(aPnt2d->X(), aPnt2d->Y(), 0.);
aShp = BRepBuilderAPI_MakeVertex(a3dPnt);
}
else if (theGeometryType == LineSketcherObject) {
Handle(Sketcher_Edge) anEdge = Handle(Sketcher_Edge)::DownCast(theGeom2d_Geometry);
Handle(Geom2d_TrimmedCurve) aTrm = new Geom2d_TrimmedCurve(anEdge, anEdge->StartParameter(), anEdge->EndParameter());
aShp = BRepBuilderAPI_MakeEdge2d(aTrm);
}
else if (theGeometryType == CircleSketcherObject) {
Handle(Geom2d_Circle) aCirc = Handle(Geom2d_Circle)::DownCast(theGeom2d_Geometry);
aShp = BRepBuilderAPI_MakeEdge2d(aCirc);
}
else if (theGeometryType == ArcSketcherObject) {
Handle(Sketcher_Arc) anArc = Handle(Sketcher_Arc)::DownCast(theGeom2d_Geometry);
Handle(Geom2d_TrimmedCurve) aTrm = new Geom2d_TrimmedCurve(anArc, anArc->FirstParameter(), anArc->LastParameter());
aShp = BRepBuilderAPI_MakeEdge2d(aTrm);
}
else if (theGeometryType == CurveSketcherObject) {
Handle(Geom2d_BezierCurve) aBez = Handle(Geom2d_BezierCurve)::DownCast(theGeom2d_Geometry);
aShp = BRepBuilderAPI_MakeEdge2d(aBez);
}
aBuilder.Generated(aShp);
}
//------------------------------------------------------------------------------
void Sketcher_Object::SetPlane(const gp_Ax3& theAx3)
{
_Ax3 = theAx3;
if (HasPrs())
SaveUpdatePrs();
}
//------------------------------------------------------------------------------
const gp_Ax3 Sketcher_Object::GetPlane()
{
return _Ax3;
}
//------------------------------------------------------------------------------
void Sketcher_Object::SetGeometryType(const Sketcher_ObjectGeometryType theGeometryType)
{
TDataStd_Integer::Set(_label.FindChild(GEOMTYPE_LABEL), theGeometryType);
}
//------------------------------------------------------------------------------
Sketcher_ObjectGeometryType Sketcher_Object::GetGeometryType()
{
Handle(TDataStd_Integer) aVal;
_label.FindChild(GEOMTYPE_LABEL).FindAttribute(TDataStd_Integer::GetID(),aVal);
return (Sketcher_ObjectGeometryType)aVal->Get();
}
//------------------------------------------------------------------------------
void Sketcher_Object::SetTypeOfMethod(const Sketcher_ObjectTypeOfMethod theTypeOfMethod)
{
TDataStd_Integer::Set(_label.FindChild(METHOD_LABEL), theTypeOfMethod);
}
//------------------------------------------------------------------------------
Sketcher_ObjectTypeOfMethod Sketcher_Object::GetTypeOfMethod()
{
Handle(TDataStd_Integer) aVal;
_label.FindChild(METHOD_LABEL).FindAttribute(TDataStd_Integer::GetID(),aVal);
return (Sketcher_ObjectTypeOfMethod)aVal->Get();
}
//------------------------------------------------------------------------------
void Sketcher_Object::SetType(const Sketcher_ObjectType theType)
{
TDataStd_Integer::Set(_label.FindChild(TYPE_LABEL), theType);
if (HasPrs())
SaveUpdatePrs();
}
//------------------------------------------------------------------------------
Sketcher_ObjectType Sketcher_Object::GetType()
{
Handle(TDataStd_Integer) aVal;
_label.FindChild(TYPE_LABEL).FindAttribute(TDataStd_Integer::GetID(),aVal);
return (Sketcher_ObjectType)aVal->Get();
}
//------------------------------------------------------------------------------
// GRAPHICS IMPLEMENTATION
Handle(AIS_InteractiveObject) Sketcher_Object::GetAIS_Object()
{
return Get_TPrsStd_AISPresentation()->GetAIS();
}
//------------------------------------------------------------------------------
Handle(TPrsStd_AISPresentation) Sketcher_Object::Get_TPrsStd_AISPresentation()
{
if (!HasPrs())
SaveUpdatePrs();
Handle(TPrsStd_AISPresentation) aPresentation;
_label.FindChild(GEOM2D_LABEL).FindAttribute(TPrsStd_AISPresentation::GetID(),aPresentation);
return aPresentation;
}
//------------------------------------------------------------------------------
void Sketcher_Object::DisplayPrs()
{
Get_TPrsStd_AISPresentation()->Display(Standard_False);
}
//------------------------------------------------------------------------------
void Sketcher_Object::ErasePrs(Standard_Boolean isRemove)
{
if (HasPrs()) {
Handle(TPrsStd_AISPresentation) aPresentation;
_label.FindChild(GEOM2D_LABEL).FindAttribute(TPrsStd_AISPresentation::GetID(),aPresentation);
aPresentation->Erase(isRemove);
if (isRemove)
_label.FindChild(GEOM2D_LABEL).ForgetAttribute(aPresentation);
}
}
//------------------------------------------------------------------------------
void Sketcher_Object::SaveUpdatePrs()
{
Handle(TPrsStd_AISPresentation) aPresentation = TPrsStd_AISPresentation::Set(_label.FindChild(GEOM2D_LABEL), TNaming_NamedShape::GetID());
gp_Trsf aTrs;
aTrs.SetDisplacement(gp::XOY(), GetPlane());
TopLoc_Location aLoc(aTrs);
aPresentation->Update();
aPresentation->GetAIS()->SetLocation(aLoc);
if (GetType() == AuxiliarySketcherType)
aPresentation->SetColor(Quantity_NOC_GRAY);
}
//------------------------------------------------------------------------------
bool Sketcher_Object::HasPrs()
{
Handle(TPrsStd_AISPresentation) aPresentation;
return (_label.FindChild(GEOM2D_LABEL).FindAttribute(TPrsStd_AISPresentation::GetID(),aPresentation));
}
//------------------------------------------------------------------------------
//------------------------------------------------------------------------------
IMPLEMENT_STANDARD_HANDLE(Sketcher_Object,MMgt_TShared)
IMPLEMENT_STANDARD_RTTI(Sketcher_Object)
IMPLEMENT_STANDARD_TYPE(Sketcher_Object)
IMPLEMENT_STANDARD_SUPERTYPE(MMgt_TShared)
IMPLEMENT_STANDARD_SUPERTYPE(Standard_Transient)
IMPLEMENT_STANDARD_SUPERTYPE_ARRAY()
IMPLEMENT_STANDARD_SUPERTYPE_ARRAY_ENTRY(MMgt_TShared)
IMPLEMENT_STANDARD_SUPERTYPE_ARRAY_ENTRY(Standard_Transient)
IMPLEMENT_STANDARD_SUPERTYPE_ARRAY_END()
IMPLEMENT_STANDARD_TYPE_END(Sketcher_Object)
//------------------------------------------------------------------------------
<|endoftext|>
|
<commit_before>/* Copyright (c) 2016 PaddlePaddle Authors. All Rights Reserved.
Licensed under the Apache License, Version 2.0 (the "License");
you may not use this file except in compliance with the License.
Indicesou 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 "paddle/fluid/framework/data_layout.h"
#include "paddle/fluid/framework/eigen.h"
#include "paddle/fluid/framework/op_registry.h"
namespace paddle {
namespace operators {
class AffineChannelOpMaker : public framework::OpProtoAndCheckerMaker {
public:
void Make() override {
AddInput("X",
"(Tensor) Feature map input can be a 4D tensor with order NCHW "
"or NHWC. It also can be a 2D tensor and C is the second "
"dimension.");
AddInput("Scale",
"(Tensor) 1D input of shape (C), the c-th element "
"is the scale factor of the affine transformation "
"for the c-th channel of the input.");
AddInput("Bias",
"(Tensor) 1D input of shape (C), the c-th element "
"is the bias of the affine transformation for the "
"c-th channel of the input.");
AddAttr<std::string>(
"data_layout",
"(string, default NCHW) Only used in "
"An optional string from: \"NHWC\", \"NCHW\". "
"Defaults to \"NHWC\". Specify the data format of the output data, "
"the input will be transformed automatically. ")
.SetDefault("AnyLayout");
AddOutput("Out", "(Tensor) A tensor of the same shape and order with X.");
AddComment(R"DOC(
Applies a separate affine transformation to each channel of the input. Useful
for replacing spatial batch norm with its equivalent fixed transformation.
The input also can be 2D tensor and applies a affine transformation in second
dimension.
$$Out = Scale*X + Bias$$
)DOC");
}
};
class AffineChannelOp : public framework::OperatorWithKernel {
public:
using framework::OperatorWithKernel::OperatorWithKernel;
void InferShape(framework::InferShapeContext* ctx) const override {
PADDLE_ENFORCE(ctx->HasInput("X"),
"Input(X) of AffineChannelOp should not be null.");
PADDLE_ENFORCE(ctx->HasInput("Scale"),
"Input(Scale) of AffineChannelOp should not be null.");
PADDLE_ENFORCE(ctx->HasInput("Bias"),
"Input(Bias) of AffineChannelOp should not be null.");
PADDLE_ENFORCE(ctx->HasOutput("Out"),
"Output(Out) of AffineChannelOp should not be null.");
ctx->SetOutputDim("Out", ctx->GetInputDim("X"));
ctx->ShareLoD("X", "Out");
}
};
class AffineChannelOpGrad : public framework::OperatorWithKernel {
public:
using framework::OperatorWithKernel::OperatorWithKernel;
void InferShape(framework::InferShapeContext* ctx) const override {
PADDLE_ENFORCE(ctx->HasInput(framework::GradVarName("Out")),
"Input(Out@GRAD) should not be null.");
if (ctx->HasOutput(framework::GradVarName("X"))) {
PADDLE_ENFORCE(ctx->HasInput("Scale"),
"Input(Scale) should not be null.");
ctx->SetOutputDim(framework::GradVarName("X"),
ctx->GetInputDim(framework::GradVarName("Out")));
}
if (ctx->HasOutput(framework::GradVarName("Scale"))) {
// Scale@GRAD and Bias@GRAD must exist at the same time.
PADDLE_ENFORCE(ctx->HasOutput(framework::GradVarName("Bias")),
"Output(Scale@GRAD) should not be null.");
PADDLE_ENFORCE(ctx->HasInput("X"), "Input(X) should not be null.");
ctx->SetOutputDim(framework::GradVarName("Scale"),
ctx->GetInputDim("Scale"));
ctx->SetOutputDim(framework::GradVarName("Bias"),
ctx->GetInputDim("Scale"));
}
}
};
template <typename T>
using EigenArrayMap =
Eigen::Map<Eigen::Array<T, Eigen::Dynamic, Eigen::Dynamic>>;
template <typename T>
using ConstEigenArrayMap =
Eigen::Map<const Eigen::Array<T, Eigen::Dynamic, Eigen::Dynamic>>;
template <typename T>
using EigenVectorArrayMap = Eigen::Map<Eigen::Array<T, Eigen::Dynamic, 1>>;
template <typename T>
using ConstEigenVectorArrayMap =
Eigen::Map<const Eigen::Array<T, Eigen::Dynamic, 1>>;
template <typename DeviceContext, typename T>
class AffineChannelKernel : public framework::OpKernel<T> {
public:
void Compute(const framework::ExecutionContext& ctx) const override {
auto* x = ctx.Input<framework::Tensor>("X");
auto* scale = ctx.Input<framework::Tensor>("Scale");
auto* bias = ctx.Input<framework::Tensor>("Bias");
auto* y = ctx.Output<framework::Tensor>("Out");
y->mutable_data<T>(ctx.GetPlace());
const framework::DataLayout layout =
framework::StringToDataLayout(ctx.Attr<std::string>("data_layout"));
auto dims = x->dims();
int N = dims[0];
int C = layout == framework::DataLayout::kNCHW ? dims[1]
: dims[dims.size() - 1];
int HxW = x->numel() / N / C;
auto* scale_d = scale->data<T>();
auto* bias_d = bias->data<T>();
ConstEigenVectorArrayMap<T> a_e(scale_d, C);
ConstEigenVectorArrayMap<T> b_e(bias_d, C);
auto* x_d = x->data<T>();
auto* y_d = y->data<T>();
if (layout == framework::DataLayout::kNCHW) {
int stride = C * HxW;
for (int i = 0; i < N; i++) {
ConstEigenArrayMap<T> x_e(x_d, HxW, C);
EigenArrayMap<T> y_e(y_d, HxW, C);
y_e = (x_e.rowwise() * a_e.transpose()).rowwise() + b_e.transpose();
x_d += stride;
y_d += stride;
}
} else {
int num = N * HxW;
ConstEigenArrayMap<T> x_e(x_d, C, num);
EigenArrayMap<T> y_e(y_d, C, num);
y_e = (x_e.colwise() * a_e).colwise() + b_e;
}
}
};
template <typename DeviceContext, typename T>
class AffineChannelGradKernel : public framework::OpKernel<T> {
public:
void Compute(const framework::ExecutionContext& ctx) const override {
auto* x = ctx.Input<framework::Tensor>("X");
auto* scale = ctx.Input<framework::Tensor>("Scale");
auto* dy = ctx.Input<framework::Tensor>(framework::GradVarName("Out"));
auto* dx = ctx.Output<framework::Tensor>(framework::GradVarName("X"));
auto* dscale =
ctx.Output<framework::Tensor>(framework::GradVarName("Scale"));
auto* dbias = ctx.Output<framework::Tensor>(framework::GradVarName("Bias"));
const framework::DataLayout layout =
framework::StringToDataLayout(ctx.Attr<std::string>("data_layout"));
auto dims = x->dims();
int N = dims[0];
int C = layout == framework::DataLayout::kNCHW ? dims[1]
: dims[dims.size() - 1];
int HxW = x->numel() / N / C;
auto* x_d = x->data<T>();
auto* dy_d = dy->data<T>();
auto* scale_d = scale->data<T>();
ConstEigenVectorArrayMap<T> scale_e(scale_d, C);
T* dx_d = dx ? dx->mutable_data<T>(ctx.GetPlace()) : nullptr;
T* dscale_d = dscale ? dscale->mutable_data<T>(ctx.GetPlace()) : nullptr;
T* dbias_d = dbias ? dbias->mutable_data<T>(ctx.GetPlace()) : nullptr;
EigenVectorArrayMap<T> dscale_e(dscale_d, C);
EigenVectorArrayMap<T> dbias_e(dbias_d, C);
if (layout == framework::DataLayout::kNCHW) {
// compute dx
int stride = C * HxW;
if (dx) {
for (int i = 0; i < N; i++) {
ConstEigenArrayMap<T> dy_e(dy_d, HxW, C);
EigenArrayMap<T> dx_e(dx_d, HxW, C);
dx_e = dy_e.rowwise() * scale_e.transpose();
dy_d += stride;
dx_d += stride;
}
}
// compute dscale and dbias
if (dscale && dbias) {
dy_d = dy->data<T>();
for (int i = 0; i < N; i++) {
ConstEigenArrayMap<T> x_e(x_d, HxW, C);
ConstEigenArrayMap<T> dy_e(dy_d, HxW, C);
if (i == 0) {
dscale_e = (x_e * dy_e).colwise().sum();
} else {
dscale_e += (x_e * dy_e).colwise().sum();
}
if (i == 0) {
dbias_e = dy_e.colwise().sum();
} else {
dbias_e += dy_e.colwise().sum();
}
x_d += stride;
dy_d += stride;
}
}
} else {
int num = N * HxW;
ConstEigenArrayMap<T> dy_e(dy_d, C, num);
// compute dx
if (dx) {
EigenArrayMap<T> dx_e(dx_d, C, num);
dx_e = dy_e.colwise() * scale_e;
}
// compute dscale and dbias
if (dscale && dbias) {
ConstEigenArrayMap<T> x_e(x_d, C, num);
dscale_e = (x_e * dy_e).rowwise().sum();
dbias_e = dy_e.rowwise().sum();
}
}
}
};
} // namespace operators
} // namespace paddle
namespace ops = paddle::operators;
using CPU = paddle::platform::CPUDeviceContext;
REGISTER_OPERATOR(affine_channel, ops::AffineChannelOp,
ops::AffineChannelOpMaker,
paddle::framework::DefaultGradOpDescMaker<true>);
REGISTER_OPERATOR(affine_channel_grad, ops::AffineChannelOpGrad);
REGISTER_OP_CPU_KERNEL(affine_channel, ops::AffineChannelKernel<CPU, float>,
ops::AffineChannelKernel<CPU, double>);
REGISTER_OP_CPU_KERNEL(affine_channel_grad,
ops::AffineChannelGradKernel<CPU, float>,
ops::AffineChannelGradKernel<CPU, double>);
<commit_msg>Enhance affine_channel_op infer-shape check (#16317)<commit_after>/* Copyright (c) 2016 PaddlePaddle Authors. All Rights Reserved.
Licensed under the Apache License, Version 2.0 (the "License");
you may not use this file except in compliance with the License.
Indicesou 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 "paddle/fluid/framework/data_layout.h"
#include "paddle/fluid/framework/eigen.h"
#include "paddle/fluid/framework/op_registry.h"
namespace paddle {
namespace operators {
class AffineChannelOpMaker : public framework::OpProtoAndCheckerMaker {
public:
void Make() override {
AddInput("X",
"(Tensor) Feature map input can be a 4D tensor with order NCHW "
"or NHWC. It also can be a 2D tensor and C is the second "
"dimension.");
AddInput("Scale",
"(Tensor) 1D input of shape (C), the c-th element "
"is the scale factor of the affine transformation "
"for the c-th channel of the input.");
AddInput("Bias",
"(Tensor) 1D input of shape (C), the c-th element "
"is the bias of the affine transformation for the "
"c-th channel of the input.");
AddAttr<std::string>(
"data_layout",
"(string, default NCHW) Only used in "
"An optional string from: \"NHWC\", \"NCHW\". "
"Defaults to \"NHWC\". Specify the data format of the output data, "
"the input will be transformed automatically. ")
.SetDefault("AnyLayout");
AddOutput("Out", "(Tensor) A tensor of the same shape and order with X.");
AddComment(R"DOC(
Applies a separate affine transformation to each channel of the input. Useful
for replacing spatial batch norm with its equivalent fixed transformation.
The input also can be 2D tensor and applies a affine transformation in second
dimension.
$$Out = Scale*X + Bias$$
)DOC");
}
};
class AffineChannelOp : public framework::OperatorWithKernel {
public:
using framework::OperatorWithKernel::OperatorWithKernel;
void InferShape(framework::InferShapeContext* ctx) const override {
PADDLE_ENFORCE(ctx->HasInput("X"),
"Input(X) of AffineChannelOp should not be null.");
PADDLE_ENFORCE(ctx->HasInput("Scale"),
"Input(Scale) of AffineChannelOp should not be null.");
PADDLE_ENFORCE(ctx->HasInput("Bias"),
"Input(Bias) of AffineChannelOp should not be null.");
PADDLE_ENFORCE(ctx->HasOutput("Out"),
"Output(Out) of AffineChannelOp should not be null.");
auto x_dims = ctx->GetInputDim("X");
auto scale_dims = ctx->GetInputDim("Scale");
auto b_dims = ctx->GetInputDim("Bias");
const framework::DataLayout data_layout = framework::StringToDataLayout(
ctx->Attrs().Get<std::string>("data_layout"));
const int64_t C = (data_layout == framework::DataLayout::kNCHW
? x_dims[1]
: x_dims[x_dims.size() - 1]);
PADDLE_ENFORCE_EQ(scale_dims.size(), 1UL);
PADDLE_ENFORCE_EQ(scale_dims[0], C);
PADDLE_ENFORCE_EQ(b_dims.size(), 1UL);
PADDLE_ENFORCE_EQ(b_dims[0], C);
ctx->SetOutputDim("Out", ctx->GetInputDim("X"));
ctx->ShareLoD("X", "Out");
}
};
class AffineChannelOpGrad : public framework::OperatorWithKernel {
public:
using framework::OperatorWithKernel::OperatorWithKernel;
void InferShape(framework::InferShapeContext* ctx) const override {
PADDLE_ENFORCE(ctx->HasInput(framework::GradVarName("Out")),
"Input(Out@GRAD) should not be null.");
if (ctx->HasOutput(framework::GradVarName("X"))) {
PADDLE_ENFORCE(ctx->HasInput("Scale"),
"Input(Scale) should not be null.");
ctx->SetOutputDim(framework::GradVarName("X"),
ctx->GetInputDim(framework::GradVarName("Out")));
}
if (ctx->HasOutput(framework::GradVarName("Scale"))) {
// Scale@GRAD and Bias@GRAD must exist at the same time.
PADDLE_ENFORCE(ctx->HasOutput(framework::GradVarName("Bias")),
"Output(Scale@GRAD) should not be null.");
PADDLE_ENFORCE(ctx->HasInput("X"), "Input(X) should not be null.");
ctx->SetOutputDim(framework::GradVarName("Scale"),
ctx->GetInputDim("Scale"));
ctx->SetOutputDim(framework::GradVarName("Bias"),
ctx->GetInputDim("Scale"));
}
}
};
template <typename T>
using EigenArrayMap =
Eigen::Map<Eigen::Array<T, Eigen::Dynamic, Eigen::Dynamic>>;
template <typename T>
using ConstEigenArrayMap =
Eigen::Map<const Eigen::Array<T, Eigen::Dynamic, Eigen::Dynamic>>;
template <typename T>
using EigenVectorArrayMap = Eigen::Map<Eigen::Array<T, Eigen::Dynamic, 1>>;
template <typename T>
using ConstEigenVectorArrayMap =
Eigen::Map<const Eigen::Array<T, Eigen::Dynamic, 1>>;
template <typename DeviceContext, typename T>
class AffineChannelKernel : public framework::OpKernel<T> {
public:
void Compute(const framework::ExecutionContext& ctx) const override {
auto* x = ctx.Input<framework::Tensor>("X");
auto* scale = ctx.Input<framework::Tensor>("Scale");
auto* bias = ctx.Input<framework::Tensor>("Bias");
auto* y = ctx.Output<framework::Tensor>("Out");
y->mutable_data<T>(ctx.GetPlace());
const framework::DataLayout layout =
framework::StringToDataLayout(ctx.Attr<std::string>("data_layout"));
auto dims = x->dims();
int N = dims[0];
int C = layout == framework::DataLayout::kNCHW ? dims[1]
: dims[dims.size() - 1];
int HxW = x->numel() / N / C;
auto* scale_d = scale->data<T>();
auto* bias_d = bias->data<T>();
ConstEigenVectorArrayMap<T> a_e(scale_d, C);
ConstEigenVectorArrayMap<T> b_e(bias_d, C);
auto* x_d = x->data<T>();
auto* y_d = y->data<T>();
if (layout == framework::DataLayout::kNCHW) {
int stride = C * HxW;
for (int i = 0; i < N; i++) {
ConstEigenArrayMap<T> x_e(x_d, HxW, C);
EigenArrayMap<T> y_e(y_d, HxW, C);
y_e = (x_e.rowwise() * a_e.transpose()).rowwise() + b_e.transpose();
x_d += stride;
y_d += stride;
}
} else {
int num = N * HxW;
ConstEigenArrayMap<T> x_e(x_d, C, num);
EigenArrayMap<T> y_e(y_d, C, num);
y_e = (x_e.colwise() * a_e).colwise() + b_e;
}
}
};
template <typename DeviceContext, typename T>
class AffineChannelGradKernel : public framework::OpKernel<T> {
public:
void Compute(const framework::ExecutionContext& ctx) const override {
auto* x = ctx.Input<framework::Tensor>("X");
auto* scale = ctx.Input<framework::Tensor>("Scale");
auto* dy = ctx.Input<framework::Tensor>(framework::GradVarName("Out"));
auto* dx = ctx.Output<framework::Tensor>(framework::GradVarName("X"));
auto* dscale =
ctx.Output<framework::Tensor>(framework::GradVarName("Scale"));
auto* dbias = ctx.Output<framework::Tensor>(framework::GradVarName("Bias"));
const framework::DataLayout layout =
framework::StringToDataLayout(ctx.Attr<std::string>("data_layout"));
auto dims = x->dims();
int N = dims[0];
int C = layout == framework::DataLayout::kNCHW ? dims[1]
: dims[dims.size() - 1];
int HxW = x->numel() / N / C;
auto* x_d = x->data<T>();
auto* dy_d = dy->data<T>();
auto* scale_d = scale->data<T>();
ConstEigenVectorArrayMap<T> scale_e(scale_d, C);
T* dx_d = dx ? dx->mutable_data<T>(ctx.GetPlace()) : nullptr;
T* dscale_d = dscale ? dscale->mutable_data<T>(ctx.GetPlace()) : nullptr;
T* dbias_d = dbias ? dbias->mutable_data<T>(ctx.GetPlace()) : nullptr;
EigenVectorArrayMap<T> dscale_e(dscale_d, C);
EigenVectorArrayMap<T> dbias_e(dbias_d, C);
if (layout == framework::DataLayout::kNCHW) {
// compute dx
int stride = C * HxW;
if (dx) {
for (int i = 0; i < N; i++) {
ConstEigenArrayMap<T> dy_e(dy_d, HxW, C);
EigenArrayMap<T> dx_e(dx_d, HxW, C);
dx_e = dy_e.rowwise() * scale_e.transpose();
dy_d += stride;
dx_d += stride;
}
}
// compute dscale and dbias
if (dscale && dbias) {
dy_d = dy->data<T>();
for (int i = 0; i < N; i++) {
ConstEigenArrayMap<T> x_e(x_d, HxW, C);
ConstEigenArrayMap<T> dy_e(dy_d, HxW, C);
if (i == 0) {
dscale_e = (x_e * dy_e).colwise().sum();
} else {
dscale_e += (x_e * dy_e).colwise().sum();
}
if (i == 0) {
dbias_e = dy_e.colwise().sum();
} else {
dbias_e += dy_e.colwise().sum();
}
x_d += stride;
dy_d += stride;
}
}
} else {
int num = N * HxW;
ConstEigenArrayMap<T> dy_e(dy_d, C, num);
// compute dx
if (dx) {
EigenArrayMap<T> dx_e(dx_d, C, num);
dx_e = dy_e.colwise() * scale_e;
}
// compute dscale and dbias
if (dscale && dbias) {
ConstEigenArrayMap<T> x_e(x_d, C, num);
dscale_e = (x_e * dy_e).rowwise().sum();
dbias_e = dy_e.rowwise().sum();
}
}
}
};
} // namespace operators
} // namespace paddle
namespace ops = paddle::operators;
using CPU = paddle::platform::CPUDeviceContext;
REGISTER_OPERATOR(affine_channel, ops::AffineChannelOp,
ops::AffineChannelOpMaker,
paddle::framework::DefaultGradOpDescMaker<true>);
REGISTER_OPERATOR(affine_channel_grad, ops::AffineChannelOpGrad);
REGISTER_OP_CPU_KERNEL(affine_channel, ops::AffineChannelKernel<CPU, float>,
ops::AffineChannelKernel<CPU, double>);
REGISTER_OP_CPU_KERNEL(affine_channel_grad,
ops::AffineChannelGradKernel<CPU, float>,
ops::AffineChannelGradKernel<CPU, double>);
<|endoftext|>
|
<commit_before>#include <iostream>
#include <fstream>
#include <cctype>
#include <string>
#include <vector>
using namespace std;
int main(int argc, char *argv[])
{
if(argc==1) //quit if no argument
{
cerr<<"Usage: "<<argv[0]<<" filename[s]\n";
exit(EXIT_FAILURE);
}
string str;
for(int file=1;file<argc;file++)
{
ifstream fin; //open stream
fin.open(argv[file]);
getline(fin , str)
fin.clear();
fin.close();
}
for(auto it = str.begin(); it != str.end() ; ++it)
*it = toupper(*it); //将当前字符改成大写形式
cout<<str<<endl;
return 0;
}<commit_msg>amend ex3_22.cpp<commit_after>#include <iostream>
#include <fstream>
#include <cctype>
#include <string>
using namespace std;
int main(int argc, char *argv[])
{
if(argc==1) //quit if no argument
{
cerr<<"Usage: "<<argv[0]<<" filename[s]\n";
exit(EXIT_FAILURE);
}
string str;
for(int file=1;file<argc;file++)
{
ifstream fin; //open stream
fin.open(argv[file]);
getline(fin , str);
fin.clear();
fin.close();
}
for(auto it = str.begin(); it != str.end() ; ++it)
*it = toupper(*it); //将当前字符改成大写形式
cout<<str<<endl;
return 0;
}<|endoftext|>
|
<commit_before>/*
* Copyright (c) 2014, Ford Motor Company
* 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 Ford Motor Company 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.
*/
#include <string.h>
#include "utils/macro.h"
#include "application_manager/mobile_message_handler.h"
#include "protocol_handler/protocol_payload.h"
#include "protocol_handler/protocol_packet.h"
#include "utils/bitstream.h"
#include "utils/logger.h"
#include <stdint.h>
#include <memory>
#include <string>
namespace {
const uint8_t kRequest = 0x0;
const uint8_t kResponse = 0x1;
const uint8_t kNotification = 0x2;
const uint8_t kUnknown = 0xF;
}
namespace application_manager {
using protocol_handler::Extract;
namespace {
typedef std::map<MessageType, std::string> MessageTypeMap;
MessageTypeMap messageTypes = {
std::make_pair(kRequest, "Request"),
std::make_pair(kResponse, "Response"),
std::make_pair(kNotification, "Notification")
};
}
CREATE_LOGGERPTR_GLOBAL(logger_, "MobileMessageHandler")
application_manager::Message* MobileMessageHandler::HandleIncomingMessageProtocol(
const protocol_handler::RawMessagePtr message) {
application_manager::Message* out_message = NULL;
if (message->protocol_version() == ProtocolVersion::kV1) {
out_message = MobileMessageHandler::HandleIncomingMessageProtocolV1(message);
} else if ((message->protocol_version() == ProtocolVersion::kV2) ||
(message->protocol_version() == ProtocolVersion::kV3) ||
(message->protocol_version() == ProtocolVersion::kV4)) {
out_message = MobileMessageHandler::HandleIncomingMessageProtocolV2(message);
} else {
return NULL;
}
LOG4CXX_DEBUG(logger_, "Incoming RPC_INFO: " <<
(out_message->connection_key() >> 16) <<", "<<
messageTypes[out_message->type()] <<", "<<
out_message->function_id() << ", " <<
out_message->correlation_id() << ", " <<
out_message->json_message());
return out_message;
}
protocol_handler::RawMessage* MobileMessageHandler::HandleOutgoingMessageProtocol(
const MobileMessage& message) {
LOG4CXX_DEBUG(logger_, "Outgoing RPC_INFO: " <<
(message->connection_key() >> 16) <<", "<<
messageTypes[message->type()]<<", "<<
message->function_id() << ", " <<
message->correlation_id() << ", " <<
message->json_message());
if (message->protocol_version() == application_manager::kV1) {
return MobileMessageHandler::HandleOutgoingMessageProtocolV1(message);
}
if ((message->protocol_version() == application_manager::kV2) ||
(message->protocol_version() == application_manager::kV3) ||
(message->protocol_version() == application_manager::kV4)) {
return MobileMessageHandler::HandleOutgoingMessageProtocolV2(message);
}
return NULL;
}
application_manager::Message*
MobileMessageHandler::HandleIncomingMessageProtocolV1(
const ::protocol_handler::RawMessagePtr message) {
LOG4CXX_INFO(logger_,
"MobileMessageHandler HandleIncomingMessageProtocolV1()");
application_manager::Message* outgoing_message =
new application_manager::Message(
protocol_handler::MessagePriority::FromServiceType(
message->service_type())
);
if (!message) {
NOTREACHED();
return NULL;
}
outgoing_message->set_connection_key(message->connection_key());
outgoing_message->set_protocol_version(
static_cast<application_manager::ProtocolVersion>(message
->protocol_version()));
outgoing_message->set_json_message(
std::string(reinterpret_cast<const char*>(message->data()),
message->data_size()));
if (outgoing_message->json_message().empty()) {
delete outgoing_message;
return NULL;
}
return outgoing_message;
}
application_manager::Message*
MobileMessageHandler::HandleIncomingMessageProtocolV2(
const ::protocol_handler::RawMessagePtr message) {
LOG4CXX_INFO(logger_,
"MobileMessageHandler HandleIncomingMessageProtocolV2()");
utils::BitStream message_bytestream(message->data(), message->data_size());
protocol_handler::ProtocolPayloadV2 payload;
protocol_handler::Extract(&message_bytestream, &payload,
message->data_size());
// Silently drop message if it wasn't parsed correctly
if (message_bytestream.IsBad()) {
LOG4CXX_WARN(logger_,
"Drop ill-formed message from mobile, partially parsed: "
<< payload);
return NULL;
}
std::auto_ptr<application_manager::Message> outgoing_message(
new application_manager::Message(
protocol_handler::MessagePriority::FromServiceType(
message->service_type())));
outgoing_message->set_json_message(payload.json);
outgoing_message->set_function_id(payload.header.rpc_function_id);
outgoing_message->set_message_type(
MessageTypeFromRpcType(payload.header.rpc_type));
outgoing_message->set_correlation_id(int32_t(payload.header.correlation_id));
outgoing_message->set_connection_key(message->connection_key());
outgoing_message->set_protocol_version(
static_cast<application_manager::ProtocolVersion>(message
->protocol_version()));
outgoing_message->set_data_size(message->data_size());
outgoing_message->set_payload_size(message->payload_size());
if (!payload.data.empty()) {
outgoing_message->set_binary_data(
new application_manager::BinaryData(payload.data));
}
return outgoing_message.release();
}
protocol_handler::RawMessage*
MobileMessageHandler::HandleOutgoingMessageProtocolV1(
const MobileMessage& message) {
LOG4CXX_INFO(logger_,
"MobileMessageHandler HandleOutgoingMessageProtocolV1()");
std::string messageString = message->json_message();
if (messageString.length() == 0) {
LOG4CXX_INFO(logger_,
"Drop ill-formed message from mobile");
return NULL;
}
uint8_t* rawMessage = new uint8_t[messageString.length() + 1];
memcpy(rawMessage, messageString.c_str(), messageString.length() + 1);
protocol_handler::RawMessage* result = new protocol_handler::RawMessage(
message->connection_key(), 1, rawMessage, messageString.length() + 1);
delete [] rawMessage;
return result;
}
protocol_handler::RawMessage*
MobileMessageHandler::HandleOutgoingMessageProtocolV2(
const MobileMessage& message) {
LOG4CXX_INFO(logger_,
"MobileMessageHandler HandleOutgoingMessageProtocolV2()");
if (message->json_message().length() == 0) {
LOG4CXX_ERROR(logger_, "json string is empty.");
}
uint32_t jsonSize = message->json_message().length();
uint32_t binarySize = 0;
if (message->has_binary_data()) {
binarySize = message->binary_data()->size();
}
const size_t dataForSendingSize =
protocol_handler::PROTOCOL_HEADER_V2_SIZE + jsonSize + binarySize;
uint8_t* dataForSending = new uint8_t[dataForSendingSize];
uint8_t offset = 0;
uint8_t rpcTypeFlag = 0;
switch (message->type()) {
case application_manager::kRequest:
rpcTypeFlag = kRequest;
break;
case application_manager::kResponse:
rpcTypeFlag = kResponse;
break;
case application_manager::kNotification:
rpcTypeFlag = kNotification;
break;
default:
NOTREACHED();
break;
}
uint32_t functionId = message->function_id();
dataForSending[offset++] = ((rpcTypeFlag << 4) & 0xF0) | (functionId >> 24);
dataForSending[offset++] = functionId >> 16;
dataForSending[offset++] = functionId >> 8;
dataForSending[offset++] = functionId;
uint32_t correlationId = message->correlation_id();
dataForSending[offset++] = correlationId >> 24;
dataForSending[offset++] = correlationId >> 16;
dataForSending[offset++] = correlationId >> 8;
dataForSending[offset++] = correlationId;
dataForSending[offset++] = jsonSize >> 24;
dataForSending[offset++] = jsonSize >> 16;
dataForSending[offset++] = jsonSize >> 8;
dataForSending[offset++] = jsonSize;
memcpy(dataForSending + offset, message->json_message().c_str(), jsonSize);
if (message->has_binary_data()) {
const std::vector<uint8_t>& binaryData = *(message->binary_data());
uint8_t* currentPointer = dataForSending + offset + jsonSize;
for (uint32_t i = 0; i < binarySize; ++i) {
currentPointer[i] = binaryData[i];
}
}
protocol_handler::RawMessage* msgToProtocolHandler =
new protocol_handler::RawMessage(message->connection_key(),
message->protocol_version(),
dataForSending,
dataForSendingSize);
delete [] dataForSending;
return msgToProtocolHandler;
}
} // namespace application_manager
<commit_msg>Fix core dump when try access to fields of incorrect message<commit_after>/*
* Copyright (c) 2014, Ford Motor Company
* 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 Ford Motor Company 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.
*/
#include <string.h>
#include "utils/macro.h"
#include "application_manager/mobile_message_handler.h"
#include "protocol_handler/protocol_payload.h"
#include "protocol_handler/protocol_packet.h"
#include "utils/bitstream.h"
#include "utils/logger.h"
#include <stdint.h>
#include <memory>
#include <string>
namespace {
const uint8_t kRequest = 0x0;
const uint8_t kResponse = 0x1;
const uint8_t kNotification = 0x2;
const uint8_t kUnknown = 0xF;
}
namespace application_manager {
using protocol_handler::Extract;
namespace {
typedef std::map<MessageType, std::string> MessageTypeMap;
MessageTypeMap messageTypes = {
std::make_pair(kRequest, "Request"),
std::make_pair(kResponse, "Response"),
std::make_pair(kNotification, "Notification")
};
}
CREATE_LOGGERPTR_GLOBAL(logger_, "MobileMessageHandler")
application_manager::Message* MobileMessageHandler::HandleIncomingMessageProtocol(
const protocol_handler::RawMessagePtr message) {
DCHECK_OR_RETURN(message, NULL);
application_manager::Message* out_message = NULL;
switch (message->protocol_version()) {
case ProtocolVersion::kV1:
LOG4CXX_DEBUG(logger_, "Protocol version - V1");
out_message = MobileMessageHandler::HandleIncomingMessageProtocolV1(message);
break;
case ProtocolVersion::kV2:
LOG4CXX_DEBUG(logger_, "Protocol version - V2");
out_message = MobileMessageHandler::HandleIncomingMessageProtocolV2(message);
break;
case ProtocolVersion::kV3:
LOG4CXX_DEBUG(logger_, "Protocol version - V3");
out_message = MobileMessageHandler::HandleIncomingMessageProtocolV2(message);
break;
case ProtocolVersion::kV4:
LOG4CXX_DEBUG(logger_, "Protocol version - V4");
out_message = MobileMessageHandler::HandleIncomingMessageProtocolV2(message);
break;
default:
LOG4CXX_WARN(logger_, "Can't recognise protocol version");
out_message = NULL;
break;
}
if (out_message == NULL) {
LOG4CXX_WARN(logger_, "Message is NULL");
return NULL;
}
LOG4CXX_DEBUG(logger_, "Incoming RPC_INFO: " <<
(out_message->connection_key() >> 16) <<", "<<
messageTypes[out_message->type()] <<", "<<
out_message->function_id() << ", " <<
out_message->correlation_id() << ", " <<
out_message->json_message());
return out_message;
}
protocol_handler::RawMessage* MobileMessageHandler::HandleOutgoingMessageProtocol(
const MobileMessage& message) {
LOG4CXX_DEBUG(logger_, "Outgoing RPC_INFO: " <<
(message->connection_key() >> 16) <<", "<<
messageTypes[message->type()]<<", "<<
message->function_id() << ", " <<
message->correlation_id() << ", " <<
message->json_message());
if (message->protocol_version() == application_manager::kV1) {
return MobileMessageHandler::HandleOutgoingMessageProtocolV1(message);
}
if ((message->protocol_version() == application_manager::kV2) ||
(message->protocol_version() == application_manager::kV3) ||
(message->protocol_version() == application_manager::kV4)) {
return MobileMessageHandler::HandleOutgoingMessageProtocolV2(message);
}
return NULL;
}
application_manager::Message*
MobileMessageHandler::HandleIncomingMessageProtocolV1(
const ::protocol_handler::RawMessagePtr message) {
LOG4CXX_AUTO_TRACE(logger_);
application_manager::Message* outgoing_message =
new application_manager::Message(
protocol_handler::MessagePriority::FromServiceType(
message->service_type())
);
if (!message) {
NOTREACHED();
return NULL;
}
outgoing_message->set_connection_key(message->connection_key());
outgoing_message->set_protocol_version(
static_cast<application_manager::ProtocolVersion>(message
->protocol_version()));
outgoing_message->set_json_message(
std::string(reinterpret_cast<const char*>(message->data()),
message->data_size()));
if (outgoing_message->json_message().empty()) {
delete outgoing_message;
return NULL;
}
return outgoing_message;
}
application_manager::Message*
MobileMessageHandler::HandleIncomingMessageProtocolV2(
const ::protocol_handler::RawMessagePtr message) {
LOG4CXX_AUTO_TRACE(logger_);
utils::BitStream message_bytestream(message->data(), message->data_size());
protocol_handler::ProtocolPayloadV2 payload;
protocol_handler::Extract(&message_bytestream, &payload,
message->data_size());
// Silently drop message if it wasn't parsed correctly
if (message_bytestream.IsBad()) {
LOG4CXX_WARN(logger_,
"Drop ill-formed message from mobile, partially parsed: "
<< payload);
return NULL;
}
std::auto_ptr<application_manager::Message> outgoing_message(
new application_manager::Message(
protocol_handler::MessagePriority::FromServiceType(
message->service_type())));
outgoing_message->set_json_message(payload.json);
outgoing_message->set_function_id(payload.header.rpc_function_id);
outgoing_message->set_message_type(
MessageTypeFromRpcType(payload.header.rpc_type));
outgoing_message->set_correlation_id(int32_t(payload.header.correlation_id));
outgoing_message->set_connection_key(message->connection_key());
outgoing_message->set_protocol_version(
static_cast<application_manager::ProtocolVersion>(message
->protocol_version()));
outgoing_message->set_data_size(message->data_size());
outgoing_message->set_payload_size(message->payload_size());
if (!payload.data.empty()) {
outgoing_message->set_binary_data(
new application_manager::BinaryData(payload.data));
}
return outgoing_message.release();
}
protocol_handler::RawMessage*
MobileMessageHandler::HandleOutgoingMessageProtocolV1(
const MobileMessage& message) {
LOG4CXX_INFO(logger_,
"MobileMessageHandler HandleOutgoingMessageProtocolV1()");
std::string messageString = message->json_message();
if (messageString.length() == 0) {
LOG4CXX_INFO(logger_,
"Drop ill-formed message from mobile");
return NULL;
}
uint8_t* rawMessage = new uint8_t[messageString.length() + 1];
memcpy(rawMessage, messageString.c_str(), messageString.length() + 1);
protocol_handler::RawMessage* result = new protocol_handler::RawMessage(
message->connection_key(), 1, rawMessage, messageString.length() + 1);
delete [] rawMessage;
return result;
}
protocol_handler::RawMessage*
MobileMessageHandler::HandleOutgoingMessageProtocolV2(
const MobileMessage& message) {
LOG4CXX_INFO(logger_,
"MobileMessageHandler HandleOutgoingMessageProtocolV2()");
if (message->json_message().length() == 0) {
LOG4CXX_ERROR(logger_, "json string is empty.");
}
uint32_t jsonSize = message->json_message().length();
uint32_t binarySize = 0;
if (message->has_binary_data()) {
binarySize = message->binary_data()->size();
}
const size_t dataForSendingSize =
protocol_handler::PROTOCOL_HEADER_V2_SIZE + jsonSize + binarySize;
uint8_t* dataForSending = new uint8_t[dataForSendingSize];
uint8_t offset = 0;
uint8_t rpcTypeFlag = 0;
switch (message->type()) {
case application_manager::kRequest:
rpcTypeFlag = kRequest;
break;
case application_manager::kResponse:
rpcTypeFlag = kResponse;
break;
case application_manager::kNotification:
rpcTypeFlag = kNotification;
break;
default:
NOTREACHED();
break;
}
uint32_t functionId = message->function_id();
dataForSending[offset++] = ((rpcTypeFlag << 4) & 0xF0) | (functionId >> 24);
dataForSending[offset++] = functionId >> 16;
dataForSending[offset++] = functionId >> 8;
dataForSending[offset++] = functionId;
uint32_t correlationId = message->correlation_id();
dataForSending[offset++] = correlationId >> 24;
dataForSending[offset++] = correlationId >> 16;
dataForSending[offset++] = correlationId >> 8;
dataForSending[offset++] = correlationId;
dataForSending[offset++] = jsonSize >> 24;
dataForSending[offset++] = jsonSize >> 16;
dataForSending[offset++] = jsonSize >> 8;
dataForSending[offset++] = jsonSize;
memcpy(dataForSending + offset, message->json_message().c_str(), jsonSize);
if (message->has_binary_data()) {
const std::vector<uint8_t>& binaryData = *(message->binary_data());
uint8_t* currentPointer = dataForSending + offset + jsonSize;
for (uint32_t i = 0; i < binarySize; ++i) {
currentPointer[i] = binaryData[i];
}
}
protocol_handler::RawMessage* msgToProtocolHandler =
new protocol_handler::RawMessage(message->connection_key(),
message->protocol_version(),
dataForSending,
dataForSendingSize);
delete [] dataForSending;
return msgToProtocolHandler;
}
} // namespace application_manager
<|endoftext|>
|
<commit_before>/*
* qihdr.cpp
*
* Created by Tobias Wood on 11/06/2015.
* Copyright (c) 2015 Tobias Wood.
*
* 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 <iostream>
#include "itkMetaDataObject.h"
#include "QI/IO.h"
#include "QI/Args.h"
#include "QI/Util.h"
args::ArgumentParser parser(
"Extracts information from image headers.\n"
"By default, a summary of the header is printed. If any options are specified,"
"only those parts of the header will be printed. Multiple files can be input"
"in which case the header info is written for each in order.\n"
"http://github.com/spinicist/QUIT");
args::PositionalList<std::string> filenames(parser, "FILES", "Input files");
args::HelpFlag help(parser, "HELP", "Show this help menu", {'h', "help"});
args::Flag verbose(parser, "VERBOSE", "Print description of each output line", {'v', "verbose"});
args::Flag print_direction(parser, "DIRECTION", "Print the image direction/orientation", {'d', "direction"});
args::Flag print_origin(parser, "ORIGIN", "Print the the origin", {'o', "origin"});
args::ValueFlag<int> print_spacing(parser, "SPACING", "Print voxel spacing (can specify one dimension)", {'S',"spacing"});
args::ValueFlag<int> print_size(parser, "SIZE", "Print the matrix size (can specify one dimension)", {'s',"size"});
args::Flag print_voxvol(parser, "VOLUME", "Calculate and print the volume of one voxel", {'v',"voxvol"});
args::Flag print_type(parser, "DTYPE", "Print the data type",{'T',"dtype"});
args::Flag print_dims(parser, "DIMS", "Print the number of dimensions",{'D',"dims"});
args::Flag dim3(parser, "3D", "Treat input as 3D (discard higher dimensions)", {'3',"3D"});
args::ValueFlagList<std::string> header_fields(parser, "METADATA", "Print a header metadata field (can be specified multiple times)", {'m', "meta"});
//******************************************************************************
// Main
//******************************************************************************
int main(int argc, char **argv) {
QI::ParseArgs(parser, argc, argv);
bool print_all = !(print_direction || print_origin || print_spacing || print_size ||
print_voxvol || print_type || print_dims || header_fields);
for (const std::string& fname : QI::CheckList(filenames)) {
itk::ImageIOBase::Pointer imageIO = itk::ImageIOFactory::CreateImageIO(fname.c_str(), itk::ImageIOFactory::ReadMode);
if (!imageIO) {
std::cerr << "Could not open: " << std::string(fname) << std::endl;
break;
}
imageIO->SetFileName(std::string(fname));
imageIO->ReadImageInformation();
size_t dims = imageIO->GetNumberOfDimensions();
if (verbose) std::cout << "File: " << std::string(fname) << std::endl;
if (print_all || verbose) std::cout << "Dimension: "; if (print_all || print_dims) std::cout << dims << std::endl;
if (print_all || verbose) std::cout << "Voxel Type: ";
if (print_all || print_type) {
std::cout << imageIO->GetPixelTypeAsString(imageIO->GetPixelType()) << " "
<< imageIO->GetComponentTypeAsString(imageIO->GetComponentType()) << std::endl;
}
if (dim3 && dims > 3) dims = 3;
if (print_all || print_size) {
if (print_size.Get() < 0 || print_size.Get() > dims) {
if (verbose) std::cerr << "Invalid dimension " << print_size.Get() << " for image " << fname << std::endl;
} else {
int start_dim, end_dim;
if (print_size.Get() == 0) {
start_dim = 0; end_dim = dims;
} else {
start_dim = print_size.Get() - 1;
end_dim = print_size.Get();
}
if (print_all || verbose) std::cout << "Size: "; if (print_all || print_size) { for (int i = start_dim; i < end_dim; i++) std::cout << imageIO->GetDimensions(i) << "\t"; std::cout << std::endl; }
}
}
if (print_all || print_spacing) {
if (print_spacing.Get() < 0 || print_spacing.Get() > dims) {
if (verbose) std::cerr << "Invalid dimension " << print_spacing.Get() << " for image " << fname << std::endl;
} else {
int start_dim, end_dim;
if (print_spacing.Get() == 0) {
start_dim = 0; end_dim = dims;
} else {
start_dim = print_spacing.Get() - 1;
end_dim = print_spacing.Get();
}
if (print_all || verbose) std::cout << "Spacing: "; if (print_all || print_spacing) { for (int i = start_dim; i < end_dim; i++) std::cout << imageIO->GetSpacing(i) << "\t"; std::cout << std::endl; }
}
}
if (print_all || verbose) std::cout << "Origin: "; if (print_all || print_origin) { for (int i = 0; i < dims; i++) std::cout << imageIO->GetOrigin(i) << "\t"; std::cout << std::endl; }
if (print_all || verbose) std::cout << "Direction: " << std::endl;
if (print_all | print_direction) {
for (int i = 0; i < dims; i++) {
std::vector<double> dir = imageIO->GetDirection(i);
for (int j = 0; j < dims; j++)
std::cout << dir[j] << "\t";
std::cout << std::endl;
}
}
if (print_all || verbose) std::cout << "Voxel vol: "; if (print_all || print_voxvol) { double vol = imageIO->GetSpacing(0); for (int i = 1; i < dims; i++) vol *= imageIO->GetSpacing(i); std::cout << vol << std::endl; }
for (const std::string &hf : header_fields.Get()) {
auto header = imageIO->GetMetaDataDictionary();
if (header.HasKey(hf)) {
std::vector<std::string> string_array_value;
std::vector<std::vector<double> > double_array_array_value;
std::vector<double> double_array_value;
std::string string_value;
auto delim = "";
double double_value;
if (verbose) std::cout << hf << ": ";
if (ExposeMetaData(header, hf, string_array_value)) {
std::cout << string_array_value << std::endl;
} else if (ExposeMetaData(header, hf, double_array_value)) {
std::cout << double_array_value << std::endl;
} else if (ExposeMetaData(header, hf, double_array_array_value)) {
std::cout << double_array_array_value << std::endl;
} else if (ExposeMetaData(header, hf, string_value)) {
std::cout << string_value << std::endl;
} else if (ExposeMetaData(header, hf, double_value)) {
std::cout << double_value << std::endl;
} else {
QI_EXCEPTION("Could not determine type of rename header field:" << hf);
}
} else {
if (verbose) std::cout << "Header field not found: " << hf << std::endl;
}
}
}
return EXIT_SUCCESS;
}
<commit_msg>ENH: Added string arrays of arrays<commit_after>/*
* qihdr.cpp
*
* Created by Tobias Wood on 11/06/2015.
* Copyright (c) 2015 Tobias Wood.
*
* 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 <iostream>
#include "itkMetaDataObject.h"
#include "QI/IO.h"
#include "QI/Args.h"
#include "QI/Util.h"
args::ArgumentParser parser(
"Extracts information from image headers.\n"
"By default, a summary of the header is printed. If any options are specified,"
"only those parts of the header will be printed. Multiple files can be input"
"in which case the header info is written for each in order.\n"
"http://github.com/spinicist/QUIT");
args::PositionalList<std::string> filenames(parser, "FILES", "Input files");
args::HelpFlag help(parser, "HELP", "Show this help menu", {'h', "help"});
args::Flag verbose(parser, "VERBOSE", "Print description of each output line", {'v', "verbose"});
args::Flag print_direction(parser, "DIRECTION", "Print the image direction/orientation", {'d', "direction"});
args::Flag print_origin(parser, "ORIGIN", "Print the the origin", {'o', "origin"});
args::ValueFlag<int> print_spacing(parser, "SPACING", "Print voxel spacing (can specify one dimension)", {'S',"spacing"});
args::ValueFlag<int> print_size(parser, "SIZE", "Print the matrix size (can specify one dimension)", {'s',"size"});
args::Flag print_voxvol(parser, "VOLUME", "Calculate and print the volume of one voxel", {'v',"voxvol"});
args::Flag print_type(parser, "DTYPE", "Print the data type",{'T',"dtype"});
args::Flag print_dims(parser, "DIMS", "Print the number of dimensions",{'D',"dims"});
args::Flag dim3(parser, "3D", "Treat input as 3D (discard higher dimensions)", {'3',"3D"});
args::ValueFlagList<std::string> header_fields(parser, "METADATA", "Print a header metadata field (can be specified multiple times)", {'m', "meta"});
//******************************************************************************
// Main
//******************************************************************************
int main(int argc, char **argv) {
QI::ParseArgs(parser, argc, argv);
bool print_all = !(print_direction || print_origin || print_spacing || print_size ||
print_voxvol || print_type || print_dims || header_fields);
for (const std::string& fname : QI::CheckList(filenames)) {
itk::ImageIOBase::Pointer imageIO = itk::ImageIOFactory::CreateImageIO(fname.c_str(), itk::ImageIOFactory::ReadMode);
if (!imageIO) {
std::cerr << "Could not open: " << std::string(fname) << std::endl;
break;
}
imageIO->SetFileName(std::string(fname));
imageIO->ReadImageInformation();
size_t dims = imageIO->GetNumberOfDimensions();
if (verbose) std::cout << "File: " << std::string(fname) << std::endl;
if (print_all || verbose) std::cout << "Dimension: "; if (print_all || print_dims) std::cout << dims << std::endl;
if (print_all || verbose) std::cout << "Voxel Type: ";
if (print_all || print_type) {
std::cout << imageIO->GetPixelTypeAsString(imageIO->GetPixelType()) << " "
<< imageIO->GetComponentTypeAsString(imageIO->GetComponentType()) << std::endl;
}
if (dim3 && dims > 3) dims = 3;
if (print_all || print_size) {
if (print_size.Get() < 0 || print_size.Get() > dims) {
if (verbose) std::cerr << "Invalid dimension " << print_size.Get() << " for image " << fname << std::endl;
} else {
int start_dim, end_dim;
if (print_size.Get() == 0) {
start_dim = 0; end_dim = dims;
} else {
start_dim = print_size.Get() - 1;
end_dim = print_size.Get();
}
if (print_all || verbose) std::cout << "Size: "; if (print_all || print_size) { for (int i = start_dim; i < end_dim; i++) std::cout << imageIO->GetDimensions(i) << "\t"; std::cout << std::endl; }
}
}
if (print_all || print_spacing) {
if (print_spacing.Get() < 0 || print_spacing.Get() > dims) {
if (verbose) std::cerr << "Invalid dimension " << print_spacing.Get() << " for image " << fname << std::endl;
} else {
int start_dim, end_dim;
if (print_spacing.Get() == 0) {
start_dim = 0; end_dim = dims;
} else {
start_dim = print_spacing.Get() - 1;
end_dim = print_spacing.Get();
}
if (print_all || verbose) std::cout << "Spacing: "; if (print_all || print_spacing) { for (int i = start_dim; i < end_dim; i++) std::cout << imageIO->GetSpacing(i) << "\t"; std::cout << std::endl; }
}
}
if (print_all || verbose) std::cout << "Origin: "; if (print_all || print_origin) { for (int i = 0; i < dims; i++) std::cout << imageIO->GetOrigin(i) << "\t"; std::cout << std::endl; }
if (print_all || verbose) std::cout << "Direction: " << std::endl;
if (print_all | print_direction) {
for (int i = 0; i < dims; i++) {
std::vector<double> dir = imageIO->GetDirection(i);
for (int j = 0; j < dims; j++)
std::cout << dir[j] << "\t";
std::cout << std::endl;
}
}
if (print_all || verbose) std::cout << "Voxel vol: "; if (print_all || print_voxvol) { double vol = imageIO->GetSpacing(0); for (int i = 1; i < dims; i++) vol *= imageIO->GetSpacing(i); std::cout << vol << std::endl; }
for (const std::string &hf : header_fields.Get()) {
auto header = imageIO->GetMetaDataDictionary();
if (header.HasKey(hf)) {
std::vector<std::string> string_array_value;
std::vector<std::vector<std::string> > string_array_array_value;
std::vector<std::vector<double> > double_array_array_value;
std::vector<double> double_array_value;
std::string string_value;
auto delim = "";
double double_value;
if (verbose) std::cout << hf << ": ";
if (ExposeMetaData(header, hf, string_array_value)) {
std::cout << string_array_value << std::endl;
} else if (ExposeMetaData(header, hf, string_array_array_value)) {
std::cout << string_array_array_value << std::endl;
} else if (ExposeMetaData(header, hf, double_array_value)) {
std::cout << double_array_value << std::endl;
} else if (ExposeMetaData(header, hf, double_array_array_value)) {
std::cout << double_array_array_value << std::endl;
} else if (ExposeMetaData(header, hf, string_value)) {
std::cout << string_value << std::endl;
} else if (ExposeMetaData(header, hf, double_value)) {
std::cout << double_value << std::endl;
} else {
QI_EXCEPTION("Could not determine type of rename header field:" << hf);
}
} else {
if (verbose) std::cout << "Header field not found: " << hf << std::endl;
}
}
}
return EXIT_SUCCESS;
}
<|endoftext|>
|
<commit_before>/*
* 2014+ Copyright (c) Andrey Kashin <[email protected]>
* All rights reserved.
*
* This program 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 of the License, or
* (at your option) any later version.
*
* This program 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.
*/
#ifndef CATEGORY_FILTER_AGGREGATOR_HPP
#define CATEGORY_FILTER_AGGREGATOR_HPP
#include "aggregator.hpp"
namespace react {
template<typename Category>
struct category_extractor_t {
category_extractor_t() {}
virtual ~category_extractor_t() {}
virtual Category operator () (const call_tree_t &call_tree) const = 0;
};
template<typename Category>
struct stat_extractor_t : public category_extractor_t<Category> {
stat_extractor_t(const std::string &stat_name): stat_name(stat_name) {}
~stat_extractor_t() {}
Category operator () (const call_tree_t &call_tree) const {
return call_tree.get_stat<Category>(stat_name);
}
std::string stat_name;
};
template<typename Category>
class category_filter_aggregator_t : public aggregator_t {
public:
category_filter_aggregator_t(const actions_set_t &actions_set,
std::shared_ptr<category_extractor_t<Category>> category_extractor):
aggregator_t(actions_set), category_extractor(category_extractor) {}
~category_filter_aggregator_t() {}
void add_category_aggregator(Category category, std::shared_ptr<aggregator_t> aggregator) {
categories_aggregators[category] = aggregator;
}
void aggregate(const call_tree_t &call_tree) {
Category category = (*category_extractor)(call_tree);
if (categories_aggregators.find(category) != categories_aggregators.end()) {
categories_aggregators[category]->aggregate(call_tree);
}
}
void to_json(rapidjson::Value &value, rapidjson::Document::AllocatorType &allocator) const {
rapidjson::Value category_aggregator_value(rapidjson::kArrayType);
for (auto it = categories_aggregators.begin(); it != categories_aggregators.end(); ++it) {
Category category = it->first;
rapidjson::Value aggregator_value(rapidjson::kObjectType);
it->second->to_json(aggregator_value, allocator);
aggregator_value.AddMember("category", category, allocator);
category_aggregator_value.PushBack(aggregator_value, allocator);
}
value.AddMember("category_filter_aggregator", category_aggregator_value, allocator);
}
private:
std::shared_ptr<category_extractor_t<Category>> category_extractor;
std::unordered_map<Category, std::shared_ptr<aggregator_t>> categories_aggregators;
};
} // namespace react
#endif // CATEGORY_FILTER_AGGREGATOR_HPP
<commit_msg>aggregators: category_extractor can now convert to json<commit_after>/*
* 2014+ Copyright (c) Andrey Kashin <[email protected]>
* All rights reserved.
*
* This program 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 of the License, or
* (at your option) any later version.
*
* This program 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.
*/
#ifndef CATEGORY_FILTER_AGGREGATOR_HPP
#define CATEGORY_FILTER_AGGREGATOR_HPP
#include "aggregator.hpp"
namespace react {
template<typename Category>
struct category_extractor_t {
category_extractor_t() {}
virtual ~category_extractor_t() {}
virtual Category operator () (const call_tree_t &call_tree) const = 0;
virtual void to_json(rapidjson::Value &value,
rapidjson::Document::AllocatorType &allocator,
const actions_set_t &) const = 0;
};
template<typename Category>
struct stat_extractor_t : public category_extractor_t<Category> {
stat_extractor_t(const std::string &stat_name): stat_name(stat_name) {}
~stat_extractor_t() {}
Category operator () (const call_tree_t &call_tree) const {
return call_tree.get_stat<Category>(stat_name);
}
void to_json(rapidjson::Value &value,
rapidjson::Document::AllocatorType &allocator,
const actions_set_t &) const {
value.AddMember("name", "stat_extractor", allocator);
rapidjson::Value stat_name_value(stat_name.c_str(), allocator);
value.AddMember("stat_name", stat_name_value, allocator);
}
std::string stat_name;
};
template<typename Category>
class category_filter_aggregator_t : public aggregator_t {
public:
category_filter_aggregator_t(const actions_set_t &actions_set,
std::shared_ptr<category_extractor_t<Category>> category_extractor):
aggregator_t(actions_set), category_extractor(category_extractor) {}
~category_filter_aggregator_t() {}
void add_category_aggregator(Category category, std::shared_ptr<aggregator_t> aggregator) {
categories_aggregators[category] = aggregator;
}
void aggregate(const call_tree_t &call_tree) {
Category category = (*category_extractor)(call_tree);
if (categories_aggregators.find(category) != categories_aggregators.end()) {
categories_aggregators[category]->aggregate(call_tree);
}
}
void to_json(rapidjson::Value &value, rapidjson::Document::AllocatorType &allocator) const {
rapidjson::Value category_aggregator_value(rapidjson::kObjectType);
rapidjson::Value categories_values(rapidjson::kArrayType);
for (auto it = categories_aggregators.begin(); it != categories_aggregators.end(); ++it) {
Category category = it->first;
rapidjson::Value aggregator_value(rapidjson::kObjectType);
it->second->to_json(aggregator_value, allocator);
aggregator_value.AddMember("category", category, allocator);
categories_values.PushBack(aggregator_value, allocator);
}
rapidjson::Value category_extractor_value(rapidjson::kObjectType);
category_extractor->to_json(category_extractor_value, allocator, actions_set);
category_aggregator_value.AddMember("category_extractor", category_extractor_value, allocator);
category_aggregator_value.AddMember("categories", categories_values, allocator);
value.AddMember("category_filter_aggregator", category_aggregator_value, allocator);
}
private:
std::shared_ptr<category_extractor_t<Category>> category_extractor;
std::unordered_map<Category, std::shared_ptr<aggregator_t>> categories_aggregators;
};
} // namespace react
#endif // CATEGORY_FILTER_AGGREGATOR_HPP
<|endoftext|>
|
<commit_before>/*
* Copyright(c) Records For Living, Inc. 2004-2011. All rights reserved
*/
#include "Stroika/Foundation/StroikaPreComp.h"
#include <iostream>
#include <sstream>
#include "Stroika/Foundation/Debug/Assertions.h"
#include "Stroika/Foundation/Debug/Trace.h"
#include "Stroika/Foundation/Execution/Sleep.h"
#include "Stroika/Foundation/Time/Date.h"
#include "Stroika/Foundation/Time/DateTime.h"
#include "Stroika/Foundation/Time/Duration.h"
#include "Stroika/Foundation/Time/Realtime.h"
#include "../TestHarness/TestHarness.h"
using namespace Stroika::Foundation;
using namespace Stroika::Foundation::Time;
using Stroika::Foundation::Debug::TraceContextBumper;
namespace {
void Test_1_TestTickCountGrowsMonotonically_ ()
{
DurationSecondsType start = Time::GetTickCount ();
Execution::Sleep (0.1);
VerifyTestResult (start <= Time::GetTickCount ());
}
}
namespace {
void Test_2_TestTimeOfDay_ ()
{
{
TimeOfDay t;
VerifyTestResult (t.empty ());
TimeOfDay t2 (2);
VerifyTestResult (t < t2);
VerifyTestResult (t.GetAsSecondsCount () == 0);
VerifyTestResult (not t2.empty ());
VerifyTestResult (t.Format ().empty ());
VerifyTestResult (not t2.Format ().empty ());
VerifyTestResult (t2.GetHours () == 0);
VerifyTestResult (t2.GetMinutes () == 0);
VerifyTestResult (t2.GetSeconds () == 2);
}
{
TimeOfDay t2 (5 * 60 * 60 + 3 * 60 + 49);
VerifyTestResult (t2.GetHours () == 5);
VerifyTestResult (t2.GetMinutes () == 3);
VerifyTestResult (t2.GetSeconds () == 49);
}
{
TimeOfDay t2 (25 * 60 * 60);
VerifyTestResult (t2.GetHours () == 23);
VerifyTestResult (t2.GetMinutes () == 59);
VerifyTestResult (t2.GetSeconds () == 59);
VerifyTestResult (t2 == TimeOfDay::kMax);
}
}
}
namespace {
void Test_3_TestDate_ ()
{
{
Date d (Year (1903), eApril, DayOfMonth (4));
VerifyTestResult (d.Format (Date::eXML_PF) == L"1903-04-04");
d.AddDays (4);
VerifyTestResult (d.Format (Date::eXML_PF) == L"1903-04-08");
d.AddDays (-4);
VerifyTestResult (d.Format (Date::eXML_PF) == L"1903-04-04");
}
}
}
namespace {
void Test_4_TestDateTime_ ()
{
{
DateTime d = Date (Year (1903), eApril, DayOfMonth (4));
VerifyTestResult (d.Format4XML () == L"1903-04-04");
}
#if 0
{
DateTime d;
VerifyTestResult (d.empty ());
VerifyTestResult (d < DateTime::Now ());
VerifyTestResult (not (DateTime::Now () > d));
}
{
DateTime d = DateTime::kMin;
VerifyTestResult (not d.empty ());
VerifyTestResult (d < DateTime::Now ());
VerifyTestResult (not (DateTime::Now () > d));
VerifyTestResult (d.Format4XML () == L"1752-01-01T00:00:00"); // xml cuz otherwise we get confusion over locale - COULD use hardwired US locale at some point?
}
#endif
}
}
namespace {
void Test_5_DateTimeTimeT_ ()
{
{
DateTime d = Date (Year (2000), eApril, DayOfMonth (20));
VerifyTestResult (d.GetUNIXEpochTime () == 956188800); // source - http://www.onlineconversion.com/unix_time.htm
}
{
DateTime d = DateTime (Date (Year (1995), eJune, DayOfMonth (4)), TimeOfDay::Parse (L"3pm", TimeOfDay::eCurrentLocale_PF));
VerifyTestResult (d.GetUNIXEpochTime () == 802278000); // source - http://www.onlineconversion.com/unix_time.htm
}
{
DateTime d = DateTime (Date (Year (1995), eJune, DayOfMonth (4)), TimeOfDay::Parse (L"3:00", TimeOfDay::eCurrentLocale_PF));
VerifyTestResult (d.GetUNIXEpochTime () == 802234800); // source - http://www.onlineconversion.com/unix_time.htm
}
#if 0
//this fails - on windows - fix asap
{
const time_t kTEST = 802234800;
DateTime d = DateTime (kTEST);
VerifyTestResult (d.GetUNIXEpochTime () == kTEST); // source - http://www.onlineconversion.com/unix_time.htm
}
#endif
}
}
namespace {
void DoRegressionTests_ ()
{
Test_1_TestTickCountGrowsMonotonically_ ();
Test_2_TestTimeOfDay_ ();
Test_3_TestDate_ ();
Test_4_TestDateTime_ ();
Test_5_DateTimeTimeT_ ();
}
}
#if qOnlyOneMain
extern int TestDateAndTime ()
#else
int main (int argc, const char* argv[])
#endif
{
Stroika::TestHarness::Setup ();
Stroika::TestHarness::PrintPassOrFail (DoRegressionTests_);
return EXIT_SUCCESS;
}
<commit_msg>More progress on same refactoring for DateTime class - cleaner construction, separation between portable/non-portable parts etc<commit_after>/*
* Copyright(c) Records For Living, Inc. 2004-2011. All rights reserved
*/
#include "Stroika/Foundation/StroikaPreComp.h"
#include <iostream>
#include <sstream>
#include "Stroika/Foundation/Debug/Assertions.h"
#include "Stroika/Foundation/Debug/Trace.h"
#include "Stroika/Foundation/Execution/Sleep.h"
#include "Stroika/Foundation/Time/Date.h"
#include "Stroika/Foundation/Time/DateTime.h"
#include "Stroika/Foundation/Time/Duration.h"
#include "Stroika/Foundation/Time/Realtime.h"
#include "../TestHarness/TestHarness.h"
using namespace Stroika::Foundation;
using namespace Stroika::Foundation::Time;
using Stroika::Foundation::Debug::TraceContextBumper;
namespace {
void Test_1_TestTickCountGrowsMonotonically_ ()
{
DurationSecondsType start = Time::GetTickCount ();
Execution::Sleep (0.1);
VerifyTestResult (start <= Time::GetTickCount ());
}
}
namespace {
void Test_2_TestTimeOfDay_ ()
{
{
TimeOfDay t;
VerifyTestResult (t.empty ());
TimeOfDay t2 (2);
VerifyTestResult (t < t2);
VerifyTestResult (t.GetAsSecondsCount () == 0);
VerifyTestResult (not t2.empty ());
VerifyTestResult (t.Format ().empty ());
VerifyTestResult (not t2.Format ().empty ());
VerifyTestResult (t2.GetHours () == 0);
VerifyTestResult (t2.GetMinutes () == 0);
VerifyTestResult (t2.GetSeconds () == 2);
}
{
TimeOfDay t2 (5 * 60 * 60 + 3 * 60 + 49);
VerifyTestResult (t2.GetHours () == 5);
VerifyTestResult (t2.GetMinutes () == 3);
VerifyTestResult (t2.GetSeconds () == 49);
}
{
TimeOfDay t2 (25 * 60 * 60);
VerifyTestResult (t2.GetHours () == 23);
VerifyTestResult (t2.GetMinutes () == 59);
VerifyTestResult (t2.GetSeconds () == 59);
VerifyTestResult (t2 == TimeOfDay::kMax);
}
}
}
namespace {
void Test_3_TestDate_ ()
{
{
Date d (Year (1903), eApril, DayOfMonth (4));
VerifyTestResult (d.Format (Date::eXML_PF) == L"1903-04-04");
d.AddDays (4);
VerifyTestResult (d.Format (Date::eXML_PF) == L"1903-04-08");
d.AddDays (-4);
VerifyTestResult (d.Format (Date::eXML_PF) == L"1903-04-04");
}
}
}
namespace {
void Test_4_TestDateTime_ ()
{
{
DateTime d = Date (Year (1903), eApril, DayOfMonth (4));
VerifyTestResult (d.Format (DateTime::eXML_PF) == L"1903-04-04");
}
#if 0
{
DateTime d;
VerifyTestResult (d.empty ());
VerifyTestResult (d < DateTime::Now ());
VerifyTestResult (not (DateTime::Now () > d));
}
{
DateTime d = DateTime::kMin;
VerifyTestResult (not d.empty ());
VerifyTestResult (d < DateTime::Now ());
VerifyTestResult (not (DateTime::Now () > d));
VerifyTestResult (d.Format4XML () == L"1752-01-01T00:00:00"); // xml cuz otherwise we get confusion over locale - COULD use hardwired US locale at some point?
}
#endif
}
}
namespace {
void Test_5_DateTimeTimeT_ ()
{
{
DateTime d = Date (Year (2000), eApril, DayOfMonth (20));
VerifyTestResult (d.GetUNIXEpochTime () == 956188800); // source - http://www.onlineconversion.com/unix_time.htm
}
{
DateTime d = DateTime (Date (Year (1995), eJune, DayOfMonth (4)), TimeOfDay::Parse (L"3pm", TimeOfDay::eCurrentLocale_PF));
VerifyTestResult (d.GetUNIXEpochTime () == 802278000); // source - http://www.onlineconversion.com/unix_time.htm
}
{
DateTime d = DateTime (Date (Year (1995), eJune, DayOfMonth (4)), TimeOfDay::Parse (L"3:00", TimeOfDay::eCurrentLocale_PF));
VerifyTestResult (d.GetUNIXEpochTime () == 802234800); // source - http://www.onlineconversion.com/unix_time.htm
}
#if 0
//this fails - on windows - fix asap
{
const time_t kTEST = 802234800;
DateTime d = DateTime (kTEST);
VerifyTestResult (d.GetUNIXEpochTime () == kTEST); // source - http://www.onlineconversion.com/unix_time.htm
}
#endif
}
}
namespace {
void DoRegressionTests_ ()
{
Test_1_TestTickCountGrowsMonotonically_ ();
Test_2_TestTimeOfDay_ ();
Test_3_TestDate_ ();
Test_4_TestDateTime_ ();
Test_5_DateTimeTimeT_ ();
}
}
#if qOnlyOneMain
extern int TestDateAndTime ()
#else
int main (int argc, const char* argv[])
#endif
{
Stroika::TestHarness::Setup ();
Stroika::TestHarness::PrintPassOrFail (DoRegressionTests_);
return EXIT_SUCCESS;
}
<|endoftext|>
|
<commit_before>/*
* Copyright(c) Sophist Solutions, Inc. 1990-2020. All rights reserved
*/
#include "../StroikaPreComp.h"
#include <algorithm>
#include <cstdlib>
#include <sstream>
#include "../../Foundation/Characters/CString/Utilities.h"
#include "../../Foundation/Characters/Format.h"
#include "../../Foundation/Characters/StringBuilder.h"
#include "../../Foundation/Characters/String_Constant.h"
#include "../../Foundation/Characters/ToString.h"
#include "../../Foundation/Containers/Common.h"
#include "../../Foundation/DataExchange/BadFormatException.h"
#include "../../Foundation/DataExchange/InternetMediaType.h"
#include "../../Foundation/DataExchange/InternetMediaTypeRegistry.h"
#include "../../Foundation/Debug/Assertions.h"
#include "../../Foundation/Debug/Trace.h"
#include "../../Foundation/IO/Network/HTTP/ClientErrorException.h"
#include "../../Foundation/IO/Network/HTTP/Exception.h"
#include "../../Foundation/IO/Network/HTTP/Headers.h"
#include "../../Foundation/Memory/SmallStackBuffer.h"
#include "Response.h"
using std::byte;
using namespace Stroika::Foundation;
using namespace Stroika::Foundation::Characters;
using namespace Stroika::Foundation::Containers;
using namespace Stroika::Foundation::Memory;
using namespace Stroika::Frameworks;
using namespace Stroika::Frameworks::WebServer;
using IO::Network::HTTP::ClientErrorException;
// Comment this in to turn on aggressive noisy DbgTrace in this module
//#define USE_NOISY_TRACE_IN_THIS_MODULE_ 1
namespace {
const set<String> kDisallowedOtherHeaders_ = set<String> ({IO::Network::HTTP::HeaderName::kContentLength,
IO::Network::HTTP::HeaderName::kContentType});
}
/*
********************************************************************************
**************************** WebServer::Response *******************************
********************************************************************************
*/
namespace {
// Based on looking at a handlful of typical file sizes...5k to 80k, but ave around
// 25 and median abit above 32k. Small, not very representative sampling. And the more we use
// subscripts (script src=x) this number could shrink.
//
// MAY want to switch to using SmallStackBuffer<byte> - but before doing so, do some cleanups of its bugs and make sure
// its optimized about how much it copies etc. Its really only tuned for POD-types (OK here but not necessarily good about reallocs).
//
// -- LGP 2011-07-06
constexpr size_t kResponseBufferReallocChunkSizeReserve_ = 16 * 1024;
}
Response::Response (const IO::Network::Socket::Ptr& s, const Streams::OutputStream<byte>::Ptr& outStream, const InternetMediaType& ct)
: fSocket_ {s}
, fState_ {State::eInProgress}
, fStatus_ {StatusCodes::kOK}
, fStatusOverrideReason_ {}
, fUnderlyingOutStream_ {outStream}
, fUseOutStream_ {Streams::BufferedOutputStream<byte>::New (outStream)}
, fHeaders_ {}
, fContentType_ {ct}
, fCodePage_ {Characters::kCodePage_UTF8}
, fBytes_ {}
, fContentSizePolicy_ {ContentSizePolicy::eAutoCompute}
, fContentSize_ {0}
{
AddHeader (IO::Network::HTTP::HeaderName::kServer, L"Stroka-Based-Web-Server"sv);
}
void Response::SetContentSizePolicy (ContentSizePolicy csp)
{
lock_guard<const AssertExternallySynchronizedLock> critSec{*this};
Require (csp == ContentSizePolicy::eAutoCompute or csp == ContentSizePolicy::eNone);
fContentSizePolicy_ = csp;
}
void Response::SetContentSizePolicy (ContentSizePolicy csp, uint64_t size)
{
lock_guard<const AssertExternallySynchronizedLock> critSec{*this};
Require (csp == ContentSizePolicy::eExact);
Require (fState_ == State::eInProgress);
fContentSizePolicy_ = csp;
fContentSize_ = size;
}
bool Response::IsContentLengthKnown () const
{
return fContentSizePolicy_ != ContentSizePolicy::eNone;
}
void Response::SetContentType (const InternetMediaType& contentType)
{
lock_guard<const AssertExternallySynchronizedLock> critSec{*this};
Require (fState_ == State::eInProgress);
fContentType_ = contentType;
}
void Response::SetCodePage (Characters::CodePage codePage)
{
lock_guard<const AssertExternallySynchronizedLock> critSec{*this};
Require (fState_ == State::eInProgress);
Require (fBytes_.empty ());
fCodePage_ = codePage;
}
void Response::SetStatus (Status newStatus, const String& overrideReason)
{
lock_guard<const AssertExternallySynchronizedLock> critSec{*this};
Require (fState_ == State::eInProgress);
fStatus_ = newStatus;
fStatusOverrideReason_ = overrideReason;
}
void Response::AddHeader (const String& headerName, const String& value)
{
lock_guard<const AssertExternallySynchronizedLock> critSec{*this};
Require (fState_ == State::eInProgress);
Require (kDisallowedOtherHeaders_.find (headerName) == kDisallowedOtherHeaders_.end ());
fHeaders_.Add (headerName, value);
}
void Response::AppendToCommaSeperatedHeader (const String& headerName, const String& value)
{
Require (not value.empty ());
lock_guard<const AssertExternallySynchronizedLock> critSec{*this};
if (auto o = fHeaders_.Lookup (headerName)) {
if (o->empty ()) {
AddHeader (headerName, value);
}
else {
AddHeader (headerName, *o + String_Constant{L", "} + value);
}
}
else {
AddHeader (headerName, value);
}
}
void Response::ClearHeaders ()
{
lock_guard<const AssertExternallySynchronizedLock> critSec{*this};
Require (fState_ == State::eInProgress);
fHeaders_.clear ();
}
void Response::ClearHeader (const String& headerName)
{
lock_guard<const AssertExternallySynchronizedLock> critSec{*this};
Require (fState_ == State::eInProgress);
Require (kDisallowedOtherHeaders_.find (headerName) == kDisallowedOtherHeaders_.end ());
fHeaders_.Remove (headerName);
}
Mapping<String, String> Response::GetHeaders () const
{
shared_lock<const AssertExternallySynchronizedLock> critSec{*this};
return fHeaders_;
}
Mapping<String, String> Response::GetEffectiveHeaders () const
{
shared_lock<const AssertExternallySynchronizedLock> critSec{*this};
Mapping<String, String> tmp = GetHeaders ();
switch (GetContentSizePolicy ()) {
case ContentSizePolicy::eAutoCompute:
case ContentSizePolicy::eExact: {
wostringstream buf;
buf << fContentSize_;
tmp.Add (IO::Network::HTTP::HeaderName::kContentLength, buf.str ());
} break;
}
if (not fContentType_.empty ()) {
using AtomType = InternetMediaType::AtomType;
InternetMediaType useContentType = fContentType_;
if (DataExchange::InternetMediaTypeRegistry::Get ().IsTextFormat (fContentType_)) {
// Don't override already specifed characterset
Containers::Mapping<String, String> params = useContentType.GetParameters ();
params.AddIf (L"charset"_k, Characters::GetCharsetString (fCodePage_));
useContentType = InternetMediaType{useContentType.GetType<AtomType> (), useContentType.GetSubType<AtomType> (), useContentType.GetSuffix (), params};
}
tmp.Add (IO::Network::HTTP::HeaderName::kContentType, useContentType.As<wstring> ());
}
return tmp;
}
void Response::Flush ()
{
#if USE_NOISY_TRACE_IN_THIS_MODULE_
Debug::TraceContextBumper ctx{L"Response::Flush"};
DbgTrace (L"fState_ = %s", Characters::ToString (fState_).c_str ());
#endif
lock_guard<const AssertExternallySynchronizedLock> critSec{*this};
if (fState_ == State::eInProgress) {
{
String statusMsg = fStatusOverrideReason_.empty () ? IO::Network::HTTP::Exception::GetStandardTextForStatus (fStatus_, true) : fStatusOverrideReason_;
wstring version = L"1.1";
wstring tmp = Characters::CString::Format (L"HTTP/%s %d %s\r\n", version.c_str (), fStatus_, statusMsg.c_str ());
string utf8 = String (tmp).AsUTF8 ();
fUseOutStream_.Write (reinterpret_cast<const byte*> (Containers::Start (utf8)), reinterpret_cast<const byte*> (Containers::End (utf8)));
}
{
Mapping<String, String> headers2Write = GetEffectiveHeaders ();
for (auto i : headers2Write) {
string utf8 = Characters::Format (L"%s: %s\r\n", i.fKey.c_str (), i.fValue.c_str ()).AsUTF8 ();
fUseOutStream_.Write (reinterpret_cast<const byte*> (Containers::Start (utf8)), reinterpret_cast<const byte*> (Containers::End (utf8)));
}
#if USE_NOISY_TRACE_IN_THIS_MODULE_
DbgTrace (L"headers: %s", Characters::ToString (headers2Write).c_str ());
#endif
}
const char kCRLF[] = "\r\n";
fUseOutStream_.Write (reinterpret_cast<const byte*> (kCRLF), reinterpret_cast<const byte*> (kCRLF + 2));
fState_ = State::eInProgressHeaderSentState;
}
// write BYTES to fOutStream
if (not fBytes_.empty ()) {
Assert (fState_ != State::eCompleted); // We PREVENT any writes when completed
#if USE_NOISY_TRACE_IN_THIS_MODULE_
DbgTrace (L"bytes.size: %lld", static_cast<long long> (fBytes_.size ()));
#endif
fUseOutStream_.Write (Containers::Start (fBytes_), Containers::End (fBytes_));
fBytes_.clear ();
}
if (fState_ != State::eCompleted) {
fUseOutStream_.Flush ();
}
Ensure (fBytes_.empty ());
}
void Response::End ()
{
lock_guard<const AssertExternallySynchronizedLock> critSec{*this};
Require ((fState_ == State::eInProgress) or (fState_ == State::eInProgressHeaderSentState));
Flush ();
fState_ = State::eCompleted;
Ensure (fState_ == State::eCompleted);
Ensure (fBytes_.empty ());
}
void Response::Abort ()
{
lock_guard<const AssertExternallySynchronizedLock> critSec{*this};
if (fState_ != State::eCompleted) {
fState_ = State::eCompleted;
fUseOutStream_.Abort ();
fSocket_.Close ();
fBytes_.clear ();
}
Ensure (fState_ == State::eCompleted);
Ensure (fBytes_.empty ());
}
void Response::Redirect (const String& url)
{
lock_guard<const AssertExternallySynchronizedLock> critSec{*this};
Require (fState_ == State::eInProgress);
fBytes_.clear ();
// PERHAPS should clear some header values???
AddHeader (L"Connection"_k, L"close"_k); // needed for redirect
AddHeader (L"Location"_k, url); // needed for redirect
SetStatus (StatusCodes::kMovedPermanently);
Flush ();
fState_ = State::eCompleted;
}
void Response::write (const byte* s, const byte* e)
{
lock_guard<const AssertExternallySynchronizedLock> critSec{*this};
Require ((fState_ == State::eInProgress) or (fState_ == State::eInProgressHeaderSentState));
Require ((fState_ == State::eInProgress) or (GetContentSizePolicy () != ContentSizePolicy::eAutoCompute));
Require (s <= e);
if (s < e) {
Containers::ReserveSpeedTweekAddN (fBytes_, (e - s), kResponseBufferReallocChunkSizeReserve_);
fBytes_.insert (fBytes_.end (), s, e);
if (GetContentSizePolicy () == ContentSizePolicy::eAutoCompute) {
// Because for autocompute - illegal to call flush and then write
fContentSize_ = fBytes_.size ();
}
}
}
void Response::write (const wchar_t* s, const wchar_t* e)
{
lock_guard<const AssertExternallySynchronizedLock> critSec{*this};
Require ((fState_ == State::eInProgress) or (fState_ == State::eInProgressHeaderSentState));
Require ((fState_ == State::eInProgress) or (GetContentSizePolicy () != ContentSizePolicy::eAutoCompute));
Require (s <= e);
if (s < e) {
wstring tmp = wstring (s, e);
string cpStr = Characters::WideStringToNarrow (tmp, fCodePage_);
if (not cpStr.empty ()) {
fBytes_.insert (fBytes_.end (), reinterpret_cast<const byte*> (cpStr.c_str ()), reinterpret_cast<const byte*> (cpStr.c_str () + cpStr.length ()));
if (GetContentSizePolicy () == ContentSizePolicy::eAutoCompute) {
// Because for autocompute - illegal to call flush and then write
fContentSize_ = fBytes_.size ();
}
}
}
}
void Response::printf (const wchar_t* format, ...)
{
lock_guard<const AssertExternallySynchronizedLock> critSec{*this};
va_list argsList;
va_start (argsList, format);
String tmp = Characters::FormatV (format, argsList);
va_end (argsList);
write (tmp);
}
String Response::ToString () const
{
shared_lock<const AssertExternallySynchronizedLock> critSec{*this};
StringBuilder sb;
sb += L"{";
sb += L"Socket: " + Characters::ToString (fSocket_) + L", ";
sb += L"State_: " + Characters::ToString (fState_) + L", ";
sb += L"StatusOverrideReason_: '" + Characters::ToString (fStatusOverrideReason_) + L"', ";
sb += L"Headers: " + Characters::ToString (GetEffectiveHeaders ()) + L", ";
sb += L"}";
return sb.str ();
}
<commit_msg>cosmetic<commit_after>/*
* Copyright(c) Sophist Solutions, Inc. 1990-2020. All rights reserved
*/
#include "../StroikaPreComp.h"
#include <algorithm>
#include <cstdlib>
#include <sstream>
#include "../../Foundation/Characters/CString/Utilities.h"
#include "../../Foundation/Characters/Format.h"
#include "../../Foundation/Characters/StringBuilder.h"
#include "../../Foundation/Characters/String_Constant.h"
#include "../../Foundation/Characters/ToString.h"
#include "../../Foundation/Containers/Common.h"
#include "../../Foundation/DataExchange/BadFormatException.h"
#include "../../Foundation/DataExchange/InternetMediaType.h"
#include "../../Foundation/DataExchange/InternetMediaTypeRegistry.h"
#include "../../Foundation/Debug/Assertions.h"
#include "../../Foundation/Debug/Trace.h"
#include "../../Foundation/IO/Network/HTTP/ClientErrorException.h"
#include "../../Foundation/IO/Network/HTTP/Exception.h"
#include "../../Foundation/IO/Network/HTTP/Headers.h"
#include "../../Foundation/Memory/SmallStackBuffer.h"
#include "Response.h"
using std::byte;
using namespace Stroika::Foundation;
using namespace Stroika::Foundation::Characters;
using namespace Stroika::Foundation::Containers;
using namespace Stroika::Foundation::Memory;
using namespace Stroika::Frameworks;
using namespace Stroika::Frameworks::WebServer;
using IO::Network::HTTP::ClientErrorException;
// Comment this in to turn on aggressive noisy DbgTrace in this module
//#define USE_NOISY_TRACE_IN_THIS_MODULE_ 1
namespace {
const set<String> kDisallowedOtherHeaders_ = set<String> ({IO::Network::HTTP::HeaderName::kContentLength,
IO::Network::HTTP::HeaderName::kContentType});
}
/*
********************************************************************************
**************************** WebServer::Response *******************************
********************************************************************************
*/
namespace {
// Based on looking at a handlful of typical file sizes...5k to 80k, but ave around
// 25 and median abit above 32k. Small, not very representative sampling. And the more we use
// subscripts (script src=x) this number could shrink.
//
// MAY want to switch to using SmallStackBuffer<byte> - but before doing so, do some cleanups of its bugs and make sure
// its optimized about how much it copies etc. Its really only tuned for POD-types (OK here but not necessarily good about reallocs).
//
// -- LGP 2011-07-06
constexpr size_t kResponseBufferReallocChunkSizeReserve_ = 16 * 1024;
}
Response::Response (const IO::Network::Socket::Ptr& s, const Streams::OutputStream<byte>::Ptr& outStream, const InternetMediaType& ct)
: fSocket_{s}
, fState_{State::eInProgress}
, fStatus_{StatusCodes::kOK}
, fStatusOverrideReason_{}
, fUnderlyingOutStream_{outStream}
, fUseOutStream_{Streams::BufferedOutputStream<byte>::New (outStream)}
, fHeaders_{}
, fContentType_{ct}
, fCodePage_{Characters::kCodePage_UTF8}
, fBytes_{}
, fContentSizePolicy_{ContentSizePolicy::eAutoCompute}
, fContentSize_{0}
{
AddHeader (IO::Network::HTTP::HeaderName::kServer, L"Stroka-Based-Web-Server"sv);
}
void Response::SetContentSizePolicy (ContentSizePolicy csp)
{
lock_guard<const AssertExternallySynchronizedLock> critSec{*this};
Require (csp == ContentSizePolicy::eAutoCompute or csp == ContentSizePolicy::eNone);
fContentSizePolicy_ = csp;
}
void Response::SetContentSizePolicy (ContentSizePolicy csp, uint64_t size)
{
lock_guard<const AssertExternallySynchronizedLock> critSec{*this};
Require (csp == ContentSizePolicy::eExact);
Require (fState_ == State::eInProgress);
fContentSizePolicy_ = csp;
fContentSize_ = size;
}
bool Response::IsContentLengthKnown () const
{
return fContentSizePolicy_ != ContentSizePolicy::eNone;
}
void Response::SetContentType (const InternetMediaType& contentType)
{
lock_guard<const AssertExternallySynchronizedLock> critSec{*this};
Require (fState_ == State::eInProgress);
fContentType_ = contentType;
}
void Response::SetCodePage (Characters::CodePage codePage)
{
lock_guard<const AssertExternallySynchronizedLock> critSec{*this};
Require (fState_ == State::eInProgress);
Require (fBytes_.empty ());
fCodePage_ = codePage;
}
void Response::SetStatus (Status newStatus, const String& overrideReason)
{
lock_guard<const AssertExternallySynchronizedLock> critSec{*this};
Require (fState_ == State::eInProgress);
fStatus_ = newStatus;
fStatusOverrideReason_ = overrideReason;
}
void Response::AddHeader (const String& headerName, const String& value)
{
lock_guard<const AssertExternallySynchronizedLock> critSec{*this};
Require (fState_ == State::eInProgress);
Require (kDisallowedOtherHeaders_.find (headerName) == kDisallowedOtherHeaders_.end ());
fHeaders_.Add (headerName, value);
}
void Response::AppendToCommaSeperatedHeader (const String& headerName, const String& value)
{
Require (not value.empty ());
lock_guard<const AssertExternallySynchronizedLock> critSec{*this};
if (auto o = fHeaders_.Lookup (headerName)) {
if (o->empty ()) {
AddHeader (headerName, value);
}
else {
AddHeader (headerName, *o + String_Constant{L", "} + value);
}
}
else {
AddHeader (headerName, value);
}
}
void Response::ClearHeaders ()
{
lock_guard<const AssertExternallySynchronizedLock> critSec{*this};
Require (fState_ == State::eInProgress);
fHeaders_.clear ();
}
void Response::ClearHeader (const String& headerName)
{
lock_guard<const AssertExternallySynchronizedLock> critSec{*this};
Require (fState_ == State::eInProgress);
Require (kDisallowedOtherHeaders_.find (headerName) == kDisallowedOtherHeaders_.end ());
fHeaders_.Remove (headerName);
}
Mapping<String, String> Response::GetHeaders () const
{
shared_lock<const AssertExternallySynchronizedLock> critSec{*this};
return fHeaders_;
}
Mapping<String, String> Response::GetEffectiveHeaders () const
{
shared_lock<const AssertExternallySynchronizedLock> critSec{*this};
Mapping<String, String> tmp = GetHeaders ();
switch (GetContentSizePolicy ()) {
case ContentSizePolicy::eAutoCompute:
case ContentSizePolicy::eExact: {
wostringstream buf;
buf << fContentSize_;
tmp.Add (IO::Network::HTTP::HeaderName::kContentLength, buf.str ());
} break;
}
if (not fContentType_.empty ()) {
using AtomType = InternetMediaType::AtomType;
InternetMediaType useContentType = fContentType_;
if (DataExchange::InternetMediaTypeRegistry::Get ().IsTextFormat (fContentType_)) {
// Don't override already specifed characterset
Containers::Mapping<String, String> params = useContentType.GetParameters ();
params.AddIf (L"charset"_k, Characters::GetCharsetString (fCodePage_));
useContentType = InternetMediaType{useContentType.GetType<AtomType> (), useContentType.GetSubType<AtomType> (), useContentType.GetSuffix (), params};
}
tmp.Add (IO::Network::HTTP::HeaderName::kContentType, useContentType.As<wstring> ());
}
return tmp;
}
void Response::Flush ()
{
#if USE_NOISY_TRACE_IN_THIS_MODULE_
Debug::TraceContextBumper ctx{L"Response::Flush"};
DbgTrace (L"fState_ = %s", Characters::ToString (fState_).c_str ());
#endif
lock_guard<const AssertExternallySynchronizedLock> critSec{*this};
if (fState_ == State::eInProgress) {
{
String statusMsg = fStatusOverrideReason_.empty () ? IO::Network::HTTP::Exception::GetStandardTextForStatus (fStatus_, true) : fStatusOverrideReason_;
wstring version = L"1.1";
wstring tmp = Characters::CString::Format (L"HTTP/%s %d %s\r\n", version.c_str (), fStatus_, statusMsg.c_str ());
string utf8 = String (tmp).AsUTF8 ();
fUseOutStream_.Write (reinterpret_cast<const byte*> (Containers::Start (utf8)), reinterpret_cast<const byte*> (Containers::End (utf8)));
}
{
Mapping<String, String> headers2Write = GetEffectiveHeaders ();
for (auto i : headers2Write) {
string utf8 = Characters::Format (L"%s: %s\r\n", i.fKey.c_str (), i.fValue.c_str ()).AsUTF8 ();
fUseOutStream_.Write (reinterpret_cast<const byte*> (Containers::Start (utf8)), reinterpret_cast<const byte*> (Containers::End (utf8)));
}
#if USE_NOISY_TRACE_IN_THIS_MODULE_
DbgTrace (L"headers: %s", Characters::ToString (headers2Write).c_str ());
#endif
}
const char kCRLF[] = "\r\n";
fUseOutStream_.Write (reinterpret_cast<const byte*> (kCRLF), reinterpret_cast<const byte*> (kCRLF + 2));
fState_ = State::eInProgressHeaderSentState;
}
// write BYTES to fOutStream
if (not fBytes_.empty ()) {
Assert (fState_ != State::eCompleted); // We PREVENT any writes when completed
#if USE_NOISY_TRACE_IN_THIS_MODULE_
DbgTrace (L"bytes.size: %lld", static_cast<long long> (fBytes_.size ()));
#endif
fUseOutStream_.Write (Containers::Start (fBytes_), Containers::End (fBytes_));
fBytes_.clear ();
}
if (fState_ != State::eCompleted) {
fUseOutStream_.Flush ();
}
Ensure (fBytes_.empty ());
}
void Response::End ()
{
lock_guard<const AssertExternallySynchronizedLock> critSec{*this};
Require ((fState_ == State::eInProgress) or (fState_ == State::eInProgressHeaderSentState));
Flush ();
fState_ = State::eCompleted;
Ensure (fState_ == State::eCompleted);
Ensure (fBytes_.empty ());
}
void Response::Abort ()
{
lock_guard<const AssertExternallySynchronizedLock> critSec{*this};
if (fState_ != State::eCompleted) {
fState_ = State::eCompleted;
fUseOutStream_.Abort ();
fSocket_.Close ();
fBytes_.clear ();
}
Ensure (fState_ == State::eCompleted);
Ensure (fBytes_.empty ());
}
void Response::Redirect (const String& url)
{
lock_guard<const AssertExternallySynchronizedLock> critSec{*this};
Require (fState_ == State::eInProgress);
fBytes_.clear ();
// PERHAPS should clear some header values???
AddHeader (L"Connection"_k, L"close"_k); // needed for redirect
AddHeader (L"Location"_k, url); // needed for redirect
SetStatus (StatusCodes::kMovedPermanently);
Flush ();
fState_ = State::eCompleted;
}
void Response::write (const byte* s, const byte* e)
{
lock_guard<const AssertExternallySynchronizedLock> critSec{*this};
Require ((fState_ == State::eInProgress) or (fState_ == State::eInProgressHeaderSentState));
Require ((fState_ == State::eInProgress) or (GetContentSizePolicy () != ContentSizePolicy::eAutoCompute));
Require (s <= e);
if (s < e) {
Containers::ReserveSpeedTweekAddN (fBytes_, (e - s), kResponseBufferReallocChunkSizeReserve_);
fBytes_.insert (fBytes_.end (), s, e);
if (GetContentSizePolicy () == ContentSizePolicy::eAutoCompute) {
// Because for autocompute - illegal to call flush and then write
fContentSize_ = fBytes_.size ();
}
}
}
void Response::write (const wchar_t* s, const wchar_t* e)
{
lock_guard<const AssertExternallySynchronizedLock> critSec{*this};
Require ((fState_ == State::eInProgress) or (fState_ == State::eInProgressHeaderSentState));
Require ((fState_ == State::eInProgress) or (GetContentSizePolicy () != ContentSizePolicy::eAutoCompute));
Require (s <= e);
if (s < e) {
wstring tmp = wstring (s, e);
string cpStr = Characters::WideStringToNarrow (tmp, fCodePage_);
if (not cpStr.empty ()) {
fBytes_.insert (fBytes_.end (), reinterpret_cast<const byte*> (cpStr.c_str ()), reinterpret_cast<const byte*> (cpStr.c_str () + cpStr.length ()));
if (GetContentSizePolicy () == ContentSizePolicy::eAutoCompute) {
// Because for autocompute - illegal to call flush and then write
fContentSize_ = fBytes_.size ();
}
}
}
}
void Response::printf (const wchar_t* format, ...)
{
lock_guard<const AssertExternallySynchronizedLock> critSec{*this};
va_list argsList;
va_start (argsList, format);
String tmp = Characters::FormatV (format, argsList);
va_end (argsList);
write (tmp);
}
String Response::ToString () const
{
shared_lock<const AssertExternallySynchronizedLock> critSec{*this};
StringBuilder sb;
sb += L"{";
sb += L"Socket: " + Characters::ToString (fSocket_) + L", ";
sb += L"State_: " + Characters::ToString (fState_) + L", ";
sb += L"StatusOverrideReason_: '" + Characters::ToString (fStatusOverrideReason_) + L"', ";
sb += L"Headers: " + Characters::ToString (GetEffectiveHeaders ()) + L", ";
sb += L"}";
return sb.str ();
}
<|endoftext|>
|
<commit_before>/* This file is part of the KDE project
*
* Copyright (C) 2014 Dominik Haumann <[email protected]>
*
* This library is free software; you can redistribute it and/or
* modify it under the terms of the GNU Library General Public
* License as published by the Free Software Foundation; either
* version 2 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
* Library General Public License for more details.
*
* You should have received a copy of the GNU Library General Public License
* along with this library; see the file COPYING.LIB. If not, write to
* the Free Software Foundation, Inc., 51 Franklin Street, Fifth Floor,
* Boston, MA 02110-1301, USA.
*/
#include "katetabbutton.h"
#include <klocalizedstring.h>
#include <QApplication>
#include <QColorDialog>
#include <QContextMenuEvent>
#include <QFontDatabase>
#include <QIcon>
#include <QMenu>
#include <QPainter>
#include <QStyle>
#include <QStyleOption>
#include <QHBoxLayout>
// #include <QStyleOptionTab>
#include <KColorScheme>
TabCloseButton::TabCloseButton(QWidget * parent)
: QAbstractButton(parent)
{
// should never have focus
setFocusPolicy(Qt::NoFocus);
// closing a tab closes the document
setToolTip(i18n("Close Document"));
}
void TabCloseButton::paintEvent(QPaintEvent *event)
{
Q_UNUSED(event)
// get the tab this close button belongs to
KateTabButton *tabButton = qobject_cast<KateTabButton*>(parent());
const bool isActive = underMouse()
|| (tabButton && tabButton->isChecked());
// set style options depending on current state
QStyleOption opt;
opt.init(this);
if (isActive && !isDown()) {
opt.state |= QStyle::State_Raised;
}
if (isDown()) {
opt.state |= QStyle::State_Sunken;
}
QPainter p(this);
style()->drawPrimitive(QStyle::PE_IndicatorTabClose, &opt, &p, this);
}
QSize TabCloseButton::sizeHint() const
{
// make sure the widget is polished
ensurePolished();
// read the metrics from the style
const int w = style()->pixelMetric(QStyle::PM_TabCloseIndicatorWidth, 0, this);
const int h = style()->pixelMetric(QStyle::PM_TabCloseIndicatorHeight, 0, this);
return QSize(w, h);
}
void TabCloseButton::enterEvent(QEvent *event)
{
update(); // repaint on hover
QAbstractButton::enterEvent(event);
}
void TabCloseButton::leaveEvent(QEvent *event)
{
update(); // repaint on hover
QAbstractButton::leaveEvent(event);
}
QColor KateTabButton::s_predefinedColors[] = { Qt::red, Qt::yellow, Qt::green, Qt::cyan, Qt::blue, Qt::magenta };
const int KateTabButton::s_colorCount = 6;
int KateTabButton::s_currentColor = 0;
KateTabButton::KateTabButton(const QString &caption, QWidget *parent)
: QPushButton(parent)
{
setFont(QFontDatabase::systemFont(QFontDatabase::SmallestReadableFont));
setCheckable(true);
setFocusPolicy(Qt::NoFocus);
setMinimumWidth(1);
setFlat(true);
setIcon(QIcon());
setText(caption);
connect(this, SIGNAL(clicked()), this, SLOT(buttonClicked()));
// add close button
const int margin = style()->pixelMetric(QStyle::PM_ButtonMargin, 0, this);
m_closeButton = new TabCloseButton(this);
QHBoxLayout * hbox = new QHBoxLayout(this);
hbox->setSpacing(0);
hbox->setContentsMargins(0, 0, margin, 0);
hbox->addStretch();
hbox->addWidget(m_closeButton);
setLayout(hbox);
connect(m_closeButton, SIGNAL(clicked()), this, SLOT(closeButtonClicked()));
}
KateTabButton::~KateTabButton()
{
}
void KateTabButton::buttonClicked()
{
// once down, stay down until another tab is activated
if (isChecked()) {
emit activated(this);
} else {
setChecked(true);
}
}
void KateTabButton::closeButtonClicked()
{
emit closeRequest(this);
}
void KateTabButton::setActivated(bool active)
{
if (isChecked() == active) {
return;
}
setChecked(active);
update();
}
bool KateTabButton::isActivated() const
{
return isChecked();
}
void KateTabButton::paintEvent(QPaintEvent *ev)
{
Q_UNUSED(ev)
QColor barColor(palette().color(QPalette::Highlight));
// read from the parent widget (=KateTabBar) the isActiveViewSpace property
if (parentWidget()) {
if (! parentWidget()->property("isActiveViewSpace").toBool()) {
// if inactive, convert color to gray value
const int g = qGray(barColor.rgb());
barColor = QColor(g, g, g);
}
}
QPainter p(this);
// paint background rect
if (isChecked() || underMouse()) {
QStyleOptionViewItemV4 option;
option.initFrom(this);
barColor.setAlpha(50);
option.backgroundBrush = barColor;
option.state = QStyle::State_Enabled | QStyle::State_MouseOver;
option.viewItemPosition = QStyleOptionViewItemV4::OnlyOne;
style()->drawPrimitive(QStyle::PE_PanelItemViewItem, &option, &p, this);
}
// paint bar
if (isActivated()) {
barColor.setAlpha(255);
p.fillRect(QRect(0, height() - 3, width(), 10), barColor);
} else if (m_highlightColor.isValid()) {
p.setOpacity(0.3);
p.fillRect(QRect(0, height() - 3, width(), 10), m_highlightColor);
p.setOpacity(1.0);
}
// icon, if applicable
const int margin = style()->pixelMetric(QStyle::PM_ButtonMargin, 0, this);
int leftMargin = margin;
if (! icon().isNull()) {
const int y = (height() - 16) / 2;
icon().paint(&p, margin, y, 16, 16);
leftMargin += 16;
leftMargin += margin;
}
// the width of the text is reduced by the close button + 2 * margin
const int w = width() // width of widget
- m_closeButton->width() - 2 * margin // close button
- leftMargin; // modified button
// draw text, we need to elide to xxx...xxx is too long
const QString elidedText = QFontMetrics(font()).elidedText (text(), Qt::ElideMiddle, w);
const QRect textRect(leftMargin, 0, w, height());
const QPalette pal = QApplication::palette();
style()->drawItemText(&p, textRect, Qt::AlignHCenter | Qt::AlignVCenter, pal, true, elidedText);
// QStyleOptionTab option;
// option.init(this);
// option.cornerWidgets = QStyleOptionTab::NoCornerWidgets;
// option.documentMode = true;
// option.icon = icon();
// option.iconSize = QSize(16, 16);
// // QSize leftButtonSize
// option.position = QStyleOptionTab::Middle;
// option.rightButtonSize = QSize(16, 16);
// option.row = 0;
// option.selectedPosition = QStyleOptionTab::NotAdjacent;
// option.shape = QTabBar::RoundedNorth;
// option.text = text();
//
// style()->drawControl(QStyle::CE_TabBarTabLabel, &option, &p);
}
void KateTabButton::contextMenuEvent(QContextMenuEvent *ev)
{
QPixmap colorIcon(22, 22);
QMenu menu(/*text(),*/ this);
QMenu *colorMenu = menu.addMenu(i18n("&Highlight Tab"));
QAction *aNone = colorMenu->addAction(i18n("&None"));
colorMenu->addSeparator();
colorIcon.fill(Qt::red);
QAction *aRed = colorMenu->addAction(colorIcon, i18n("&Red"));
colorIcon.fill(Qt::yellow);
QAction *aYellow = colorMenu->addAction(colorIcon, i18n("&Yellow"));
colorIcon.fill(Qt::green);
QAction *aGreen = colorMenu->addAction(colorIcon, i18n("&Green"));
colorIcon.fill(Qt::cyan);
QAction *aCyan = colorMenu->addAction(colorIcon, i18n("&Cyan"));
colorIcon.fill(Qt::blue);
QAction *aBlue = colorMenu->addAction(colorIcon, i18n("&Blue"));
colorIcon.fill(Qt::magenta);
QAction *aMagenta = colorMenu->addAction(colorIcon, i18n("&Magenta"));
colorMenu->addSeparator();
QAction *aCustomColor = colorMenu->addAction(
QIcon::fromTheme(QStringLiteral("colors")), i18n("C&ustom Color..."));
menu.addSeparator();
QAction *aCloseTab = menu.addAction(i18n("&Close Document"));
QAction *choice = menu.exec(ev->globalPos());
// process the result
if (choice == aNone) {
if (m_highlightColor.isValid()) {
setHighlightColor(QColor());
emit highlightChanged(this);
}
} else if (choice == aRed) {
setHighlightColor(Qt::red);
emit highlightChanged(this);
} else if (choice == aYellow) {
setHighlightColor(Qt::yellow);
emit highlightChanged(this);
} else if (choice == aGreen) {
setHighlightColor(Qt::green);
emit highlightChanged(this);
} else if (choice == aCyan) {
setHighlightColor(Qt::cyan);
emit highlightChanged(this);
} else if (choice == aBlue) {
setHighlightColor(Qt::blue);
emit highlightChanged(this);
} else if (choice == aMagenta) {
setHighlightColor(Qt::magenta);
emit highlightChanged(this);
} else if (choice == aCustomColor) {
QColor newColor = QColorDialog::getColor(m_highlightColor, this);
if (newColor.isValid()) {
setHighlightColor(newColor);
emit highlightChanged(this);
}
} else if (choice == aCloseTab) {
emit closeRequest(this);
}
}
void KateTabButton::mousePressEvent(QMouseEvent *ev)
{
if (ev->button() == Qt::MidButton) {
if (ev->modifiers() & Qt::ControlModifier) {
// clear tab highlight
setHighlightColor(QColor());
} else {
setHighlightColor(s_predefinedColors[s_currentColor]);
if (++s_currentColor >= s_colorCount) {
s_currentColor = 0;
}
}
ev->accept();
} else {
QPushButton::mousePressEvent(ev);
}
}
void KateTabButton::mouseDoubleClickEvent(QMouseEvent *event)
{
event->accept();
}
void KateTabButton::setHighlightColor(const QColor &color)
{
if (color.isValid()) {
m_highlightColor = color;
update();
} else if (m_highlightColor.isValid()) {
m_highlightColor = QColor();
update();
}
}
QColor KateTabButton::highlightColor() const
{
return m_highlightColor;
}
<commit_msg>remove commented out code<commit_after>/* This file is part of the KDE project
*
* Copyright (C) 2014 Dominik Haumann <[email protected]>
*
* This library is free software; you can redistribute it and/or
* modify it under the terms of the GNU Library General Public
* License as published by the Free Software Foundation; either
* version 2 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
* Library General Public License for more details.
*
* You should have received a copy of the GNU Library General Public License
* along with this library; see the file COPYING.LIB. If not, write to
* the Free Software Foundation, Inc., 51 Franklin Street, Fifth Floor,
* Boston, MA 02110-1301, USA.
*/
#include "katetabbutton.h"
#include <klocalizedstring.h>
#include <QApplication>
#include <QColorDialog>
#include <QContextMenuEvent>
#include <QFontDatabase>
#include <QIcon>
#include <QMenu>
#include <QPainter>
#include <QStyle>
#include <QStyleOption>
#include <QHBoxLayout>
#include <KColorScheme>
TabCloseButton::TabCloseButton(QWidget * parent)
: QAbstractButton(parent)
{
// should never have focus
setFocusPolicy(Qt::NoFocus);
// closing a tab closes the document
setToolTip(i18n("Close Document"));
}
void TabCloseButton::paintEvent(QPaintEvent *event)
{
Q_UNUSED(event)
// get the tab this close button belongs to
KateTabButton *tabButton = qobject_cast<KateTabButton*>(parent());
const bool isActive = underMouse()
|| (tabButton && tabButton->isChecked());
// set style options depending on current state
QStyleOption opt;
opt.init(this);
if (isActive && !isDown()) {
opt.state |= QStyle::State_Raised;
}
if (isDown()) {
opt.state |= QStyle::State_Sunken;
}
QPainter p(this);
style()->drawPrimitive(QStyle::PE_IndicatorTabClose, &opt, &p, this);
}
QSize TabCloseButton::sizeHint() const
{
// make sure the widget is polished
ensurePolished();
// read the metrics from the style
const int w = style()->pixelMetric(QStyle::PM_TabCloseIndicatorWidth, 0, this);
const int h = style()->pixelMetric(QStyle::PM_TabCloseIndicatorHeight, 0, this);
return QSize(w, h);
}
void TabCloseButton::enterEvent(QEvent *event)
{
update(); // repaint on hover
QAbstractButton::enterEvent(event);
}
void TabCloseButton::leaveEvent(QEvent *event)
{
update(); // repaint on hover
QAbstractButton::leaveEvent(event);
}
QColor KateTabButton::s_predefinedColors[] = { Qt::red, Qt::yellow, Qt::green, Qt::cyan, Qt::blue, Qt::magenta };
const int KateTabButton::s_colorCount = 6;
int KateTabButton::s_currentColor = 0;
KateTabButton::KateTabButton(const QString &caption, QWidget *parent)
: QPushButton(parent)
{
setFont(QFontDatabase::systemFont(QFontDatabase::SmallestReadableFont));
setCheckable(true);
setFocusPolicy(Qt::NoFocus);
setMinimumWidth(1);
setFlat(true);
setIcon(QIcon());
setText(caption);
connect(this, SIGNAL(clicked()), this, SLOT(buttonClicked()));
// add close button
const int margin = style()->pixelMetric(QStyle::PM_ButtonMargin, 0, this);
m_closeButton = new TabCloseButton(this);
QHBoxLayout * hbox = new QHBoxLayout(this);
hbox->setSpacing(0);
hbox->setContentsMargins(0, 0, margin, 0);
hbox->addStretch();
hbox->addWidget(m_closeButton);
setLayout(hbox);
connect(m_closeButton, SIGNAL(clicked()), this, SLOT(closeButtonClicked()));
}
KateTabButton::~KateTabButton()
{
}
void KateTabButton::buttonClicked()
{
// once down, stay down until another tab is activated
if (isChecked()) {
emit activated(this);
} else {
setChecked(true);
}
}
void KateTabButton::closeButtonClicked()
{
emit closeRequest(this);
}
void KateTabButton::setActivated(bool active)
{
if (isChecked() == active) {
return;
}
setChecked(active);
update();
}
bool KateTabButton::isActivated() const
{
return isChecked();
}
void KateTabButton::paintEvent(QPaintEvent *ev)
{
Q_UNUSED(ev)
QColor barColor(palette().color(QPalette::Highlight));
// read from the parent widget (=KateTabBar) the isActiveViewSpace property
if (parentWidget()) {
if (! parentWidget()->property("isActiveViewSpace").toBool()) {
// if inactive, convert color to gray value
const int g = qGray(barColor.rgb());
barColor = QColor(g, g, g);
}
}
QPainter p(this);
// paint background rect
if (isChecked() || underMouse()) {
QStyleOptionViewItemV4 option;
option.initFrom(this);
barColor.setAlpha(50);
option.backgroundBrush = barColor;
option.state = QStyle::State_Enabled | QStyle::State_MouseOver;
option.viewItemPosition = QStyleOptionViewItemV4::OnlyOne;
style()->drawPrimitive(QStyle::PE_PanelItemViewItem, &option, &p, this);
}
// paint bar
if (isActivated()) {
barColor.setAlpha(255);
p.fillRect(QRect(0, height() - 3, width(), 10), barColor);
} else if (m_highlightColor.isValid()) {
p.setOpacity(0.3);
p.fillRect(QRect(0, height() - 3, width(), 10), m_highlightColor);
p.setOpacity(1.0);
}
// icon, if applicable
const int margin = style()->pixelMetric(QStyle::PM_ButtonMargin, 0, this);
int leftMargin = margin;
if (! icon().isNull()) {
const int y = (height() - 16) / 2;
icon().paint(&p, margin, y, 16, 16);
leftMargin += 16;
leftMargin += margin;
}
// the width of the text is reduced by the close button + 2 * margin
const int w = width() // width of widget
- m_closeButton->width() - 2 * margin // close button
- leftMargin; // modified button
// draw text, we need to elide to xxx...xxx is too long
const QString elidedText = QFontMetrics(font()).elidedText (text(), Qt::ElideMiddle, w);
const QRect textRect(leftMargin, 0, w, height());
const QPalette pal = QApplication::palette();
style()->drawItemText(&p, textRect, Qt::AlignHCenter | Qt::AlignVCenter, pal, true, elidedText);
}
void KateTabButton::contextMenuEvent(QContextMenuEvent *ev)
{
QPixmap colorIcon(22, 22);
QMenu menu(/*text(),*/ this);
QMenu *colorMenu = menu.addMenu(i18n("&Highlight Tab"));
QAction *aNone = colorMenu->addAction(i18n("&None"));
colorMenu->addSeparator();
colorIcon.fill(Qt::red);
QAction *aRed = colorMenu->addAction(colorIcon, i18n("&Red"));
colorIcon.fill(Qt::yellow);
QAction *aYellow = colorMenu->addAction(colorIcon, i18n("&Yellow"));
colorIcon.fill(Qt::green);
QAction *aGreen = colorMenu->addAction(colorIcon, i18n("&Green"));
colorIcon.fill(Qt::cyan);
QAction *aCyan = colorMenu->addAction(colorIcon, i18n("&Cyan"));
colorIcon.fill(Qt::blue);
QAction *aBlue = colorMenu->addAction(colorIcon, i18n("&Blue"));
colorIcon.fill(Qt::magenta);
QAction *aMagenta = colorMenu->addAction(colorIcon, i18n("&Magenta"));
colorMenu->addSeparator();
QAction *aCustomColor = colorMenu->addAction(
QIcon::fromTheme(QStringLiteral("colors")), i18n("C&ustom Color..."));
menu.addSeparator();
QAction *aCloseTab = menu.addAction(i18n("&Close Document"));
QAction *choice = menu.exec(ev->globalPos());
// process the result
if (choice == aNone) {
if (m_highlightColor.isValid()) {
setHighlightColor(QColor());
emit highlightChanged(this);
}
} else if (choice == aRed) {
setHighlightColor(Qt::red);
emit highlightChanged(this);
} else if (choice == aYellow) {
setHighlightColor(Qt::yellow);
emit highlightChanged(this);
} else if (choice == aGreen) {
setHighlightColor(Qt::green);
emit highlightChanged(this);
} else if (choice == aCyan) {
setHighlightColor(Qt::cyan);
emit highlightChanged(this);
} else if (choice == aBlue) {
setHighlightColor(Qt::blue);
emit highlightChanged(this);
} else if (choice == aMagenta) {
setHighlightColor(Qt::magenta);
emit highlightChanged(this);
} else if (choice == aCustomColor) {
QColor newColor = QColorDialog::getColor(m_highlightColor, this);
if (newColor.isValid()) {
setHighlightColor(newColor);
emit highlightChanged(this);
}
} else if (choice == aCloseTab) {
emit closeRequest(this);
}
}
void KateTabButton::mousePressEvent(QMouseEvent *ev)
{
if (ev->button() == Qt::MidButton) {
if (ev->modifiers() & Qt::ControlModifier) {
// clear tab highlight
setHighlightColor(QColor());
} else {
setHighlightColor(s_predefinedColors[s_currentColor]);
if (++s_currentColor >= s_colorCount) {
s_currentColor = 0;
}
}
ev->accept();
} else {
QPushButton::mousePressEvent(ev);
}
}
void KateTabButton::mouseDoubleClickEvent(QMouseEvent *event)
{
event->accept();
}
void KateTabButton::setHighlightColor(const QColor &color)
{
if (color.isValid()) {
m_highlightColor = color;
update();
} else if (m_highlightColor.isValid()) {
m_highlightColor = QColor();
update();
}
}
QColor KateTabButton::highlightColor() const
{
return m_highlightColor;
}
<|endoftext|>
|
<commit_before>/* ------------------------------------------------------------------------ */
/* Copyright 2002-2010, OpenNebula Project Leads (OpenNebula.org) */
/* */
/* 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 <limits.h>
#include <string.h>
#include <iostream>
#include <sstream>
#include "Host.h"
#include "NebulaLog.h"
/* ************************************************************************ */
/* Host :: Constructor/Destructor */
/* ************************************************************************ */
Host::Host(
int id,
string _hostname,
string _im_mad_name,
string _vmm_mad_name,
string _tm_mad_name):
PoolObjectSQL(id),
hostname(_hostname),
state(INIT),
im_mad_name(_im_mad_name),
vmm_mad_name(_vmm_mad_name),
tm_mad_name(_tm_mad_name),
last_monitored(0),
cluster(ClusterPool::DEFAULT_CLUSTER_NAME),
host_template(id)
{};
Host::~Host(){};
/* ************************************************************************ */
/* Host :: Database Access Functions */
/* ************************************************************************ */
const char * Host::table = "host_pool";
const char * Host::db_names = "(oid,host_name,state,im_mad,vm_mad,"
"tm_mad,last_mon_time, cluster, template)";
const char * Host::db_bootstrap = "CREATE TABLE IF NOT EXISTS host_pool ("
"oid INTEGER PRIMARY KEY,host_name VARCHAR(512), state INTEGER,"
"im_mad VARCHAR(128),vm_mad VARCHAR(128),tm_mad VARCHAR(128),"
"last_mon_time INTEGER, cluster VARCHAR(128), template TEXT, "
"UNIQUE(host_name, im_mad, vm_mad, tm_mad) )";
/* ------------------------------------------------------------------------ */
/* ------------------------------------------------------------------------ */
int Host::select_cb(void * nil, int num, char **values, char ** names)
{
if ((!values[OID]) ||
(!values[HOST_NAME]) ||
(!values[STATE]) ||
(!values[IM_MAD]) ||
(!values[VM_MAD]) ||
(!values[TM_MAD]) ||
(!values[LAST_MON_TIME]) ||
(!values[CLUSTER]) ||
(!values[TEMPLATE]) ||
(num != LIMIT ))
{
return -1;
}
oid = atoi(values[OID]);
hostname = values[HOST_NAME];
state = static_cast<HostState>(atoi(values[STATE]));
im_mad_name = values[IM_MAD];
vmm_mad_name = values[VM_MAD];
tm_mad_name = values[TM_MAD];
last_monitored = static_cast<time_t>(atoi(values[LAST_MON_TIME]));
cluster = values[CLUSTER];
// TODO: Template needs to be cleared before?
host_template.from_xml(values[TEMPLATE]);
host_share.hsid = oid;
return 0;
}
/* ------------------------------------------------------------------------ */
int Host::select(SqlDB *db)
{
ostringstream oss;
int rc;
int boid;
set_callback(static_cast<Callbackable::Callback>(&Host::select_cb));
oss << "SELECT * FROM " << table << " WHERE oid = " << oid;
boid = oid;
oid = -1;
rc = db->exec(oss, this);
unset_callback();
if ((rc != 0) || (oid != boid ))
{
return -1;
}
if ( rc != 0 )
{
return -1;
}
// Select the host shares from the DB
rc = host_share.select(db);
if ( rc != 0 )
{
return rc;
}
return 0;
}
/* ------------------------------------------------------------------------ */
/* ------------------------------------------------------------------------ */
int Host::insert(SqlDB *db)
{
int rc;
map<int,HostShare *>::iterator iter;
// Set up the share ID, to insert it
if ( host_share.hsid == -1 )
{
host_share.hsid = oid;
}
// Update the HostShare
rc = host_share.insert(db);
if ( rc != 0 )
{
return rc;
}
//Insert the Host
rc = insert_replace(db, false);
if ( rc != 0 )
{
host_share.drop(db);
return rc;
}
return 0;
}
/* ------------------------------------------------------------------------ */
/* ------------------------------------------------------------------------ */
int Host::update(SqlDB *db)
{
int rc;
// Update the HostShare
rc = host_share.update(db);
if ( rc != 0 )
{
return rc;
}
rc = insert_replace(db, true);
if ( rc != 0 )
{
return rc;
}
return 0;
}
/* ------------------------------------------------------------------------ */
/* ------------------------------------------------------------------------ */
int Host::insert_replace(SqlDB *db, bool replace)
{
ostringstream oss;
int rc;
string xml_template;
char * sql_hostname;
char * sql_im_mad_name;
char * sql_tm_mad_name;
char * sql_vmm_mad_name;
char * sql_cluster;
char * sql_template;
// Update the Host
sql_hostname = db->escape_str(hostname.c_str());
if ( sql_hostname == 0 )
{
goto error_hostname;
}
sql_im_mad_name = db->escape_str(im_mad_name.c_str());
if ( sql_im_mad_name == 0 )
{
goto error_im;
}
sql_tm_mad_name = db->escape_str(tm_mad_name.c_str());
if ( sql_tm_mad_name == 0 )
{
goto error_tm;
}
sql_vmm_mad_name = db->escape_str(vmm_mad_name.c_str());
if ( sql_vmm_mad_name == 0 )
{
goto error_vmm;
}
sql_cluster = db->escape_str(cluster.c_str());
if ( sql_cluster == 0 )
{
goto error_cluster;
}
host_template.to_xml(xml_template);
sql_template = db->escape_str(xml_template.c_str());
if ( sql_template == 0 )
{
goto error_template;
}
if(replace)
{
oss << "REPLACE";
}
else
{
oss << "INSERT";
}
// Construct the SQL statement to Insert or Replace
oss <<" INTO "<< table <<" "<< db_names <<" VALUES ("
<< oid << ","
<< "'" << sql_hostname << "',"
<< state << ","
<< "'" << sql_im_mad_name << "',"
<< "'" << sql_vmm_mad_name << "',"
<< "'" << sql_tm_mad_name << "',"
<< last_monitored << ","
<< "'" << sql_cluster << "',"
<< "'" << sql_template << "')";
rc = db->exec(oss);
db->free_str(sql_hostname);
db->free_str(sql_im_mad_name);
db->free_str(sql_tm_mad_name);
db->free_str(sql_vmm_mad_name);
db->free_str(sql_cluster);
db->free_str(sql_template);
return rc;
error_template:
db->free_str(sql_cluster);
error_cluster:
db->free_str(sql_vmm_mad_name);
error_vmm:
db->free_str(sql_tm_mad_name);
error_tm:
db->free_str(sql_im_mad_name);
error_im:
db->free_str(sql_hostname);
error_hostname:
return -1;
}
/* ------------------------------------------------------------------------ */
/* ------------------------------------------------------------------------ */
int Host::dump(ostringstream& oss, int num, char **values, char **names)
{
if ((!values[OID]) ||
(!values[HOST_NAME]) ||
(!values[STATE]) ||
(!values[IM_MAD]) ||
(!values[VM_MAD]) ||
(!values[TM_MAD]) ||
(!values[LAST_MON_TIME]) ||
(!values[CLUSTER]) ||
(!values[TEMPLATE]) ||
(num != LIMIT + HostShare::LIMIT ))
{
return -1;
}
oss <<
"<HOST>" <<
"<ID>" << values[OID] <<"</ID>" <<
"<NAME>" << values[HOST_NAME] <<"</NAME>" <<
"<STATE>" << values[STATE] <<"</STATE>" <<
"<IM_MAD>" << values[IM_MAD] <<"</IM_MAD>" <<
"<VM_MAD>" << values[VM_MAD] <<"</VM_MAD>" <<
"<TM_MAD>" << values[TM_MAD] <<"</TM_MAD>" <<
"<LAST_MON_TIME>"<< values[LAST_MON_TIME]<<"</LAST_MON_TIME>"<<
"<CLUSTER>" << values[CLUSTER] <<"</CLUSTER>" <<
values[TEMPLATE];
HostShare::dump(oss,num - LIMIT, values + LIMIT, names + LIMIT);
oss << "</HOST>";
return 0;
}
/* ------------------------------------------------------------------------ */
/* ------------------------------------------------------------------------ */
int Host::drop(SqlDB * db)
{
ostringstream oss;
int rc;
host_share.drop(db);
oss << "DELETE FROM " << table << " WHERE oid=" << oid;
rc = db->exec(oss);
if ( rc == 0 )
{
set_valid(false);
}
return rc;
}
/* ------------------------------------------------------------------------ */
/* ------------------------------------------------------------------------ */
int Host::update_info(string &parse_str)
{
char * error_msg;
int rc;
rc = host_template.parse(parse_str, &error_msg);
if ( rc != 0 )
{
NebulaLog::log("ONE", Log::ERROR, error_msg);
free(error_msg);
return -1;
}
get_template_attribute("TOTALCPU",host_share.max_cpu);
get_template_attribute("TOTALMEMORY",host_share.max_mem);
get_template_attribute("FREECPU",host_share.free_cpu);
get_template_attribute("FREEMEMORY",host_share.free_mem);
get_template_attribute("USEDCPU",host_share.used_cpu);
get_template_attribute("USEDMEMORY",host_share.used_mem);
return 0;
}
/* ************************************************************************ */
/* Host :: Misc */
/* ************************************************************************ */
ostream& operator<<(ostream& os, Host& host)
{
string host_str;
os << host.to_xml(host_str);
return os;
};
/* ------------------------------------------------------------------------ */
/* ------------------------------------------------------------------------ */
string& Host::to_xml(string& xml) const
{
string template_xml;
string share_xml;
ostringstream oss;
oss <<
"<HOST>"
"<ID>" << oid << "</ID>" <<
"<NAME>" << hostname << "</NAME>" <<
"<STATE>" << state << "</STATE>" <<
"<IM_MAD>" << im_mad_name << "</IM_MAD>" <<
"<VM_MAD>" << vmm_mad_name << "</VM_MAD>" <<
"<TM_MAD>" << tm_mad_name << "</TM_MAD>" <<
"<LAST_MON_TIME>" << last_monitored << "</LAST_MON_TIME>" <<
"<CLUSTER>" << cluster << "</CLUSTER>" <<
host_share.to_xml(share_xml) <<
host_template.to_xml(template_xml) <<
"</HOST>";
xml = oss.str();
return xml;
}
/* ------------------------------------------------------------------------ */
/* ------------------------------------------------------------------------ */
string& Host::to_str(string& str) const
{
string template_str;
string share_str;
ostringstream os;
os <<
"ID = " << oid << endl <<
"NAME = " << hostname << endl <<
"STATE = " << state << endl <<
"IM MAD = " << im_mad_name << endl <<
"VMM MAD = " << vmm_mad_name << endl <<
"TM MAD = " << tm_mad_name << endl <<
"LAST_MON = " << last_monitored << endl <<
"CLUSTER = " << cluster << endl <<
"ATTRIBUTES" << endl << host_template.to_str(template_str) << endl <<
"HOST SHARES" << endl << host_share.to_str(share_str) <<endl;
str = os.str();
return str;
}
<commit_msg>feature #282: Removed already addressed TODO<commit_after>/* ------------------------------------------------------------------------ */
/* Copyright 2002-2010, OpenNebula Project Leads (OpenNebula.org) */
/* */
/* 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 <limits.h>
#include <string.h>
#include <iostream>
#include <sstream>
#include "Host.h"
#include "NebulaLog.h"
/* ************************************************************************ */
/* Host :: Constructor/Destructor */
/* ************************************************************************ */
Host::Host(
int id,
string _hostname,
string _im_mad_name,
string _vmm_mad_name,
string _tm_mad_name):
PoolObjectSQL(id),
hostname(_hostname),
state(INIT),
im_mad_name(_im_mad_name),
vmm_mad_name(_vmm_mad_name),
tm_mad_name(_tm_mad_name),
last_monitored(0),
cluster(ClusterPool::DEFAULT_CLUSTER_NAME),
host_template(id)
{};
Host::~Host(){};
/* ************************************************************************ */
/* Host :: Database Access Functions */
/* ************************************************************************ */
const char * Host::table = "host_pool";
const char * Host::db_names = "(oid,host_name,state,im_mad,vm_mad,"
"tm_mad,last_mon_time, cluster, template)";
const char * Host::db_bootstrap = "CREATE TABLE IF NOT EXISTS host_pool ("
"oid INTEGER PRIMARY KEY,host_name VARCHAR(512), state INTEGER,"
"im_mad VARCHAR(128),vm_mad VARCHAR(128),tm_mad VARCHAR(128),"
"last_mon_time INTEGER, cluster VARCHAR(128), template TEXT, "
"UNIQUE(host_name, im_mad, vm_mad, tm_mad) )";
/* ------------------------------------------------------------------------ */
/* ------------------------------------------------------------------------ */
int Host::select_cb(void * nil, int num, char **values, char ** names)
{
if ((!values[OID]) ||
(!values[HOST_NAME]) ||
(!values[STATE]) ||
(!values[IM_MAD]) ||
(!values[VM_MAD]) ||
(!values[TM_MAD]) ||
(!values[LAST_MON_TIME]) ||
(!values[CLUSTER]) ||
(!values[TEMPLATE]) ||
(num != LIMIT ))
{
return -1;
}
oid = atoi(values[OID]);
hostname = values[HOST_NAME];
state = static_cast<HostState>(atoi(values[STATE]));
im_mad_name = values[IM_MAD];
vmm_mad_name = values[VM_MAD];
tm_mad_name = values[TM_MAD];
last_monitored = static_cast<time_t>(atoi(values[LAST_MON_TIME]));
cluster = values[CLUSTER];
host_template.from_xml(values[TEMPLATE]);
host_share.hsid = oid;
return 0;
}
/* ------------------------------------------------------------------------ */
int Host::select(SqlDB *db)
{
ostringstream oss;
int rc;
int boid;
set_callback(static_cast<Callbackable::Callback>(&Host::select_cb));
oss << "SELECT * FROM " << table << " WHERE oid = " << oid;
boid = oid;
oid = -1;
rc = db->exec(oss, this);
unset_callback();
if ((rc != 0) || (oid != boid ))
{
return -1;
}
if ( rc != 0 )
{
return -1;
}
// Select the host shares from the DB
rc = host_share.select(db);
if ( rc != 0 )
{
return rc;
}
return 0;
}
/* ------------------------------------------------------------------------ */
/* ------------------------------------------------------------------------ */
int Host::insert(SqlDB *db)
{
int rc;
map<int,HostShare *>::iterator iter;
// Set up the share ID, to insert it
if ( host_share.hsid == -1 )
{
host_share.hsid = oid;
}
// Update the HostShare
rc = host_share.insert(db);
if ( rc != 0 )
{
return rc;
}
//Insert the Host
rc = insert_replace(db, false);
if ( rc != 0 )
{
host_share.drop(db);
return rc;
}
return 0;
}
/* ------------------------------------------------------------------------ */
/* ------------------------------------------------------------------------ */
int Host::update(SqlDB *db)
{
int rc;
// Update the HostShare
rc = host_share.update(db);
if ( rc != 0 )
{
return rc;
}
rc = insert_replace(db, true);
if ( rc != 0 )
{
return rc;
}
return 0;
}
/* ------------------------------------------------------------------------ */
/* ------------------------------------------------------------------------ */
int Host::insert_replace(SqlDB *db, bool replace)
{
ostringstream oss;
int rc;
string xml_template;
char * sql_hostname;
char * sql_im_mad_name;
char * sql_tm_mad_name;
char * sql_vmm_mad_name;
char * sql_cluster;
char * sql_template;
// Update the Host
sql_hostname = db->escape_str(hostname.c_str());
if ( sql_hostname == 0 )
{
goto error_hostname;
}
sql_im_mad_name = db->escape_str(im_mad_name.c_str());
if ( sql_im_mad_name == 0 )
{
goto error_im;
}
sql_tm_mad_name = db->escape_str(tm_mad_name.c_str());
if ( sql_tm_mad_name == 0 )
{
goto error_tm;
}
sql_vmm_mad_name = db->escape_str(vmm_mad_name.c_str());
if ( sql_vmm_mad_name == 0 )
{
goto error_vmm;
}
sql_cluster = db->escape_str(cluster.c_str());
if ( sql_cluster == 0 )
{
goto error_cluster;
}
host_template.to_xml(xml_template);
sql_template = db->escape_str(xml_template.c_str());
if ( sql_template == 0 )
{
goto error_template;
}
if(replace)
{
oss << "REPLACE";
}
else
{
oss << "INSERT";
}
// Construct the SQL statement to Insert or Replace
oss <<" INTO "<< table <<" "<< db_names <<" VALUES ("
<< oid << ","
<< "'" << sql_hostname << "',"
<< state << ","
<< "'" << sql_im_mad_name << "',"
<< "'" << sql_vmm_mad_name << "',"
<< "'" << sql_tm_mad_name << "',"
<< last_monitored << ","
<< "'" << sql_cluster << "',"
<< "'" << sql_template << "')";
rc = db->exec(oss);
db->free_str(sql_hostname);
db->free_str(sql_im_mad_name);
db->free_str(sql_tm_mad_name);
db->free_str(sql_vmm_mad_name);
db->free_str(sql_cluster);
db->free_str(sql_template);
return rc;
error_template:
db->free_str(sql_cluster);
error_cluster:
db->free_str(sql_vmm_mad_name);
error_vmm:
db->free_str(sql_tm_mad_name);
error_tm:
db->free_str(sql_im_mad_name);
error_im:
db->free_str(sql_hostname);
error_hostname:
return -1;
}
/* ------------------------------------------------------------------------ */
/* ------------------------------------------------------------------------ */
int Host::dump(ostringstream& oss, int num, char **values, char **names)
{
if ((!values[OID]) ||
(!values[HOST_NAME]) ||
(!values[STATE]) ||
(!values[IM_MAD]) ||
(!values[VM_MAD]) ||
(!values[TM_MAD]) ||
(!values[LAST_MON_TIME]) ||
(!values[CLUSTER]) ||
(!values[TEMPLATE]) ||
(num != LIMIT + HostShare::LIMIT ))
{
return -1;
}
oss <<
"<HOST>" <<
"<ID>" << values[OID] <<"</ID>" <<
"<NAME>" << values[HOST_NAME] <<"</NAME>" <<
"<STATE>" << values[STATE] <<"</STATE>" <<
"<IM_MAD>" << values[IM_MAD] <<"</IM_MAD>" <<
"<VM_MAD>" << values[VM_MAD] <<"</VM_MAD>" <<
"<TM_MAD>" << values[TM_MAD] <<"</TM_MAD>" <<
"<LAST_MON_TIME>"<< values[LAST_MON_TIME]<<"</LAST_MON_TIME>"<<
"<CLUSTER>" << values[CLUSTER] <<"</CLUSTER>" <<
values[TEMPLATE];
HostShare::dump(oss,num - LIMIT, values + LIMIT, names + LIMIT);
oss << "</HOST>";
return 0;
}
/* ------------------------------------------------------------------------ */
/* ------------------------------------------------------------------------ */
int Host::drop(SqlDB * db)
{
ostringstream oss;
int rc;
host_share.drop(db);
oss << "DELETE FROM " << table << " WHERE oid=" << oid;
rc = db->exec(oss);
if ( rc == 0 )
{
set_valid(false);
}
return rc;
}
/* ------------------------------------------------------------------------ */
/* ------------------------------------------------------------------------ */
int Host::update_info(string &parse_str)
{
char * error_msg;
int rc;
rc = host_template.parse(parse_str, &error_msg);
if ( rc != 0 )
{
NebulaLog::log("ONE", Log::ERROR, error_msg);
free(error_msg);
return -1;
}
get_template_attribute("TOTALCPU",host_share.max_cpu);
get_template_attribute("TOTALMEMORY",host_share.max_mem);
get_template_attribute("FREECPU",host_share.free_cpu);
get_template_attribute("FREEMEMORY",host_share.free_mem);
get_template_attribute("USEDCPU",host_share.used_cpu);
get_template_attribute("USEDMEMORY",host_share.used_mem);
return 0;
}
/* ************************************************************************ */
/* Host :: Misc */
/* ************************************************************************ */
ostream& operator<<(ostream& os, Host& host)
{
string host_str;
os << host.to_xml(host_str);
return os;
};
/* ------------------------------------------------------------------------ */
/* ------------------------------------------------------------------------ */
string& Host::to_xml(string& xml) const
{
string template_xml;
string share_xml;
ostringstream oss;
oss <<
"<HOST>"
"<ID>" << oid << "</ID>" <<
"<NAME>" << hostname << "</NAME>" <<
"<STATE>" << state << "</STATE>" <<
"<IM_MAD>" << im_mad_name << "</IM_MAD>" <<
"<VM_MAD>" << vmm_mad_name << "</VM_MAD>" <<
"<TM_MAD>" << tm_mad_name << "</TM_MAD>" <<
"<LAST_MON_TIME>" << last_monitored << "</LAST_MON_TIME>" <<
"<CLUSTER>" << cluster << "</CLUSTER>" <<
host_share.to_xml(share_xml) <<
host_template.to_xml(template_xml) <<
"</HOST>";
xml = oss.str();
return xml;
}
/* ------------------------------------------------------------------------ */
/* ------------------------------------------------------------------------ */
string& Host::to_str(string& str) const
{
string template_str;
string share_str;
ostringstream os;
os <<
"ID = " << oid << endl <<
"NAME = " << hostname << endl <<
"STATE = " << state << endl <<
"IM MAD = " << im_mad_name << endl <<
"VMM MAD = " << vmm_mad_name << endl <<
"TM MAD = " << tm_mad_name << endl <<
"LAST_MON = " << last_monitored << endl <<
"CLUSTER = " << cluster << endl <<
"ATTRIBUTES" << endl << host_template.to_str(template_str) << endl <<
"HOST SHARES" << endl << host_share.to_str(share_str) <<endl;
str = os.str();
return str;
}
<|endoftext|>
|
<commit_before>/*
* Copyright (c) 2004 The Regents of The University of Michigan
* 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 copyright holders 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.
*/
/**
* @file
* linux_system.cc loads the linux kernel, console, pal and patches certain functions.
* The symbol tables are loaded so that traces can show the executing function and we can
* skip functions. Various delay loops are skipped and their final values manually computed to
* speed up boot time.
*/
#include "base/loader/aout_object.hh"
#include "base/loader/elf_object.hh"
#include "base/loader/object_file.hh"
#include "base/loader/symtab.hh"
#include "base/remote_gdb.hh"
#include "base/trace.hh"
#include "cpu/exec_context.hh"
#include "cpu/base_cpu.hh"
#include "kern/linux/linux_events.hh"
#include "kern/linux/linux_system.hh"
#include "kern/system_events.hh"
#include "mem/functional_mem/memory_control.hh"
#include "mem/functional_mem/physical_memory.hh"
#include "sim/builder.hh"
#include "dev/platform.hh"
#include "targetarch/isa_traits.hh"
#include "targetarch/vtophys.hh"
#include "sim/debug.hh"
extern SymbolTable *debugSymbolTable;
using namespace std;
LinuxSystem::LinuxSystem(const string _name, const uint64_t _init_param,
MemoryController *_memCtrl, PhysicalMemory *_physmem,
const string &kernel_path, const string &console_path,
const string &palcode, const string &boot_osflags,
const bool _bin, const vector<string> &_binned_fns)
: System(_name, _init_param, _memCtrl, _physmem, _bin, _binned_fns),
bin(_bin), binned_fns(_binned_fns)
{
kernelSymtab = new SymbolTable;
consoleSymtab = new SymbolTable;
/**
* Load the kernel, pal, and console code into memory
*/
// Load kernel code
ObjectFile *kernel = createObjectFile(kernel_path);
if (kernel == NULL)
fatal("Could not load kernel file %s", kernel_path);
// Load Console Code
ObjectFile *console = createObjectFile(console_path);
if (console == NULL)
fatal("Could not load console file %s", console_path);
// Load pal file
ObjectFile *pal = createObjectFile(palcode);
if (pal == NULL)
fatal("Could not load PALcode file %s", palcode);
pal->loadSections(physmem, true);
// Load console file
console->loadSections(physmem, true);
// Load kernel file
kernel->loadSections(physmem, true);
kernelStart = kernel->textBase();
kernelEnd = kernel->bssBase() + kernel->bssSize();
kernelEntry = kernel->entryPoint();
// load symbols
if (!kernel->loadGlobalSymbols(kernelSymtab))
panic("could not load kernel symbols\n");
debugSymbolTable = kernelSymtab;
if (!kernel->loadLocalSymbols(kernelSymtab))
panic("could not load kernel local symbols\n");
if (!console->loadGlobalSymbols(consoleSymtab))
panic("could not load console symbols\n");
DPRINTF(Loader, "Kernel start = %#x\n"
"Kernel end = %#x\n"
"Kernel entry = %#x\n",
kernelStart, kernelEnd, kernelEntry);
DPRINTF(Loader, "Kernel loaded...\n");
#ifdef DEBUG
kernelPanicEvent = new BreakPCEvent(&pcEventQueue, "kernel panic");
consolePanicEvent = new BreakPCEvent(&pcEventQueue, "console panic");
#endif
skipIdeDelay50msEvent = new SkipFuncEvent(&pcEventQueue,
"ide_delay_50ms");
skipDelayLoopEvent = new LinuxSkipDelayLoopEvent(&pcEventQueue,
"calibrate_delay");
skipCacheProbeEvent = new SkipFuncEvent(&pcEventQueue,
"determine_cpu_caches");
Addr addr = 0;
/**
* find the address of the est_cycle_freq variable and insert it so we don't
* through the lengthly process of trying to calculated it by using the PIT,
* RTC, etc.
*/
if (kernelSymtab->findAddress("est_cycle_freq", addr)) {
Addr paddr = vtophys(physmem, addr);
uint8_t *est_cycle_frequency =
physmem->dma_addr(paddr, sizeof(uint64_t));
if (est_cycle_frequency)
*(uint64_t *)est_cycle_frequency = htoa(ticksPerSecond);
}
/**
* Copy the osflags (kernel arguments) into the consoles memory. Presently
* Linux does use the console service routine to get these command line
* arguments, but we might as well make them available just in case.
*/
if (consoleSymtab->findAddress("env_booted_osflags", addr)) {
Addr paddr = vtophys(physmem, addr);
char *osflags = (char *)physmem->dma_addr(paddr, sizeof(uint32_t));
if (osflags)
strcpy(osflags, boot_osflags.c_str());
}
/**
* Since we aren't using a bootloader, we have to copy the kernel arguments
* directly into the kernels memory.
*/
{
Addr paddr = vtophys(physmem, PARAM_ADDR);
char *commandline = (char*)physmem->dma_addr(paddr, sizeof(uint64_t));
if (commandline)
strcpy(commandline, boot_osflags.c_str());
}
/**
* Set the hardware reset parameter block system type and revision
* information to Tsunami.
*/
if (consoleSymtab->findAddress("xxm_rpb", addr)) {
Addr paddr = vtophys(physmem, addr);
char *hwprb = (char *)physmem->dma_addr(paddr, sizeof(uint64_t));
if (hwprb) {
// Tsunami
*(uint64_t*)(hwprb + 0x50) = htoa(ULL(34));
// Plain DP264
*(uint64_t*)(hwprb + 0x58) = htoa(ULL(1) << 10);
}
else
panic("could not translate hwprb addr to set system type/variation\n");
} else
panic("could not find hwprb to set system type/variation\n");
/**
* EV5 only supports 127 ASNs so we are going to tell the kernel that the
* paritiuclar EV6 we have only supports 127 asns.
* @todo At some point we should change ev5.hh and the palcode to support
* 255 ASNs.
*/
if (kernelSymtab->findAddress("dp264_mv", addr)) {
Addr paddr = vtophys(physmem, addr);
char *dp264_mv = (char *)physmem->dma_addr(paddr, sizeof(uint64_t));
if (dp264_mv) {
*(uint32_t*)(dp264_mv+0x18) = htoa((uint32_t)127);
} else
panic("could not translate dp264_mv addr to set the MAX_ASN to 127\n");
} else
panic("could not find dp264_mv to set the MAX_ASN to 127\n");
#ifdef DEBUG
if (kernelSymtab->findAddress("panic", addr))
kernelPanicEvent->schedule(addr);
else
panic("could not find kernel symbol \'panic\'");
if (consoleSymtab->findAddress("panic", addr))
consolePanicEvent->schedule(addr);
#endif
/**
* Any time ide_delay_50ms, calibarte_delay or determine_cpu_caches is called
* just skip the function. Currently determine_cpu_caches only is used put
* information in proc, however if that changes in the future we will have to
* fill in the cache size variables appropriately.
*/
if (kernelSymtab->findAddress("ide_delay_50ms", addr))
skipIdeDelay50msEvent->schedule(addr+sizeof(MachInst));
if (kernelSymtab->findAddress("calibrate_delay", addr))
skipDelayLoopEvent->schedule(addr+sizeof(MachInst));
if (kernelSymtab->findAddress("determine_cpu_caches", addr))
skipCacheProbeEvent->schedule(addr+sizeof(MachInst));
}
LinuxSystem::~LinuxSystem()
{
delete kernel;
delete console;
delete kernelSymtab;
delete consoleSymtab;
delete kernelPanicEvent;
delete consolePanicEvent;
delete skipIdeDelay50msEvent;
delete skipDelayLoopEvent;
delete skipCacheProbeEvent;
}
void
LinuxSystem::setDelayLoop(ExecContext *xc)
{
Addr addr = 0;
if (kernelSymtab->findAddress("loops_per_jiffy", addr)) {
Addr paddr = vtophys(physmem, addr);
uint8_t *loops_per_jiffy =
physmem->dma_addr(paddr, sizeof(uint32_t));
Tick cpuFreq = xc->cpu->getFreq();
Tick intrFreq = platform->interrupt_frequency;
*(uint32_t *)loops_per_jiffy =
(uint32_t)((cpuFreq / intrFreq) * 0.9988);
}
}
int
LinuxSystem::registerExecContext(ExecContext *xc)
{
int xcIndex = System::registerExecContext(xc);
if (xcIndex == 0) {
// activate with zero delay so that we start ticking right
// away on cycle 0
xc->activate(0);
}
RemoteGDB *rgdb = new RemoteGDB(this, xc);
GDBListener *gdbl = new GDBListener(rgdb, 7000 + xcIndex);
gdbl->listen();
/**
* Uncommenting this line waits for a remote debugger to connect
* to the simulator before continuing.
*/
//gdbl->accept();
if (remoteGDB.size() <= xcIndex) {
remoteGDB.resize(xcIndex+1);
}
remoteGDB[xcIndex] = rgdb;
return xcIndex;
}
void
LinuxSystem::replaceExecContext(ExecContext *xc, int xcIndex)
{
System::replaceExecContext(xcIndex, xc);
remoteGDB[xcIndex]->replaceExecContext(xc);
}
bool
LinuxSystem::breakpoint()
{
return remoteGDB[0]->trap(ALPHA_KENTRY_IF);
}
BEGIN_DECLARE_SIM_OBJECT_PARAMS(LinuxSystem)
Param<bool> bin;
SimObjectParam<MemoryController *> mem_ctl;
SimObjectParam<PhysicalMemory *> physmem;
Param<uint64_t> init_param;
Param<string> kernel_code;
Param<string> console_code;
Param<string> pal_code;
Param<string> boot_osflags;
VectorParam<string> binned_fns;
Param<string> readfile;
END_DECLARE_SIM_OBJECT_PARAMS(LinuxSystem)
BEGIN_INIT_SIM_OBJECT_PARAMS(LinuxSystem)
INIT_PARAM_DFLT(bin, "is this system to be binned", false),
INIT_PARAM(mem_ctl, "memory controller"),
INIT_PARAM(physmem, "phsyical memory"),
INIT_PARAM_DFLT(init_param, "numerical value to pass into simulator", 0),
INIT_PARAM(kernel_code, "file that contains the code"),
INIT_PARAM(console_code, "file that contains the console code"),
INIT_PARAM(pal_code, "file that contains palcode"),
INIT_PARAM_DFLT(boot_osflags, "flags to pass to the kernel during boot",
"a"),
INIT_PARAM(binned_fns, "functions to be broken down and binned"),
INIT_PARAM_DFLT(readfile, "file to read startup script from", "")
END_INIT_SIM_OBJECT_PARAMS(LinuxSystem)
CREATE_SIM_OBJECT(LinuxSystem)
{
LinuxSystem *sys = new LinuxSystem(getInstanceName(), init_param, mem_ctl,
physmem, kernel_code, console_code,
pal_code, boot_osflags, bin, binned_fns);
sys->readfile = readfile;
return sys;
}
REGISTER_SIM_OBJECT("LinuxSystem", LinuxSystem)
<commit_msg>formatting<commit_after>/*
* Copyright (c) 2004 The Regents of The University of Michigan
* 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 copyright holders 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.
*/
/**
* @file
* loads the linux kernel, console, pal and patches certain functions.
* The symbol tables are loaded so that traces can show the executing
* function and we can skip functions. Various delay loops are skipped
* and their final values manually computed to speed up boot time.
*/
#include "base/loader/aout_object.hh"
#include "base/loader/elf_object.hh"
#include "base/loader/object_file.hh"
#include "base/loader/symtab.hh"
#include "base/remote_gdb.hh"
#include "base/trace.hh"
#include "cpu/exec_context.hh"
#include "cpu/base_cpu.hh"
#include "kern/linux/linux_events.hh"
#include "kern/linux/linux_system.hh"
#include "kern/system_events.hh"
#include "mem/functional_mem/memory_control.hh"
#include "mem/functional_mem/physical_memory.hh"
#include "sim/builder.hh"
#include "dev/platform.hh"
#include "targetarch/isa_traits.hh"
#include "targetarch/vtophys.hh"
#include "sim/debug.hh"
extern SymbolTable *debugSymbolTable;
using namespace std;
LinuxSystem::LinuxSystem(const string _name, const uint64_t _init_param,
MemoryController *_memCtrl, PhysicalMemory *_physmem,
const string &kernel_path, const string &console_path,
const string &palcode, const string &boot_osflags,
const bool _bin, const vector<string> &_binned_fns)
: System(_name, _init_param, _memCtrl, _physmem, _bin, _binned_fns),
bin(_bin), binned_fns(_binned_fns)
{
kernelSymtab = new SymbolTable;
consoleSymtab = new SymbolTable;
/**
* Load the kernel, pal, and console code into memory
*/
// Load kernel code
ObjectFile *kernel = createObjectFile(kernel_path);
if (kernel == NULL)
fatal("Could not load kernel file %s", kernel_path);
// Load Console Code
ObjectFile *console = createObjectFile(console_path);
if (console == NULL)
fatal("Could not load console file %s", console_path);
// Load pal file
ObjectFile *pal = createObjectFile(palcode);
if (pal == NULL)
fatal("Could not load PALcode file %s", palcode);
pal->loadSections(physmem, true);
// Load console file
console->loadSections(physmem, true);
// Load kernel file
kernel->loadSections(physmem, true);
kernelStart = kernel->textBase();
kernelEnd = kernel->bssBase() + kernel->bssSize();
kernelEntry = kernel->entryPoint();
// load symbols
if (!kernel->loadGlobalSymbols(kernelSymtab))
panic("could not load kernel symbols\n");
debugSymbolTable = kernelSymtab;
if (!kernel->loadLocalSymbols(kernelSymtab))
panic("could not load kernel local symbols\n");
if (!console->loadGlobalSymbols(consoleSymtab))
panic("could not load console symbols\n");
DPRINTF(Loader, "Kernel start = %#x\n"
"Kernel end = %#x\n"
"Kernel entry = %#x\n",
kernelStart, kernelEnd, kernelEntry);
DPRINTF(Loader, "Kernel loaded...\n");
#ifdef DEBUG
kernelPanicEvent = new BreakPCEvent(&pcEventQueue, "kernel panic");
consolePanicEvent = new BreakPCEvent(&pcEventQueue, "console panic");
#endif
skipIdeDelay50msEvent = new SkipFuncEvent(&pcEventQueue,
"ide_delay_50ms");
skipDelayLoopEvent = new LinuxSkipDelayLoopEvent(&pcEventQueue,
"calibrate_delay");
skipCacheProbeEvent = new SkipFuncEvent(&pcEventQueue,
"determine_cpu_caches");
Addr addr = 0;
/**
* find the address of the est_cycle_freq variable and insert it so we don't
* through the lengthly process of trying to calculated it by using the PIT,
* RTC, etc.
*/
if (kernelSymtab->findAddress("est_cycle_freq", addr)) {
Addr paddr = vtophys(physmem, addr);
uint8_t *est_cycle_frequency =
physmem->dma_addr(paddr, sizeof(uint64_t));
if (est_cycle_frequency)
*(uint64_t *)est_cycle_frequency = htoa(ticksPerSecond);
}
/**
* Copy the osflags (kernel arguments) into the consoles memory. Presently
* Linux does use the console service routine to get these command line
* arguments, but we might as well make them available just in case.
*/
if (consoleSymtab->findAddress("env_booted_osflags", addr)) {
Addr paddr = vtophys(physmem, addr);
char *osflags = (char *)physmem->dma_addr(paddr, sizeof(uint32_t));
if (osflags)
strcpy(osflags, boot_osflags.c_str());
}
/**
* Since we aren't using a bootloader, we have to copy the kernel arguments
* directly into the kernels memory.
*/
{
Addr paddr = vtophys(physmem, PARAM_ADDR);
char *commandline = (char*)physmem->dma_addr(paddr, sizeof(uint64_t));
if (commandline)
strcpy(commandline, boot_osflags.c_str());
}
/**
* Set the hardware reset parameter block system type and revision
* information to Tsunami.
*/
if (consoleSymtab->findAddress("xxm_rpb", addr)) {
Addr paddr = vtophys(physmem, addr);
char *hwprb = (char *)physmem->dma_addr(paddr, sizeof(uint64_t));
if (hwprb) {
// Tsunami
*(uint64_t*)(hwprb + 0x50) = htoa(ULL(34));
// Plain DP264
*(uint64_t*)(hwprb + 0x58) = htoa(ULL(1) << 10);
}
else
panic("could not translate hwprb addr to set system type/variation\n");
} else
panic("could not find hwprb to set system type/variation\n");
/**
* EV5 only supports 127 ASNs so we are going to tell the kernel that the
* paritiuclar EV6 we have only supports 127 asns.
* @todo At some point we should change ev5.hh and the palcode to support
* 255 ASNs.
*/
if (kernelSymtab->findAddress("dp264_mv", addr)) {
Addr paddr = vtophys(physmem, addr);
char *dp264_mv = (char *)physmem->dma_addr(paddr, sizeof(uint64_t));
if (dp264_mv) {
*(uint32_t*)(dp264_mv+0x18) = htoa((uint32_t)127);
} else
panic("could not translate dp264_mv addr to set the MAX_ASN to 127\n");
} else
panic("could not find dp264_mv to set the MAX_ASN to 127\n");
#ifdef DEBUG
if (kernelSymtab->findAddress("panic", addr))
kernelPanicEvent->schedule(addr);
else
panic("could not find kernel symbol \'panic\'");
if (consoleSymtab->findAddress("panic", addr))
consolePanicEvent->schedule(addr);
#endif
/**
* Any time ide_delay_50ms, calibarte_delay or determine_cpu_caches is called
* just skip the function. Currently determine_cpu_caches only is used put
* information in proc, however if that changes in the future we will have to
* fill in the cache size variables appropriately.
*/
if (kernelSymtab->findAddress("ide_delay_50ms", addr))
skipIdeDelay50msEvent->schedule(addr+sizeof(MachInst));
if (kernelSymtab->findAddress("calibrate_delay", addr))
skipDelayLoopEvent->schedule(addr+sizeof(MachInst));
if (kernelSymtab->findAddress("determine_cpu_caches", addr))
skipCacheProbeEvent->schedule(addr+sizeof(MachInst));
}
LinuxSystem::~LinuxSystem()
{
delete kernel;
delete console;
delete kernelSymtab;
delete consoleSymtab;
delete kernelPanicEvent;
delete consolePanicEvent;
delete skipIdeDelay50msEvent;
delete skipDelayLoopEvent;
delete skipCacheProbeEvent;
}
void
LinuxSystem::setDelayLoop(ExecContext *xc)
{
Addr addr = 0;
if (kernelSymtab->findAddress("loops_per_jiffy", addr)) {
Addr paddr = vtophys(physmem, addr);
uint8_t *loops_per_jiffy =
physmem->dma_addr(paddr, sizeof(uint32_t));
Tick cpuFreq = xc->cpu->getFreq();
Tick intrFreq = platform->interrupt_frequency;
*(uint32_t *)loops_per_jiffy =
(uint32_t)((cpuFreq / intrFreq) * 0.9988);
}
}
int
LinuxSystem::registerExecContext(ExecContext *xc)
{
int xcIndex = System::registerExecContext(xc);
if (xcIndex == 0) {
// activate with zero delay so that we start ticking right
// away on cycle 0
xc->activate(0);
}
RemoteGDB *rgdb = new RemoteGDB(this, xc);
GDBListener *gdbl = new GDBListener(rgdb, 7000 + xcIndex);
gdbl->listen();
/**
* Uncommenting this line waits for a remote debugger to connect
* to the simulator before continuing.
*/
//gdbl->accept();
if (remoteGDB.size() <= xcIndex) {
remoteGDB.resize(xcIndex+1);
}
remoteGDB[xcIndex] = rgdb;
return xcIndex;
}
void
LinuxSystem::replaceExecContext(ExecContext *xc, int xcIndex)
{
System::replaceExecContext(xcIndex, xc);
remoteGDB[xcIndex]->replaceExecContext(xc);
}
bool
LinuxSystem::breakpoint()
{
return remoteGDB[0]->trap(ALPHA_KENTRY_IF);
}
BEGIN_DECLARE_SIM_OBJECT_PARAMS(LinuxSystem)
Param<bool> bin;
SimObjectParam<MemoryController *> mem_ctl;
SimObjectParam<PhysicalMemory *> physmem;
Param<uint64_t> init_param;
Param<string> kernel_code;
Param<string> console_code;
Param<string> pal_code;
Param<string> boot_osflags;
VectorParam<string> binned_fns;
Param<string> readfile;
END_DECLARE_SIM_OBJECT_PARAMS(LinuxSystem)
BEGIN_INIT_SIM_OBJECT_PARAMS(LinuxSystem)
INIT_PARAM_DFLT(bin, "is this system to be binned", false),
INIT_PARAM(mem_ctl, "memory controller"),
INIT_PARAM(physmem, "phsyical memory"),
INIT_PARAM_DFLT(init_param, "numerical value to pass into simulator", 0),
INIT_PARAM(kernel_code, "file that contains the code"),
INIT_PARAM(console_code, "file that contains the console code"),
INIT_PARAM(pal_code, "file that contains palcode"),
INIT_PARAM_DFLT(boot_osflags, "flags to pass to the kernel during boot",
"a"),
INIT_PARAM(binned_fns, "functions to be broken down and binned"),
INIT_PARAM_DFLT(readfile, "file to read startup script from", "")
END_INIT_SIM_OBJECT_PARAMS(LinuxSystem)
CREATE_SIM_OBJECT(LinuxSystem)
{
LinuxSystem *sys = new LinuxSystem(getInstanceName(), init_param, mem_ctl,
physmem, kernel_code, console_code,
pal_code, boot_osflags, bin, binned_fns);
sys->readfile = readfile;
return sys;
}
REGISTER_SIM_OBJECT("LinuxSystem", LinuxSystem)
<|endoftext|>
|
<commit_before>/*
* Copyright (c) 2019 Pedro Falcato
* This file is part of Onyx, and is released under the terms of the MIT License
* check LICENSE at the root directory for more information
*/
#include <stdio.h>
#include <cpuid.h>
#include <onyx/cpu.h>
#include <onyx/x86/kvm.h>
#include <onyx/x86/msr.h>
#include <onyx/panic.h>
static bool clocksource2_supported = false;
static bool clocksource_supported = false;
static unsigned long wall_clock_msr;
static unsigned long system_time_msr;
void pvclock_init(void);
void kvm_init(void)
{
uint32_t eax, ebx, ecx, edx;
__cpuid(KVM_CPUID_SIGNATURE, eax, ebx, ecx, edx);
if(!x86_has_cap(X86_FEATURE_HYPERVISOR))
{
/* Means we're definitely not running on kvm */
return;
}
/* Check if we're running on kvm from the signature */
if(ebx != KVM_CPUID_SIGNATURE_EBX)
return;
if(ecx != KVM_CPUID_SIGNATURE_ECX)
return;
if(edx != KVM_CPUID_SIGNATURE_EDX)
return;
/* Old hosts set eax to 0, but it should be interpreted as KVM_CPUID_FEATURES */
if(eax == 0)
eax = KVM_CPUID_FEATURES;
__cpuid(KVM_CPUID_FEATURES, eax, ebx, ecx, edx);
if(eax & KVM_FEATURE_CLOCKSOURCE2)
clocksource2_supported = true;
if(eax & KVM_FEATURE_CLOCKSOURCE)
clocksource_supported = true;
pvclock_init();
}
static struct pvclock_system_time *system_time;
static struct pvclock_wall_clock *wall_clock;
static volatile struct pvclock_system_time *vsystem_time;
static inline bool pvclock_system_time_updating(uint32_t version)
{
/* Odd version numbers = under update */
return version % 2;
}
unsigned long pvclock_get_tsc_frequency(void)
{
uint32_t start_version = 0, end_version = 0;
uint32_t tsc_mul = 0;
int8_t tsc_shift = 0;
do
{
start_version = vsystem_time->version;
if(pvclock_system_time_updating(start_version))
{
continue;
}
tsc_mul = vsystem_time->tsc_to_system_mul;
tsc_shift = vsystem_time->tsc_shift;
end_version = vsystem_time->version;
} while(start_version != end_version);
uint64_t tsc_freq = 1000000000UL << 32;
tsc_freq = tsc_freq / tsc_mul;
if(tsc_shift > 0)
tsc_freq >>= tsc_shift;
else
tsc_freq <<= -tsc_shift;
return tsc_freq;
}
void pvclock_init(void)
{
/* Nothing to do. */
if(!clocksource2_supported && !clocksource_supported)
return;
if(clocksource2_supported)
{
wall_clock_msr = MSR_KVM_WALL_CLOCK_NEW;
system_time_msr = MSR_KVM_SYSTEM_TIME_NEW;
}
else
{
wall_clock_msr = MSR_KVM_WALL_CLOCK;
system_time_msr = MSR_KVM_SYSTEM_TIME;
}
struct page *p = alloc_page(0);
if(!p)
return;
unsigned long paddr = (unsigned long) page_to_phys(p);
system_time = (struct pvclock_system_time *) paddr;
paddr = ALIGN_TO(paddr, 4);
wall_clock = (struct pvclock_wall_clock *) paddr;
vsystem_time = (volatile pvclock_system_time *) PHYS_TO_VIRT(system_time);
wrmsr(system_time_msr, (unsigned long) system_time | MSR_KVM_SYSTEM_TIME_ENABLE);
x86_set_tsc_rate(pvclock_get_tsc_frequency());
}
<commit_msg>x86/kvm: Fix error that could result in incorrect readings.<commit_after>/*
* Copyright (c) 2019 Pedro Falcato
* This file is part of Onyx, and is released under the terms of the MIT License
* check LICENSE at the root directory for more information
*/
#include <stdio.h>
#include <cpuid.h>
#include <onyx/cpu.h>
#include <onyx/x86/kvm.h>
#include <onyx/x86/msr.h>
#include <onyx/panic.h>
static bool clocksource2_supported = false;
static bool clocksource_supported = false;
static unsigned long wall_clock_msr;
static unsigned long system_time_msr;
void pvclock_init(void);
void kvm_init(void)
{
uint32_t eax, ebx, ecx, edx;
__cpuid(KVM_CPUID_SIGNATURE, eax, ebx, ecx, edx);
if(!x86_has_cap(X86_FEATURE_HYPERVISOR))
{
/* Means we're definitely not running on kvm */
return;
}
/* Check if we're running on kvm from the signature */
if(ebx != KVM_CPUID_SIGNATURE_EBX)
return;
if(ecx != KVM_CPUID_SIGNATURE_ECX)
return;
if(edx != KVM_CPUID_SIGNATURE_EDX)
return;
/* Old hosts set eax to 0, but it should be interpreted as KVM_CPUID_FEATURES */
if(eax == 0)
eax = KVM_CPUID_FEATURES;
__cpuid(KVM_CPUID_FEATURES, eax, ebx, ecx, edx);
if(eax & KVM_FEATURE_CLOCKSOURCE2)
clocksource2_supported = true;
if(eax & KVM_FEATURE_CLOCKSOURCE)
clocksource_supported = true;
pvclock_init();
}
static struct pvclock_system_time *system_time;
static struct pvclock_wall_clock *wall_clock;
static volatile struct pvclock_system_time *vsystem_time;
static inline bool pvclock_system_time_updating(uint32_t version)
{
/* Odd version numbers = under update */
return version % 2;
}
unsigned long pvclock_get_tsc_frequency(void)
{
uint32_t start_version = 0, end_version = 0;
uint32_t tsc_mul = 0;
int8_t tsc_shift = 0;
do
{
start_version = vsystem_time->version;
if(pvclock_system_time_updating(start_version))
{
continue;
}
tsc_mul = vsystem_time->tsc_to_system_mul;
tsc_shift = vsystem_time->tsc_shift;
end_version = vsystem_time->version;
} while(start_version != end_version || pvclock_system_time_updating(end_version));
uint64_t tsc_freq = 1000000000UL << 32;
tsc_freq = tsc_freq / tsc_mul;
if(tsc_shift > 0)
tsc_freq >>= tsc_shift;
else
tsc_freq <<= -tsc_shift;
return tsc_freq;
}
void pvclock_init(void)
{
/* Nothing to do. */
if(!clocksource2_supported && !clocksource_supported)
return;
if(clocksource2_supported)
{
wall_clock_msr = MSR_KVM_WALL_CLOCK_NEW;
system_time_msr = MSR_KVM_SYSTEM_TIME_NEW;
}
else
{
wall_clock_msr = MSR_KVM_WALL_CLOCK;
system_time_msr = MSR_KVM_SYSTEM_TIME;
}
struct page *p = alloc_page(0);
if(!p)
return;
unsigned long paddr = (unsigned long) page_to_phys(p);
system_time = (struct pvclock_system_time *) paddr;
paddr = ALIGN_TO(paddr, 4);
wall_clock = (struct pvclock_wall_clock *) paddr;
vsystem_time = (volatile pvclock_system_time *) PHYS_TO_VIRT(system_time);
wrmsr(system_time_msr, (unsigned long) system_time | MSR_KVM_SYSTEM_TIME_ENABLE);
x86_set_tsc_rate(pvclock_get_tsc_frequency());
}
<|endoftext|>
|
<commit_before>#include "scanscalar.h"
#include "scanner.h"
#include "exp.h"
#include "exceptions.h"
#include "token.h"
namespace YAML
{
// ScanScalar
// . This is where the scalar magic happens.
//
// . We do the scanning in three phases:
// 1. Scan until newline
// 2. Eat newline
// 3. Scan leading blanks.
//
// . Depending on the parameters given, we store or stop
// and different places in the above flow.
std::string ScanScalar(Stream& INPUT, ScanScalarParams& params)
{
bool foundNonEmptyLine = false;
bool emptyLine = false, moreIndented = false;
std::string scalar;
params.leadingSpaces = false;
while(INPUT) {
// ********************************
// Phase #1: scan until line ending
while(!params.end.Matches(INPUT) && !Exp::Break.Matches(INPUT)) {
if(INPUT.peek() == EOF)
break;
// document indicator?
if(INPUT.column == 0 && Exp::DocIndicator.Matches(INPUT)) {
if(params.onDocIndicator == BREAK)
break;
else if(params.onDocIndicator == THROW)
throw IllegalDocIndicator();
}
foundNonEmptyLine = true;
// escaped newline? (only if we're escaping on slash)
if(params.escape == '\\' && Exp::EscBreak.Matches(INPUT)) {
int n = Exp::EscBreak.Match(INPUT);
INPUT.eat(n);
continue;
}
// escape this?
if(INPUT.peek() == params.escape) {
scalar += Exp::Escape(INPUT);
continue;
}
// otherwise, just add the damn character
scalar += INPUT.get();
}
// eof? if we're looking to eat something, then we throw
if(INPUT.peek() == EOF) {
if(params.eatEnd)
throw IllegalEOF();
break;
}
// doc indicator?
if(params.onDocIndicator == BREAK && INPUT.column == 0 && Exp::DocIndicator.Matches(INPUT))
break;
// are we done via character match?
int n = params.end.Match(INPUT);
if(n >= 0) {
if(params.eatEnd)
INPUT.eat(n);
break;
}
// ********************************
// Phase #2: eat line ending
n = Exp::Break.Match(INPUT);
INPUT.eat(n);
// ********************************
// Phase #3: scan initial spaces
// first the required indentation
while(INPUT.peek() == ' ' && (INPUT.column < params.indent || (params.detectIndent && !foundNonEmptyLine)))
INPUT.eat(1);
// update indent if we're auto-detecting
if(params.detectIndent && !foundNonEmptyLine)
params.indent = std::max(params.indent, INPUT.column);
// and then the rest of the whitespace
while(Exp::Blank.Matches(INPUT)) {
// we check for tabs that masquerade as indentation
if(INPUT.peek() == '\t'&& INPUT.column < params.indent && params.onTabInIndentation == THROW)
throw IllegalTabInIndentation();
if(!params.eatLeadingWhitespace)
break;
INPUT.eat(1);
}
// was this an empty line?
bool nextEmptyLine = Exp::Break.Matches(INPUT);
bool nextMoreIndented = (INPUT.peek() == ' ');
// TODO: for block scalars, we always start with a newline, so we should fold OR keep that
if(params.fold && !emptyLine && !nextEmptyLine && !moreIndented && !nextMoreIndented)
scalar += " ";
else
scalar += "\n";
emptyLine = nextEmptyLine;
moreIndented = nextMoreIndented;
// are we done via indentation?
if(!emptyLine && INPUT.column < params.indent) {
params.leadingSpaces = true;
break;
}
}
// post-processing
if(params.trimTrailingSpaces) {
unsigned pos = scalar.find_last_not_of(' ');
if(pos < scalar.size())
scalar.erase(pos + 1);
}
if(params.chomp <= 0) {
unsigned pos = scalar.find_last_not_of('\n');
if(params.chomp == 0 && pos + 1 < scalar.size())
scalar.erase(pos + 2);
else if(params.chomp == -1 && pos < scalar.size())
scalar.erase(pos + 1);
}
return scalar;
}
}
<commit_msg>Fixed opening newline bug for block scalars.<commit_after>#include "scanscalar.h"
#include "scanner.h"
#include "exp.h"
#include "exceptions.h"
#include "token.h"
namespace YAML
{
// ScanScalar
// . This is where the scalar magic happens.
//
// . We do the scanning in three phases:
// 1. Scan until newline
// 2. Eat newline
// 3. Scan leading blanks.
//
// . Depending on the parameters given, we store or stop
// and different places in the above flow.
std::string ScanScalar(Stream& INPUT, ScanScalarParams& params)
{
bool foundNonEmptyLine = false, pastOpeningBreak = false;
bool emptyLine = false, moreIndented = false;
std::string scalar;
params.leadingSpaces = false;
while(INPUT) {
// ********************************
// Phase #1: scan until line ending
while(!params.end.Matches(INPUT) && !Exp::Break.Matches(INPUT)) {
if(INPUT.peek() == EOF)
break;
// document indicator?
if(INPUT.column == 0 && Exp::DocIndicator.Matches(INPUT)) {
if(params.onDocIndicator == BREAK)
break;
else if(params.onDocIndicator == THROW)
throw IllegalDocIndicator();
}
foundNonEmptyLine = true;
pastOpeningBreak = true;
// escaped newline? (only if we're escaping on slash)
if(params.escape == '\\' && Exp::EscBreak.Matches(INPUT)) {
int n = Exp::EscBreak.Match(INPUT);
INPUT.eat(n);
continue;
}
// escape this?
if(INPUT.peek() == params.escape) {
scalar += Exp::Escape(INPUT);
continue;
}
// otherwise, just add the damn character
scalar += INPUT.get();
}
// eof? if we're looking to eat something, then we throw
if(INPUT.peek() == EOF) {
if(params.eatEnd)
throw IllegalEOF();
break;
}
// doc indicator?
if(params.onDocIndicator == BREAK && INPUT.column == 0 && Exp::DocIndicator.Matches(INPUT))
break;
// are we done via character match?
int n = params.end.Match(INPUT);
if(n >= 0) {
if(params.eatEnd)
INPUT.eat(n);
break;
}
// ********************************
// Phase #2: eat line ending
n = Exp::Break.Match(INPUT);
INPUT.eat(n);
// ********************************
// Phase #3: scan initial spaces
// first the required indentation
while(INPUT.peek() == ' ' && (INPUT.column < params.indent || (params.detectIndent && !foundNonEmptyLine)))
INPUT.eat(1);
// update indent if we're auto-detecting
if(params.detectIndent && !foundNonEmptyLine)
params.indent = std::max(params.indent, INPUT.column);
// and then the rest of the whitespace
while(Exp::Blank.Matches(INPUT)) {
// we check for tabs that masquerade as indentation
if(INPUT.peek() == '\t'&& INPUT.column < params.indent && params.onTabInIndentation == THROW)
throw IllegalTabInIndentation();
if(!params.eatLeadingWhitespace)
break;
INPUT.eat(1);
}
// was this an empty line?
bool nextEmptyLine = Exp::Break.Matches(INPUT);
bool nextMoreIndented = (INPUT.peek() == ' ');
// for block scalars, we always start with a newline, so we should ignore it (not fold or keep)
if(pastOpeningBreak) {
if(params.fold && !emptyLine && !nextEmptyLine && !moreIndented && !nextMoreIndented)
scalar += " ";
else
scalar += "\n";
}
emptyLine = nextEmptyLine;
moreIndented = nextMoreIndented;
pastOpeningBreak = true;
// are we done via indentation?
if(!emptyLine && INPUT.column < params.indent) {
params.leadingSpaces = true;
break;
}
}
// post-processing
if(params.trimTrailingSpaces) {
unsigned pos = scalar.find_last_not_of(' ');
if(pos < scalar.size())
scalar.erase(pos + 1);
}
if(params.chomp <= 0) {
unsigned pos = scalar.find_last_not_of('\n');
if(params.chomp == 0 && pos + 1 < scalar.size())
scalar.erase(pos + 2);
else if(params.chomp == -1 && pos < scalar.size())
scalar.erase(pos + 1);
}
return scalar;
}
}
<|endoftext|>
|
<commit_before>#include <shoveler.h>
#include <improbable/standard_library.h>
#include <iostream>
#include <unordered_map>
using shoveler::Client;
using shoveler::Color;
using shoveler::Drawable;
using shoveler::DrawableType;
using shoveler::Material;
using shoveler::MaterialType;
using shoveler::Model;
using shoveler::Plane;
using improbable::EntityAcl;
using improbable::EntityAclData;
using improbable::Metadata;
using improbable::Persistence;
using improbable::Position;
using improbable::WorkerAttributeSet;
using improbable::WorkerRequirementSet;
int main(int argc, char **argv) {
if (argc != 2) {
std::cerr << "Usage: " << argv[0] << " <seed snapshot file>" << std::endl;
return 1;
}
std::string path(argv[1]);
Color grayColor{0.7f, 0.7f, 0.7f};
Drawable quadDrawable{DrawableType::QUAD};
Material grayColorMaterial{MaterialType::COLOR, grayColor, ""};
WorkerAttributeSet clientAttributeSet({"client"});
WorkerRequirementSet clientRequirementSet({clientAttributeSet});
std::unordered_map<worker::EntityId, worker::Entity> entities;
worker::Entity bootstrapEntity;
bootstrapEntity.Add<Metadata>({"bootstrap"});
bootstrapEntity.Add<Persistence>({});
bootstrapEntity.Add<Position>({{0, 0, 0}});
bootstrapEntity.Add<Client>({});
worker::Map<std::uint32_t, WorkerRequirementSet> bootstrapComponentAclMap;
bootstrapComponentAclMap.insert({{Client::ComponentId, clientRequirementSet}});
EntityAclData bootstrapEntityAclData(clientRequirementSet, bootstrapComponentAclMap);
bootstrapEntity.Add<EntityAcl>(bootstrapEntityAclData);
entities[1] = bootstrapEntity;
worker::Entity planeEntity;
planeEntity.Add<Metadata>({"plane"});
planeEntity.Add<Persistence>({});
planeEntity.Add<Position>({{0, 0, 0}});
planeEntity.Add<Plane>({{0.5, 0.5, 0.5}, 10.0});
planeEntity.Add<Model>({quadDrawable, grayColorMaterial});
worker::Map<std::uint32_t, WorkerRequirementSet> planeComponentAclMap;
EntityAclData planeEntityAclData(clientRequirementSet, planeComponentAclMap);
planeEntity.Add<EntityAcl>(planeEntityAclData);
entities[2] = planeEntity;
worker::SaveSnapshot(path, entities);
return 0;
}
<commit_msg>added cube entity to snapshot seeder<commit_after>#include <shoveler.h>
#include <improbable/standard_library.h>
#include <iostream>
#include <unordered_map>
using shoveler::Client;
using shoveler::Color;
using shoveler::Drawable;
using shoveler::DrawableType;
using shoveler::Material;
using shoveler::MaterialType;
using shoveler::Model;
using shoveler::Plane;
using improbable::EntityAcl;
using improbable::EntityAclData;
using improbable::Metadata;
using improbable::Persistence;
using improbable::Position;
using improbable::WorkerAttributeSet;
using improbable::WorkerRequirementSet;
int main(int argc, char **argv) {
if (argc != 2) {
std::cerr << "Usage: " << argv[0] << " <seed snapshot file>" << std::endl;
return 1;
}
std::string path(argv[1]);
Color grayColor{0.7f, 0.7f, 0.7f};
Drawable cubeDrawable{DrawableType::CUBE};
Drawable quadDrawable{DrawableType::QUAD};
Material grayColorMaterial{MaterialType::COLOR, grayColor, ""};
worker::Map<std::uint32_t, WorkerRequirementSet> emptyComponentAclMap;
WorkerAttributeSet clientAttributeSet({"client"});
WorkerRequirementSet clientRequirementSet({clientAttributeSet});
std::unordered_map<worker::EntityId, worker::Entity> entities;
worker::Entity bootstrapEntity;
bootstrapEntity.Add<Metadata>({"bootstrap"});
bootstrapEntity.Add<Persistence>({});
bootstrapEntity.Add<Position>({{0, 0, 0}});
bootstrapEntity.Add<Client>({});
worker::Map<std::uint32_t, WorkerRequirementSet> bootstrapComponentAclMap;
bootstrapComponentAclMap.insert({{Client::ComponentId, clientRequirementSet}});
EntityAclData bootstrapEntityAclData(clientRequirementSet, bootstrapComponentAclMap);
bootstrapEntity.Add<EntityAcl>(bootstrapEntityAclData);
entities[1] = bootstrapEntity;
worker::Entity planeEntity;
planeEntity.Add<Metadata>({"plane"});
planeEntity.Add<Persistence>({});
planeEntity.Add<Position>({{0, 0, 0}});
planeEntity.Add<Plane>({{0.5, 0.5, 0.5}, 10.0});
planeEntity.Add<Model>({quadDrawable, grayColorMaterial});
EntityAclData planeEntityAclData(clientRequirementSet, emptyComponentAclMap);
planeEntity.Add<EntityAcl>({clientRequirementSet, emptyComponentAclMap});
entities[2] = planeEntity;
worker::Entity cubeEntity;
cubeEntity.Add<Metadata>({"cube"});
cubeEntity.Add<Persistence>({});
cubeEntity.Add<Position>({{0, 0, 5}});
cubeEntity.Add<Model>({cubeDrawable, grayColorMaterial});
cubeEntity.Add<EntityAcl>({clientRequirementSet, emptyComponentAclMap});
entities[3] = cubeEntity;
worker::SaveSnapshot(path, entities);
return 0;
}
<|endoftext|>
|
<commit_before>#include "BetaPrimeRand.h"
BetaPrimeRand::BetaPrimeRand(double shape1, double shape2)
{
SetParameters(shape1, shape2);
}
std::string BetaPrimeRand::Name() const
{
return "Beta Prime(" + toStringWithPrecision(GetAlpha()) + ", " + toStringWithPrecision(GetBeta()) + ")";
}
void BetaPrimeRand::SetParameters(double shape1, double shape2)
{
B.SetParameters(shape1, shape2);
alpha = B.GetAlpha();
beta = B.GetBeta();
}
double BetaPrimeRand::f(double x) const
{
if (x < 0)
return 0;
if (x == 0) {
if (alpha == 1)
return GetInverseBetaFunction();
return (alpha > 1) ? 0.0 : INFINITY;
}
double y = (alpha - 1) * std::log(x);
y -= (alpha + beta) * std::log1p(x);
return std::exp(y - GetLogBetaFunction());
}
double BetaPrimeRand::F(double x) const
{
return (x > 0) ? B.F(x / (1.0 + x)) : 0;
}
double BetaPrimeRand::Variate() const
{
double x = B.Variate();
return x / (1.0 - x);
}
void BetaPrimeRand::Sample(std::vector<double> &outputData) const
{
B.Sample(outputData);
for (double &var : outputData)
var = var / (1.0 - var);
}
double BetaPrimeRand::Mean() const
{
return (beta > 1) ? alpha / (beta - 1) : INFINITY;
}
double BetaPrimeRand::Variance() const
{
if (beta <= 2)
return INFINITY;
double betam1 = beta - 1;
double numerator = alpha * (alpha + betam1);
double denominator = (betam1 - 1) * betam1 * betam1;
return numerator / denominator;
}
double BetaPrimeRand::Median() const
{
return (alpha == beta) ? 1.0 : quantileImpl(0.5);
}
double BetaPrimeRand::Mode() const
{
return (alpha < 1) ? 0 : (alpha - 1) / (beta + 1);
}
double BetaPrimeRand::Skewness() const
{
if (beta <= 3)
return INFINITY;
double aux = alpha + beta - 1;
double skewness = (beta - 2) / (alpha * aux);
skewness = std::sqrt(skewness);
aux += alpha;
aux += aux;
return aux * skewness / (beta - 3);
}
double BetaPrimeRand::ExcessKurtosis() const
{
if (beta <= 4)
return INFINITY;
double betam1 = beta - 1;
double numerator = betam1 * betam1 * (beta - 2) / (alpha * (alpha + betam1));
numerator += 5 * beta - 11;
double denominator = (beta - 3) * (beta - 4);
return 6 * numerator / denominator;
}
double BetaPrimeRand::quantileImpl(double p) const
{
double x = B.Quantile(p);
return x / (1.0 - x);
}
double BetaPrimeRand::quantileImpl1m(double p) const
{
double x = B.Quantile1m(p);
return x / (1.0 - x);
}
std::complex<double> BetaPrimeRand::CFImpl(double t) const
{
/// if no singularity - simple numeric integration
if (alpha > 1)
return UnivariateProbabilityDistribution::CFImpl(t);
double re = RandMath::integral([this, t] (double x) {
if (x <= 0)
return 0.0;
double y = std::pow(1 + x, -alpha - beta) - 1.0;
y *= std::pow(x, alpha - 1);
return y;
}, 0, 1);
re += 1.0 / alpha;
re *= GetInverseBetaFunction();
re += RandMath::integral([this, t] (double x)
{
if (x >= 1.0)
return 0.0;
double denom = 1.0 - x;
double p = 1.0 + x / denom;
double y = std::cos(p * t) * f(p);
denom *= denom;
return y / denom;
},
0.0, 1.0);
double im = ExpectedValue([this, t] (double x)
{
return std::sin(t * x);
}, 0.0, Quantile1m(1e-6));
return std::complex<double>(re, im);
}
<commit_msg>Update BetaPrimeRand.cpp<commit_after>#include "BetaPrimeRand.h"
BetaPrimeRand::BetaPrimeRand(double shape1, double shape2)
{
SetParameters(shape1, shape2);
}
std::string BetaPrimeRand::Name() const
{
return "Beta Prime(" + toStringWithPrecision(GetAlpha()) + ", " + toStringWithPrecision(GetBeta()) + ")";
}
void BetaPrimeRand::SetParameters(double shape1, double shape2)
{
B.SetParameters(shape1, shape2);
alpha = B.GetAlpha();
beta = B.GetBeta();
}
double BetaPrimeRand::f(double x) const
{
if (x < 0)
return 0;
if (x == 0) {
if (alpha == 1)
return GetInverseBetaFunction();
return (alpha > 1) ? 0.0 : INFINITY;
}
double y = (alpha - 1) * std::log(x);
y -= (alpha + beta) * std::log1p(x);
return std::exp(y - GetLogBetaFunction());
}
double BetaPrimeRand::F(double x) const
{
return (x > 0) ? B.F(x / (1.0 + x)) : 0;
}
double BetaPrimeRand::S(double x) const
{
return (x > 0) ? B.S(x / (1.0 + x)) : 1;
}
double BetaPrimeRand::Variate() const
{
double x = B.Variate();
return x / (1.0 - x);
}
void BetaPrimeRand::Sample(std::vector<double> &outputData) const
{
B.Sample(outputData);
for (double &var : outputData)
var = var / (1.0 - var);
}
double BetaPrimeRand::Mean() const
{
return (beta > 1) ? alpha / (beta - 1) : INFINITY;
}
double BetaPrimeRand::Variance() const
{
if (beta <= 2)
return INFINITY;
double betam1 = beta - 1;
double numerator = alpha * (alpha + betam1);
double denominator = (betam1 - 1) * betam1 * betam1;
return numerator / denominator;
}
double BetaPrimeRand::Median() const
{
return (alpha == beta) ? 1.0 : quantileImpl(0.5);
}
double BetaPrimeRand::Mode() const
{
return (alpha < 1) ? 0 : (alpha - 1) / (beta + 1);
}
double BetaPrimeRand::Skewness() const
{
if (beta <= 3)
return INFINITY;
double aux = alpha + beta - 1;
double skewness = (beta - 2) / (alpha * aux);
skewness = std::sqrt(skewness);
aux += alpha;
aux += aux;
return aux * skewness / (beta - 3);
}
double BetaPrimeRand::ExcessKurtosis() const
{
if (beta <= 4)
return INFINITY;
double betam1 = beta - 1;
double numerator = betam1 * betam1 * (beta - 2) / (alpha * (alpha + betam1));
numerator += 5 * beta - 11;
double denominator = (beta - 3) * (beta - 4);
return 6 * numerator / denominator;
}
double BetaPrimeRand::quantileImpl(double p) const
{
double x = B.Quantile(p);
return x / (1.0 - x);
}
double BetaPrimeRand::quantileImpl1m(double p) const
{
double x = B.Quantile1m(p);
return x / (1.0 - x);
}
std::complex<double> BetaPrimeRand::CFImpl(double t) const
{
/// if no singularity - simple numeric integration
if (alpha > 1)
return UnivariateProbabilityDistribution::CFImpl(t);
double re = RandMath::integral([this, t] (double x) {
if (x <= 0)
return 0.0;
double y = std::pow(1 + x, -alpha - beta) - 1.0;
y *= std::pow(x, alpha - 1);
return y;
}, 0, 1);
re += 1.0 / alpha;
re *= GetInverseBetaFunction();
re += RandMath::integral([this, t] (double x)
{
if (x >= 1.0)
return 0.0;
double denom = 1.0 - x;
double p = 1.0 + x / denom;
double y = std::cos(p * t) * f(p);
denom *= denom;
return y / denom;
},
0.0, 1.0);
double im = ExpectedValue([this, t] (double x)
{
return std::sin(t * x);
}, 0.0, Quantile1m(1e-6));
return std::complex<double>(re, im);
}
<|endoftext|>
|
<commit_before>/*!
* \file
* \brief Adds/builds and checks a Cyclic Redundancy Check (CRC) for a set of information bits.
*
* \section LICENSE
* This file is under MIT license (https://opensource.org/licenses/MIT).
*/
#ifndef CRC_HPP_
#define CRC_HPP_
#include <string>
#include <vector>
#include <stdexcept>
#include "Tools/Perf/MIPP/mipp.h"
#include "Module/Module.hpp"
namespace aff3ct
{
namespace module
{
/*!
* \class CRC_i
*
* \brief Adds/builds and checks a Cyclic Redundancy Check (CRC) for a set of information bits.
*
* \tparam B: type of the bits in the CRC.
*
* Please use CRC for inheritance (instead of CRC_i).
*/
template <typename B = int>
class CRC_i : public Module
{
protected:
const int K; /*!< Number of information bits (the CRC bits are included in K) */
public:
/*!
* \brief Constructor.
*
* \param K: number of information bits (the CRC bits are included in K).
* \param n_frames: number of frames to process in the CRC.
* \param name: CRC's name.
*/
CRC_i(const int K, const int n_frames = 1, const std::string name = "CRC_i")
: Module(n_frames, name), K(K)
{
if (K <= 0)
throw std::invalid_argument("aff3ct::module::CRC: \"K\" has to be greater than 0.");
}
/*!
* \brief Destructor.
*/
virtual ~CRC_i()
{
}
/*!
* \brief Gets the size of the CRC (the number of bits for the CRC signature).
*
* \return the size of the CRC.
*/
virtual int size() const = 0;
/*!
* \brief Computes and adds the CRC in the vector of information bits (the CRC bits are often put at the end of the
* vector).
*
* \param U_K: a vector (size = K - CRC<B>::size()) containing the information bits, adds "CRC<B>::size()" bits in
* U_K.
*/
void build(mipp::vector<B>& U_K)
{
if (this->K * this->n_frames != (int)U_K.size())
throw std::length_error("aff3ct::module::CRC: \"U_K.size()\" has to be equal to \"K\" * \"n_frames\".");
this->build(U_K.data());
}
virtual void build(B *U_K)
{
for (auto f = 0; f < this->n_frames; f++)
this->_build(U_K + f * this->K);
}
/*!
* \brief Checks if the CRC is verified or not.
*
* \param V_K: a vector containing information bits plus the CRC bits.
* \param n_frames: you should not use this parameter unless you know what you are doing, this parameter
* redefine the number of frames to check specifically in this method.
*
* \return true if the CRC is verified, false otherwise.
*/
bool check(const mipp::vector<B>& V_K, const int n_frames = -1)
{
if (this->K * n_frames != (int)V_K.size() || this->K * this->n_frames != (int)V_K.size())
throw std::length_error("aff3ct::module::CRC: \"V_K.size()\" has to be equal to \"K\" * \"n_frames\".");
if (n_frames <= 0 && n_frames != -1)
throw std::invalid_argument("aff3ct::module::CRC: \"n_frames\" has to be greater than 0 (or equal "
"to -1).");
return this->check(V_K.data(), n_frames);
}
virtual bool check(const B *V_K, const int n_frames = -1)
{
const int real_n_frames = (n_frames != -1) ? n_frames : this->n_frames;
auto f = 0;
while (f < real_n_frames && this->_check(V_K + f * this->K))
f++;
return f == real_n_frames;
}
/*!
* \brief Checks if the CRC is verified or not (works on packed bits).
*
* \param V_K: a vector of packed bits containing information bits plus the CRC bits.
* \param n_frames: you should not use this parameter unless you know what you are doing, this parameter
* redefine the number of frames to check specifically in this method.
*
* \return true if the CRC is verified, false otherwise.
*/
bool check_packed(const mipp::vector<B>& V_K, const int n_frames = -1)
{
if (this->K * n_frames > (int)V_K.size() || this->K * this->n_frames > (int)V_K.size())
throw std::length_error("aff3ct::module::CRC: \"V_K.size()\" has to be equal or greater than "
"\"K\" * \"n_frames\".");
if (n_frames <= 0 && n_frames != -1)
throw std::invalid_argument("aff3ct::module::CRC: \"n_frames\" has to be greater than 0 (or equal "
"to -1).");
return this->check_packed(V_K.data(), n_frames);
}
bool check_packed(const B *V_K, const int n_frames = -1)
{
const int real_n_frames = (n_frames != -1) ? n_frames : this->n_frames;
auto f = 0;
while (f < real_n_frames && this->_check_packed(V_K + f * this->K))
f++;
return f == real_n_frames;
}
protected:
virtual void _build(const B *V_K)
{
throw std::runtime_error("aff3ct::module::CRC: \"_build\" is unimplemented.");
}
virtual bool _check(const B *V_K)
{
throw std::runtime_error("aff3ct::module::CRC: \"_check\" is unimplemented.");
return false;
}
virtual bool _check_packed(const B *V_K)
{
throw std::runtime_error("aff3ct::module::CRC: \"_check_packed\" is unimplemented.");
return false;
}
};
}
}
#include "SC_CRC.hpp"
#endif
<commit_msg>Manual merge from master.<commit_after>/*!
* \file
* \brief Adds/builds and checks a Cyclic Redundancy Check (CRC) for a set of information bits.
*
* \section LICENSE
* This file is under MIT license (https://opensource.org/licenses/MIT).
*/
#ifndef CRC_HPP_
#define CRC_HPP_
#include <string>
#include <vector>
#include <stdexcept>
#include "Tools/Perf/MIPP/mipp.h"
#include "Module/Module.hpp"
namespace aff3ct
{
namespace module
{
/*!
* \class CRC_i
*
* \brief Adds/builds and checks a Cyclic Redundancy Check (CRC) for a set of information bits.
*
* \tparam B: type of the bits in the CRC.
*
* Please use CRC for inheritance (instead of CRC_i).
*/
template <typename B = int>
class CRC_i : public Module
{
protected:
const int K; /*!< Number of information bits (the CRC bits are included in K) */
public:
/*!
* \brief Constructor.
*
* \param K: number of information bits (the CRC bits are included in K).
* \param n_frames: number of frames to process in the CRC.
* \param name: CRC's name.
*/
CRC_i(const int K, const int n_frames = 1, const std::string name = "CRC_i")
: Module(n_frames, name), K(K)
{
if (K <= 0)
throw std::invalid_argument("aff3ct::module::CRC: \"K\" has to be greater than 0.");
}
/*!
* \brief Destructor.
*/
virtual ~CRC_i()
{
}
/*!
* \brief Gets the size of the CRC (the number of bits for the CRC signature).
*
* \return the size of the CRC.
*/
virtual int size() const = 0;
/*!
* \brief Computes and adds the CRC in the vector of information bits (the CRC bits are often put at the end of the
* vector).
*
* \param U_K: a vector (size = K - CRC<B>::size()) containing the information bits, adds "CRC<B>::size()" bits in
* U_K.
*/
void build(mipp::vector<B>& U_K)
{
if (this->K * this->n_frames != (int)U_K.size())
throw std::length_error("aff3ct::module::CRC: \"U_K.size()\" has to be equal to \"K\" * \"n_frames\".");
this->build(U_K.data());
}
virtual void build(B *U_K)
{
for (auto f = 0; f < this->n_frames; f++)
this->_build(U_K + f * this->K);
}
/*!
* \brief Checks if the CRC is verified or not.
*
* \param V_K: a vector containing information bits plus the CRC bits.
* \param n_frames: you should not use this parameter unless you know what you are doing, this parameter
* redefine the number of frames to check specifically in this method.
*
* \return true if the CRC is verified, false otherwise.
*/
bool check(const mipp::vector<B>& V_K, const int n_frames = -1)
{
if (this->K * n_frames != (int)V_K.size() || this->K * this->n_frames != (int)V_K.size())
throw std::length_error("aff3ct::module::CRC: \"V_K.size()\" has to be equal to \"K\" * \"n_frames\".");
if (n_frames <= 0 && n_frames != -1)
throw std::invalid_argument("aff3ct::module::CRC: \"n_frames\" has to be greater than 0 (or equal "
"to -1).");
return this->check(V_K.data(), n_frames);
}
virtual bool check(const B *V_K, const int n_frames = -1)
{
const int real_n_frames = (n_frames != -1) ? n_frames : this->n_frames;
auto f = 0;
while (f < real_n_frames && this->_check(V_K + f * this->K))
f++;
return f == real_n_frames;
}
/*!
* \brief Checks if the CRC is verified or not (works on packed bits).
*
* \param V_K: a vector of packed bits containing information bits plus the CRC bits.
* \param n_frames: you should not use this parameter unless you know what you are doing, this parameter
* redefine the number of frames to check specifically in this method.
*
* \return true if the CRC is verified, false otherwise.
*/
bool check_packed(const mipp::vector<B>& V_K, const int n_frames = -1)
{
if (this->K * n_frames > (int)V_K.size() || this->K * this->n_frames > (int)V_K.size())
throw std::length_error("aff3ct::module::CRC: \"V_K.size()\" has to be equal or greater than "
"\"K\" * \"n_frames\".");
if (n_frames <= 0 && n_frames != -1)
throw std::invalid_argument("aff3ct::module::CRC: \"n_frames\" has to be greater than 0 (or equal "
"to -1).");
return this->check_packed(V_K.data(), n_frames);
}
bool check_packed(const B *V_K, const int n_frames = -1)
{
const int real_n_frames = (n_frames != -1) ? n_frames : this->n_frames;
auto f = 0;
while (f < real_n_frames && this->_check_packed(V_K + f * this->K))
f++;
return f == real_n_frames;
}
protected:
virtual void _build(B *V_K)
{
throw std::runtime_error("aff3ct::module::CRC: \"_build\" is unimplemented.");
}
virtual bool _check(const B *V_K)
{
throw std::runtime_error("aff3ct::module::CRC: \"_check\" is unimplemented.");
return false;
}
virtual bool _check_packed(const B *V_K)
{
throw std::runtime_error("aff3ct::module::CRC: \"_check_packed\" is unimplemented.");
return false;
}
};
}
}
#include "SC_CRC.hpp"
#endif
<|endoftext|>
|
<commit_before>/* IBM_PROLOG_BEGIN_TAG */
/* This is an automatically generated prolog. */
/* */
/* $Source: src/import/chips/p9/procedures/hwp/pm/p9_pm_recovery_ffdc_pgpe.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 */
// *INDENT-OFF*
///
/// @file p9_pm_recovery_ffdc_pgpe.C
/// @brief Models PGPE platform for the FFDC collection of PM complex
///
/// *HWP HWP Owner: Greg Still <[email protected]>
/// *HWP FW Owner: Prem S Jha <[email protected]>
/// *HWP Team: PM
/// *HWP Level: 2
/// *HWP Consumed by: Hostboot
//
// *INDENT-OFF*
//--------------------------------------------------------------------------
// Includes
//--------------------------------------------------------------------------
#include <p9_pm_recovery_ffdc_pgpe.H>
#include <p9_hcd_memmap_occ_sram.H>
#include <p9_ppe_defs.H>
#include <stddef.h>
#include <endian.h>
namespace p9_stop_recov_ffdc
{
PlatPgpe::PlatPgpe( const fapi2::Target< fapi2::TARGET_TYPE_PROC_CHIP > i_procChipTgt )
: PlatPmComplex( i_procChipTgt,
PLAT_PGPE,
OCC_SRAM_PGPE_HEADER_ADDR,
OCC_SRAM_PGPE_TRACE_START,
OCC_SRAM_PGPE_DASHBOARD_START )
{ }
//----------------------------------------------------------------------
fapi2::ReturnCode PlatPgpe::init ( void* i_pHomerBuf )
{
FAPI_DBG (">> PlatPgpe::init" );
FAPI_TRY ( collectFfdc( i_pHomerBuf, INIT),
"Failed To init PGPE FFDC" );
fapi_try_exit:
FAPI_DBG ("<< PlatPgpe::init" );
return fapi2::current_err;
}
//----------------------------------------------------------------------
fapi2::ReturnCode PlatPgpe::collectFfdc( void * i_pHomerBuf,
uint8_t i_ffdcType )
{
FAPI_DBG(">> PlatPgpe::collectFfdc: 0x%02X", i_ffdcType);
fapi2::ReturnCode l_retCode = fapi2::FAPI2_RC_SUCCESS;
HomerFfdcRegion * l_pHomerFfdc =
( HomerFfdcRegion *)( (uint8_t *)i_pHomerBuf + FFDC_REGION_HOMER_BASE_OFFSET );
uint8_t* l_pFfdcLoc = (uint8_t *)(&l_pHomerFfdc->iv_pgpeFfdcRegion);
PpeFfdcHeader* l_pPgpeFfdcHdr = (PpeFfdcHeader*) l_pFfdcLoc;
uint16_t l_ffdcValdityVect = l_pPgpeFfdcHdr->iv_sectionsValid;
if ( i_ffdcType & INIT )
{ // overwrite on init
l_ffdcValdityVect = PPE_FFDC_INVALID;
}
//In case of error , invalidate FFDC in header.
if ( i_ffdcType & PPE_HALT_STATE )
{
l_ffdcValdityVect |= PPE_HALT_STATE_VALID;
l_retCode = readPpeHaltState ( PGPE_BASE_ADDRESS, l_pFfdcLoc);
if ( l_retCode != fapi2::FAPI2_RC_SUCCESS )
{
FAPI_ERR ( "Error collecting PGPE Halt State" );
l_ffdcValdityVect &= ~PPE_HALT_STATE_VALID;
}
}
if (i_ffdcType & PPE_STATE )
{
l_ffdcValdityVect |= PPE_STATE_VALID;
l_retCode = collectPpeState ( PGPE_BASE_ADDRESS,
l_pFfdcLoc );
if ( l_retCode != fapi2::FAPI2_RC_SUCCESS )
{
FAPI_ERR ( "Error collecting PGPE State" );
l_ffdcValdityVect &= ~PPE_STATE_VALID;
}
}
if ( i_ffdcType & TRACES )
{
l_ffdcValdityVect |= PPE_TRACE_VALID;
l_retCode = collectTrace( l_pFfdcLoc );
if( l_retCode )
{
FAPI_ERR("Error in collecting PGPE Trace " );
l_ffdcValdityVect &= ~PPE_TRACE_VALID;
}
}
if ( i_ffdcType & DASH_BOARD_VAR )
{
l_ffdcValdityVect |= PPE_DASHBOARD_VALID;
l_retCode = collectGlobals( l_pFfdcLoc );
if( l_retCode )
{
FAPI_ERR("Error in collecting PGPE Globals" );
l_ffdcValdityVect &= ~PPE_DASHBOARD_VALID;
}
}
if ( i_ffdcType & IMAGE_HEADER )
{
l_ffdcValdityVect |= PPE_IMAGE_HEADER_VALID;
l_retCode = collectImageHeader( l_pFfdcLoc );
if( l_retCode )
{
FAPI_ERR("Error in collecting PGPE Image header" );
l_ffdcValdityVect &= ~PPE_IMAGE_HEADER_VALID;
}
}
FAPI_TRY( updatePgpeFfdcHeader( l_pFfdcLoc, l_ffdcValdityVect ),
"Failed To Update PGPE FFDC Header for PGPE " );
if (l_ffdcValdityVect == PPE_FFDC_INVALID)
setPmFfdcSectionValid ( i_pHomerBuf, PM_FFDC_PGPE_VALID, false );
else
setPmFfdcSectionValid ( i_pHomerBuf, PM_FFDC_PGPE_VALID );
fapi_try_exit:
FAPI_DBG("<< PlatPgpe::collectFfdc");
return fapi2::current_err;
}
//-----------------------------------------------------------------------
fapi2::ReturnCode PlatPgpe::collectTrace( uint8_t * i_pTraceBuf )
{
FAPI_DBG(">> PlatPgpe::collectTrace" );
PpeFfdcLayout * l_pPgpeFfdc = ( PpeFfdcLayout *) ( i_pTraceBuf );
uint8_t * l_pTraceLoc = &l_pPgpeFfdc->iv_ppeTraces[0];
FAPI_TRY( PlatPmComplex::collectSramInfo
( PlatPmComplex::getProcChip(),
l_pTraceLoc,
TRACES,
FFDC_PPE_TRACES_SIZE ),
"Trace Collection Failed" );
fapi_try_exit:
FAPI_DBG("<< PlatPgpe::collectTrace" );
return fapi2::current_err;
}
//-----------------------------------------------------------------------
fapi2::ReturnCode PlatPgpe::collectGlobals( uint8_t * i_pPgpeGlobals )
{
FAPI_DBG(">> PlatPgpe::collectGlobals" );
PpeFfdcLayout * l_pPgpeFfdc = ( PpeFfdcLayout *) ( i_pPgpeGlobals );
uint8_t * l_pTraceLoc = &l_pPgpeFfdc->iv_ppeGlobals[0];
FAPI_TRY( PlatPmComplex::collectSramInfo
( PlatPmComplex::getProcChip(),
l_pTraceLoc,
DASH_BOARD_VAR,
OCC_SRAM_PGPE_DASHBOARD_SIZE ),
"Failed To Collect PGPE Global Variables" );
fapi_try_exit:
FAPI_DBG("<< PlatPgpe::collectGlobals" );
return fapi2::current_err;
}
//-----------------------------------------------------------------------
fapi2::ReturnCode PlatPgpe::collectInternalReg( uint8_t * i_pPgpeIntReg )
{
return fapi2::FAPI2_RC_SUCCESS;
}
//-----------------------------------------------------------------------
fapi2::ReturnCode PlatPgpe::collectImageHeader( uint8_t * i_pPgpeImgHdr )
{
FAPI_DBG(">> PlatPgpe::collectImageHeader" );
PpeFfdcLayout *l_pPgpeFfdc = ( PpeFfdcLayout *) ( i_pPgpeImgHdr );
uint8_t * l_pTraceLoc = &l_pPgpeFfdc->iv_ppeImageHeader[0];
FAPI_TRY( PlatPmComplex::collectSramInfo
( PlatPmComplex::getProcChip(),
l_pTraceLoc,
IMAGE_HEADER,
FFDC_PPE_IMG_HDR_SIZE ),
"Failed To Collect PGPE Image Header" );
fapi_try_exit:
FAPI_DBG("<< PlatPgpe::collectImageHeader" );
return fapi2::current_err;
}
//-----------------------------------------------------------------------
fapi2::ReturnCode PlatPgpe::updatePgpeFfdcHeader( uint8_t* i_pHomerBuf,
uint16_t i_sectionsValid )
{
FAPI_DBG(">> updatePgpeFfdcHeader" );
PpeFfdcHeader * l_pPgpeFfdcHdr = ( (PpeFfdcHeader *)(( PpeFfdcHdrRegion * ) i_pHomerBuf ));
l_pPgpeFfdcHdr->iv_ppeMagicNumber = htobe32( FFDC_PGPE_MAGIC_NUM );
l_pPgpeFfdcHdr->iv_ppeNumber = 0;
updatePpeFfdcHeader ( l_pPgpeFfdcHdr, i_sectionsValid );
FAPI_DBG("<< updatePgpeFfdcHeader" );
return fapi2::FAPI2_RC_SUCCESS;
}
//-----------------------------------------------------------------------
extern "C"
{
fapi2::ReturnCode p9_pm_recovery_ffdc_pgpe( const fapi2::Target<fapi2::TARGET_TYPE_PROC_CHIP >& i_procChip,
void * i_pFfdcBuf )
{
FAPI_IMP(">> p9_pm_recovery_pgpe" );
PlatPgpe l_pgpeFfdc( i_procChip );
FAPI_TRY( l_pgpeFfdc.collectFfdc( i_pFfdcBuf, (ALL & ~PPE_HALT_STATE) ),
"Failed To Collect PGPE FFDC" );
fapi_try_exit:
FAPI_IMP("<< p9_pm_recovery_pgpe" );
return fapi2::current_err;
}
}
}//namespace p9_stop_recov_ffdc ends
<commit_msg>PM: Generation of summarized version of STOP Recovery FFDC.<commit_after>/* IBM_PROLOG_BEGIN_TAG */
/* This is an automatically generated prolog. */
/* */
/* $Source: src/import/chips/p9/procedures/hwp/pm/p9_pm_recovery_ffdc_pgpe.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 */
// *INDENT-OFF*
///
/// @file p9_pm_recovery_ffdc_pgpe.C
/// @brief Models PGPE platform for the FFDC collection of PM complex
///
/// *HWP HWP Owner: Greg Still <[email protected]>
/// *HWP FW Owner: Prem S Jha <[email protected]>
/// *HWP Team: PM
/// *HWP Level: 2
/// *HWP Consumed by: Hostboot
//
// *INDENT-OFF*
//--------------------------------------------------------------------------
// Includes
//--------------------------------------------------------------------------
#include <p9_pm_recovery_ffdc_pgpe.H>
#include <p9_hcd_memmap_occ_sram.H>
#include <p9_ppe_defs.H>
#include <p9_ppe_utils.H>
#include <stddef.h>
#include <endian.h>
namespace p9_stop_recov_ffdc
{
PlatPgpe::PlatPgpe( const fapi2::Target< fapi2::TARGET_TYPE_PROC_CHIP > i_procChipTgt )
: PlatPmComplex( i_procChipTgt,
PLAT_PGPE,
OCC_SRAM_PGPE_HEADER_ADDR,
OCC_SRAM_PGPE_TRACE_START,
OCC_SRAM_PGPE_DASHBOARD_START )
{ }
//----------------------------------------------------------------------
fapi2::ReturnCode PlatPgpe::init ( void* i_pHomerBuf )
{
FAPI_DBG (">> PlatPgpe::init" );
FAPI_TRY ( collectFfdc( i_pHomerBuf, INIT),
"Failed To init PGPE FFDC" );
fapi_try_exit:
FAPI_DBG ("<< PlatPgpe::init" );
return fapi2::current_err;
}
//----------------------------------------------------------------------
fapi2::ReturnCode PlatPgpe::collectFfdc( void * i_pHomerBuf,
uint8_t i_ffdcType )
{
FAPI_DBG(">> PlatPgpe::collectFfdc: 0x%02X", i_ffdcType);
fapi2::ReturnCode l_retCode = fapi2::FAPI2_RC_SUCCESS;
HomerFfdcRegion * l_pHomerFfdc =
( HomerFfdcRegion *)( (uint8_t *)i_pHomerBuf + FFDC_REGION_HOMER_BASE_OFFSET );
uint8_t* l_pFfdcLoc = (uint8_t *)(&l_pHomerFfdc->iv_pgpeFfdcRegion);
PpeFfdcHeader* l_pPgpeFfdcHdr = (PpeFfdcHeader*) l_pFfdcLoc;
uint16_t l_ffdcValdityVect = l_pPgpeFfdcHdr->iv_sectionsValid;
if ( i_ffdcType & INIT )
{ // overwrite on init
l_ffdcValdityVect = PPE_FFDC_INVALID;
}
//In case of error , invalidate FFDC in header.
if ( i_ffdcType & PPE_HALT_STATE )
{
l_ffdcValdityVect |= PPE_HALT_STATE_VALID;
l_retCode = readPpeHaltState ( PGPE_BASE_ADDRESS, l_pFfdcLoc);
if ( l_retCode != fapi2::FAPI2_RC_SUCCESS )
{
FAPI_ERR ( "Error collecting PGPE Halt State" );
l_ffdcValdityVect &= ~PPE_HALT_STATE_VALID;
}
}
if (i_ffdcType & PPE_STATE )
{
l_ffdcValdityVect |= PPE_STATE_VALID;
l_retCode = collectPpeState ( PGPE_BASE_ADDRESS,
l_pFfdcLoc );
if ( l_retCode != fapi2::FAPI2_RC_SUCCESS )
{
FAPI_ERR ( "Error collecting PGPE State" );
l_ffdcValdityVect &= ~PPE_STATE_VALID;
}
}
if ( i_ffdcType & TRACES )
{
l_ffdcValdityVect |= PPE_TRACE_VALID;
l_retCode = collectTrace( l_pFfdcLoc );
if( l_retCode )
{
FAPI_ERR("Error in collecting PGPE Trace " );
l_ffdcValdityVect &= ~PPE_TRACE_VALID;
}
}
if ( i_ffdcType & DASH_BOARD_VAR )
{
l_ffdcValdityVect |= PPE_DASHBOARD_VALID;
l_retCode = collectGlobals( l_pFfdcLoc );
if( l_retCode )
{
FAPI_ERR("Error in collecting PGPE Globals" );
l_ffdcValdityVect &= ~PPE_DASHBOARD_VALID;
}
}
if ( i_ffdcType & IMAGE_HEADER )
{
l_ffdcValdityVect |= PPE_IMAGE_HEADER_VALID;
l_retCode = collectImageHeader( l_pFfdcLoc );
if( l_retCode )
{
FAPI_ERR("Error in collecting PGPE Image header" );
l_ffdcValdityVect &= ~PPE_IMAGE_HEADER_VALID;
}
}
FAPI_TRY( updatePgpeFfdcHeader( l_pFfdcLoc, l_ffdcValdityVect ),
"Failed To Update PGPE FFDC Header for PGPE " );
if (l_ffdcValdityVect == PPE_FFDC_INVALID)
setPmFfdcSectionValid ( i_pHomerBuf, PM_FFDC_PGPE_VALID, false );
else
setPmFfdcSectionValid ( i_pHomerBuf, PM_FFDC_PGPE_VALID );
if( !(i_ffdcType & INIT) )
{
generateSummary( i_pHomerBuf );
}
fapi_try_exit:
FAPI_DBG("<< PlatPgpe::collectFfdc");
return fapi2::current_err;
}
//-----------------------------------------------------------------------
fapi2::ReturnCode PlatPgpe::collectTrace( uint8_t * i_pTraceBuf )
{
FAPI_DBG(">> PlatPgpe::collectTrace" );
PpeFfdcLayout * l_pPgpeFfdc = ( PpeFfdcLayout *) ( i_pTraceBuf );
uint8_t * l_pTraceLoc = &l_pPgpeFfdc->iv_ppeTraces[0];
uint64_t l_traceBufHdr = 0;
uint32_t l_traceBufAddress = 0;
uint32_t l_doubleWordsRead = 0;
FAPI_TRY( PlatPmComplex::readSramInfo( PlatPmComplex::getProcChip(),
getTraceBufAddr(),
(uint8_t *)&l_traceBufHdr,
8,
l_doubleWordsRead ),
"Trace Buf Ptr Collection Failed" );
l_traceBufHdr = htobe64( l_traceBufHdr );
l_traceBufAddress = (uint32_t) l_traceBufHdr;
FAPI_DBG( "Trace Buf Address 0x%08x", l_traceBufAddress );
FAPI_TRY( PlatPmComplex::readSramInfo( PlatPmComplex::getProcChip(),
l_traceBufAddress,
l_pTraceLoc,
FFDC_PPE_TRACES_SIZE,
l_doubleWordsRead ),
"Trace Bin Collection Failed" );
fapi_try_exit:
FAPI_DBG("<< PlatPgpe::collectTrace" );
return fapi2::current_err;
}
//-----------------------------------------------------------------------
fapi2::ReturnCode PlatPgpe::collectGlobals( uint8_t * i_pPgpeGlobals )
{
FAPI_DBG(">> PlatPgpe::collectGlobals" );
PpeFfdcLayout * l_pPgpeFfdc = ( PpeFfdcLayout *) ( i_pPgpeGlobals );
uint8_t * l_pTraceLoc = &l_pPgpeFfdc->iv_ppeGlobals[0];
FAPI_TRY( PlatPmComplex::collectSramInfo
( PlatPmComplex::getProcChip(),
l_pTraceLoc,
DASH_BOARD_VAR,
OCC_SRAM_PGPE_DASHBOARD_SIZE ),
"Failed To Collect PGPE Global Variables" );
fapi_try_exit:
FAPI_DBG("<< PlatPgpe::collectGlobals" );
return fapi2::current_err;
}
//-----------------------------------------------------------------------
fapi2::ReturnCode PlatPgpe::collectInternalReg( uint8_t * i_pPgpeIntReg )
{
return fapi2::FAPI2_RC_SUCCESS;
}
//-----------------------------------------------------------------------
fapi2::ReturnCode PlatPgpe::collectImageHeader( uint8_t * i_pPgpeImgHdr )
{
FAPI_DBG(">> PlatPgpe::collectImageHeader" );
PpeFfdcLayout *l_pPgpeFfdc = ( PpeFfdcLayout *) ( i_pPgpeImgHdr );
uint8_t * l_pTraceLoc = &l_pPgpeFfdc->iv_ppeImageHeader[0];
FAPI_TRY( PlatPmComplex::collectSramInfo
( PlatPmComplex::getProcChip(),
l_pTraceLoc,
IMAGE_HEADER,
FFDC_PPE_IMG_HDR_SIZE ),
"Failed To Collect PGPE Image Header" );
fapi_try_exit:
FAPI_DBG("<< PlatPgpe::collectImageHeader" );
return fapi2::current_err;
}
//-----------------------------------------------------------------------
fapi2::ReturnCode PlatPgpe::updatePgpeFfdcHeader( uint8_t* i_pHomerBuf,
uint16_t i_sectionsValid )
{
FAPI_DBG(">> updatePgpeFfdcHeader" );
PpeFfdcHeader * l_pPgpeFfdcHdr = ( (PpeFfdcHeader *)(( PpeFfdcHdrRegion * ) i_pHomerBuf ));
l_pPgpeFfdcHdr->iv_ppeMagicNumber = htobe32( FFDC_PGPE_MAGIC_NUM );
l_pPgpeFfdcHdr->iv_ppeNumber = 0;
updatePpeFfdcHeader ( l_pPgpeFfdcHdr, i_sectionsValid );
FAPI_DBG("<< updatePgpeFfdcHeader" );
return fapi2::FAPI2_RC_SUCCESS;
}
//-----------------------------------------------------------------------
fapi2::ReturnCode PlatPgpe::generateSummary( void * i_pHomer )
{
FAPI_DBG(">> PlatPgpe::generateSummary" );
HomerFfdcRegion * l_pHomerFfdc =
( HomerFfdcRegion *)( (uint8_t *)i_pHomer + FFDC_REGION_HOMER_BASE_OFFSET );
PpeFfdcLayout * l_pPgpeLayout = ( PpeFfdcLayout * ) &l_pHomerFfdc->iv_pgpeFfdcRegion;
uint8_t * l_pPgpeXirReg = &l_pPgpeLayout->iv_ppeXirReg[0];
uint8_t * l_pPgpeSummary = &l_pHomerFfdc->iv_ffdcSummaryRegion.iv_pgpeSummary[FFDC_SUMMARY_SEC_HDR_SIZE];
PpeFfdcHeader* l_pPgpeFfdcHdr = (PpeFfdcHeader*) &l_pHomerFfdc->iv_pgpeFfdcRegion;
FfdcSummSubSectHdr * l_pPgpeSummaryHdr = (FfdcSummSubSectHdr *)&l_pHomerFfdc->iv_ffdcSummaryRegion.iv_pgpeSummary[0];
l_pPgpeSummaryHdr->iv_subSectnId = PLAT_PGPE;
l_pPgpeSummaryHdr->iv_majorNum = 1;
l_pPgpeSummaryHdr->iv_minorNum = 0;
l_pPgpeSummaryHdr->iv_secValid = l_pPgpeFfdcHdr->iv_sectionsValid;
if( l_pPgpeSummaryHdr->iv_secValid )
{
PlatPmComplex::initRegList();
PlatPmComplex::extractPpeSummaryReg( l_pPgpeXirReg, FFDC_PPE_XIR_SIZE, l_pPgpeSummary );
//Populating the Extended FFDC summary
l_pHomerFfdc->iv_ffdcSummaryRegion.iv_pgpeScoreBoard.iv_dataPtr = &l_pPgpeLayout->iv_ppeGlobals[0];
l_pHomerFfdc->iv_ffdcSummaryRegion.iv_pgpeScoreBoard.iv_dataSize = FFDC_PPE_SCORE_BOARD_SIZE;
}
FAPI_DBG("<< PlatPgpe::generateSummary" );
return fapi2::FAPI2_RC_SUCCESS;
}
//-----------------------------------------------------------------------
extern "C"
{
fapi2::ReturnCode p9_pm_recovery_ffdc_pgpe( const fapi2::Target<fapi2::TARGET_TYPE_PROC_CHIP >& i_procChip,
void * i_pFfdcBuf )
{
FAPI_IMP(">> p9_pm_recovery_pgpe" );
PlatPgpe l_pgpeFfdc( i_procChip );
FAPI_TRY( l_pgpeFfdc.collectFfdc( i_pFfdcBuf, (ALL & ~PPE_HALT_STATE) ),
"Failed To Collect PGPE FFDC" );
fapi_try_exit:
FAPI_IMP("<< p9_pm_recovery_pgpe" );
return fapi2::current_err;
}
}
}//namespace p9_stop_recov_ffdc ends
<|endoftext|>
|
<commit_before>#include "SpatiaLiteDB.h"
#include <iostream>
#include <algorithm>
////////////////////////////////////////////////////////////////////
SpatiaLiteDB::Point::Point(double x, double y, std::string label):
_x(x),
_y(y),
_label(label)
{
}
////////////////////////////////////////////////////////////////////
SpatiaLiteDB::Point::~Point() {
}
////////////////////////////////////////////////////////////////////
std::ostream& operator<<(std::ostream& lhs, SpatiaLiteDB::Point& rhs) {
lhs << "(" << rhs._x << "," << rhs._y << ")";
return lhs;
}
////////////////////////////////////////////////////////////////////
SpatiaLiteDB::Linestring::Linestring(std::string label):
_label(label)
{
}
////////////////////////////////////////////////////////////////////
SpatiaLiteDB::Linestring::~Linestring() {
}
////////////////////////////////////////////////////////////////////
std::ostream& operator<<(std::ostream& lhs, SpatiaLiteDB::Linestring& rhs) {
for (SpatiaLiteDB::Linestring::iterator i = rhs.begin();
i != rhs.end();
i++) {
lhs << *i;
}
return lhs;
}
////////////////////////////////////////////////////////////////////
SpatiaLiteDB::Ring::Ring():
_clockwise(0)
{
}
////////////////////////////////////////////////////////////////////
SpatiaLiteDB::Ring::Ring(int clockwise):
_clockwise(clockwise)
{
}
////////////////////////////////////////////////////////////////////
SpatiaLiteDB::Ring::~Ring() {
}
////////////////////////////////////////////////////////////////////
std::ostream& operator<<(std::ostream& lhs, SpatiaLiteDB::Ring& rhs) {
for (SpatiaLiteDB::Ring::iterator i = rhs.begin();
i != rhs.end();
i++) {
lhs << *i;
}
return lhs;
}
////////////////////////////////////////////////////////////////////
SpatiaLiteDB::Polygon::Polygon(std::string label):
_label(label)
{
}
////////////////////////////////////////////////////////////////////
SpatiaLiteDB::Polygon::~Polygon() {
}
////////////////////////////////////////////////////////////////////
void SpatiaLiteDB::Polygon::setExtRing(Ring r) {
_extRing = r;
}
////////////////////////////////////////////////////////////////////
void SpatiaLiteDB::Polygon::addIntRing(Ring r) {
_intRings.push_back(r);
}
////////////////////////////////////////////////////////////////////
SpatiaLiteDB::Ring SpatiaLiteDB::Polygon::extRing() {
return _extRing;
}
////////////////////////////////////////////////////////////////////
std::vector<SpatiaLiteDB::Ring> SpatiaLiteDB::Polygon::intRings() {
return _intRings;
}
////////////////////////////////////////////////////////////////////
std::ostream& operator<<(std::ostream& lhs, SpatiaLiteDB::Polygon& rhs) {
lhs << rhs._extRing;
for (int i = 0;
i < rhs._intRings.size();
i++) {
lhs << rhs._intRings[i];
}
return lhs;
}
////////////////////////////////////////////////////////////////////
SpatiaLiteDB::PointList::PointList()
{
}
////////////////////////////////////////////////////////////////////
SpatiaLiteDB::PointList::~PointList() {
}
////////////////////////////////////////////////////////////////////
SpatiaLiteDB::LinestringList::LinestringList()
{
}
////////////////////////////////////////////////////////////////////
SpatiaLiteDB::LinestringList::~LinestringList() {
}
////////////////////////////////////////////////////////////////////
SpatiaLiteDB::PolygonList::PolygonList(std::string label)
{
}
////////////////////////////////////////////////////////////////////
SpatiaLiteDB::PolygonList::~PolygonList() {
}
////////////////////////////////////////////////////////////////////
SpatiaLiteDB::SpatiaLiteDB(std::string dbPath) throw (std::string) :
SQLiteDB(dbPath, true)
{
// initialize spatiaLite.
_connection = spatialite_alloc_connection();
SQLiteDB::init();
spatialite_init_ex(handle(), _connection, true);
}
////////////////////////////////////////////////////////////////////
SpatiaLiteDB::~SpatiaLiteDB() {
SQLiteDB::close();
spatialite_cleanup_ex(_connection);
}
////////////////////////////////////////////////////////////////////
std::string SpatiaLiteDB::version() {
std::stringstream s;
s << SQLiteDB::version() << ", ";
s << "SpatiaLite version: " << spatialite_version();
return s.str();
}
////////////////////////////////////////////////////////////////////
void SpatiaLiteDB::queryGeometry(
std::string table,
std::string geometry_col,
double left,
double bottom,
double right,
double top,
std::string label_col) {
_pointlist.clear();
_linestringlist.clear();
_polygonlist.clear();
bool getLabel = label_col.size() != 0;
// Search for geometry and name
// The query will be either
//
// SELECT Geometry FROM table WHERE MbrWithin(Column, BuildMbr(left, bottom, right, top));
// or
// SELECT Geometry,Label FROM table WHERE MbrWithin(Column, BuildMbr(left, bottom, right, top));
//
// where Geometry is the geometry column name and Label is the column containing a name or label.
std::string label;
if (getLabel) {
label = "," + label_col;
}
std::stringstream s;
s <<
"SELECT " <<
geometry_col <<
label <<
" FROM " <<
table <<
" WHERE MbrIntersects(" <<
geometry_col <<
", BuildMbr(" <<
left <<
"," <<
bottom <<
"," <<
right <<
"," <<
top <<
"));";
// prepare the query
prepare(s.str());
// fetch the next result row
while (step()) {
// get the geometry
gaiaGeomCollPtr geom = Geom(0);
// get the label, if we asked for it
std::string label;
if (getLabel) {
label = Text(1);
}
// the following will create lists for points, lines and polygons found in
// a single geometry. In practice it seems that only one of those types
// exists for a given geometry, but it's not clear if this is a requirement
// or just occurs in the sample databases we have been working with.
PointList points = point_list(geom, label);
for (PointList::iterator i = points.begin(); i != points.end(); i++) {
_pointlist.push_back(*i);
}
LinestringList lines = linestring_list(geom, label);
for (LinestringList::iterator i = lines.begin(); i != lines.end(); i++) {
_linestringlist.push_back(*i);
}
PolygonList polys = polygon_list(geom, label);
for (PolygonList::iterator i = polys.begin(); i != polys.end(); i++) {
_polygonlist.push_back(*i);
}
}
// finish with this query
finalize();
}
////////////////////////////////////////////////////////////////////
gaiaGeomCollPtr SpatiaLiteDB::Geom(int col) throw (std::string) {
// throw an exception if the requested column doesn't exist
checkColumn(SQLITE_BLOB, col);
const void* blob;
int blob_size;
gaiaGeomCollPtr geom;
blob = Blob(col, blob_size);
geom = gaiaFromSpatiaLiteBlobWkb((const unsigned char*) blob, blob_size);
// Save geom for later cleanup.
_geoms.push_back(geom);
return geom;
}
////////////////////////////////////////////////////////////////////
SpatiaLiteDB::PointList SpatiaLiteDB::point_list(gaiaGeomCollPtr geom, std::string label) {
SpatiaLiteDB::PointList pl;
gaiaPointPtr point = geom->FirstPoint;
while (point) {
pl.push_back(SpatiaLiteDB::Point(point->X, point->Y, label));
point = point->Next;
}
return pl;
}
////////////////////////////////////////////////////////////////////
SpatiaLiteDB::LinestringList SpatiaLiteDB::linestring_list(gaiaGeomCollPtr geom, std::string label) {
SpatiaLiteDB::LinestringList ll;
gaiaLinestringPtr linestring = geom->FirstLinestring;
while (linestring) {
Linestring ls(label);
for (int i = 0; i < linestring->Points; i++) {
double x;
double y;
gaiaGetPoint(linestring->Coords, i, &x, &y);
ls.push_back(SpatiaLiteDB::Point(x, y));
}
ll.push_back(ls);
linestring = linestring->Next;
}
return ll;
}
////////////////////////////////////////////////////////////////////
SpatiaLiteDB::PolygonList SpatiaLiteDB::polygon_list(gaiaGeomCollPtr geom, std::string label) {
double x;
double y;
SpatiaLiteDB::PolygonList polylist;
gaiaPolygonPtr polygon = geom->FirstPolygon;
while (polygon) {
Polygon p(label);
gaiaRingPtr rExt = polygon->Exterior;
Ring r(rExt->Clockwise);
for (int i = 0; i < rExt->Points; i++) {
gaiaGetPoint(rExt->Coords, i, &x, &y);
r.push_back(SpatiaLiteDB::Point(x, y));
}
p.setExtRing(r);
gaiaRingPtr rInt = polygon->Interiors;
while (rInt) {
Ring r(rInt->Clockwise);
for (int i = 0; i < rInt->Points; i++) {
gaiaGetPoint(rInt->Coords, i, &x, &y);
r.push_back(SpatiaLiteDB::Point(x, y));
}
p.addIntRing(r);
rInt = rInt->Next;
}
polylist.push_back(p);
polygon = polygon->Next;
}
return polylist;
}
////////////////////////////////////////////////////////////////////
SpatiaLiteDB::PointList SpatiaLiteDB::points() {
return _pointlist;
}
////////////////////////////////////////////////////////////////////
SpatiaLiteDB::LinestringList SpatiaLiteDB::linestrings() {
return _linestringlist;
}
////////////////////////////////////////////////////////////////////
SpatiaLiteDB::PolygonList SpatiaLiteDB::polygons() {
return _polygonlist;
}
////////////////////////////////////////////////////////////////////
std::vector<std::string> SpatiaLiteDB::geometryTables() {
std::vector<std::string> all_tables = table_names();
// find all tables containing a geometry column
std::vector<std::string> geometry_tables;
for (std::vector<std::string>::iterator table = all_tables.begin();
table != all_tables.end(); table++) {
std::vector<std::string> columns = column_names(*table);
for (std::vector<std::string>::iterator column = columns.begin();
column != columns.end(); column++) {
std::transform(column->begin(), column->end(), column->begin(),
(int(*)(int))std::tolower);
if (!column->compare("geometry")) {
geometry_tables.push_back(*table);
}
}
}
return geometry_tables;
}
////////////////////////////////////////////////////////////////////
////////////////////////////////////////////////////////////////////
<commit_msg>Restore the geometry freeing.<commit_after>#include "SpatiaLiteDB.h"
#include <iostream>
#include <algorithm>
////////////////////////////////////////////////////////////////////
SpatiaLiteDB::Point::Point(double x, double y, std::string label):
_x(x),
_y(y),
_label(label)
{
}
////////////////////////////////////////////////////////////////////
SpatiaLiteDB::Point::~Point() {
}
////////////////////////////////////////////////////////////////////
std::ostream& operator<<(std::ostream& lhs, SpatiaLiteDB::Point& rhs) {
lhs << "(" << rhs._x << "," << rhs._y << ")";
return lhs;
}
////////////////////////////////////////////////////////////////////
SpatiaLiteDB::Linestring::Linestring(std::string label):
_label(label)
{
}
////////////////////////////////////////////////////////////////////
SpatiaLiteDB::Linestring::~Linestring() {
}
////////////////////////////////////////////////////////////////////
std::ostream& operator<<(std::ostream& lhs, SpatiaLiteDB::Linestring& rhs) {
for (SpatiaLiteDB::Linestring::iterator i = rhs.begin();
i != rhs.end();
i++) {
lhs << *i;
}
return lhs;
}
////////////////////////////////////////////////////////////////////
SpatiaLiteDB::Ring::Ring():
_clockwise(0)
{
}
////////////////////////////////////////////////////////////////////
SpatiaLiteDB::Ring::Ring(int clockwise):
_clockwise(clockwise)
{
}
////////////////////////////////////////////////////////////////////
SpatiaLiteDB::Ring::~Ring() {
}
////////////////////////////////////////////////////////////////////
std::ostream& operator<<(std::ostream& lhs, SpatiaLiteDB::Ring& rhs) {
for (SpatiaLiteDB::Ring::iterator i = rhs.begin();
i != rhs.end();
i++) {
lhs << *i;
}
return lhs;
}
////////////////////////////////////////////////////////////////////
SpatiaLiteDB::Polygon::Polygon(std::string label):
_label(label)
{
}
////////////////////////////////////////////////////////////////////
SpatiaLiteDB::Polygon::~Polygon() {
}
////////////////////////////////////////////////////////////////////
void SpatiaLiteDB::Polygon::setExtRing(Ring r) {
_extRing = r;
}
////////////////////////////////////////////////////////////////////
void SpatiaLiteDB::Polygon::addIntRing(Ring r) {
_intRings.push_back(r);
}
////////////////////////////////////////////////////////////////////
SpatiaLiteDB::Ring SpatiaLiteDB::Polygon::extRing() {
return _extRing;
}
////////////////////////////////////////////////////////////////////
std::vector<SpatiaLiteDB::Ring> SpatiaLiteDB::Polygon::intRings() {
return _intRings;
}
////////////////////////////////////////////////////////////////////
std::ostream& operator<<(std::ostream& lhs, SpatiaLiteDB::Polygon& rhs) {
lhs << rhs._extRing;
for (int i = 0;
i < rhs._intRings.size();
i++) {
lhs << rhs._intRings[i];
}
return lhs;
}
////////////////////////////////////////////////////////////////////
SpatiaLiteDB::PointList::PointList()
{
}
////////////////////////////////////////////////////////////////////
SpatiaLiteDB::PointList::~PointList() {
}
////////////////////////////////////////////////////////////////////
SpatiaLiteDB::LinestringList::LinestringList()
{
}
////////////////////////////////////////////////////////////////////
SpatiaLiteDB::LinestringList::~LinestringList() {
}
////////////////////////////////////////////////////////////////////
SpatiaLiteDB::PolygonList::PolygonList(std::string label)
{
}
////////////////////////////////////////////////////////////////////
SpatiaLiteDB::PolygonList::~PolygonList() {
}
////////////////////////////////////////////////////////////////////
SpatiaLiteDB::SpatiaLiteDB(std::string dbPath) throw (std::string) :
SQLiteDB(dbPath, true)
{
// initialize spatiaLite.
_connection = spatialite_alloc_connection();
SQLiteDB::init();
spatialite_init_ex(handle(), _connection, true);
}
////////////////////////////////////////////////////////////////////
SpatiaLiteDB::~SpatiaLiteDB() {
for (int i = 0; i < _geoms.size(); i++) {
gaiaFreeGeomColl(_geoms[i]);
}
SQLiteDB::close();
spatialite_cleanup_ex(_connection);
}
////////////////////////////////////////////////////////////////////
std::string SpatiaLiteDB::version() {
std::stringstream s;
s << SQLiteDB::version() << ", ";
s << "SpatiaLite version: " << spatialite_version();
return s.str();
}
////////////////////////////////////////////////////////////////////
void SpatiaLiteDB::queryGeometry(
std::string table,
std::string geometry_col,
double left,
double bottom,
double right,
double top,
std::string label_col) {
_pointlist.clear();
_linestringlist.clear();
_polygonlist.clear();
bool getLabel = label_col.size() != 0;
// Search for geometry and name
// The query will be either
//
// SELECT Geometry FROM table WHERE MbrWithin(Column, BuildMbr(left, bottom, right, top));
// or
// SELECT Geometry,Label FROM table WHERE MbrWithin(Column, BuildMbr(left, bottom, right, top));
//
// where Geometry is the geometry column name and Label is the column containing a name or label.
std::string label;
if (getLabel) {
label = "," + label_col;
}
std::stringstream s;
s <<
"SELECT " <<
geometry_col <<
label <<
" FROM " <<
table <<
" WHERE MbrIntersects(" <<
geometry_col <<
", BuildMbr(" <<
left <<
"," <<
bottom <<
"," <<
right <<
"," <<
top <<
"));";
// prepare the query
prepare(s.str());
// fetch the next result row
while (step()) {
// get the geometry
gaiaGeomCollPtr geom = Geom(0);
// get the label, if we asked for it
std::string label;
if (getLabel) {
label = Text(1);
}
// the following will create lists for points, lines and polygons found in
// a single geometry. In practice it seems that only one of those types
// exists for a given geometry, but it's not clear if this is a requirement
// or just occurs in the sample databases we have been working with.
PointList points = point_list(geom, label);
for (PointList::iterator i = points.begin(); i != points.end(); i++) {
_pointlist.push_back(*i);
}
LinestringList lines = linestring_list(geom, label);
for (LinestringList::iterator i = lines.begin(); i != lines.end(); i++) {
_linestringlist.push_back(*i);
}
PolygonList polys = polygon_list(geom, label);
for (PolygonList::iterator i = polys.begin(); i != polys.end(); i++) {
_polygonlist.push_back(*i);
}
}
// finish with this query
finalize();
}
////////////////////////////////////////////////////////////////////
gaiaGeomCollPtr SpatiaLiteDB::Geom(int col) throw (std::string) {
// throw an exception if the requested column doesn't exist
checkColumn(SQLITE_BLOB, col);
const void* blob;
int blob_size;
gaiaGeomCollPtr geom;
blob = Blob(col, blob_size);
geom = gaiaFromSpatiaLiteBlobWkb((const unsigned char*) blob, blob_size);
// Save geom for later cleanup.
_geoms.push_back(geom);
return geom;
}
////////////////////////////////////////////////////////////////////
SpatiaLiteDB::PointList SpatiaLiteDB::point_list(gaiaGeomCollPtr geom, std::string label) {
SpatiaLiteDB::PointList pl;
gaiaPointPtr point = geom->FirstPoint;
while (point) {
pl.push_back(SpatiaLiteDB::Point(point->X, point->Y, label));
point = point->Next;
}
return pl;
}
////////////////////////////////////////////////////////////////////
SpatiaLiteDB::LinestringList SpatiaLiteDB::linestring_list(gaiaGeomCollPtr geom, std::string label) {
SpatiaLiteDB::LinestringList ll;
gaiaLinestringPtr linestring = geom->FirstLinestring;
while (linestring) {
Linestring ls(label);
for (int i = 0; i < linestring->Points; i++) {
double x;
double y;
gaiaGetPoint(linestring->Coords, i, &x, &y);
ls.push_back(SpatiaLiteDB::Point(x, y));
}
ll.push_back(ls);
linestring = linestring->Next;
}
return ll;
}
////////////////////////////////////////////////////////////////////
SpatiaLiteDB::PolygonList SpatiaLiteDB::polygon_list(gaiaGeomCollPtr geom, std::string label) {
double x;
double y;
SpatiaLiteDB::PolygonList polylist;
gaiaPolygonPtr polygon = geom->FirstPolygon;
while (polygon) {
Polygon p(label);
gaiaRingPtr rExt = polygon->Exterior;
Ring r(rExt->Clockwise);
for (int i = 0; i < rExt->Points; i++) {
gaiaGetPoint(rExt->Coords, i, &x, &y);
r.push_back(SpatiaLiteDB::Point(x, y));
}
p.setExtRing(r);
gaiaRingPtr rInt = polygon->Interiors;
while (rInt) {
Ring r(rInt->Clockwise);
for (int i = 0; i < rInt->Points; i++) {
gaiaGetPoint(rInt->Coords, i, &x, &y);
r.push_back(SpatiaLiteDB::Point(x, y));
}
p.addIntRing(r);
rInt = rInt->Next;
}
polylist.push_back(p);
polygon = polygon->Next;
}
return polylist;
}
////////////////////////////////////////////////////////////////////
SpatiaLiteDB::PointList SpatiaLiteDB::points() {
return _pointlist;
}
////////////////////////////////////////////////////////////////////
SpatiaLiteDB::LinestringList SpatiaLiteDB::linestrings() {
return _linestringlist;
}
////////////////////////////////////////////////////////////////////
SpatiaLiteDB::PolygonList SpatiaLiteDB::polygons() {
return _polygonlist;
}
////////////////////////////////////////////////////////////////////
std::vector<std::string> SpatiaLiteDB::geometryTables() {
std::vector<std::string> all_tables = table_names();
// find all tables containing a geometry column
std::vector<std::string> geometry_tables;
for (std::vector<std::string>::iterator table = all_tables.begin();
table != all_tables.end(); table++) {
std::vector<std::string> columns = column_names(*table);
for (std::vector<std::string>::iterator column = columns.begin();
column != columns.end(); column++) {
std::transform(column->begin(), column->end(), column->begin(),
(int(*)(int))std::tolower);
if (!column->compare("geometry")) {
geometry_tables.push_back(*table);
}
}
}
return geometry_tables;
}
////////////////////////////////////////////////////////////////////
////////////////////////////////////////////////////////////////////
<|endoftext|>
|
<commit_before>#include "workerCL.hpp"
#define __CL_DEFINE_EXCEPTIONS
#include <CL/cl.hpp>
#include <vector>
#include <string>
#include <iostream>
#include "log.hpp"
#include "reads.hpp"
using namespace std;
WorkerCL::WorkerCL(size_t platform_id, size_t device_id){
/* GPU environment preparation */
//Get platforms (drivers) list and keep the one to be use
vector<cl::Platform> all_platforms;
cl::Platform::get(&all_platforms);
if(!all_platforms.size()){
//No platform ? Send error
string error = "OPENCL: no platforms found.";
throw(error);
}
m_platform = all_platforms[platform_id];
//Get devices list and keep the one to use
vector<cl::Device> devices;
m_platform.getDevices(CL_DEVICE_TYPE_ALL, &devices);
if(device_id >= devices.size()){
string error = "OPENCL: no device of id "+to_string(device_id)+
" on platform "+to_string(platform_id)+" ("+to_string(devices.size())+" devices)";
throw(error);
}
m_device = devices[device_id];
//Create context
m_context = cl::Context({m_device});
//initialize commands queue
m_commandqueue = cl::CommandQueue(m_context, m_device);
//Build kernel sources
m_program = cl::Program(m_context, kernel_cmp_2_contigs);
if(m_program.build({m_device}) != CL_SUCCESS){
string error = "Error building: ";
error += m_program.getBuildInfo<CL_PROGRAM_BUILD_LOG>(m_device);
throw(error);
}
//Make the kernel
m_kernel = cl::Kernel(m_program, "cmp_2_contigs");
}
WorkerCL::~WorkerCL(){
}
void WorkerCL::run(Contigs contigs){
/*
Create the string containing all contigs sequences
and store the list of contigs size (in same orders)
to be able to retrieve contigs. Size is store in
an uint64_t (ulong) to be sure it is 64bits as cl_ulong
*/
//Get list of contigs size and the total length of the
//contigs concatenation
uint64_t nbContigs = contigs.get_nbContigs();
uint64_t ultraSequenceSize = 0;
vector<uint64_t> contigs_size (nbContigs, 0);
for(uint64_t i=0; i < nbContigs; i++){
contigs_size[i] = contigs.get_sizeContig(i);
ultraSequenceSize += contigs_size[i];
}
//Create the ultraSequence
char* ultraSequence = new char[ultraSequenceSize];
uint64_t i = 0;
//Get each contigs sequence and add it in ultraSequence
for(uint64_t c=0; c < nbContigs; c++){
string seq = contigs.get_seqContig(c);
for(size_t j=0; j < seq.size();j++){
ultraSequence[i] = seq[j];
i++;
}
}
cout << "UltraSequence:" << endl;
cout << ultraSequence << endl;
//Prepare GPU for the run
cl::Event ev;
//infos buffer (64bits): nbcontigs
//buffer only accepts non-dynamics arrays (even of size 1)
uint64_t infos[1] = {ultraSequenceSize};
cl::Buffer buf_infos (m_context, CL_MEM_READ_ONLY, sizeof(uint64_t));
m_commandqueue.enqueueWriteBuffer(buf_infos, CL_TRUE, 0, sizeof(uint64_t), &infos);
//sequences sizes (array of 64bits) buffer
cl::Buffer buf_sizes (m_context, CL_ME_READ_ONLY, sizeof(uint64_t)*nbContigs);
m_commandqueue.enqueueWriteBuffer(buf_sizes, CL_TRUE, 0, sizeof(uint64_t)*nbContigs, &contigs_size[0]);
//Update the kernel (gpu function)
m_kernel.setArg(0, buf_infos);
//Run the kernel and wait the end
m_commandqueue.enqueueNDRangeKernel(m_kernel,cl::NullRange, cl::NDRange::NDRange(nbContigs, nbContigs), cl::NullRange, NULL, &ev);
ev.wait();
//Clean the memory
delete ultraSequence;
}
void WorkerCL::list_infos(Log& output){
string txt;
//Get platforms
txt = "\n\t[Platforms list]";
output.write(txt);
vector<cl::Platform> platforms;
cl::Platform::get(&platforms);
if(!platforms.size()){
txt = "No platform detected";
output.write(txt);
return;
}
txt = "platform_id\tplatform_name\tplatform_profile\tplatform_vendor\tplatform_version";
output.write(txt);
for(size_t i=0; i < platforms.size(); i++){
cl::Platform& p = platforms[i];
txt += "\t" + p.getInfo<CL_PLATFORM_NAME>();
txt += "\t" + p.getInfo<CL_PLATFORM_PROFILE>();
txt += "\t" + p.getInfo<CL_PLATFORM_VENDOR>();
txt += "\t" + p.getInfo<CL_PLATFORM_VERSION>();
//txt += "\t" + p.getInfo<CL_PLATFORM_EXTENSIONS>();
output.write(txt);
}
//Get devices
txt = "\n\t[Devices list]";
output.write(txt);
txt = "platform_id\tdevice_id\tdevice_name\tdevice_vendor\tdevice_profile\tdevice_version\tdriver_version\topencl_c_version";
output.write(txt);
for(size_t p = 0; p < platforms.size(); p++){
vector<cl::Device> devices;
platforms[p].getDevices(CL_DEVICE_TYPE_ALL, &devices);
for(size_t d = 0; d < devices.size(); d++){
cl::Device& device = devices[d];
txt = to_string(p)+"\t"+to_string(d);
txt += "\t" + device.getInfo<CL_DEVICE_NAME>();
txt += "\t" + device.getInfo<CL_DEVICE_VENDOR>();
txt += "\t" + device.getInfo<CL_DEVICE_PROFILE>();
txt += "\t" + device.getInfo<CL_DEVICE_VERSION>();
txt += "\t" + device.getInfo<CL_DRIVER_VERSION>();
txt += "\t" + device.getInfo<CL_DEVICE_OPENCL_C_VERSION>();
output.write(txt);
}
}
}
/*
Les balises 'R"CLCODE(' et ')CLCODE' (du type R"NAME( ... )NAME") servent à définir un
string litéral brut. C'est utile pour avoir un string sur plusieurs ligne, comme un code,
et cela évite d'avoir à ouvrir puis fermer les guillemets à chaque ligne.
*/
string WorkerCL::kernel_cmp_2_contigs = R"CLCODE(
kernel void cmp_2_contigs(){
int i = 0;
}
)CLCODE";
<commit_msg>Correct some typos<commit_after>#include "workerCL.hpp"
#define __CL_DEFINE_EXCEPTIONS
#include <CL/cl.hpp>
#include <vector>
#include <string>
#include <iostream>
#include "log.hpp"
#include "reads.hpp"
using namespace std;
WorkerCL::WorkerCL(size_t platform_id, size_t device_id){
/* GPU environment preparation */
//Get platforms (drivers) list and keep the one to be use
vector<cl::Platform> all_platforms;
cl::Platform::get(&all_platforms);
if(!all_platforms.size()){
//No platform ? Send error
string error = "OPENCL: no platforms found.";
throw(error);
}
m_platform = all_platforms[platform_id];
//Get devices list and keep the one to use
vector<cl::Device> devices;
m_platform.getDevices(CL_DEVICE_TYPE_ALL, &devices);
if(device_id >= devices.size()){
string error = "OPENCL: no device of id "+to_string(device_id)+
" on platform "+to_string(platform_id)+" ("+to_string(devices.size())+" devices)";
throw(error);
}
m_device = devices[device_id];
//Create context
m_context = cl::Context({m_device});
//initialize commands queue
m_commandqueue = cl::CommandQueue(m_context, m_device);
//Build kernel sources
m_program = cl::Program(m_context, kernel_cmp_2_contigs);
if(m_program.build({m_device}) != CL_SUCCESS){
string error = "Error building: ";
error += m_program.getBuildInfo<CL_PROGRAM_BUILD_LOG>(m_device);
throw(error);
}
//Make the kernel
m_kernel = cl::Kernel(m_program, "cmp_2_contigs");
}
WorkerCL::~WorkerCL(){
}
void WorkerCL::run(Contigs contigs){
/*
Create the string containing all contigs sequences
and store the list of contigs size (in same orders)
to be able to retrieve contigs. Size is store in
an uint64_t (ulong) to be sure it is 64bits as cl_ulong
*/
//Get list of contigs size and the total length of the
//contigs concatenation
uint64_t nbContigs = contigs.get_nbContigs();
uint64_t ultraSequenceSize = 0;
vector<uint64_t> contigs_size (nbContigs, 0);
for(uint64_t i=0; i < nbContigs; i++){
contigs_size[i] = contigs.get_sizeContig(i);
ultraSequenceSize += contigs_size[i];
}
//Create the ultraSequence
char* ultraSequence = new char[ultraSequenceSize];
uint64_t i = 0;
//Get each contigs sequence and add it in ultraSequence
for(uint64_t c=0; c < nbContigs; c++){
string seq = contigs.get_seqContig(c);
for(size_t j=0; j < seq.size();j++){
ultraSequence[i] = seq[j];
i++;
}
}
cout << "UltraSequence:" << endl;
cout << ultraSequence << endl;
//Prepare GPU for the run
cl::Event ev;
//infos buffer (64bits): nbcontigs
//buffer only accepts non-dynamics arrays (even of size 1)
uint64_t infos[1] = {ultraSequenceSize};
cl::Buffer buf_infos (m_context, CL_MEM_READ_ONLY, sizeof(uint64_t));
m_commandqueue.enqueueWriteBuffer(buf_infos, CL_TRUE, 0, sizeof(uint64_t), &infos);
//sequences sizes (array of 64bits) buffer
cl::Buffer buf_sizes (m_context, CL_MEM_READ_ONLY, sizeof(uint64_t)*nbContigs);
m_commandqueue.enqueueWriteBuffer(buf_sizes, CL_TRUE, 0, sizeof(uint64_t)*nbContigs, &contigs_size[0]);
//Update the kernel (gpu function)
m_kernel.setArg(0, buf_infos);
//Run the kernel and wait the end
m_commandqueue.enqueueNDRangeKernel(m_kernel,cl::NullRange, cl::NDRange(nbContigs, nbContigs), cl::NullRange, NULL, &ev);
ev.wait();
//Clean the memory
delete ultraSequence;
}
void WorkerCL::list_infos(Log& output){
string txt;
//Get platforms
txt = "\n\t[Platforms list]";
output.write(txt);
vector<cl::Platform> platforms;
cl::Platform::get(&platforms);
if(!platforms.size()){
txt = "No platform detected";
output.write(txt);
return;
}
txt = "platform_id\tplatform_name\tplatform_profile\tplatform_vendor\tplatform_version";
output.write(txt);
for(size_t i=0; i < platforms.size(); i++){
cl::Platform& p = platforms[i];
txt += "\t" + p.getInfo<CL_PLATFORM_NAME>();
txt += "\t" + p.getInfo<CL_PLATFORM_PROFILE>();
txt += "\t" + p.getInfo<CL_PLATFORM_VENDOR>();
txt += "\t" + p.getInfo<CL_PLATFORM_VERSION>();
//txt += "\t" + p.getInfo<CL_PLATFORM_EXTENSIONS>();
output.write(txt);
}
//Get devices
txt = "\n\t[Devices list]";
output.write(txt);
txt = "platform_id\tdevice_id\tdevice_name\tdevice_vendor\tdevice_profile\tdevice_version\tdriver_version\topencl_c_version";
output.write(txt);
for(size_t p = 0; p < platforms.size(); p++){
vector<cl::Device> devices;
platforms[p].getDevices(CL_DEVICE_TYPE_ALL, &devices);
for(size_t d = 0; d < devices.size(); d++){
cl::Device& device = devices[d];
txt = to_string(p)+"\t"+to_string(d);
txt += "\t" + device.getInfo<CL_DEVICE_NAME>();
txt += "\t" + device.getInfo<CL_DEVICE_VENDOR>();
txt += "\t" + device.getInfo<CL_DEVICE_PROFILE>();
txt += "\t" + device.getInfo<CL_DEVICE_VERSION>();
txt += "\t" + device.getInfo<CL_DRIVER_VERSION>();
txt += "\t" + device.getInfo<CL_DEVICE_OPENCL_C_VERSION>();
output.write(txt);
}
}
}
/*
Les balises 'R"CLCODE(' et ')CLCODE' (du type R"NAME( ... )NAME") servent à définir un
string litéral brut. C'est utile pour avoir un string sur plusieurs ligne, comme un code,
et cela évite d'avoir à ouvrir puis fermer les guillemets à chaque ligne.
*/
string WorkerCL::kernel_cmp_2_contigs = R"CLCODE(
kernel void cmp_2_contigs(){
int i = 0;
}
)CLCODE";
<|endoftext|>
|
<commit_before>#include "itkImage.h"
#include "itkImageFileReader.h"
#include "itkImageFileWriter.h"
#include "itkImageRegionIterator.h"
#include "itkRGBPixel.h"
#include "itkRGBAPixel.h"
#include "itkRedColormapFunctor.h"
#include "itkGreenColormapFunctor.h"
#include "itkBlueColormapFunctor.h"
#include "itkGreyColormapFunctor.h"
#include "itkHotColormapFunctor.h"
#include "itkCoolColormapFunctor.h"
#include "itkSpringColormapFunctor.h"
#include "itkSummerColormapFunctor.h"
#include "itkAutumnColormapFunctor.h"
#include "itkWinterColormapFunctor.h"
#include "itkCopperColormapFunctor.h"
#include "itkHSVColormapFunctor.h"
#include "itkJetColormapFunctor.h"
#include "itkCustomColormapFunctor.h"
#include "itkOverUnderColormapFunctor.h"
#include "itkScalarToRGBColormapImageFilter.h"
template <unsigned int ImageDimension>
int ConvertScalarImageToRGB( int argc, char *argv[] )
{
typedef unsigned int PixelType;
// typedef itk::RGBPixel<unsigned char> RGBPixelType;
typedef itk::RGBAPixel<unsigned char> RGBPixelType;
typedef float RealType;
typedef itk::Image<PixelType, ImageDimension> ImageType;
typedef itk::Image<float, ImageDimension> RealImageType;
typedef itk::Image<RGBPixelType, ImageDimension> RGBImageType;
typedef itk::ImageFileReader<RealImageType> ReaderType;
typename ReaderType::Pointer reader = ReaderType::New();
reader->SetFileName( argv[2] );
reader->Update();
typedef itk::Image<unsigned char, ImageDimension> MaskImageType;
typename MaskImageType::Pointer maskImage = MaskImageType::New();
typedef itk::ImageFileReader<MaskImageType> MaskReaderType;
typename MaskReaderType::Pointer maskreader = MaskReaderType::New();
maskreader->SetFileName( argv[4] );
try
{
maskreader->Update();
maskImage = maskreader->GetOutput();
}
catch(...)
{
maskImage = NULL;
};
std::string colormapString( argv[5] );
typedef itk::ScalarToRGBColormapImageFilter<RealImageType,
RGBImageType> RGBFilterType;
typename RGBFilterType::Pointer rgbfilter = RGBFilterType::New();
rgbfilter->SetInput( reader->GetOutput() );
if ( colormapString == "red" )
{
rgbfilter->SetColormap( RGBFilterType::Red );
}
else if ( colormapString == "green" )
{
rgbfilter->SetColormap( RGBFilterType::Green );
}
else if ( colormapString == "blue" )
{
rgbfilter->SetColormap( RGBFilterType::Blue );
}
else if ( colormapString == "grey" )
{
rgbfilter->SetColormap( RGBFilterType::Grey );
}
else if ( colormapString == "cool" )
{
rgbfilter->SetColormap( RGBFilterType::Cool );
}
else if ( colormapString == "hot" )
{
rgbfilter->SetColormap( RGBFilterType::Hot );
}
else if ( colormapString == "spring" )
{
rgbfilter->SetColormap( RGBFilterType::Spring );
}
else if ( colormapString == "autumn" )
{
rgbfilter->SetColormap( RGBFilterType::Autumn );
}
else if ( colormapString == "winter" )
{
rgbfilter->SetColormap( RGBFilterType::Winter );
}
else if ( colormapString == "copper" )
{
rgbfilter->SetColormap( RGBFilterType::Copper );
}
else if ( colormapString == "summer" )
{
rgbfilter->SetColormap( RGBFilterType::Summer );
}
else if ( colormapString == "jet" )
{
// rgbfilter->SetColormap( RGBFilterType::Jet );
typedef itk::Functor::JetColormapFunctor<typename RealImageType::PixelType,
typename RGBImageType::PixelType> ColormapType;
typename ColormapType::Pointer colormap = ColormapType::New();
rgbfilter->SetColormap( colormap );
}
else if ( colormapString == "hsv" )
{
// rgbfilter->SetColormap( RGBFilterType::HSV );
typedef itk::Functor::HSVColormapFunctor<typename RealImageType::PixelType,
typename RGBImageType::PixelType> ColormapType;
typename ColormapType::Pointer colormap = ColormapType::New();
rgbfilter->SetColormap( colormap );
}
else if ( colormapString == "overunder" )
{
rgbfilter->SetColormap( RGBFilterType::OverUnder );
}
else if ( colormapString == "custom" )
{
typedef itk::Functor::CustomColormapFunctor<typename RealImageType::PixelType,
typename RGBImageType::PixelType> ColormapType;
typename ColormapType::Pointer colormap = ColormapType::New();
ifstream str( argv[6] );
std::string line;
// Get red values
{
std::getline( str, line );
std::istringstream iss( line );
float value;
typename ColormapType::ChannelType channel;
while ( iss >> value )
{
channel.push_back( value );
}
colormap->SetRedChannel( channel );
}
// Get green values
{
std::getline( str, line );
std::istringstream iss( line );
float value;
typename ColormapType::ChannelType channel;
while ( iss >> value )
{
channel.push_back( value );
}
colormap->SetGreenChannel( channel );
}
// Get blue values
{
std::getline( str, line );
std::istringstream iss( line );
float value;
typename ColormapType::ChannelType channel;
while ( iss >> value )
{
channel.push_back( value );
}
colormap->SetBlueChannel( channel );
}
rgbfilter->SetColormap( colormap );
}
if( maskImage )
{
RealType maskMinimumValue = itk::NumericTraits<RealType>::max();
RealType maskMaximumValue = itk::NumericTraits<RealType>::NonpositiveMin();
itk::ImageRegionIterator<MaskImageType> ItM( maskImage,
maskImage->GetLargestPossibleRegion() );
itk::ImageRegionIterator<RealImageType> ItS( reader->GetOutput(),
reader->GetOutput()->GetLargestPossibleRegion() );
for( ItM.GoToBegin(), ItS.GoToBegin(); !ItM.IsAtEnd(); ++ItM, ++ItS )
{
if( ItM.Get() != 0 )
{
if( maskMinimumValue >= ItS.Get() )
{
maskMinimumValue = ItS.Get();
}
if( maskMaximumValue <= ItS.Get() )
{
maskMaximumValue = ItS.Get();
}
}
}
rgbfilter->SetUseInputImageExtremaForScaling( false );
rgbfilter->GetColormap()->SetMinimumInputValue( maskMinimumValue );
rgbfilter->GetColormap()->SetMaximumInputValue( maskMaximumValue );
}
rgbfilter->GetColormap()->SetMinimumRGBComponentValue(
( argc > 9 ) ? static_cast<
typename RGBPixelType::ComponentType>( atof( argv[9] ) ) : 0 );
rgbfilter->GetColormap()->SetMaximumRGBComponentValue(
( argc > 10 ) ? static_cast<
typename RGBPixelType::ComponentType>( atof( argv[10] ) ) : 255 );
if( argc > 8 )
{
rgbfilter->SetUseInputImageExtremaForScaling( false );
rgbfilter->GetColormap()->SetMinimumInputValue(
static_cast<RealType>( atof( argv[7] ) ) );
rgbfilter->GetColormap()->SetMaximumInputValue(
static_cast<RealType>( atof( argv[8] ) ) );
}
try
{
rgbfilter->Update();
}
catch (...)
{
return EXIT_FAILURE;
}
if( maskImage )
{
itk::ImageRegionIterator<MaskImageType> ItM( maskImage,
maskImage->GetLargestPossibleRegion() );
itk::ImageRegionIterator<RGBImageType> ItC( rgbfilter->GetOutput(),
rgbfilter->GetOutput()->GetLargestPossibleRegion() );
itk::ImageRegionIterator<RealImageType> ItS( reader->GetOutput(),
reader->GetOutput()->GetLargestPossibleRegion() );
ItM.GoToBegin();
ItC.GoToBegin();
ItS.GoToBegin();
while( !ItM.IsAtEnd() )
{
if( ItM.Get() == 0 )
{
RGBPixelType rgbpixel;
// RealType minimumValue = rgbfilter->GetColormap()->GetMinimumInputValue();
// RealType maximumValue = rgbfilter->GetColormap()->GetMaximumInputValue();
//
// RealType minimumRGBValue
// = rgbfilter->GetColormap()->GetMinimumRGBComponentValue();
// RealType maximumRGBValue
// = rgbfilter->GetColormap()->GetMaximumRGBComponentValue();
//
// RealType ratio = ( ItS.Get() - minimumValue ) / ( maximumValue - minimumValue );
//
// rgbpixel.Fill( ratio * ( maximumRGBValue - minimumRGBValue )
// + minimumRGBValue );
rgbpixel.Fill( 0.0 );
ItC.Set( rgbpixel );
}
++ItM;
++ItC;
++ItS;
}
}
typedef itk::ImageFileWriter<RGBImageType> WriterType;
typename WriterType::Pointer writer = WriterType::New();
writer->SetInput( rgbfilter->GetOutput() );
writer->SetFileName( argv[3] );
writer->Update();
return 0;
}
int main( int argc, char *argv[] )
{
if ( argc < 6 )
{
std::cout << "Usage: " << argv[0] << " imageDimension inputImage outputImage "
<< "mask colormap [customColormapFile] [minimumInput] [maximumInput] "
<< "[minimumRGBOutput] [maximumRGBOutput]" << std::endl;
std::cout << " Possible colormaps: grey, red, green, blue, copper, jet, hsv, ";
std::cout << "spring, summer, autumn, winter, hot, cool, overunder, custom" << std::endl;
exit( 1 );
}
switch( atoi( argv[1] ) )
{
case 2:
ConvertScalarImageToRGB<2>( argc, argv );
break;
case 3:
ConvertScalarImageToRGB<3>( argc, argv );
break;
default:
std::cerr << "Unsupported dimension" << std::endl;
exit( EXIT_FAILURE );
}
}
<commit_msg> include issues <commit_after>
#include <string>
#include <fstream>
#include <iostream>
#include "itkImage.h"
#include "itkImageFileReader.h"
#include "itkImageFileWriter.h"
#include "itkImageRegionIterator.h"
#include "itkRGBPixel.h"
#include "itkRGBAPixel.h"
#include "itkRedColormapFunctor.h"
#include "itkGreenColormapFunctor.h"
#include "itkBlueColormapFunctor.h"
#include "itkGreyColormapFunctor.h"
#include "itkHotColormapFunctor.h"
#include "itkCoolColormapFunctor.h"
#include "itkSpringColormapFunctor.h"
#include "itkSummerColormapFunctor.h"
#include "itkAutumnColormapFunctor.h"
#include "itkWinterColormapFunctor.h"
#include "itkCopperColormapFunctor.h"
#include "itkHSVColormapFunctor.h"
#include "itkJetColormapFunctor.h"
#include "itkCustomColormapFunctor.h"
#include "itkOverUnderColormapFunctor.h"
#include "itkScalarToRGBColormapImageFilter.h"
template <unsigned int ImageDimension>
int ConvertScalarImageToRGB( int argc, char *argv[] )
{
typedef unsigned int PixelType;
// typedef itk::RGBPixel<unsigned char> RGBPixelType;
typedef itk::RGBAPixel<unsigned char> RGBPixelType;
typedef float RealType;
typedef itk::Image<PixelType, ImageDimension> ImageType;
typedef itk::Image<float, ImageDimension> RealImageType;
typedef itk::Image<RGBPixelType, ImageDimension> RGBImageType;
typedef itk::ImageFileReader<RealImageType> ReaderType;
typename ReaderType::Pointer reader = ReaderType::New();
reader->SetFileName( argv[2] );
reader->Update();
typedef itk::Image<unsigned char, ImageDimension> MaskImageType;
typename MaskImageType::Pointer maskImage = MaskImageType::New();
typedef itk::ImageFileReader<MaskImageType> MaskReaderType;
typename MaskReaderType::Pointer maskreader = MaskReaderType::New();
maskreader->SetFileName( argv[4] );
try
{
maskreader->Update();
maskImage = maskreader->GetOutput();
}
catch(...)
{
maskImage = NULL;
};
std::string colormapString( argv[5] );
typedef itk::ScalarToRGBColormapImageFilter<RealImageType,
RGBImageType> RGBFilterType;
typename RGBFilterType::Pointer rgbfilter = RGBFilterType::New();
rgbfilter->SetInput( reader->GetOutput() );
if ( colormapString == "red" )
{
rgbfilter->SetColormap( RGBFilterType::Red );
}
else if ( colormapString == "green" )
{
rgbfilter->SetColormap( RGBFilterType::Green );
}
else if ( colormapString == "blue" )
{
rgbfilter->SetColormap( RGBFilterType::Blue );
}
else if ( colormapString == "grey" )
{
rgbfilter->SetColormap( RGBFilterType::Grey );
}
else if ( colormapString == "cool" )
{
rgbfilter->SetColormap( RGBFilterType::Cool );
}
else if ( colormapString == "hot" )
{
rgbfilter->SetColormap( RGBFilterType::Hot );
}
else if ( colormapString == "spring" )
{
rgbfilter->SetColormap( RGBFilterType::Spring );
}
else if ( colormapString == "autumn" )
{
rgbfilter->SetColormap( RGBFilterType::Autumn );
}
else if ( colormapString == "winter" )
{
rgbfilter->SetColormap( RGBFilterType::Winter );
}
else if ( colormapString == "copper" )
{
rgbfilter->SetColormap( RGBFilterType::Copper );
}
else if ( colormapString == "summer" )
{
rgbfilter->SetColormap( RGBFilterType::Summer );
}
else if ( colormapString == "jet" )
{
// rgbfilter->SetColormap( RGBFilterType::Jet );
typedef itk::Functor::JetColormapFunctor<typename RealImageType::PixelType,
typename RGBImageType::PixelType> ColormapType;
typename ColormapType::Pointer colormap = ColormapType::New();
rgbfilter->SetColormap( colormap );
}
else if ( colormapString == "hsv" )
{
// rgbfilter->SetColormap( RGBFilterType::HSV );
typedef itk::Functor::HSVColormapFunctor<typename RealImageType::PixelType,
typename RGBImageType::PixelType> ColormapType;
typename ColormapType::Pointer colormap = ColormapType::New();
rgbfilter->SetColormap( colormap );
}
else if ( colormapString == "overunder" )
{
rgbfilter->SetColormap( RGBFilterType::OverUnder );
}
else if ( colormapString == "custom" )
{
typedef itk::Functor::CustomColormapFunctor<typename RealImageType::PixelType,
typename RGBImageType::PixelType> ColormapType;
typename ColormapType::Pointer colormap = ColormapType::New();
std::ifstream str( argv[6] );
std::string line;
// Get red values
{
std::getline( str, line );
std::istringstream iss( line );
float value;
typename ColormapType::ChannelType channel;
while ( iss >> value )
{
channel.push_back( value );
}
colormap->SetRedChannel( channel );
}
// Get green values
{
std::getline( str, line );
std::istringstream iss( line );
float value;
typename ColormapType::ChannelType channel;
while ( iss >> value )
{
channel.push_back( value );
}
colormap->SetGreenChannel( channel );
}
// Get blue values
{
std::getline( str, line );
std::istringstream iss( line );
float value;
typename ColormapType::ChannelType channel;
while ( iss >> value )
{
channel.push_back( value );
}
colormap->SetBlueChannel( channel );
}
rgbfilter->SetColormap( colormap );
}
if( maskImage )
{
RealType maskMinimumValue = itk::NumericTraits<RealType>::max();
RealType maskMaximumValue = itk::NumericTraits<RealType>::NonpositiveMin();
itk::ImageRegionIterator<MaskImageType> ItM( maskImage,
maskImage->GetLargestPossibleRegion() );
itk::ImageRegionIterator<RealImageType> ItS( reader->GetOutput(),
reader->GetOutput()->GetLargestPossibleRegion() );
for( ItM.GoToBegin(), ItS.GoToBegin(); !ItM.IsAtEnd(); ++ItM, ++ItS )
{
if( ItM.Get() != 0 )
{
if( maskMinimumValue >= ItS.Get() )
{
maskMinimumValue = ItS.Get();
}
if( maskMaximumValue <= ItS.Get() )
{
maskMaximumValue = ItS.Get();
}
}
}
rgbfilter->SetUseInputImageExtremaForScaling( false );
rgbfilter->GetColormap()->SetMinimumInputValue( maskMinimumValue );
rgbfilter->GetColormap()->SetMaximumInputValue( maskMaximumValue );
}
rgbfilter->GetColormap()->SetMinimumRGBComponentValue(
( argc > 9 ) ? static_cast<
typename RGBPixelType::ComponentType>( atof( argv[9] ) ) : 0 );
rgbfilter->GetColormap()->SetMaximumRGBComponentValue(
( argc > 10 ) ? static_cast<
typename RGBPixelType::ComponentType>( atof( argv[10] ) ) : 255 );
if( argc > 8 )
{
rgbfilter->SetUseInputImageExtremaForScaling( false );
rgbfilter->GetColormap()->SetMinimumInputValue(
static_cast<RealType>( atof( argv[7] ) ) );
rgbfilter->GetColormap()->SetMaximumInputValue(
static_cast<RealType>( atof( argv[8] ) ) );
}
try
{
rgbfilter->Update();
}
catch (...)
{
return EXIT_FAILURE;
}
if( maskImage )
{
itk::ImageRegionIterator<MaskImageType> ItM( maskImage,
maskImage->GetLargestPossibleRegion() );
itk::ImageRegionIterator<RGBImageType> ItC( rgbfilter->GetOutput(),
rgbfilter->GetOutput()->GetLargestPossibleRegion() );
itk::ImageRegionIterator<RealImageType> ItS( reader->GetOutput(),
reader->GetOutput()->GetLargestPossibleRegion() );
ItM.GoToBegin();
ItC.GoToBegin();
ItS.GoToBegin();
while( !ItM.IsAtEnd() )
{
if( ItM.Get() == 0 )
{
RGBPixelType rgbpixel;
// RealType minimumValue = rgbfilter->GetColormap()->GetMinimumInputValue();
// RealType maximumValue = rgbfilter->GetColormap()->GetMaximumInputValue();
//
// RealType minimumRGBValue
// = rgbfilter->GetColormap()->GetMinimumRGBComponentValue();
// RealType maximumRGBValue
// = rgbfilter->GetColormap()->GetMaximumRGBComponentValue();
//
// RealType ratio = ( ItS.Get() - minimumValue ) / ( maximumValue - minimumValue );
//
// rgbpixel.Fill( ratio * ( maximumRGBValue - minimumRGBValue )
// + minimumRGBValue );
rgbpixel.Fill( 0.0 );
ItC.Set( rgbpixel );
}
++ItM;
++ItC;
++ItS;
}
}
typedef itk::ImageFileWriter<RGBImageType> WriterType;
typename WriterType::Pointer writer = WriterType::New();
writer->SetInput( rgbfilter->GetOutput() );
writer->SetFileName( argv[3] );
writer->Update();
return 0;
}
int main( int argc, char *argv[] )
{
if ( argc < 6 )
{
std::cout << "Usage: " << argv[0] << " imageDimension inputImage outputImage "
<< "mask colormap [customColormapFile] [minimumInput] [maximumInput] "
<< "[minimumRGBOutput] [maximumRGBOutput]" << std::endl;
std::cout << " Possible colormaps: grey, red, green, blue, copper, jet, hsv, ";
std::cout << "spring, summer, autumn, winter, hot, cool, overunder, custom" << std::endl;
exit( 1 );
}
switch( atoi( argv[1] ) )
{
case 2:
ConvertScalarImageToRGB<2>( argc, argv );
break;
case 3:
ConvertScalarImageToRGB<3>( argc, argv );
break;
default:
std::cerr << "Unsupported dimension" << std::endl;
exit( EXIT_FAILURE );
}
}
<|endoftext|>
|
<commit_before>/* Copyright 2009 Thomas McGuire <[email protected]>
This library is free software; you can redistribute it and/or modify
it under the terms of the GNU Library General Public License as published
by the Free Software Foundation; either version 2 of the License or
( at your option ) version 3 or, at the discretion of KDE e.V.
( which shall act as a proxy as in section 14 of the GPLv3 ), 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
Library General Public License for more details.
You should have received a copy of the GNU Library General Public License
along with this library; see the file COPYING.LIB. If not, write to
the Free Software Foundation, Inc., 51 Franklin Street, Fifth Floor,
Boston, MA 02110-1301, USA.
*/
#include "htmlquotecolorer.h"
#include "csshelper.h"
#include <dom/html_document.h>
#include <dom/dom_element.h>
namespace KMail {
HTMLQuoteColorer::HTMLQuoteColorer( KPIM::CSSHelper *cssHelper )
: mCSSHelper( cssHelper )
{
}
QString HTMLQuoteColorer::process( const QString &htmlSource )
{
// Create a DOM Document from the HTML source
DOM::HTMLDocument doc;
doc.open();
doc.write( htmlSource );
doc.close();
mIsQuotedLine = false;
mIsFirstTextNodeInLine = true;
processNode( doc.documentElement() );
return doc.toString().string();
}
DOM::Node HTMLQuoteColorer::processNode( DOM::Node node )
{
// Below, we determine if the current text node should be quote colored by keeping track of
// linebreaks and wether this text node is the first one.
const QString textContent = node.textContent().string();
const bool isTextNode = !textContent.isEmpty() && !node.hasChildNodes();
if ( isTextNode ) {
if ( mIsFirstTextNodeInLine ) {
if ( textContent.simplified().startsWith( '>' ) ||
textContent.simplified().startsWith( '|' ) ) {
mIsQuotedLine = true;
currentQuoteLength = quoteLength( textContent ) - 1;
}
else {
mIsQuotedLine = false;
}
}
// All subsequent text nodes are not the first ones anymore
mIsFirstTextNodeInLine = false;
}
const QString nodeName = node.nodeName().string().toLower();
if ( nodeName == "br" || nodeName == "p" ) { // FIXME: Are there more newline nodes?
mIsFirstTextNodeInLine = true;
}
DOM::Node returnNode = node;
bool fontTagAdded = false;
if ( mIsQuotedLine && isTextNode ) {
// Ok, we are in a line that should be quoted, so create a font node for the color and replace
// the current node with it.
DOM::Element font = node.ownerDocument().createElement( QString( "font" ) );
font.setAttribute( QString( "color" ), mCSSHelper->quoteColor( currentQuoteLength ).name() );
node.parentNode().replaceChild( font, node );
font.appendChild( node );
returnNode = font;
fontTagAdded = true;
}
// Process all child nodes, but only if we are didn't add those child nodes itself, as otherwise
// we'll go into an infinite recursion.
if ( !fontTagAdded ) {
DOM::Node childNode = node.firstChild();
while ( !childNode.isNull() ) {
childNode = processNode( childNode );
childNode = childNode.nextSibling();
}
}
return returnNode;
}
int HTMLQuoteColorer::quoteLength( const QString &line ) const
{
QString simplified = line.simplified();
simplified = simplified.replace( QRegExp( QLatin1String( "\\s" ) ), QString() )
.replace( QLatin1Char( '|' ), QLatin1Char( '>' ) );
if ( simplified.startsWith( ">>>" ) ) return 3;
if ( simplified.startsWith( ">>" ) ) return 2;
if ( simplified.startsWith( ">" ) ) return 1;
return 0;
}
}
<commit_msg>Add more linebreak nodes.<commit_after>/* Copyright 2009 Thomas McGuire <[email protected]>
This library is free software; you can redistribute it and/or modify
it under the terms of the GNU Library General Public License as published
by the Free Software Foundation; either version 2 of the License or
( at your option ) version 3 or, at the discretion of KDE e.V.
( which shall act as a proxy as in section 14 of the GPLv3 ), 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
Library General Public License for more details.
You should have received a copy of the GNU Library General Public License
along with this library; see the file COPYING.LIB. If not, write to
the Free Software Foundation, Inc., 51 Franklin Street, Fifth Floor,
Boston, MA 02110-1301, USA.
*/
#include "htmlquotecolorer.h"
#include "csshelper.h"
#include <dom/html_document.h>
#include <dom/dom_element.h>
namespace KMail {
HTMLQuoteColorer::HTMLQuoteColorer( KPIM::CSSHelper *cssHelper )
: mCSSHelper( cssHelper )
{
}
QString HTMLQuoteColorer::process( const QString &htmlSource )
{
// Create a DOM Document from the HTML source
DOM::HTMLDocument doc;
doc.open();
doc.write( htmlSource );
doc.close();
mIsQuotedLine = false;
mIsFirstTextNodeInLine = true;
processNode( doc.documentElement() );
return doc.toString().string();
}
DOM::Node HTMLQuoteColorer::processNode( DOM::Node node )
{
// Below, we determine if the current text node should be quote colored by keeping track of
// linebreaks and wether this text node is the first one.
const QString textContent = node.textContent().string();
const bool isTextNode = !textContent.isEmpty() && !node.hasChildNodes();
if ( isTextNode ) {
if ( mIsFirstTextNodeInLine ) {
if ( textContent.simplified().startsWith( '>' ) ||
textContent.simplified().startsWith( '|' ) ) {
mIsQuotedLine = true;
currentQuoteLength = quoteLength( textContent ) - 1;
}
else {
mIsQuotedLine = false;
}
}
// All subsequent text nodes are not the first ones anymore
mIsFirstTextNodeInLine = false;
}
const QString nodeName = node.nodeName().string().toLower();
QStringList lineBreakNodes;
lineBreakNodes << "br" << "p" << "div" << "ul" << "ol" << "li";
if ( lineBreakNodes.contains( nodeName ) ) {
mIsFirstTextNodeInLine = true;
}
DOM::Node returnNode = node;
bool fontTagAdded = false;
if ( mIsQuotedLine && isTextNode ) {
// Ok, we are in a line that should be quoted, so create a font node for the color and replace
// the current node with it.
DOM::Element font = node.ownerDocument().createElement( QString( "font" ) );
font.setAttribute( QString( "color" ), mCSSHelper->quoteColor( currentQuoteLength ).name() );
node.parentNode().replaceChild( font, node );
font.appendChild( node );
returnNode = font;
fontTagAdded = true;
}
// Process all child nodes, but only if we are didn't add those child nodes itself, as otherwise
// we'll go into an infinite recursion.
if ( !fontTagAdded ) {
DOM::Node childNode = node.firstChild();
while ( !childNode.isNull() ) {
childNode = processNode( childNode );
childNode = childNode.nextSibling();
}
}
return returnNode;
}
int HTMLQuoteColorer::quoteLength( const QString &line ) const
{
QString simplified = line.simplified();
simplified = simplified.replace( QRegExp( QLatin1String( "\\s" ) ), QString() )
.replace( QLatin1Char( '|' ), QLatin1Char( '>' ) );
if ( simplified.startsWith( ">>>" ) ) return 3;
if ( simplified.startsWith( ">>" ) ) return 2;
if ( simplified.startsWith( ">" ) ) return 1;
return 0;
}
}
<|endoftext|>
|
<commit_before>/*************************************************************************
*
* OpenOffice.org - a multi-platform office productivity suite
*
* $RCSfile: b2dtuple.cxx,v $
*
* $Revision: 1.11 $
*
* last change: $Author: obo $ $Date: 2006-09-17 08:06:26 $
*
* 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_basegfx.hxx"
#ifndef _BGFX_TUPLE_B2DTUPLE_HXX
#include <basegfx/tuple/b2dtuple.hxx>
#endif
#ifndef _BGFX_NUMERIC_FTOOLS_HXX
#include <basegfx/numeric/ftools.hxx>
#endif
#ifndef INCLUDED_RTL_INSTANCE_HXX
#include <rtl/instance.hxx>
#endif
namespace { struct EmptyTuple : public rtl::Static<basegfx::B2DTuple, EmptyTuple> {}; }
#ifndef _BGFX_TUPLE_B2ITUPLE_HXX
#include <basegfx/tuple/b2ituple.hxx>
#endif
namespace basegfx
{
const B2DTuple& B2DTuple::getEmptyTuple()
{
return EmptyTuple::get();
}
B2DTuple::B2DTuple(const B2ITuple& rTup)
: mfX( rTup.getX() ),
mfY( rTup.getY() )
{}
bool B2DTuple::equalZero() const
{
return (this == &getEmptyTuple() ||
(::basegfx::fTools::equalZero(mfX) && ::basegfx::fTools::equalZero(mfY)));
}
bool B2DTuple::equalZero(const double& rfSmallValue) const
{
return (this == &getEmptyTuple() ||
(::basegfx::fTools::equalZero(mfX, rfSmallValue) && ::basegfx::fTools::equalZero(mfY, rfSmallValue)));
}
bool B2DTuple::equal(const B2DTuple& rTup) const
{
return (
::basegfx::fTools::equal(mfX, rTup.mfX) &&
::basegfx::fTools::equal(mfY, rTup.mfY));
}
bool B2DTuple::equal(const B2DTuple& rTup, const double& rfSmallValue) const
{
return (
::basegfx::fTools::equal(mfX, rTup.mfX, rfSmallValue) &&
::basegfx::fTools::equal(mfY, rTup.mfY, rfSmallValue));
}
void B2DTuple::correctValues(const double fCompareValue)
{
if(0.0 == fCompareValue)
{
if(::basegfx::fTools::equalZero(mfX))
{
mfX = 0.0;
}
if(::basegfx::fTools::equalZero(mfY))
{
mfY = 0.0;
}
}
else
{
if(::basegfx::fTools::equal(mfX, fCompareValue))
{
mfX = fCompareValue;
}
if(::basegfx::fTools::equal(mfY, fCompareValue))
{
mfY = fCompareValue;
}
}
}
B2ITuple fround(const B2DTuple& rTup)
{
return B2ITuple(fround(rTup.getX()), fround(rTup.getY()));
}
} // end of namespace basegfx
// eof
<commit_msg>INTEGRATION: CWS aw051 (1.11.34); FILE MERGED 2007/06/15 13:29:21 aw 1.11.34.1: #i77162# 3rd round of adaptions to B2DPolygon bezier handling<commit_after>/*************************************************************************
*
* OpenOffice.org - a multi-platform office productivity suite
*
* $RCSfile: b2dtuple.cxx,v $
*
* $Revision: 1.12 $
*
* last change: $Author: obo $ $Date: 2007-07-18 11:08:05 $
*
* 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_basegfx.hxx"
#ifndef _BGFX_TUPLE_B2DTUPLE_HXX
#include <basegfx/tuple/b2dtuple.hxx>
#endif
#ifndef _BGFX_NUMERIC_FTOOLS_HXX
#include <basegfx/numeric/ftools.hxx>
#endif
#ifndef INCLUDED_RTL_INSTANCE_HXX
#include <rtl/instance.hxx>
#endif
namespace { struct EmptyTuple : public rtl::Static<basegfx::B2DTuple, EmptyTuple> {}; }
#ifndef _BGFX_TUPLE_B2ITUPLE_HXX
#include <basegfx/tuple/b2ituple.hxx>
#endif
namespace basegfx
{
const B2DTuple& B2DTuple::getEmptyTuple()
{
return EmptyTuple::get();
}
B2DTuple::B2DTuple(const B2ITuple& rTup)
: mfX( rTup.getX() ),
mfY( rTup.getY() )
{}
bool B2DTuple::equalZero() const
{
return (this == &getEmptyTuple() ||
(::basegfx::fTools::equalZero(mfX) && ::basegfx::fTools::equalZero(mfY)));
}
bool B2DTuple::equalZero(const double& rfSmallValue) const
{
return (this == &getEmptyTuple() ||
(::basegfx::fTools::equalZero(mfX, rfSmallValue) && ::basegfx::fTools::equalZero(mfY, rfSmallValue)));
}
bool B2DTuple::equal(const B2DTuple& rTup) const
{
return (
::basegfx::fTools::equal(mfX, rTup.mfX) &&
::basegfx::fTools::equal(mfY, rTup.mfY));
}
void B2DTuple::correctValues(const double fCompareValue)
{
if(0.0 == fCompareValue)
{
if(::basegfx::fTools::equalZero(mfX))
{
mfX = 0.0;
}
if(::basegfx::fTools::equalZero(mfY))
{
mfY = 0.0;
}
}
else
{
if(::basegfx::fTools::equal(mfX, fCompareValue))
{
mfX = fCompareValue;
}
if(::basegfx::fTools::equal(mfY, fCompareValue))
{
mfY = fCompareValue;
}
}
}
B2ITuple fround(const B2DTuple& rTup)
{
return B2ITuple(fround(rTup.getX()), fround(rTup.getY()));
}
} // end of namespace basegfx
// eof
<|endoftext|>
|
<commit_before>/* KPilot
**
** Copyright (C) 1998-2001 by Dan Pilone
** Copyright (C) 2003-2004 Reinhold Kainhofer <[email protected]>
**
** This defines the "ActionQueue", which is the pile of actions
** that will occur during a HotSync.
*/
/*
** This program is free software; you can redistribute it and/or modify
** it under the terms of the GNU General Public License as published by
** the Free Software Foundation; either version 2 of the License, or
** (at your option) any later version.
**
** This program 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 General Public License for more details.
**
** You should have received a copy of the GNU General Public License
** along with this program in a file called COPYING; if not, write to
** the Free Software Foundation, Inc., 59 Temple Place, Suite 330, Boston,
** MA 02111-1307, USA.
*/
/*
** Bug reports and questions can be sent to [email protected]
*/
#include "options.h"
static const char *syncStack_id = "$Id$";
#include <unistd.h>
#include <qtimer.h>
#include <qfile.h>
#include <qdir.h>
#include <qtextcodec.h>
#include <kservice.h>
#include <kservicetype.h>
#include <kuserprofile.h>
#include <klibloader.h>
#include <ksavefile.h>
#include "pilotUser.h"
#include "hotSync.h"
#include "interactiveSync.h"
#include "fileInstaller.h"
#include "kpilotSettings.h"
#include "pilotAppCategory.h"
#include "syncStack.moc"
WelcomeAction::WelcomeAction(KPilotDeviceLink *p) :
SyncAction(p,"welcomeAction")
{
FUNCTIONSETUP;
(void) syncStack_id;
}
/* virtual */ bool WelcomeAction::exec()
{
FUNCTIONSETUP;
addSyncLogEntry(i18n("KPilot %1 HotSync starting...\n")
.arg(QString::fromLatin1(KPILOT_VERSION)));
emit logMessage( i18n("Using encoding %1 on the handheld.").arg(PilotAppCategory::codecName()) );
emit syncDone(this);
return true;
}
SorryAction::SorryAction(KPilotDeviceLink *p, const QString &s) :
SyncAction(p,"sorryAction"),
fMessage(s)
{
if (fMessage.isEmpty())
{
fMessage = i18n("KPilot is busy and cannot process the "
"HotSync right now.");
}
}
bool SorryAction::exec()
{
FUNCTIONSETUP;
addSyncLogEntry(fMessage);
return delayDone();
}
LocalBackupAction::LocalBackupAction(KPilotDeviceLink *p, const QString &d) :
SyncAction(p,"LocalBackupAction"),
fDir(d)
{
}
bool LocalBackupAction::exec()
{
FUNCTIONSETUP;
startTickle();
QString dirname = fDir +
PilotAppCategory::codec()->toUnicode(fHandle->getPilotUser()->getUserName()) +
CSL1("/");
QDir dir(dirname,QString::null,QDir::Unsorted,QDir::Files);
if (!dir.exists())
{
emit logMessage( i18n("Cannot create local backup.") );
return false;
}
logMessage( i18n("Creating local backup of databases in %1.").arg(dirname) );
addSyncLogEntry( i18n("Creating local backup ..") );
qApp->processEvents();
QStringList files = dir.entryList();
for (QStringList::Iterator i = files.begin() ;
i != files.end();
++i)
{
KSaveFile::backupFile(dirname + (*i));
}
stopTickle();
return delayDone();
}
ConduitProxy::ConduitProxy(KPilotDeviceLink *p,
const QString &name,
SyncAction::SyncMode m,
bool local) :
ConduitAction(p,name.latin1()),
fDesktopName(name),
fMode(m),
fLocal(local)
{
FUNCTIONSETUP;
}
/* static */ QStringList ConduitProxy::flagsForMode(SyncAction::SyncMode m)
{
FUNCTIONSETUP;
QStringList l;
switch(m)
{
case eBackup :
l.append(CSL1("--backup"));
break;
case eTest:
l.append(CSL1("--test"));
break;
case eFastSync: /* FALLTHRU */
case eHotSync:
/* Nothing to do for fast or hotsync */
break;
case eFullSync:
l.append(CSL1("--full"));
break;
case eCopyHHToPC:
l.append(CSL1("--copyHHToPC"));
break;
case eCopyPCToHH:
l.append(CSL1("--copyPCToHH"));
break;
case eRestore:
kdWarning() << k_funcinfo << ": Running conduits during restore." << endl;
l.append(CSL1("--test"));
break;
case eDefaultSync:
Q_ASSERT(eDefaultSync != m); // Bail
break;
}
return l;
}
/* virtual */ bool ConduitProxy::exec()
{
FUNCTIONSETUP;
// query that service
KSharedPtr < KService > o = KService::serviceByDesktopName(fDesktopName);
if (!o)
{
kdWarning() << k_funcinfo
<< ": Can't find desktop file for conduit "
<< fDesktopName
<< endl;
addSyncLogEntry(i18n("Could not find conduit %1.").arg(fDesktopName));
emit syncDone(this);
return true;
}
// load the lib
#ifdef DEBUG
DEBUGKPILOT << fname
<< ": Loading desktop "
<< fDesktopName
<< " with lib "
<< o->library()
<< endl;
#endif
fLibraryName = o->library();
KLibFactory *factory = KLibLoader::self()->factory(
QFile::encodeName(o->library()));
if (!factory)
{
kdWarning() << k_funcinfo
<< ": Can't load library "
<< o->library()
<< endl;
addSyncLogEntry(i18n("Could not load conduit %1.").arg(fDesktopName));
emit syncDone(this);
return true;
}
QStringList l = flagsForMode(fMode);
if (fLocal)
{
l.append(CSL1("--local"));
}
#ifdef DEBUG
DEBUGDAEMON << fname << ": Flags: " << fMode << endl;
#endif
QObject *object = factory->create(fHandle,name(),"SyncAction",l);
if (!object)
{
kdWarning() << k_funcinfo
<< ": Can't create SyncAction."
<< endl;
addSyncLogEntry(i18n("Could not create conduit %1.").arg(fDesktopName));
emit syncDone(this);
return true;
}
fConduit = dynamic_cast<ConduitAction *>(object);
if (!fConduit)
{
kdWarning() << k_funcinfo
<< ": Can't cast to ConduitAction."
<< endl;
addSyncLogEntry(i18n("Could not create conduit %1.").arg(fDesktopName));
emit syncDone(this);
return true;
}
addSyncLogEntry(i18n("[Conduit %1]").arg(fDesktopName));
// Handle the syncDone signal properly & unload the conduit.
QObject::connect(fConduit,SIGNAL(syncDone(SyncAction *)),
this,SLOT(execDone(SyncAction *)));
// Proxy all the log and error messages.
QObject::connect(fConduit,SIGNAL(logMessage(const QString &)),
this,SIGNAL(logMessage(const QString &)));
QObject::connect(fConduit,SIGNAL(logError(const QString &)),
this,SIGNAL(logError(const QString &)));
QObject::connect(fConduit,SIGNAL(logProgress(const QString &,int)),
this,SIGNAL(logProgress(const QString &,int)));
QTimer::singleShot(0,fConduit,SLOT(execConduit()));
return true;
}
void ConduitProxy::execDone(SyncAction *p)
{
FUNCTIONSETUP;
if (p!=fConduit)
{
kdError() << k_funcinfo
<< ": Unknown conduit @"
<< (long) p
<< " finished."
<< endl;
emit syncDone(this);
return;
}
delete p;
addSyncLogEntry(CSL1("\n"),false); // Put bits of the conduit logs on separate lines
emit syncDone(this);
}
ActionQueue::ActionQueue(KPilotDeviceLink *d) :
SyncAction(d,"ActionQueue"),
fTestMode(false),
fReady(false)
// The string lists have default constructors
{
FUNCTIONSETUP;
}
ActionQueue::~ActionQueue()
{
FUNCTIONSETUP;
}
void ActionQueue::queueInit(bool checkUser)
{
FUNCTIONSETUP;
addAction(new WelcomeAction(fHandle));
if (checkUser)
{
addAction(new CheckUser(fHandle));
}
}
void ActionQueue::queueConduits(const QStringList &l,SyncAction::SyncMode m, bool /*local*/)
{
FUNCTIONSETUP;
// Add conduits here ...
//
//
for (QStringList::ConstIterator it = l.begin();
it != l.end();
++it)
{
if ((*it).startsWith(CSL1("internal_")))
{
#ifdef DEBUG
DEBUGDAEMON << fname <<
": Ignoring conduit " << *it << endl;
#endif
continue;
}
#ifdef DEBUG
DEBUGDAEMON << fname
<< ": Creating proxy with mode=" << m << endl;
#endif
ConduitProxy *cp = new ConduitProxy(fHandle,*it,m);
addAction(cp);
}
}
void ActionQueue::queueInstaller(const QString &dir)
{
addAction(new FileInstallAction(fHandle,dir));
}
void ActionQueue::queueCleanup()
{
addAction(new CleanupAction(fHandle));
}
bool ActionQueue::exec()
{
actionCompleted(0L);
return true;
}
void ActionQueue::actionCompleted(SyncAction *b)
{
FUNCTIONSETUP;
if (b)
{
#ifdef DEBUG
DEBUGDAEMON << fname
<< ": Completed action "
<< b->name()
<< endl;
#endif
delete b;
}
if (isEmpty())
{
delayDone();
return;
}
if (!fTestMode && !fHandle->tickle())
{
emit logError(i18n("The connection to the handheld "
"was lost. Synchronization cannot continue."));
SyncAction *del = 0L;
while ( (del = nextAction()) )
{
delete del;
}
delayDone();
return;
}
SyncAction *a = nextAction();
if (!a)
{
kdWarning() << k_funcinfo
<< ": NULL action on stack."
<< endl;
return;
}
#ifdef DEBUG
DEBUGDAEMON << fname
<< ": Will run action "
<< a->name()
<< endl;
#endif
QObject::connect(a, SIGNAL(logMessage(const QString &)),
this, SIGNAL(logMessage(const QString &)));
QObject::connect(a, SIGNAL(logError(const QString &)),
this, SIGNAL(logMessage(const QString &)));
QObject::connect(a, SIGNAL(logProgress(const QString &, int)),
this, SIGNAL(logProgress(const QString &, int)));
QObject::connect(a, SIGNAL(syncDone(SyncAction *)),
this, SLOT(actionCompleted(SyncAction *)));
QTimer::singleShot(0,a,SLOT(execConduit()));
}
<commit_msg>Minor: having set the variable, use it<commit_after>/* KPilot
**
** Copyright (C) 1998-2001 by Dan Pilone
** Copyright (C) 2003-2004 Reinhold Kainhofer <[email protected]>
**
** This defines the "ActionQueue", which is the pile of actions
** that will occur during a HotSync.
*/
/*
** This program is free software; you can redistribute it and/or modify
** it under the terms of the GNU General Public License as published by
** the Free Software Foundation; either version 2 of the License, or
** (at your option) any later version.
**
** This program 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 General Public License for more details.
**
** You should have received a copy of the GNU General Public License
** along with this program in a file called COPYING; if not, write to
** the Free Software Foundation, Inc., 59 Temple Place, Suite 330, Boston,
** MA 02111-1307, USA.
*/
/*
** Bug reports and questions can be sent to [email protected]
*/
#include "options.h"
static const char *syncStack_id = "$Id$";
#include <unistd.h>
#include <qtimer.h>
#include <qfile.h>
#include <qdir.h>
#include <qtextcodec.h>
#include <kservice.h>
#include <kservicetype.h>
#include <kuserprofile.h>
#include <klibloader.h>
#include <ksavefile.h>
#include "pilotUser.h"
#include "hotSync.h"
#include "interactiveSync.h"
#include "fileInstaller.h"
#include "kpilotSettings.h"
#include "pilotAppCategory.h"
#include "syncStack.moc"
WelcomeAction::WelcomeAction(KPilotDeviceLink *p) :
SyncAction(p,"welcomeAction")
{
FUNCTIONSETUP;
(void) syncStack_id;
}
/* virtual */ bool WelcomeAction::exec()
{
FUNCTIONSETUP;
addSyncLogEntry(i18n("KPilot %1 HotSync starting...\n")
.arg(QString::fromLatin1(KPILOT_VERSION)));
emit logMessage( i18n("Using encoding %1 on the handheld.").arg(PilotAppCategory::codecName()) );
emit syncDone(this);
return true;
}
SorryAction::SorryAction(KPilotDeviceLink *p, const QString &s) :
SyncAction(p,"sorryAction"),
fMessage(s)
{
if (fMessage.isEmpty())
{
fMessage = i18n("KPilot is busy and cannot process the "
"HotSync right now.");
}
}
bool SorryAction::exec()
{
FUNCTIONSETUP;
addSyncLogEntry(fMessage);
return delayDone();
}
LocalBackupAction::LocalBackupAction(KPilotDeviceLink *p, const QString &d) :
SyncAction(p,"LocalBackupAction"),
fDir(d)
{
}
bool LocalBackupAction::exec()
{
FUNCTIONSETUP;
startTickle();
QString dirname = fDir +
PilotAppCategory::codec()->toUnicode(fHandle->getPilotUser()->getUserName()) +
CSL1("/");
QDir dir(dirname,QString::null,QDir::Unsorted,QDir::Files);
if (!dir.exists())
{
emit logMessage( i18n("Cannot create local backup.") );
return false;
}
logMessage( i18n("Creating local backup of databases in %1.").arg(dirname) );
addSyncLogEntry( i18n("Creating local backup ..") );
qApp->processEvents();
QStringList files = dir.entryList();
for (QStringList::Iterator i = files.begin() ;
i != files.end();
++i)
{
KSaveFile::backupFile(dirname + (*i));
}
stopTickle();
return delayDone();
}
ConduitProxy::ConduitProxy(KPilotDeviceLink *p,
const QString &name,
SyncAction::SyncMode m,
bool local) :
ConduitAction(p,name.latin1()),
fDesktopName(name),
fMode(m),
fLocal(local)
{
FUNCTIONSETUP;
}
/* static */ QStringList ConduitProxy::flagsForMode(SyncAction::SyncMode m)
{
FUNCTIONSETUP;
QStringList l;
switch(m)
{
case eBackup :
l.append(CSL1("--backup"));
break;
case eTest:
l.append(CSL1("--test"));
break;
case eFastSync: /* FALLTHRU */
case eHotSync:
/* Nothing to do for fast or hotsync */
break;
case eFullSync:
l.append(CSL1("--full"));
break;
case eCopyHHToPC:
l.append(CSL1("--copyHHToPC"));
break;
case eCopyPCToHH:
l.append(CSL1("--copyPCToHH"));
break;
case eRestore:
kdWarning() << k_funcinfo << ": Running conduits during restore." << endl;
l.append(CSL1("--test"));
break;
case eDefaultSync:
Q_ASSERT(eDefaultSync != m); // Bail
break;
}
return l;
}
/* virtual */ bool ConduitProxy::exec()
{
FUNCTIONSETUP;
// query that service
KSharedPtr < KService > o = KService::serviceByDesktopName(fDesktopName);
if (!o)
{
kdWarning() << k_funcinfo
<< ": Can't find desktop file for conduit "
<< fDesktopName
<< endl;
addSyncLogEntry(i18n("Could not find conduit %1.").arg(fDesktopName));
emit syncDone(this);
return true;
}
// load the lib
fLibraryName = o->library();
#ifdef DEBUG
DEBUGKPILOT << fname
<< ": Loading desktop "
<< fDesktopName
<< " with lib "
<< fLibraryName
<< endl;
#endif
KLibFactory *factory = KLibLoader::self()->factory(
QFile::encodeName(fLibraryName));
if (!factory)
{
kdWarning() << k_funcinfo
<< ": Can't load library "
<< fLibraryName
<< endl;
addSyncLogEntry(i18n("Could not load conduit %1.").arg(fDesktopName));
emit syncDone(this);
return true;
}
QStringList l = flagsForMode(fMode);
if (fLocal)
{
l.append(CSL1("--local"));
}
#ifdef DEBUG
DEBUGDAEMON << fname << ": Flags: " << fMode << endl;
#endif
QObject *object = factory->create(fHandle,name(),"SyncAction",l);
if (!object)
{
kdWarning() << k_funcinfo
<< ": Can't create SyncAction."
<< endl;
addSyncLogEntry(i18n("Could not create conduit %1.").arg(fDesktopName));
emit syncDone(this);
return true;
}
fConduit = dynamic_cast<ConduitAction *>(object);
if (!fConduit)
{
kdWarning() << k_funcinfo
<< ": Can't cast to ConduitAction."
<< endl;
addSyncLogEntry(i18n("Could not create conduit %1.").arg(fDesktopName));
emit syncDone(this);
return true;
}
addSyncLogEntry(i18n("[Conduit %1]").arg(fDesktopName));
// Handle the syncDone signal properly & unload the conduit.
QObject::connect(fConduit,SIGNAL(syncDone(SyncAction *)),
this,SLOT(execDone(SyncAction *)));
// Proxy all the log and error messages.
QObject::connect(fConduit,SIGNAL(logMessage(const QString &)),
this,SIGNAL(logMessage(const QString &)));
QObject::connect(fConduit,SIGNAL(logError(const QString &)),
this,SIGNAL(logError(const QString &)));
QObject::connect(fConduit,SIGNAL(logProgress(const QString &,int)),
this,SIGNAL(logProgress(const QString &,int)));
QTimer::singleShot(0,fConduit,SLOT(execConduit()));
return true;
}
void ConduitProxy::execDone(SyncAction *p)
{
FUNCTIONSETUP;
if (p!=fConduit)
{
kdError() << k_funcinfo
<< ": Unknown conduit @"
<< (long) p
<< " finished."
<< endl;
emit syncDone(this);
return;
}
delete p;
addSyncLogEntry(CSL1("\n"),false); // Put bits of the conduit logs on separate lines
emit syncDone(this);
}
ActionQueue::ActionQueue(KPilotDeviceLink *d) :
SyncAction(d,"ActionQueue"),
fTestMode(false),
fReady(false)
// The string lists have default constructors
{
FUNCTIONSETUP;
}
ActionQueue::~ActionQueue()
{
FUNCTIONSETUP;
}
void ActionQueue::queueInit(bool checkUser)
{
FUNCTIONSETUP;
addAction(new WelcomeAction(fHandle));
if (checkUser)
{
addAction(new CheckUser(fHandle));
}
}
void ActionQueue::queueConduits(const QStringList &l,SyncAction::SyncMode m, bool /*local*/)
{
FUNCTIONSETUP;
// Add conduits here ...
//
//
for (QStringList::ConstIterator it = l.begin();
it != l.end();
++it)
{
if ((*it).startsWith(CSL1("internal_")))
{
#ifdef DEBUG
DEBUGDAEMON << fname <<
": Ignoring conduit " << *it << endl;
#endif
continue;
}
#ifdef DEBUG
DEBUGDAEMON << fname
<< ": Creating proxy with mode=" << m << endl;
#endif
ConduitProxy *cp = new ConduitProxy(fHandle,*it,m);
addAction(cp);
}
}
void ActionQueue::queueInstaller(const QString &dir)
{
addAction(new FileInstallAction(fHandle,dir));
}
void ActionQueue::queueCleanup()
{
addAction(new CleanupAction(fHandle));
}
bool ActionQueue::exec()
{
actionCompleted(0L);
return true;
}
void ActionQueue::actionCompleted(SyncAction *b)
{
FUNCTIONSETUP;
if (b)
{
#ifdef DEBUG
DEBUGDAEMON << fname
<< ": Completed action "
<< b->name()
<< endl;
#endif
delete b;
}
if (isEmpty())
{
delayDone();
return;
}
if (!fTestMode && !fHandle->tickle())
{
emit logError(i18n("The connection to the handheld "
"was lost. Synchronization cannot continue."));
SyncAction *del = 0L;
while ( (del = nextAction()) )
{
delete del;
}
delayDone();
return;
}
SyncAction *a = nextAction();
if (!a)
{
kdWarning() << k_funcinfo
<< ": NULL action on stack."
<< endl;
return;
}
#ifdef DEBUG
DEBUGDAEMON << fname
<< ": Will run action "
<< a->name()
<< endl;
#endif
QObject::connect(a, SIGNAL(logMessage(const QString &)),
this, SIGNAL(logMessage(const QString &)));
QObject::connect(a, SIGNAL(logError(const QString &)),
this, SIGNAL(logMessage(const QString &)));
QObject::connect(a, SIGNAL(logProgress(const QString &, int)),
this, SIGNAL(logProgress(const QString &, int)));
QObject::connect(a, SIGNAL(syncDone(SyncAction *)),
this, SLOT(actionCompleted(SyncAction *)));
QTimer::singleShot(0,a,SLOT(execConduit()));
}
<|endoftext|>
|
<commit_before>#include <iostream>
#include <unistd.h>
#include "benchmark.h"
#include "simdjson.h"
SIMDJSON_PUSH_DISABLE_ALL_WARNINGS
// #define RAPIDJSON_SSE2 // bad
// #define RAPIDJSON_SSE42 // bad
#include "rapidjson/document.h"
#include "rapidjson/reader.h" // you have to check in the submodule
#include "rapidjson/stringbuffer.h"
#include "rapidjson/writer.h"
#include "sajson.h"
SIMDJSON_POP_DISABLE_WARNINGS
using namespace rapidjson;
using namespace simdjson;
std::string rapid_stringme_insitu(char *json) {
Document d;
d.ParseInsitu(json);
if (d.HasParseError()) {
std::cerr << "problem!" << std::endl;
return ""; // should do something
}
StringBuffer buffer;
Writer<StringBuffer> writer(buffer);
d.Accept(writer);
return buffer.GetString();
}
std::string rapid_stringme(char *json) {
Document d;
d.Parse(json);
if (d.HasParseError()) {
std::cerr << "problem!" << std::endl;
return ""; // should do something
}
StringBuffer buffer;
Writer<StringBuffer> writer(buffer);
d.Accept(writer);
return buffer.GetString();
}
int main(int argc, char *argv[]) {
int c;
bool verbose = false;
bool just_data = false;
while ((c = getopt(argc, argv, "vt")) != -1)
switch (c) {
case 't':
just_data = true;
break;
case 'v':
verbose = true;
break;
default:
abort();
}
if (optind >= argc) {
std::cerr << "Usage: " << argv[0] << " <jsonfile>" << std::endl;
exit(1);
}
const char *filename = argv[optind];
auto [p, error] = simdjson::padded_string::load(filename);
if (error) {
std::cerr << "Could not load the file " << filename << std::endl;
return EXIT_FAILURE;
}
// Gigabyte: https://en.wikipedia.org/wiki/Gigabyte
if (verbose) {
std::cout << "Input has ";
if (p.size() > 1000 * 1000)
std::cout << p.size() / (1000 * 1000) << " MB ";
else if (p.size() > 1000)
std::cout << p.size() / 1000 << " KB ";
else
std::cout << p.size() << " B ";
std::cout << std::endl;
}
char *buffer = simdjson::internal::allocate_padded_buffer(p.size() + 1);
memcpy(buffer, p.data(), p.size());
buffer[p.size()] = '\0';
int repeat = 50;
size_t volume = p.size();
if (just_data) {
printf(
"name cycles_per_byte cycles_per_byte_err gb_per_s gb_per_s_err \n");
}
size_t strlength = rapid_stringme((char *)p.data()).size();
if (verbose)
std::cout << "input length is " << p.size() << " stringified length is "
<< strlength << std::endl;
BEST_TIME_NOCHECK("despacing with RapidJSON",
rapid_stringme((char *)p.data()), , repeat, volume,
!just_data);
BEST_TIME_NOCHECK(
"despacing with RapidJSON Insitu", rapid_stringme_insitu((char *)buffer),
memcpy(buffer, p.data(), p.size()), repeat, volume, !just_data);
memcpy(buffer, p.data(), p.size());
size_t outlength;
uint8_t *cbuffer = (uint8_t *)buffer;
for (auto imple : simdjson::available_implementations) {
BEST_TIME((std::string("simdjson->minify+")+imple->name()).c_str(), (imple->minify(cbuffer, p.size(), cbuffer, outlength) ? outlength : -1),
outlength, memcpy(buffer, p.data(), p.size()), repeat, volume,
!just_data);
}
printf("minisize = %zu, original size = %zu (minified down to %.2f percent "
"of original) \n",
outlength, p.size(), static_cast<double>(outlength) * 100.0 / static_cast<double>(p.size()));
/***
* Is it worth it to minify before parsing?
***/
rapidjson::Document d;
BEST_TIME("RapidJSON Insitu orig", d.ParseInsitu(buffer).HasParseError(),
false, memcpy(buffer, p.data(), p.size()), repeat, volume,
!just_data);
char *mini_buffer = simdjson::internal::allocate_padded_buffer(p.size() + 1);
size_t minisize;
auto minierror = simdjson::active_implementation->minify((const uint8_t *)p.data(), p.size(),
(uint8_t *)mini_buffer, minisize);
if (!minierror) { std::cerr << minierror << std::endl; exit(1); }
mini_buffer[minisize] = '\0';
BEST_TIME("RapidJSON Insitu despaced", d.ParseInsitu(buffer).HasParseError(),
false, memcpy(buffer, mini_buffer, p.size()), repeat, volume,
!just_data);
size_t ast_buffer_size = p.size() * 2;
size_t *ast_buffer = (size_t *)malloc(ast_buffer_size * sizeof(size_t));
BEST_TIME(
"sajson orig",
sajson::parse(sajson::bounded_allocation(ast_buffer, ast_buffer_size),
sajson::mutable_string_view(p.size(), buffer))
.is_valid(),
true, memcpy(buffer, p.data(), p.size()), repeat, volume, !just_data);
BEST_TIME(
"sajson despaced",
sajson::parse(sajson::bounded_allocation(ast_buffer, ast_buffer_size),
sajson::mutable_string_view(minisize, buffer))
.is_valid(),
true, memcpy(buffer, mini_buffer, p.size()), repeat, volume, !just_data);
simdjson::dom::parser parser;
bool automated_reallocation = false;
BEST_TIME("simdjson orig",
parser.parse((const uint8_t *)buffer, p.size(),
automated_reallocation).error(),
simdjson::SUCCESS, memcpy(buffer, p.data(), p.size()), repeat, volume,
!just_data);
BEST_TIME("simdjson despaced",
parser.parse((const uint8_t *)buffer, minisize,
automated_reallocation).error(),
simdjson::SUCCESS, memcpy(buffer, mini_buffer, p.size()), repeat, volume,
!just_data);
free(buffer);
free(ast_buffer);
free(mini_buffer);
}
<commit_msg>Obvious fix. (#885)<commit_after>#include <iostream>
#include <unistd.h>
#include "benchmark.h"
#include "simdjson.h"
SIMDJSON_PUSH_DISABLE_ALL_WARNINGS
// #define RAPIDJSON_SSE2 // bad
// #define RAPIDJSON_SSE42 // bad
#include "rapidjson/document.h"
#include "rapidjson/reader.h" // you have to check in the submodule
#include "rapidjson/stringbuffer.h"
#include "rapidjson/writer.h"
#include "sajson.h"
SIMDJSON_POP_DISABLE_WARNINGS
using namespace rapidjson;
using namespace simdjson;
std::string rapid_stringme_insitu(char *json) {
Document d;
d.ParseInsitu(json);
if (d.HasParseError()) {
std::cerr << "problem!" << std::endl;
return ""; // should do something
}
StringBuffer buffer;
Writer<StringBuffer> writer(buffer);
d.Accept(writer);
return buffer.GetString();
}
std::string rapid_stringme(char *json) {
Document d;
d.Parse(json);
if (d.HasParseError()) {
std::cerr << "problem!" << std::endl;
return ""; // should do something
}
StringBuffer buffer;
Writer<StringBuffer> writer(buffer);
d.Accept(writer);
return buffer.GetString();
}
int main(int argc, char *argv[]) {
int c;
bool verbose = false;
bool just_data = false;
while ((c = getopt(argc, argv, "vt")) != -1)
switch (c) {
case 't':
just_data = true;
break;
case 'v':
verbose = true;
break;
default:
abort();
}
if (optind >= argc) {
std::cerr << "Usage: " << argv[0] << " <jsonfile>" << std::endl;
exit(1);
}
const char *filename = argv[optind];
auto [p, error] = simdjson::padded_string::load(filename);
if (error) {
std::cerr << "Could not load the file " << filename << std::endl;
return EXIT_FAILURE;
}
// Gigabyte: https://en.wikipedia.org/wiki/Gigabyte
if (verbose) {
std::cout << "Input has ";
if (p.size() > 1000 * 1000)
std::cout << p.size() / (1000 * 1000) << " MB ";
else if (p.size() > 1000)
std::cout << p.size() / 1000 << " KB ";
else
std::cout << p.size() << " B ";
std::cout << std::endl;
}
char *buffer = simdjson::internal::allocate_padded_buffer(p.size() + 1);
memcpy(buffer, p.data(), p.size());
buffer[p.size()] = '\0';
int repeat = 50;
size_t volume = p.size();
if (just_data) {
printf(
"name cycles_per_byte cycles_per_byte_err gb_per_s gb_per_s_err \n");
}
size_t strlength = rapid_stringme((char *)p.data()).size();
if (verbose)
std::cout << "input length is " << p.size() << " stringified length is "
<< strlength << std::endl;
BEST_TIME_NOCHECK("despacing with RapidJSON",
rapid_stringme((char *)p.data()), , repeat, volume,
!just_data);
BEST_TIME_NOCHECK(
"despacing with RapidJSON Insitu", rapid_stringme_insitu((char *)buffer),
memcpy(buffer, p.data(), p.size()), repeat, volume, !just_data);
memcpy(buffer, p.data(), p.size());
size_t outlength;
uint8_t *cbuffer = (uint8_t *)buffer;
for (auto imple : simdjson::available_implementations) {
BEST_TIME((std::string("simdjson->minify+")+imple->name()).c_str(), (imple->minify(cbuffer, p.size(), cbuffer, outlength) == simdjson::SUCCESS ? outlength : -1),
outlength, memcpy(buffer, p.data(), p.size()), repeat, volume,
!just_data);
}
printf("minisize = %zu, original size = %zu (minified down to %.2f percent "
"of original) \n",
outlength, p.size(), static_cast<double>(outlength) * 100.0 / static_cast<double>(p.size()));
/***
* Is it worth it to minify before parsing?
***/
rapidjson::Document d;
BEST_TIME("RapidJSON Insitu orig", d.ParseInsitu(buffer).HasParseError(),
false, memcpy(buffer, p.data(), p.size()), repeat, volume,
!just_data);
char *mini_buffer = simdjson::internal::allocate_padded_buffer(p.size() + 1);
size_t minisize;
auto minierror = simdjson::active_implementation->minify((const uint8_t *)p.data(), p.size(),
(uint8_t *)mini_buffer, minisize);
if (!minierror) { std::cerr << minierror << std::endl; exit(1); }
mini_buffer[minisize] = '\0';
BEST_TIME("RapidJSON Insitu despaced", d.ParseInsitu(buffer).HasParseError(),
false, memcpy(buffer, mini_buffer, p.size()), repeat, volume,
!just_data);
size_t ast_buffer_size = p.size() * 2;
size_t *ast_buffer = (size_t *)malloc(ast_buffer_size * sizeof(size_t));
BEST_TIME(
"sajson orig",
sajson::parse(sajson::bounded_allocation(ast_buffer, ast_buffer_size),
sajson::mutable_string_view(p.size(), buffer))
.is_valid(),
true, memcpy(buffer, p.data(), p.size()), repeat, volume, !just_data);
BEST_TIME(
"sajson despaced",
sajson::parse(sajson::bounded_allocation(ast_buffer, ast_buffer_size),
sajson::mutable_string_view(minisize, buffer))
.is_valid(),
true, memcpy(buffer, mini_buffer, p.size()), repeat, volume, !just_data);
simdjson::dom::parser parser;
bool automated_reallocation = false;
BEST_TIME("simdjson orig",
parser.parse((const uint8_t *)buffer, p.size(),
automated_reallocation).error(),
simdjson::SUCCESS, memcpy(buffer, p.data(), p.size()), repeat, volume,
!just_data);
BEST_TIME("simdjson despaced",
parser.parse((const uint8_t *)buffer, minisize,
automated_reallocation).error(),
simdjson::SUCCESS, memcpy(buffer, mini_buffer, p.size()), repeat, volume,
!just_data);
free(buffer);
free(ast_buffer);
free(mini_buffer);
}
<|endoftext|>
|
<commit_before>#include <iostream>
#include <unistd.h>
#include "benchmark.h"
#include "simdjson.h"
SIMDJSON_PUSH_DISABLE_ALL_WARNINGS
// #define RAPIDJSON_SSE2 // bad
// #define RAPIDJSON_SSE42 // bad
#include "rapidjson/document.h"
#include "rapidjson/reader.h" // you have to check in the submodule
#include "rapidjson/stringbuffer.h"
#include "rapidjson/writer.h"
#include "sajson.h"
SIMDJSON_POP_DISABLE_WARNINGS
using namespace rapidjson;
using namespace simdjson;
std::string rapid_stringme_insitu(char *json) {
Document d;
d.ParseInsitu(json);
if (d.HasParseError()) {
std::cerr << "problem!" << std::endl;
return ""; // should do something
}
StringBuffer buffer;
Writer<StringBuffer> writer(buffer);
d.Accept(writer);
return buffer.GetString();
}
std::string rapid_stringme(char *json) {
Document d;
d.Parse(json);
if (d.HasParseError()) {
std::cerr << "problem!" << std::endl;
return ""; // should do something
}
StringBuffer buffer;
Writer<StringBuffer> writer(buffer);
d.Accept(writer);
return buffer.GetString();
}
int main(int argc, char *argv[]) {
int c;
bool verbose = false;
bool just_data = false;
while ((c = getopt(argc, argv, "vt")) != -1)
switch (c) {
case 't':
just_data = true;
break;
case 'v':
verbose = true;
break;
default:
abort();
}
if (optind >= argc) {
std::cerr << "Usage: " << argv[0] << " <jsonfile>" << std::endl;
exit(1);
}
const char *filename = argv[optind];
auto [p, error] = simdjson::padded_string::load(filename);
if (error) {
std::cerr << "Could not load the file " << filename << std::endl;
return EXIT_FAILURE;
}
// Gigabyte: https://en.wikipedia.org/wiki/Gigabyte
if (verbose) {
std::cout << "Input has ";
if (p.size() > 1000 * 1000)
std::cout << p.size() / (1000 * 1000) << " MB ";
else if (p.size() > 1000)
std::cout << p.size() / 1000 << " KB ";
else
std::cout << p.size() << " B ";
std::cout << std::endl;
}
char *buffer = simdjson::internal::allocate_padded_buffer(p.size() + 1);
memcpy(buffer, p.data(), p.size());
buffer[p.size()] = '\0';
int repeat = 50;
size_t volume = p.size();
if (just_data) {
printf(
"name cycles_per_byte cycles_per_byte_err gb_per_s gb_per_s_err \n");
}
size_t strlength = rapid_stringme((char *)p.data()).size();
if (verbose)
std::cout << "input length is " << p.size() << " stringified length is "
<< strlength << std::endl;
BEST_TIME_NOCHECK("despacing with RapidJSON",
rapid_stringme((char *)p.data()), , repeat, volume,
!just_data);
BEST_TIME_NOCHECK(
"despacing with RapidJSON Insitu", rapid_stringme_insitu((char *)buffer),
memcpy(buffer, p.data(), p.size()), repeat, volume, !just_data);
memcpy(buffer, p.data(), p.size());
size_t outlength;
uint8_t *cbuffer = (uint8_t *)buffer;
for (auto imple : simdjson::available_implementations) {
BEST_TIME((std::string("simdjson->minify+")+imple->name()).c_str(), (imple->minify(cbuffer, p.size(), cbuffer, outlength) == simdjson::SUCCESS ? outlength : -1),
outlength, memcpy(buffer, p.data(), p.size()), repeat, volume,
!just_data);
}
printf("minisize = %zu, original size = %zu (minified down to %.2f percent "
"of original) \n",
outlength, p.size(), static_cast<double>(outlength) * 100.0 / static_cast<double>(p.size()));
/***
* Is it worth it to minify before parsing?
***/
rapidjson::Document d;
BEST_TIME("RapidJSON Insitu orig", d.ParseInsitu(buffer).HasParseError(),
false, memcpy(buffer, p.data(), p.size()), repeat, volume,
!just_data);
char *mini_buffer = simdjson::internal::allocate_padded_buffer(p.size() + 1);
size_t minisize;
auto minierror = minify_string(p.data(), p.size(),mini_buffer, minisize);
if (!minierror) { std::cerr << minierror << std::endl; exit(1); }
mini_buffer[minisize] = '\0';
BEST_TIME("RapidJSON Insitu despaced", d.ParseInsitu(buffer).HasParseError(),
false, memcpy(buffer, mini_buffer, p.size()), repeat, volume,
!just_data);
size_t ast_buffer_size = p.size() * 2;
size_t *ast_buffer = (size_t *)malloc(ast_buffer_size * sizeof(size_t));
BEST_TIME(
"sajson orig",
sajson::parse(sajson::bounded_allocation(ast_buffer, ast_buffer_size),
sajson::mutable_string_view(p.size(), buffer))
.is_valid(),
true, memcpy(buffer, p.data(), p.size()), repeat, volume, !just_data);
BEST_TIME(
"sajson despaced",
sajson::parse(sajson::bounded_allocation(ast_buffer, ast_buffer_size),
sajson::mutable_string_view(minisize, buffer))
.is_valid(),
true, memcpy(buffer, mini_buffer, p.size()), repeat, volume, !just_data);
simdjson::dom::parser parser;
bool automated_reallocation = false;
BEST_TIME("simdjson orig",
parser.parse((const uint8_t *)buffer, p.size(),
automated_reallocation).error(),
simdjson::SUCCESS, memcpy(buffer, p.data(), p.size()), repeat, volume,
!just_data);
BEST_TIME("simdjson despaced",
parser.parse((const uint8_t *)buffer, minisize,
automated_reallocation).error(),
simdjson::SUCCESS, memcpy(buffer, mini_buffer, p.size()), repeat, volume,
!just_data);
free(buffer);
free(ast_buffer);
free(mini_buffer);
}
<commit_msg>Added std::minify<commit_after>#include <iostream>
#include <unistd.h>
#include "benchmark.h"
#include "simdjson.h"
SIMDJSON_PUSH_DISABLE_ALL_WARNINGS
// #define RAPIDJSON_SSE2 // bad
// #define RAPIDJSON_SSE42 // bad
#include "rapidjson/document.h"
#include "rapidjson/reader.h" // you have to check in the submodule
#include "rapidjson/stringbuffer.h"
#include "rapidjson/writer.h"
#include "sajson.h"
SIMDJSON_POP_DISABLE_WARNINGS
using namespace rapidjson;
using namespace simdjson;
std::string rapid_stringme_insitu(char *json) {
Document d;
d.ParseInsitu(json);
if (d.HasParseError()) {
std::cerr << "problem!" << std::endl;
return ""; // should do something
}
StringBuffer buffer;
Writer<StringBuffer> writer(buffer);
d.Accept(writer);
return buffer.GetString();
}
std::string rapid_stringme(char *json) {
Document d;
d.Parse(json);
if (d.HasParseError()) {
std::cerr << "problem!" << std::endl;
return ""; // should do something
}
StringBuffer buffer;
Writer<StringBuffer> writer(buffer);
d.Accept(writer);
return buffer.GetString();
}
std::string simdjson_stringme(simdjson::padded_string & json) {
std::stringstream ss;
dom::parser parser;
dom::element doc = parser.parse(json);
ss << simdjson::minify(doc);
return ss.str();
}
int main(int argc, char *argv[]) {
int c;
bool verbose = false;
bool just_data = false;
while ((c = getopt(argc, argv, "vt")) != -1)
switch (c) {
case 't':
just_data = true;
break;
case 'v':
verbose = true;
break;
default:
abort();
}
if (optind >= argc) {
std::cerr << "Usage: " << argv[0] << " <jsonfile>" << std::endl;
exit(1);
}
const char *filename = argv[optind];
auto [p, error] = simdjson::padded_string::load(filename);
if (error) {
std::cerr << "Could not load the file " << filename << std::endl;
return EXIT_FAILURE;
}
// Gigabyte: https://en.wikipedia.org/wiki/Gigabyte
if (verbose) {
std::cout << "Input has ";
if (p.size() > 1000 * 1000)
std::cout << p.size() / (1000 * 1000) << " MB ";
else if (p.size() > 1000)
std::cout << p.size() / 1000 << " KB ";
else
std::cout << p.size() << " B ";
std::cout << std::endl;
}
char *buffer = simdjson::internal::allocate_padded_buffer(p.size() + 1);
memcpy(buffer, p.data(), p.size());
buffer[p.size()] = '\0';
int repeat = 50;
size_t volume = p.size();
if (just_data) {
printf(
"name cycles_per_byte cycles_per_byte_err gb_per_s gb_per_s_err \n");
}
size_t strlength = rapid_stringme((char *)p.data()).size();
if (verbose)
std::cout << "input length is " << p.size() << " stringified length is "
<< strlength << std::endl;
BEST_TIME_NOCHECK("despacing with RapidJSON",
rapid_stringme((char *)p.data()), , repeat, volume,
!just_data);
BEST_TIME_NOCHECK(
"despacing with RapidJSON Insitu", rapid_stringme_insitu((char *)buffer),
memcpy(buffer, p.data(), p.size()), repeat, volume, !just_data);
BEST_TIME_NOCHECK(
"despacing with std::minify", simdjson_stringme(p),, repeat, volume, !just_data);
memcpy(buffer, p.data(), p.size());
size_t outlength;
uint8_t *cbuffer = (uint8_t *)buffer;
for (auto imple : simdjson::available_implementations) {
BEST_TIME((std::string("simdjson->minify+")+imple->name()).c_str(), (imple->minify(cbuffer, p.size(), cbuffer, outlength) == simdjson::SUCCESS ? outlength : -1),
outlength, memcpy(buffer, p.data(), p.size()), repeat, volume,
!just_data);
}
printf("minisize = %zu, original size = %zu (minified down to %.2f percent "
"of original) \n",
outlength, p.size(), static_cast<double>(outlength) * 100.0 / static_cast<double>(p.size()));
/***
* Is it worth it to minify before parsing?
***/
rapidjson::Document d;
BEST_TIME("RapidJSON Insitu orig", d.ParseInsitu(buffer).HasParseError(),
false, memcpy(buffer, p.data(), p.size()), repeat, volume,
!just_data);
char *mini_buffer = simdjson::internal::allocate_padded_buffer(p.size() + 1);
size_t minisize;
auto minierror = minify_string(p.data(), p.size(),mini_buffer, minisize);
if (!minierror) { std::cerr << minierror << std::endl; exit(1); }
mini_buffer[minisize] = '\0';
BEST_TIME("RapidJSON Insitu despaced", d.ParseInsitu(buffer).HasParseError(),
false, memcpy(buffer, mini_buffer, p.size()), repeat, volume,
!just_data);
size_t ast_buffer_size = p.size() * 2;
size_t *ast_buffer = (size_t *)malloc(ast_buffer_size * sizeof(size_t));
BEST_TIME(
"sajson orig",
sajson::parse(sajson::bounded_allocation(ast_buffer, ast_buffer_size),
sajson::mutable_string_view(p.size(), buffer))
.is_valid(),
true, memcpy(buffer, p.data(), p.size()), repeat, volume, !just_data);
BEST_TIME(
"sajson despaced",
sajson::parse(sajson::bounded_allocation(ast_buffer, ast_buffer_size),
sajson::mutable_string_view(minisize, buffer))
.is_valid(),
true, memcpy(buffer, mini_buffer, p.size()), repeat, volume, !just_data);
simdjson::dom::parser parser;
bool automated_reallocation = false;
BEST_TIME("simdjson orig",
parser.parse((const uint8_t *)buffer, p.size(),
automated_reallocation).error(),
simdjson::SUCCESS, memcpy(buffer, p.data(), p.size()), repeat, volume,
!just_data);
BEST_TIME("simdjson despaced",
parser.parse((const uint8_t *)buffer, minisize,
automated_reallocation).error(),
simdjson::SUCCESS, memcpy(buffer, mini_buffer, p.size()), repeat, volume,
!just_data);
free(buffer);
free(ast_buffer);
free(mini_buffer);
}
<|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/command_line.h"
#include "base/json/json_writer.h"
#include "base/string_number_conversions.h"
#include "base/utf_string_conversions.h"
#include "base/values.h"
#include "chrome/browser/browser.h"
#include "chrome/browser/browser_list.h"
#include "chrome/browser/browser_process.h"
#include "chrome/browser/browser_window.h"
#include "chrome/browser/debugger/devtools_manager.h"
#include "chrome/browser/debugger/devtools_window.h"
#include "chrome/browser/extensions/extensions_service.h"
#include "chrome/browser/in_process_webkit/session_storage_namespace.h"
#include "chrome/browser/load_notification_details.h"
#include "chrome/browser/prefs/pref_service.h"
#include "chrome/browser/profile.h"
#include "chrome/browser/renderer_host/render_view_host.h"
#include "chrome/browser/tab_contents/navigation_controller.h"
#include "chrome/browser/tab_contents/navigation_entry.h"
#include "chrome/browser/tab_contents/tab_contents.h"
#include "chrome/browser/tab_contents/tab_contents_view.h"
#include "chrome/browser/tabs/tab_strip_model.h"
#include "chrome/browser/themes/browser_theme_provider.h"
#include "chrome/common/bindings_policy.h"
#include "chrome/common/chrome_switches.h"
#include "chrome/common/pref_names.h"
#include "chrome/common/render_messages.h"
#include "chrome/common/url_constants.h"
#include "grit/generated_resources.h"
const char DevToolsWindow::kDevToolsApp[] = "DevToolsApp";
// static
TabContents* DevToolsWindow::GetDevToolsContents(TabContents* inspected_tab) {
if (!inspected_tab) {
return NULL;
}
if (!DevToolsManager::GetInstance())
return NULL; // Happens only in tests.
DevToolsClientHost* client_host = DevToolsManager::GetInstance()->
GetDevToolsClientHostFor(inspected_tab->render_view_host());
if (!client_host) {
return NULL;
}
DevToolsWindow* window = client_host->AsDevToolsWindow();
if (!window || !window->is_docked()) {
return NULL;
}
return window->tab_contents();
}
DevToolsWindow::DevToolsWindow(Profile* profile,
RenderViewHost* inspected_rvh,
bool docked)
: profile_(profile),
browser_(NULL),
docked_(docked),
is_loaded_(false),
action_on_load_(DEVTOOLS_TOGGLE_ACTION_NONE) {
// Create TabContents with devtools.
tab_contents_ = new TabContents(profile, NULL, MSG_ROUTING_NONE, NULL, NULL);
tab_contents_->render_view_host()->AllowBindings(BindingsPolicy::DOM_UI);
tab_contents_->controller().LoadURL(
GetDevToolsUrl(), GURL(), PageTransition::START_PAGE);
// Wipe out page icon so that the default application icon is used.
NavigationEntry* entry = tab_contents_->controller().GetActiveEntry();
entry->favicon().set_bitmap(SkBitmap());
entry->favicon().set_is_valid(true);
// Register on-load actions.
registrar_.Add(this,
NotificationType::LOAD_STOP,
Source<NavigationController>(&tab_contents_->controller()));
registrar_.Add(this,
NotificationType::TAB_CLOSING,
Source<NavigationController>(&tab_contents_->controller()));
registrar_.Add(this, NotificationType::BROWSER_THEME_CHANGED,
NotificationService::AllSources());
inspected_tab_ = inspected_rvh->delegate()->GetAsTabContents();
}
DevToolsWindow::~DevToolsWindow() {
}
DevToolsWindow* DevToolsWindow::AsDevToolsWindow() {
return this;
}
void DevToolsWindow::SendMessageToClient(const IPC::Message& message) {
RenderViewHost* target_host = tab_contents_->render_view_host();
IPC::Message* m = new IPC::Message(message);
m->set_routing_id(target_host->routing_id());
target_host->Send(m);
}
void DevToolsWindow::InspectedTabClosing() {
if (docked_) {
// Update dev tools to reflect removed dev tools window.
BrowserWindow* inspected_window = GetInspectedBrowserWindow();
if (inspected_window)
inspected_window->UpdateDevTools();
// In case of docked tab_contents we own it, so delete here.
delete tab_contents_;
delete this;
} else {
// First, initiate self-destruct to free all the registrars.
// Then close all tabs. Browser will take care of deleting tab_contents
// for us.
Browser* browser = browser_;
delete this;
browser->CloseAllTabs();
}
}
void DevToolsWindow::Show(DevToolsToggleAction action) {
if (docked_) {
// Just tell inspected browser to update splitter.
BrowserWindow* inspected_window = GetInspectedBrowserWindow();
if (inspected_window) {
tab_contents_->set_delegate(this);
inspected_window->UpdateDevTools();
SetAttachedWindow();
tab_contents_->view()->SetInitialFocus();
ScheduleAction(action);
return;
} else {
// Sometimes we don't know where to dock. Stay undocked.
docked_ = false;
}
}
// Avoid consecutive window switching if the devtools window has been opened
// and the Inspect Element shortcut is pressed in the inspected tab.
bool should_show_window =
!browser_ || action != DEVTOOLS_TOGGLE_ACTION_INSPECT;
if (!browser_)
CreateDevToolsBrowser();
if (should_show_window)
browser_->window()->Show();
SetAttachedWindow();
if (should_show_window)
tab_contents_->view()->SetInitialFocus();
ScheduleAction(action);
}
void DevToolsWindow::Activate() {
if (!docked_) {
if (!browser_->window()->IsActive()) {
browser_->window()->Activate();
}
} else {
BrowserWindow* inspected_window = GetInspectedBrowserWindow();
if (inspected_window)
tab_contents_->view()->Focus();
}
}
void DevToolsWindow::SetDocked(bool docked) {
if (docked_ == docked)
return;
if (docked && !GetInspectedBrowserWindow()) {
// Cannot dock, avoid window flashing due to close-reopen cycle.
return;
}
docked_ = docked;
if (docked) {
// Detach window from the external devtools browser. It will lead to
// the browser object's close and delete. Remove observer first.
TabStripModel* tabstrip_model = browser_->tabstrip_model();
tabstrip_model->DetachTabContentsAt(
tabstrip_model->GetIndexOfTabContents(tab_contents_));
browser_ = NULL;
} else {
// Update inspected window to hide split and reset it.
BrowserWindow* inspected_window = GetInspectedBrowserWindow();
if (inspected_window) {
inspected_window->UpdateDevTools();
inspected_window = NULL;
}
}
Show(DEVTOOLS_TOGGLE_ACTION_NONE);
}
RenderViewHost* DevToolsWindow::GetRenderViewHost() {
return tab_contents_->render_view_host();
}
void DevToolsWindow::CreateDevToolsBrowser() {
// TODO(pfeldman): Make browser's getter for this key static.
std::string wp_key;
wp_key.append(prefs::kBrowserWindowPlacement);
wp_key.append("_");
wp_key.append(kDevToolsApp);
PrefService* prefs = g_browser_process->local_state();
if (!prefs->FindPreference(wp_key.c_str())) {
prefs->RegisterDictionaryPref(wp_key.c_str());
}
const DictionaryValue* wp_pref = prefs->GetDictionary(wp_key.c_str());
if (!wp_pref) {
DictionaryValue* defaults = prefs->GetMutableDictionary(wp_key.c_str());
defaults->SetInteger("left", 100);
defaults->SetInteger("top", 100);
defaults->SetInteger("right", 740);
defaults->SetInteger("bottom", 740);
defaults->SetBoolean("maximized", false);
defaults->SetBoolean("always_on_top", false);
}
browser_ = Browser::CreateForDevTools(profile_);
browser_->tabstrip_model()->AddTabContents(
tab_contents_, -1, PageTransition::START_PAGE,
TabStripModel::ADD_SELECTED);
}
BrowserWindow* DevToolsWindow::GetInspectedBrowserWindow() {
for (BrowserList::const_iterator it = BrowserList::begin();
it != BrowserList::end(); ++it) {
Browser* browser = *it;
for (int i = 0; i < browser->tab_count(); ++i) {
TabContents* tab_contents = browser->GetTabContentsAt(i);
if (tab_contents == inspected_tab_) {
return browser->window();
}
}
}
return NULL;
}
void DevToolsWindow::SetAttachedWindow() {
tab_contents_->render_view_host()->
ExecuteJavascriptInWebFrame(
L"", docked_ ? L"WebInspector.setAttachedWindow(true);" :
L"WebInspector.setAttachedWindow(false);");
}
void DevToolsWindow::AddDevToolsExtensionsToClient() {
ListValue results;
const ExtensionsService* extension_service = tab_contents_->profile()->
GetOriginalProfile()->GetExtensionsService();
const ExtensionList* extensions = extension_service->extensions();
for (ExtensionList::const_iterator extension = extensions->begin();
extension != extensions->end(); ++extension) {
if ((*extension)->devtools_url().is_empty())
continue;
DictionaryValue* extension_info = new DictionaryValue();
extension_info->Set("startPage",
new StringValue((*extension)->devtools_url().spec()));
results.Append(extension_info);
}
CallClientFunction(L"WebInspector.addExtensions", results);
}
void DevToolsWindow::CallClientFunction(const std::wstring& function_name,
const Value& arg) {
std::string json;
base::JSONWriter::Write(&arg, false, &json);
std::wstring javascript = function_name + L"(" + UTF8ToWide(json) + L");";
tab_contents_->render_view_host()->
ExecuteJavascriptInWebFrame(L"", javascript);
}
void DevToolsWindow::Observe(NotificationType type,
const NotificationSource& source,
const NotificationDetails& details) {
if (type == NotificationType::LOAD_STOP && !is_loaded_) {
SetAttachedWindow();
is_loaded_ = true;
UpdateTheme();
DoAction();
AddDevToolsExtensionsToClient();
} else if (type == NotificationType::TAB_CLOSING) {
if (Source<NavigationController>(source).ptr() ==
&tab_contents_->controller()) {
// This happens when browser closes all of its tabs as a result
// of window.Close event.
// Notify manager that this DevToolsClientHost no longer exists and
// initiate self-destuct here.
NotifyCloseListener();
delete this;
}
} else if (type == NotificationType::BROWSER_THEME_CHANGED) {
UpdateTheme();
}
}
void DevToolsWindow::ScheduleAction(DevToolsToggleAction action) {
action_on_load_ = action;
if (is_loaded_)
DoAction();
}
void DevToolsWindow::DoAction() {
// TODO: these messages should be pushed through the WebKit API instead.
switch (action_on_load_) {
case DEVTOOLS_TOGGLE_ACTION_SHOW_CONSOLE:
tab_contents_->render_view_host()->
ExecuteJavascriptInWebFrame(L"", L"WebInspector.showConsole();");
break;
case DEVTOOLS_TOGGLE_ACTION_INSPECT:
tab_contents_->render_view_host()->
ExecuteJavascriptInWebFrame(
L"", L"WebInspector.toggleSearchingForNode();");
case DEVTOOLS_TOGGLE_ACTION_NONE:
// Do nothing.
break;
default:
NOTREACHED();
}
action_on_load_ = DEVTOOLS_TOGGLE_ACTION_NONE;
}
std::string SkColorToRGBAString(SkColor color) {
// We convert the alpha using DoubleToString because StringPrintf will use
// locale specific formatters (e.g., use , instead of . in German).
return StringPrintf("rgba(%d,%d,%d,%s)", SkColorGetR(color),
SkColorGetG(color), SkColorGetB(color),
base::DoubleToString(SkColorGetA(color) / 255.0).c_str());
}
GURL DevToolsWindow::GetDevToolsUrl() {
BrowserThemeProvider* tp = profile_->GetThemeProvider();
CHECK(tp);
SkColor color_toolbar =
tp->GetColor(BrowserThemeProvider::COLOR_TOOLBAR);
SkColor color_tab_text =
tp->GetColor(BrowserThemeProvider::COLOR_BOOKMARK_TEXT);
std::string url_string = StringPrintf(
"%sdevtools.html?docked=%s&toolbar_color=%s&text_color=%s",
chrome::kChromeUIDevToolsURL,
docked_ ? "true" : "false",
SkColorToRGBAString(color_toolbar).c_str(),
SkColorToRGBAString(color_tab_text).c_str());
return GURL(url_string);
}
void DevToolsWindow::UpdateTheme() {
BrowserThemeProvider* tp = profile_->GetThemeProvider();
CHECK(tp);
SkColor color_toolbar =
tp->GetColor(BrowserThemeProvider::COLOR_TOOLBAR);
SkColor color_tab_text =
tp->GetColor(BrowserThemeProvider::COLOR_BOOKMARK_TEXT);
std::string command = StringPrintf(
"WebInspector.setToolbarColors(\"%s\", \"%s\")",
SkColorToRGBAString(color_toolbar).c_str(),
SkColorToRGBAString(color_tab_text).c_str());
tab_contents_->render_view_host()->
ExecuteJavascriptInWebFrame(L"", UTF8ToWide(command));
}
bool DevToolsWindow::PreHandleKeyboardEvent(
const NativeWebKeyboardEvent& event, bool* is_keyboard_shortcut) {
if (docked_) {
BrowserWindow* inspected_window = GetInspectedBrowserWindow();
if (inspected_window)
return inspected_window->PreHandleKeyboardEvent(
event, is_keyboard_shortcut);
}
return false;
}
void DevToolsWindow::HandleKeyboardEvent(const NativeWebKeyboardEvent& event) {
if (docked_) {
BrowserWindow* inspected_window = GetInspectedBrowserWindow();
if (inspected_window)
inspected_window->HandleKeyboardEvent(event);
}
}
<commit_msg>Pass inspected tab id to DevTools front-end before initializing DevTools extensions.<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/command_line.h"
#include "base/json/json_writer.h"
#include "base/string_number_conversions.h"
#include "base/utf_string_conversions.h"
#include "base/values.h"
#include "chrome/browser/browser.h"
#include "chrome/browser/browser_list.h"
#include "chrome/browser/browser_process.h"
#include "chrome/browser/browser_window.h"
#include "chrome/browser/debugger/devtools_manager.h"
#include "chrome/browser/debugger/devtools_window.h"
#include "chrome/browser/extensions/extensions_service.h"
#include "chrome/browser/in_process_webkit/session_storage_namespace.h"
#include "chrome/browser/load_notification_details.h"
#include "chrome/browser/prefs/pref_service.h"
#include "chrome/browser/profile.h"
#include "chrome/browser/renderer_host/render_view_host.h"
#include "chrome/browser/tab_contents/navigation_controller.h"
#include "chrome/browser/tab_contents/navigation_entry.h"
#include "chrome/browser/tab_contents/tab_contents.h"
#include "chrome/browser/tab_contents/tab_contents_view.h"
#include "chrome/browser/tabs/tab_strip_model.h"
#include "chrome/browser/themes/browser_theme_provider.h"
#include "chrome/common/bindings_policy.h"
#include "chrome/common/chrome_switches.h"
#include "chrome/common/pref_names.h"
#include "chrome/common/render_messages.h"
#include "chrome/common/url_constants.h"
#include "grit/generated_resources.h"
const char DevToolsWindow::kDevToolsApp[] = "DevToolsApp";
// static
TabContents* DevToolsWindow::GetDevToolsContents(TabContents* inspected_tab) {
if (!inspected_tab) {
return NULL;
}
if (!DevToolsManager::GetInstance())
return NULL; // Happens only in tests.
DevToolsClientHost* client_host = DevToolsManager::GetInstance()->
GetDevToolsClientHostFor(inspected_tab->render_view_host());
if (!client_host) {
return NULL;
}
DevToolsWindow* window = client_host->AsDevToolsWindow();
if (!window || !window->is_docked()) {
return NULL;
}
return window->tab_contents();
}
DevToolsWindow::DevToolsWindow(Profile* profile,
RenderViewHost* inspected_rvh,
bool docked)
: profile_(profile),
browser_(NULL),
docked_(docked),
is_loaded_(false),
action_on_load_(DEVTOOLS_TOGGLE_ACTION_NONE) {
// Create TabContents with devtools.
tab_contents_ = new TabContents(profile, NULL, MSG_ROUTING_NONE, NULL, NULL);
tab_contents_->render_view_host()->AllowBindings(BindingsPolicy::DOM_UI);
tab_contents_->controller().LoadURL(
GetDevToolsUrl(), GURL(), PageTransition::START_PAGE);
// Wipe out page icon so that the default application icon is used.
NavigationEntry* entry = tab_contents_->controller().GetActiveEntry();
entry->favicon().set_bitmap(SkBitmap());
entry->favicon().set_is_valid(true);
// Register on-load actions.
registrar_.Add(this,
NotificationType::LOAD_STOP,
Source<NavigationController>(&tab_contents_->controller()));
registrar_.Add(this,
NotificationType::TAB_CLOSING,
Source<NavigationController>(&tab_contents_->controller()));
registrar_.Add(this, NotificationType::BROWSER_THEME_CHANGED,
NotificationService::AllSources());
inspected_tab_ = inspected_rvh->delegate()->GetAsTabContents();
}
DevToolsWindow::~DevToolsWindow() {
}
DevToolsWindow* DevToolsWindow::AsDevToolsWindow() {
return this;
}
void DevToolsWindow::SendMessageToClient(const IPC::Message& message) {
RenderViewHost* target_host = tab_contents_->render_view_host();
IPC::Message* m = new IPC::Message(message);
m->set_routing_id(target_host->routing_id());
target_host->Send(m);
}
void DevToolsWindow::InspectedTabClosing() {
if (docked_) {
// Update dev tools to reflect removed dev tools window.
BrowserWindow* inspected_window = GetInspectedBrowserWindow();
if (inspected_window)
inspected_window->UpdateDevTools();
// In case of docked tab_contents we own it, so delete here.
delete tab_contents_;
delete this;
} else {
// First, initiate self-destruct to free all the registrars.
// Then close all tabs. Browser will take care of deleting tab_contents
// for us.
Browser* browser = browser_;
delete this;
browser->CloseAllTabs();
}
}
void DevToolsWindow::Show(DevToolsToggleAction action) {
if (docked_) {
// Just tell inspected browser to update splitter.
BrowserWindow* inspected_window = GetInspectedBrowserWindow();
if (inspected_window) {
tab_contents_->set_delegate(this);
inspected_window->UpdateDevTools();
SetAttachedWindow();
tab_contents_->view()->SetInitialFocus();
ScheduleAction(action);
return;
} else {
// Sometimes we don't know where to dock. Stay undocked.
docked_ = false;
}
}
// Avoid consecutive window switching if the devtools window has been opened
// and the Inspect Element shortcut is pressed in the inspected tab.
bool should_show_window =
!browser_ || action != DEVTOOLS_TOGGLE_ACTION_INSPECT;
if (!browser_)
CreateDevToolsBrowser();
if (should_show_window)
browser_->window()->Show();
SetAttachedWindow();
if (should_show_window)
tab_contents_->view()->SetInitialFocus();
ScheduleAction(action);
}
void DevToolsWindow::Activate() {
if (!docked_) {
if (!browser_->window()->IsActive()) {
browser_->window()->Activate();
}
} else {
BrowserWindow* inspected_window = GetInspectedBrowserWindow();
if (inspected_window)
tab_contents_->view()->Focus();
}
}
void DevToolsWindow::SetDocked(bool docked) {
if (docked_ == docked)
return;
if (docked && !GetInspectedBrowserWindow()) {
// Cannot dock, avoid window flashing due to close-reopen cycle.
return;
}
docked_ = docked;
if (docked) {
// Detach window from the external devtools browser. It will lead to
// the browser object's close and delete. Remove observer first.
TabStripModel* tabstrip_model = browser_->tabstrip_model();
tabstrip_model->DetachTabContentsAt(
tabstrip_model->GetIndexOfTabContents(tab_contents_));
browser_ = NULL;
} else {
// Update inspected window to hide split and reset it.
BrowserWindow* inspected_window = GetInspectedBrowserWindow();
if (inspected_window) {
inspected_window->UpdateDevTools();
inspected_window = NULL;
}
}
Show(DEVTOOLS_TOGGLE_ACTION_NONE);
}
RenderViewHost* DevToolsWindow::GetRenderViewHost() {
return tab_contents_->render_view_host();
}
void DevToolsWindow::CreateDevToolsBrowser() {
// TODO(pfeldman): Make browser's getter for this key static.
std::string wp_key;
wp_key.append(prefs::kBrowserWindowPlacement);
wp_key.append("_");
wp_key.append(kDevToolsApp);
PrefService* prefs = g_browser_process->local_state();
if (!prefs->FindPreference(wp_key.c_str())) {
prefs->RegisterDictionaryPref(wp_key.c_str());
}
const DictionaryValue* wp_pref = prefs->GetDictionary(wp_key.c_str());
if (!wp_pref) {
DictionaryValue* defaults = prefs->GetMutableDictionary(wp_key.c_str());
defaults->SetInteger("left", 100);
defaults->SetInteger("top", 100);
defaults->SetInteger("right", 740);
defaults->SetInteger("bottom", 740);
defaults->SetBoolean("maximized", false);
defaults->SetBoolean("always_on_top", false);
}
browser_ = Browser::CreateForDevTools(profile_);
browser_->tabstrip_model()->AddTabContents(
tab_contents_, -1, PageTransition::START_PAGE,
TabStripModel::ADD_SELECTED);
}
BrowserWindow* DevToolsWindow::GetInspectedBrowserWindow() {
for (BrowserList::const_iterator it = BrowserList::begin();
it != BrowserList::end(); ++it) {
Browser* browser = *it;
for (int i = 0; i < browser->tab_count(); ++i) {
TabContents* tab_contents = browser->GetTabContentsAt(i);
if (tab_contents == inspected_tab_) {
return browser->window();
}
}
}
return NULL;
}
void DevToolsWindow::SetAttachedWindow() {
tab_contents_->render_view_host()->
ExecuteJavascriptInWebFrame(
L"", docked_ ? L"WebInspector.setAttachedWindow(true);" :
L"WebInspector.setAttachedWindow(false);");
}
void DevToolsWindow::AddDevToolsExtensionsToClient() {
if (inspected_tab_) {
FundamentalValue tabId(inspected_tab_->controller().session_id().id());
CallClientFunction(L"WebInspector.setInspectedTabId", tabId);
}
ListValue results;
const ExtensionsService* extension_service = tab_contents_->profile()->
GetOriginalProfile()->GetExtensionsService();
const ExtensionList* extensions = extension_service->extensions();
for (ExtensionList::const_iterator extension = extensions->begin();
extension != extensions->end(); ++extension) {
if ((*extension)->devtools_url().is_empty())
continue;
DictionaryValue* extension_info = new DictionaryValue();
extension_info->Set("startPage",
new StringValue((*extension)->devtools_url().spec()));
results.Append(extension_info);
}
CallClientFunction(L"WebInspector.addExtensions", results);
}
void DevToolsWindow::CallClientFunction(const std::wstring& function_name,
const Value& arg) {
std::string json;
base::JSONWriter::Write(&arg, false, &json);
std::wstring javascript = function_name + L"(" + UTF8ToWide(json) + L");";
tab_contents_->render_view_host()->
ExecuteJavascriptInWebFrame(L"", javascript);
}
void DevToolsWindow::Observe(NotificationType type,
const NotificationSource& source,
const NotificationDetails& details) {
if (type == NotificationType::LOAD_STOP && !is_loaded_) {
SetAttachedWindow();
is_loaded_ = true;
UpdateTheme();
DoAction();
AddDevToolsExtensionsToClient();
} else if (type == NotificationType::TAB_CLOSING) {
if (Source<NavigationController>(source).ptr() ==
&tab_contents_->controller()) {
// This happens when browser closes all of its tabs as a result
// of window.Close event.
// Notify manager that this DevToolsClientHost no longer exists and
// initiate self-destuct here.
NotifyCloseListener();
delete this;
}
} else if (type == NotificationType::BROWSER_THEME_CHANGED) {
UpdateTheme();
}
}
void DevToolsWindow::ScheduleAction(DevToolsToggleAction action) {
action_on_load_ = action;
if (is_loaded_)
DoAction();
}
void DevToolsWindow::DoAction() {
// TODO: these messages should be pushed through the WebKit API instead.
switch (action_on_load_) {
case DEVTOOLS_TOGGLE_ACTION_SHOW_CONSOLE:
tab_contents_->render_view_host()->
ExecuteJavascriptInWebFrame(L"", L"WebInspector.showConsole();");
break;
case DEVTOOLS_TOGGLE_ACTION_INSPECT:
tab_contents_->render_view_host()->
ExecuteJavascriptInWebFrame(
L"", L"WebInspector.toggleSearchingForNode();");
case DEVTOOLS_TOGGLE_ACTION_NONE:
// Do nothing.
break;
default:
NOTREACHED();
}
action_on_load_ = DEVTOOLS_TOGGLE_ACTION_NONE;
}
std::string SkColorToRGBAString(SkColor color) {
// We convert the alpha using DoubleToString because StringPrintf will use
// locale specific formatters (e.g., use , instead of . in German).
return StringPrintf("rgba(%d,%d,%d,%s)", SkColorGetR(color),
SkColorGetG(color), SkColorGetB(color),
base::DoubleToString(SkColorGetA(color) / 255.0).c_str());
}
GURL DevToolsWindow::GetDevToolsUrl() {
BrowserThemeProvider* tp = profile_->GetThemeProvider();
CHECK(tp);
SkColor color_toolbar =
tp->GetColor(BrowserThemeProvider::COLOR_TOOLBAR);
SkColor color_tab_text =
tp->GetColor(BrowserThemeProvider::COLOR_BOOKMARK_TEXT);
std::string url_string = StringPrintf(
"%sdevtools.html?docked=%s&toolbar_color=%s&text_color=%s",
chrome::kChromeUIDevToolsURL,
docked_ ? "true" : "false",
SkColorToRGBAString(color_toolbar).c_str(),
SkColorToRGBAString(color_tab_text).c_str());
return GURL(url_string);
}
void DevToolsWindow::UpdateTheme() {
BrowserThemeProvider* tp = profile_->GetThemeProvider();
CHECK(tp);
SkColor color_toolbar =
tp->GetColor(BrowserThemeProvider::COLOR_TOOLBAR);
SkColor color_tab_text =
tp->GetColor(BrowserThemeProvider::COLOR_BOOKMARK_TEXT);
std::string command = StringPrintf(
"WebInspector.setToolbarColors(\"%s\", \"%s\")",
SkColorToRGBAString(color_toolbar).c_str(),
SkColorToRGBAString(color_tab_text).c_str());
tab_contents_->render_view_host()->
ExecuteJavascriptInWebFrame(L"", UTF8ToWide(command));
}
bool DevToolsWindow::PreHandleKeyboardEvent(
const NativeWebKeyboardEvent& event, bool* is_keyboard_shortcut) {
if (docked_) {
BrowserWindow* inspected_window = GetInspectedBrowserWindow();
if (inspected_window)
return inspected_window->PreHandleKeyboardEvent(
event, is_keyboard_shortcut);
}
return false;
}
void DevToolsWindow::HandleKeyboardEvent(const NativeWebKeyboardEvent& event) {
if (docked_) {
BrowserWindow* inspected_window = GetInspectedBrowserWindow();
if (inspected_window)
inspected_window->HandleKeyboardEvent(event);
}
}
<|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 "chrome/browser/net/metadata_url_request.h"
#include "base/file_path.h"
#include "base/message_loop.h"
#include "build/build_config.h"
#include "chrome/browser/parsers/metadata_parser_manager.h"
#include "chrome/browser/parsers/metadata_parser.h"
#include "chrome/common/url_constants.h"
#include "net/base/io_buffer.h"
#include "net/base/net_util.h"
#include "net/url_request/url_request.h"
#include "net/url_request/url_request_job.h"
namespace {
const char kMetadataScheme[] = "metadata";
class MetadataRequestHandler : public URLRequestJob {
public:
explicit MetadataRequestHandler(URLRequest* request);
static URLRequestJob* Factory(URLRequest* request, const std::string& scheme);
// URLRequestJob implementation.
virtual void Start();
virtual void Kill();
virtual bool ReadRawData(net::IOBuffer* buf, int buf_size, int *bytes_read);
virtual bool GetMimeType(std::string* mime_type) const;
private:
~MetadataRequestHandler();
void StartAsync();
std::string result_;
bool parsed;
int data_offset_;
DISALLOW_COPY_AND_ASSIGN(MetadataRequestHandler);
};
MetadataRequestHandler::MetadataRequestHandler(URLRequest* request)
: URLRequestJob(request),
data_offset_(0) {
parsed = false;
}
MetadataRequestHandler::~MetadataRequestHandler() {
}
URLRequestJob* MetadataRequestHandler::Factory(URLRequest* request,
const std::string& scheme) {
return new MetadataRequestHandler(request);
}
void MetadataRequestHandler::Start() {
// Start reading asynchronously so that all error reporting and data
// callbacks happen as they would for network requests.
MessageLoop::current()->PostTask(FROM_HERE, NewRunnableMethod(
this, &MetadataRequestHandler::StartAsync));
}
void MetadataRequestHandler::Kill() {
}
bool MetadataRequestHandler::ReadRawData(net::IOBuffer* buf, int buf_size,
int *bytes_read) {
FilePath path;
if (!request()->url().is_valid()) {
return false;
}
if (!net::FileURLToFilePath(request()->url(), &path)) {
return false;
}
if (!parsed) {
MetadataParserManager* manager = MetadataParserManager::Get();
scoped_ptr<MetadataParser> parser(manager->GetParserForFile(path));
if (parser != NULL) {
result_ = "{\n";
parser->Parse();
MetadataPropertyIterator *iter = parser->GetPropertyIterator();
while (!iter->IsEnd()) {
std::string key;
std::string value;
if (iter->GetNext(&key, &value)) {
result_ += "\"";
result_ += key;
result_ += "\":";
result_ += "\"";
result_ += value;
result_ += "\",\n";
} else {
break;
}
}
result_ += "}";
delete iter;
} else {
result_ = "{}";
}
parsed = true;
}
int remaining = static_cast<int>(result_.size()) - data_offset_;
if (buf_size > remaining)
buf_size = remaining;
if (buf_size > 0) {
memcpy(buf->data(), &result_[data_offset_], buf_size);
data_offset_ += buf_size;
}
*bytes_read = buf_size;
return true;
}
bool MetadataRequestHandler::GetMimeType(std::string* mime_type) const {
*mime_type = "application/json";
return true;
}
void MetadataRequestHandler::StartAsync() {
NotifyHeadersComplete();
}
} // namespace
void RegisterMetadataURLRequestHandler() {
#if defined(OS_CHROMEOS)
URLRequest::RegisterProtocolFactory(chrome::kMetadataScheme,
&MetadataRequestHandler::Factory);
#endif
}
<commit_msg>Try to fix CrOS build.<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 "chrome/browser/net/metadata_url_request.h"
#include "base/file_path.h"
#include "base/message_loop.h"
#include "build/build_config.h"
#include "chrome/browser/parsers/metadata_parser_manager.h"
#include "chrome/browser/parsers/metadata_parser.h"
#include "chrome/common/url_constants.h"
#include "net/base/io_buffer.h"
#include "net/base/net_util.h"
#include "net/url_request/url_request.h"
#include "net/url_request/url_request_job.h"
namespace {
class MetadataRequestHandler : public URLRequestJob {
public:
explicit MetadataRequestHandler(URLRequest* request);
static URLRequestJob* Factory(URLRequest* request, const std::string& scheme);
// URLRequestJob implementation.
virtual void Start();
virtual void Kill();
virtual bool ReadRawData(net::IOBuffer* buf, int buf_size, int *bytes_read);
virtual bool GetMimeType(std::string* mime_type) const;
private:
~MetadataRequestHandler();
void StartAsync();
std::string result_;
bool parsed;
int data_offset_;
DISALLOW_COPY_AND_ASSIGN(MetadataRequestHandler);
};
MetadataRequestHandler::MetadataRequestHandler(URLRequest* request)
: URLRequestJob(request),
data_offset_(0) {
parsed = false;
}
MetadataRequestHandler::~MetadataRequestHandler() {
}
URLRequestJob* MetadataRequestHandler::Factory(URLRequest* request,
const std::string& scheme) {
return new MetadataRequestHandler(request);
}
void MetadataRequestHandler::Start() {
// Start reading asynchronously so that all error reporting and data
// callbacks happen as they would for network requests.
MessageLoop::current()->PostTask(FROM_HERE, NewRunnableMethod(
this, &MetadataRequestHandler::StartAsync));
}
void MetadataRequestHandler::Kill() {
}
bool MetadataRequestHandler::ReadRawData(net::IOBuffer* buf, int buf_size,
int *bytes_read) {
FilePath path;
if (!request()->url().is_valid()) {
return false;
}
if (!net::FileURLToFilePath(request()->url(), &path)) {
return false;
}
if (!parsed) {
MetadataParserManager* manager = MetadataParserManager::Get();
scoped_ptr<MetadataParser> parser(manager->GetParserForFile(path));
if (parser != NULL) {
result_ = "{\n";
parser->Parse();
MetadataPropertyIterator *iter = parser->GetPropertyIterator();
while (!iter->IsEnd()) {
std::string key;
std::string value;
if (iter->GetNext(&key, &value)) {
result_ += "\"";
result_ += key;
result_ += "\":";
result_ += "\"";
result_ += value;
result_ += "\",\n";
} else {
break;
}
}
result_ += "}";
delete iter;
} else {
result_ = "{}";
}
parsed = true;
}
int remaining = static_cast<int>(result_.size()) - data_offset_;
if (buf_size > remaining)
buf_size = remaining;
if (buf_size > 0) {
memcpy(buf->data(), &result_[data_offset_], buf_size);
data_offset_ += buf_size;
}
*bytes_read = buf_size;
return true;
}
bool MetadataRequestHandler::GetMimeType(std::string* mime_type) const {
*mime_type = "application/json";
return true;
}
void MetadataRequestHandler::StartAsync() {
NotifyHeadersComplete();
}
} // namespace
void RegisterMetadataURLRequestHandler() {
#if defined(OS_CHROMEOS)
URLRequest::RegisterProtocolFactory(chrome::kMetadataScheme,
&MetadataRequestHandler::Factory);
#endif
}
<|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 "chrome/browser/task_manager.h"
#include "app/l10n_util.h"
#include "base/file_path.h"
#include "chrome/browser/browser.h"
#include "chrome/browser/browser_window.h"
#include "chrome/browser/extensions/crashed_extension_infobar.h"
#include "chrome/browser/extensions/extension_browsertest.h"
#include "chrome/browser/tab_contents/infobar_delegate.h"
#include "chrome/browser/tab_contents/tab_contents.h"
#include "chrome/common/extensions/extension.h"
#include "chrome/common/page_transition_types.h"
#include "chrome/test/in_process_browser_test.h"
#include "chrome/test/ui_test_utils.h"
#include "grit/generated_resources.h"
#include "testing/gtest/include/gtest/gtest.h"
namespace {
const FilePath::CharType* kTitle1File = FILE_PATH_LITERAL("title1.html");
class ResourceChangeObserver : public TaskManagerModelObserver {
public:
ResourceChangeObserver(const TaskManagerModel* model,
int target_resource_count)
: model_(model),
target_resource_count_(target_resource_count) {
}
virtual void OnModelChanged() {
OnResourceChange();
}
virtual void OnItemsChanged(int start, int length) {
OnResourceChange();
}
virtual void OnItemsAdded(int start, int length) {
OnResourceChange();
}
virtual void OnItemsRemoved(int start, int length) {
OnResourceChange();
}
private:
void OnResourceChange() {
if (model_->ResourceCount() == target_resource_count_)
MessageLoopForUI::current()->Quit();
}
const TaskManagerModel* model_;
const int target_resource_count_;
};
} // namespace
class TaskManagerBrowserTest : public ExtensionBrowserTest {
public:
TaskManagerModel* model() const {
return TaskManager::GetInstance()->model();
}
void WaitForResourceChange(int target_count) {
if (model()->ResourceCount() == target_count)
return;
ResourceChangeObserver observer(model(), target_count);
model()->AddObserver(&observer);
ui_test_utils::RunMessageLoop();
model()->RemoveObserver(&observer);
}
};
// Regression test for http://crbug.com/13361
IN_PROC_BROWSER_TEST_F(TaskManagerBrowserTest, ShutdownWhileOpen) {
browser()->window()->ShowTaskManager();
}
IN_PROC_BROWSER_TEST_F(TaskManagerBrowserTest, NoticeTabContentsChanges) {
EXPECT_EQ(0, model()->ResourceCount());
// Show the task manager. This populates the model, and helps with debugging
// (you see the task manager).
browser()->window()->ShowTaskManager();
// Browser and the New Tab Page.
EXPECT_EQ(2, model()->ResourceCount());
// Open a new tab and make sure we notice that.
GURL url(ui_test_utils::GetTestUrl(FilePath(FilePath::kCurrentDirectory),
FilePath(kTitle1File)));
browser()->AddTabWithURL(url, GURL(), PageTransition::TYPED,
true, 0, false, NULL);
WaitForResourceChange(3);
// Close the tab and verify that we notice.
TabContents* first_tab = browser()->GetTabContentsAt(0);
ASSERT_TRUE(first_tab);
browser()->CloseTabContents(first_tab);
WaitForResourceChange(2);
}
#if defined(OS_WIN)
// http://crbug.com/31663
#define NoticeExtensionChanges DISABLED_NoticeExtensionChanges
#endif
IN_PROC_BROWSER_TEST_F(TaskManagerBrowserTest, NoticeExtensionChanges) {
EXPECT_EQ(0, model()->ResourceCount());
// Show the task manager. This populates the model, and helps with debugging
// (you see the task manager).
browser()->window()->ShowTaskManager();
// Browser and the New Tab Page.
EXPECT_EQ(2, model()->ResourceCount());
// Loading an extension should result in a new resource being
// created for it.
ASSERT_TRUE(LoadExtension(
test_data_dir_.AppendASCII("common").AppendASCII("one_in_shelf")));
WaitForResourceChange(3);
// Make sure we also recognize extensions with just background pages.
ASSERT_TRUE(LoadExtension(
test_data_dir_.AppendASCII("common").AppendASCII("background_page")));
WaitForResourceChange(4);
}
IN_PROC_BROWSER_TEST_F(TaskManagerBrowserTest, KillExtension) {
// Show the task manager. This populates the model, and helps with debugging
// (you see the task manager).
browser()->window()->ShowTaskManager();
ASSERT_TRUE(LoadExtension(
test_data_dir_.AppendASCII("common").AppendASCII("background_page")));
// Wait until we see the loaded extension in the task manager (the three
// resources are: the browser process, New Tab Page, and the extension).
WaitForResourceChange(3);
EXPECT_TRUE(model()->GetResourceExtension(0) == NULL);
EXPECT_TRUE(model()->GetResourceExtension(1) == NULL);
ASSERT_TRUE(model()->GetResourceExtension(2) != NULL);
// Kill the extension process and make sure we notice it.
TaskManager::GetInstance()->KillProcess(2);
WaitForResourceChange(2);
}
IN_PROC_BROWSER_TEST_F(TaskManagerBrowserTest, KillExtensionAndReload) {
// Show the task manager. This populates the model, and helps with debugging
// (you see the task manager).
browser()->window()->ShowTaskManager();
ASSERT_TRUE(LoadExtension(
test_data_dir_.AppendASCII("common").AppendASCII("background_page")));
// Wait until we see the loaded extension in the task manager (the three
// resources are: the browser process, New Tab Page, and the extension).
WaitForResourceChange(3);
EXPECT_TRUE(model()->GetResourceExtension(0) == NULL);
EXPECT_TRUE(model()->GetResourceExtension(1) == NULL);
ASSERT_TRUE(model()->GetResourceExtension(2) != NULL);
// Kill the extension process and make sure we notice it.
TaskManager::GetInstance()->KillProcess(2);
WaitForResourceChange(2);
// Reload the extension using the "crashed extension" infobar while the task
// manager is still visible. Make sure we don't crash and the extension
// gets reloaded and noticed in the task manager.
TabContents* current_tab = browser()->GetSelectedTabContents();
ASSERT_EQ(1, current_tab->infobar_delegate_count());
InfoBarDelegate* delegate = current_tab->GetInfoBarDelegateAt(0);
CrashedExtensionInfoBarDelegate* crashed_delegate =
delegate->AsCrashedExtensionInfoBarDelegate();
ASSERT_TRUE(crashed_delegate);
crashed_delegate->Accept();
WaitForResourceChange(3);
}
// Regression test for http://crbug.com/18693.
IN_PROC_BROWSER_TEST_F(TaskManagerBrowserTest, ReloadExtension) {
// Show the task manager. This populates the model, and helps with debugging
// (you see the task manager).
browser()->window()->ShowTaskManager();
ASSERT_TRUE(LoadExtension(
test_data_dir_.AppendASCII("common").AppendASCII("background_page")));
// Wait until we see the loaded extension in the task manager (the three
// resources are: the browser process, New Tab Page, and the extension).
WaitForResourceChange(3);
EXPECT_TRUE(model()->GetResourceExtension(0) == NULL);
EXPECT_TRUE(model()->GetResourceExtension(1) == NULL);
ASSERT_TRUE(model()->GetResourceExtension(2) != NULL);
const Extension* extension = model()->GetResourceExtension(2);
// Reload the extension a few times and make sure our resource count
// doesn't increase.
ReloadExtension(extension->id());
WaitForResourceChange(3);
extension = model()->GetResourceExtension(2);
ReloadExtension(extension->id());
WaitForResourceChange(3);
extension = model()->GetResourceExtension(2);
ReloadExtension(extension->id());
WaitForResourceChange(3);
}
// Crashy, http://crbug.com/42301.
IN_PROC_BROWSER_TEST_F(TaskManagerBrowserTest,
DISABLED_PopulateWebCacheFields) {
EXPECT_EQ(0, model()->ResourceCount());
// Show the task manager. This populates the model, and helps with debugging
// (you see the task manager).
browser()->window()->ShowTaskManager();
// Browser and the New Tab Page.
EXPECT_EQ(2, model()->ResourceCount());
// Open a new tab and make sure we notice that.
GURL url(ui_test_utils::GetTestUrl(FilePath(FilePath::kCurrentDirectory),
FilePath(kTitle1File)));
browser()->AddTabWithURL(url, GURL(), PageTransition::TYPED,
true, 0, false, NULL);
WaitForResourceChange(3);
// Check that we get some value for the cache columns.
DCHECK_NE(model()->GetResourceWebCoreImageCacheSize(2),
l10n_util::GetString(IDS_TASK_MANAGER_NA_CELL_TEXT));
DCHECK_NE(model()->GetResourceWebCoreScriptsCacheSize(2),
l10n_util::GetString(IDS_TASK_MANAGER_NA_CELL_TEXT));
DCHECK_NE(model()->GetResourceWebCoreCSSCacheSize(2),
l10n_util::GetString(IDS_TASK_MANAGER_NA_CELL_TEXT));
}
<commit_msg>Disable crashy TaskManagerBrowserTest.ReloadExtension on Windows.<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 "chrome/browser/task_manager.h"
#include "app/l10n_util.h"
#include "base/file_path.h"
#include "chrome/browser/browser.h"
#include "chrome/browser/browser_window.h"
#include "chrome/browser/extensions/crashed_extension_infobar.h"
#include "chrome/browser/extensions/extension_browsertest.h"
#include "chrome/browser/tab_contents/infobar_delegate.h"
#include "chrome/browser/tab_contents/tab_contents.h"
#include "chrome/common/extensions/extension.h"
#include "chrome/common/page_transition_types.h"
#include "chrome/test/in_process_browser_test.h"
#include "chrome/test/ui_test_utils.h"
#include "grit/generated_resources.h"
#include "testing/gtest/include/gtest/gtest.h"
namespace {
const FilePath::CharType* kTitle1File = FILE_PATH_LITERAL("title1.html");
class ResourceChangeObserver : public TaskManagerModelObserver {
public:
ResourceChangeObserver(const TaskManagerModel* model,
int target_resource_count)
: model_(model),
target_resource_count_(target_resource_count) {
}
virtual void OnModelChanged() {
OnResourceChange();
}
virtual void OnItemsChanged(int start, int length) {
OnResourceChange();
}
virtual void OnItemsAdded(int start, int length) {
OnResourceChange();
}
virtual void OnItemsRemoved(int start, int length) {
OnResourceChange();
}
private:
void OnResourceChange() {
if (model_->ResourceCount() == target_resource_count_)
MessageLoopForUI::current()->Quit();
}
const TaskManagerModel* model_;
const int target_resource_count_;
};
} // namespace
class TaskManagerBrowserTest : public ExtensionBrowserTest {
public:
TaskManagerModel* model() const {
return TaskManager::GetInstance()->model();
}
void WaitForResourceChange(int target_count) {
if (model()->ResourceCount() == target_count)
return;
ResourceChangeObserver observer(model(), target_count);
model()->AddObserver(&observer);
ui_test_utils::RunMessageLoop();
model()->RemoveObserver(&observer);
}
};
// Regression test for http://crbug.com/13361
IN_PROC_BROWSER_TEST_F(TaskManagerBrowserTest, ShutdownWhileOpen) {
browser()->window()->ShowTaskManager();
}
IN_PROC_BROWSER_TEST_F(TaskManagerBrowserTest, NoticeTabContentsChanges) {
EXPECT_EQ(0, model()->ResourceCount());
// Show the task manager. This populates the model, and helps with debugging
// (you see the task manager).
browser()->window()->ShowTaskManager();
// Browser and the New Tab Page.
EXPECT_EQ(2, model()->ResourceCount());
// Open a new tab and make sure we notice that.
GURL url(ui_test_utils::GetTestUrl(FilePath(FilePath::kCurrentDirectory),
FilePath(kTitle1File)));
browser()->AddTabWithURL(url, GURL(), PageTransition::TYPED,
true, 0, false, NULL);
WaitForResourceChange(3);
// Close the tab and verify that we notice.
TabContents* first_tab = browser()->GetTabContentsAt(0);
ASSERT_TRUE(first_tab);
browser()->CloseTabContents(first_tab);
WaitForResourceChange(2);
}
#if defined(OS_WIN)
// http://crbug.com/31663
#define NoticeExtensionChanges DISABLED_NoticeExtensionChanges
#endif
IN_PROC_BROWSER_TEST_F(TaskManagerBrowserTest, NoticeExtensionChanges) {
EXPECT_EQ(0, model()->ResourceCount());
// Show the task manager. This populates the model, and helps with debugging
// (you see the task manager).
browser()->window()->ShowTaskManager();
// Browser and the New Tab Page.
EXPECT_EQ(2, model()->ResourceCount());
// Loading an extension should result in a new resource being
// created for it.
ASSERT_TRUE(LoadExtension(
test_data_dir_.AppendASCII("common").AppendASCII("one_in_shelf")));
WaitForResourceChange(3);
// Make sure we also recognize extensions with just background pages.
ASSERT_TRUE(LoadExtension(
test_data_dir_.AppendASCII("common").AppendASCII("background_page")));
WaitForResourceChange(4);
}
IN_PROC_BROWSER_TEST_F(TaskManagerBrowserTest, KillExtension) {
// Show the task manager. This populates the model, and helps with debugging
// (you see the task manager).
browser()->window()->ShowTaskManager();
ASSERT_TRUE(LoadExtension(
test_data_dir_.AppendASCII("common").AppendASCII("background_page")));
// Wait until we see the loaded extension in the task manager (the three
// resources are: the browser process, New Tab Page, and the extension).
WaitForResourceChange(3);
EXPECT_TRUE(model()->GetResourceExtension(0) == NULL);
EXPECT_TRUE(model()->GetResourceExtension(1) == NULL);
ASSERT_TRUE(model()->GetResourceExtension(2) != NULL);
// Kill the extension process and make sure we notice it.
TaskManager::GetInstance()->KillProcess(2);
WaitForResourceChange(2);
}
IN_PROC_BROWSER_TEST_F(TaskManagerBrowserTest, KillExtensionAndReload) {
// Show the task manager. This populates the model, and helps with debugging
// (you see the task manager).
browser()->window()->ShowTaskManager();
ASSERT_TRUE(LoadExtension(
test_data_dir_.AppendASCII("common").AppendASCII("background_page")));
// Wait until we see the loaded extension in the task manager (the three
// resources are: the browser process, New Tab Page, and the extension).
WaitForResourceChange(3);
EXPECT_TRUE(model()->GetResourceExtension(0) == NULL);
EXPECT_TRUE(model()->GetResourceExtension(1) == NULL);
ASSERT_TRUE(model()->GetResourceExtension(2) != NULL);
// Kill the extension process and make sure we notice it.
TaskManager::GetInstance()->KillProcess(2);
WaitForResourceChange(2);
// Reload the extension using the "crashed extension" infobar while the task
// manager is still visible. Make sure we don't crash and the extension
// gets reloaded and noticed in the task manager.
TabContents* current_tab = browser()->GetSelectedTabContents();
ASSERT_EQ(1, current_tab->infobar_delegate_count());
InfoBarDelegate* delegate = current_tab->GetInfoBarDelegateAt(0);
CrashedExtensionInfoBarDelegate* crashed_delegate =
delegate->AsCrashedExtensionInfoBarDelegate();
ASSERT_TRUE(crashed_delegate);
crashed_delegate->Accept();
WaitForResourceChange(3);
}
// Regression test for http://crbug.com/18693.
#if defined(OS_WIN)
// Crashy, http://crbug.com/42315.
#define MAYBE_ReloadExtension DISABLED_ReloadExtension
#else
#define MAYBE_ReloadExtension ReloadExtension
#endif
IN_PROC_BROWSER_TEST_F(TaskManagerBrowserTest, MAYBE_ReloadExtension) {
// Show the task manager. This populates the model, and helps with debugging
// (you see the task manager).
browser()->window()->ShowTaskManager();
ASSERT_TRUE(LoadExtension(
test_data_dir_.AppendASCII("common").AppendASCII("background_page")));
// Wait until we see the loaded extension in the task manager (the three
// resources are: the browser process, New Tab Page, and the extension).
WaitForResourceChange(3);
EXPECT_TRUE(model()->GetResourceExtension(0) == NULL);
EXPECT_TRUE(model()->GetResourceExtension(1) == NULL);
ASSERT_TRUE(model()->GetResourceExtension(2) != NULL);
const Extension* extension = model()->GetResourceExtension(2);
// Reload the extension a few times and make sure our resource count
// doesn't increase.
ReloadExtension(extension->id());
WaitForResourceChange(3);
extension = model()->GetResourceExtension(2);
ReloadExtension(extension->id());
WaitForResourceChange(3);
extension = model()->GetResourceExtension(2);
ReloadExtension(extension->id());
WaitForResourceChange(3);
}
// Crashy, http://crbug.com/42301.
IN_PROC_BROWSER_TEST_F(TaskManagerBrowserTest,
DISABLED_PopulateWebCacheFields) {
EXPECT_EQ(0, model()->ResourceCount());
// Show the task manager. This populates the model, and helps with debugging
// (you see the task manager).
browser()->window()->ShowTaskManager();
// Browser and the New Tab Page.
EXPECT_EQ(2, model()->ResourceCount());
// Open a new tab and make sure we notice that.
GURL url(ui_test_utils::GetTestUrl(FilePath(FilePath::kCurrentDirectory),
FilePath(kTitle1File)));
browser()->AddTabWithURL(url, GURL(), PageTransition::TYPED,
true, 0, false, NULL);
WaitForResourceChange(3);
// Check that we get some value for the cache columns.
DCHECK_NE(model()->GetResourceWebCoreImageCacheSize(2),
l10n_util::GetString(IDS_TASK_MANAGER_NA_CELL_TEXT));
DCHECK_NE(model()->GetResourceWebCoreScriptsCacheSize(2),
l10n_util::GetString(IDS_TASK_MANAGER_NA_CELL_TEXT));
DCHECK_NE(model()->GetResourceWebCoreCSSCacheSize(2),
l10n_util::GetString(IDS_TASK_MANAGER_NA_CELL_TEXT));
}
<|endoftext|>
|
<commit_before>// Copyright 2013 The Chromium Authors. All rights reserved.
// Use of this source code is governed by a BSD-style license that can be
// found in the LICENSE file.
#include "chrome/browser/ui/webui/inline_login_ui.h"
#include "base/bind.h"
#include "base/command_line.h"
#include "base/memory/scoped_ptr.h"
#include "base/strings/string_number_conversions.h"
#include "base/strings/string_util.h"
#include "base/strings/stringprintf.h"
#include "base/values.h"
#include "chrome/browser/browser_process.h"
#include "chrome/browser/extensions/tab_helper.h"
#include "chrome/browser/profiles/profile.h"
#include "chrome/browser/signin/signin_global_error.h"
#include "chrome/browser/signin/signin_manager_cookie_helper.h"
#include "chrome/browser/signin/signin_names_io_thread.h"
#include "chrome/browser/signin/signin_promo.h"
#include "chrome/browser/signin/token_service.h"
#include "chrome/browser/signin/token_service_factory.h"
#include "chrome/browser/sync/profile_sync_service.h"
#include "chrome/browser/sync/profile_sync_service_factory.h"
#include "chrome/browser/ui/browser_finder.h"
#include "chrome/browser/ui/sync/one_click_signin_sync_starter.h"
#include "chrome/browser/ui/tabs/tab_strip_model.h"
#include "chrome/common/chrome_switches.h"
#include "chrome/common/url_constants.h"
#include "content/public/browser/storage_partition.h"
#include "content/public/browser/web_contents.h"
#include "content/public/browser/web_ui.h"
#include "content/public/browser/web_ui_data_source.h"
#include "content/public/browser/web_ui_message_handler.h"
#include "google_apis/gaia/gaia_switches.h"
#include "google_apis/gaia/gaia_urls.h"
#include "grit/browser_resources.h"
#include "net/base/escape.h"
#include "net/base/url_util.h"
#if defined(OS_CHROMEOS)
#include "chrome/browser/chromeos/login/oauth2_token_fetcher.h"
#endif
namespace {
content::WebUIDataSource* CreateWebUIDataSource() {
content::WebUIDataSource* source =
content::WebUIDataSource::Create(chrome::kChromeUIInlineLoginHost);
source->SetUseJsonJSFormatV2();
source->SetJsonPath("strings.js");
source->SetDefaultResource(IDR_INLINE_LOGIN_HTML);
source->AddResourcePath("inline_login.css", IDR_INLINE_LOGIN_CSS);
source->AddResourcePath("inline_login.js", IDR_INLINE_LOGIN_JS);
return source;
};
#if defined(OS_CHROMEOS)
class InlineLoginUIOAuth2Delegate
: public chromeos::OAuth2TokenFetcher::Delegate {
public:
explicit InlineLoginUIOAuth2Delegate(content::WebUI* web_ui)
: web_ui_(web_ui) {}
virtual ~InlineLoginUIOAuth2Delegate() {}
// OAuth2TokenFetcher::Delegate overrides:
virtual void OnOAuth2TokensAvailable(
const GaiaAuthConsumer::ClientOAuthResult& oauth2_tokens) OVERRIDE {
// Closes sign-in dialog before update token service. Token service update
// might trigger a permission dialog and if this dialog does not close,
// a DCHECK would be triggered because attempting to activate a window
// while there is a modal dialog.
web_ui_->CallJavascriptFunction("inline.login.closeDialog");
Profile* profile = Profile::FromWebUI(web_ui_);
TokenService* token_service =
TokenServiceFactory::GetForProfile(profile);
token_service->UpdateCredentialsWithOAuth2(oauth2_tokens);
}
virtual void OnOAuth2TokensFetchFailed() OVERRIDE {
LOG(ERROR) << "Failed to fetch oauth2 token with inline login.";
web_ui_->CallJavascriptFunction("inline.login.handleOAuth2TokenFailure");
}
private:
content::WebUI* web_ui_;
};
#endif // OS_CHROMEOS
class InlineLoginUIHandler : public content::WebUIMessageHandler {
public:
explicit InlineLoginUIHandler(Profile* profile)
: profile_(profile), weak_factory_(this), choose_what_to_sync_(false) {}
virtual ~InlineLoginUIHandler() {}
// content::WebUIMessageHandler overrides:
virtual void RegisterMessages() OVERRIDE {
web_ui()->RegisterMessageCallback("initialize",
base::Bind(&InlineLoginUIHandler::HandleInitialize,
base::Unretained(this)));
web_ui()->RegisterMessageCallback("completeLogin",
base::Bind(&InlineLoginUIHandler::HandleCompleteLogin,
base::Unretained(this)));
}
private:
// Enum for gaia auth mode, must match AuthMode defined in
// chrome/browser/resources/gaia_auth_host/gaia_auth_host.js.
enum AuthMode {
kDefaultAuthMode = 0,
kOfflineAuthMode = 1,
kInlineAuthMode = 2
};
void LoadAuthExtension() {
base::DictionaryValue params;
const std::string& app_locale = g_browser_process->GetApplicationLocale();
params.SetString("hl", app_locale);
GaiaUrls* gaiaUrls = GaiaUrls::GetInstance();
params.SetString("gaiaUrl", gaiaUrls->gaia_url().spec());
bool enable_inline = CommandLine::ForCurrentProcess()->HasSwitch(
switches::kEnableInlineSignin);
params.SetInteger("authMode",
enable_inline ? kInlineAuthMode : kDefaultAuthMode);
// Set parameters specific for inline signin flow.
#if !defined(OS_CHROMEOS)
if (enable_inline) {
// Set continueUrl param for the inline sign in flow. It should point to
// the oauth2 auth code URL so that later we can grab the auth code from
// the cookie jar of the embedded webview.
std::string scope = net::EscapeUrlEncodedData(
gaiaUrls->oauth1_login_scope(), true);
std::string client_id = net::EscapeUrlEncodedData(
gaiaUrls->oauth2_chrome_client_id(), true);
std::string encoded_continue_params = base::StringPrintf(
"?scope=%s&client_id=%s", scope.c_str(), client_id.c_str());
const GURL& current_url = web_ui()->GetWebContents()->GetURL();
signin::Source source = signin::GetSourceForPromoURL(current_url);
if (source != signin::SOURCE_UNKNOWN) {
params.SetString("service", "chromiumsync");
base::StringAppendF(
&encoded_continue_params, "&%s=%d", "source",
static_cast<int>(source));
}
params.SetString("continueUrl",
gaiaUrls->client_login_to_oauth2_url().Resolve(
encoded_continue_params).spec());
}
#endif
web_ui()->CallJavascriptFunction("inline.login.loadAuthExtension", params);
}
// JS callback:
void HandleInitialize(const base::ListValue* args) {
LoadAuthExtension();
}
void HandleCompleteLogin(const base::ListValue* args) {
// TODO(guohui, xiyuan): we should investigate if it is possible to unify
// the signin-with-cookies flow across ChromeOS and Chrome.
#if defined(OS_CHROMEOS)
oauth2_delegate_.reset(new InlineLoginUIOAuth2Delegate(web_ui()));
oauth2_token_fetcher_.reset(new chromeos::OAuth2TokenFetcher(
oauth2_delegate_.get(), profile_->GetRequestContext()));
oauth2_token_fetcher_->StartExchangeFromCookies();
#elif !defined(OS_ANDROID)
const base::DictionaryValue* dict = NULL;
string16 email;
string16 password;
if (!args->GetDictionary(0, &dict) || !dict ||
!dict->GetString("email", &email) ||
!dict->GetString("password", &password)) {
NOTREACHED();
return;
}
dict->GetBoolean("chooseWhatToSync", &choose_what_to_sync_);
content::WebContents* web_contents = web_ui()->GetWebContents();
content::StoragePartition* partition =
content::BrowserContext::GetStoragePartitionForSite(
web_contents->GetBrowserContext(),
GURL("chrome-guest://mfffpogegjflfpflabcdkioaeobkgjik/?"));
scoped_refptr<SigninManagerCookieHelper> cookie_helper(
new SigninManagerCookieHelper(partition->GetURLRequestContext()));
cookie_helper->StartFetchingCookiesOnUIThread(
GURL(GaiaUrls::GetInstance()->client_login_to_oauth2_url()),
base::Bind(&InlineLoginUIHandler::OnGaiaCookiesFetched,
weak_factory_.GetWeakPtr(), email, password));
#endif
}
void OnGaiaCookiesFetched(
const string16 email,
const string16 password,
const net::CookieList& cookie_list) {
net::CookieList::const_iterator it;
for (it = cookie_list.begin(); it != cookie_list.end(); ++it) {
if (it->Name() == "oauth_code") {
content::WebContents* contents = web_ui()->GetWebContents();
ProfileSyncService* sync_service =
ProfileSyncServiceFactory::GetForProfile(profile_);
const GURL& current_url = contents->GetURL();
signin::Source source = signin::GetSourceForPromoURL(current_url);
OneClickSigninSyncStarter::StartSyncMode start_mode =
source == signin::SOURCE_SETTINGS || choose_what_to_sync_ ?
(SigninGlobalError::GetForProfile(profile_)->HasMenuItem() &&
sync_service && sync_service->HasSyncSetupCompleted()) ?
OneClickSigninSyncStarter::SHOW_SETTINGS_WITHOUT_CONFIGURE :
OneClickSigninSyncStarter::CONFIGURE_SYNC_FIRST :
OneClickSigninSyncStarter::SYNC_WITH_DEFAULT_SETTINGS;
OneClickSigninSyncStarter::ConfirmationRequired confirmation_required =
source == signin::SOURCE_SETTINGS ||
source == signin::SOURCE_WEBSTORE_INSTALL ||
choose_what_to_sync_?
OneClickSigninSyncStarter::NO_CONFIRMATION :
OneClickSigninSyncStarter::CONFIRM_AFTER_SIGNIN;
// Call OneClickSigninSyncStarter to exchange oauth code for tokens.
// OneClickSigninSyncStarter will delete itself once the job is done.
new OneClickSigninSyncStarter(
profile_, NULL, "0" /* session_index 0 for the default user */,
UTF16ToASCII(email), UTF16ToASCII(password), it->Value(),
start_mode,
contents,
confirmation_required,
base::Bind(&InlineLoginUIHandler::SyncStarterCallback,
weak_factory_.GetWeakPtr()));
break;
}
}
web_ui()->CallJavascriptFunction("inline.login.closeDialog");
}
void SyncStarterCallback(OneClickSigninSyncStarter::SyncSetupResult result) {
content::WebContents* contents = web_ui()->GetWebContents();
const GURL& current_url = contents->GetURL();
bool auto_close = signin::IsAutoCloseEnabledInURL(current_url);
signin::Source source = signin::GetSourceForPromoURL(current_url);
if (auto_close) {
base::MessageLoop::current()->PostTask(
FROM_HERE,
base::Bind(
&InlineLoginUIHandler::CloseTab, weak_factory_.GetWeakPtr()));
} else if (source != signin::SOURCE_UNKNOWN &&
source != signin::SOURCE_SETTINGS &&
source != signin::SOURCE_WEBSTORE_INSTALL) {
// Redirect to NTP/Apps page and display a confirmation bubble.
// TODO(guohui): should redirect to the given continue url for webstore
// install flows.
GURL url(source == signin::SOURCE_APPS_PAGE_LINK ?
chrome::kChromeUIAppsURL : chrome::kChromeUINewTabURL);
content::OpenURLParams params(url,
content::Referrer(),
CURRENT_TAB,
content::PAGE_TRANSITION_AUTO_TOPLEVEL,
false);
contents->OpenURL(params);
}
}
void CloseTab() {
content::WebContents* tab = web_ui()->GetWebContents();
Browser* browser = chrome::FindBrowserWithWebContents(tab);
if (browser) {
TabStripModel* tab_strip_model = browser->tab_strip_model();
if (tab_strip_model) {
int index = tab_strip_model->GetIndexOfWebContents(tab);
if (index != TabStripModel::kNoTab) {
tab_strip_model->ExecuteContextMenuCommand(
index, TabStripModel::CommandCloseTab);
}
}
}
}
Profile* profile_;
base::WeakPtrFactory<InlineLoginUIHandler> weak_factory_;
bool choose_what_to_sync_;
#if defined(OS_CHROMEOS)
scoped_ptr<chromeos::OAuth2TokenFetcher> oauth2_token_fetcher_;
scoped_ptr<InlineLoginUIOAuth2Delegate> oauth2_delegate_;
#endif
DISALLOW_COPY_AND_ASSIGN(InlineLoginUIHandler);
};
} // namespace
InlineLoginUI::InlineLoginUI(content::WebUI* web_ui)
: WebDialogUI(web_ui),
auth_extension_(Profile::FromWebUI(web_ui)) {
Profile* profile = Profile::FromWebUI(web_ui);
content::WebUIDataSource::Add(profile, CreateWebUIDataSource());
web_ui->AddMessageHandler(new InlineLoginUIHandler(profile));
// Required for intercepting extension function calls when the page is loaded
// in a bubble (not a full tab, thus tab helpers are not registered
// automatically).
extensions::TabHelper::CreateForWebContents(web_ui->GetWebContents());
}
InlineLoginUI::~InlineLoginUI() {}
<commit_msg>Fix crash in inline flows for SAML users<commit_after>// Copyright 2013 The Chromium Authors. All rights reserved.
// Use of this source code is governed by a BSD-style license that can be
// found in the LICENSE file.
#include "chrome/browser/ui/webui/inline_login_ui.h"
#include "base/bind.h"
#include "base/command_line.h"
#include "base/memory/scoped_ptr.h"
#include "base/strings/string_number_conversions.h"
#include "base/strings/string_util.h"
#include "base/strings/stringprintf.h"
#include "base/values.h"
#include "chrome/browser/browser_process.h"
#include "chrome/browser/extensions/tab_helper.h"
#include "chrome/browser/profiles/profile.h"
#include "chrome/browser/signin/signin_global_error.h"
#include "chrome/browser/signin/signin_manager_cookie_helper.h"
#include "chrome/browser/signin/signin_names_io_thread.h"
#include "chrome/browser/signin/signin_promo.h"
#include "chrome/browser/signin/token_service.h"
#include "chrome/browser/signin/token_service_factory.h"
#include "chrome/browser/sync/profile_sync_service.h"
#include "chrome/browser/sync/profile_sync_service_factory.h"
#include "chrome/browser/ui/browser_finder.h"
#include "chrome/browser/ui/sync/one_click_signin_sync_starter.h"
#include "chrome/browser/ui/tabs/tab_strip_model.h"
#include "chrome/common/chrome_switches.h"
#include "chrome/common/url_constants.h"
#include "content/public/browser/storage_partition.h"
#include "content/public/browser/web_contents.h"
#include "content/public/browser/web_ui.h"
#include "content/public/browser/web_ui_data_source.h"
#include "content/public/browser/web_ui_message_handler.h"
#include "google_apis/gaia/gaia_switches.h"
#include "google_apis/gaia/gaia_urls.h"
#include "grit/browser_resources.h"
#include "net/base/escape.h"
#include "net/base/url_util.h"
#if defined(OS_CHROMEOS)
#include "chrome/browser/chromeos/login/oauth2_token_fetcher.h"
#endif
namespace {
content::WebUIDataSource* CreateWebUIDataSource() {
content::WebUIDataSource* source =
content::WebUIDataSource::Create(chrome::kChromeUIInlineLoginHost);
source->SetUseJsonJSFormatV2();
source->SetJsonPath("strings.js");
source->SetDefaultResource(IDR_INLINE_LOGIN_HTML);
source->AddResourcePath("inline_login.css", IDR_INLINE_LOGIN_CSS);
source->AddResourcePath("inline_login.js", IDR_INLINE_LOGIN_JS);
return source;
};
#if defined(OS_CHROMEOS)
class InlineLoginUIOAuth2Delegate
: public chromeos::OAuth2TokenFetcher::Delegate {
public:
explicit InlineLoginUIOAuth2Delegate(content::WebUI* web_ui)
: web_ui_(web_ui) {}
virtual ~InlineLoginUIOAuth2Delegate() {}
// OAuth2TokenFetcher::Delegate overrides:
virtual void OnOAuth2TokensAvailable(
const GaiaAuthConsumer::ClientOAuthResult& oauth2_tokens) OVERRIDE {
// Closes sign-in dialog before update token service. Token service update
// might trigger a permission dialog and if this dialog does not close,
// a DCHECK would be triggered because attempting to activate a window
// while there is a modal dialog.
web_ui_->CallJavascriptFunction("inline.login.closeDialog");
Profile* profile = Profile::FromWebUI(web_ui_);
TokenService* token_service =
TokenServiceFactory::GetForProfile(profile);
token_service->UpdateCredentialsWithOAuth2(oauth2_tokens);
}
virtual void OnOAuth2TokensFetchFailed() OVERRIDE {
LOG(ERROR) << "Failed to fetch oauth2 token with inline login.";
web_ui_->CallJavascriptFunction("inline.login.handleOAuth2TokenFailure");
}
private:
content::WebUI* web_ui_;
};
#endif // OS_CHROMEOS
class InlineLoginUIHandler : public content::WebUIMessageHandler {
public:
explicit InlineLoginUIHandler(Profile* profile)
: profile_(profile), weak_factory_(this), choose_what_to_sync_(false) {}
virtual ~InlineLoginUIHandler() {}
// content::WebUIMessageHandler overrides:
virtual void RegisterMessages() OVERRIDE {
web_ui()->RegisterMessageCallback("initialize",
base::Bind(&InlineLoginUIHandler::HandleInitialize,
base::Unretained(this)));
web_ui()->RegisterMessageCallback("completeLogin",
base::Bind(&InlineLoginUIHandler::HandleCompleteLogin,
base::Unretained(this)));
}
private:
// Enum for gaia auth mode, must match AuthMode defined in
// chrome/browser/resources/gaia_auth_host/gaia_auth_host.js.
enum AuthMode {
kDefaultAuthMode = 0,
kOfflineAuthMode = 1,
kInlineAuthMode = 2
};
void LoadAuthExtension() {
base::DictionaryValue params;
const std::string& app_locale = g_browser_process->GetApplicationLocale();
params.SetString("hl", app_locale);
GaiaUrls* gaiaUrls = GaiaUrls::GetInstance();
params.SetString("gaiaUrl", gaiaUrls->gaia_url().spec());
bool enable_inline = CommandLine::ForCurrentProcess()->HasSwitch(
switches::kEnableInlineSignin);
params.SetInteger("authMode",
enable_inline ? kInlineAuthMode : kDefaultAuthMode);
// Set parameters specific for inline signin flow.
#if !defined(OS_CHROMEOS)
if (enable_inline) {
// Set continueUrl param for the inline sign in flow. It should point to
// the oauth2 auth code URL so that later we can grab the auth code from
// the cookie jar of the embedded webview.
std::string scope = net::EscapeUrlEncodedData(
gaiaUrls->oauth1_login_scope(), true);
std::string client_id = net::EscapeUrlEncodedData(
gaiaUrls->oauth2_chrome_client_id(), true);
std::string encoded_continue_params = base::StringPrintf(
"?scope=%s&client_id=%s", scope.c_str(), client_id.c_str());
const GURL& current_url = web_ui()->GetWebContents()->GetURL();
signin::Source source = signin::GetSourceForPromoURL(current_url);
if (source != signin::SOURCE_UNKNOWN) {
params.SetString("service", "chromiumsync");
base::StringAppendF(
&encoded_continue_params, "&%s=%d", "source",
static_cast<int>(source));
}
params.SetString("continueUrl",
gaiaUrls->client_login_to_oauth2_url().Resolve(
encoded_continue_params).spec());
}
#endif
web_ui()->CallJavascriptFunction("inline.login.loadAuthExtension", params);
}
// JS callback:
void HandleInitialize(const base::ListValue* args) {
LoadAuthExtension();
}
void HandleCompleteLogin(const base::ListValue* args) {
// TODO(guohui, xiyuan): we should investigate if it is possible to unify
// the signin-with-cookies flow across ChromeOS and Chrome.
#if defined(OS_CHROMEOS)
oauth2_delegate_.reset(new InlineLoginUIOAuth2Delegate(web_ui()));
oauth2_token_fetcher_.reset(new chromeos::OAuth2TokenFetcher(
oauth2_delegate_.get(), profile_->GetRequestContext()));
oauth2_token_fetcher_->StartExchangeFromCookies();
#elif !defined(OS_ANDROID)
const base::DictionaryValue* dict = NULL;
string16 email;
string16 password;
if (!args->GetDictionary(0, &dict) || !dict ||
!dict->GetString("email", &email)) {
NOTREACHED();
return;
}
dict->GetString("password", &password);
dict->GetBoolean("chooseWhatToSync", &choose_what_to_sync_);
content::WebContents* web_contents = web_ui()->GetWebContents();
content::StoragePartition* partition =
content::BrowserContext::GetStoragePartitionForSite(
web_contents->GetBrowserContext(),
GURL("chrome-guest://mfffpogegjflfpflabcdkioaeobkgjik/?"));
scoped_refptr<SigninManagerCookieHelper> cookie_helper(
new SigninManagerCookieHelper(partition->GetURLRequestContext()));
cookie_helper->StartFetchingCookiesOnUIThread(
GURL(GaiaUrls::GetInstance()->client_login_to_oauth2_url()),
base::Bind(&InlineLoginUIHandler::OnGaiaCookiesFetched,
weak_factory_.GetWeakPtr(), email, password));
#endif
}
void OnGaiaCookiesFetched(
const string16 email,
const string16 password,
const net::CookieList& cookie_list) {
net::CookieList::const_iterator it;
for (it = cookie_list.begin(); it != cookie_list.end(); ++it) {
if (it->Name() == "oauth_code") {
content::WebContents* contents = web_ui()->GetWebContents();
ProfileSyncService* sync_service =
ProfileSyncServiceFactory::GetForProfile(profile_);
const GURL& current_url = contents->GetURL();
signin::Source source = signin::GetSourceForPromoURL(current_url);
OneClickSigninSyncStarter::StartSyncMode start_mode =
source == signin::SOURCE_SETTINGS || choose_what_to_sync_ ?
(SigninGlobalError::GetForProfile(profile_)->HasMenuItem() &&
sync_service && sync_service->HasSyncSetupCompleted()) ?
OneClickSigninSyncStarter::SHOW_SETTINGS_WITHOUT_CONFIGURE :
OneClickSigninSyncStarter::CONFIGURE_SYNC_FIRST :
OneClickSigninSyncStarter::SYNC_WITH_DEFAULT_SETTINGS;
OneClickSigninSyncStarter::ConfirmationRequired confirmation_required =
source == signin::SOURCE_SETTINGS ||
source == signin::SOURCE_WEBSTORE_INSTALL ||
choose_what_to_sync_?
OneClickSigninSyncStarter::NO_CONFIRMATION :
OneClickSigninSyncStarter::CONFIRM_AFTER_SIGNIN;
// Call OneClickSigninSyncStarter to exchange oauth code for tokens.
// OneClickSigninSyncStarter will delete itself once the job is done.
new OneClickSigninSyncStarter(
profile_, NULL, "0" /* session_index 0 for the default user */,
UTF16ToASCII(email), UTF16ToASCII(password), it->Value(),
start_mode,
contents,
confirmation_required,
base::Bind(&InlineLoginUIHandler::SyncStarterCallback,
weak_factory_.GetWeakPtr()));
break;
}
}
web_ui()->CallJavascriptFunction("inline.login.closeDialog");
}
void SyncStarterCallback(OneClickSigninSyncStarter::SyncSetupResult result) {
content::WebContents* contents = web_ui()->GetWebContents();
const GURL& current_url = contents->GetURL();
bool auto_close = signin::IsAutoCloseEnabledInURL(current_url);
signin::Source source = signin::GetSourceForPromoURL(current_url);
if (auto_close) {
base::MessageLoop::current()->PostTask(
FROM_HERE,
base::Bind(
&InlineLoginUIHandler::CloseTab, weak_factory_.GetWeakPtr()));
} else if (source != signin::SOURCE_UNKNOWN &&
source != signin::SOURCE_SETTINGS &&
source != signin::SOURCE_WEBSTORE_INSTALL) {
// Redirect to NTP/Apps page and display a confirmation bubble.
// TODO(guohui): should redirect to the given continue url for webstore
// install flows.
GURL url(source == signin::SOURCE_APPS_PAGE_LINK ?
chrome::kChromeUIAppsURL : chrome::kChromeUINewTabURL);
content::OpenURLParams params(url,
content::Referrer(),
CURRENT_TAB,
content::PAGE_TRANSITION_AUTO_TOPLEVEL,
false);
contents->OpenURL(params);
}
}
void CloseTab() {
content::WebContents* tab = web_ui()->GetWebContents();
Browser* browser = chrome::FindBrowserWithWebContents(tab);
if (browser) {
TabStripModel* tab_strip_model = browser->tab_strip_model();
if (tab_strip_model) {
int index = tab_strip_model->GetIndexOfWebContents(tab);
if (index != TabStripModel::kNoTab) {
tab_strip_model->ExecuteContextMenuCommand(
index, TabStripModel::CommandCloseTab);
}
}
}
}
Profile* profile_;
base::WeakPtrFactory<InlineLoginUIHandler> weak_factory_;
bool choose_what_to_sync_;
#if defined(OS_CHROMEOS)
scoped_ptr<chromeos::OAuth2TokenFetcher> oauth2_token_fetcher_;
scoped_ptr<InlineLoginUIOAuth2Delegate> oauth2_delegate_;
#endif
DISALLOW_COPY_AND_ASSIGN(InlineLoginUIHandler);
};
} // namespace
InlineLoginUI::InlineLoginUI(content::WebUI* web_ui)
: WebDialogUI(web_ui),
auth_extension_(Profile::FromWebUI(web_ui)) {
Profile* profile = Profile::FromWebUI(web_ui);
content::WebUIDataSource::Add(profile, CreateWebUIDataSource());
web_ui->AddMessageHandler(new InlineLoginUIHandler(profile));
// Required for intercepting extension function calls when the page is loaded
// in a bubble (not a full tab, thus tab helpers are not registered
// automatically).
extensions::TabHelper::CreateForWebContents(web_ui->GetWebContents());
}
InlineLoginUI::~InlineLoginUI() {}
<|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 "chrome/browser/views/browser_bubble.h"
#include "app/l10n_util_win.h"
#include "chrome/browser/views/frame/browser_view.h"
#include "views/widget/root_view.h"
#include "views/widget/widget_win.h"
#include "views/window/window.h"
class BubbleWidget : public views::WidgetWin {
public:
explicit BubbleWidget(BrowserBubble* bubble)
: bubble_(bubble), closed_(false) {
}
void Show(bool activate) {
if (activate)
ShowWindow(SW_SHOW);
else
views::WidgetWin::Show();
}
void Close() {
if (closed_)
return;
closed_ = true;
if (IsActive()) {
BrowserBubble::Delegate* delegate = bubble_->delegate();
if (delegate)
delegate->BubbleLostFocus(bubble_);
}
views::WidgetWin::Close();
}
void Hide() {
if (IsActive()) {
BrowserBubble::Delegate* delegate = bubble_->delegate();
if (delegate)
delegate->BubbleLostFocus(bubble_);
}
views::WidgetWin::Hide();
}
void OnActivate(UINT action, BOOL minimized, HWND window) {
BrowserBubble::Delegate* delegate = bubble_->delegate();
if (!delegate) {
if (action == WA_INACTIVE && !closed_) {
bubble_->DetachFromBrowser();
delete bubble_;
}
return;
}
if (action == WA_INACTIVE && !closed_) {
delegate->BubbleLostFocus(bubble_);
} else if (action == WA_ACTIVE) {
delegate->BubbleGotFocus(bubble_);
}
}
private:
bool closed_;
BrowserBubble* bubble_;
};
void BrowserBubble::InitPopup() {
// popup_ is a Widget, but we need to do some WidgetWin stuff first, then
// we'll assign it into popup_.
views::WidgetWin* pop = new BubbleWidget(this);
pop->set_window_style(WS_POPUP);
pop->Init(frame_native_view_, bounds_);
pop->SetContentsView(view_);
popup_ = pop;
Reposition();
AttachToBrowser();
}
void BrowserBubble::MovePopup(int x, int y, int w, int h) {
views::WidgetWin* pop = static_cast<views::WidgetWin*>(popup_);
pop->MoveWindow(x, y, w, h);
}
void BrowserBubble::Show(bool activate) {
if (visible_)
return;
BubbleWidget* pop = static_cast<BubbleWidget*>(popup_);
pop->Show(activate);
visible_ = true;
}
void BrowserBubble::Hide() {
if (!visible_)
return;
views::WidgetWin* pop = static_cast<views::WidgetWin*>(popup_);
pop->Hide();
visible_ = false;
}
<commit_msg>Mostly fixes black flashing that happens during popup resize.<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 "chrome/browser/views/browser_bubble.h"
#include "app/l10n_util_win.h"
#include "chrome/browser/views/frame/browser_view.h"
#include "views/widget/root_view.h"
#include "views/widget/widget_win.h"
#include "views/window/window.h"
class BubbleWidget : public views::WidgetWin {
public:
explicit BubbleWidget(BrowserBubble* bubble)
: bubble_(bubble), closed_(false) {
set_window_style(WS_POPUP | WS_CLIPCHILDREN);
set_window_ex_style(WS_EX_TOOLWINDOW);
}
void Show(bool activate) {
if (activate)
ShowWindow(SW_SHOW);
else
views::WidgetWin::Show();
}
void Close() {
if (closed_)
return;
closed_ = true;
if (IsActive()) {
BrowserBubble::Delegate* delegate = bubble_->delegate();
if (delegate)
delegate->BubbleLostFocus(bubble_);
}
views::WidgetWin::Close();
}
void Hide() {
if (IsActive()) {
BrowserBubble::Delegate* delegate = bubble_->delegate();
if (delegate)
delegate->BubbleLostFocus(bubble_);
}
views::WidgetWin::Hide();
}
void OnActivate(UINT action, BOOL minimized, HWND window) {
BrowserBubble::Delegate* delegate = bubble_->delegate();
if (!delegate) {
if (action == WA_INACTIVE && !closed_) {
bubble_->DetachFromBrowser();
delete bubble_;
}
return;
}
if (action == WA_INACTIVE && !closed_) {
delegate->BubbleLostFocus(bubble_);
} else if (action == WA_ACTIVE) {
delegate->BubbleGotFocus(bubble_);
}
}
private:
bool closed_;
BrowserBubble* bubble_;
};
void BrowserBubble::InitPopup() {
// popup_ is a Widget, but we need to do some WidgetWin stuff first, then
// we'll assign it into popup_.
views::WidgetWin* pop = new BubbleWidget(this);
pop->Init(frame_native_view_, bounds_);
pop->SetContentsView(view_);
popup_ = pop;
Reposition();
AttachToBrowser();
}
void BrowserBubble::MovePopup(int x, int y, int w, int h) {
views::WidgetWin* pop = static_cast<views::WidgetWin*>(popup_);
pop->SetBounds(gfx::Rect(x, y, w, h));
}
void BrowserBubble::Show(bool activate) {
if (visible_)
return;
BubbleWidget* pop = static_cast<BubbleWidget*>(popup_);
pop->Show(activate);
visible_ = true;
}
void BrowserBubble::Hide() {
if (!visible_)
return;
views::WidgetWin* pop = static_cast<views::WidgetWin*>(popup_);
pop->Hide();
visible_ = false;
}
<|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 "jingle/notifier/communicator/gaia_token_pre_xmpp_auth.h"
#include <algorithm>
#include "talk/base/socketaddress.h"
#include "talk/xmpp/constants.h"
#include "talk/xmpp/saslcookiemechanism.h"
namespace notifier {
namespace {
const char kGaiaAuthMechanism[] = "X-GOOGLE-TOKEN";
} // namespace
GaiaTokenPreXmppAuth::GaiaTokenPreXmppAuth(
const std::string& username,
const std::string& token,
const std::string& token_service)
: username_(username),
token_(token),
token_service_(token_service) { }
GaiaTokenPreXmppAuth::~GaiaTokenPreXmppAuth() { }
void GaiaTokenPreXmppAuth::StartPreXmppAuth(
const buzz::Jid& jid,
const talk_base::SocketAddress& server,
const talk_base::CryptString& pass,
const std::string& auth_cookie) {
SignalAuthDone();
}
bool GaiaTokenPreXmppAuth::IsAuthDone() const {
return true;
}
bool GaiaTokenPreXmppAuth::IsAuthorized() const {
return true;
}
bool GaiaTokenPreXmppAuth::HadError() const {
return false;
}
int GaiaTokenPreXmppAuth::GetError() const {
return 0;
}
buzz::CaptchaChallenge GaiaTokenPreXmppAuth::GetCaptchaChallenge() const {
return buzz::CaptchaChallenge();
}
std::string GaiaTokenPreXmppAuth::GetAuthCookie() const {
return std::string();
}
std::string GaiaTokenPreXmppAuth::ChooseBestSaslMechanism(
const std::vector<std::string> & mechanisms, bool encrypted) {
return (std::find(mechanisms.begin(),
mechanisms.end(), kGaiaAuthMechanism) !=
mechanisms.end()) ? kGaiaAuthMechanism : "";
}
buzz::SaslMechanism* GaiaTokenPreXmppAuth::CreateSaslMechanism(
const std::string& mechanism) {
if (mechanism != kGaiaAuthMechanism)
return NULL;
return new buzz::SaslCookieMechanism(
kGaiaAuthMechanism, username_, token_, token_service_);
}
} // namespace notifier
<commit_msg>Fixed bug where sync notifications don't work for non-gmail accounts.<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 "jingle/notifier/communicator/gaia_token_pre_xmpp_auth.h"
#include <algorithm>
#include "base/basictypes.h"
#include "talk/base/socketaddress.h"
#include "talk/xmpp/constants.h"
#include "talk/xmpp/saslcookiemechanism.h"
namespace notifier {
namespace {
const char kGaiaAuthMechanism[] = "X-GOOGLE-TOKEN";
class GaiaCookieMechanism : public buzz::SaslCookieMechanism {
public:
GaiaCookieMechanism(const std::string & mechanism,
const std::string & username,
const std::string & cookie,
const std::string & token_service)
: buzz::SaslCookieMechanism(
mechanism, username, cookie, token_service) {}
virtual ~GaiaCookieMechanism() {}
virtual buzz::XmlElement* StartSaslAuth() {
buzz::XmlElement* auth = buzz::SaslCookieMechanism::StartSaslAuth();
// These attributes are necessary for working with non-gmail gaia
// accounts.
const std::string NS_GOOGLE_AUTH_PROTOCOL(
"http://www.google.com/talk/protocol/auth");
const buzz::QName QN_GOOGLE_ALLOW_GENERATED_JID_XMPP_LOGIN(
true, NS_GOOGLE_AUTH_PROTOCOL, "allow-generated-jid");
const buzz::QName QN_GOOGLE_AUTH_CLIENT_USES_FULL_BIND_RESULT(
true, NS_GOOGLE_AUTH_PROTOCOL, "client-uses-full-bind-result");
auth->SetAttr(QN_GOOGLE_ALLOW_GENERATED_JID_XMPP_LOGIN, "true");
auth->SetAttr(QN_GOOGLE_AUTH_CLIENT_USES_FULL_BIND_RESULT, "true");
return auth;
}
private:
DISALLOW_COPY_AND_ASSIGN(GaiaCookieMechanism);
};
} // namespace
GaiaTokenPreXmppAuth::GaiaTokenPreXmppAuth(
const std::string& username,
const std::string& token,
const std::string& token_service)
: username_(username),
token_(token),
token_service_(token_service) { }
GaiaTokenPreXmppAuth::~GaiaTokenPreXmppAuth() { }
void GaiaTokenPreXmppAuth::StartPreXmppAuth(
const buzz::Jid& jid,
const talk_base::SocketAddress& server,
const talk_base::CryptString& pass,
const std::string& auth_cookie) {
SignalAuthDone();
}
bool GaiaTokenPreXmppAuth::IsAuthDone() const {
return true;
}
bool GaiaTokenPreXmppAuth::IsAuthorized() const {
return true;
}
bool GaiaTokenPreXmppAuth::HadError() const {
return false;
}
int GaiaTokenPreXmppAuth::GetError() const {
return 0;
}
buzz::CaptchaChallenge GaiaTokenPreXmppAuth::GetCaptchaChallenge() const {
return buzz::CaptchaChallenge();
}
std::string GaiaTokenPreXmppAuth::GetAuthCookie() const {
return std::string();
}
std::string GaiaTokenPreXmppAuth::ChooseBestSaslMechanism(
const std::vector<std::string> & mechanisms, bool encrypted) {
return (std::find(mechanisms.begin(),
mechanisms.end(), kGaiaAuthMechanism) !=
mechanisms.end()) ? kGaiaAuthMechanism : "";
}
buzz::SaslMechanism* GaiaTokenPreXmppAuth::CreateSaslMechanism(
const std::string& mechanism) {
if (mechanism != kGaiaAuthMechanism)
return NULL;
return new GaiaCookieMechanism(
kGaiaAuthMechanism, username_, token_, token_service_);
}
} // namespace notifier
<|endoftext|>
|
<commit_before>/** \addtogroup examples
* @{
* \defgroup btwn_central betweenness centrality
* @{
* \brief betweenness centrality computation
*/
#include <ctf.hpp>
#include <float.h>
using namespace CTF;
//structure for regular path that keeps track of the multiplicity of paths
class path {
public:
int w; // weighted distance
int m; // multiplictiy
path(int w_, int m_){ w=w_; m=m_; }
path(path const & p){ w=p.w; m=p.m; }
path(){};
};
//(min, +) tropical semiring for path structure
Semiring<path> get_path_semiring(){
//struct for path with w=path weight, h=#hops
MPI_Op opath;
MPI_Op_create(
[](void * a, void * b, int * n, MPI_Datatype*){
for (int i=0; i<*n; i++){
if (((path*)a)[i].w <= ((path*)b)[i].w){
((path*)b)[0] = ((path*)a)[0];
}
}
},
1, &opath);
//tropical semiring with hops carried by winner of min
Semiring<path> p(path(INT_MAX/2,1),
[](path a, path b){
if (a.w<b.w){ return a; }
else if (b.w<a.w){ return b; }
else { return path(a.w, a.m+b.m); }
},
opath,
path(0,1),
[](path a, path b){ return path(a.w+b.w, a.m*b.m); });
return p;
}
//path with a centrality score
class cpath : public path {
public:
double c; // centrality score
cpath(int w_, int m_, double c_) : path(w_, m_) { c=c_;}
cpath(cpath const & p) : path(p) { c=p.c; }
cpath(){};
};
// min Monoid for cpath structure
Monoid<cpath> get_cpath_monoid(){
//struct for cpath with w=cpath weight, h=#hops
MPI_Op ocpath;
MPI_Op_create(
[](void * a, void * b, int * n, MPI_Datatype*){
for (int i=0; i<*n; i++){
if (((cpath*)a)[i].w <= ((cpath*)b)[i].w){
((cpath*)b)[0] = ((cpath*)a)[0];
}
}
},
1, &ocpath);
Monoid<cpath> cp(cpath(-INT_MAX/2,1,0.),
[](cpath a, cpath b){
if (a.w>b.w){ return a; }
else if (b.w>a.w){ return b; }
else { return cpath(a.w, a.m+b.m, a.c+b.c); }
}, ocpath);
return cp;
}
//overwrite printfs to make it possible to print matrices of paths
namespace CTF {
template <>
inline void Set<path>::print(char const * a, FILE * fp) const {
fprintf(fp,"(w=%d m=%d)",((path*)a)[0].w,((path*)a)[0].m);
}
template <>
inline void Set<cpath>::print(char const * a, FILE * fp) const {
fprintf(fp,"(w=%d m=%d c=%lf)",((cpath*)a)[0].w,((cpath*)a)[0].m,((cpath*)a)[0].c);
}
}
/**
* \brief fast algorithm for betweenness centrality using Bellman Ford
* \param[in] A matrix on the tropical semiring containing edge weights
* \param[in] b number of source vertices for which to compute Bellman Ford at a time
* \param[out] v vector that will contain centrality scores for each vertex
*/
void btwn_cnt_fast(Matrix<int> A, int b, Vector<double> & v){
World dw = *A.wrld;
int n = A.nrow;
Semiring<path> p = get_path_semiring();
Monoid<cpath> cp = get_cpath_monoid();
for (int ib=0; ib<n; ib+=b){
int k = std::min(b, n-ib);
//initialize shortest path vectors from the next k sources to the corresponding columns of the adjacency matrices and loops with weight 0
((Transform<int>)([=](int& w){ w = 0; }))(A["ii"]);
Tensor<int> iA = A.slice(ib*n, (ib+k-1)*n+n-1);
((Transform<int>)([=](int& w){ w = INT_MAX/2; }))(A["ii"]);
//let shortest paths vectors be paths
Matrix<path> B(n, k, dw, p, "B");
B["ij"] = ((Function<int,path>)([](int i){ return path(i, 1); }))(iA["ij"]);
//compute Bellman Ford
for (int i=0; i<n; i++){
B["ij"] = ((Function<int,path,path>)([](int i, path p){ return path(p.w+i, p.m); }))(A["ik"],B["kj"]);
B["ij"] += ((Function<int,path>)([](int i){ return path(i, 1); }))(iA["ij"]);
}
//transfer shortest path data to Matrix of cpaths to compute c centrality scores
Matrix<cpath> cB(n, k, dw, cp, "cB");
((Transform<path,cpath>)([](path p, cpath & cp){ cp = cpath(p.w, p.m, 0.); }))(B["ij"],cB["ij"]);
//compute centrality scores by propagating them backwards from the furthest nodes (reverse Bellman Ford)
for (int i=0; i<n; i++){
cB["ij"] = ((Function<int,cpath,cpath>)(
[](int i, cpath p){
return cpath(p.w-i, p.m, (1.+p.c)/p.m);
}))(A["ki"],cB["kj"]);
((Transform<path,cpath>)([](path p, cpath & cp){
cp = (p.w <= cp.w) ? cpath(p.w, p.m, cp.c*p.m) : cpath(p.w, p.m, 0.);
}))(B["ij"],cB["ij"]);
}
//set self-centrality scores to zero
//FIXME: assumes loops are zero edges and there are no others zero edges in A
((Transform<cpath>)([](cpath & p){ if (p.w == 0) p.c=0; }))(cB["ij"]);
//((Transform<cpath>)([](cpath & p){ p.c=0; }))(cB["ii"]);
//accumulate centrality scores
v["i"] += ((Function<cpath,double>)([](cpath a){ return a.c; }))(cB["ij"]);
}
}
/**
* \brief naive algorithm for betweenness centrality using 3D tensor of counts
* \param[in] A matrix on the tropical semiring containing edge weights
* \param[out] v vector that will contain centrality scores for each vertex
*/
void btwn_cnt_naive(Matrix<int> & A, Vector<double> & v){
World dw = *A.wrld;
int n = A.nrow;
Semiring<path> p = get_path_semiring();
Monoid<cpath> cp = get_cpath_monoid();
//path matrix to contain distance matrix
Matrix<path> P(n, n, dw, p, "P");
Function<int,path> setw([](int w){ return path(w, 1); });
P["ij"] = setw(A["ij"]);
((Transform<path>)([=](path& w){ w = path(INT_MAX/2, 1); }))(P["ii"]);
Matrix<path> Pi(n, n, dw, p);
Pi["ij"] = P["ij"];
//compute all shortest paths by Bellman Ford
for (int i=0; i<n; i++){
((Transform<path>)([=](path & p){ p = path(0,1); }))(P["ii"]);
P["ij"] = Pi["ik"]*P["kj"];
}
((Transform<path>)([=](path& p){ p = path(INT_MAX/2, 1); }))(P["ii"]);
int lenn[3] = {n,n,n};
Tensor<cpath> postv(3, lenn, dw, cp, "postv");
//set postv_ijk = shortest path from i to k (d_ik)
postv["ijk"] += ((Function<path,cpath>)([](path p){ return cpath(p.w, p.m, 0.0); }))(P["ik"]);
//set postv_ijk =
// for all nodes j on the shortest path from i to k (d_ik=d_ij+d_jk)
// let multiplicity of shortest paths from i to j is a, from j to k is b, and from i to k is c
// then postv_ijk = a*b/c
((Transform<path,path,cpath>)(
[=](path a, path b, cpath & c){
if (c.w<INT_MAX/2 && a.w+b.w == c.w){ c.c = ((double)a.m*b.m)/c.m; }
else { c.c = 0; }
}
))(P["ij"],P["jk"],postv["ijk"]);
//sum multiplicities v_j = sum(i,k) postv_ijk
v["j"] += ((Function<cpath,double>)([](cpath p){ return p.c; }))(postv["ijk"]);
}
// calculate betweenness centrality a graph of n nodes distributed on World (communicator) dw
int btwn_cnt(int n,
World & dw){
//tropical semiring, define additive identity to be INT_MAX/2 to prevent integer overflow
Semiring<int> s(INT_MAX/2,
[](int a, int b){ return std::min(a,b); },
MPI_MIN,
0,
[](int a, int b){ return a+b; });
//random adjacency matrix
Matrix<int> A(n, n, dw, s, "A");
//fill with values in the range of [1,min(n*n,100)]
srand(dw.rank+1);
A.fill_random(1, std::min(n*n,100));
A["ii"] = 0;
//keep only values smaller than 20 (about 20% sparsity)
A.sparsify([=](int a){ return a<20; });
Vector<double> v1(n,dw);
Vector<double> v2(n,dw);
//compute centrality scores by naive counting
btwn_cnt_naive(A, v1);
//compute centrality scores by Bellman Ford with block size 2
btwn_cnt_fast(A, 2, v2);
v1["i"] -= v2["i"];
int pass = v1.norm2() <= 1.E-6;
if (dw.rank == 0){
MPI_Reduce(MPI_IN_PLACE, &pass, 1, MPI_INT, MPI_MIN, 0, MPI_COMM_WORLD);
if (pass)
printf("{ betweenness centrality } passed \n");
else
printf("{ betweenness centrality } failed \n");
} else
MPI_Reduce(&pass, MPI_IN_PLACE, 1, MPI_INT, MPI_MIN, 0, MPI_COMM_WORLD);
return pass;
}
#ifndef TEST_SUITE
char* getCmdOption(char ** begin,
char ** end,
const std::string & option){
char ** itr = std::find(begin, end, option);
if (itr != end && ++itr != end){
return *itr;
}
return 0;
}
int main(int argc, char ** argv){
int rank, np, n, pass;
int const in_num = argc;
char ** input_str = argv;
MPI_Init(&argc, &argv);
MPI_Comm_rank(MPI_COMM_WORLD, &rank);
MPI_Comm_size(MPI_COMM_WORLD, &np);
if (getCmdOption(input_str, input_str+in_num, "-n")){
n = atoi(getCmdOption(input_str, input_str+in_num, "-n"));
if (n < 0) n = 7;
} else n = 7;
{
World dw(argc, argv);
if (rank == 0){
printf("Computing betweenness centrality for graph with %d nodes\n",n);
}
pass = btwn_cnt(n, dw);
assert(pass);
}
MPI_Finalize();
return 0;
}
/**
* @}
* @}
*/
#endif
<commit_msg>renamed i variable so code is less confusing<commit_after>/** \addtogroup examples
* @{
* \defgroup btwn_central betweenness centrality
* @{
* \brief betweenness centrality computation
*/
#include <ctf.hpp>
#include <float.h>
using namespace CTF;
//structure for regular path that keeps track of the multiplicity of paths
class path {
public:
int w; // weighted distance
int m; // multiplictiy
path(int w_, int m_){ w=w_; m=m_; }
path(path const & p){ w=p.w; m=p.m; }
path(){};
};
//(min, +) tropical semiring for path structure
Semiring<path> get_path_semiring(){
//struct for path with w=path weight, h=#hops
MPI_Op opath;
MPI_Op_create(
[](void * a, void * b, int * n, MPI_Datatype*){
for (int i=0; i<*n; i++){
if (((path*)a)[i].w <= ((path*)b)[i].w){
((path*)b)[0] = ((path*)a)[0];
}
}
},
1, &opath);
//tropical semiring with hops carried by winner of min
Semiring<path> p(path(INT_MAX/2,1),
[](path a, path b){
if (a.w<b.w){ return a; }
else if (b.w<a.w){ return b; }
else { return path(a.w, a.m+b.m); }
},
opath,
path(0,1),
[](path a, path b){ return path(a.w+b.w, a.m*b.m); });
return p;
}
//path with a centrality score
class cpath : public path {
public:
double c; // centrality score
cpath(int w_, int m_, double c_) : path(w_, m_) { c=c_;}
cpath(cpath const & p) : path(p) { c=p.c; }
cpath(){};
};
// min Monoid for cpath structure
Monoid<cpath> get_cpath_monoid(){
//struct for cpath with w=cpath weight, h=#hops
MPI_Op ocpath;
MPI_Op_create(
[](void * a, void * b, int * n, MPI_Datatype*){
for (int i=0; i<*n; i++){
if (((cpath*)a)[i].w <= ((cpath*)b)[i].w){
((cpath*)b)[0] = ((cpath*)a)[0];
}
}
},
1, &ocpath);
Monoid<cpath> cp(cpath(-INT_MAX/2,1,0.),
[](cpath a, cpath b){
if (a.w>b.w){ return a; }
else if (b.w>a.w){ return b; }
else { return cpath(a.w, a.m+b.m, a.c+b.c); }
}, ocpath);
return cp;
}
//overwrite printfs to make it possible to print matrices of paths
namespace CTF {
template <>
inline void Set<path>::print(char const * a, FILE * fp) const {
fprintf(fp,"(w=%d m=%d)",((path*)a)[0].w,((path*)a)[0].m);
}
template <>
inline void Set<cpath>::print(char const * a, FILE * fp) const {
fprintf(fp,"(w=%d m=%d c=%lf)",((cpath*)a)[0].w,((cpath*)a)[0].m,((cpath*)a)[0].c);
}
}
/**
* \brief fast algorithm for betweenness centrality using Bellman Ford
* \param[in] A matrix on the tropical semiring containing edge weights
* \param[in] b number of source vertices for which to compute Bellman Ford at a time
* \param[out] v vector that will contain centrality scores for each vertex
*/
void btwn_cnt_fast(Matrix<int> A, int b, Vector<double> & v){
World dw = *A.wrld;
int n = A.nrow;
Semiring<path> p = get_path_semiring();
Monoid<cpath> cp = get_cpath_monoid();
for (int ib=0; ib<n; ib+=b){
int k = std::min(b, n-ib);
//initialize shortest path vectors from the next k sources to the corresponding columns of the adjacency matrices and loops with weight 0
((Transform<int>)([=](int& w){ w = 0; }))(A["ii"]);
Tensor<int> iA = A.slice(ib*n, (ib+k-1)*n+n-1);
((Transform<int>)([=](int& w){ w = INT_MAX/2; }))(A["ii"]);
//let shortest paths vectors be paths
Matrix<path> B(n, k, dw, p, "B");
B["ij"] = ((Function<int,path>)([](int w){ return path(w, 1); }))(iA["ij"]);
//compute Bellman Ford
for (int i=0; i<n; i++){
B["ij"] = ((Function<int,path,path>)([](int w, path p){ return path(p.w+w, p.m); }))(A["ik"],B["kj"]);
B["ij"] += ((Function<int,path>)([](int w){ return path(w, 1); }))(iA["ij"]);
}
//transfer shortest path data to Matrix of cpaths to compute c centrality scores
Matrix<cpath> cB(n, k, dw, cp, "cB");
((Transform<path,cpath>)([](path p, cpath & cp){ cp = cpath(p.w, p.m, 0.); }))(B["ij"],cB["ij"]);
//compute centrality scores by propagating them backwards from the furthest nodes (reverse Bellman Ford)
for (int i=0; i<n; i++){
cB["ij"] = ((Function<int,cpath,cpath>)(
[](int w, cpath p){
return cpath(p.w-w, p.m, (1.+p.c)/p.m);
}))(A["ki"],cB["kj"]);
((Transform<path,cpath>)([](path p, cpath & cp){
cp = (p.w <= cp.w) ? cpath(p.w, p.m, cp.c*p.m) : cpath(p.w, p.m, 0.);
}))(B["ij"],cB["ij"]);
}
//set self-centrality scores to zero
//FIXME: assumes loops are zero edges and there are no others zero edges in A
((Transform<cpath>)([](cpath & p){ if (p.w == 0) p.c=0; }))(cB["ij"]);
//((Transform<cpath>)([](cpath & p){ p.c=0; }))(cB["ii"]);
//accumulate centrality scores
v["i"] += ((Function<cpath,double>)([](cpath a){ return a.c; }))(cB["ij"]);
}
}
/**
* \brief naive algorithm for betweenness centrality using 3D tensor of counts
* \param[in] A matrix on the tropical semiring containing edge weights
* \param[out] v vector that will contain centrality scores for each vertex
*/
void btwn_cnt_naive(Matrix<int> & A, Vector<double> & v){
World dw = *A.wrld;
int n = A.nrow;
Semiring<path> p = get_path_semiring();
Monoid<cpath> cp = get_cpath_monoid();
//path matrix to contain distance matrix
Matrix<path> P(n, n, dw, p, "P");
Function<int,path> setw([](int w){ return path(w, 1); });
P["ij"] = setw(A["ij"]);
((Transform<path>)([=](path& w){ w = path(INT_MAX/2, 1); }))(P["ii"]);
Matrix<path> Pi(n, n, dw, p);
Pi["ij"] = P["ij"];
//compute all shortest paths by Bellman Ford
for (int i=0; i<n; i++){
((Transform<path>)([=](path & p){ p = path(0,1); }))(P["ii"]);
P["ij"] = Pi["ik"]*P["kj"];
}
((Transform<path>)([=](path& p){ p = path(INT_MAX/2, 1); }))(P["ii"]);
int lenn[3] = {n,n,n};
Tensor<cpath> postv(3, lenn, dw, cp, "postv");
//set postv_ijk = shortest path from i to k (d_ik)
postv["ijk"] += ((Function<path,cpath>)([](path p){ return cpath(p.w, p.m, 0.0); }))(P["ik"]);
//set postv_ijk =
// for all nodes j on the shortest path from i to k (d_ik=d_ij+d_jk)
// let multiplicity of shortest paths from i to j is a, from j to k is b, and from i to k is c
// then postv_ijk = a*b/c
((Transform<path,path,cpath>)(
[=](path a, path b, cpath & c){
if (c.w<INT_MAX/2 && a.w+b.w == c.w){ c.c = ((double)a.m*b.m)/c.m; }
else { c.c = 0; }
}
))(P["ij"],P["jk"],postv["ijk"]);
//sum multiplicities v_j = sum(i,k) postv_ijk
v["j"] += ((Function<cpath,double>)([](cpath p){ return p.c; }))(postv["ijk"]);
}
// calculate betweenness centrality a graph of n nodes distributed on World (communicator) dw
int btwn_cnt(int n,
World & dw){
//tropical semiring, define additive identity to be INT_MAX/2 to prevent integer overflow
Semiring<int> s(INT_MAX/2,
[](int a, int b){ return std::min(a,b); },
MPI_MIN,
0,
[](int a, int b){ return a+b; });
//random adjacency matrix
Matrix<int> A(n, n, dw, s, "A");
//fill with values in the range of [1,min(n*n,100)]
srand(dw.rank+1);
A.fill_random(1, std::min(n*n,100));
A["ii"] = 0;
//keep only values smaller than 20 (about 20% sparsity)
A.sparsify([=](int a){ return a<20; });
Vector<double> v1(n,dw);
Vector<double> v2(n,dw);
//compute centrality scores by naive counting
btwn_cnt_naive(A, v1);
//compute centrality scores by Bellman Ford with block size 2
btwn_cnt_fast(A, 2, v2);
v1["i"] -= v2["i"];
int pass = v1.norm2() <= 1.E-6;
if (dw.rank == 0){
MPI_Reduce(MPI_IN_PLACE, &pass, 1, MPI_INT, MPI_MIN, 0, MPI_COMM_WORLD);
if (pass)
printf("{ betweenness centrality } passed \n");
else
printf("{ betweenness centrality } failed \n");
} else
MPI_Reduce(&pass, MPI_IN_PLACE, 1, MPI_INT, MPI_MIN, 0, MPI_COMM_WORLD);
return pass;
}
#ifndef TEST_SUITE
char* getCmdOption(char ** begin,
char ** end,
const std::string & option){
char ** itr = std::find(begin, end, option);
if (itr != end && ++itr != end){
return *itr;
}
return 0;
}
int main(int argc, char ** argv){
int rank, np, n, pass;
int const in_num = argc;
char ** input_str = argv;
MPI_Init(&argc, &argv);
MPI_Comm_rank(MPI_COMM_WORLD, &rank);
MPI_Comm_size(MPI_COMM_WORLD, &np);
if (getCmdOption(input_str, input_str+in_num, "-n")){
n = atoi(getCmdOption(input_str, input_str+in_num, "-n"));
if (n < 0) n = 7;
} else n = 7;
{
World dw(argc, argv);
if (rank == 0){
printf("Computing betweenness centrality for graph with %d nodes\n",n);
}
pass = btwn_cnt(n, dw);
assert(pass);
}
MPI_Finalize();
return 0;
}
/**
* @}
* @}
*/
#endif
<|endoftext|>
|
<commit_before>#include <fstream>
#include <iostream>
#include <string>
using namespace std;
int **createTable()
{
ifstream fileWithTable("table.txt");
int **table = new int*[3];
for (int i = 0; i < 3; i++)
{
table[i] = new int[4]{0};
}
for (int i = 0; i < 3; i++)
{
for (int j = 0; j < 4; j++)
{
fileWithTable >> table[i][j];
}
}
fileWithTable.close();
return table;
}
void main()
{
ifstream inputFile("test.txt");
int **table = createTable();
char symbol = {};
int state = 0;
while (!inputFile.eof())
{
inputFile >> symbol;
if (state == 2 && symbol !='*')
{
cout << symbol;
}
else
{
if (symbol == '/')
{
int previosState = state;
state = table[0][state];
if (previosState == 3 && state == 0)
{
cout << "*/";
}
}
else
{
if (symbol == '*')
{
int previosState = state;
state = table[1][state];
if (state == 2 && previosState == 1)
{
cout << "/*";
}
}
else
{
state = table[2][state];
}
}
}
}
inputFile.close();
}<commit_msg>Add function deleteTable<commit_after>#include <fstream>
#include <iostream>
#include <string>
using namespace std;
int **createTable()
{
ifstream fileWithTable("table.txt");
int **table = new int*[3];
for (int i = 0; i < 3; i++)
{
table[i] = new int[4]{0};
}
for (int i = 0; i < 3; i++)
{
for (int j = 0; j < 4; j++)
{
fileWithTable >> table[i][j];
}
}
fileWithTable.close();
return table;
}
void deleteTable(int **table)
{
for (int i = 0; i < 3; i++)
{
delete table[i];
}
delete table;
table = nullptr;
}
void main()
{
ifstream inputFile("test.txt");
int **table = createTable();
char symbol = {};
int state = 0;
while (!inputFile.eof())
{
inputFile >> symbol;
if (state == 2 && symbol != '*')
{
cout << symbol;
}
else
{
if (symbol == '/')
{
int previosState = state;
state = table[0][state];
if (previosState == 3 && state == 0)
{
cout << "*/";
}
}
else
{
if (symbol == '*')
{
int previosState = state;
state = table[1][state];
if (state == 2 && previosState == 1)
{
cout << "/*";
}
}
else
{
state = table[2][state];
}
}
}
}
inputFile.close();
deleteTable(table);
}<|endoftext|>
|
<commit_before>/*
Скопировать один файл в другой. Имена файлов передаются из командной строки.
Пример использования:
8_2.exe source_file1.txt file2.txt
*/
#include <iostream>
#include <cstdlib>
#include <fstream>
using namespace std;
void error(const char *s, const char *s2 = "")
{
cerr << s << " " << s2 << endl;
exit(1);
}
int main(int argc, char *argv[])
{
if ( argc != 3 )
error("Wrong number of arguments");
ifstream source(argv[1]);
if ( !source )
error("Can't open source file", argv[1]);
ofstream target(argv[2]);
if ( !target )
error("Can't open source file", argv[2]);
char symbol;
while ( source.get(symbol) )
target.put(symbol);
if ( !source.eof() || target.bad() )
error("There were errors during copying");
source.close();
target.close();
return 0;
}
<commit_msg>translation for 8_2_c.cpp program<commit_after>/*
Скопировать один файл в другой. Имена файлов передаются из командной строки.
Пример использования:
8_2.exe source_file1.txt file2.txt
*/
#include <iostream>
#include <cstdlib>
#include <fstream>
#include <clocale>
using namespace std;
void error(const char *s, const char *s2 = "")
{
cerr << s << " " << s2 << endl;
exit(1);
}
int main(int argc, char *argv[])
{
setlocale(LC_ALL, "RUS");
if ( argc != 3 )
error("Неправильное число аргументов. Использование: <название_программы>.exe <исходный_файл> <файл_для_записи>");
ifstream source(argv[1]);
if ( !source )
error("Проблемы при открытии исходного файла", argv[1]);
ofstream target(argv[2]);
if ( !target )
error("Проблемы при открытии файла для записи", argv[2]);
char symbol;
while ( source.get(symbol) )
target.put(symbol);
if ( !source.eof() || target.bad() )
error("Возникли ошибки при копировании!");
source.close();
target.close();
return 0;
}
<|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.
*/
/**
* @author Pavel Pervov
* @version $Revision: 1.1.2.3.4.4 $
*/
#define LOG_DOMAIN "classloader"
#include "cxxlog.h"
#include "Class.h"
#include "open/jthread.h"
#include "open/gc.h"
#include "exceptions.h"
#include "thread_manager.h"
#include "vm_strings.h"
#include "classloader.h"
#include "ini.h"
#include "vm_threads.h"
// Initializes a class.
void Class::initialize()
{
ASSERT_RAISE_AREA;
assert(!exn_raised());
assert(!hythread_is_suspend_enabled());
// the following code implements the 11-step class initialization program
// described in page 226, section 12.4.2 of Java Language Spec, 1996
// ISBN 0-201-63451-1
TRACE2("class.init", "initializing class " << m_name->bytes);
// --- step 1 ----------------------------------------------------------
assert(!hythread_is_suspend_enabled());
jobject jlc = struct_Class_to_java_lang_Class_Handle(this);
jthread_monitor_enter(jlc);
// --- step 2 ----------------------------------------------------------
TRACE2("class.init", "initializing class " << m_name->bytes << " STEP 2" );
while(m_initializing_thread != p_TLS_vmthread && is_initializing()) {
jthread_monitor_wait(jlc);
if(exn_raised()) {
jthread_monitor_exit(jlc);
return;
}
}
// --- step 3 ----------------------------------------------------------
if(m_initializing_thread == p_TLS_vmthread) {
jthread_monitor_exit(jlc);
return;
}
// --- step 4 ----------------------------------------------------------
if(is_initialized()) {
jthread_monitor_exit(jlc);
return;
}
// --- step 5 ----------------------------------------------------------
if(in_error()) {
jthread_monitor_exit(jlc);
tmn_suspend_enable();
exn_raise_by_name("java/lang/NoClassDefFoundError", m_name->bytes);
tmn_suspend_disable();
return;
}
// --- step 6 ----------------------------------------------------------
TRACE2("class.init", "initializing class " << m_name->bytes << "STEP 6" );
assert(m_state == ST_ConstraintsVerified);
assert(m_initializing_thread == 0);
lock();
m_state = ST_Initializing;
unlock();
m_initializing_thread = p_TLS_vmthread;
jthread_monitor_exit(jlc);
// --- step 7 ------------------------------------------------------------
if(has_super_class()) {
class_initialize_ex(get_super_class());
if(get_super_class()->in_error()) {
jthread_monitor_enter(jlc);
m_initializing_thread = NULL;
lock();
m_state = ST_Error;
unlock();
assert(!hythread_is_suspend_enabled());
jthread_monitor_notify_all(jlc);
jthread_monitor_exit(jlc);
return;
}
}
// --- step 8 ----------------------------------------------------------
Method* meth = m_static_initializer;
if(meth == NULL) {
jthread_monitor_enter(jlc);
lock();
m_state = ST_Initialized;
unlock();
TRACE2("classloader", "class " << m_name->bytes << " initialized");
m_initializing_thread = NULL;
assert(!hythread_is_suspend_enabled());
jthread_monitor_notify_all(jlc);
jthread_monitor_exit(jlc);
return;
}
TRACE2("class.init", "initializing class " << m_name->bytes << " STEP 8" );
jthrowable p_error_object;
assert(!hythread_is_suspend_enabled());
// it's a safe poin so enviroment should be protected
vm_execute_java_method_array((jmethodID) meth, 0, 0);
// suspend can be enabeled in safe enviroment
tmn_suspend_enable();
p_error_object = exn_get();
tmn_suspend_disable();
// --- step 9 ----------------------------------------------------------
TRACE2("class.init", "initializing class " << m_name->bytes << " STEP 9" );
if(!p_error_object) {
jthread_monitor_enter(jlc);
lock();
m_state = ST_Initialized;
unlock();
TRACE2("classloader", "class " << m_name->bytes << " initialized");
m_initializing_thread = NULL;
assert(!hythread_is_suspend_enabled());
jthread_monitor_notify_all(jlc);
jthread_monitor_exit(jlc);
return;
}
// --- step 10 ----------------------------------------------------------
assert(p_error_object != NULL);
assert(!hythread_is_suspend_enabled());
exn_clear();
Class* p_error_class = p_error_object->object->vt()->clss;
Class* jle = VM_Global_State::loader_env->java_lang_Error_Class;
while(p_error_class && p_error_class != jle) {
p_error_class = p_error_class->get_super_class();
}
assert(!hythread_is_suspend_enabled());
if(p_error_class == NULL) {
// class of p_error_object is not a descendant of java/lang/Error
#ifdef _DEBUG_REMOVED
Class* eiie = VM_Global_State::loader_env->
java_lang_ExceptionInInitializerError_Class;
assert(eiie);
#endif
tmn_suspend_enable();
p_error_object = exn_create("java/lang/ExceptionInInitializerError",
p_error_object);
tmn_suspend_disable();
}
// --- step 11 ----------------------------------------------------------
assert(!hythread_is_suspend_enabled());
jthread_monitor_enter(jlc);
lock();
m_state = ST_Error;
unlock();
m_initializing_thread = NULL;
assert(!hythread_is_suspend_enabled());
jthread_monitor_notify_all(jlc);
jthread_monitor_exit(jlc);
exn_raise_object(p_error_object);
// end of 11 step class initialization program
} //class_initialize1
void class_initialize_from_jni(Class *clss)
{
ASSERT_RAISE_AREA;
assert(hythread_is_suspend_enabled());
// check verifier constraints
if(!clss->verify_constraints(VM_Global_State::loader_env)) {
assert(exn_raised());
return;
}
tmn_suspend_disable();
if (class_needs_initialization(clss)) {
clss->initialize();
}
tmn_suspend_enable();
} // class_initialize_from_jni
void class_initialize(Class *clss)
{
ASSERT_RAISE_AREA;
class_initialize_ex(clss);
}
void class_initialize_ex(Class *clss)
{
ASSERT_RAISE_AREA;
assert(!hythread_is_suspend_enabled());
// check verifier constraints
tmn_suspend_enable();
if(!clss->verify_constraints(VM_Global_State::loader_env)) {
assert(exn_raised());
tmn_suspend_disable();
return;
}
tmn_suspend_disable();
if(class_needs_initialization(clss)) {
clss->initialize();
}
} // class_initialize_ex
<commit_msg>added newline to kick CC<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.
*/
/**
* @author Pavel Pervov
* @version $Revision: 1.1.2.3.4.4 $
*/
#define LOG_DOMAIN "classloader"
#include "cxxlog.h"
#include "Class.h"
#include "open/jthread.h"
#include "open/gc.h"
#include "exceptions.h"
#include "thread_manager.h"
#include "vm_strings.h"
#include "classloader.h"
#include "ini.h"
#include "vm_threads.h"
// Initializes a class.
void Class::initialize()
{
ASSERT_RAISE_AREA;
assert(!exn_raised());
assert(!hythread_is_suspend_enabled());
// the following code implements the 11-step class initialization program
// described in page 226, section 12.4.2 of Java Language Spec, 1996
// ISBN 0-201-63451-1
TRACE2("class.init", "initializing class " << m_name->bytes);
// --- step 1 ----------------------------------------------------------
assert(!hythread_is_suspend_enabled());
jobject jlc = struct_Class_to_java_lang_Class_Handle(this);
jthread_monitor_enter(jlc);
// --- step 2 ----------------------------------------------------------
TRACE2("class.init", "initializing class " << m_name->bytes << " STEP 2" );
while(m_initializing_thread != p_TLS_vmthread && is_initializing()) {
jthread_monitor_wait(jlc);
if(exn_raised()) {
jthread_monitor_exit(jlc);
return;
}
}
// --- step 3 ----------------------------------------------------------
if(m_initializing_thread == p_TLS_vmthread) {
jthread_monitor_exit(jlc);
return;
}
// --- step 4 ----------------------------------------------------------
if(is_initialized()) {
jthread_monitor_exit(jlc);
return;
}
// --- step 5 ----------------------------------------------------------
if(in_error()) {
jthread_monitor_exit(jlc);
tmn_suspend_enable();
exn_raise_by_name("java/lang/NoClassDefFoundError", m_name->bytes);
tmn_suspend_disable();
return;
}
// --- step 6 ----------------------------------------------------------
TRACE2("class.init", "initializing class " << m_name->bytes << "STEP 6" );
assert(m_state == ST_ConstraintsVerified);
assert(m_initializing_thread == 0);
lock();
m_state = ST_Initializing;
unlock();
m_initializing_thread = p_TLS_vmthread;
jthread_monitor_exit(jlc);
// --- step 7 ------------------------------------------------------------
if(has_super_class()) {
class_initialize_ex(get_super_class());
if(get_super_class()->in_error()) {
jthread_monitor_enter(jlc);
m_initializing_thread = NULL;
lock();
m_state = ST_Error;
unlock();
assert(!hythread_is_suspend_enabled());
jthread_monitor_notify_all(jlc);
jthread_monitor_exit(jlc);
return;
}
}
// --- step 8 ----------------------------------------------------------
Method* meth = m_static_initializer;
if(meth == NULL) {
jthread_monitor_enter(jlc);
lock();
m_state = ST_Initialized;
unlock();
TRACE2("classloader", "class " << m_name->bytes << " initialized");
m_initializing_thread = NULL;
assert(!hythread_is_suspend_enabled());
jthread_monitor_notify_all(jlc);
jthread_monitor_exit(jlc);
return;
}
TRACE2("class.init", "initializing class " << m_name->bytes << " STEP 8" );
jthrowable p_error_object;
assert(!hythread_is_suspend_enabled());
// it's a safe poin so enviroment should be protected
vm_execute_java_method_array((jmethodID) meth, 0, 0);
// suspend can be enabeled in safe enviroment
tmn_suspend_enable();
p_error_object = exn_get();
tmn_suspend_disable();
// --- step 9 ----------------------------------------------------------
TRACE2("class.init", "initializing class " << m_name->bytes << " STEP 9" );
if(!p_error_object) {
jthread_monitor_enter(jlc);
lock();
m_state = ST_Initialized;
unlock();
TRACE2("classloader", "class " << m_name->bytes << " initialized");
m_initializing_thread = NULL;
assert(!hythread_is_suspend_enabled());
jthread_monitor_notify_all(jlc);
jthread_monitor_exit(jlc);
return;
}
// --- step 10 ----------------------------------------------------------
assert(p_error_object != NULL);
assert(!hythread_is_suspend_enabled());
exn_clear();
Class* p_error_class = p_error_object->object->vt()->clss;
Class* jle = VM_Global_State::loader_env->java_lang_Error_Class;
while(p_error_class && p_error_class != jle) {
p_error_class = p_error_class->get_super_class();
}
assert(!hythread_is_suspend_enabled());
if(p_error_class == NULL) {
// class of p_error_object is not a descendant of java/lang/Error
#ifdef _DEBUG_REMOVED
Class* eiie = VM_Global_State::loader_env->
java_lang_ExceptionInInitializerError_Class;
assert(eiie);
#endif
tmn_suspend_enable();
p_error_object = exn_create("java/lang/ExceptionInInitializerError",
p_error_object);
tmn_suspend_disable();
}
// --- step 11 ----------------------------------------------------------
assert(!hythread_is_suspend_enabled());
jthread_monitor_enter(jlc);
lock();
m_state = ST_Error;
unlock();
m_initializing_thread = NULL;
assert(!hythread_is_suspend_enabled());
jthread_monitor_notify_all(jlc);
jthread_monitor_exit(jlc);
exn_raise_object(p_error_object);
// end of 11 step class initialization program
} //class_initialize1
void class_initialize_from_jni(Class *clss)
{
ASSERT_RAISE_AREA;
assert(hythread_is_suspend_enabled());
// check verifier constraints
if(!clss->verify_constraints(VM_Global_State::loader_env)) {
assert(exn_raised());
return;
}
tmn_suspend_disable();
if (class_needs_initialization(clss)) {
clss->initialize();
}
tmn_suspend_enable();
} // class_initialize_from_jni
void class_initialize(Class *clss)
{
ASSERT_RAISE_AREA;
class_initialize_ex(clss);
}
void class_initialize_ex(Class *clss)
{
ASSERT_RAISE_AREA;
assert(!hythread_is_suspend_enabled());
// check verifier constraints
tmn_suspend_enable();
if(!clss->verify_constraints(VM_Global_State::loader_env)) {
assert(exn_raised());
tmn_suspend_disable();
return;
}
tmn_suspend_disable();
if(class_needs_initialization(clss)) {
clss->initialize();
}
} // class_initialize_ex
<|endoftext|>
|
<commit_before>#include "our_list.h"
//Insert function
void insert(Our_list* &l1,int ID_value) //Not tested
{
Our_list *add = new Our_list;
add->next = l1;
add->ID = ID_value;
}
void insert(Our_list* &l1,Our_list * el) //Not tested
{
el->next = l1;
}
int insert(Our_list* &l1,int ID_value,int itm_nr)
{
}
int insert(Our_list* &l1,Our_list * el, int itm_nr)
{
}
//Append function
void append(Our_list* l1,int ID_value) //Not tested
{
Our_list *temp = new Our_list;
temp->ID = ID_value;
while(l1 != NULL)
{
if(l1 == NULL)
l1->next = temp;
l1 = l1->next;
}
}
void append(Our_list* l1,Our_list * el)
{
}
//return Our_List funct
Our_list* connect(Our_list* l1,Our_list* l2)
{
}
Our_list* at(Our_list* l1, int n) //Not tested
{
Our_list* temp = l1;
for(int i=0; i<n; i++)
{
if(temp)
temp = temp->next;
}
return temp;
}
Our_list* last(Our_list *l1) //Not tested
{
while(l1->next != NULL)
{
l1 = l1->next;
}
return l1;
}
//Erase funct
void erase_first(Our_list* &l1)
{
}
int erase_first_n(Our_list* &l1,int n)
{
}
void erase_all(Our_list* &l1)
{
}
void erase_last(Our_list* &l1)
{
}
int erase_last_n(Our_list* &l1)
{
}
//Other funct
int length(Our_list* l1) //tested
{
int len;
while(l1->next != NULL)
{
len++;
l1 = l1->next;
}
return len;
}
bool xchange(Our_list* &l1, int n1, int n2)
{
Our_list* temp = l1;
Our_list* minus_a = NULL;
Our_list* minus_b = NULL;
Our_list* plus_a = NULL;
Our_list* plus_b = NULL;
Our_list* list_a = NULL;
Our_list* list_b = NULL;
for(int x=0; x<n1+2; x++)
{
if(x == n1)
list_a = temp;
if(x == n1-1)
minus_a = temp;
if(x == n1+1)
plus_a = temp;
if(temp != NULL)
temp = temp->next;
}
temp = l1;
for(int x=0; x<n2+2; x++)
{
if(x == n2)
list_b = temp;
if(x == n2-1)
minus_b = temp;
if(x == n2+1)
plus_b = temp;
if(temp != NULL)
temp = temp->next;
}
list_a->next = plus_b;
list_b->next = plus_a;
minus_a->next = list_b;
minus_b->next = list_a;
return true;
}
bool issorted_dec(Our_list *l1)
{
}
bool issorted_inc(Our_list *l1)
{
}
bool merge(Our_list *&l1, Our_list *l2)
{
}
bool merge(Our_list *&l1, int ID_val)
{
}
int extract(Our_list *l1, int ID_arr[], int n)
{
}
<commit_msg>Adding false return value<commit_after>#include "our_list.h"
//Insert function
void insert(Our_list* &l1,int ID_value) //Not tested
{
Our_list *add = new Our_list;
add->next = l1;
add->ID = ID_value;
}
void insert(Our_list* &l1,Our_list * el) //Not tested
{
el->next = l1;
}
int insert(Our_list* &l1,int ID_value,int itm_nr)
{
}
int insert(Our_list* &l1,Our_list * el, int itm_nr)
{
}
//Append function
void append(Our_list* l1,int ID_value) //Not tested
{
Our_list *temp = new Our_list;
temp->ID = ID_value;
while(l1 != NULL)
{
if(l1 == NULL)
l1->next = temp;
l1 = l1->next;
}
}
void append(Our_list* l1,Our_list * el)
{
}
//return Our_List funct
Our_list* connect(Our_list* l1,Our_list* l2)
{
}
Our_list* at(Our_list* l1, int n) //Not tested
{
Our_list* temp = l1;
for(int i=0; i<n; i++)
{
if(temp)
temp = temp->next;
}
return temp;
}
Our_list* last(Our_list *l1) //Not tested
{
while(l1->next != NULL)
{
l1 = l1->next;
}
return l1;
}
//Erase funct
void erase_first(Our_list* &l1)
{
}
int erase_first_n(Our_list* &l1,int n)
{
}
void erase_all(Our_list* &l1)
{
}
void erase_last(Our_list* &l1)
{
}
int erase_last_n(Our_list* &l1)
{
}
//Other funct
int length(Our_list* l1) //tested
{
int len;
while(l1->next != NULL)
{
len++;
l1 = l1->next;
}
return len;
}
bool xchange(Our_list* &l1, int n1, int n2)
{
Our_list* temp = l1;
Our_list* minus_a = NULL;
Our_list* minus_b = NULL;
Our_list* plus_a = NULL;
Our_list* plus_b = NULL;
Our_list* list_a = NULL;
Our_list* list_b = NULL;
for(int x=0; x<n1+2; x++)
{
if(x == n1)
list_a = temp;
if(x == n1-1)
minus_a = temp;
if(x == n1+1)
plus_a = temp;
if(temp != NULL)
temp = temp->next;
else
return false;
}
temp = l1;
for(int x=0; x<n2+2; x++)
{
if(x == n2)
list_b = temp;
if(x == n2-1)
minus_b = temp;
if(x == n2+1)
plus_b = temp;
if(temp != NULL)
temp = temp->next;
else
return false;
}
list_a->next = plus_b;
list_b->next = plus_a;
minus_a->next = list_b;
minus_b->next = list_a;
return true;
}
bool issorted_dec(Our_list *l1)
{
}
bool issorted_inc(Our_list *l1)
{
}
bool merge(Our_list *&l1, Our_list *l2)
{
}
bool merge(Our_list *&l1, int ID_val)
{
}
int extract(Our_list *l1, int ID_arr[], int n)
{
}
<|endoftext|>
|
<commit_before>// ----------------------------------------------------------------------------
// PSP Player Emulation Suite
// Copyright (C) 2006 Ben Vanik (noxa)
// Licensed under the LGPL - see License.txt in the project root for details
// ----------------------------------------------------------------------------
#include "StdAfx.h"
#define WIN32_LEAN_AND_MEAN
#include <Windows.h>
#include <assert.h>
#include <string>
#include <cmath>
#pragma unmanaged
#include <gl/gl.h>
#include <gl/glu.h>
#include <gl/glext.h>
#include <gl/wglext.h>
#pragma managed
#include "OglDriver.h"
#include "VideoApi.h"
#include "OglContext.h"
#include "OglTextures.h"
#include "OglExtensions.h"
using namespace System::Diagnostics;
using namespace System::Threading;
using namespace Noxa::Emulation::Psp;
using namespace Noxa::Emulation::Psp::Video;
using namespace Noxa::Emulation::Psp::Video::Native;
void DrawBuffers( OglContext* context, int primitiveType, int vertexType, int vertexCount, byte* indexBuffer );
void SetupVertexBuffers( OglContext* context, int vertexType, int vertexCount, int vertexSize, byte* ptr );
#pragma unmanaged
void DrawBuffers( OglContext* context, int primitiveType, int vertexType, int vertexCount, byte* indexBuffer )
{
bool transformed = ( vertexType & VTTransformedMask ) != 0;
if( transformed == true )
{
glDisable( GL_CULL_FACE );
glMatrixMode( GL_PROJECTION );
glPushMatrix();
glLoadIdentity();
glOrtho( 0.0f, 480.0f, 272.0f, 0.0f, -1.0f, 1.0f );
glMatrixMode( GL_MODELVIEW );
glPushMatrix();
glLoadIdentity();
}
if( indexBuffer == NULL )
{
glDrawArrays( primitiveType, 0, vertexCount );
}
else
{
if( ( vertexType & VTIndex8 ) != 0 )
glDrawElements( primitiveType, vertexCount, GL_UNSIGNED_BYTE, indexBuffer );
else if( ( vertexType & VTIndex16 ) != 0 )
glDrawElements( primitiveType, vertexCount, GL_UNSIGNED_SHORT, indexBuffer );
}
if( transformed == true )
{
glPopMatrix();
glMatrixMode( GL_PROJECTION );
glPopMatrix();
glEnable( GL_CULL_FACE );
}
}
float _textureCoordBuffer[ 1024 * 10 ];
void SetupVertexBuffers( OglContext* context, int vertexType, int vertexCount, int vertexSize, byte* ptr )
{
// DO NOT SUPPORT WEIGHTS/MORPHING
// PSP comes in this order:
//float skinWeight[WEIGHTS_PER_VERTEX];
//float u,v;
//unsigned int color;
//float nx,ny,nz;
//float x,y,z;
bool transformed = ( vertexType & VTTransformedMask ) != 0;
GLenum format = 0;
int careMasks = VTPositionMask | VTNormalMask | VTTextureMask | VTColorMask;
int careType = vertexType & careMasks;
// Always assume V3F set
if( careType == ( VTTextureFloat | VTNormalFloat | VTPositionFloat ) )
format = GL_T2F_N3F_V3F;
else if( careType == ( VTTextureFloat | VTColorABGR8888 | VTPositionFloat ) )
format = GL_T2F_C4UB_V3F;
else if( careType == ( VTColorABGR8888 | VTPositionFloat ) )
format = GL_C4UB_V3F;
else if( careType == ( VTTextureFloat | VTPositionFloat ) )
format = GL_T2F_V3F;
else if( careType == ( VTNormalFloat | VTPositionFloat ) )
format = GL_N3F_V3F;
else if( careType == VTPositionFloat )
format = GL_V3F;
// We can only support interleaved arrays if we are not transformed
if( ( format != 0 ) && ( transformed == false ) )
{
// Something we support - issue an interleaved array
glInterleavedArrays( format, vertexSize, ptr );
}
else
{
// Interleaved unsupported - use separate arrays
int positionType = ( vertexType & VTPositionMask );
int normalType = ( vertexType & VTNormalMask );
int textureType = ( vertexType & VTTextureMask );
int colorType = ( vertexType & VTColorMask );
int weightType = ( vertexType & VTWeightMask );
if( positionType != 0 )
glEnableClientState( GL_VERTEX_ARRAY );
else
glDisableClientState( GL_VERTEX_ARRAY );
if( normalType != 0 )
glEnableClientState( GL_NORMAL_ARRAY );
else
glDisableClientState( GL_NORMAL_ARRAY );
if( textureType != 0 )
glEnableClientState( GL_TEXTURE_COORD_ARRAY );
else
glDisableClientState( GL_TEXTURE_COORD_ARRAY );
if( colorType != 0 )
glEnableClientState( GL_COLOR_ARRAY );
else
glDisableClientState( GL_COLOR_ARRAY );
byte* src = ptr;
switch( textureType )
{
case VTTextureFixed8:
assert( false );
src += 2;
break;
case VTTextureFixed16:
if( transformed == true )
{
byte* sp = src;
float* dp = _textureCoordBuffer;
int textureWidth = context->Textures[ 0 ].Width;
int textureHeight = context->Textures[ 0 ].Height;
for( int n = 0; n < vertexCount; n++ )
{
ushort* usp = ( ushort* )sp;
*dp = ( ( float )*usp / textureWidth );
usp++;
dp++;
*dp = ( ( float )*usp / textureHeight );
dp++;
sp += vertexSize;
}
glTexCoordPointer( 2, GL_FLOAT, 0, _textureCoordBuffer );
}
else
glTexCoordPointer( 2, GL_SHORT, vertexSize, src );
src += 4;
break;
case VTTextureFloat:
if( transformed == true )
{
byte* sp = src;
float* dp = _textureCoordBuffer;
int textureWidth = context->Textures[ 0 ].Width;
int textureHeight = context->Textures[ 0 ].Height;
for( int n = 0; n < vertexCount; n++ )
{
float* usp = ( float* )sp;
*dp = ( ( float )*usp / textureWidth );
usp++;
dp++;
*dp = ( ( float )*usp / textureHeight );
dp++;
sp += vertexSize;
}
glTexCoordPointer( 2, GL_FLOAT, 0, _textureCoordBuffer );
}
else
glTexCoordPointer( 2, GL_FLOAT, vertexSize, src );
src += 8;
break;
}
switch( colorType )
{
case VTColorBGR5650:
assert( false );
src += 2;
break;
case VTColorABGR4444:
assert( false );
src += 2;
break;
case VTColorABGR5551:
assert( false );
src += 2;
break;
case VTColorABGR8888:
glColorPointer( 4, GL_UNSIGNED_BYTE, vertexSize, src );
src += 4;
break;
}
switch( normalType )
{
case VTNormalFixed8:
glNormalPointer( GL_BYTE, vertexSize, src );
src += 3;
break;
case VTNormalFixed16:
glNormalPointer( GL_SHORT, vertexSize, src );
src += 6;
break;
case VTNormalFloat:
glNormalPointer( GL_FLOAT, vertexSize, src );
src += 12;
break;
}
switch( positionType )
{
case VTPositionFixed8:
glVertexPointer( 3, GL_BYTE, vertexSize, src ); // THIS MAY NOT WORK!!!
src += 3;
break;
case VTPositionFixed16:
glVertexPointer( 3, GL_SHORT, vertexSize, src );
src += 6;
break;
case VTPositionFloat:
glVertexPointer( 3, GL_FLOAT, vertexSize, src );
src += 12;
break;
}
}
}
#pragma managed
<commit_msg>WOOOO Quick hack to get Puzzle Bobble displaying stuff (by randomly setting the color of things drawn). Everything seems to be drawn - the game even runs! This means that it's just textures that are not working now!<commit_after>// ----------------------------------------------------------------------------
// PSP Player Emulation Suite
// Copyright (C) 2006 Ben Vanik (noxa)
// Licensed under the LGPL - see License.txt in the project root for details
// ----------------------------------------------------------------------------
#include "StdAfx.h"
#define WIN32_LEAN_AND_MEAN
#include <Windows.h>
#include <assert.h>
#include <string>
#include <cmath>
#pragma unmanaged
#include <gl/gl.h>
#include <gl/glu.h>
#include <gl/glext.h>
#include <gl/wglext.h>
#pragma managed
#include "OglDriver.h"
#include "VideoApi.h"
#include "OglContext.h"
#include "OglTextures.h"
#include "OglExtensions.h"
using namespace System::Diagnostics;
using namespace System::Threading;
using namespace Noxa::Emulation::Psp;
using namespace Noxa::Emulation::Psp::Video;
using namespace Noxa::Emulation::Psp::Video::Native;
void DrawBuffers( OglContext* context, int primitiveType, int vertexType, int vertexCount, byte* indexBuffer );
void SetupVertexBuffers( OglContext* context, int vertexType, int vertexCount, int vertexSize, byte* ptr );
#pragma unmanaged
void DrawBuffers( OglContext* context, int primitiveType, int vertexType, int vertexCount, byte* indexBuffer )
{
bool transformed = ( vertexType & VTTransformedMask ) != 0;
if( transformed == true )
{
glDisable( GL_CULL_FACE );
glMatrixMode( GL_PROJECTION );
glPushMatrix();
glLoadIdentity();
glOrtho( 0.0f, 480.0f, 272.0f, 0.0f, -1.0f, 1.0f );
glMatrixMode( GL_MODELVIEW );
glPushMatrix();
glLoadIdentity();
}
if( indexBuffer == NULL )
{
glDrawArrays( primitiveType, 0, vertexCount );
}
else
{
if( ( vertexType & VTIndex8 ) != 0 )
glDrawElements( primitiveType, vertexCount, GL_UNSIGNED_BYTE, indexBuffer );
else if( ( vertexType & VTIndex16 ) != 0 )
glDrawElements( primitiveType, vertexCount, GL_UNSIGNED_SHORT, indexBuffer );
}
if( transformed == true )
{
glPopMatrix();
glMatrixMode( GL_PROJECTION );
glPopMatrix();
glEnable( GL_CULL_FACE );
}
}
float _textureCoordBuffer[ 1024 * 10 ];
void SetupVertexBuffers( OglContext* context, int vertexType, int vertexCount, int vertexSize, byte* ptr )
{
// DO NOT SUPPORT WEIGHTS/MORPHING
// PSP comes in this order:
//float skinWeight[WEIGHTS_PER_VERTEX];
//float u,v;
//unsigned int color;
//float nx,ny,nz;
//float x,y,z;
bool transformed = ( vertexType & VTTransformedMask ) != 0;
GLenum format = 0;
int careMasks = VTPositionMask | VTNormalMask | VTTextureMask | VTColorMask;
int careType = vertexType & careMasks;
// Always assume V3F set
if( careType == ( VTTextureFloat | VTNormalFloat | VTPositionFloat ) )
format = GL_T2F_N3F_V3F;
else if( careType == ( VTTextureFloat | VTColorABGR8888 | VTPositionFloat ) )
format = GL_T2F_C4UB_V3F;
else if( careType == ( VTColorABGR8888 | VTPositionFloat ) )
format = GL_C4UB_V3F;
else if( careType == ( VTTextureFloat | VTPositionFloat ) )
format = GL_T2F_V3F;
else if( careType == ( VTNormalFloat | VTPositionFloat ) )
format = GL_N3F_V3F;
else if( careType == VTPositionFloat )
format = GL_V3F;
// We can only support interleaved arrays if we are not transformed
if( ( format != 0 ) && ( transformed == false ) )
{
// Something we support - issue an interleaved array
glInterleavedArrays( format, vertexSize, ptr );
}
else
{
// Interleaved unsupported - use separate arrays
int positionType = ( vertexType & VTPositionMask );
int normalType = ( vertexType & VTNormalMask );
int textureType = ( vertexType & VTTextureMask );
int colorType = ( vertexType & VTColorMask );
int weightType = ( vertexType & VTWeightMask );
if( positionType != 0 )
glEnableClientState( GL_VERTEX_ARRAY );
else
glDisableClientState( GL_VERTEX_ARRAY );
if( normalType != 0 )
glEnableClientState( GL_NORMAL_ARRAY );
else
glDisableClientState( GL_NORMAL_ARRAY );
if( textureType != 0 )
glEnableClientState( GL_TEXTURE_COORD_ARRAY );
else
glDisableClientState( GL_TEXTURE_COORD_ARRAY );
if( colorType != 0 )
glEnableClientState( GL_COLOR_ARRAY );
else
glDisableClientState( GL_COLOR_ARRAY );
byte* src = ptr;
switch( textureType )
{
case VTTextureFixed8:
assert( false );
src += 2;
break;
case VTTextureFixed16:
if( transformed == true )
{
byte* sp = src;
float* dp = _textureCoordBuffer;
int textureWidth = context->Textures[ 0 ].Width;
int textureHeight = context->Textures[ 0 ].Height;
for( int n = 0; n < vertexCount; n++ )
{
ushort* usp = ( ushort* )sp;
*dp = ( ( float )*usp / textureWidth );
usp++;
dp++;
*dp = ( ( float )*usp / textureHeight );
dp++;
sp += vertexSize;
}
glTexCoordPointer( 2, GL_FLOAT, 0, _textureCoordBuffer );
}
else
glTexCoordPointer( 2, GL_SHORT, vertexSize, src );
src += 4;
break;
case VTTextureFloat:
if( transformed == true )
{
byte* sp = src;
float* dp = _textureCoordBuffer;
int textureWidth = context->Textures[ 0 ].Width;
int textureHeight = context->Textures[ 0 ].Height;
for( int n = 0; n < vertexCount; n++ )
{
float* usp = ( float* )sp;
*dp = ( ( float )*usp / textureWidth );
usp++;
dp++;
*dp = ( ( float )*usp / textureHeight );
dp++;
sp += vertexSize;
}
glTexCoordPointer( 2, GL_FLOAT, 0, _textureCoordBuffer );
}
else
glTexCoordPointer( 2, GL_FLOAT, vertexSize, src );
src += 8;
break;
}
switch( colorType )
{
case VTColorBGR5650:
assert( false );
src += 2;
break;
case VTColorABGR4444:
assert( false );
src += 2;
break;
case VTColorABGR5551:
assert( false );
src += 2;
break;
case VTColorABGR8888:
glColorPointer( 4, GL_UNSIGNED_BYTE, vertexSize, src );
src += 4;
break;
}
float f = ( float )rand() / RAND_MAX;
glColor3f( f, f, f );
switch( normalType )
{
case VTNormalFixed8:
glNormalPointer( GL_BYTE, vertexSize, src );
src += 3;
break;
case VTNormalFixed16:
glNormalPointer( GL_SHORT, vertexSize, src );
src += 6;
break;
case VTNormalFloat:
glNormalPointer( GL_FLOAT, vertexSize, src );
src += 12;
break;
}
switch( positionType )
{
case VTPositionFixed8:
glVertexPointer( 3, GL_BYTE, vertexSize, src ); // THIS MAY NOT WORK!!!
src += 3;
break;
case VTPositionFixed16:
glVertexPointer( 3, GL_SHORT, vertexSize, src );
src += 6;
break;
case VTPositionFloat:
glVertexPointer( 3, GL_FLOAT, vertexSize, src );
src += 12;
break;
}
}
}
#pragma managed
<|endoftext|>
|
<commit_before>//===-- ProcessFreeBSD.cpp ----------------------------------------*- C++ -*-===//
//
// The LLVM Compiler Infrastructure
//
// This file is distributed under the University of Illinois Open Source
// License. See LICENSE.TXT for details.
//
//===----------------------------------------------------------------------===//
// C Includes
#include <errno.h>
// C++ Includes
// Other libraries and framework includes
#include "lldb/Core/PluginManager.h"
#include "lldb/Core/State.h"
#include "lldb/Host/Host.h"
#include "lldb/Symbol/ObjectFile.h"
#include "lldb/Target/DynamicLoader.h"
#include "lldb/Target/Target.h"
#include "ProcessFreeBSD.h"
#include "ProcessPOSIXLog.h"
#include "Plugins/Process/Utility/InferiorCallPOSIX.h"
#include "ProcessMonitor.h"
#include "FreeBSDThread.h"
using namespace lldb;
using namespace lldb_private;
//------------------------------------------------------------------------------
// Static functions.
lldb::ProcessSP
ProcessFreeBSD::CreateInstance(Target& target,
Listener &listener,
const FileSpec *crash_file_path)
{
lldb::ProcessSP process_sp;
if (crash_file_path == NULL)
process_sp.reset(new ProcessFreeBSD (target, listener));
return process_sp;
}
void
ProcessFreeBSD::Initialize()
{
static bool g_initialized = false;
if (!g_initialized)
{
PluginManager::RegisterPlugin(GetPluginNameStatic(),
GetPluginDescriptionStatic(),
CreateInstance);
Log::Callbacks log_callbacks = {
ProcessPOSIXLog::DisableLog,
ProcessPOSIXLog::EnableLog,
ProcessPOSIXLog::ListLogCategories
};
Log::RegisterLogChannel (ProcessFreeBSD::GetPluginNameStatic(), log_callbacks);
ProcessPOSIXLog::RegisterPluginName(GetPluginNameStatic());
g_initialized = true;
}
}
lldb_private::ConstString
ProcessFreeBSD::GetPluginNameStatic()
{
static ConstString g_name("freebsd");
return g_name;
}
const char *
ProcessFreeBSD::GetPluginDescriptionStatic()
{
return "Process plugin for FreeBSD";
}
//------------------------------------------------------------------------------
// ProcessInterface protocol.
lldb_private::ConstString
ProcessFreeBSD::GetPluginName()
{
return GetPluginNameStatic();
}
uint32_t
ProcessFreeBSD::GetPluginVersion()
{
return 1;
}
void
ProcessFreeBSD::GetPluginCommandHelp(const char *command, Stream *strm)
{
}
Error
ProcessFreeBSD::ExecutePluginCommand(Args &command, Stream *strm)
{
return Error(1, eErrorTypeGeneric);
}
Log *
ProcessFreeBSD::EnablePluginLogging(Stream *strm, Args &command)
{
return NULL;
}
//------------------------------------------------------------------------------
// Constructors and destructors.
ProcessFreeBSD::ProcessFreeBSD(Target& target, Listener &listener)
: ProcessPOSIX(target, listener)
{
}
void
ProcessFreeBSD::Terminate()
{
}
Error
ProcessFreeBSD::DoDetach(bool keep_stopped)
{
Error error;
if (keep_stopped)
{
error.SetErrorString("Detaching with keep_stopped true is not currently supported on FreeBSD.");
return error;
}
error = m_monitor->Detach(GetID());
if (error.Success())
SetPrivateState(eStateDetached);
return error;
}
Error
ProcessFreeBSD::DoResume()
{
Log *log (ProcessPOSIXLog::GetLogIfAllCategoriesSet (POSIX_LOG_PROCESS));
// FreeBSD's ptrace() uses 0 to indicate "no signal is to be sent."
int resume_signal = 0;
SetPrivateState(eStateRunning);
Mutex::Locker lock(m_thread_list.GetMutex());
bool do_step = false;
for (tid_collection::const_iterator t_pos = m_run_tids.begin(), t_end = m_run_tids.end(); t_pos != t_end; ++t_pos)
{
m_monitor->ThreadSuspend(*t_pos, false);
}
for (tid_collection::const_iterator t_pos = m_step_tids.begin(), t_end = m_step_tids.end(); t_pos != t_end; ++t_pos)
{
m_monitor->ThreadSuspend(*t_pos, false);
do_step = true;
}
for (tid_collection::const_iterator t_pos = m_suspend_tids.begin(), t_end = m_suspend_tids.end(); t_pos != t_end; ++t_pos)
{
m_monitor->ThreadSuspend(*t_pos, true);
// XXX Cannot PT_CONTINUE properly with suspended threads.
do_step = true;
}
if (log)
log->Printf("process %lu resuming (%s)", GetID(), do_step ? "step" : "continue");
if (do_step)
m_monitor->SingleStep(GetID(), resume_signal);
else
m_monitor->Resume(GetID(), resume_signal);
return Error();
}
bool
ProcessFreeBSD::UpdateThreadList(ThreadList &old_thread_list, ThreadList &new_thread_list)
{
Log *log (ProcessPOSIXLog::GetLogIfAllCategoriesSet (POSIX_LOG_PROCESS));
if (log)
log->Printf("ProcessFreeBSD::%s (pid = %" PRIu64 ")", __FUNCTION__, GetID());
std::vector<lldb::pid_t> tds;
if (!GetMonitor().GetCurrentThreadIDs(tds))
{
return false;
}
ThreadList old_thread_list_copy(old_thread_list);
for (size_t i = 0; i < tds.size(); ++i)
{
tid_t tid = tds[i];
ThreadSP thread_sp (old_thread_list_copy.RemoveThreadByID(tid, false));
if (!thread_sp)
{
thread_sp.reset(new FreeBSDThread(*this, tid));
if (log)
log->Printf("ProcessFreeBSD::%s new tid = %" PRIu64, __FUNCTION__, tid);
}
else
{
if (log)
log->Printf("ProcessFreeBSD::%s existing tid = %" PRIu64, __FUNCTION__, tid);
}
new_thread_list.AddThread(thread_sp);
}
for (size_t i = 0; i < old_thread_list_copy.GetSize(false); ++i)
{
ThreadSP old_thread_sp(old_thread_list_copy.GetThreadAtIndex(i, false));
if (old_thread_sp)
{
if (log)
log->Printf("ProcessFreeBSD::%s remove tid", __FUNCTION__);
}
}
return true;
}
Error
ProcessFreeBSD::WillResume()
{
m_suspend_tids.clear();
m_run_tids.clear();
m_step_tids.clear();
return ProcessPOSIX::WillResume();
}
void
ProcessFreeBSD::SendMessage(const ProcessMessage &message)
{
Mutex::Locker lock(m_message_mutex);
switch (message.GetKind())
{
case ProcessMessage::eInvalidMessage:
return;
case ProcessMessage::eAttachMessage:
SetPrivateState(eStateStopped);
return;
case ProcessMessage::eLimboMessage:
case ProcessMessage::eExitMessage:
m_exit_status = message.GetExitStatus();
SetExitStatus(m_exit_status, NULL);
break;
case ProcessMessage::eSignalMessage:
case ProcessMessage::eSignalDeliveredMessage:
case ProcessMessage::eBreakpointMessage:
case ProcessMessage::eTraceMessage:
case ProcessMessage::eWatchpointMessage:
case ProcessMessage::eCrashMessage:
SetPrivateState(eStateStopped);
break;
case ProcessMessage::eNewThreadMessage:
assert(0 && "eNewThreadMessage unexpected on FreeBSD");
break;
case ProcessMessage::eExecMessage:
SetPrivateState(eStateStopped);
break;
}
m_message_queue.push(message);
}
<commit_msg>Disable breakpoint sites upon detach on FreeBSD<commit_after>//===-- ProcessFreeBSD.cpp ----------------------------------------*- C++ -*-===//
//
// The LLVM Compiler Infrastructure
//
// This file is distributed under the University of Illinois Open Source
// License. See LICENSE.TXT for details.
//
//===----------------------------------------------------------------------===//
// C Includes
#include <errno.h>
// C++ Includes
// Other libraries and framework includes
#include "lldb/Core/PluginManager.h"
#include "lldb/Core/State.h"
#include "lldb/Host/Host.h"
#include "lldb/Symbol/ObjectFile.h"
#include "lldb/Target/DynamicLoader.h"
#include "lldb/Target/Target.h"
#include "ProcessFreeBSD.h"
#include "ProcessPOSIXLog.h"
#include "Plugins/Process/Utility/InferiorCallPOSIX.h"
#include "ProcessMonitor.h"
#include "FreeBSDThread.h"
using namespace lldb;
using namespace lldb_private;
//------------------------------------------------------------------------------
// Static functions.
lldb::ProcessSP
ProcessFreeBSD::CreateInstance(Target& target,
Listener &listener,
const FileSpec *crash_file_path)
{
lldb::ProcessSP process_sp;
if (crash_file_path == NULL)
process_sp.reset(new ProcessFreeBSD (target, listener));
return process_sp;
}
void
ProcessFreeBSD::Initialize()
{
static bool g_initialized = false;
if (!g_initialized)
{
PluginManager::RegisterPlugin(GetPluginNameStatic(),
GetPluginDescriptionStatic(),
CreateInstance);
Log::Callbacks log_callbacks = {
ProcessPOSIXLog::DisableLog,
ProcessPOSIXLog::EnableLog,
ProcessPOSIXLog::ListLogCategories
};
Log::RegisterLogChannel (ProcessFreeBSD::GetPluginNameStatic(), log_callbacks);
ProcessPOSIXLog::RegisterPluginName(GetPluginNameStatic());
g_initialized = true;
}
}
lldb_private::ConstString
ProcessFreeBSD::GetPluginNameStatic()
{
static ConstString g_name("freebsd");
return g_name;
}
const char *
ProcessFreeBSD::GetPluginDescriptionStatic()
{
return "Process plugin for FreeBSD";
}
//------------------------------------------------------------------------------
// ProcessInterface protocol.
lldb_private::ConstString
ProcessFreeBSD::GetPluginName()
{
return GetPluginNameStatic();
}
uint32_t
ProcessFreeBSD::GetPluginVersion()
{
return 1;
}
void
ProcessFreeBSD::GetPluginCommandHelp(const char *command, Stream *strm)
{
}
Error
ProcessFreeBSD::ExecutePluginCommand(Args &command, Stream *strm)
{
return Error(1, eErrorTypeGeneric);
}
Log *
ProcessFreeBSD::EnablePluginLogging(Stream *strm, Args &command)
{
return NULL;
}
//------------------------------------------------------------------------------
// Constructors and destructors.
ProcessFreeBSD::ProcessFreeBSD(Target& target, Listener &listener)
: ProcessPOSIX(target, listener)
{
}
void
ProcessFreeBSD::Terminate()
{
}
Error
ProcessFreeBSD::DoDetach(bool keep_stopped)
{
Error error;
if (keep_stopped)
{
error.SetErrorString("Detaching with keep_stopped true is not currently supported on FreeBSD.");
return error;
}
DisableAllBreakpointSites();
error = m_monitor->Detach(GetID());
if (error.Success())
SetPrivateState(eStateDetached);
return error;
}
Error
ProcessFreeBSD::DoResume()
{
Log *log (ProcessPOSIXLog::GetLogIfAllCategoriesSet (POSIX_LOG_PROCESS));
// FreeBSD's ptrace() uses 0 to indicate "no signal is to be sent."
int resume_signal = 0;
SetPrivateState(eStateRunning);
Mutex::Locker lock(m_thread_list.GetMutex());
bool do_step = false;
for (tid_collection::const_iterator t_pos = m_run_tids.begin(), t_end = m_run_tids.end(); t_pos != t_end; ++t_pos)
{
m_monitor->ThreadSuspend(*t_pos, false);
}
for (tid_collection::const_iterator t_pos = m_step_tids.begin(), t_end = m_step_tids.end(); t_pos != t_end; ++t_pos)
{
m_monitor->ThreadSuspend(*t_pos, false);
do_step = true;
}
for (tid_collection::const_iterator t_pos = m_suspend_tids.begin(), t_end = m_suspend_tids.end(); t_pos != t_end; ++t_pos)
{
m_monitor->ThreadSuspend(*t_pos, true);
// XXX Cannot PT_CONTINUE properly with suspended threads.
do_step = true;
}
if (log)
log->Printf("process %lu resuming (%s)", GetID(), do_step ? "step" : "continue");
if (do_step)
m_monitor->SingleStep(GetID(), resume_signal);
else
m_monitor->Resume(GetID(), resume_signal);
return Error();
}
bool
ProcessFreeBSD::UpdateThreadList(ThreadList &old_thread_list, ThreadList &new_thread_list)
{
Log *log (ProcessPOSIXLog::GetLogIfAllCategoriesSet (POSIX_LOG_PROCESS));
if (log)
log->Printf("ProcessFreeBSD::%s (pid = %" PRIu64 ")", __FUNCTION__, GetID());
std::vector<lldb::pid_t> tds;
if (!GetMonitor().GetCurrentThreadIDs(tds))
{
return false;
}
ThreadList old_thread_list_copy(old_thread_list);
for (size_t i = 0; i < tds.size(); ++i)
{
tid_t tid = tds[i];
ThreadSP thread_sp (old_thread_list_copy.RemoveThreadByID(tid, false));
if (!thread_sp)
{
thread_sp.reset(new FreeBSDThread(*this, tid));
if (log)
log->Printf("ProcessFreeBSD::%s new tid = %" PRIu64, __FUNCTION__, tid);
}
else
{
if (log)
log->Printf("ProcessFreeBSD::%s existing tid = %" PRIu64, __FUNCTION__, tid);
}
new_thread_list.AddThread(thread_sp);
}
for (size_t i = 0; i < old_thread_list_copy.GetSize(false); ++i)
{
ThreadSP old_thread_sp(old_thread_list_copy.GetThreadAtIndex(i, false));
if (old_thread_sp)
{
if (log)
log->Printf("ProcessFreeBSD::%s remove tid", __FUNCTION__);
}
}
return true;
}
Error
ProcessFreeBSD::WillResume()
{
m_suspend_tids.clear();
m_run_tids.clear();
m_step_tids.clear();
return ProcessPOSIX::WillResume();
}
void
ProcessFreeBSD::SendMessage(const ProcessMessage &message)
{
Mutex::Locker lock(m_message_mutex);
switch (message.GetKind())
{
case ProcessMessage::eInvalidMessage:
return;
case ProcessMessage::eAttachMessage:
SetPrivateState(eStateStopped);
return;
case ProcessMessage::eLimboMessage:
case ProcessMessage::eExitMessage:
m_exit_status = message.GetExitStatus();
SetExitStatus(m_exit_status, NULL);
break;
case ProcessMessage::eSignalMessage:
case ProcessMessage::eSignalDeliveredMessage:
case ProcessMessage::eBreakpointMessage:
case ProcessMessage::eTraceMessage:
case ProcessMessage::eWatchpointMessage:
case ProcessMessage::eCrashMessage:
SetPrivateState(eStateStopped);
break;
case ProcessMessage::eNewThreadMessage:
assert(0 && "eNewThreadMessage unexpected on FreeBSD");
break;
case ProcessMessage::eExecMessage:
SetPrivateState(eStateStopped);
break;
}
m_message_queue.push(message);
}
<|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/command_line.h"
#include "base/file_path.h"
#include "base/file_util.h"
#include "base/path_service.h"
#include "base/string_util.h"
#include "base/values.h"
#include "chrome/common/chrome_paths.h"
#include "chrome/common/chrome_switches.h"
#include "chrome/common/json_value_serializer.h"
#include "chrome/test/automation/tab_proxy.h"
#include "chrome/test/ui/javascript_test_util.h"
#include "chrome/test/ui/ui_test.h"
#include "googleurl/src/gurl.h"
#include "net/base/net_util.h"
namespace {
static const FilePath::CharType kStartFile[] =
FILE_PATH_LITERAL("index.html?dom|jslib&automated");
const wchar_t kRunDromaeo[] = L"run-dromaeo-benchmark";
class DromaeoTest : public UITest {
public:
typedef std::map<std::string, std::string> ResultsMap;
DromaeoTest() : reference_(false) {
dom_automation_enabled_ = true;
show_window_ = true;
}
void RunTest() {
FilePath::StringType start_file(kStartFile);
FilePath test_path = GetDromaeoDir();
test_path = test_path.Append(start_file);
GURL test_url(net::FilePathToFileURL(test_path));
scoped_refptr<TabProxy> tab(GetActiveTab());
tab->NavigateToURL(test_url);
// Wait for the test to finish.
ASSERT_TRUE(WaitUntilTestCompletes(tab.get(), test_url));
PrintResults(tab.get());
}
protected:
bool reference_; // True if this is a reference build.
private:
// Return the path to the dromaeo benchmark directory on the local filesystem.
FilePath GetDromaeoDir() {
FilePath test_dir;
PathService::Get(chrome::DIR_TEST_DATA, &test_dir);
return test_dir.AppendASCII("dromaeo");
}
bool WaitUntilTestCompletes(TabProxy* tab, const GURL& test_url) {
return WaitUntilCookieValue(tab, test_url, "__done", 1000,
UITest::test_timeout_ms(), "1");
}
bool GetScore(TabProxy* tab, std::string* score) {
std::wstring score_wide;
bool succeeded = tab->ExecuteAndExtractString(L"",
L"window.domAutomationController.send(automation.GetScore());",
&score_wide);
// Note that we don't use ASSERT_TRUE here (and in some other places) as it
// doesn't work inside a function with a return type other than void.
EXPECT_TRUE(succeeded);
if (!succeeded)
return false;
score->assign(WideToUTF8(score_wide));
return true;
}
bool GetResults(TabProxy* tab, ResultsMap* results) {
std::wstring json_wide;
bool succeeded = tab->ExecuteAndExtractString(L"",
L"window.domAutomationController.send("
L" JSON.stringify(automation.GetResults()));",
&json_wide);
EXPECT_TRUE(succeeded);
if (!succeeded)
return false;
std::string json = WideToUTF8(json_wide);
return JsonDictionaryToMap(json, results);
}
void PrintResults(TabProxy* tab) {
std::string score;
ASSERT_TRUE(GetScore(tab, &score));
ResultsMap results;
ASSERT_TRUE(GetResults(tab, &results));
std::string trace_name = reference_ ? "score_ref" : "score";
std::string unit_name = "runs/s";
PrintResult("score", "", trace_name, score, unit_name, true);
ResultsMap::const_iterator it = results.begin();
for (; it != results.end(); ++it) {
std::string test_name = it->first;
for (size_t i = 0; i < test_name.length(); i++)
if (!isalnum(test_name[i]))
test_name[i] = '_';
PrintResult(test_name, "", trace_name, it->second, unit_name, false);
}
}
DISALLOW_COPY_AND_ASSIGN(DromaeoTest);
};
class DromaeoReferenceTest : public DromaeoTest {
public:
DromaeoReferenceTest() : DromaeoTest() {
reference_ = true;
}
// Override the browser directory that is used by UITest::SetUp to cause it
// to use the reference build instead.
void SetUp() {
FilePath dir;
PathService::Get(chrome::DIR_TEST_TOOLS, &dir);
dir = dir.AppendASCII("reference_build");
#if defined(OS_WIN)
dir = dir.AppendASCII("chrome");
#elif defined(OS_LINUX)
dir = dir.AppendASCII("chrome_linux");
#elif defined(OS_MACOSX)
dir = dir.AppendASCII("chrome_mac");
#endif
browser_directory_ = dir;
UITest::SetUp();
}
};
TEST_F(DromaeoTest, Perf) {
if (!CommandLine::ForCurrentProcess()->HasSwitch(kRunDromaeo))
return;
RunTest();
}
TEST_F(DromaeoReferenceTest, Perf) {
if (!CommandLine::ForCurrentProcess()->HasSwitch(kRunDromaeo))
return;
RunTest();
}
} // namespace
<commit_msg>Split Dromaeo test per suite.<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/command_line.h"
#include "base/file_path.h"
#include "base/file_util.h"
#include "base/path_service.h"
#include "base/string_util.h"
#include "base/values.h"
#include "chrome/common/chrome_paths.h"
#include "chrome/common/chrome_switches.h"
#include "chrome/common/json_value_serializer.h"
#include "chrome/test/automation/tab_proxy.h"
#include "chrome/test/ui/javascript_test_util.h"
#include "chrome/test/ui/ui_test.h"
#include "googleurl/src/gurl.h"
#include "net/base/net_util.h"
namespace {
const wchar_t kRunDromaeo[] = L"run-dromaeo-benchmark";
class DromaeoTest : public UITest {
public:
typedef std::map<std::string, std::string> ResultsMap;
DromaeoTest() : reference_(false) {
dom_automation_enabled_ = true;
show_window_ = true;
}
void RunTest(const FilePath::CharType* suite) {
FilePath test_path = GetDromaeoDir();
test_path = test_path.Append(
FilePath::StringType(FILE_PATH_LITERAL("index.html?")) +
FilePath::StringType(suite) +
FilePath::StringType(FILE_PATH_LITERAL("&automated")));
GURL test_url(net::FilePathToFileURL(test_path));
scoped_refptr<TabProxy> tab(GetActiveTab());
tab->NavigateToURL(test_url);
// Wait for the test to finish.
ASSERT_TRUE(WaitUntilTestCompletes(tab.get(), test_url));
PrintResults(tab.get());
}
protected:
bool reference_; // True if this is a reference build.
private:
// Return the path to the dromaeo benchmark directory on the local filesystem.
FilePath GetDromaeoDir() {
FilePath test_dir;
PathService::Get(chrome::DIR_TEST_DATA, &test_dir);
return test_dir.AppendASCII("dromaeo");
}
bool WaitUntilTestCompletes(TabProxy* tab, const GURL& test_url) {
return WaitUntilCookieValue(tab, test_url, "__done", 1000,
UITest::test_timeout_ms(), "1");
}
bool GetScore(TabProxy* tab, std::string* score) {
std::wstring score_wide;
bool succeeded = tab->ExecuteAndExtractString(L"",
L"window.domAutomationController.send(automation.GetScore());",
&score_wide);
// Note that we don't use ASSERT_TRUE here (and in some other places) as it
// doesn't work inside a function with a return type other than void.
EXPECT_TRUE(succeeded);
if (!succeeded)
return false;
score->assign(WideToUTF8(score_wide));
return true;
}
bool GetResults(TabProxy* tab, ResultsMap* results) {
std::wstring json_wide;
bool succeeded = tab->ExecuteAndExtractString(L"",
L"window.domAutomationController.send("
L" JSON.stringify(automation.GetResults()));",
&json_wide);
EXPECT_TRUE(succeeded);
if (!succeeded)
return false;
std::string json = WideToUTF8(json_wide);
return JsonDictionaryToMap(json, results);
}
void PrintResults(TabProxy* tab) {
std::string score;
ASSERT_TRUE(GetScore(tab, &score));
ResultsMap results;
ASSERT_TRUE(GetResults(tab, &results));
std::string trace_name = reference_ ? "score_ref" : "score";
std::string unit_name = "runs/s";
PrintResult("score", "", trace_name, score, unit_name, true);
ResultsMap::const_iterator it = results.begin();
for (; it != results.end(); ++it) {
std::string test_name = it->first;
for (size_t i = 0; i < test_name.length(); i++)
if (!isalnum(test_name[i]))
test_name[i] = '_';
PrintResult(test_name, "", trace_name, it->second, unit_name, false);
}
}
DISALLOW_COPY_AND_ASSIGN(DromaeoTest);
};
class DromaeoReferenceTest : public DromaeoTest {
public:
DromaeoReferenceTest() : DromaeoTest() {
reference_ = true;
}
// Override the browser directory that is used by UITest::SetUp to cause it
// to use the reference build instead.
void SetUp() {
FilePath dir;
PathService::Get(chrome::DIR_TEST_TOOLS, &dir);
dir = dir.AppendASCII("reference_build");
#if defined(OS_WIN)
dir = dir.AppendASCII("chrome");
#elif defined(OS_LINUX)
dir = dir.AppendASCII("chrome_linux");
#elif defined(OS_MACOSX)
dir = dir.AppendASCII("chrome_mac");
#endif
browser_directory_ = dir;
UITest::SetUp();
}
};
TEST_F(DromaeoTest, DOMCorePerf) {
if (!CommandLine::ForCurrentProcess()->HasSwitch(kRunDromaeo))
return;
RunTest(FILE_PATH_LITERAL("dom"));
}
TEST_F(DromaeoTest, JSLibPerf) {
if (!CommandLine::ForCurrentProcess()->HasSwitch(kRunDromaeo))
return;
RunTest(FILE_PATH_LITERAL("jslib"));
}
TEST_F(DromaeoReferenceTest, DOMCorePerf) {
if (!CommandLine::ForCurrentProcess()->HasSwitch(kRunDromaeo))
return;
RunTest(FILE_PATH_LITERAL("dom"));
}
TEST_F(DromaeoReferenceTest, JSLibPerf) {
if (!CommandLine::ForCurrentProcess()->HasSwitch(kRunDromaeo))
return;
RunTest(FILE_PATH_LITERAL("jslib"));
}
} // namespace
<|endoftext|>
|
<commit_before><?hh
abstract class BaseStore {
protected $class;
protected $db;
public function __construct(string $collection = null, string $class = null) {
if (defined('static::COLLECTION') && defined('static::MODEL')) {
$collection = static::COLLECTION;
$class = static::MODEL;
}
invariant($collection && $class, 'Collection or class not provided');
$this->collection = $collection;
$this->class = $class;
$this->db = MongoInstance::get($collection);
}
public function db() {
return $this->db;
}
public function find(
array $query = [],
?int $skip = 0,
?int $limit = 0): BaseModel {
$docs = $this->db->find($query);
$class = $this->class;
if ($skip !== null) {
$docs = $docs->skip($skip);
}
if ($limit !== null) {
$limit = $docs->limit($limit);
}
foreach ($docs as $doc) {
yield new $class($doc);
}
}
public function paginatedFind($query, $skip = 0, $limit = 0) {
$class = $this->class;
$count = $this->db->count($query);
$docs = $this->db->find($query)->skip($skip)->limit($limit);
return $docs ?
new BaseStoreCursor($class, $count, $docs, $skip, $limit) :
false;
}
public function distinct($key, $query = []) {
$docs = $this->db->distinct($key, $query);
return !is_array($docs) ? [] : $docs;
}
public function findOne($query) {
$doc = $this->db->findOne($query);
$class = $this->class;
return $doc ? new $class($doc) : null;
}
public function findById($id) {
return $this->findOne(['_id' => mid($id)]);
}
public function count($query) {
return $this->db->count($query);
}
protected function ensureType(BaseModel $item) {
return class_exists($this->class) && is_a($item, $this->class);
}
public function remove(BaseModel $item) {
if (!$this->ensureType($item)) {
throw new Exception('Invalid object provided, expected ' . $this->class);
return false;
}
if ($item == null) {
return false;
}
try {
if ($item->getID()) {
$this->db->remove($item->document());
return true;
} else {
return false;
}
} catch (MongoException $e) {
l('MongoException:', $e->getMessage());
return false;
}
}
public function removeWhere($query = []) {
try {
$this->db->remove($query);
return true;
} catch (MongoException $e) {
l('MongoException:', $e->getMessage());
return false;
}
}
public function removeById($id) {
return $this->removeWhere(['_id' => mid($id)]);
}
protected function validateRequiredFields(BaseModel $item) {
foreach ($item->schema() as $field => $type) {
if ($field != '_id' &&
$type === BaseModel::REQUIRED && !$item->has($field)) {
return false;
}
}
return true;
}
public function aggregate(BaseAggregation $aggregation) {
return call_user_func_array(
[$this->db, 'aggregate'],
$aggregation->getPipeline());
}
public function mapReduce(
MongoCode $map,
MongoCode $reduce,
array $query = null,
array $config = null) {
$options = [
'mapreduce' => $this->collection,
'map' => $map,
'reduce' => $reduce,
'out' => ['inline' => true]];
if ($query) {
$options['query'] = $query;
}
if ($config) {
unset($options['mapreduce']);
unset($options['map']);
unset($options['reduce']);
unset($options['query']);
$options = array_merge($options, $config);
}
$res = MongoInstance::get()->command($options);
if (idx($res, 'ok')) {
return $res;
} else {
l('MapReduce error:', $res);
return null;
}
}
public function save(BaseModel &$item) {
if (!$this->ensureType($item)) {
throw new Exception('Invalid object provided, expected ' . $this->class);
return false;
}
if (!$this->validateRequiredFields($item)) {
throw new Exception('One or more required fields are missing.');
return false;
}
if ($item == null) {
return false;
}
try {
if (!$item->getID()) {
$id = new MongoID();
$item->setID($id);
}
$this->db->save($item->document());
return true;
} catch (MongoException $e) {
l('MongoException:', $e->getMessage());
return false;
}
return true;
}
}
class BaseStoreCursor {
protected
$class,
$count,
$cursor,
$next;
public function __construct($class, $count, $cursor, $skip, $limit) {
$this->class = $class;
$this->count = $count;
$this->cursor = $cursor;
$this->next = $count > $limit ? $skip + 1 : null;
}
public function count() {
return $this->count;
}
public function nextPage() {
return $this->next;
}
public function docs() {
$class = $this->class;
foreach ($this->cursor as $entry) {
yield new $class($entry);
}
}
}
class BaseAggregation {
protected $pipeline;
public function __construct() {
$this->pipeline = [];
}
public function getPipeline() {
return $this->pipeline;
}
public function project(array $spec) {
if (!empty($spec)) {
$this->pipeline[] = ['$project' => $spec];
}
return $this;
}
public function match(array $spec) {
if (!empty($spec)) {
$this->pipeline[] = ['$match' => $spec];
}
return $this;
}
public function limit($limit) {
$this->pipeline[] = ['$limit' => $limit];
return $this;
}
public function skip($skip) {
$this->pipeline[] = ['$skip' => $skip];
return $this;
}
public function unwind($field) {
$this->pipeline[] = ['$unwind' => '$' . $field];
return $this;
}
public function group(array $spec) {
if (!empty($spec)) {
$this->pipeline[] = ['$group' => $spec];
}
return $this;
}
public function sort(array $spec) {
if (!empty($spec)) {
$this->pipeline[] = ['$sort' => $spec];
}
return $this;
}
public function sum($value = 1) {
if (!is_numeric($value)) {
$value = '$' . $value;
}
return ['$sum' => $value];
}
public function __call($name, $args) {
$field = array_pop($args);
switch ($name) {
case 'addToSet':
case 'first':
case 'last':
case 'max':
case 'min':
case 'avg':
return ['$' . $name => '$' . $field];
}
throw new RuntimeException('Method not found: ' . $name);
}
public function push($field) {
if (is_array($field)) {
foreach ($field as &$f) {
$f = '$' . $f;
}
} else {
$field = '$' . $field;
}
return ['$push' => $field];
}
}
abstract class BaseModel {
protected MongoId $_id;
public function __construct(array<string, mixed> $document = []) {
foreach ($document as $key => $value) {
if (property_exists($this, $key)) {
$this->$key = $key == '_id' ? mid($value) : $value;
}
}
}
public function document(): array<string, mixed> {
$out = [];
foreach ($this as $key => $value) {
$out[$key] = $key == '_id' ? (string)$value : $value;
}
return $out;
}
final public function getID(): ?MongoId {
return $this->_id;
}
final public function setID(MongoId $_id): void {
$this->_id = $_id;
}
public function __call($method, $args) {
if (strpos($method, 'get') === 0) {
$op = 'get';
} elseif (strpos($method, 'set') === 0) {
$op = 'set';
} elseif (strpos($method, 'remove') === 0) {
$op = 'remove';
} elseif (strpos($method, 'has') === 0) {
$op = 'has';
} else {
$e = sprintf('Method "%s" not found in %s', $method, get_called_class());
throw new RuntimeException($e);
return null;
}
$method = preg_replace('/^(get|set|remove|has)/i', '', $method);
preg_match_all(
'!([A-Z][A-Z0-9]*(?=$|[A-Z][a-z0-9])|[A-Za-z][a-z0-9]+)!',
$method,
$matches);
$ret = $matches[0];
foreach ($ret as &$match) {
$match = $match == strtoupper($match) ?
strtolower($match) :
lcfirst($match);
}
$field = implode('_', $ret);
if ($this->strict && !idx($this->schema, $field)) {
$e = sprintf(
'"%s" is not a valid field for %s',
$field,
get_called_class());
throw new InvalidArgumentException($e);
return null;
}
$arg = array_pop($args);
if (!method_exists($this, $op)) {
$e = sprintf('%s::%s() is not defined', get_called_class(), $op);
throw new Exception($e);
}
return $op == 'set' ? $this->set($field, $arg) : $this->$op($field);
}
private function overriddenMethod($prefix, $key) {
$method = $prefix . preg_replace_callback(
'/(?:^|_)(.?)/',
function($matches) {
return strtolower($matches[0]);
},
$key);
return method_exists($this, $method) ? strtolower($method) : null;
}
public final function get(string $key): ?mixed {
invariant(
idx($this, $key),
'%s is not a valid field for %s',
$key,
get_called_class());
$method = $this->overriddenMethod(__FUNCTION__, $key);
if ($method) {
return $this->$method();
}
return idx($this, $key);
}
public final function set(string $key, mixed $value): void {
invariant(
idx($this, $key),
'%s is not a valid field for %s',
$key,
get_called_class());
$method = $this->overriddenMethod(__FUNCTION__, $key);
if ($method) {
return $this->$method($value);
}
$this->document[$key] = $value;
}
public function has(string $key): bool {
invariant(
idx($this, $key),
'%s is not a valid field for %s',
$key,
get_called_class());
$method = $this->overriddenMethod(__FUNCTION__, $key);
if ($method) {
return $this->$method();
}
return !!idx($this, $key, false);
}
public final function remove(string $key): void {
invariant(
idx($this, $key),
'%s is not a valid field for %s',
$key,
get_called_class());
$method = $this->overriddenMethod(__FUNCTION__, $key);
if ($method) {
$this->$method();
}
unset($this->$key);
}
}
<commit_msg>added typehint to BaseStore<commit_after><?hh
abstract class BaseStore {
protected $class;
protected $db;
public function __construct(string $collection = null, string $class = null) {
if (defined('static::COLLECTION') && defined('static::MODEL')) {
$collection = static::COLLECTION;
$class = static::MODEL;
}
invariant($collection && $class, 'Collection or class not provided');
$this->collection = $collection;
$this->class = $class;
$this->db = MongoInstance::get($collection);
}
public function db() {
return $this->db;
}
public function find(
array $query = [],
?int $skip = 0,
?int $limit = 0): BaseModel {
$docs = $this->db->find($query);
$class = $this->class;
if ($skip !== null) {
$docs = $docs->skip($skip);
}
if ($limit !== null) {
$limit = $docs->limit($limit);
}
foreach ($docs as $doc) {
yield new $class($doc);
}
}
public function distinct(string $key, array $query = []) {
$docs = $this->db->distinct($key, $query);
return !is_array($docs) ? [] : $docs;
}
public function findOne(array $query): ?BaseModel {
$doc = $this->db->findOne($query);
$class = $this->class;
return $doc ? new $class($doc) : null;
}
public function findById(MongoId $id): ?BaseModel {
return $this->findOne(['_id' => $id]);
}
public function count(array $query): int {
return $this->db->count($query);
}
protected function ensureType(BaseModel $item): bool {
return class_exists($this->class) && is_a($item, $this->class);
}
public function remove(BaseModel $item) {
if (!$this->ensureType($item)) {
throw new Exception('Invalid object provided, expected ' . $this->class);
return false;
}
if ($item == null) {
return false;
}
try {
if ($item->getID()) {
$this->db->remove($item->document());
return true;
} else {
return false;
}
} catch (MongoException $e) {
l('MongoException:', $e->getMessage());
return false;
}
}
public function removeWhere($query = []) {
try {
$this->db->remove($query);
return true;
} catch (MongoException $e) {
l('MongoException:', $e->getMessage());
return false;
}
}
public function removeById($id) {
return $this->removeWhere(['_id' => mid($id)]);
}
protected function validateRequiredFields(BaseModel $item) {
foreach ($item->schema() as $field => $type) {
if ($field != '_id' &&
$type === BaseModel::REQUIRED && !$item->has($field)) {
return false;
}
}
return true;
}
public function aggregate(BaseAggregation $aggregation) {
return call_user_func_array(
[$this->db, 'aggregate'],
$aggregation->getPipeline());
}
public function mapReduce(
MongoCode $map,
MongoCode $reduce,
array $query = null,
array $config = null) {
$options = [
'mapreduce' => $this->collection,
'map' => $map,
'reduce' => $reduce,
'out' => ['inline' => true]];
if ($query) {
$options['query'] = $query;
}
if ($config) {
unset($options['mapreduce']);
unset($options['map']);
unset($options['reduce']);
unset($options['query']);
$options = array_merge($options, $config);
}
$res = MongoInstance::get()->command($options);
if (idx($res, 'ok')) {
return $res;
} else {
l('MapReduce error:', $res);
return null;
}
}
public function save(BaseModel &$item) {
if (!$this->ensureType($item)) {
throw new Exception('Invalid object provided, expected ' . $this->class);
return false;
}
if (!$this->validateRequiredFields($item)) {
throw new Exception('One or more required fields are missing.');
return false;
}
if ($item == null) {
return false;
}
try {
if (!$item->getID()) {
$id = new MongoID();
$item->setID($id);
}
$this->db->save($item->document());
return true;
} catch (MongoException $e) {
l('MongoException:', $e->getMessage());
return false;
}
return true;
}
}
class BaseStoreCursor {
protected
$class,
$count,
$cursor,
$next;
public function __construct($class, $count, $cursor, $skip, $limit) {
$this->class = $class;
$this->count = $count;
$this->cursor = $cursor;
$this->next = $count > $limit ? $skip + 1 : null;
}
public function count() {
return $this->count;
}
public function nextPage() {
return $this->next;
}
public function docs() {
$class = $this->class;
foreach ($this->cursor as $entry) {
yield new $class($entry);
}
}
}
class BaseAggregation {
protected $pipeline;
public function __construct() {
$this->pipeline = [];
}
public function getPipeline() {
return $this->pipeline;
}
public function project(array $spec) {
if (!empty($spec)) {
$this->pipeline[] = ['$project' => $spec];
}
return $this;
}
public function match(array $spec) {
if (!empty($spec)) {
$this->pipeline[] = ['$match' => $spec];
}
return $this;
}
public function limit($limit) {
$this->pipeline[] = ['$limit' => $limit];
return $this;
}
public function skip($skip) {
$this->pipeline[] = ['$skip' => $skip];
return $this;
}
public function unwind($field) {
$this->pipeline[] = ['$unwind' => '$' . $field];
return $this;
}
public function group(array $spec) {
if (!empty($spec)) {
$this->pipeline[] = ['$group' => $spec];
}
return $this;
}
public function sort(array $spec) {
if (!empty($spec)) {
$this->pipeline[] = ['$sort' => $spec];
}
return $this;
}
public function sum($value = 1) {
if (!is_numeric($value)) {
$value = '$' . $value;
}
return ['$sum' => $value];
}
public function __call($name, $args) {
$field = array_pop($args);
switch ($name) {
case 'addToSet':
case 'first':
case 'last':
case 'max':
case 'min':
case 'avg':
return ['$' . $name => '$' . $field];
}
throw new RuntimeException('Method not found: ' . $name);
}
public function push($field) {
if (is_array($field)) {
foreach ($field as &$f) {
$f = '$' . $f;
}
} else {
$field = '$' . $field;
}
return ['$push' => $field];
}
}
abstract class BaseModel {
protected MongoId $_id;
public function __construct(array<string, mixed> $document = []) {
foreach ($document as $key => $value) {
if (property_exists($this, $key)) {
$this->$key = $key == '_id' ? mid($value) : $value;
}
}
}
public function document(): array<string, mixed> {
$out = [];
foreach ($this as $key => $value) {
$out[$key] = $key == '_id' ? (string)$value : $value;
}
return $out;
}
final public function getID(): ?MongoId {
return $this->_id;
}
final public function setID(MongoId $_id): void {
$this->_id = $_id;
}
public function __call($method, $args) {
if (strpos($method, 'get') === 0) {
$op = 'get';
} elseif (strpos($method, 'set') === 0) {
$op = 'set';
} elseif (strpos($method, 'remove') === 0) {
$op = 'remove';
} elseif (strpos($method, 'has') === 0) {
$op = 'has';
} else {
$e = sprintf('Method "%s" not found in %s', $method, get_called_class());
throw new RuntimeException($e);
return null;
}
// $method = preg_replace('/^(get|set|remove|has)/i', '', $method);
$method = preg_replace('/^(get|set)/i', '', $method);
preg_match_all(
'!([A-Z][A-Z0-9]*(?=$|[A-Z][a-z0-9])|[A-Za-z][a-z0-9]+)!',
$method,
$matches);
$ret = $matches[0];
foreach ($ret as &$match) {
$match = $match == strtoupper($match) ?
strtolower($match) :
lcfirst($match);
}
$field = implode('_', $ret);
$arg = array_pop($args);
if (!method_exists($this, $op)) {
$e = sprintf('%s::%s() is not defined', get_called_class(), $op);
throw new Exception($e);
}
switch ($op) {
case 'set':
$this->$field = $arg;
return;
case 'get':
invariant(
property_exists($this, $field),
'%s is not a valid field for %s',
$field,
get_called_class());
return $this->$field;
}
}
}
<|endoftext|>
|
<commit_before>#include <xpcc/architecture/platform.hpp>
#include "../stm32f4_discovery.hpp"
#include <xpcc/processing/timeout.hpp>
#include <xpcc/processing/protothread.hpp>
#include <xpcc/driver/temperature/tmp102.hpp>
#include <xpcc/io/iostream.hpp>
xpcc::IODeviceWrapper< Usart2, xpcc::IOBuffer::BlockIfFull > device;
xpcc::IOStream stream(device);
typedef I2cMaster1 MyI2cMaster;
class ThreadOne : public xpcc::pt::Protothread
{
public:
ThreadOne()
: temp(temperatureData, 0x48)
{
}
bool
update()
{
temp.update();
PT_BEGIN();
// ping the device until it responds
while(true)
{
// we wait until the task started
if (PT_CALL(temp.ping(this)))
break;
// otherwise, try again in 100ms
this->timer.restart(100);
PT_WAIT_UNTIL(this->timer.isExpired());
}
PT_CALL(temp.setUpdateRate(this, 200));
PT_CALL(temp.enableExtendedMode(this));
PT_CALL(temp.configureAlertMode(this,
xpcc::tmp102::ThermostatMode::Comparator,
xpcc::tmp102::AlertPolarity::ActiveLow,
xpcc::tmp102::FaultQueue::Faults6));
PT_CALL(temp.writeLowerLimit(this, 28.f));
PT_CALL(temp.writeUpperLimit(this, 30.f));
while (true)
{
{
PT_CALL(temp.readComparatorMode(this, result));
float temperature = temperatureData.getTemperature();
uint8_t tI = (int) temperature;
uint16_t tP = (temperature - tI) * 10000;
stream << "T= " << tI << ".";
if (tP == 0)
{
stream << "0000 C";
}
else if (tP == 625)
{
stream << "0" << tP << " C";
}
else
{
stream << tP << " C";
}
stream << xpcc::endl;
if (result) stream << "Heat me up!" << xpcc::endl;
}
this->timer.restart(200);
PT_WAIT_UNTIL(this->timer.isExpired());
LedRed::toggle();
}
PT_END();
}
private:
bool result;
xpcc::Timeout<> timer;
xpcc::tmp102::Data temperatureData;
xpcc::Tmp102<MyI2cMaster> temp;
};
ThreadOne one;
// ----------------------------------------------------------------------------
MAIN_FUNCTION
{
defaultSystemClock::enable();
xpcc::cortex::SysTickTimer::enable();
LedOrange::setOutput(xpcc::Gpio::High);
LedGreen::setOutput(xpcc::Gpio::Low);
LedRed::setOutput(xpcc::Gpio::High);
LedBlue::setOutput(xpcc::Gpio::High);
GpioOutputA2::connect(Usart2::Tx);
Usart2::initialize<defaultSystemClock, xpcc::Uart::B38400>(10);
GpioB7::connect(MyI2cMaster::Sda);
GpioB8::connect(MyI2cMaster::Scl);
GpioB7::configure(Gpio::InputType::PullUp);
GpioB8::configure(Gpio::InputType::PullUp);
MyI2cMaster::initialize<defaultSystemClock, 100000>();
stream << "\n\nRESTART\n\n";
while (1)
{
one.update();
LedOrange::toggle();
}
return 0;
}
<commit_msg>Examples: Adapt Protothreads example to Coroutine context change.<commit_after>#include <xpcc/architecture/platform.hpp>
#include "../stm32f4_discovery.hpp"
#include <xpcc/processing/timeout.hpp>
#include <xpcc/processing/protothread.hpp>
#include <xpcc/driver/temperature/tmp102.hpp>
#include <xpcc/io/iostream.hpp>
xpcc::IODeviceWrapper< Usart2, xpcc::IOBuffer::BlockIfFull > device;
xpcc::IOStream stream(device);
typedef I2cMaster1 MyI2cMaster;
class ThreadOne : public xpcc::pt::Protothread
{
public:
ThreadOne()
: temp(temperatureData, 0x48)
{
}
bool
update()
{
temp.update();
PT_BEGIN();
// ping the device until it responds
while(true)
{
// we wait until the task started
if (PT_CALL(temp.ping()))
break;
// otherwise, try again in 100ms
this->timer.restart(100);
PT_WAIT_UNTIL(this->timer.isExpired());
}
PT_CALL(temp.setUpdateRate(200));
PT_CALL(temp.enableExtendedMode());
PT_CALL(temp.configureAlertMode(
xpcc::tmp102::ThermostatMode::Comparator,
xpcc::tmp102::AlertPolarity::ActiveLow,
xpcc::tmp102::FaultQueue::Faults6));
PT_CALL(temp.writeLowerLimit(28.f));
PT_CALL(temp.writeUpperLimit(30.f));
while (true)
{
{
PT_CALL(temp.readComparatorMode(result));
float temperature = temperatureData.getTemperature();
uint8_t tI = (int) temperature;
uint16_t tP = (temperature - tI) * 10000;
stream << "T= " << tI << ".";
if (tP == 0)
{
stream << "0000 C";
}
else if (tP == 625)
{
stream << "0" << tP << " C";
}
else
{
stream << tP << " C";
}
stream << xpcc::endl;
if (result) stream << "Heat me up!" << xpcc::endl;
}
this->timer.restart(200);
PT_WAIT_UNTIL(this->timer.isExpired());
LedRed::toggle();
}
PT_END();
}
private:
bool result;
xpcc::Timeout<> timer;
xpcc::tmp102::Data temperatureData;
xpcc::Tmp102<MyI2cMaster> temp;
};
ThreadOne one;
// ----------------------------------------------------------------------------
MAIN_FUNCTION
{
defaultSystemClock::enable();
xpcc::cortex::SysTickTimer::enable();
LedOrange::setOutput(xpcc::Gpio::High);
LedGreen::setOutput(xpcc::Gpio::Low);
LedRed::setOutput(xpcc::Gpio::High);
LedBlue::setOutput(xpcc::Gpio::High);
GpioOutputA2::connect(Usart2::Tx);
Usart2::initialize<defaultSystemClock, xpcc::Uart::B38400>(10);
GpioB7::connect(MyI2cMaster::Sda);
GpioB8::connect(MyI2cMaster::Scl);
GpioB7::configure(Gpio::InputType::PullUp);
GpioB8::configure(Gpio::InputType::PullUp);
MyI2cMaster::initialize<defaultSystemClock, 100000>();
stream << "\n\nRESTART\n\n";
while (1)
{
one.update();
LedOrange::toggle();
}
return 0;
}
<|endoftext|>
|
<commit_before>/*
* Copyright (C) 2013 Google Inc. 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 Google Inc. 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.
*/
#include "config.h"
#include "Init.h"
#include "bindings/core/v8/ScriptStreamerThread.h"
#include "core/EventNames.h"
#include "core/EventTargetNames.h"
#include "core/EventTypeNames.h"
#include "core/FetchInitiatorTypeNames.h"
#include "core/HTMLNames.h"
#include "core/HTMLTokenizerNames.h"
#include "core/InputTypeNames.h"
#include "core/MathMLNames.h"
#include "core/MediaFeatureNames.h"
#include "core/MediaTypeNames.h"
#include "core/SVGNames.h"
#include "core/XLinkNames.h"
#include "core/XMLNSNames.h"
#include "core/XMLNames.h"
#include "core/css/parser/CSSParserTokenRange.h"
#include "core/dom/Document.h"
#include "core/dom/StyleChangeReason.h"
#include "core/events/EventFactory.h"
#include "core/html/parser/HTMLParserThread.h"
#include "core/workers/WorkerThread.h"
#include "platform/EventTracer.h"
#include "platform/FontFamilyNames.h"
#include "platform/Partitions.h"
#include "platform/PlatformThreadData.h"
#include "platform/heap/Heap.h"
#include "wtf/text/StringStatics.h"
namespace blink {
void CoreInitializer::registerEventFactory()
{
static bool isRegistered = false;
if (isRegistered)
return;
isRegistered = true;
Document::registerEventFactory(EventFactory::create());
}
void CoreInitializer::init()
{
ASSERT(!m_isInited);
m_isInited = true;
HTMLNames::init();
SVGNames::init();
XLinkNames::init();
MathMLNames::init();
XMLNSNames::init();
XMLNames::init();
EventNames::init();
EventTargetNames::init();
EventTypeNames::init();
FetchInitiatorTypeNames::init();
FontFamilyNames::init();
HTMLTokenizerNames::init();
InputTypeNames::init();
MediaFeatureNames::init();
MediaTypeNames::init();
CSSParserTokenRange::initStaticEOFToken();
// It would make logical sense to do this in WTF::initialize() but there are
// ordering dependencies, e.g. about "xmlns".
WTF::StringStatics::init();
StyleChangeExtraData::init();
QualifiedName::init();
Partitions::init();
EventTracer::initialize();
registerEventFactory();
// Ensure that the main thread's thread-local data is initialized before
// starting any worker threads.
PlatformThreadData::current();
StringImpl::freezeStaticStrings();
// Creates HTMLParserThread::shared and ScriptStreamerThread::shared, but
// does not start the threads.
HTMLParserThread::init();
ScriptStreamerThread::init();
}
void CoreInitializer::shutdown()
{
// Make sure we stop the HTMLParserThread before Platform::current() is
// cleared.
HTMLParserThread::shutdown();
Partitions::shutdown();
}
} // namespace blink
<commit_msg>Remove unnecessary include from Heap.cpp<commit_after>/*
* Copyright (C) 2013 Google Inc. 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 Google Inc. 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.
*/
#include "config.h"
#include "Init.h"
#include "bindings/core/v8/ScriptStreamerThread.h"
#include "core/EventNames.h"
#include "core/EventTargetNames.h"
#include "core/EventTypeNames.h"
#include "core/FetchInitiatorTypeNames.h"
#include "core/HTMLNames.h"
#include "core/HTMLTokenizerNames.h"
#include "core/InputTypeNames.h"
#include "core/MathMLNames.h"
#include "core/MediaFeatureNames.h"
#include "core/MediaTypeNames.h"
#include "core/SVGNames.h"
#include "core/XLinkNames.h"
#include "core/XMLNSNames.h"
#include "core/XMLNames.h"
#include "core/css/parser/CSSParserTokenRange.h"
#include "core/dom/Document.h"
#include "core/dom/StyleChangeReason.h"
#include "core/events/EventFactory.h"
#include "core/html/parser/HTMLParserThread.h"
#include "core/workers/WorkerThread.h"
#include "platform/EventTracer.h"
#include "platform/FontFamilyNames.h"
#include "platform/Partitions.h"
#include "platform/PlatformThreadData.h"
#include "wtf/text/StringStatics.h"
namespace blink {
void CoreInitializer::registerEventFactory()
{
static bool isRegistered = false;
if (isRegistered)
return;
isRegistered = true;
Document::registerEventFactory(EventFactory::create());
}
void CoreInitializer::init()
{
ASSERT(!m_isInited);
m_isInited = true;
HTMLNames::init();
SVGNames::init();
XLinkNames::init();
MathMLNames::init();
XMLNSNames::init();
XMLNames::init();
EventNames::init();
EventTargetNames::init();
EventTypeNames::init();
FetchInitiatorTypeNames::init();
FontFamilyNames::init();
HTMLTokenizerNames::init();
InputTypeNames::init();
MediaFeatureNames::init();
MediaTypeNames::init();
CSSParserTokenRange::initStaticEOFToken();
// It would make logical sense to do this in WTF::initialize() but there are
// ordering dependencies, e.g. about "xmlns".
WTF::StringStatics::init();
StyleChangeExtraData::init();
QualifiedName::init();
Partitions::init();
EventTracer::initialize();
registerEventFactory();
// Ensure that the main thread's thread-local data is initialized before
// starting any worker threads.
PlatformThreadData::current();
StringImpl::freezeStaticStrings();
// Creates HTMLParserThread::shared and ScriptStreamerThread::shared, but
// does not start the threads.
HTMLParserThread::init();
ScriptStreamerThread::init();
}
void CoreInitializer::shutdown()
{
// Make sure we stop the HTMLParserThread before Platform::current() is
// cleared.
HTMLParserThread::shutdown();
Partitions::shutdown();
}
} // namespace blink
<|endoftext|>
|
<commit_before>#include <iostream>
#include <unordered_map>
#include <tuple>
#include <exception>
#include <vector>
namespace TM
{
enum SHIFT {
LEFT = -1,
RIGHT = 1,
HOLD = 0
};
bool operator==(const std::tuple<int, char> &a,
const std::tuple<int, char> &b)
{
return std::get<0>(a) == std::get<0>(b) &&
std::get<1>(a) == std::get<1>(b);
}
struct tuple_hash : public std::unary_function<std::tuple<int, char>,
std::size_t>
{
const int MOD = 666013;
std::size_t operator()(const std::tuple<int, char> &k) const
{
return (std::get<0>(k) + std::get<1>(k)) % MOD;
}
};
class MultipleValuesMappedToKey : public std::exception
{
private:
virtual const char *what() const throw()
{
return "Cannot map multiple values to a key in an unordered_map";
}
};
class KeyNotFound: public std::exception
{
private:
virtual const char *what() const throw()
{
return "Key not found. Maybe first test using contains?";
}
};
class TMTransition
{
public:
typedef std::tuple<int, char> key_type;
typedef std::tuple<int, char, SHIFT> value_type;
void emplace(const key_type &k, const value_type &v) throw()
{
if (gamma_.count(k))
throw new MultipleValuesMappedToKey();
gamma_.emplace(k, v);
}
value_type get(const key_type &k) const
{
if (!gamma_.count(k))
throw new KeyNotFound();
return gamma_.find(k)->second;
}
bool contains(const key_type &k) const
{
return gamma_.count(k);
}
private:
std::unordered_map<key_type, value_type, tuple_hash> gamma_;
};
class TMConfiguration
{
public:
TMConfiguration()
: statesNr_(0)
{
}
void addTransition(int state_in, char sym_in, int state_af,
char sym_af, SHIFT shift ) throw()
{
addTransition(std::make_tuple(state_in, sym_in),
std::make_tuple(state_af, sym_af, shift));
// Educated guess. May change in the future - machines with multiple
// final states.
if (statesNr_ < state_in || statesNr_ < state_af)
statesNr_ = std::max(state_af, state_in);
}
bool is_final(int state) const
{
return state >= statesNr_;
}
bool is_undefined(int state, char sym) const
{
return !gamma_.contains(std::make_tuple(state, sym));
}
TMTransition::value_type getValue(int state, char sym) const
{
return gamma_.get(std::make_tuple(state, sym));
}
private:
void addTransition(const TMTransition::key_type &k,
const TMTransition::value_type &v)
{
gamma_.emplace(k, v);
}
TMTransition gamma_;
int statesNr_;
};
class TMRuntime
{
public:
TMRuntime(const TMConfiguration &conf)
: conf_(conf)
{
}
std::string run(std::string tape) throw()
{
int tape_head = 1;
int current_state = 0;
while (!conf_.is_final(current_state)) {
#ifdef VERBOSE
print(current_state, tape_head, tape);
#endif
int curr_sym = static_cast<int>(tape[tape_head]);
TMTransition::value_type val = conf_.getValue(current_state, curr_sym);
tape[tape_head] = std::get<1>(val);
tape_head += std::get<2>(val);
current_state = std::get<0>(val);
}
#ifdef VERBOSE
print(current_state, tape_head, tape);
#endif
return tape;
}
private:
void print(int current_state, int tape_head, const std::string ¤t_tape)
{
std::string head_str(current_tape.size(), ' ');
head_str[tape_head] = '^';
if (conf_.is_final(current_state))
std::cout << "Final state: ";
else
std::cout << "Current State: ";
std::cout << current_state << std::endl;
std::cout << current_tape << std::endl;
std::cout << head_str;
std::cout << std::endl;
}
TMConfiguration conf_;
};
#define TEST_SUCCEDED(testNr)\
std::cout << "Test " << testNr << " succeded" << std::endl
#define TEST_FAILED(testNr, expected, actual)\
std::cout << "Test " << testNr << " failed:" << std::endl\
<< "Expected: " << expected << std::endl\
<< "Actual: " << actual << std::endl;
namespace unittest
{
class UnitTest
{
public:
virtual void init() = 0;
void runTest()
{
init();
TMRuntime *tm_runtime = new TMRuntime(tm_conf);
auto inouts = getInOuts();
for (auto it = inouts.cbegin(); it != inouts.cend(); ++it) {
std::string actual_out = tm_runtime->run(it->first);
if (actual_out != it->second) {
TEST_FAILED(it - inouts.cbegin() + 1, it->second, actual_out);
} else {
TEST_SUCCEDED(it - inouts.cbegin() + 1);
}
std::cout << std::endl;
}
}
protected:
TMConfiguration tm_conf;
private:
virtual std::vector<std::pair<std::string, std::string>> getInOuts() = 0;
};
}
}
using namespace TM;
class PalindromeTest : public ::unittest::UnitTest
{
public:
void init()
{
tm_conf.addTransition(0, '0', 0, '0', TM::RIGHT);
tm_conf.addTransition(0, '1', 0, '1', RIGHT);
tm_conf.addTransition(0, '#', 1, '#', LEFT);
tm_conf.addTransition(1, '0', 2, '1', LEFT);
tm_conf.addTransition(1, '1', 1, '0', LEFT);
tm_conf.addTransition(2, '0', 2, '0', LEFT);
tm_conf.addTransition(2, '1', 2, '1', LEFT);
tm_conf.addTransition(2, '>', 3, '>', HOLD);
}
private:
std::vector<std::pair<std::string, std::string>> getInOuts()
{
std::vector<std::pair<std::string, std::string>> ret;
ret.emplace_back(">0001#", ">0010#");
ret.emplace_back(">00010#", ">00011#");
return ret;
}
};
int main()
{
::unittest::UnitTest *test = new PalindromeTest();
test->runTest();
return 0;
}
<commit_msg>Minor changes<commit_after>#include <iostream>
#include <unordered_map>
#include <tuple>
#include <exception>
#include <vector>
namespace TM
{
enum SHIFT {
LEFT = -1,
RIGHT = 1,
HOLD = 0
};
bool operator==(const std::tuple<int, char> &a,
const std::tuple<int, char> &b)
{
return std::get<0>(a) == std::get<0>(b) &&
std::get<1>(a) == std::get<1>(b);
}
struct tuple_hash : public std::unary_function<std::tuple<int, char>,
std::size_t>
{
const int MOD = 666013;
std::size_t operator()(const std::tuple<int, char> &k) const
{
return (std::get<0>(k) + std::get<1>(k)) % MOD;
}
};
class MultipleValuesMappedToKey : public std::exception
{
private:
virtual const char *what() const throw()
{
return "Cannot map multiple values to a key in an unordered_map";
}
};
class KeyNotFound: public std::exception
{
private:
virtual const char *what() const throw()
{
return "Key not found. Maybe first test using contains?";
}
};
class TMTransition
{
public:
typedef std::tuple<int, char> key_type;
typedef std::tuple<int, char, SHIFT> value_type;
void emplace(const key_type &k, const value_type &v) throw()
{
if (gamma_.count(k))
throw new MultipleValuesMappedToKey();
gamma_.emplace(k, v);
}
value_type get(const key_type &k) const
{
if (!gamma_.count(k))
throw new KeyNotFound();
return gamma_.find(k)->second;
}
bool contains(const key_type &k) const
{
return gamma_.count(k);
}
private:
std::unordered_map<key_type, value_type, tuple_hash> gamma_;
};
class TMConfiguration
{
public:
TMConfiguration()
: statesNr_(0)
{
}
void addTransition(int state_in, char sym_in, int state_af,
char sym_af, SHIFT shift ) throw()
{
addTransition(std::make_tuple(state_in, sym_in),
std::make_tuple(state_af, sym_af, shift));
// Educated guess. May change in the future - machines with multiple
// final states.
if (statesNr_ < state_in || statesNr_ < state_af)
statesNr_ = std::max(state_af, state_in);
}
bool is_final(int state) const
{
return state >= statesNr_;
}
bool is_undefined(int state, char sym) const
{
return !gamma_.contains(std::make_tuple(state, sym));
}
TMTransition::value_type getValue(int state, char sym) const
{
return gamma_.get(std::make_tuple(state, sym));
}
private:
void addTransition(const TMTransition::key_type &k,
const TMTransition::value_type &v)
{
gamma_.emplace(k, v);
}
TMTransition gamma_;
int statesNr_;
};
class TMRuntime
{
public:
TMRuntime(const TMConfiguration &conf)
: conf_(conf)
{
}
std::string run(std::string tape) throw()
{
int tape_head = 1;
int current_state = 0;
while (!conf_.is_final(current_state)) {
#ifdef VERBOSE
print(current_state, tape_head, tape);
#endif
int curr_sym = static_cast<int>(tape[tape_head]);
TMTransition::value_type val = conf_.getValue(current_state, curr_sym);
tape[tape_head] = std::get<1>(val);
tape_head += std::get<2>(val);
current_state = std::get<0>(val);
}
#ifdef VERBOSE
print(current_state, tape_head, tape);
#endif
return tape;
}
private:
void print(int current_state, int tape_head, const std::string ¤t_tape)
{
std::string head_str(current_tape.size(), ' ');
head_str[tape_head] = '^';
if (conf_.is_final(current_state))
std::cout << "Final state: ";
else
std::cout << "Current State: ";
std::cout << current_state << std::endl;
std::cout << current_tape << std::endl;
std::cout << head_str;
std::cout << std::endl;
}
TMConfiguration conf_;
};
#define TEST_SUCCEDED(testNr)\
std::cout << "Test " << testNr << " succeded" << std::endl
#define TEST_FAILED(testNr, expected, actual)\
std::cout << "Test " << testNr << " failed:" << std::endl\
<< "Expected: " << expected << std::endl\
<< "Actual: " << actual << std::endl;
namespace unittest
{
class UnitTest
{
public:
virtual void init() = 0;
void runTest()
{
init();
TMRuntime *tm_runtime = new TMRuntime(tmConf_);
auto inouts = getInOuts();
for (auto it = inouts.cbegin(); it != inouts.cend(); ++it) {
std::string actual_out = tm_runtime->run(it->first);
if (actual_out != it->second) {
TEST_FAILED(it - inouts.cbegin() + 1, it->second, actual_out);
} else {
TEST_SUCCEDED(it - inouts.cbegin() + 1);
}
std::cout << std::endl;
}
}
protected:
TMConfiguration tmConf_;
private:
virtual std::vector<std::pair<std::string, std::string>> getInOuts() = 0;
};
}
}
using namespace TM;
class IncrementTest : public ::unittest::UnitTest
{
public:
void init()
{
tmConf_.addTransition(0, '0', 0, '0', RIGHT);
tmConf_.addTransition(0, '1', 0, '1', RIGHT);
tmConf_.addTransition(0, '#', 1, '#', LEFT);
tmConf_.addTransition(1, '0', 2, '1', LEFT);
tmConf_.addTransition(1, '1', 1, '0', LEFT);
tmConf_.addTransition(2, '0', 2, '0', LEFT);
tmConf_.addTransition(2, '1', 2, '1', LEFT);
tmConf_.addTransition(2, '>', 3, '>', HOLD);
}
private:
std::vector<std::pair<std::string, std::string>> getInOuts()
{
std::vector<std::pair<std::string, std::string>> ret;
ret.emplace_back(">0001#", ">0010#");
ret.emplace_back(">00010#", ">00011#");
return ret;
}
};
int main()
{
unittest::UnitTest *test = new IncrementTest();
test->runTest();
return 0;
}
<|endoftext|>
|
<commit_before>/***********************************************************************************
** MIT License **
** **
** Copyright (c) 2018 Victor DENIS ([email protected]) **
** **
** 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 "AddressBarCompleterDelegate.hpp"
#include <QPainter>
#include <QTextLayout>
#include "Widgets/AddressBar/AddressBarCompleterModel.hpp"
#include "Application.hpp"
namespace Sn
{
AddressBarCompleterDelegate::AddressBarCompleterDelegate(QObject* parent) :
QStyledItemDelegate(parent)
{
// Empty
}
void AddressBarCompleterDelegate::paint(QPainter* painter, const QStyleOptionViewItem& option,
const QModelIndex& index) const
{
QStyleOptionViewItem opt{option};
initStyleOption(&opt, index);
const QWidget* w{opt.widget};
const QStyle* style{w ? w->style() : QApplication::style()};
const int height{opt.rect.height()};
const int center{height / 2 + opt.rect.top()};
// Prepare title font
QFont titleFont = opt.font;
titleFont.setPointSize(titleFont.pointSize() + 1);
const QFontMetrics titleMetrics{titleFont};
int leftPosition{m_padding * 2};
int rightPosition{opt.rect.right() - m_padding};
opt.state |= QStyle::State_Active;
const QIcon::Mode iconMode{opt.state & QStyle::State_Selected ? QIcon::Selected : QIcon::Normal};
const QPalette::ColorRole colorRole{opt.state & QStyle::State_Selected ? QPalette::HighlightedText : QPalette::Text};
const QPalette::ColorRole colorLinkRole{
opt.state & QStyle::State_Selected
? QPalette::HighlightedText
: QPalette::Link
};
#ifdef Q_OS_WIN
opt.palette.setColor(QPalette::All, QPalette::HighlightedText, opt.palette.color(QPalette::Active, QPalette::Text));
opt.palette.setColor(QPalette::All, QPalette::Highlight, opt.palette.base().color().darker(108));
#endif
QPalette textPalette{opt.palette};
textPalette.setCurrentColorGroup(opt.state & QStyle::State_Enabled ? QPalette::Normal : QPalette::Disabled);
// Draw background
style->drawPrimitive(QStyle::PE_PanelItemViewItem, &opt, painter, w);
const bool isVisitSearchItem{index.data(AddressBarCompleterModel::VisitSearchItemRole).toBool()};
const bool isSearchSuggestion{index.data(AddressBarCompleterModel::SearchSuggestionRole).toBool()};
const bool isWebSearch{!isUrlOrDomain(m_originalText.trimmed())};
// Draw icon
const int iconSize{16};
const int iconYPos{center - (iconSize / 2)};
QRect iconRect{leftPosition, iconYPos, iconSize, iconSize};
QPixmap pixmap{index.data(Qt::DecorationRole).value<QIcon>().pixmap(iconSize, iconMode)};
if (isSearchSuggestion || (isVisitSearchItem && isWebSearch))
pixmap = Application::getAppIcon("search").pixmap(iconSize, iconMode);
painter->drawPixmap(iconRect, pixmap);
leftPosition = iconRect.right() + m_padding * 2;
// Draw star to bookmark items
int starPixmapWidth{0};
if (index.data(AddressBarCompleterModel::BookmarkRole).toBool()) {
const QIcon icon{Application::getAppIcon("bookmarks")};
const QSize starSize{16, 16};
starPixmapWidth = starSize.width();
QPoint pos{rightPosition - starPixmapWidth, center - starSize.height() / 2};
QRect starRect{pos, starSize};
painter->drawPixmap(starRect, icon.pixmap(starSize, iconMode));
}
QString searchText{index.data(AddressBarCompleterModel::SearchStringRole).toString()};
// Draw title
leftPosition += 2;
QRect titleRect{
leftPosition, center - titleMetrics.height() / 2, static_cast<int>(opt.rect.width() * 0.6), titleMetrics.height()
};
QString title{index.data(AddressBarCompleterModel::TitleRole).toString()};
painter->setFont(titleFont);
if (isVisitSearchItem) {
title = m_originalText.trimmed();
if (searchText == title)
searchText.clear();
}
leftPosition += viewItemDrawText(painter, &opt, titleRect, title, textPalette.color(colorRole), searchText);
leftPosition += m_padding * 2;
const int maxChars{(opt.rect.width() - leftPosition) / opt.fontMetrics.width(QLatin1Char('i'))};
QString link{};
const QByteArray linkArray{index.data(Qt::DisplayRole).toByteArray()};
if (!linkArray.startsWith("data") && !linkArray.startsWith("javascript"))
link = QString::fromUtf8(QByteArray::fromPercentEncoding(linkArray)).left(maxChars);
else
link = QString::fromLatin1(linkArray.left(maxChars));
if (isVisitSearchItem || isSearchSuggestion) {
if (!isSearchSuggestion && !isWebSearch)
link = tr("Visit");
else if (opt.state.testFlag(QStyle::State_Selected) || opt.state.testFlag(QStyle::State_MouseOver))
link = tr("Search with your search engine");
else
link.clear();
}
// Draw separator
if (!link.isEmpty()) {
QChar separator{QLatin1Char('-')};
QRect separatorRect{
leftPosition, center - titleMetrics.height() / 2, titleMetrics.width(separator),
titleMetrics.height()
};
style->drawItemText(painter, separatorRect, Qt::AlignCenter, textPalette, true, separator, colorRole);
leftPosition += separatorRect.width() + m_padding * 2;
}
// Draw link
const int leftLinkEdge{leftPosition};
const int rightLinkEdge{rightPosition - m_padding - starPixmapWidth};
QRect linkRect{
leftLinkEdge, center - opt.fontMetrics.height() / 2, rightLinkEdge - leftLinkEdge,
opt.fontMetrics.height()
};
painter->setFont(opt.font);
// Draw url (or switch to tab)
int tabPos{index.data(AddressBarCompleterModel::TabPositionTabRole).toInt()};
if (drawSwitchToTab() && tabPos != -1) {
// TODO: have an icon for real tab
const QIcon tabIcon = Application::getAppIcon("new-tab");
QRect iconRect{linkRect};
iconRect.setX(iconRect.x());
iconRect.setWidth(16);
painter->drawPixmap(iconRect, tabIcon.pixmap(iconRect.size(), iconMode));
QRect textRect{linkRect};
textRect.setX(textRect.x() + m_padding + 16 + m_padding);
viewItemDrawText(painter, &opt, textRect, tr("Switch to tab"), textPalette.color(colorLinkRole));
}
else if (isVisitSearchItem || isSearchSuggestion)
viewItemDrawText(painter, &opt, linkRect, link, textPalette.color(colorLinkRole));
else
viewItemDrawText(painter, &opt, linkRect, link, textPalette.color(colorLinkRole), searchText);
// Draw line at the very bottom of item if the item is not highlighted
if (!(opt.state & QStyle::State_Selected)) {
QRect lineRect{opt.rect.left(), opt.rect.bottom(), opt.rect.width(), 1};
painter->fillRect(lineRect, opt.palette.color(QPalette::AlternateBase));
}
}
QSize AddressBarCompleterDelegate::sizeHint(const QStyleOptionViewItem& option, const QModelIndex& index)
{
Q_UNUSED(index)
if (!m_rowHeight) {
QStyleOptionViewItem opt{option};
initStyleOption(&opt, index);
const QWidget* widget{opt.widget};
const QStyle* style{widget ? widget->style() : Application::style()};
const int padding{style->pixelMetric(QStyle::PM_FocusFrameHMargin, 0) + 1};
QFont titleFont{opt.font};
titleFont.setPointSize(titleFont.pointSize() + 1);
m_padding = padding > 3 ? padding : 3;
const QFontMetrics titleMetrics{titleFont};
m_rowHeight = 4 * m_padding + qMax(16, titleMetrics.height());
}
return QSize(200, m_rowHeight);
}
void AddressBarCompleterDelegate::setShowSwitchToTab(bool enable)
{
m_drawSwitchToTab = enable;
}
void AddressBarCompleterDelegate::setOriginalText(const QString& originalText)
{
m_originalText = originalText;
}
bool AddressBarCompleterDelegate::isUrlOrDomain(const QString& text) const
{
QUrl url{text};
if (!url.scheme().isEmpty() && (!url.host().isEmpty() || !url.path().isEmpty()))
return true;
if (text.contains(QLatin1Char('.')) && !text.contains(QLatin1Char(' ')))
return true;
if (text == QLatin1String("localhost"))
return true;
return false;
}
QSizeF AddressBarCompleterDelegate::viewItemTextLayout(QTextLayout& textLayout, int lineWidth) const
{
qreal height{0};
qreal widthUsed{0};
textLayout.beginLayout();
QTextLine line{textLayout.createLine()};
if (line.isValid()) {
line.setLineWidth(lineWidth);
line.setPosition(QPointF(0, height));
height += line.height();
widthUsed = qMax(widthUsed, line.naturalTextWidth());
textLayout.endLayout();
}
return QSizeF(widthUsed, height);
}
int AddressBarCompleterDelegate::viewItemDrawText(QPainter* painter, const QStyleOptionViewItem* option,
const QRect& rect,
const QString& text, const QColor& color,
const QString& searchText) const
{
if (text.isEmpty())
return 0;
const QFontMetrics fontMetrics{painter->font()};
QString elidedText{fontMetrics.elidedText(text, option->textElideMode, rect.width())};
QTextOption textOption{};
textOption.setWrapMode(QTextOption::NoWrap);
textOption.setAlignment(QStyle::visualAlignment(textOption.textDirection(), option->displayAlignment));
QTextLayout textLayout{};
textLayout.setFont(painter->font());
textLayout.setText(elidedText);
textLayout.setTextOption(textOption);
if (!searchText.isEmpty()) {
QList<int> delimiters{};
QStringList searchStrings{searchText.split(QLatin1Char(' '), QString::SkipEmptyParts)};
std::sort(searchStrings.begin(), searchStrings.end(), [](const QString& size1, const QString& size2) {
return size1.size() > size2.size();
});
foreach(const QString &string, searchStrings) {
int delimiter{text.indexOf(string, 0, Qt::CaseInsensitive)};
while (delimiter != -1) {
int start{delimiter};
int end{delimiter + string.length()};
bool alreadyContains{false};
for (int i{0}; i < delimiters.count(); ++i) {
int dStart{delimiters[i]};
int dEnd{delimiters[++i]};
if (dStart <= start && dEnd >= end) {
alreadyContains = true;
break;
}
}
if (!alreadyContains) {
delimiters.append(start);
delimiters.append(end);
}
delimiter = text.indexOf(string, end, Qt::CaseInsensitive);
}
}
std::sort(delimiters.begin(), delimiters.end());
if (!delimiters.isEmpty() && !(delimiters.count() % 2)) {
QList<QTextLayout::FormatRange> highlightParts{};
QTextLayout::FormatRange lighterWholeLine{};
lighterWholeLine.start = 0;
lighterWholeLine.length = elidedText.size();
QColor lighterColor{color.lighter(130)};
if (lighterColor == color)
lighterColor = QColor(Qt::gray).darker(180);
lighterWholeLine.format.setForeground(lighterColor);
highlightParts << lighterWholeLine;
while (!delimiters.isEmpty()) {
QTextLayout::FormatRange highlightedPart{};
int start{delimiters.takeFirst()};
int end{delimiters.takeFirst()};
highlightedPart.start = start;
highlightedPart.length = end - start;
highlightedPart.format.setFontWeight(QFont::Bold);
highlightedPart.format.setUnderlineStyle(QTextCharFormat::SingleUnderline);
highlightedPart.format.setForeground(color);
highlightParts << highlightedPart;
}
textLayout.setAdditionalFormats(highlightParts);
}
}
viewItemTextLayout(textLayout, rect.width());
if (textLayout.lineCount() <= 0)
return 0;
QTextLine textLine{textLayout.lineAt(0)};
int diff = textLine.naturalTextWidth() - rect.width();
if (diff > 0) {
elidedText = fontMetrics.elidedText(elidedText, option->textElideMode, rect.width() - diff);
textLayout.setText(elidedText);
viewItemTextLayout(textLayout, rect.width());
if (textLayout.lineCount() <= 0)
return 0;
textLine = textLayout.lineAt(0);
}
painter->setPen(color);
qreal width{qMax<qreal>(rect.width(), textLayout.lineAt(0).width())};
const QRect& layoutRect{
QStyle::alignedRect(option->direction, option->displayAlignment,
QSize(int(width), int(textLine.height())), rect)
};
const QPointF& position{layoutRect.topLeft()};
textLine.draw(painter, position);
return qMin<int>(rect.width(), textLayout.lineAt(0).naturalTextWidth());
}
}
<commit_msg>[Fix] Design of auto completion with themes<commit_after>/***********************************************************************************
** MIT License **
** **
** Copyright (c) 2018 Victor DENIS ([email protected]) **
** **
** 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 "AddressBarCompleterDelegate.hpp"
#include <QPainter>
#include <QTextLayout>
#include "Widgets/AddressBar/AddressBarCompleterModel.hpp"
#include "Application.hpp"
namespace Sn
{
AddressBarCompleterDelegate::AddressBarCompleterDelegate(QObject* parent) :
QStyledItemDelegate(parent)
{
// Empty
}
void AddressBarCompleterDelegate::paint(QPainter* painter, const QStyleOptionViewItem& option,
const QModelIndex& index) const
{
QStyleOptionViewItem opt{option};
initStyleOption(&opt, index);
QColor backgroundColor{ option.palette.window().color() };
const double darkness{ 1 - (0.299 * backgroundColor.red() + 0.587 * backgroundColor.green() +
0.115 * backgroundColor.blue()) / 255 };
bool isDark{ darkness >= 0.5 };
const QWidget* w{opt.widget};
const QStyle* style{w ? w->style() : QApplication::style()};
const int height{opt.rect.height()};
const int center{height / 2 + opt.rect.top()};
// Prepare title font
QFont titleFont = opt.font;
titleFont.setPointSize(titleFont.pointSize() + 1);
const QFontMetrics titleMetrics{titleFont};
int leftPosition{m_padding * 2};
int rightPosition{opt.rect.right() - m_padding};
opt.state |= QStyle::State_Active;
const QIcon::Mode iconMode{opt.state & QStyle::State_Selected ? QIcon::Selected : QIcon::Normal};
QColor textColor{};
QColor highlightedTextColor{};
QColor linkColor{};
if (isDark) {
textColor = QColor(250, 250, 250);
highlightedTextColor = QColor(200, 200, 200);
linkColor = QColor(0, 157, 255);
}
else {
textColor = QColor(10, 10, 10);
highlightedTextColor = QColor(55, 55, 55);
linkColor = QColor(0, 57, 255);
}
/*
const QPalette::ColorRole colorRole{opt.state & QStyle::State_Selected ? QPalette::HighlightedText : QPalette::Text};
const QPalette::ColorRole colorLinkRole{
opt.state & QStyle::State_Selected
? QPalette::HighlightedText
: QPalette::Link
};
*/
QPalette textPalette{opt.palette};
//textPalette.setCurrentColorGroup(opt.state & QStyle::State_Enabled ? QPalette::Normal : QPalette::Disabled);
/*
textPalette.setColor(QPalette::All, QPalette::HighlightedText, QColor(255, 255, 255));
textPalette.setColor(QPalette::All, QPalette::Text, QColor(255, 255, 255));
textPalette.setColor(QPalette::All, QPalette::Link, QColor(255, 255, 255));
*/
// Draw background
style->drawPrimitive(QStyle::PE_PanelItemViewItem, &opt, painter, w);
const bool isVisitSearchItem{index.data(AddressBarCompleterModel::VisitSearchItemRole).toBool()};
const bool isSearchSuggestion{index.data(AddressBarCompleterModel::SearchSuggestionRole).toBool()};
const bool isWebSearch{!isUrlOrDomain(m_originalText.trimmed())};
// Draw icon
const int iconSize{16};
const int iconYPos{center - (iconSize / 2)};
QRect iconRect{leftPosition, iconYPos, iconSize, iconSize};
QPixmap pixmap{index.data(Qt::DecorationRole).value<QIcon>().pixmap(iconSize, iconMode)};
if (isSearchSuggestion || (isVisitSearchItem && isWebSearch))
pixmap = Application::getAppIcon("search").pixmap(iconSize, iconMode);
painter->drawPixmap(iconRect, pixmap);
leftPosition = iconRect.right() + m_padding * 2;
// Draw star to bookmark items
int starPixmapWidth{0};
if (index.data(AddressBarCompleterModel::BookmarkRole).toBool()) {
const QIcon icon{Application::getAppIcon("bookmarks")};
const QSize starSize{16, 16};
starPixmapWidth = starSize.width();
QPoint pos{rightPosition - starPixmapWidth, center - starSize.height() / 2};
QRect starRect{pos, starSize};
painter->drawPixmap(starRect, icon.pixmap(starSize, iconMode));
}
QString searchText{index.data(AddressBarCompleterModel::SearchStringRole).toString()};
// Draw title
leftPosition += 2;
QRect titleRect{
leftPosition, center - titleMetrics.height() / 2, static_cast<int>(opt.rect.width() * 0.6), titleMetrics.height()
};
QString title{index.data(AddressBarCompleterModel::TitleRole).toString()};
painter->setFont(titleFont);
if (isVisitSearchItem) {
title = m_originalText.trimmed();
if (searchText == title)
searchText.clear();
}
leftPosition += viewItemDrawText(painter, &opt, titleRect, title, opt.state & QStyle::State_Selected ? highlightedTextColor : textColor, searchText);
leftPosition += m_padding * 2;
const int maxChars{(opt.rect.width() - leftPosition) / opt.fontMetrics.width(QLatin1Char('i'))};
QString link{};
const QByteArray linkArray{index.data(Qt::DisplayRole).toByteArray()};
if (!linkArray.startsWith("data") && !linkArray.startsWith("javascript"))
link = QString::fromUtf8(QByteArray::fromPercentEncoding(linkArray)).left(maxChars);
else
link = QString::fromLatin1(linkArray.left(maxChars));
if (isVisitSearchItem || isSearchSuggestion) {
if (!isSearchSuggestion && !isWebSearch)
link = tr("Visit");
else if (opt.state.testFlag(QStyle::State_Selected) || opt.state.testFlag(QStyle::State_MouseOver))
link = tr("Search with your search engine");
else
link.clear();
}
// Draw separator
if (!link.isEmpty()) {
QChar separator{QLatin1Char('-')};
QRect separatorRect{
leftPosition, center - titleMetrics.height() / 2, titleMetrics.width(separator),
titleMetrics.height()
};
style->drawItemText(painter, separatorRect, Qt::AlignCenter, textPalette, true, separator, opt.state & QStyle::State_Selected ? QPalette::HighlightedText : QPalette::Text);
leftPosition += separatorRect.width() + m_padding * 2;
}
// Draw link
const int leftLinkEdge{leftPosition};
const int rightLinkEdge{rightPosition - m_padding - starPixmapWidth};
QRect linkRect{
leftLinkEdge, center - opt.fontMetrics.height() / 2, rightLinkEdge - leftLinkEdge,
opt.fontMetrics.height()
};
painter->setFont(opt.font);
// Draw url (or switch to tab)
int tabPos{index.data(AddressBarCompleterModel::TabPositionTabRole).toInt()};
if (drawSwitchToTab() && tabPos != -1) {
// TODO: have an icon for real tab
const QIcon tabIcon = Application::getAppIcon("new-tab");
QRect iconRect{linkRect};
iconRect.setX(iconRect.x());
iconRect.setWidth(16);
painter->drawPixmap(iconRect, tabIcon.pixmap(iconRect.size(), iconMode));
QRect textRect{linkRect};
textRect.setX(textRect.x() + m_padding + 16 + m_padding);
viewItemDrawText(painter, &opt, textRect, tr("Switch to tab"), opt.state & QStyle::State_Selected ? highlightedTextColor : linkColor);
}
else if (isVisitSearchItem || isSearchSuggestion)
viewItemDrawText(painter, &opt, linkRect, link, opt.state & QStyle::State_Selected ? highlightedTextColor : linkColor);
else
viewItemDrawText(painter, &opt, linkRect, link, opt.state & QStyle::State_Selected ? highlightedTextColor : linkColor, searchText);
// Draw line at the very bottom of item if the item is not highlighted
if (!(opt.state & QStyle::State_Selected)) {
QRect lineRect{opt.rect.left(), opt.rect.bottom(), opt.rect.width(), 1};
painter->fillRect(lineRect, opt.palette.color(QPalette::AlternateBase));
}
}
QSize AddressBarCompleterDelegate::sizeHint(const QStyleOptionViewItem& option, const QModelIndex& index)
{
Q_UNUSED(index)
if (!m_rowHeight) {
QStyleOptionViewItem opt{option};
initStyleOption(&opt, index);
const QWidget* widget{opt.widget};
const QStyle* style{widget ? widget->style() : Application::style()};
const int padding{style->pixelMetric(QStyle::PM_FocusFrameHMargin, 0) + 1};
QFont titleFont{opt.font};
titleFont.setPointSize(titleFont.pointSize() + 1);
m_padding = padding > 3 ? padding : 3;
const QFontMetrics titleMetrics{titleFont};
m_rowHeight = 4 * m_padding + qMax(16, titleMetrics.height());
}
return QSize(200, m_rowHeight);
}
void AddressBarCompleterDelegate::setShowSwitchToTab(bool enable)
{
m_drawSwitchToTab = enable;
}
void AddressBarCompleterDelegate::setOriginalText(const QString& originalText)
{
m_originalText = originalText;
}
bool AddressBarCompleterDelegate::isUrlOrDomain(const QString& text) const
{
QUrl url{text};
if (!url.scheme().isEmpty() && (!url.host().isEmpty() || !url.path().isEmpty()))
return true;
if (text.contains(QLatin1Char('.')) && !text.contains(QLatin1Char(' ')))
return true;
if (text == QLatin1String("localhost"))
return true;
return false;
}
QSizeF AddressBarCompleterDelegate::viewItemTextLayout(QTextLayout& textLayout, int lineWidth) const
{
qreal height{0};
qreal widthUsed{0};
textLayout.beginLayout();
QTextLine line{textLayout.createLine()};
if (line.isValid()) {
line.setLineWidth(lineWidth);
line.setPosition(QPointF(0, height));
height += line.height();
widthUsed = qMax(widthUsed, line.naturalTextWidth());
textLayout.endLayout();
}
return QSizeF(widthUsed, height);
}
int AddressBarCompleterDelegate::viewItemDrawText(QPainter* painter, const QStyleOptionViewItem* option,
const QRect& rect,
const QString& text, const QColor& color,
const QString& searchText) const
{
if (text.isEmpty())
return 0;
const QFontMetrics fontMetrics{painter->font()};
QString elidedText{fontMetrics.elidedText(text, option->textElideMode, rect.width())};
QTextOption textOption{};
textOption.setWrapMode(QTextOption::NoWrap);
textOption.setAlignment(QStyle::visualAlignment(textOption.textDirection(), option->displayAlignment));
QTextLayout textLayout{};
textLayout.setFont(painter->font());
textLayout.setText(elidedText);
textLayout.setTextOption(textOption);
if (!searchText.isEmpty()) {
QList<int> delimiters{};
QStringList searchStrings{searchText.split(QLatin1Char(' '), QString::SkipEmptyParts)};
std::sort(searchStrings.begin(), searchStrings.end(), [](const QString& size1, const QString& size2) {
return size1.size() > size2.size();
});
foreach(const QString &string, searchStrings) {
int delimiter{text.indexOf(string, 0, Qt::CaseInsensitive)};
while (delimiter != -1) {
int start{delimiter};
int end{delimiter + string.length()};
bool alreadyContains{false};
for (int i{0}; i < delimiters.count(); ++i) {
int dStart{delimiters[i]};
int dEnd{delimiters[++i]};
if (dStart <= start && dEnd >= end) {
alreadyContains = true;
break;
}
}
if (!alreadyContains) {
delimiters.append(start);
delimiters.append(end);
}
delimiter = text.indexOf(string, end, Qt::CaseInsensitive);
}
}
std::sort(delimiters.begin(), delimiters.end());
if (!delimiters.isEmpty() && !(delimiters.count() % 2)) {
QList<QTextLayout::FormatRange> highlightParts{};
QTextLayout::FormatRange lighterWholeLine{};
lighterWholeLine.start = 0;
lighterWholeLine.length = elidedText.size();
QColor lighterColor{color.lighter(130)};
if (lighterColor == color)
lighterColor = QColor(Qt::gray).darker(180);
lighterWholeLine.format.setForeground(lighterColor);
highlightParts << lighterWholeLine;
while (!delimiters.isEmpty()) {
QTextLayout::FormatRange highlightedPart{};
int start{delimiters.takeFirst()};
int end{delimiters.takeFirst()};
highlightedPart.start = start;
highlightedPart.length = end - start;
highlightedPart.format.setFontWeight(QFont::Bold);
highlightedPart.format.setUnderlineStyle(QTextCharFormat::SingleUnderline);
highlightedPart.format.setForeground(color);
highlightParts << highlightedPart;
}
textLayout.setAdditionalFormats(highlightParts);
}
}
viewItemTextLayout(textLayout, rect.width());
if (textLayout.lineCount() <= 0)
return 0;
QTextLine textLine{textLayout.lineAt(0)};
int diff = textLine.naturalTextWidth() - rect.width();
if (diff > 0) {
elidedText = fontMetrics.elidedText(elidedText, option->textElideMode, rect.width() - diff);
textLayout.setText(elidedText);
viewItemTextLayout(textLayout, rect.width());
if (textLayout.lineCount() <= 0)
return 0;
textLine = textLayout.lineAt(0);
}
painter->setPen(color);
qreal width{qMax<qreal>(rect.width(), textLayout.lineAt(0).width())};
const QRect& layoutRect{
QStyle::alignedRect(option->direction, option->displayAlignment,
QSize(int(width), int(textLine.height())), rect)
};
const QPointF& position{layoutRect.topLeft()};
textLine.draw(painter, position);
return qMin<int>(rect.width(), textLayout.lineAt(0).naturalTextWidth());
}
}
<|endoftext|>
|
<commit_before>//===-------- ExponentialGrowthAppendingBinaryByteStream.cpp --------------===//
//
// This source file is part of the Swift.org open source project
//
// Copyright (c) 2014 - 2018 Apple Inc. and the Swift project authors
// Licensed under Apache License v2.0 with Runtime Library Exception
//
// See https://swift.org/LICENSE.txt for license information
// See https://swift.org/CONTRIBUTORS.txt for the list of Swift project authors
//
//===----------------------------------------------------------------------===//
#include "swift/Basic/ExponentialGrowthAppendingBinaryByteStream.h"
using namespace llvm;
using namespace swift;
Error ExponentialGrowthAppendingBinaryByteStream::readBytes(
uint32_t Offset, uint32_t Size, ArrayRef<uint8_t> &Buffer) {
if (Offset > getLength())
return make_error<BinaryStreamError>(stream_error_code::invalid_offset);
if (Offset + Size > getLength())
return make_error<BinaryStreamError>(stream_error_code::stream_too_short);
Buffer = ArrayRef<uint8_t>(Data.data() + Offset, Size);
return Error::success();
}
Error ExponentialGrowthAppendingBinaryByteStream::readLongestContiguousChunk(
uint32_t Offset, ArrayRef<uint8_t> &Buffer) {
if (Offset > getLength())
return make_error<BinaryStreamError>(stream_error_code::invalid_offset);
Buffer = ArrayRef<uint8_t>(Data.data() + Offset, Data.size() - Offset);
return Error::success();
}
void ExponentialGrowthAppendingBinaryByteStream::reserve(size_t Size) {
Data.reserve(Size);
}
Error ExponentialGrowthAppendingBinaryByteStream::writeBytes(
uint32_t Offset, ArrayRef<uint8_t> Buffer) {
if (Buffer.empty())
return Error::success();
if (Offset > getLength())
return make_error<BinaryStreamError>(stream_error_code::invalid_offset);
// Resize the internal buffer if needed.
uint32_t RequiredSize = Offset + Buffer.size();
if (RequiredSize > Data.size()) {
Data.resize(RequiredSize);
}
::memcpy(Data.data() + Offset, Buffer.data(), Buffer.size());
return Error::success();
}
<commit_msg>[swiftBasic] Simplify bound checks for ExponentialGrowthAppendingBinaryByteStream<commit_after>//===-------- ExponentialGrowthAppendingBinaryByteStream.cpp --------------===//
//
// This source file is part of the Swift.org open source project
//
// Copyright (c) 2014 - 2018 Apple Inc. and the Swift project authors
// Licensed under Apache License v2.0 with Runtime Library Exception
//
// See https://swift.org/LICENSE.txt for license information
// See https://swift.org/CONTRIBUTORS.txt for the list of Swift project authors
//
//===----------------------------------------------------------------------===//
#include "swift/Basic/ExponentialGrowthAppendingBinaryByteStream.h"
using namespace llvm;
using namespace swift;
Error ExponentialGrowthAppendingBinaryByteStream::readBytes(
uint32_t Offset, uint32_t Size, ArrayRef<uint8_t> &Buffer) {
if (auto Error = checkOffsetForRead(Offset, Size)) {
return Error;
}
Buffer = ArrayRef<uint8_t>(Data.data() + Offset, Size);
return Error::success();
}
Error ExponentialGrowthAppendingBinaryByteStream::readLongestContiguousChunk(
uint32_t Offset, ArrayRef<uint8_t> &Buffer) {
if (auto Error = checkOffsetForRead(Offset, 0)) {
return Error;
}
Buffer = ArrayRef<uint8_t>(Data.data() + Offset, Data.size() - Offset);
return Error::success();
}
void ExponentialGrowthAppendingBinaryByteStream::reserve(size_t Size) {
Data.reserve(Size);
}
Error ExponentialGrowthAppendingBinaryByteStream::writeBytes(
uint32_t Offset, ArrayRef<uint8_t> Buffer) {
if (Buffer.empty())
return Error::success();
if (auto Error = checkOffsetForWrite(Offset, Buffer.size())) {
return Error;
}
// Resize the internal buffer if needed.
uint32_t RequiredSize = Offset + Buffer.size();
if (RequiredSize > Data.size()) {
Data.resize(RequiredSize);
}
::memcpy(Data.data() + Offset, Buffer.data(), Buffer.size());
return Error::success();
}
<|endoftext|>
|
<commit_before>/*
* Copyright 2010-2012 Esrille 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 "HTMLLinkElementImp.h"
#include <boost/bind.hpp>
#include <boost/version.hpp>
#include <boost/iostreams/stream.hpp>
#include <boost/iostreams/device/file_descriptor.hpp>
#include "DocumentImp.h"
#include "WindowImp.h"
#include "css/CSSInputStream.h"
#include "css/CSSParser.h"
#include "Test.util.h"
namespace org { namespace w3c { namespace dom { namespace bootstrap {
HTMLLinkElementImp::HTMLLinkElementImp(DocumentImp* ownerDocument) :
ObjectMixin(ownerDocument, u"link"),
request(0),
styleSheet(0)
{
}
HTMLLinkElementImp::HTMLLinkElementImp(HTMLLinkElementImp* org, bool deep) :
ObjectMixin(org, deep),
request(0), // TODO: XXX
styleSheet(org->styleSheet) // TODO: make a clone sheet, too?
{
}
HTMLLinkElementImp::~HTMLLinkElementImp()
{
delete request;
}
void HTMLLinkElementImp::eval()
{
std::u16string href = getHref();
if (href.empty())
return;
HTMLElementImp::eval();
if (compareIgnoreCase(getRel(), u"stylesheet") == 0) { // CI
// TODO: check type
if (!getAttribute(u"title").hasValue()) {
// non-alternate style sheet
DocumentImp* document = getOwnerDocumentImp();
request = new(std::nothrow) HttpRequest(document->getDocumentURI());
if (request) {
request->open(u"GET", href);
request->setHanndler(boost::bind(&HTMLLinkElementImp::notify, this));
document->incrementLoadEventDelayCount();
request->send();
}
}
}
}
void HTMLLinkElementImp::notify()
{
DocumentImp* document = getOwnerDocumentImp();
if (request->getStatus() == 200) {
#if 104400 <= BOOST_VERSION
boost::iostreams::stream<boost::iostreams::file_descriptor_source> stream(request->getContentDescriptor(), boost::iostreams::never_close_handle);
#else
boost::iostreams::stream<boost::iostreams::file_descriptor_source> stream(request->getContentDescriptor(), false);
#endif
CSSParser parser;
CSSInputStream cssStream(stream, request->getResponseMessage().getContentCharset(), utfconv(document->getCharset()));
styleSheet = parser.parse(document, cssStream);
if (3 <= getLogLevel())
dumpStyleSheet(std::cerr, styleSheet.self());
if (WindowImp* view = document->getDefaultWindow())
view->setFlagsToBoxTree(1);
}
document->decrementLoadEventDelayCount();
}
// Node
Node HTMLLinkElementImp::cloneNode(bool deep)
{
return new(std::nothrow) HTMLLinkElementImp(this, deep);
}
// HTMLLinkElement
bool HTMLLinkElementImp::getDisabled()
{
if (!styleSheet)
return false;
return styleSheet.getDisabled();
}
void HTMLLinkElementImp::setDisabled(bool disabled)
{
if (styleSheet)
styleSheet.setDisabled(disabled);
}
std::u16string HTMLLinkElementImp::getHref()
{
return getAttribute(u"href");
}
void HTMLLinkElementImp::setHref(std::u16string href)
{
// TODO: implement me!
}
std::u16string HTMLLinkElementImp::getRel()
{
return getAttribute(u"rel");
}
void HTMLLinkElementImp::setRel(std::u16string rel)
{
// TODO: implement me!
}
DOMTokenList HTMLLinkElementImp::getRelList()
{
// TODO: implement me!
return static_cast<Object*>(0);
}
std::u16string HTMLLinkElementImp::getMedia()
{
return getAttribute(u"media");
}
void HTMLLinkElementImp::setMedia(std::u16string media)
{
// TODO: implement me!
}
std::u16string HTMLLinkElementImp::getHreflang()
{
return getAttribute(u"hreflang");
}
void HTMLLinkElementImp::setHreflang(std::u16string hreflang)
{
// TODO: implement me!
}
std::u16string HTMLLinkElementImp::getType()
{
return getAttribute(u"type");
}
void HTMLLinkElementImp::setType(std::u16string type)
{
// TODO: implement me!
}
DOMSettableTokenList HTMLLinkElementImp::getSizes()
{
// TODO: implement me!
return static_cast<Object*>(0);
}
void HTMLLinkElementImp::setSizes(std::u16string sizes)
{
// TODO: implement me!
}
stylesheets::StyleSheet HTMLLinkElementImp::getSheet()
{
return styleSheet;
}
std::u16string HTMLLinkElementImp::getCharset()
{
// TODO: implement me!
return u"";
}
void HTMLLinkElementImp::setCharset(std::u16string charset)
{
// TODO: implement me!
}
std::u16string HTMLLinkElementImp::getRev()
{
// TODO: implement me!
return u"";
}
void HTMLLinkElementImp::setRev(std::u16string rev)
{
// TODO: implement me!
}
std::u16string HTMLLinkElementImp::getTarget()
{
// TODO: implement me!
return u"";
}
void HTMLLinkElementImp::setTarget(std::u16string target)
{
// TODO: implement me!
}
}}}} // org::w3c::dom::bootstrap
<commit_msg>(HTMLLinkElementImp::eval, HTMLLinkElementImp::getRel) : Support a set of space-separated tokens in the rel attribute; cf. acid2.<commit_after>/*
* Copyright 2010-2012 Esrille 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 "HTMLLinkElementImp.h"
#include <boost/bind.hpp>
#include <boost/version.hpp>
#include <boost/iostreams/stream.hpp>
#include <boost/iostreams/device/file_descriptor.hpp>
#include "DocumentImp.h"
#include "WindowImp.h"
#include "css/CSSInputStream.h"
#include "css/CSSParser.h"
#include "Test.util.h"
namespace org { namespace w3c { namespace dom { namespace bootstrap {
HTMLLinkElementImp::HTMLLinkElementImp(DocumentImp* ownerDocument) :
ObjectMixin(ownerDocument, u"link"),
request(0),
styleSheet(0)
{
}
HTMLLinkElementImp::HTMLLinkElementImp(HTMLLinkElementImp* org, bool deep) :
ObjectMixin(org, deep),
request(0), // TODO: XXX
styleSheet(org->styleSheet) // TODO: make a clone sheet, too?
{
}
HTMLLinkElementImp::~HTMLLinkElementImp()
{
delete request;
}
void HTMLLinkElementImp::eval()
{
std::u16string href = getHref();
if (href.empty())
return;
HTMLElementImp::eval();
std::u16string rel = getRel();
if (contains(rel, u"stylesheet")) {
// TODO: check type
if (!contains(rel, u"alternate")) {
DocumentImp* document = getOwnerDocumentImp();
request = new(std::nothrow) HttpRequest(document->getDocumentURI());
if (request) {
request->open(u"GET", href);
request->setHanndler(boost::bind(&HTMLLinkElementImp::notify, this));
document->incrementLoadEventDelayCount();
request->send();
}
}
}
}
void HTMLLinkElementImp::notify()
{
DocumentImp* document = getOwnerDocumentImp();
if (request->getStatus() == 200) {
#if 104400 <= BOOST_VERSION
boost::iostreams::stream<boost::iostreams::file_descriptor_source> stream(request->getContentDescriptor(), boost::iostreams::never_close_handle);
#else
boost::iostreams::stream<boost::iostreams::file_descriptor_source> stream(request->getContentDescriptor(), false);
#endif
CSSParser parser;
CSSInputStream cssStream(stream, request->getResponseMessage().getContentCharset(), utfconv(document->getCharset()));
styleSheet = parser.parse(document, cssStream);
if (3 <= getLogLevel())
dumpStyleSheet(std::cerr, styleSheet.self());
if (WindowImp* view = document->getDefaultWindow())
view->setFlagsToBoxTree(1);
}
document->decrementLoadEventDelayCount();
}
// Node
Node HTMLLinkElementImp::cloneNode(bool deep)
{
return new(std::nothrow) HTMLLinkElementImp(this, deep);
}
// HTMLLinkElement
bool HTMLLinkElementImp::getDisabled()
{
if (!styleSheet)
return false;
return styleSheet.getDisabled();
}
void HTMLLinkElementImp::setDisabled(bool disabled)
{
if (styleSheet)
styleSheet.setDisabled(disabled);
}
std::u16string HTMLLinkElementImp::getHref()
{
return getAttribute(u"href");
}
void HTMLLinkElementImp::setHref(std::u16string href)
{
// TODO: implement me!
}
std::u16string HTMLLinkElementImp::getRel()
{
// cf. http://www.whatwg.org/specs/web-apps/current-work/multipage/links.html#linkTypes
std::u16string rel = getAttribute(u"rel");
toLower(rel);
return rel;
}
void HTMLLinkElementImp::setRel(std::u16string rel)
{
// TODO: implement me!
}
DOMTokenList HTMLLinkElementImp::getRelList()
{
// TODO: implement me!
return static_cast<Object*>(0);
}
std::u16string HTMLLinkElementImp::getMedia()
{
return getAttribute(u"media");
}
void HTMLLinkElementImp::setMedia(std::u16string media)
{
// TODO: implement me!
}
std::u16string HTMLLinkElementImp::getHreflang()
{
return getAttribute(u"hreflang");
}
void HTMLLinkElementImp::setHreflang(std::u16string hreflang)
{
// TODO: implement me!
}
std::u16string HTMLLinkElementImp::getType()
{
return getAttribute(u"type");
}
void HTMLLinkElementImp::setType(std::u16string type)
{
// TODO: implement me!
}
DOMSettableTokenList HTMLLinkElementImp::getSizes()
{
// TODO: implement me!
return static_cast<Object*>(0);
}
void HTMLLinkElementImp::setSizes(std::u16string sizes)
{
// TODO: implement me!
}
stylesheets::StyleSheet HTMLLinkElementImp::getSheet()
{
return styleSheet;
}
std::u16string HTMLLinkElementImp::getCharset()
{
// TODO: implement me!
return u"";
}
void HTMLLinkElementImp::setCharset(std::u16string charset)
{
// TODO: implement me!
}
std::u16string HTMLLinkElementImp::getRev()
{
// TODO: implement me!
return u"";
}
void HTMLLinkElementImp::setRev(std::u16string rev)
{
// TODO: implement me!
}
std::u16string HTMLLinkElementImp::getTarget()
{
// TODO: implement me!
return u"";
}
void HTMLLinkElementImp::setTarget(std::u16string target)
{
// TODO: implement me!
}
}}}} // org::w3c::dom::bootstrap
<|endoftext|>
|
<commit_before>#include "Time.h"
#include "Singleton.h"
#if _WIN32
#include <Windows.h>
#else // _WIN32
#include <time.h>
#endif // _WIN32
namespace saba
{
namespace
{
#if _WIN32
class Time
{
public:
Time()
{
QueryPerformanceFrequency(&m_freq);
}
double GetTime() const
{
LARGE_INTEGER count;
QueryPerformanceCounter(&count);
return (double)count.QuadPart / (double)m_freq.QuadPart;
}
private:
LARGE_INTEGER m_freq;
};
#else // _WIN32
class Time
{
public:
Time()
{
}
double GetTime() const
{
timespec ts;
clock_gettime(CLOCK_MONOTONIC, &ts);
uint64_t time = (uint64_t)tv.tv_sec * 1000000000 + (uint64_t)tv.tv_usec;
return (double)time / 1000000000.0;
}
};
#endif // _WIN32
}
double GetTime()
{
return Singleton<Time>::Get()->GetTime();
}
double GetTimeMSec()
{
return GetTime() * 1000.0;
}
double GetTimeUSec()
{
return GetTimeMSec() * 1000.0;
}
}
<commit_msg>Fix Linux compile error.<commit_after>#include "Time.h"
#include "Singleton.h"
#if _WIN32
#include <Windows.h>
#else // _WIN32
#include <time.h>
#endif // _WIN32
namespace saba
{
namespace
{
#if _WIN32
class Time
{
public:
Time()
{
QueryPerformanceFrequency(&m_freq);
}
double GetTime() const
{
LARGE_INTEGER count;
QueryPerformanceCounter(&count);
return (double)count.QuadPart / (double)m_freq.QuadPart;
}
private:
LARGE_INTEGER m_freq;
};
#else // _WIN32
class Time
{
public:
Time()
{
}
double GetTime() const
{
timespec ts;
clock_gettime(CLOCK_MONOTONIC, &ts);
uint64_t time = (uint64_t)ts.tv_sec * 1000000000 + (uint64_t)ts.tv_nsec;
return (double)time / 1000000000.0;
}
};
#endif // _WIN32
}
double GetTime()
{
return Singleton<Time>::Get()->GetTime();
}
double GetTimeMSec()
{
return GetTime() * 1000.0;
}
double GetTimeUSec()
{
return GetTimeMSec() * 1000.0;
}
}
<|endoftext|>
|
<commit_before>/*
* Distributed under the OSI-approved Apache License, Version 2.0. See
* accompanying file Copyright.txt for details.
*
* CompressMGARD.cpp :
*
* Created on: Aug 3, 2018
* Author: William F Godoy [email protected]
*/
#include "CompressMGARD.h"
#include <cstring> //std::memcpy
extern "C" {
#include <mgard_capi.h>
}
#include "adios2/helper/adiosFunctions.h"
namespace adios2
{
namespace core
{
namespace compress
{
CompressMGARD::CompressMGARD(const Params ¶meters, const bool debugMode)
: Operator("mgard", parameters, debugMode)
{
}
size_t CompressMGARD::Compress(const void *dataIn, const Dims &dimensions,
const size_t elementSize, const std::string type,
void *bufferOut, const Params ¶meters) const
{
const size_t ndims = dimensions.size();
if (m_DebugMode)
{
if (ndims > 3)
{
throw std::invalid_argument(
"ERROR: ADIOS2 MGARD compression: no more "
"than 3-dimensions is supported.\n");
}
}
// set type
int mgardType = -1;
if (type == "float")
{
if (m_DebugMode)
{
throw std::invalid_argument(
"ERROR: ADIOS2 operator "
"MGARD only supports double precision, in call to Put\n");
}
}
else if (type == "double")
{
mgardType = 1;
}
int r[3];
r[0] = 0;
r[1] = 0;
r[2] = 0;
for (auto i = 0; i < ndims; i++)
{
r[ndims - i - 1] = static_cast<int>(dimensions[i]);
}
// Parameters
auto itTolerance = parameters.find("tolerance");
if (m_DebugMode)
{
if (itTolerance == parameters.end())
{
throw std::invalid_argument("ERROR: missing mandatory parameter "
"tolerance for MGARD compression "
"operator, in call to Put\n");
}
}
double tolerance = std::stod(itTolerance->second);
int sizeOut = 0;
unsigned char *dataOutPtr =
mgard_compress(mgardType, const_cast<void *>(dataIn), &sizeOut, r[0],
r[1], r[2], &tolerance);
const size_t sizeOutT = static_cast<size_t>(sizeOut);
std::memcpy(bufferOut, dataOutPtr, sizeOutT);
return sizeOutT;
}
size_t CompressMGARD::Decompress(const void *bufferIn, const size_t sizeIn,
void *dataOut, const Dims &dimensions,
const std::string type,
const Params & /*parameters*/) const
{
int mgardType = -1;
size_t elementSize = 0;
if (type == "float")
{
if (m_DebugMode)
{
throw std::invalid_argument(
"ERROR: ADIOS2 operator "
"MGARD only supports double precision, in call to Get\n");
}
}
else if (type == "double")
{
mgardType = 1;
elementSize = 8;
}
else
{
if (m_DebugMode)
{
throw std::invalid_argument(
"ERROR: ADIOS2 operator "
"MGARD only supports double precision, in call to Get\n");
}
}
const size_t ndims = dimensions.size();
int r[3];
r[0] = 0;
r[1] = 0;
r[2] = 0;
for (auto i = 0; i < ndims; i++)
{
r[ndims - i - 1] = static_cast<int>(dimensions[i]);
}
void *dataPtr = mgard_decompress(
mgardType,
reinterpret_cast<unsigned char *>(const_cast<void *>(bufferIn)),
static_cast<int>(sizeIn), r[0], r[1], r[2]);
const size_t dataSizeBytes = helper::GetTotalSize(dimensions) * elementSize;
std::memcpy(dataOut, dataPtr, dataSizeBytes);
return static_cast<size_t>(dataSizeBytes);
}
} // end namespace compress
} // end namespace core
} // end namespace adios2
<commit_msg>Support option 'accuracy' in MGARD, as a synonym for tolerance<commit_after>/*
* Distributed under the OSI-approved Apache License, Version 2.0. See
* accompanying file Copyright.txt for details.
*
* CompressMGARD.cpp :
*
* Created on: Aug 3, 2018
* Author: William F Godoy [email protected]
*/
#include "CompressMGARD.h"
#include <cstring> //std::memcpy
extern "C" {
#include <mgard_capi.h>
}
#include "adios2/helper/adiosFunctions.h"
namespace adios2
{
namespace core
{
namespace compress
{
CompressMGARD::CompressMGARD(const Params ¶meters, const bool debugMode)
: Operator("mgard", parameters, debugMode)
{
}
size_t CompressMGARD::Compress(const void *dataIn, const Dims &dimensions,
const size_t elementSize, const std::string type,
void *bufferOut, const Params ¶meters) const
{
const size_t ndims = dimensions.size();
if (m_DebugMode)
{
if (ndims > 3)
{
throw std::invalid_argument(
"ERROR: ADIOS2 MGARD compression: no more "
"than 3-dimensions is supported.\n");
}
}
// set type
int mgardType = -1;
if (type == "float")
{
if (m_DebugMode)
{
throw std::invalid_argument(
"ERROR: ADIOS2 operator "
"MGARD only supports double precision, in call to Put\n");
}
}
else if (type == "double")
{
mgardType = 1;
}
int r[3];
r[0] = 0;
r[1] = 0;
r[2] = 0;
for (auto i = 0; i < ndims; i++)
{
r[ndims - i - 1] = static_cast<int>(dimensions[i]);
}
// Parameters
bool hasTolerance = false;
double tolerance;
auto itAccuracy = parameters.find("accuracy");
if (itAccuracy != parameters.end())
{
tolerance = std::stod(itAccuracy->second);
hasTolerance = true;
}
auto itTolerance = parameters.find("tolerance");
if (itTolerance != parameters.end())
{
tolerance = std::stod(itTolerance->second);
hasTolerance = true;
}
if (!hasTolerance)
{
throw std::invalid_argument("ERROR: missing mandatory parameter "
"tolerance for MGARD compression "
"operator\n");
}
int sizeOut = 0;
unsigned char *dataOutPtr =
mgard_compress(mgardType, const_cast<void *>(dataIn), &sizeOut, r[0],
r[1], r[2], &tolerance);
const size_t sizeOutT = static_cast<size_t>(sizeOut);
std::memcpy(bufferOut, dataOutPtr, sizeOutT);
return sizeOutT;
}
size_t CompressMGARD::Decompress(const void *bufferIn, const size_t sizeIn,
void *dataOut, const Dims &dimensions,
const std::string type,
const Params & /*parameters*/) const
{
int mgardType = -1;
size_t elementSize = 0;
if (type == "float")
{
if (m_DebugMode)
{
throw std::invalid_argument(
"ERROR: ADIOS2 operator "
"MGARD only supports double precision, in call to Get\n");
}
}
else if (type == "double")
{
mgardType = 1;
elementSize = 8;
}
else
{
if (m_DebugMode)
{
throw std::invalid_argument(
"ERROR: ADIOS2 operator "
"MGARD only supports double precision, in call to Get\n");
}
}
const size_t ndims = dimensions.size();
int r[3];
r[0] = 0;
r[1] = 0;
r[2] = 0;
for (auto i = 0; i < ndims; i++)
{
r[ndims - i - 1] = static_cast<int>(dimensions[i]);
}
void *dataPtr = mgard_decompress(
mgardType,
reinterpret_cast<unsigned char *>(const_cast<void *>(bufferIn)),
static_cast<int>(sizeIn), r[0], r[1], r[2]);
const size_t dataSizeBytes = helper::GetTotalSize(dimensions) * elementSize;
std::memcpy(dataOut, dataPtr, dataSizeBytes);
return static_cast<size_t>(dataSizeBytes);
}
} // end namespace compress
} // end namespace core
} // end namespace adios2
<|endoftext|>
|
<commit_before>/*
* Jamoma OSC Receiver
* Copyright © 2011, Théo de la Hogue
*
* License: This code is licensed under the terms of the "New BSD License"
* http://creativecommons.org/licenses/BSD/
*/
#include "TTOscSocket.h"
TTPtr TTOscSocketListener(TTPtr anArgument)
{
TTOscSocketPtr anOscSocket= (TTOscSocketPtr) anArgument;
try {
anOscSocket->mSocketListener = new UdpListeningReceiveSocket(IpEndpointName(IpEndpointName::ANY_ADDRESS, anOscSocket->mPort), anOscSocket);
} catch (const std::runtime_error& error) {
anOscSocket->mSocketListenerStatus = kOscSocketConnectionFailed;
return NULL;
}
if (anOscSocket->mSocketListener) {
try {
anOscSocket->mSocketListenerStatus = kOscSocketConnectionSucceeded;
anOscSocket->mSocketListener->Run();
} catch (const std::exception& exception) {
anOscSocket->mSocketListenerStatus = kOscSocketConnectionFailed;
return NULL;
}
}
return NULL;
}
TTOscSocket::TTOscSocket(const TTObjectBasePtr owner, const TTUInt16 port)
{
mOwner = owner;
mPort = port;
mSocketListenerStatus = kOscSocketConnectionTrying;
mSocketListener = NULL;
mSocketListenerThread = new TTThread(TTOscSocketListener, this);
mSocketTransmitter = NULL;
}
TTOscSocket::TTOscSocket(const TTString& address, const TTUInt16 port)
{
mAddress = address;
mPort = port;
mSocketTransmitter = new UdpTransmitSocket(IpEndpointName(address.data(), port));
mSocketListenerStatus = kOscSocketConnectionTrying;
mSocketListener = NULL;
}
TTOscSocket::~TTOscSocket()
{
unsigned int usecToStopTheSelect = 20000;
if (mSocketListener) {
mSocketListener->AsynchronousBreak();
#ifdef TT_PLATFORM_WIN
Sleep(usecToStopTheSelect/1000);
#else
usleep(usecToStopTheSelect);
#endif
delete mSocketListener;
mSocketListener = NULL;
mSocketListenerStatus = kOscSocketConnectionTrying;
}
if (mSocketTransmitter) {
delete mSocketTransmitter;
mSocketTransmitter = NULL;
}
}
void TTOscSocket::ProcessMessage(const osc::ReceivedMessage&m, const IpEndpointName& remoteEndPoint)
{
TTValue receivedMessage = TTSymbol(m.AddressPattern());
TTValue none;
osc::ReceivedMessage::const_iterator arguments = m.ArgumentsBegin(); // get arguments
while (arguments != m.ArgumentsEnd()) {
if (arguments->IsChar())
receivedMessage.append(arguments->AsChar());
else if (arguments->IsInt32()) {
TTInt32 i = arguments->AsInt32();
receivedMessage.append((int)i);
} else if (arguments->IsFloat())
receivedMessage.append((TTFloat64)arguments->AsFloat());
else if (arguments->IsString())
receivedMessage.append(TTSymbol(arguments->AsString()));
arguments++;
}
this->mOwner->sendMessage(TTSymbol("oscSocketReceive"), receivedMessage, none);
}
TTErr TTOscSocket::SendMessage(TTSymbol& message, const TTValue& arguments)
{
TTUInt32 bufferSize = computeMessageSize(message, arguments);
if (!bufferSize)
return kTTErrGeneric;
#ifdef TT_PLATFORM_WIN
char* buffer = (char*)malloc(bufferSize);
#else
char buffer[bufferSize];
#endif
osc::OutboundPacketStream oscStream(buffer, bufferSize);
oscStream << osc::BeginMessage(message.c_str());
TTSymbol symValue;
TTInt32 intValue;
TTFloat64 floatValue;
TTDataType valueType;
for (TTUInt32 i = 0; i < arguments.size(); ++i) {
valueType = arguments[i].type();
if (valueType == kTypeSymbol) {
symValue = arguments[i];
oscStream << symValue.c_str();
}
else if (valueType == kTypeBoolean) {
intValue = arguments[i];
oscStream << intValue;
}
else if (valueType == kTypeUInt8 || valueType == kTypeUInt16 || valueType == kTypeUInt32 || valueType == kTypeUInt64) {
intValue = arguments[i];
oscStream << intValue;
}
else if (valueType == kTypeInt8 || valueType == kTypeInt16 || valueType == kTypeInt32 || valueType == kTypeInt64) {
intValue = arguments[i];
oscStream << intValue;
}
else if (valueType == kTypeFloat32 || valueType == kTypeFloat64) {
floatValue = arguments[i];
oscStream << (float)floatValue;
}
else {
#ifdef TT_PLATFORM_WIN
free(buffer);
#endif
return kTTErrGeneric;
}
}
oscStream << osc::EndMessage;
mSocketTransmitter->Send(oscStream.Data(), oscStream.Size());
oscStream.Clear();
#ifdef TT_PLATFORM_WIN
free(buffer);
#endif
return kTTErrNone;
}
TTOscSocketConnectionFlag TTOscSocket::getSocketListenerStatus()
{
return mSocketListenerStatus;
}
TTUInt32 TTOscSocket::computeMessageSize(TTSymbol& message, const TTValue& arguments)
{
TTUInt32 result = 0;
result += 8; //#bundle
result += 8; //timetag
result += 4; //datasize
TTUInt32 messageSize = message.string().size();
messageSize += 1; // /0 for end of string
result += ((messageSize/4) + 1) * 4;
TTUInt32 argumentSize = arguments.size();
argumentSize += 1; // , for indicating this is an argument string information
result += ((argumentSize/4) + 1) * 4; // ArgumentTag Size
for (TTUInt32 i = 0; i < arguments.size(); ++i) {
if (arguments[i].type() == kTypeSymbol) {
TTSymbol symValue;
symValue = arguments[i];
TTUInt32 stringSize = symValue.string().size();
stringSize += 1; // /0 for end of string
result += ((stringSize/4) + 1) * 4; // String Size
}
else if (arguments[i].type() == kTypeBoolean) {
result += 1; // Boolean size
}
else if (arguments[i].type() == kTypeUInt8 || arguments[i].type() == kTypeInt8) {
result += 2; // Int8 size
}
else if (arguments[i].type() == kTypeUInt16 || arguments[i].type() == kTypeInt16) {
result += 4; // Int16 size
}
else if (arguments[i].type() == kTypeUInt32 || arguments[i].type() == kTypeInt32 || arguments[i].type() == kTypeFloat32) {
result += 4; // Float32/Int32 size
}
else if (arguments[i].type() == kTypeUInt64 || arguments[i].type() == kTypeInt64 || arguments[i].type() == kTypeFloat64) {
result += 8; // Float64/Int64 size
}
else
return 0; // Error
}
return result;
}<commit_msg>Adding an arror log when an OSC argument cannot be handled<commit_after>/*
* Jamoma OSC Receiver
* Copyright © 2011, Théo de la Hogue
*
* License: This code is licensed under the terms of the "New BSD License"
* http://creativecommons.org/licenses/BSD/
*/
#include "TTOscSocket.h"
TTPtr TTOscSocketListener(TTPtr anArgument)
{
TTOscSocketPtr anOscSocket= (TTOscSocketPtr) anArgument;
try {
anOscSocket->mSocketListener = new UdpListeningReceiveSocket(IpEndpointName(IpEndpointName::ANY_ADDRESS, anOscSocket->mPort), anOscSocket);
} catch (const std::runtime_error& error) {
anOscSocket->mSocketListenerStatus = kOscSocketConnectionFailed;
return NULL;
}
if (anOscSocket->mSocketListener) {
try {
anOscSocket->mSocketListenerStatus = kOscSocketConnectionSucceeded;
anOscSocket->mSocketListener->Run();
} catch (const std::exception& exception) {
anOscSocket->mSocketListenerStatus = kOscSocketConnectionFailed;
return NULL;
}
}
return NULL;
}
TTOscSocket::TTOscSocket(const TTObjectBasePtr owner, const TTUInt16 port)
{
mOwner = owner;
mPort = port;
mSocketListenerStatus = kOscSocketConnectionTrying;
mSocketListener = NULL;
mSocketListenerThread = new TTThread(TTOscSocketListener, this);
mSocketTransmitter = NULL;
}
TTOscSocket::TTOscSocket(const TTString& address, const TTUInt16 port)
{
mAddress = address;
mPort = port;
mSocketTransmitter = new UdpTransmitSocket(IpEndpointName(address.data(), port));
mSocketListenerStatus = kOscSocketConnectionTrying;
mSocketListener = NULL;
}
TTOscSocket::~TTOscSocket()
{
unsigned int usecToStopTheSelect = 20000;
if (mSocketListener) {
mSocketListener->AsynchronousBreak();
#ifdef TT_PLATFORM_WIN
Sleep(usecToStopTheSelect/1000);
#else
usleep(usecToStopTheSelect);
#endif
delete mSocketListener;
mSocketListener = NULL;
mSocketListenerStatus = kOscSocketConnectionTrying;
}
if (mSocketTransmitter) {
delete mSocketTransmitter;
mSocketTransmitter = NULL;
}
}
void TTOscSocket::ProcessMessage(const osc::ReceivedMessage&m, const IpEndpointName& remoteEndPoint)
{
TTValue receivedMessage = TTSymbol(m.AddressPattern());
TTValue none;
osc::ReceivedMessage::const_iterator arguments = m.ArgumentsBegin();
while (arguments != m.ArgumentsEnd())
{
if (arguments->IsChar())
receivedMessage.append(arguments->AsChar());
else if (arguments->IsInt32())
{
TTInt32 i = arguments->AsInt32();
receivedMessage.append((int)i);
}
else if (arguments->IsFloat())
receivedMessage.append((TTFloat64)arguments->AsFloat());
else if (arguments->IsString())
receivedMessage.append(TTSymbol(arguments->AsString()));
else
TTLogError("TTOscSocket::ProcessMessage : the type of an argument is not handled");
arguments++;
}
this->mOwner->sendMessage(TTSymbol("oscSocketReceive"), receivedMessage, none);
}
TTErr TTOscSocket::SendMessage(TTSymbol& message, const TTValue& arguments)
{
TTUInt32 bufferSize = computeMessageSize(message, arguments);
if (!bufferSize)
return kTTErrGeneric;
#ifdef TT_PLATFORM_WIN
char* buffer = (char*)malloc(bufferSize);
#else
char buffer[bufferSize];
#endif
osc::OutboundPacketStream oscStream(buffer, bufferSize);
oscStream << osc::BeginMessage(message.c_str());
TTSymbol symValue;
TTInt32 intValue;
TTFloat64 floatValue;
TTDataType valueType;
for (TTUInt32 i = 0; i < arguments.size(); ++i) {
valueType = arguments[i].type();
if (valueType == kTypeSymbol) {
symValue = arguments[i];
oscStream << symValue.c_str();
}
else if (valueType == kTypeBoolean) {
intValue = arguments[i];
oscStream << intValue;
}
else if (valueType == kTypeUInt8 || valueType == kTypeUInt16 || valueType == kTypeUInt32 || valueType == kTypeUInt64) {
intValue = arguments[i];
oscStream << intValue;
}
else if (valueType == kTypeInt8 || valueType == kTypeInt16 || valueType == kTypeInt32 || valueType == kTypeInt64) {
intValue = arguments[i];
oscStream << intValue;
}
else if (valueType == kTypeFloat32 || valueType == kTypeFloat64) {
floatValue = arguments[i];
oscStream << (float)floatValue;
}
else {
#ifdef TT_PLATFORM_WIN
free(buffer);
#endif
return kTTErrGeneric;
}
}
oscStream << osc::EndMessage;
mSocketTransmitter->Send(oscStream.Data(), oscStream.Size());
oscStream.Clear();
#ifdef TT_PLATFORM_WIN
free(buffer);
#endif
return kTTErrNone;
}
TTOscSocketConnectionFlag TTOscSocket::getSocketListenerStatus()
{
return mSocketListenerStatus;
}
TTUInt32 TTOscSocket::computeMessageSize(TTSymbol& message, const TTValue& arguments)
{
TTUInt32 result = 0;
result += 8; //#bundle
result += 8; //timetag
result += 4; //datasize
TTUInt32 messageSize = message.string().size();
messageSize += 1; // /0 for end of string
result += ((messageSize/4) + 1) * 4;
TTUInt32 argumentSize = arguments.size();
argumentSize += 1; // , for indicating this is an argument string information
result += ((argumentSize/4) + 1) * 4; // ArgumentTag Size
for (TTUInt32 i = 0; i < arguments.size(); ++i) {
if (arguments[i].type() == kTypeSymbol) {
TTSymbol symValue;
symValue = arguments[i];
TTUInt32 stringSize = symValue.string().size();
stringSize += 1; // /0 for end of string
result += ((stringSize/4) + 1) * 4; // String Size
}
else if (arguments[i].type() == kTypeBoolean) {
result += 1; // Boolean size
}
else if (arguments[i].type() == kTypeUInt8 || arguments[i].type() == kTypeInt8) {
result += 2; // Int8 size
}
else if (arguments[i].type() == kTypeUInt16 || arguments[i].type() == kTypeInt16) {
result += 4; // Int16 size
}
else if (arguments[i].type() == kTypeUInt32 || arguments[i].type() == kTypeInt32 || arguments[i].type() == kTypeFloat32) {
result += 4; // Float32/Int32 size
}
else if (arguments[i].type() == kTypeUInt64 || arguments[i].type() == kTypeInt64 || arguments[i].type() == kTypeFloat64) {
result += 8; // Float64/Int64 size
}
else
return 0; // Error
}
return result;
}<|endoftext|>
|
<commit_before>/*
* Copyright 2004 Sandia Corporation.
* Under the terms of Contract DE-AC04-94AL85000, there is a non-exclusive
* license for use of this work by or on behalf of the
* U.S. Government. Redistribution and use in source and binary forms, with
* or without modification, are permitted provided that this Notice and any
* statement of authorship are reproduced on all copies.
*/
/*========================================================================
For general information about using VTK and Qt, see:
http://www.trolltech.com/products/3rdparty/vtksupport.html
=========================================================================*/
/*========================================================================
!!! WARNING for those who want to contribute code to this file.
!!! If you use a commercial edition of Qt, you can modify this code.
!!! If you use an open source version of Qt, you are free to modify
!!! and use this code within the guidelines of the GPL license.
!!! Unfortunately, you cannot contribute the changes back into this
!!! file. Doing so creates a conflict between the GPL and BSD-like VTK
!!! license.
=========================================================================*/
#ifdef _MSC_VER
// Disable warnings that Qt headers give.
#pragma warning(disable:4127)
#pragma warning(disable:4512)
#endif
#if !defined(_DEBUG)
# if !defined(QT_NO_DEBUG)
# define QT_NO_DEBUG
# endif
#endif
#include "Q4VTKWidgetPlugin.h"
#include "QVTKWidget.xpm"
// macro for debug printing
#ifndef qDebug
#define qDebug(a)
//#define qDebug(a) printf(a)
#endif
QVTKWidgetPlugin::QVTKWidgetPlugin()
{
qDebug("QVTKWidgetPlugin instantiated\n");
}
QVTKWidgetPlugin::~QVTKWidgetPlugin()
{
qDebug("QVTKWidgetPlugin destructed\n");
}
//! return the name of this widget
QString QVTKWidgetPlugin::name() const
{
qDebug("QVTKWidgetPlugin::name\n");
return "QVTKWidget";
}
QString QVTKWidgetPlugin::domXml() const
{
return QLatin1String("<widget class=\"QVTKWidget\" name=\"qvtkWidget\">\n"
" <property name=\"geometry\">\n"
" <rect>\n"
" <x>0</x>\n"
" <y>0</y>\n"
" <width>100</width>\n"
" <height>100</height>\n"
" </rect>\n"
" </property>\n"
"</widget>\n");
}
QWidget* QVTKWidgetPlugin::createWidget(QWidget* parent)
{
qDebug("QVTKWidgetPlugin::createWidget\n");
QVTKWidget* widget = new QVTKWidget(parent);
// make black background
QPalette p = widget->palette();
p.setColor(QPalette::Background, QColor("black"));
widget->setPalette(p);
widget->setAutoFillBackground(true);
// return the widget
return widget;
}
QString QVTKWidgetPlugin::group() const
{
qDebug("QVTKWidgetPlugin::group\n");
return "QVTK";
}
QIcon QVTKWidgetPlugin::icon() const
{
qDebug("QVTKWidgetPlugin::icon\n");
return QIcon( QPixmap( QVTKWidget_image ) );
}
//! the name of the include file for building an app with a widget
QString QVTKWidgetPlugin::includeFile() const
{
qDebug("QVTKWidgetPlugin::includeFile\n");
return "QVTKWidget.h";
}
//! tool tip text
QString QVTKWidgetPlugin::toolTip() const
{
qDebug("QVTKWidgetPlugin::toolTip\n");
return "Qt VTK Widget";
}
//! what's this text
QString QVTKWidgetPlugin::whatsThis() const
{
qDebug("QVTKWidgetPlugin::whatsThis\n");
return "A Qt/VTK Graphics Window";
}
//! returns whether widget is a container
bool QVTKWidgetPlugin::isContainer() const
{
qDebug("QVTKWidgetPlugin::isContainer\n");
return false;
}
QVTKPlugin::QVTKPlugin()
{
mQVTKWidgetPlugin = new QVTKWidgetPlugin;
}
QVTKPlugin::~QVTKPlugin()
{
delete mQVTKWidgetPlugin;
}
QList<QDesignerCustomWidgetInterface*> QVTKPlugin::customWidgets() const
{
QList<QDesignerCustomWidgetInterface*> plugins;
plugins.append(mQVTKWidgetPlugin);
return plugins;
}
#if QT_VERSION < 0x050000
Q_EXPORT_PLUGIN(QVTKPlugin)
#endif
<commit_msg>Hopefully supress dashboard compiler warning in QT header<commit_after>/*
* Copyright 2004 Sandia Corporation.
* Under the terms of Contract DE-AC04-94AL85000, there is a non-exclusive
* license for use of this work by or on behalf of the
* U.S. Government. Redistribution and use in source and binary forms, with
* or without modification, are permitted provided that this Notice and any
* statement of authorship are reproduced on all copies.
*/
/*========================================================================
For general information about using VTK and Qt, see:
http://www.trolltech.com/products/3rdparty/vtksupport.html
=========================================================================*/
/*========================================================================
!!! WARNING for those who want to contribute code to this file.
!!! If you use a commercial edition of Qt, you can modify this code.
!!! If you use an open source version of Qt, you are free to modify
!!! and use this code within the guidelines of the GPL license.
!!! Unfortunately, you cannot contribute the changes back into this
!!! file. Doing so creates a conflict between the GPL and BSD-like VTK
!!! license.
=========================================================================*/
// Disable warnings that Qt headers give.
#ifdef _MSC_VER
#pragma warning(disable:4127)
#pragma warning(disable:4512)
#endif
#if defined(__GNUC__) && (__GNUC__>4) || (__GNUC__==4 && __GNUC_MINOR__>=2)
#pragma GCC diagnostic ignored "-Wunused-parameter"
#endif
#if !defined(_DEBUG)
# if !defined(QT_NO_DEBUG)
# define QT_NO_DEBUG
# endif
#endif
#include "Q4VTKWidgetPlugin.h"
#include "QVTKWidget.xpm"
// macro for debug printing
#ifndef qDebug
#define qDebug(a)
//#define qDebug(a) printf(a)
#endif
QVTKWidgetPlugin::QVTKWidgetPlugin()
{
qDebug("QVTKWidgetPlugin instantiated\n");
}
QVTKWidgetPlugin::~QVTKWidgetPlugin()
{
qDebug("QVTKWidgetPlugin destructed\n");
}
//! return the name of this widget
QString QVTKWidgetPlugin::name() const
{
qDebug("QVTKWidgetPlugin::name\n");
return "QVTKWidget";
}
QString QVTKWidgetPlugin::domXml() const
{
return QLatin1String("<widget class=\"QVTKWidget\" name=\"qvtkWidget\">\n"
" <property name=\"geometry\">\n"
" <rect>\n"
" <x>0</x>\n"
" <y>0</y>\n"
" <width>100</width>\n"
" <height>100</height>\n"
" </rect>\n"
" </property>\n"
"</widget>\n");
}
QWidget* QVTKWidgetPlugin::createWidget(QWidget* parent)
{
qDebug("QVTKWidgetPlugin::createWidget\n");
QVTKWidget* widget = new QVTKWidget(parent);
// make black background
QPalette p = widget->palette();
p.setColor(QPalette::Background, QColor("black"));
widget->setPalette(p);
widget->setAutoFillBackground(true);
// return the widget
return widget;
}
QString QVTKWidgetPlugin::group() const
{
qDebug("QVTKWidgetPlugin::group\n");
return "QVTK";
}
QIcon QVTKWidgetPlugin::icon() const
{
qDebug("QVTKWidgetPlugin::icon\n");
return QIcon( QPixmap( QVTKWidget_image ) );
}
//! the name of the include file for building an app with a widget
QString QVTKWidgetPlugin::includeFile() const
{
qDebug("QVTKWidgetPlugin::includeFile\n");
return "QVTKWidget.h";
}
//! tool tip text
QString QVTKWidgetPlugin::toolTip() const
{
qDebug("QVTKWidgetPlugin::toolTip\n");
return "Qt VTK Widget";
}
//! what's this text
QString QVTKWidgetPlugin::whatsThis() const
{
qDebug("QVTKWidgetPlugin::whatsThis\n");
return "A Qt/VTK Graphics Window";
}
//! returns whether widget is a container
bool QVTKWidgetPlugin::isContainer() const
{
qDebug("QVTKWidgetPlugin::isContainer\n");
return false;
}
QVTKPlugin::QVTKPlugin()
{
mQVTKWidgetPlugin = new QVTKWidgetPlugin;
}
QVTKPlugin::~QVTKPlugin()
{
delete mQVTKWidgetPlugin;
}
QList<QDesignerCustomWidgetInterface*> QVTKPlugin::customWidgets() const
{
QList<QDesignerCustomWidgetInterface*> plugins;
plugins.append(mQVTKWidgetPlugin);
return plugins;
}
#if QT_VERSION < 0x050000
Q_EXPORT_PLUGIN(QVTKPlugin)
#endif
<|endoftext|>
|
<commit_before>#include "SparkFunCCS811.hpp"
#include "cox.h"
CCS811Core::CCS811Core( uint8_t inputArg ) : I2CAddress(inputArg){}
CCS811Core::status CCS811Core::readRegister(uint8_t offset, uint8_t* outputPointer){
//Return value
uint8_t result=0;
uint8_t numBytes = 1;
Wire.beginTransmission(I2CAddress);
Wire.write(offset);
Wire.endTransmission();
// slave may send less than requeste
// receive a byte as a proper uint8_t
Wire.requestFrom(I2CAddress, numBytes);
while( Wire.available() ){
result = Wire.read();
}
*outputPointer = result;
return SENSOR_SUCCESS;
}
CCS811Core::status CCS811Core::multiReadRegister(uint8_t offset, uint8_t *outputPointer, uint8_t length){
//define pointer that will point to the external space
uint8_t i = 0;
uint8_t c = 0;
//Set the address
Wire.beginTransmission(I2CAddress);
Wire.write(offset);
Wire.endTransmission();
// request 6 bytes from slave device
Wire.requestFrom(I2CAddress, 4);
while ( (Wire.available()) && (i < length)){
// slave may send less than requested
// receive a byte as character
c = Wire.read();
*outputPointer = c;
outputPointer++;
i++;
}
return SENSOR_SUCCESS;
}
CCS811Core::status CCS811Core::writeRegister(uint8_t offset, uint8_t dataToWrite) {
//offset -- register to write
//dataToWrite -- 8 bit data to write to register
Wire.beginTransmission(I2CAddress);
Wire.write(offset);
Wire.write(dataToWrite);
Wire.endTransmission();
return SENSOR_SUCCESS;
}
CCS811Core::status CCS811Core::multiWriteRegister(uint8_t offset, uint8_t *inputPointer, uint8_t length){
//offset -- register to read
//*inputPointer -- Pass &variable (base address of) to save read data to
//length -- number of bytes to read
//define pointer that will point to the external space
uint8_t i = 0;
//Set the address
Wire.beginTransmission(I2CAddress);
Wire.write(offset);
// receive a byte as character
while ( i < length ){
Wire.write(*inputPointer);
inputPointer++;
i++;
}
Wire.endTransmission();
return SENSOR_SUCCESS;
}
CCS811::CCS811( uint8_t inputArg ) : CCS811Core( inputArg ){
refResistance = 10000;
resistance = 0;
temperature = 0;
tVOC = 0;
CO2 = 0;
}
CCS811Core::status CCS811::begin( void ){
//Reset key
uint8_t data[4] = {0x11,0xE5,0x72,0x8A};
multiWriteRegister(CSS811_SW_RESET, data, 4);
delay(20);
//Write 0 bytes to this register to start app
Wire.beginTransmission(I2CAddress);
Wire.write(CSS811_APP_START);
Wire.endTransmission();
//Read every second
setDriveMode(1);
return SENSOR_SUCCESS;
}
CCS811Core::status CCS811::readAlgorithmResults( void ){
uint8_t data[4];
uint8_t i = 0;
//Set the address
Wire.beginTransmission(I2CAddress);
Wire.write(CSS811_ALG_RESULT_DATA);
Wire.endTransmission();
Wire.requestFrom(I2CAddress, 4);
while ( i < 4){
data[i] = Wire.read();
i++;
}
// data : co2MSB, co2LSB, tvocMSB, tvocLSB
CO2 = ((uint16_t)data[0] << 8) | data[1];
tVOC = ((uint16_t)data[2] << 8) | data[3];
return SENSOR_SUCCESS;
}
//Mode 0 = Idle
//Mode 1 = read every 1s
//Mode 2 = every 10s
//Mode 3 = every 60s
//Mode 4 = RAW mode
CCS811Core::status CCS811::setDriveMode( uint8_t mode ){
//sanitize input
if (mode > 4) mode = 4;
uint8_t value;
//Read what's currently there
//Clear DRIVE_MODE bits
//Mask in mode
CCS811Core::status returnError = readRegister( CSS811_MEAS_MODE, &value );
value &= ~(0b00000111 << 4);
value |= (mode << 4);
returnError = writeRegister(CSS811_MEAS_MODE, value);
return returnError;
}
uint16_t CCS811::getTVOC( void ){
return tVOC;
}
uint16_t CCS811::getCO2( void ){
return CO2;
}
<commit_msg>SparkFunCCS811 library<commit_after>#include "SparkFunCCS811.hpp"
#include "cox.h"
CCS811Core::CCS811Core( uint8_t inputArg ) : I2CAddress(inputArg){}
CCS811Core::status CCS811Core::readRegister(uint8_t offset, uint8_t* outputPointer){
//Return value
uint8_t result=0;
uint8_t numBytes = 1;
Wire.beginTransmission(I2CAddress);
Wire.write(offset);
Wire.endTransmission();
// slave may send less than requeste
// receive a byte as a proper uint8_t
Wire.requestFrom(I2CAddress, numBytes);
while( Wire.available() ){
result = Wire.read();
}
*outputPointer = result;
return SENSOR_SUCCESS;
}
CCS811Core::status CCS811Core::multiReadRegister(uint8_t offset, uint8_t *outputPointer, uint8_t length){
//define pointer that will point to the external space
uint8_t i = 0;
uint8_t c = 0;
//Set the address
Wire.beginTransmission(I2CAddress);
Wire.write(offset);
Wire.endTransmission();
// request 6 bytes from slave device
Wire.requestFrom(I2CAddress, 4);
while ( (Wire.available()) && (i < length)){
// slave may send less than requested
// receive a byte as character
c = Wire.read();
*outputPointer = c;
outputPointer++;
i++;
}
return SENSOR_SUCCESS;
}
CCS811Core::status CCS811Core::writeRegister(uint8_t offset, uint8_t dataToWrite) {
//offset -- register to write
//dataToWrite -- 8 bit data to write to register
Wire.beginTransmission(I2CAddress);
Wire.write(offset);
Wire.write(dataToWrite);
Wire.endTransmission();
return SENSOR_SUCCESS;
}
CCS811Core::status CCS811Core::multiWriteRegister(uint8_t offset, uint8_t *inputPointer, uint8_t length){
//offset -- register to read
//*inputPointer -- Pass &variable (base address of) to save read data to
//length -- number of bytes to read
//define pointer that will point to the external space
uint8_t i = 0;
//Set the address
Wire.beginTransmission(I2CAddress);
Wire.write(offset);
// receive a byte as character
while ( i < length ){
Wire.write(*inputPointer);
inputPointer++;
i++;
}
Wire.endTransmission();
return SENSOR_SUCCESS;
}
CCS811::CCS811( uint8_t inputArg ) : CCS811Core( inputArg ){
refResistance = 10000;
resistance = 0;
temperature = 0;
tVOC = 0;
CO2 = 0;
}
CCS811Core::status CCS811::begin( void ){
//Reset key
uint8_t data[4] = {0x11,0xE5,0x72,0x8A};
multiWriteRegister(CSS811_SW_RESET, data, 4);
delay(20);
//Write 0 bytes to this register to start app
Wire.beginTransmission(I2CAddress);
Wire.write(CSS811_APP_START);
Wire.endTransmission();
//Read every second
setDriveMode(1);
return SENSOR_SUCCESS;
}
CCS811Core::status CCS811::readAlgorithmResults( void ){
uint8_t data[4];
uint8_t i = 0;
//Set the address
Wire.beginTransmission(I2CAddress);
Wire.write(CSS811_ALG_RESULT_DATA);
Wire.endTransmission();
Wire.requestFrom(I2CAddress, 4);
while ( i < 4){
data[i] = Wire.read();
i++;
}
// data : co2MSB, co2LSB, tvocMSB, tvocLSB
CO2 = ((uint16_t)data[0] << 8) | data[1];
tVOC = ((uint16_t)data[2] << 8) | data[3];
return SENSOR_SUCCESS;
}
//Mode 0 = Idle
//Mode 1 = read every 1s
//Mode 2 = every 10s
//Mode 3 = every 60s
//Mode 4 = RAW mode
CCS811Core::status CCS811::setDriveMode( uint8_t mode ){
//sanitize input
if (mode > 4) mode = 4;
uint8_t value;
//Read what's currently there
//Clear DRIVE_MODE bits
//Mask in mode
CCS811Core::status returnError = readRegister( CSS811_MEAS_MODE, &value );
value &= ~(0b00000111 << 4);
value |= (mode << 4);
returnError = writeRegister(CSS811_MEAS_MODE, value);
return returnError;
}
uint16_t CCS811::getTVOC( void ){
return tVOC;
}
uint16_t CCS811::getCO2( void ){
return CO2;
}
<|endoftext|>
|
<commit_before>/*=========================================================================
Program: Visualization Toolkit
Module: TestCubeAxes3.cxx
Copyright (c) Ken Martin, Will Schroeder, Bill Lorensen
All rights reserved.
See Copyright.txt or http://www.kitware.com/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 notice for more information.
=========================================================================*/
// This example illustrates how one may explicitly specify the range of each
// axes that's used to define the prop, while displaying data with a different
// set of bounds (unlike cubeAxes2.tcl). This example allows you to separate
// the notion of extent of the axes in physical space (bounds) and the extent
// of the values it represents. In other words, you can have the ticks and
// labels show a different range.
#include "vtkBYUReader.h"
#include "vtkCamera.h"
#include "vtkCubeAxesActor.h"
#include "vtkLight.h"
#include "vtkLODActor.h"
#include "vtkNew.h"
#include "vtkOutlineFilter.h"
#include "vtkPolyDataMapper.h"
#include "vtkPolyDataNormals.h"
#include "vtkProperty.h"
#include "vtkRegressionTestImage.h"
#include "vtkRenderer.h"
#include "vtkRenderWindow.h"
#include "vtkRenderWindowInteractor.h"
#include "vtkSmartPointer.h"
#include "vtkTestUtilities.h"
#include "vtkTextProperty.h"
//----------------------------------------------------------------------------
int TestCubeAxes3( int argc, char * argv [] )
{
vtkNew<vtkBYUReader> fohe;
char* fname = vtkTestUtilities::ExpandDataFileName(argc, argv, "Data/teapot.g");
fohe->SetGeometryFileName(fname);
delete [] fname;
vtkNew<vtkPolyDataNormals> normals;
normals->SetInputConnection(fohe->GetOutputPort());
vtkNew<vtkPolyDataMapper> foheMapper;
foheMapper->SetInputConnection(normals->GetOutputPort());
vtkNew<vtkLODActor> foheActor;
foheActor->SetMapper(foheMapper.GetPointer());
foheActor->GetProperty()->SetDiffuseColor(0.7, 0.3, 0.0);
vtkNew<vtkOutlineFilter> outline;
outline->SetInputConnection(normals->GetOutputPort());
vtkNew<vtkPolyDataMapper> mapOutline;
mapOutline->SetInputConnection(outline->GetOutputPort());
vtkNew<vtkActor> outlineActor;
outlineActor->SetMapper(mapOutline.GetPointer());
outlineActor->GetProperty()->SetColor(0.0 ,0.0 ,0.0);
vtkNew<vtkCamera> camera;
camera->SetClippingRange(1.0, 100.0);
camera->SetFocalPoint(0.9, 1.0, 0.0);
camera->SetPosition(11.63, 6.0, 10.77);
vtkNew<vtkLight> light;
light->SetFocalPoint(0.21406, 1.5, 0.0);
light->SetPosition(8.3761, 4.94858, 4.12505);
vtkNew<vtkRenderer> ren2;
ren2->SetActiveCamera(camera.GetPointer());
ren2->AddLight(light.GetPointer());
vtkNew<vtkRenderWindow> renWin;
renWin->SetMultiSamples(0);
renWin->AddRenderer(ren2.GetPointer());
renWin->SetWindowName("VTK - Cube Axes custom range");
renWin->SetSize(600, 600);
vtkNew<vtkRenderWindowInteractor> iren;
iren->SetRenderWindow(renWin.GetPointer());
ren2->AddViewProp(foheActor.GetPointer());
ren2->AddViewProp(outlineActor.GetPointer());
ren2->SetBackground(0.1, 0.2, 0.4);
normals->Update();
vtkNew<vtkCubeAxesActor> axes2;
axes2->SetBounds(normals->GetOutput()->GetBounds());
axes2->SetXAxisRange(20, 300);
axes2->SetYAxisRange(-0.01, 0.01);
axes2->SetCamera(ren2->GetActiveCamera());
axes2->SetXLabelFormat("%6.1f");
axes2->SetYLabelFormat("%6.1f");
axes2->SetZLabelFormat("%6.1f");
axes2->SetScreenSize(15.0);
axes2->SetFlyModeToClosestTriad();
axes2->SetCornerOffset(0.0);
axes2->GetTitleTextProperty(0)->SetColor(1., 0., 0.);
axes2->GetLabelTextProperty(0)->SetColor(.5, 0., 0.);
axes2->GetTitleTextProperty(1)->SetColor(0., 1., 0.);
axes2->GetLabelTextProperty(1)->SetColor(0., .5, 0.);
ren2->AddViewProp(axes2.GetPointer());
renWin->Render();
int retVal = vtkRegressionTestImage( renWin.GetPointer() );
if ( retVal == vtkRegressionTester::DO_INTERACTOR)
{
iren->Start();
}
return !retVal;
}
<commit_msg>Now testing various color options for axes lines, titles, etc.<commit_after>/*=========================================================================
Program: Visualization Toolkit
Module: TestCubeAxes3.cxx
Copyright (c) Ken Martin, Will Schroeder, Bill Lorensen
All rights reserved.
See Copyright.txt or http://www.kitware.com/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 notice for more information.
=========================================================================*/
// This example illustrates how one may explicitly specify the range of each
// axes that's used to define the prop, while displaying data with a different
// set of bounds (unlike cubeAxes2.tcl). This example allows you to separate
// the notion of extent of the axes in physical space (bounds) and the extent
// of the values it represents. In other words, you can have the ticks and
// labels show a different range.
#include "vtkBYUReader.h"
#include "vtkCamera.h"
#include "vtkCubeAxesActor.h"
#include "vtkLight.h"
#include "vtkLODActor.h"
#include "vtkNew.h"
#include "vtkOutlineFilter.h"
#include "vtkPolyDataMapper.h"
#include "vtkPolyDataNormals.h"
#include "vtkProperty.h"
#include "vtkRegressionTestImage.h"
#include "vtkRenderer.h"
#include "vtkRenderWindow.h"
#include "vtkRenderWindowInteractor.h"
#include "vtkSmartPointer.h"
#include "vtkTestUtilities.h"
#include "vtkTextProperty.h"
//----------------------------------------------------------------------------
int TestCubeAxes3( int argc, char * argv [] )
{
vtkNew<vtkBYUReader> fohe;
char* fname = vtkTestUtilities::ExpandDataFileName(argc, argv, "Data/teapot.g");
fohe->SetGeometryFileName(fname);
delete [] fname;
vtkNew<vtkPolyDataNormals> normals;
normals->SetInputConnection(fohe->GetOutputPort());
vtkNew<vtkPolyDataMapper> foheMapper;
foheMapper->SetInputConnection(normals->GetOutputPort());
vtkNew<vtkLODActor> foheActor;
foheActor->SetMapper(foheMapper.GetPointer());
foheActor->GetProperty()->SetDiffuseColor(0.7, 0.3, 0.0);
vtkNew<vtkOutlineFilter> outline;
outline->SetInputConnection(normals->GetOutputPort());
vtkNew<vtkPolyDataMapper> mapOutline;
mapOutline->SetInputConnection(outline->GetOutputPort());
vtkNew<vtkActor> outlineActor;
outlineActor->SetMapper(mapOutline.GetPointer());
outlineActor->GetProperty()->SetColor(0.0 ,0.0 ,0.0);
vtkNew<vtkCamera> camera;
camera->SetClippingRange(1.0, 100.0);
camera->SetFocalPoint(0.9, 1.0, 0.0);
camera->SetPosition(11.63, 6.0, 10.77);
vtkNew<vtkLight> light;
light->SetFocalPoint(0.21406, 1.5, 0.0);
light->SetPosition(8.3761, 4.94858, 4.12505);
vtkNew<vtkRenderer> ren2;
ren2->SetActiveCamera(camera.GetPointer());
ren2->AddLight(light.GetPointer());
vtkNew<vtkRenderWindow> renWin;
renWin->SetMultiSamples(0);
renWin->AddRenderer(ren2.GetPointer());
renWin->SetWindowName("VTK - Cube Axes custom range");
renWin->SetSize(600, 600);
vtkNew<vtkRenderWindowInteractor> iren;
iren->SetRenderWindow(renWin.GetPointer());
ren2->AddViewProp(foheActor.GetPointer());
ren2->AddViewProp(outlineActor.GetPointer());
ren2->SetBackground(0.1, 0.2, 0.4);
normals->Update();
vtkNew<vtkCubeAxesActor> axes2;
axes2->SetBounds(normals->GetOutput()->GetBounds());
axes2->SetXAxisRange(20, 300);
axes2->SetYAxisRange(-0.01, 0.01);
axes2->SetCamera(ren2->GetActiveCamera());
axes2->SetXLabelFormat("%6.1f");
axes2->SetYLabelFormat("%6.1f");
axes2->SetZLabelFormat("%6.1f");
axes2->SetScreenSize(15.0);
axes2->SetFlyModeToClosestTriad();
axes2->SetCornerOffset(0.0);
// Use red color for X axis
axes2->GetXAxesLinesProperty()->SetColor(1., 0., 0.);
axes2->GetTitleTextProperty(0)->SetColor(1., 0., 0.);
axes2->GetLabelTextProperty(0)->SetColor(.8, 0., 0.);
// Use green color for Y axis
axes2->GetYAxesLinesProperty()->SetColor(0., 1., 0.);
axes2->GetTitleTextProperty(1)->SetColor(0., 1., 0.);
axes2->GetLabelTextProperty(1)->SetColor(0., .8, 0.);
ren2->AddViewProp(axes2.GetPointer());
renWin->Render();
int retVal = vtkRegressionTestImage( renWin.GetPointer() );
if ( retVal == vtkRegressionTester::DO_INTERACTOR)
{
iren->Start();
}
return !retVal;
}
<|endoftext|>
|
<commit_before>// Copyright (c) 2014, Facebook, Inc. All rights reserved.
// This source code is licensed under the BSD-style license found in the
// LICENSE file in the root directory of this source tree. An additional grant
// of patent rights can be found in the PATENTS file in the same directory.
//
// Copyright (c) 2011 The LevelDB Authors. All rights reserved.
// Use of this source code is governed by a BSD-style license that can be
// found in the LICENSE file. See the AUTHORS file for names of contributors.
#include "util/rate_limiter.h"
#include "rocksdb/env.h"
namespace rocksdb {
// Pending request
struct GenericRateLimiter::Req {
explicit Req(int64_t bytes, port::Mutex* mu) :
bytes(bytes), cv(mu), granted(false) {}
int64_t bytes;
port::CondVar cv;
bool granted;
};
GenericRateLimiter::GenericRateLimiter(
int64_t rate_bytes_per_sec,
int64_t refill_period_us,
int32_t fairness)
: refill_period_us_(refill_period_us),
refill_bytes_per_period_(rate_bytes_per_sec * refill_period_us / 1000000.0),
env_(Env::Default()),
stop_(false),
exit_cv_(&request_mutex_),
requests_to_wait_(0),
total_requests_{0, 0},
total_bytes_through_{0, 0},
available_bytes_(0),
next_refill_us_(env_->NowMicros()),
fairness_(fairness > 100 ? 100 : fairness),
rnd_((uint32_t)time(nullptr)),
leader_(nullptr) {
total_bytes_through_[0] = 0;
total_bytes_through_[1] = 0;
}
GenericRateLimiter::~GenericRateLimiter() {
MutexLock g(&request_mutex_);
stop_ = true;
requests_to_wait_ = queue_[Env::IO_LOW].size() + queue_[Env::IO_HIGH].size();
for (auto& r : queue_[Env::IO_HIGH]) {
r->cv.Signal();
}
for (auto& r : queue_[Env::IO_LOW]) {
r->cv.Signal();
}
while (requests_to_wait_ > 0) {
exit_cv_.Wait();
}
}
void GenericRateLimiter::Request(int64_t bytes, const Env::IOPriority pri) {
assert(bytes < refill_bytes_per_period_);
MutexLock g(&request_mutex_);
if (stop_) {
return;
}
++total_requests_[pri];
if (available_bytes_ >= bytes) {
// Refill thread assigns quota and notifies requests waiting on
// the queue under mutex. So if we get here, that means nobody
// is waiting?
available_bytes_ -= bytes;
total_bytes_through_[pri] += bytes;
return;
}
// Request cannot be satisfied at this moment, enqueue
Req r(bytes, &request_mutex_);
queue_[pri].push_back(&r);
do {
bool timedout = false;
// Leader election, candidates can be:
// (1) a new incoming request,
// (2) a previous leader, whose quota has not been not assigned yet due
// to lower priority
// (3) a previous waiter at the front of queue, who got notified by
// previous leader
if (leader_ == nullptr &&
((!queue_[Env::IO_HIGH].empty() &&
&r == queue_[Env::IO_HIGH].front()) ||
(!queue_[Env::IO_LOW].empty() &&
&r == queue_[Env::IO_LOW].front()))) {
leader_ = &r;
timedout = r.cv.TimedWait(next_refill_us_);
} else {
// Not at the front of queue or an leader has already been elected
r.cv.Wait();
}
// request_mutex_ is held from now on
if (stop_) {
--requests_to_wait_;
exit_cv_.Signal();
return;
}
// Make sure the waken up request is always the header of its queue
assert(r.granted ||
(!queue_[Env::IO_HIGH].empty() &&
&r == queue_[Env::IO_HIGH].front()) ||
(!queue_[Env::IO_LOW].empty() &&
&r == queue_[Env::IO_LOW].front()));
assert(leader_ == nullptr ||
(!queue_[Env::IO_HIGH].empty() &&
leader_ == queue_[Env::IO_HIGH].front()) ||
(!queue_[Env::IO_LOW].empty() &&
leader_ == queue_[Env::IO_LOW].front()));
if (leader_ == &r) {
// Waken up from TimedWait()
if (timedout) {
// Time to do refill!
Refill();
// Re-elect a new leader regardless. This is to simplify the
// election handling.
leader_ = nullptr;
// Notify the header of queue if current leader is going away
if (r.granted) {
// Current leader already got granted with quota. Notify header
// of waiting queue to participate next round of election.
assert((queue_[Env::IO_HIGH].empty() ||
&r != queue_[Env::IO_HIGH].front()) &&
(queue_[Env::IO_LOW].empty() ||
&r != queue_[Env::IO_LOW].front()));
if (!queue_[Env::IO_HIGH].empty()) {
queue_[Env::IO_HIGH].front()->cv.Signal();
} else if (!queue_[Env::IO_LOW].empty()) {
queue_[Env::IO_LOW].front()->cv.Signal();
}
// Done
break;
}
} else {
// Spontaneous wake up, need to continue to wait
assert(!r.granted);
leader_ = nullptr;
}
} else {
// Waken up by previous leader:
// (1) if requested quota is granted, it is done.
// (2) if requested quota is not granted, this means current thread
// was picked as a new leader candidate (previous leader got quota).
// It needs to participate leader election because a new request may
// come in before this thread gets waken up. So it may actually need
// to do Wait() again.
assert(!timedout);
}
} while (!r.granted);
}
void GenericRateLimiter::Refill() {
next_refill_us_ = env_->NowMicros() + refill_period_us_;
// Carry over the left over quota from the last period
if (available_bytes_ < refill_bytes_per_period_) {
available_bytes_ += refill_bytes_per_period_;
}
int use_low_pri_first = rnd_.OneIn(fairness_) ? 0 : 1;
for (int q = 0; q < 2; ++q) {
auto use_pri = (use_low_pri_first == q) ? Env::IO_LOW : Env::IO_HIGH;
auto* queue = &queue_[use_pri];
while (!queue->empty()) {
auto* next_req = queue->front();
if (available_bytes_ < next_req->bytes) {
break;
}
available_bytes_ -= next_req->bytes;
total_bytes_through_[use_pri] += next_req->bytes;
queue->pop_front();
next_req->granted = true;
if (next_req != leader_) {
// Quota granted, signal the thread
next_req->cv.Signal();
}
}
}
}
RateLimiter* NewGenericRateLimiter(
int64_t rate_bytes_per_sec, int64_t refill_period_us, int32_t fairness) {
return new GenericRateLimiter(
rate_bytes_per_sec, refill_period_us, fairness);
}
} // namespace rocksdb
<commit_msg>fix rate limiter crash #286<commit_after>// Copyright (c) 2014, Facebook, Inc. All rights reserved.
// This source code is licensed under the BSD-style license found in the
// LICENSE file in the root directory of this source tree. An additional grant
// of patent rights can be found in the PATENTS file in the same directory.
//
// Copyright (c) 2011 The LevelDB Authors. All rights reserved.
// Use of this source code is governed by a BSD-style license that can be
// found in the LICENSE file. See the AUTHORS file for names of contributors.
#include "util/rate_limiter.h"
#include "rocksdb/env.h"
namespace rocksdb {
// Pending request
struct GenericRateLimiter::Req {
explicit Req(int64_t bytes, port::Mutex* mu) :
bytes(bytes), cv(mu), granted(false) {}
int64_t bytes;
port::CondVar cv;
bool granted;
};
GenericRateLimiter::GenericRateLimiter(
int64_t rate_bytes_per_sec,
int64_t refill_period_us,
int32_t fairness)
: refill_period_us_(refill_period_us),
refill_bytes_per_period_(rate_bytes_per_sec * refill_period_us / 1000000.0),
env_(Env::Default()),
stop_(false),
exit_cv_(&request_mutex_),
requests_to_wait_(0),
total_requests_{0, 0},
total_bytes_through_{0, 0},
available_bytes_(0),
next_refill_us_(env_->NowMicros()),
fairness_(fairness > 100 ? 100 : fairness),
rnd_((uint32_t)time(nullptr)),
leader_(nullptr) {
total_bytes_through_[0] = 0;
total_bytes_through_[1] = 0;
}
GenericRateLimiter::~GenericRateLimiter() {
MutexLock g(&request_mutex_);
stop_ = true;
requests_to_wait_ = queue_[Env::IO_LOW].size() + queue_[Env::IO_HIGH].size();
for (auto& r : queue_[Env::IO_HIGH]) {
r->cv.Signal();
}
for (auto& r : queue_[Env::IO_LOW]) {
r->cv.Signal();
}
while (requests_to_wait_ > 0) {
exit_cv_.Wait();
}
}
void GenericRateLimiter::Request(int64_t bytes, const Env::IOPriority pri) {
assert(bytes <= refill_bytes_per_period_);
MutexLock g(&request_mutex_);
if (stop_) {
return;
}
++total_requests_[pri];
if (available_bytes_ >= bytes) {
// Refill thread assigns quota and notifies requests waiting on
// the queue under mutex. So if we get here, that means nobody
// is waiting?
available_bytes_ -= bytes;
total_bytes_through_[pri] += bytes;
return;
}
// Request cannot be satisfied at this moment, enqueue
Req r(bytes, &request_mutex_);
queue_[pri].push_back(&r);
do {
bool timedout = false;
// Leader election, candidates can be:
// (1) a new incoming request,
// (2) a previous leader, whose quota has not been not assigned yet due
// to lower priority
// (3) a previous waiter at the front of queue, who got notified by
// previous leader
if (leader_ == nullptr &&
((!queue_[Env::IO_HIGH].empty() &&
&r == queue_[Env::IO_HIGH].front()) ||
(!queue_[Env::IO_LOW].empty() &&
&r == queue_[Env::IO_LOW].front()))) {
leader_ = &r;
timedout = r.cv.TimedWait(next_refill_us_);
} else {
// Not at the front of queue or an leader has already been elected
r.cv.Wait();
}
// request_mutex_ is held from now on
if (stop_) {
--requests_to_wait_;
exit_cv_.Signal();
return;
}
// Make sure the waken up request is always the header of its queue
assert(r.granted ||
(!queue_[Env::IO_HIGH].empty() &&
&r == queue_[Env::IO_HIGH].front()) ||
(!queue_[Env::IO_LOW].empty() &&
&r == queue_[Env::IO_LOW].front()));
assert(leader_ == nullptr ||
(!queue_[Env::IO_HIGH].empty() &&
leader_ == queue_[Env::IO_HIGH].front()) ||
(!queue_[Env::IO_LOW].empty() &&
leader_ == queue_[Env::IO_LOW].front()));
if (leader_ == &r) {
// Waken up from TimedWait()
if (timedout) {
// Time to do refill!
Refill();
// Re-elect a new leader regardless. This is to simplify the
// election handling.
leader_ = nullptr;
// Notify the header of queue if current leader is going away
if (r.granted) {
// Current leader already got granted with quota. Notify header
// of waiting queue to participate next round of election.
assert((queue_[Env::IO_HIGH].empty() ||
&r != queue_[Env::IO_HIGH].front()) &&
(queue_[Env::IO_LOW].empty() ||
&r != queue_[Env::IO_LOW].front()));
if (!queue_[Env::IO_HIGH].empty()) {
queue_[Env::IO_HIGH].front()->cv.Signal();
} else if (!queue_[Env::IO_LOW].empty()) {
queue_[Env::IO_LOW].front()->cv.Signal();
}
// Done
break;
}
} else {
// Spontaneous wake up, need to continue to wait
assert(!r.granted);
leader_ = nullptr;
}
} else {
// Waken up by previous leader:
// (1) if requested quota is granted, it is done.
// (2) if requested quota is not granted, this means current thread
// was picked as a new leader candidate (previous leader got quota).
// It needs to participate leader election because a new request may
// come in before this thread gets waken up. So it may actually need
// to do Wait() again.
assert(!timedout);
}
} while (!r.granted);
}
void GenericRateLimiter::Refill() {
next_refill_us_ = env_->NowMicros() + refill_period_us_;
// Carry over the left over quota from the last period
if (available_bytes_ < refill_bytes_per_period_) {
available_bytes_ += refill_bytes_per_period_;
}
int use_low_pri_first = rnd_.OneIn(fairness_) ? 0 : 1;
for (int q = 0; q < 2; ++q) {
auto use_pri = (use_low_pri_first == q) ? Env::IO_LOW : Env::IO_HIGH;
auto* queue = &queue_[use_pri];
while (!queue->empty()) {
auto* next_req = queue->front();
if (available_bytes_ < next_req->bytes) {
break;
}
available_bytes_ -= next_req->bytes;
total_bytes_through_[use_pri] += next_req->bytes;
queue->pop_front();
next_req->granted = true;
if (next_req != leader_) {
// Quota granted, signal the thread
next_req->cv.Signal();
}
}
}
}
RateLimiter* NewGenericRateLimiter(
int64_t rate_bytes_per_sec, int64_t refill_period_us, int32_t fairness) {
return new GenericRateLimiter(
rate_bytes_per_sec, refill_period_us, fairness);
}
} // namespace rocksdb
<|endoftext|>
|
<commit_before>// ==========================================================================
// SeqAn - The Library for Sequence Analysis
// ==========================================================================
// Copyright (c) 2006-2010, Knut Reinert, FU Berlin
// 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 Knut Reinert or the FU Berlin 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 KNUT REINERT OR THE FU BERLIN 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.
//
// ==========================================================================
// Author: Manuel Holtgrewe <[email protected]>
// ==========================================================================
// Tests for the paramChooser.h header.
//
// Currently, we only test the I/O routines from this file.
// ==========================================================================
#undef SEQAN_ENABLE_TESTING
#define SEQAN_ENABLE_TESTING 1
#include <sstream>
#include <seqan/basic.h>
#include <seqan/file.h>
#include "../../../core/apps/splazers/paramChooser.h"
SEQAN_DEFINE_TEST(test_param_chooser_quality_distribution_from_prb_file)
{
seqan::ParamChooserOptions pmOptions;
pmOptions.totalN = 4; // Read length.
pmOptions.verbose = false;
pmOptions.qualityCutoff = 10; // Ignore reads with smaller average quality than threshold.
seqan::String<double> qualDist;
std::stringstream ss;
ss << "40 -40 -40 -40 10 20 30 40 30 30 20 10 10 20 10 10\n"
<< "10 -40 -40 -40 10 10 0 10 9 0 0 0 5 5 5 10\n"
<< "40 -40 -40 -40 10 20 30 40 30 30 20 10 10 20 10 10";
ss.seekg(0);
SEQAN_ASSERT_EQ(qualityDistributionFromPrbFile(ss, qualDist, pmOptions), 0);
SEQAN_ASSERT_EQ(length(qualDist), 4u);
SEQAN_ASSERT_IN_DELTA(qualDist[0], 9.999e-05, 1.0e-07);
SEQAN_ASSERT_IN_DELTA(qualDist[1], 9.999e-05, 1.0e-07);
SEQAN_ASSERT_IN_DELTA(qualDist[2], 0.000999001, 1.0e-07);
SEQAN_ASSERT_IN_DELTA(qualDist[3], 0.00990099, 1.0e-07);
}
SEQAN_DEFINE_TEST(test_param_chooser_quality_distribution_from_fastq_file)
{
seqan::ParamChooserOptions pmOptions;
pmOptions.totalN = 4; // Read length.
pmOptions.verbose = false;
pmOptions.qualityCutoff = 10; // Ignore reads with smaller average quality than threshold.
seqan::String<double> qualDist;
std::stringstream ss;
ss << "@1\n"
<< "CGAT\n"
<< "+\n"
<< "II?5\n"
// << "@2\n" // see prb test, but from FASTQ does not kick out bad reads
// << "CGAT\n"
// << "+\n"
// << "+!*+\n"
<< "@3\n"
<< "CGAT\n"
<< "+\n"
<< "II?5";
ss.seekg(0);
SEQAN_ASSERT_EQ(qualityDistributionFromFastQFile(ss, qualDist, pmOptions), 0);
SEQAN_ASSERT_EQ(length(qualDist), 4u);
SEQAN_ASSERT_IN_DELTA(qualDist[0], 9.999e-05, 1.0e-07);
SEQAN_ASSERT_IN_DELTA(qualDist[1], 9.999e-05, 1.0e-07);
SEQAN_ASSERT_IN_DELTA(qualDist[2], 0.000999001, 1.0e-07);
SEQAN_ASSERT_IN_DELTA(qualDist[3], 0.00990099, 1.0e-07);
}
SEQAN_DEFINE_TEST(test_param_chooser_quality_distribution_from_fastq_int_file)
{
seqan::ParamChooserOptions pmOptions;
pmOptions.totalN = 4; // Read length.
pmOptions.verbose = false;
pmOptions.qualityCutoff = 10; // Ignore reads with smaller average quality than threshold.
seqan::String<double> qualDist;
std::stringstream ss;
ss << "@1\n"
<< "CGAT\n"
<< "+\n"
<< "40 40 30 20\n"
// << "@2\n" // see prb test, but from FASTQ does not kick out bad reads
// << "CGAT\n"
// << "+\n"
// << "+!*+\n"
<< "@3\n"
<< "CGAT\n"
<< "+\n"
<< "40 40 30 20";
ss.seekg(0);
SEQAN_ASSERT_EQ(qualityDistributionFromFastQIntFile(ss, qualDist, pmOptions), 0);
SEQAN_ASSERT_EQ(length(qualDist), 4u);
SEQAN_ASSERT_IN_DELTA(qualDist[0], 9.999e-05, 1.0e-07);
SEQAN_ASSERT_IN_DELTA(qualDist[1], 9.999e-05, 1.0e-07);
SEQAN_ASSERT_IN_DELTA(qualDist[2], 0.000999001, 1.0e-07);
SEQAN_ASSERT_IN_DELTA(qualDist[3], 0.00990099, 1.0e-07);
}
SEQAN_DEFINE_TEST(test_param_chooser_parse_gapped_params)
{
seqan::ParamChooserOptions pmOptions;
pmOptions.totalN = 4; // Read length.
pmOptions.verbose = false;
pmOptions.chooseOneGappedOnly = false;
pmOptions.chooseUngappedOnly = false;
pmOptions.minThreshold = 3;
pmOptions.optionLossRate = 0.01;
seqan::RazerSOptions<> rOptions;
std::stringstream ss;
ss << "errors shape t lossrate PM\n"
<< "\n"
<< "0 11000000100100101 3 0 40895\n"
<< "1 11000000100100101 2 0 492286\n"
<< "2 11000000100100101 1 0.0293446 48417798\n"
<< "3 11000000100100101 1 0.195237 48417798\n"
<< "0 1111100001 10 0 40484\n"
<< "1 1111100001 7 0.163535 48622\n"
<< "1 1111100001 6 0.0497708 51290\n"
<< "1 1111100001 5 0 61068\n"
<< "1 1111101 4 0 61068";
ss.seekg(0);
SEQAN_ASSERT(parseGappedParams(rOptions, ss, pmOptions));
SEQAN_ASSERT_EQ(rOptions.shape, "1111100001");
SEQAN_ASSERT_EQ(rOptions.threshold, 10);
pmOptions.chooseOneGappedOnly = true;
ss.clear();
ss.seekg(0);
SEQAN_ASSERT(parseGappedParams(rOptions, ss, pmOptions));
SEQAN_ASSERT_EQ(rOptions.shape, "1111100001");
SEQAN_ASSERT_EQ(rOptions.threshold, 10);
pmOptions.chooseUngappedOnly = true;
ss.clear();
ss.seekg(0);
SEQAN_ASSERT_NOT(parseGappedParams(rOptions, ss, pmOptions));
}
SEQAN_DEFINE_TEST(test_param_parse_shapes_from_file)
{
seqan::ParamChooserOptions pmOptions;
std::stringstream ss;
ss << " 11000000100100101 \n"
<< "1111100001\n"
<< "1111100001";
ss.seekg(0);
seqan::String<seqan::CharString> shapes;
SEQAN_ASSERT_EQ(parseShapesFromFile(shapes, ss, pmOptions), 3u);
SEQAN_ASSERT_EQ(length(shapes), 3u);
SEQAN_ASSERT_EQ(shapes[0], "11000000100100101");
SEQAN_ASSERT_EQ(shapes[1], "1111100001");
SEQAN_ASSERT_EQ(shapes[2], "1111100001");
}
SEQAN_BEGIN_TESTSUITE(test_param_chooser)
{
SEQAN_CALL_TEST(test_param_chooser_quality_distribution_from_prb_file);
SEQAN_CALL_TEST(test_param_chooser_quality_distribution_from_fastq_file);
SEQAN_CALL_TEST(test_param_chooser_quality_distribution_from_fastq_int_file);
SEQAN_CALL_TEST(test_param_chooser_parse_gapped_params);
SEQAN_CALL_TEST(test_param_parse_shapes_from_file);
}
SEQAN_END_TESTSUITE
<commit_msg>[FIX] Fixing signed/unsigned comparison warning.<commit_after>// ==========================================================================
// SeqAn - The Library for Sequence Analysis
// ==========================================================================
// Copyright (c) 2006-2010, Knut Reinert, FU Berlin
// 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 Knut Reinert or the FU Berlin 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 KNUT REINERT OR THE FU BERLIN 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.
//
// ==========================================================================
// Author: Manuel Holtgrewe <[email protected]>
// ==========================================================================
// Tests for the paramChooser.h header.
//
// Currently, we only test the I/O routines from this file.
// ==========================================================================
#undef SEQAN_ENABLE_TESTING
#define SEQAN_ENABLE_TESTING 1
#include <sstream>
#include <seqan/basic.h>
#include <seqan/file.h>
#include "../../../core/apps/splazers/paramChooser.h"
SEQAN_DEFINE_TEST(test_param_chooser_quality_distribution_from_prb_file)
{
seqan::ParamChooserOptions pmOptions;
pmOptions.totalN = 4; // Read length.
pmOptions.verbose = false;
pmOptions.qualityCutoff = 10; // Ignore reads with smaller average quality than threshold.
seqan::String<double> qualDist;
std::stringstream ss;
ss << "40 -40 -40 -40 10 20 30 40 30 30 20 10 10 20 10 10\n"
<< "10 -40 -40 -40 10 10 0 10 9 0 0 0 5 5 5 10\n"
<< "40 -40 -40 -40 10 20 30 40 30 30 20 10 10 20 10 10";
ss.seekg(0);
SEQAN_ASSERT_EQ(qualityDistributionFromPrbFile(ss, qualDist, pmOptions), 0);
SEQAN_ASSERT_EQ(length(qualDist), 4u);
SEQAN_ASSERT_IN_DELTA(qualDist[0], 9.999e-05, 1.0e-07);
SEQAN_ASSERT_IN_DELTA(qualDist[1], 9.999e-05, 1.0e-07);
SEQAN_ASSERT_IN_DELTA(qualDist[2], 0.000999001, 1.0e-07);
SEQAN_ASSERT_IN_DELTA(qualDist[3], 0.00990099, 1.0e-07);
}
SEQAN_DEFINE_TEST(test_param_chooser_quality_distribution_from_fastq_file)
{
seqan::ParamChooserOptions pmOptions;
pmOptions.totalN = 4; // Read length.
pmOptions.verbose = false;
pmOptions.qualityCutoff = 10; // Ignore reads with smaller average quality than threshold.
seqan::String<double> qualDist;
std::stringstream ss;
ss << "@1\n"
<< "CGAT\n"
<< "+\n"
<< "II?5\n"
// << "@2\n" // see prb test, but from FASTQ does not kick out bad reads
// << "CGAT\n"
// << "+\n"
// << "+!*+\n"
<< "@3\n"
<< "CGAT\n"
<< "+\n"
<< "II?5";
ss.seekg(0);
SEQAN_ASSERT_EQ(qualityDistributionFromFastQFile(ss, qualDist, pmOptions), 0);
SEQAN_ASSERT_EQ(length(qualDist), 4u);
SEQAN_ASSERT_IN_DELTA(qualDist[0], 9.999e-05, 1.0e-07);
SEQAN_ASSERT_IN_DELTA(qualDist[1], 9.999e-05, 1.0e-07);
SEQAN_ASSERT_IN_DELTA(qualDist[2], 0.000999001, 1.0e-07);
SEQAN_ASSERT_IN_DELTA(qualDist[3], 0.00990099, 1.0e-07);
}
SEQAN_DEFINE_TEST(test_param_chooser_quality_distribution_from_fastq_int_file)
{
seqan::ParamChooserOptions pmOptions;
pmOptions.totalN = 4; // Read length.
pmOptions.verbose = false;
pmOptions.qualityCutoff = 10; // Ignore reads with smaller average quality than threshold.
seqan::String<double> qualDist;
std::stringstream ss;
ss << "@1\n"
<< "CGAT\n"
<< "+\n"
<< "40 40 30 20\n"
// << "@2\n" // see prb test, but from FASTQ does not kick out bad reads
// << "CGAT\n"
// << "+\n"
// << "+!*+\n"
<< "@3\n"
<< "CGAT\n"
<< "+\n"
<< "40 40 30 20";
ss.seekg(0);
SEQAN_ASSERT_EQ(qualityDistributionFromFastQIntFile(ss, qualDist, pmOptions), 0);
SEQAN_ASSERT_EQ(length(qualDist), 4u);
SEQAN_ASSERT_IN_DELTA(qualDist[0], 9.999e-05, 1.0e-07);
SEQAN_ASSERT_IN_DELTA(qualDist[1], 9.999e-05, 1.0e-07);
SEQAN_ASSERT_IN_DELTA(qualDist[2], 0.000999001, 1.0e-07);
SEQAN_ASSERT_IN_DELTA(qualDist[3], 0.00990099, 1.0e-07);
}
SEQAN_DEFINE_TEST(test_param_chooser_parse_gapped_params)
{
seqan::ParamChooserOptions pmOptions;
pmOptions.totalN = 4; // Read length.
pmOptions.verbose = false;
pmOptions.chooseOneGappedOnly = false;
pmOptions.chooseUngappedOnly = false;
pmOptions.minThreshold = 3;
pmOptions.optionLossRate = 0.01;
seqan::RazerSOptions<> rOptions;
std::stringstream ss;
ss << "errors shape t lossrate PM\n"
<< "\n"
<< "0 11000000100100101 3 0 40895\n"
<< "1 11000000100100101 2 0 492286\n"
<< "2 11000000100100101 1 0.0293446 48417798\n"
<< "3 11000000100100101 1 0.195237 48417798\n"
<< "0 1111100001 10 0 40484\n"
<< "1 1111100001 7 0.163535 48622\n"
<< "1 1111100001 6 0.0497708 51290\n"
<< "1 1111100001 5 0 61068\n"
<< "1 1111101 4 0 61068";
ss.seekg(0);
SEQAN_ASSERT(parseGappedParams(rOptions, ss, pmOptions));
SEQAN_ASSERT_EQ(rOptions.shape, "1111100001");
SEQAN_ASSERT_EQ(rOptions.threshold, 10);
pmOptions.chooseOneGappedOnly = true;
ss.clear();
ss.seekg(0);
SEQAN_ASSERT(parseGappedParams(rOptions, ss, pmOptions));
SEQAN_ASSERT_EQ(rOptions.shape, "1111100001");
SEQAN_ASSERT_EQ(rOptions.threshold, 10);
pmOptions.chooseUngappedOnly = true;
ss.clear();
ss.seekg(0);
SEQAN_ASSERT_NOT(parseGappedParams(rOptions, ss, pmOptions));
}
SEQAN_DEFINE_TEST(test_param_parse_shapes_from_file)
{
seqan::ParamChooserOptions pmOptions;
std::stringstream ss;
ss << " 11000000100100101 \n"
<< "1111100001\n"
<< "1111100001";
ss.seekg(0);
seqan::String<seqan::CharString> shapes;
SEQAN_ASSERT_EQ(parseShapesFromFile(shapes, ss, pmOptions), 3);
SEQAN_ASSERT_EQ(length(shapes), 3u);
SEQAN_ASSERT_EQ(shapes[0], "11000000100100101");
SEQAN_ASSERT_EQ(shapes[1], "1111100001");
SEQAN_ASSERT_EQ(shapes[2], "1111100001");
}
SEQAN_BEGIN_TESTSUITE(test_param_chooser)
{
SEQAN_CALL_TEST(test_param_chooser_quality_distribution_from_prb_file);
SEQAN_CALL_TEST(test_param_chooser_quality_distribution_from_fastq_file);
SEQAN_CALL_TEST(test_param_chooser_quality_distribution_from_fastq_int_file);
SEQAN_CALL_TEST(test_param_chooser_parse_gapped_params);
SEQAN_CALL_TEST(test_param_parse_shapes_from_file);
}
SEQAN_END_TESTSUITE
<|endoftext|>
|
<commit_before>// @(#) $Id$
/**************************************************************************
* This file is property of and copyright by the ALICE HLT Project *
* ALICE Experiment at CERN, All rights reserved. *
* *
* Primary Authors: Matthias Richter <[email protected]> *
* for The ALICE HLT Project. *
* *
* Permission to use, copy, modify and distribute this software and its *
* documentation strictly for non-commercial purposes is hereby granted *
* without fee, provided that the above copyright notice appears in all *
* copies and that both the copyright notice and this permission notice *
* appear in the supporting documentation. The authors make no claims *
* about the suitability of this software for any purpose. It is *
* provided "as is" without express or implied warranty. *
**************************************************************************/
/** @file AliHLTTPCDigitPublisherComponent.cxx
@author Matthias Richter
@date
@brief TPC digit publisher component (input from offline).
*/
#include "AliHLTTPCDigitPublisherComponent.h"
#include "AliRunLoader.h"
#include "AliLog.h"
#include "TTree.h"
#include "AliHLTTPCDigitData.h"
#include "AliHLTTPCDefinitions.h"
#include "AliHLTTPCFileHandler.h"
/** global instance for agent registration */
AliHLTTPCDigitPublisherComponent gAliHLTTPCDigitPublisherComponent;
/** ROOT macro for the implementation of ROOT specific class methods */
ClassImp(AliHLTTPCDigitPublisherComponent)
AliHLTTPCDigitPublisherComponent::AliHLTTPCDigitPublisherComponent()
:
fMaxSize(200000), // just a number to start with
fMinSlice(0),
fMinPart(0),
fpFileHandler(NULL)
{
// see header file for class documentation
// or
// refer to README to build package
// or
// visit http://web.ift.uib.no/~kjeks/doc/alice-hlt
}
AliHLTTPCDigitPublisherComponent::~AliHLTTPCDigitPublisherComponent()
{
// see header file for class documentation
if (fpFileHandler) {
HLTWarning("improper state, de-initialization missing");
DoDeinit();
}
}
const char* AliHLTTPCDigitPublisherComponent::GetComponentID()
{
// see header file for class documentation
return "TPCDigitPublisher";
}
AliHLTComponentDataType AliHLTTPCDigitPublisherComponent::GetOutputDataType()
{
return AliHLTTPCDefinitions::fgkUnpackedRawDataType;
}
void AliHLTTPCDigitPublisherComponent::GetOutputDataSize( unsigned long& constBase, double& inputMultiplier )
{
constBase=fMaxSize;
inputMultiplier=1;
}
AliHLTComponent* AliHLTTPCDigitPublisherComponent::Spawn()
{
// see header file for class documentation
return new AliHLTTPCDigitPublisherComponent;
}
int AliHLTTPCDigitPublisherComponent::DoInit( int argc, const char** argv )
{
// see header file for class documentation
int iResult=0;
// scan arguments
TString argument="";
int bMissingParam=0;
for (int i=0; i<argc && iResult>=0; i++) {
argument=argv[i];
if (argument.IsNull()) continue;
// -slice
if (argument.CompareTo("-slice")==0) {
if ((bMissingParam=(++i>=argc))) break;
TString parameter(argv[i]);
parameter.Remove(TString::kLeading, ' '); // remove all blanks
if (parameter.IsDigit()) {
fMinSlice=parameter.Atoi();
} else {
HLTError("wrong parameter for argument %s, number expected", argument.Data());
iResult=-EINVAL;
}
// -partition
} else if (argument.CompareTo("-partition")==0) {
if ((bMissingParam=(++i>=argc))) break;
TString parameter(argv[i]);
parameter.Remove(TString::kLeading, ' '); // remove all blanks
if (parameter.IsDigit()) {
fMinPart=parameter.Atoi();
} else {
HLTError("wrong parameter for argument %s, number expected", argument.Data());
iResult=-EINVAL;
}
} else {
HLTError("unknown argument %s", argument.Data());
iResult=-EINVAL;
}
}
if (bMissingParam) {
HLTError("missing parameter for argument %s", argument.Data());
iResult=-EINVAL;
}
if (iResult<0) return iResult;
// fetch runLoader instance from interface
AliRunLoader* pRunLoader=GetRunLoader();
if (pRunLoader) {
fpFileHandler=new AliHLTTPCFileHandler;
if (fpFileHandler) {
fpFileHandler->Init(fMinSlice,fMinPart);
fpFileHandler->SetAliInput(pRunLoader);
} else {
AliErrorStream() << "can not allocate file handler object" << endl;
iResult=-EFAULT;
}
} else {
AliErrorStream() << "can not get runLoader" << endl;
iResult=-EFAULT;
}
return iResult;
}
int AliHLTTPCDigitPublisherComponent::DoDeinit()
{
// see header file for class documentation
int iResult=0;
try {
if (fpFileHandler) {
delete fpFileHandler;
}
}
catch (...) {
HLTFatal("exeption during object cleanup");
iResult=-EFAULT;
}
fpFileHandler=NULL;
return iResult;
}
int AliHLTTPCDigitPublisherComponent::GetEvent(const AliHLTComponentEventData& evtData,
AliHLTComponentTriggerData& trigData,
AliHLTUInt8_t* outputPtr,
AliHLTUInt32_t& size,
vector<AliHLTComponentBlockData>& outputBlocks)
{
// see header file for class documentation
int iResult=0;
if (outputPtr==NULL || size==0) {
HLTError("no target buffer provided");
return -EFAULT;
}
if (fpFileHandler) {
int event=GetEventCount();
AliHLTTPCUnpackedRawData* pTgt=reinterpret_cast<AliHLTTPCUnpackedRawData*>(outputPtr);
if (pTgt) {
UInt_t nrow=0;
UInt_t tgtSize=size-sizeof(AliHLTTPCUnpackedRawData);
AliHLTTPCDigitRowData* pData=fpFileHandler->AliDigits2Memory(nrow, event, reinterpret_cast<Byte_t*>(pTgt->fDigits), &tgtSize);
if (pData==NULL && tgtSize>0 && tgtSize>fMaxSize) {
HLTInfo("target buffer too small: %d byte required, %d available", tgtSize+sizeof(AliHLTTPCUnpackedRawData), size);
// indicate insufficient buffer size, on occasion the frameworks calls
// again with the corrected buffer
fMaxSize=tgtSize;
iResult=-ENOSPC;
} else if (pData!=pTgt->fDigits) {
HLTError("can not read directly into output buffer");
try {delete pData;}
catch (...) {/* no action */}
iResult=-EIO;
} else {
size=tgtSize+sizeof(AliHLTTPCUnpackedRawData);
AliHLTComponentBlockData bd;
FillBlockData( bd );
bd.fOffset = 0;
bd.fSize = size;
bd.fSpecification = AliHLTTPCDefinitions::EncodeDataSpecification(fMinSlice, fMinSlice, fMinPart, fMinPart);
outputBlocks.push_back( bd );
}
}
} else {
AliErrorStream() << "component not initialized" << endl;
iResult=-EFAULT;
}
return iResult;
}
<commit_msg>bugfix: memory cleanup after each event; patch and slice no mandatory<commit_after>// @(#) $Id$
/**************************************************************************
* This file is property of and copyright by the ALICE HLT Project *
* ALICE Experiment at CERN, All rights reserved. *
* *
* Primary Authors: Matthias Richter <[email protected]> *
* for The ALICE HLT Project. *
* *
* Permission to use, copy, modify and distribute this software and its *
* documentation strictly for non-commercial purposes is hereby granted *
* without fee, provided that the above copyright notice appears in all *
* copies and that both the copyright notice and this permission notice *
* appear in the supporting documentation. The authors make no claims *
* about the suitability of this software for any purpose. It is *
* provided "as is" without express or implied warranty. *
**************************************************************************/
/** @file AliHLTTPCDigitPublisherComponent.cxx
@author Matthias Richter
@date
@brief TPC digit publisher component (input from offline).
*/
#include "AliHLTTPCDigitPublisherComponent.h"
#include "AliRunLoader.h"
#include "AliLog.h"
#include "TTree.h"
#include "AliHLTTPCDigitData.h"
#include "AliHLTTPCDefinitions.h"
#include "AliHLTTPCFileHandler.h"
/** global instance for agent registration */
AliHLTTPCDigitPublisherComponent gAliHLTTPCDigitPublisherComponent;
/** ROOT macro for the implementation of ROOT specific class methods */
ClassImp(AliHLTTPCDigitPublisherComponent)
AliHLTTPCDigitPublisherComponent::AliHLTTPCDigitPublisherComponent()
:
fMaxSize(200000), // just a number to start with
fMinSlice(-1),
fMinPart(-1),
fpFileHandler(NULL)
{
// see header file for class documentation
// or
// refer to README to build package
// or
// visit http://web.ift.uib.no/~kjeks/doc/alice-hlt
}
AliHLTTPCDigitPublisherComponent::~AliHLTTPCDigitPublisherComponent()
{
// see header file for class documentation
if (fpFileHandler) {
HLTWarning("improper state, de-initialization missing");
DoDeinit();
}
}
const char* AliHLTTPCDigitPublisherComponent::GetComponentID()
{
// see header file for class documentation
return "TPCDigitPublisher";
}
AliHLTComponentDataType AliHLTTPCDigitPublisherComponent::GetOutputDataType()
{
return AliHLTTPCDefinitions::fgkUnpackedRawDataType;
}
void AliHLTTPCDigitPublisherComponent::GetOutputDataSize( unsigned long& constBase, double& inputMultiplier )
{
constBase=fMaxSize;
inputMultiplier=1;
}
AliHLTComponent* AliHLTTPCDigitPublisherComponent::Spawn()
{
// see header file for class documentation
return new AliHLTTPCDigitPublisherComponent;
}
int AliHLTTPCDigitPublisherComponent::DoInit( int argc, const char** argv )
{
// see header file for class documentation
int iResult=0;
// scan arguments
TString argument="";
int bMissingParam=0;
for (int i=0; i<argc && iResult>=0; i++) {
argument=argv[i];
if (argument.IsNull()) continue;
// -slice
if (argument.CompareTo("-slice")==0) {
if ((bMissingParam=(++i>=argc))) break;
TString parameter(argv[i]);
parameter.Remove(TString::kLeading, ' '); // remove all blanks
if (parameter.IsDigit()) {
fMinSlice=parameter.Atoi();
} else {
HLTError("wrong parameter for argument %s, number expected", argument.Data());
iResult=-EINVAL;
}
// -partition
} else if (argument.CompareTo("-partition")==0) {
if ((bMissingParam=(++i>=argc))) break;
TString parameter(argv[i]);
parameter.Remove(TString::kLeading, ' '); // remove all blanks
if (parameter.IsDigit()) {
fMinPart=parameter.Atoi();
} else {
HLTError("wrong parameter for argument %s, number expected", argument.Data());
iResult=-EINVAL;
}
} else {
HLTError("unknown argument %s", argument.Data());
iResult=-EINVAL;
}
}
if (bMissingParam) {
HLTError("missing parameter for argument %s", argument.Data());
iResult=-EINVAL;
}
if (fMinSlice<0) {
HLTError("slice no required");
iResult=-EINVAL;
}
if (fMinPart<0) {
HLTError("partition (patch) no required");
iResult=-EINVAL;
}
if (iResult<0) return iResult;
// fetch runLoader instance from interface
AliRunLoader* pRunLoader=GetRunLoader();
if (pRunLoader) {
fpFileHandler=new AliHLTTPCFileHandler;
if (fpFileHandler) {
fpFileHandler->Init(fMinSlice,fMinPart);
fpFileHandler->SetAliInput(pRunLoader);
} else {
AliErrorStream() << "can not allocate file handler object" << endl;
iResult=-EFAULT;
}
} else {
AliErrorStream() << "can not get runLoader" << endl;
iResult=-EFAULT;
}
return iResult;
}
int AliHLTTPCDigitPublisherComponent::DoDeinit()
{
// see header file for class documentation
int iResult=0;
try {
if (fpFileHandler) {
delete fpFileHandler;
}
}
catch (...) {
HLTFatal("exeption during object cleanup");
iResult=-EFAULT;
}
fpFileHandler=NULL;
return iResult;
}
int AliHLTTPCDigitPublisherComponent::GetEvent(const AliHLTComponentEventData& evtData,
AliHLTComponentTriggerData& trigData,
AliHLTUInt8_t* outputPtr,
AliHLTUInt32_t& size,
vector<AliHLTComponentBlockData>& outputBlocks)
{
// see header file for class documentation
int iResult=0;
if (outputPtr==NULL || size==0) {
HLTError("no target buffer provided");
return -EFAULT;
}
if (fpFileHandler) {
int event=GetEventCount();
AliHLTTPCUnpackedRawData* pTgt=reinterpret_cast<AliHLTTPCUnpackedRawData*>(outputPtr);
if (pTgt) {
UInt_t nrow=0;
UInt_t tgtSize=size-sizeof(AliHLTTPCUnpackedRawData);
AliHLTTPCDigitRowData* pData=fpFileHandler->AliDigits2Memory(nrow, event, reinterpret_cast<Byte_t*>(pTgt->fDigits), &tgtSize);
if (pData==NULL && tgtSize>0 && tgtSize>fMaxSize) {
HLTInfo("target buffer too small: %d byte required, %d available", tgtSize+sizeof(AliHLTTPCUnpackedRawData), size);
// indicate insufficient buffer size, on occasion the frameworks calls
// again with the corrected buffer
fMaxSize=tgtSize;
iResult=-ENOSPC;
} else if (pData!=pTgt->fDigits) {
HLTError("can not read directly into output buffer");
try {delete pData;}
catch (...) {/* no action */}
iResult=-EIO;
} else {
size=tgtSize+sizeof(AliHLTTPCUnpackedRawData);
AliHLTComponentBlockData bd;
FillBlockData( bd );
bd.fOffset = 0;
bd.fSize = size;
bd.fSpecification = AliHLTTPCDefinitions::EncodeDataSpecification(fMinSlice, fMinSlice, fMinPart, fMinPart);
outputBlocks.push_back( bd );
}
fpFileHandler->FreeDigitsTree();
}
} else {
AliErrorStream() << "component not initialized" << endl;
iResult=-EFAULT;
}
return iResult;
}
<|endoftext|>
|
<commit_before>//===--- Comment.cpp - Comment AST node implementation --------------------===//
//
// The LLVM Compiler Infrastructure
//
// This file is distributed under the University of Illinois Open Source
// License. See LICENSE.TXT for details.
//
//===----------------------------------------------------------------------===//
#include "clang/AST/Comment.h"
#include "clang/AST/Decl.h"
#include "clang/AST/DeclObjC.h"
#include "clang/AST/DeclTemplate.h"
#include "llvm/Support/ErrorHandling.h"
#include "llvm/Support/raw_ostream.h"
namespace clang {
namespace comments {
const char *Comment::getCommentKindName() const {
switch (getCommentKind()) {
case NoCommentKind: return "NoCommentKind";
#define ABSTRACT_COMMENT(COMMENT)
#define COMMENT(CLASS, PARENT) \
case CLASS##Kind: \
return #CLASS;
#include "clang/AST/CommentNodes.inc"
#undef COMMENT
#undef ABSTRACT_COMMENT
}
llvm_unreachable("Unknown comment kind!");
}
void Comment::dump() const {
// It is important that Comment::dump() is defined in a different TU than
// Comment::dump(raw_ostream, SourceManager). If both functions were defined
// in CommentDumper.cpp, that object file would be removed by linker because
// none of its functions are referenced by other object files, despite the
// LLVM_ATTRIBUTE_USED.
dump(llvm::errs(), NULL);
}
void Comment::dump(SourceManager &SM) const {
dump(llvm::errs(), &SM);
}
namespace {
struct good {};
struct bad {};
template <typename T>
good implements_child_begin_end(Comment::child_iterator (T::*)() const) {
return good();
}
static inline bad implements_child_begin_end(
Comment::child_iterator (Comment::*)() const) {
return bad();
}
#define ASSERT_IMPLEMENTS_child_begin(function) \
(void) sizeof(good(implements_child_begin_end(function)))
static inline void CheckCommentASTNodes() {
#define ABSTRACT_COMMENT(COMMENT)
#define COMMENT(CLASS, PARENT) \
ASSERT_IMPLEMENTS_child_begin(&CLASS::child_begin); \
ASSERT_IMPLEMENTS_child_begin(&CLASS::child_end);
#include "clang/AST/CommentNodes.inc"
#undef COMMENT
#undef ABSTRACT_COMMENT
}
#undef ASSERT_IMPLEMENTS_child_begin
} // end unnamed namespace
Comment::child_iterator Comment::child_begin() const {
switch (getCommentKind()) {
case NoCommentKind: llvm_unreachable("comment without a kind");
#define ABSTRACT_COMMENT(COMMENT)
#define COMMENT(CLASS, PARENT) \
case CLASS##Kind: \
return static_cast<const CLASS *>(this)->child_begin();
#include "clang/AST/CommentNodes.inc"
#undef COMMENT
#undef ABSTRACT_COMMENT
}
llvm_unreachable("Unknown comment kind!");
}
Comment::child_iterator Comment::child_end() const {
switch (getCommentKind()) {
case NoCommentKind: llvm_unreachable("comment without a kind");
#define ABSTRACT_COMMENT(COMMENT)
#define COMMENT(CLASS, PARENT) \
case CLASS##Kind: \
return static_cast<const CLASS *>(this)->child_end();
#include "clang/AST/CommentNodes.inc"
#undef COMMENT
#undef ABSTRACT_COMMENT
}
llvm_unreachable("Unknown comment kind!");
}
bool TextComment::isWhitespaceNoCache() const {
for (StringRef::const_iterator I = Text.begin(), E = Text.end();
I != E; ++I) {
const char C = *I;
if (C != ' ' && C != '\n' && C != '\r' &&
C != '\t' && C != '\f' && C != '\v')
return false;
}
return true;
}
bool ParagraphComment::isWhitespaceNoCache() const {
for (child_iterator I = child_begin(), E = child_end(); I != E; ++I) {
if (const TextComment *TC = dyn_cast<TextComment>(*I)) {
if (!TC->isWhitespace())
return false;
} else
return false;
}
return true;
}
const char *ParamCommandComment::getDirectionAsString(PassDirection D) {
switch (D) {
case ParamCommandComment::In:
return "[in]";
case ParamCommandComment::Out:
return "[out]";
case ParamCommandComment::InOut:
return "[in,out]";
}
llvm_unreachable("unknown PassDirection");
}
void DeclInfo::fill() {
assert(!IsFilled);
// Set defaults.
Kind = FunctionKind;
IsTemplateDecl = false;
IsTemplateSpecialization = false;
IsTemplatePartialSpecialization = false;
IsInstanceMethod = false;
IsClassMethod = false;
ParamVars = ArrayRef<const ParmVarDecl *>();
TemplateParameters = NULL;
if (!ThisDecl) {
// Defaults are OK.
} else if (const FunctionDecl *FD = dyn_cast<FunctionDecl>(ThisDecl)) {
Kind = FunctionKind;
ParamVars = ArrayRef<const ParmVarDecl *>(FD->param_begin(),
FD->getNumParams());
unsigned NumLists = FD->getNumTemplateParameterLists();
if (NumLists != 0) {
IsTemplateDecl = true;
IsTemplateSpecialization = true;
TemplateParameters =
FD->getTemplateParameterList(NumLists - 1);
}
if (const CXXMethodDecl *MD = dyn_cast<CXXMethodDecl>(FD)) {
IsInstanceMethod = MD->isInstance();
IsClassMethod = !IsInstanceMethod;
}
} else if (const ObjCMethodDecl *MD = dyn_cast<ObjCMethodDecl>(ThisDecl)) {
Kind = FunctionKind;
ParamVars = ArrayRef<const ParmVarDecl *>(MD->param_begin(),
MD->param_size());
IsInstanceMethod = MD->isInstanceMethod();
IsClassMethod = !IsInstanceMethod;
} else if (const FunctionTemplateDecl *FTD =
dyn_cast<FunctionTemplateDecl>(ThisDecl)) {
Kind = FunctionKind;
IsTemplateDecl = true;
const FunctionDecl *FD = FTD->getTemplatedDecl();
ParamVars = ArrayRef<const ParmVarDecl *>(FD->param_begin(),
FD->getNumParams());
TemplateParameters = FTD->getTemplateParameters();
} else if (const ClassTemplateDecl *CTD =
dyn_cast<ClassTemplateDecl>(ThisDecl)) {
Kind = ClassKind;
IsTemplateDecl = true;
TemplateParameters = CTD->getTemplateParameters();
} else if (const ClassTemplatePartialSpecializationDecl *CTPSD =
dyn_cast<ClassTemplatePartialSpecializationDecl>(ThisDecl)) {
Kind = ClassKind;
IsTemplateDecl = true;
IsTemplatePartialSpecialization = true;
TemplateParameters = CTPSD->getTemplateParameters();
} else if (isa<ClassTemplateSpecializationDecl>(ThisDecl)) {
Kind = ClassKind;
IsTemplateDecl = true;
IsTemplateSpecialization = true;
} else if (isa<RecordDecl>(ThisDecl)) {
Kind = ClassKind;
} else if (isa<VarDecl>(ThisDecl) || isa<FieldDecl>(ThisDecl)) {
Kind = VariableKind;
} else if (isa<NamespaceDecl>(ThisDecl)) {
Kind = NamespaceKind;
} else if (isa<TypedefNameDecl>(ThisDecl)) {
Kind = TypedefKind;
} else if (const TypeAliasTemplateDecl *TAT =
dyn_cast<TypeAliasTemplateDecl>(ThisDecl)) {
Kind = TypedefKind;
IsTemplateDecl = true;
TemplateParameters = TAT->getTemplateParameters();
}
IsFilled = true;
}
} // end namespace comments
} // end namespace clang
<commit_msg>Comment AST: convert a huge if -- else if statement on Decl's type into a switch. Thanks Sean Silva for suggestion!<commit_after>//===--- Comment.cpp - Comment AST node implementation --------------------===//
//
// The LLVM Compiler Infrastructure
//
// This file is distributed under the University of Illinois Open Source
// License. See LICENSE.TXT for details.
//
//===----------------------------------------------------------------------===//
#include "clang/AST/Comment.h"
#include "clang/AST/Decl.h"
#include "clang/AST/DeclObjC.h"
#include "clang/AST/DeclTemplate.h"
#include "llvm/Support/ErrorHandling.h"
#include "llvm/Support/raw_ostream.h"
namespace clang {
namespace comments {
const char *Comment::getCommentKindName() const {
switch (getCommentKind()) {
case NoCommentKind: return "NoCommentKind";
#define ABSTRACT_COMMENT(COMMENT)
#define COMMENT(CLASS, PARENT) \
case CLASS##Kind: \
return #CLASS;
#include "clang/AST/CommentNodes.inc"
#undef COMMENT
#undef ABSTRACT_COMMENT
}
llvm_unreachable("Unknown comment kind!");
}
void Comment::dump() const {
// It is important that Comment::dump() is defined in a different TU than
// Comment::dump(raw_ostream, SourceManager). If both functions were defined
// in CommentDumper.cpp, that object file would be removed by linker because
// none of its functions are referenced by other object files, despite the
// LLVM_ATTRIBUTE_USED.
dump(llvm::errs(), NULL);
}
void Comment::dump(SourceManager &SM) const {
dump(llvm::errs(), &SM);
}
namespace {
struct good {};
struct bad {};
template <typename T>
good implements_child_begin_end(Comment::child_iterator (T::*)() const) {
return good();
}
static inline bad implements_child_begin_end(
Comment::child_iterator (Comment::*)() const) {
return bad();
}
#define ASSERT_IMPLEMENTS_child_begin(function) \
(void) sizeof(good(implements_child_begin_end(function)))
static inline void CheckCommentASTNodes() {
#define ABSTRACT_COMMENT(COMMENT)
#define COMMENT(CLASS, PARENT) \
ASSERT_IMPLEMENTS_child_begin(&CLASS::child_begin); \
ASSERT_IMPLEMENTS_child_begin(&CLASS::child_end);
#include "clang/AST/CommentNodes.inc"
#undef COMMENT
#undef ABSTRACT_COMMENT
}
#undef ASSERT_IMPLEMENTS_child_begin
} // end unnamed namespace
Comment::child_iterator Comment::child_begin() const {
switch (getCommentKind()) {
case NoCommentKind: llvm_unreachable("comment without a kind");
#define ABSTRACT_COMMENT(COMMENT)
#define COMMENT(CLASS, PARENT) \
case CLASS##Kind: \
return static_cast<const CLASS *>(this)->child_begin();
#include "clang/AST/CommentNodes.inc"
#undef COMMENT
#undef ABSTRACT_COMMENT
}
llvm_unreachable("Unknown comment kind!");
}
Comment::child_iterator Comment::child_end() const {
switch (getCommentKind()) {
case NoCommentKind: llvm_unreachable("comment without a kind");
#define ABSTRACT_COMMENT(COMMENT)
#define COMMENT(CLASS, PARENT) \
case CLASS##Kind: \
return static_cast<const CLASS *>(this)->child_end();
#include "clang/AST/CommentNodes.inc"
#undef COMMENT
#undef ABSTRACT_COMMENT
}
llvm_unreachable("Unknown comment kind!");
}
bool TextComment::isWhitespaceNoCache() const {
for (StringRef::const_iterator I = Text.begin(), E = Text.end();
I != E; ++I) {
const char C = *I;
if (C != ' ' && C != '\n' && C != '\r' &&
C != '\t' && C != '\f' && C != '\v')
return false;
}
return true;
}
bool ParagraphComment::isWhitespaceNoCache() const {
for (child_iterator I = child_begin(), E = child_end(); I != E; ++I) {
if (const TextComment *TC = dyn_cast<TextComment>(*I)) {
if (!TC->isWhitespace())
return false;
} else
return false;
}
return true;
}
const char *ParamCommandComment::getDirectionAsString(PassDirection D) {
switch (D) {
case ParamCommandComment::In:
return "[in]";
case ParamCommandComment::Out:
return "[out]";
case ParamCommandComment::InOut:
return "[in,out]";
}
llvm_unreachable("unknown PassDirection");
}
void DeclInfo::fill() {
assert(!IsFilled);
// Set defaults.
Kind = FunctionKind;
IsTemplateDecl = false;
IsTemplateSpecialization = false;
IsTemplatePartialSpecialization = false;
IsInstanceMethod = false;
IsClassMethod = false;
ParamVars = ArrayRef<const ParmVarDecl *>();
TemplateParameters = NULL;
if (!ThisDecl) {
// If there is no declaration, the defaults is our only guess.
IsFilled = true;
return;
}
Decl::Kind K = ThisDecl->getKind();
switch (K) {
default:
// Defaults are should be good for declarations we don't handle explicitly.
break;
case Decl::Function:
case Decl::CXXMethod:
case Decl::CXXConstructor:
case Decl::CXXDestructor:
case Decl::CXXConversion: {
const FunctionDecl *FD = cast<FunctionDecl>(ThisDecl);
Kind = FunctionKind;
ParamVars = ArrayRef<const ParmVarDecl *>(FD->param_begin(),
FD->getNumParams());
unsigned NumLists = FD->getNumTemplateParameterLists();
if (NumLists != 0) {
IsTemplateDecl = true;
IsTemplateSpecialization = true;
TemplateParameters =
FD->getTemplateParameterList(NumLists - 1);
}
if (K == Decl::CXXMethod) {
const CXXMethodDecl *MD = cast<CXXMethodDecl>(ThisDecl);
IsInstanceMethod = MD->isInstance();
IsClassMethod = !IsInstanceMethod;
}
break;
}
case Decl::ObjCMethod: {
const ObjCMethodDecl *MD = cast<ObjCMethodDecl>(ThisDecl);
Kind = FunctionKind;
ParamVars = ArrayRef<const ParmVarDecl *>(MD->param_begin(),
MD->param_size());
IsInstanceMethod = MD->isInstanceMethod();
IsClassMethod = !IsInstanceMethod;
break;
}
case Decl::FunctionTemplate: {
const FunctionTemplateDecl *FTD = cast<FunctionTemplateDecl>(ThisDecl);
Kind = FunctionKind;
IsTemplateDecl = true;
const FunctionDecl *FD = FTD->getTemplatedDecl();
ParamVars = ArrayRef<const ParmVarDecl *>(FD->param_begin(),
FD->getNumParams());
TemplateParameters = FTD->getTemplateParameters();
break;
}
case Decl::ClassTemplate: {
const ClassTemplateDecl *CTD = cast<ClassTemplateDecl>(ThisDecl);
Kind = ClassKind;
IsTemplateDecl = true;
TemplateParameters = CTD->getTemplateParameters();
break;
}
case Decl::ClassTemplatePartialSpecialization: {
const ClassTemplatePartialSpecializationDecl *CTPSD =
cast<ClassTemplatePartialSpecializationDecl>(ThisDecl);
Kind = ClassKind;
IsTemplateDecl = true;
IsTemplatePartialSpecialization = true;
TemplateParameters = CTPSD->getTemplateParameters();
break;
}
case Decl::ClassTemplateSpecialization:
Kind = ClassKind;
IsTemplateDecl = true;
IsTemplateSpecialization = true;
break;
case Decl::Record:
Kind = ClassKind;
break;
case Decl::Var:
case Decl::Field:
case Decl::ObjCIvar:
case Decl::ObjCAtDefsField:
Kind = VariableKind;
break;
case Decl::Namespace:
Kind = NamespaceKind;
break;
case Decl::Typedef:
case Decl::TypeAlias:
Kind = TypedefKind;
break;
case Decl::TypeAliasTemplate: {
const TypeAliasTemplateDecl *TAT = cast<TypeAliasTemplateDecl>(ThisDecl);
Kind = TypedefKind;
IsTemplateDecl = true;
TemplateParameters = TAT->getTemplateParameters();
break;
}
}
IsFilled = true;
}
} // end namespace comments
} // end namespace clang
<|endoftext|>
|
<commit_before>#include "StorageFolding.h"
#include "IROperator.h"
#include "IRMutator.h"
#include "Simplify.h"
#include "Bounds.h"
#include "IRPrinter.h"
#include "Debug.h"
#include "Derivative.h"
namespace Halide {
namespace Internal {
using std::string;
using std::vector;
using std::map;
// Fold the storage of a function in a particular dimension by a particular factor
class FoldStorageOfFunction : public IRMutator {
string func;
int dim;
Expr factor;
using IRMutator::visit;
void visit(const Call *op) {
IRMutator::visit(op);
op = expr.as<Call>();
internal_assert(op);
if (op->name == func && op->call_type == Call::Halide) {
vector<Expr> args = op->args;
internal_assert(dim < (int)args.size());
args[dim] = args[dim] % factor;
expr = Call::make(op->type, op->name, args, op->call_type,
op->func, op->value_index, op->image, op->param);
}
}
void visit(const Provide *op) {
IRMutator::visit(op);
op = stmt.as<Provide>();
internal_assert(op);
if (op->name == func) {
vector<Expr> args = op->args;
args[dim] = args[dim] % factor;
stmt = Provide::make(op->name, op->values, args);
}
}
public:
FoldStorageOfFunction(string f, int d, Expr e) :
func(f), dim(d), factor(e) {}
};
// Attempt to fold the storage of a particular function in a statement
class AttemptStorageFoldingOfFunction : public IRMutator {
string func;
using IRMutator::visit;
void visit(const Pipeline *op) {
if (op->name == func) {
// Can't proceed into the pipeline for this func
stmt = op;
} else {
IRMutator::visit(op);
}
}
void visit(const For *op) {
if (op->for_type != For::Serial && op->for_type != For::Unrolled) {
// We can't proceed into a parallel for loop.
// TODO: If there's no overlap between the region touched
// by the threads as this loop counter varies
// (i.e. there's no cross-talk between threads), then it's
// safe to proceed.
stmt = op;
return;
}
Box box = box_touched(op->body, func);
Stmt result = op;
// Try each dimension in turn from outermost in
for (size_t i = box.size(); i > 0; i--) {
Expr min = box[i-1].min;
Expr max = box[i-1].max;
debug(3) << "Considering folding " << func << " over for loop over " << op->name << '\n'
<< "Min: " << min << '\n'
<< "Max: " << max << '\n';
// The min or max has to be monotonic with the loop
// variable, and should depend on the loop variable.
if (is_monotonic(min, op->name) == MonotonicIncreasing ||
is_monotonic(max, op->name) == MonotonicDecreasing) {
// The max of the extent over all values of the loop variable must be a constant
Expr extent = simplify(max - min);
Scope<Interval> scope;
scope.push(op->name, Interval(Variable::make(Int(32), op->name + ".loop_min"),
Variable::make(Int(32), op->name + ".loop_max")));
Expr max_extent = bounds_of_expr_in_scope(extent, scope).max;
scope.pop(op->name);
max_extent = simplify(max_extent);
const IntImm *max_extent_int = max_extent.as<IntImm>();
if (max_extent_int) {
int extent = max_extent_int->value;
debug(3) << "Proceeding...\n";
int factor = 1;
while (factor <= extent) factor *= 2;
dim_folded = (int)i - 1;
fold_factor = factor;
stmt = FoldStorageOfFunction(func, (int)i - 1, factor).mutate(result);
return;
} else {
debug(3) << "Not folding because extent not bounded by a constant\n"
<< "extent = " << extent << "\n"
<< "max extent = " << max_extent << "\n";
}
} else {
debug(3) << "Not folding because loop min or max not monotonic in the loop variable\n"
<< "min = " << min << "\n"
<< "max = " << max << "\n";
}
}
stmt = result;
}
public:
int dim_folded;
Expr fold_factor;
AttemptStorageFoldingOfFunction(string f) : func(f), dim_folded(-1) {}
};
/** Check if a buffer's allocated is referred to directly via an
* intrinsic. If so we should leave it alone. (e.g. it may be used
* extern). */
class IsBufferSpecial : public IRVisitor {
public:
string func;
bool special;
IsBufferSpecial(string f) : func(f), special(false) {}
private:
using IRVisitor::visit;
void visit(const Call *call) {
if (call->call_type == Call::Intrinsic &&
call->name == func) {
special = true;
}
}
};
// Look for opportunities for storage folding in a statement
class StorageFolding : public IRMutator {
using IRMutator::visit;
void visit(const Realize *op) {
Stmt body = mutate(op->body);
AttemptStorageFoldingOfFunction folder(op->name);
IsBufferSpecial special(op->name);
op->accept(&special);
if (special.special) {
debug(3) << "Not attempting to fold " << op->name << " because it is referenced by an intrinsic\n";
if (body.same_as(op->body)) {
stmt = op;
} else {
stmt = Realize::make(op->name, op->types, op->bounds, body);
}
} else {
debug(3) << "Attempting to fold " << op->name << "\n";
Stmt new_body = folder.mutate(body);
if (new_body.same_as(op->body)) {
stmt = op;
} else if (new_body.same_as(body)) {
stmt = Realize::make(op->name, op->types, op->bounds, body);
} else {
Region bounds = op->bounds;
internal_assert(folder.dim_folded >= 0 &&
folder.dim_folded < (int)bounds.size());
bounds[folder.dim_folded] = Range(0, folder.fold_factor);
stmt = Realize::make(op->name, op->types, bounds, new_body);
}
}
}
};
Stmt storage_folding(Stmt s) {
return StorageFolding().mutate(s);
}
}
}
<commit_msg>Indentation fix.<commit_after>#include "StorageFolding.h"
#include "IROperator.h"
#include "IRMutator.h"
#include "Simplify.h"
#include "Bounds.h"
#include "IRPrinter.h"
#include "Debug.h"
#include "Derivative.h"
namespace Halide {
namespace Internal {
using std::string;
using std::vector;
using std::map;
// Fold the storage of a function in a particular dimension by a particular factor
class FoldStorageOfFunction : public IRMutator {
string func;
int dim;
Expr factor;
using IRMutator::visit;
void visit(const Call *op) {
IRMutator::visit(op);
op = expr.as<Call>();
internal_assert(op);
if (op->name == func && op->call_type == Call::Halide) {
vector<Expr> args = op->args;
internal_assert(dim < (int)args.size());
args[dim] = args[dim] % factor;
expr = Call::make(op->type, op->name, args, op->call_type,
op->func, op->value_index, op->image, op->param);
}
}
void visit(const Provide *op) {
IRMutator::visit(op);
op = stmt.as<Provide>();
internal_assert(op);
if (op->name == func) {
vector<Expr> args = op->args;
args[dim] = args[dim] % factor;
stmt = Provide::make(op->name, op->values, args);
}
}
public:
FoldStorageOfFunction(string f, int d, Expr e) :
func(f), dim(d), factor(e) {}
};
// Attempt to fold the storage of a particular function in a statement
class AttemptStorageFoldingOfFunction : public IRMutator {
string func;
using IRMutator::visit;
void visit(const Pipeline *op) {
if (op->name == func) {
// Can't proceed into the pipeline for this func
stmt = op;
} else {
IRMutator::visit(op);
}
}
void visit(const For *op) {
if (op->for_type != For::Serial && op->for_type != For::Unrolled) {
// We can't proceed into a parallel for loop.
// TODO: If there's no overlap between the region touched
// by the threads as this loop counter varies
// (i.e. there's no cross-talk between threads), then it's
// safe to proceed.
stmt = op;
return;
}
Box box = box_touched(op->body, func);
Stmt result = op;
// Try each dimension in turn from outermost in
for (size_t i = box.size(); i > 0; i--) {
Expr min = box[i-1].min;
Expr max = box[i-1].max;
debug(3) << "Considering folding " << func << " over for loop over " << op->name << '\n'
<< "Min: " << min << '\n'
<< "Max: " << max << '\n';
// The min or max has to be monotonic with the loop
// variable, and should depend on the loop variable.
if (is_monotonic(min, op->name) == MonotonicIncreasing ||
is_monotonic(max, op->name) == MonotonicDecreasing) {
// The max of the extent over all values of the loop variable must be a constant
Expr extent = simplify(max - min);
Scope<Interval> scope;
scope.push(op->name, Interval(Variable::make(Int(32), op->name + ".loop_min"),
Variable::make(Int(32), op->name + ".loop_max")));
Expr max_extent = bounds_of_expr_in_scope(extent, scope).max;
scope.pop(op->name);
max_extent = simplify(max_extent);
const IntImm *max_extent_int = max_extent.as<IntImm>();
if (max_extent_int) {
int extent = max_extent_int->value;
debug(3) << "Proceeding...\n";
int factor = 1;
while (factor <= extent) factor *= 2;
dim_folded = (int)i - 1;
fold_factor = factor;
stmt = FoldStorageOfFunction(func, (int)i - 1, factor).mutate(result);
return;
} else {
debug(3) << "Not folding because extent not bounded by a constant\n"
<< "extent = " << extent << "\n"
<< "max extent = " << max_extent << "\n";
}
} else {
debug(3) << "Not folding because loop min or max not monotonic in the loop variable\n"
<< "min = " << min << "\n"
<< "max = " << max << "\n";
}
}
stmt = result;
}
public:
int dim_folded;
Expr fold_factor;
AttemptStorageFoldingOfFunction(string f) : func(f), dim_folded(-1) {}
};
/** Check if a buffer's allocated is referred to directly via an
* intrinsic. If so we should leave it alone. (e.g. it may be used
* extern). */
class IsBufferSpecial : public IRVisitor {
public:
string func;
bool special;
IsBufferSpecial(string f) : func(f), special(false) {}
private:
using IRVisitor::visit;
void visit(const Call *call) {
if (call->call_type == Call::Intrinsic &&
call->name == func) {
special = true;
}
}
};
// Look for opportunities for storage folding in a statement
class StorageFolding : public IRMutator {
using IRMutator::visit;
void visit(const Realize *op) {
Stmt body = mutate(op->body);
AttemptStorageFoldingOfFunction folder(op->name);
IsBufferSpecial special(op->name);
op->accept(&special);
if (special.special) {
debug(3) << "Not attempting to fold " << op->name << " because it is referenced by an intrinsic\n";
if (body.same_as(op->body)) {
stmt = op;
} else {
stmt = Realize::make(op->name, op->types, op->bounds, body);
}
} else {
debug(3) << "Attempting to fold " << op->name << "\n";
Stmt new_body = folder.mutate(body);
if (new_body.same_as(op->body)) {
stmt = op;
} else if (new_body.same_as(body)) {
stmt = Realize::make(op->name, op->types, op->bounds, body);
} else {
Region bounds = op->bounds;
internal_assert(folder.dim_folded >= 0 &&
folder.dim_folded < (int)bounds.size());
bounds[folder.dim_folded] = Range(0, folder.fold_factor);
stmt = Realize::make(op->name, op->types, bounds, new_body);
}
}
}
};
Stmt storage_folding(Stmt s) {
return StorageFolding().mutate(s);
}
}
}
<|endoftext|>
|
<commit_before>// ==========================================================================
// SeqAn - The Library for Sequence Analysis
// ==========================================================================
// Copyright (c) 2006-2010, Knut Reinert, FU Berlin
// 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 Knut Reinert or the FU Berlin 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 KNUT REINERT OR THE FU BERLIN 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.
//
// ==========================================================================
// Author: Manuel Holtgrewe <[email protected]>
// ==========================================================================
// Tests for the paramChooser.h header.
//
// Currently, we only test the I/O routines from this file.
// ==========================================================================
#undef SEQAN_ENABLE_TESTING
#define SEQAN_ENABLE_TESTING 1
#include <sstream>
#include <seqan/basic.h>
#include <seqan/file.h>
#include "../../../core/apps/splazers/paramChooser.h"
SEQAN_DEFINE_TEST(test_param_chooser_quality_distribution_from_prb_file)
{
seqan::ParamChooserOptions pmOptions;
pmOptions.totalN = 4; // Read length.
pmOptions.verbose = false;
pmOptions.qualityCutoff = 10; // Ignore reads with smaller average quality than threshold.
seqan::String<double> qualDist;
std::stringstream ss;
ss << "40 -40 -40 -40 10 20 30 40 30 30 20 10 10 20 10 10\n"
<< "10 -40 -40 -40 10 10 0 10 9 0 0 0 5 5 5 10\n"
<< "40 -40 -40 -40 10 20 30 40 30 30 20 10 10 20 10 10";
ss.seekg(0);
SEQAN_ASSERT_EQ(qualityDistributionFromPrbFile(ss, qualDist, pmOptions), 0);
SEQAN_ASSERT_EQ(length(qualDist), 4u);
SEQAN_ASSERT_IN_DELTA(qualDist[0], 9.999e-05, 1.0e-07);
SEQAN_ASSERT_IN_DELTA(qualDist[1], 9.999e-05, 1.0e-07);
SEQAN_ASSERT_IN_DELTA(qualDist[2], 0.000999001, 1.0e-07);
SEQAN_ASSERT_IN_DELTA(qualDist[3], 0.00990099, 1.0e-07);
}
SEQAN_DEFINE_TEST(test_param_chooser_quality_distribution_from_fastq_file)
{
seqan::ParamChooserOptions pmOptions;
pmOptions.totalN = 4; // Read length.
pmOptions.verbose = false;
pmOptions.qualityCutoff = 10; // Ignore reads with smaller average quality than threshold.
seqan::String<double> qualDist;
std::stringstream ss;
ss << "@1\n"
<< "CGAT\n"
<< "+\n"
<< "II?5\n"
// << "@2\n" // see prb test, but from FASTQ does not kick out bad reads
// << "CGAT\n"
// << "+\n"
// << "+!*+\n"
<< "@3\n"
<< "CGAT\n"
<< "+\n"
<< "II?5";
ss.seekg(0);
SEQAN_ASSERT_EQ(qualityDistributionFromFastQFile(ss, qualDist, pmOptions), 0);
SEQAN_ASSERT_EQ(length(qualDist), 4u);
SEQAN_ASSERT_IN_DELTA(qualDist[0], 9.999e-05, 1.0e-07);
SEQAN_ASSERT_IN_DELTA(qualDist[1], 9.999e-05, 1.0e-07);
SEQAN_ASSERT_IN_DELTA(qualDist[2], 0.000999001, 1.0e-07);
SEQAN_ASSERT_IN_DELTA(qualDist[3], 0.00990099, 1.0e-07);
}
SEQAN_DEFINE_TEST(test_param_chooser_quality_distribution_from_fastq_int_file)
{
seqan::ParamChooserOptions pmOptions;
pmOptions.totalN = 4; // Read length.
pmOptions.verbose = false;
pmOptions.qualityCutoff = 10; // Ignore reads with smaller average quality than threshold.
seqan::String<double> qualDist;
std::stringstream ss;
ss << "@1\n"
<< "CGAT\n"
<< "+\n"
<< "40 40 30 20\n"
// << "@2\n" // see prb test, but from FASTQ does not kick out bad reads
// << "CGAT\n"
// << "+\n"
// << "+!*+\n"
<< "@3\n"
<< "CGAT\n"
<< "+\n"
<< "40 40 30 20";
ss.seekg(0);
SEQAN_ASSERT_EQ(qualityDistributionFromFastQIntFile(ss, qualDist, pmOptions), 0);
SEQAN_ASSERT_EQ(length(qualDist), 4u);
SEQAN_ASSERT_IN_DELTA(qualDist[0], 9.999e-05, 1.0e-07);
SEQAN_ASSERT_IN_DELTA(qualDist[1], 9.999e-05, 1.0e-07);
SEQAN_ASSERT_IN_DELTA(qualDist[2], 0.000999001, 1.0e-07);
SEQAN_ASSERT_IN_DELTA(qualDist[3], 0.00990099, 1.0e-07);
}
SEQAN_BEGIN_TESTSUITE(test_param_chooser)
{
SEQAN_CALL_TEST(test_param_chooser_quality_distribution_from_prb_file);
SEQAN_CALL_TEST(test_param_chooser_quality_distribution_from_fastq_file);
SEQAN_CALL_TEST(test_param_chooser_quality_distribution_from_fastq_int_file);
}
SEQAN_END_TESTSUITE
<commit_msg>[TEST] Adding test for parseGappedParams in paramChooser.h.<commit_after>// ==========================================================================
// SeqAn - The Library for Sequence Analysis
// ==========================================================================
// Copyright (c) 2006-2010, Knut Reinert, FU Berlin
// 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 Knut Reinert or the FU Berlin 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 KNUT REINERT OR THE FU BERLIN 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.
//
// ==========================================================================
// Author: Manuel Holtgrewe <[email protected]>
// ==========================================================================
// Tests for the paramChooser.h header.
//
// Currently, we only test the I/O routines from this file.
// ==========================================================================
#undef SEQAN_ENABLE_TESTING
#define SEQAN_ENABLE_TESTING 1
#include <sstream>
#include <seqan/basic.h>
#include <seqan/file.h>
#include "../../../core/apps/splazers/paramChooser.h"
SEQAN_DEFINE_TEST(test_param_chooser_quality_distribution_from_prb_file)
{
seqan::ParamChooserOptions pmOptions;
pmOptions.totalN = 4; // Read length.
pmOptions.verbose = false;
pmOptions.qualityCutoff = 10; // Ignore reads with smaller average quality than threshold.
seqan::String<double> qualDist;
std::stringstream ss;
ss << "40 -40 -40 -40 10 20 30 40 30 30 20 10 10 20 10 10\n"
<< "10 -40 -40 -40 10 10 0 10 9 0 0 0 5 5 5 10\n"
<< "40 -40 -40 -40 10 20 30 40 30 30 20 10 10 20 10 10";
ss.seekg(0);
SEQAN_ASSERT_EQ(qualityDistributionFromPrbFile(ss, qualDist, pmOptions), 0);
SEQAN_ASSERT_EQ(length(qualDist), 4u);
SEQAN_ASSERT_IN_DELTA(qualDist[0], 9.999e-05, 1.0e-07);
SEQAN_ASSERT_IN_DELTA(qualDist[1], 9.999e-05, 1.0e-07);
SEQAN_ASSERT_IN_DELTA(qualDist[2], 0.000999001, 1.0e-07);
SEQAN_ASSERT_IN_DELTA(qualDist[3], 0.00990099, 1.0e-07);
}
SEQAN_DEFINE_TEST(test_param_chooser_quality_distribution_from_fastq_file)
{
seqan::ParamChooserOptions pmOptions;
pmOptions.totalN = 4; // Read length.
pmOptions.verbose = false;
pmOptions.qualityCutoff = 10; // Ignore reads with smaller average quality than threshold.
seqan::String<double> qualDist;
std::stringstream ss;
ss << "@1\n"
<< "CGAT\n"
<< "+\n"
<< "II?5\n"
// << "@2\n" // see prb test, but from FASTQ does not kick out bad reads
// << "CGAT\n"
// << "+\n"
// << "+!*+\n"
<< "@3\n"
<< "CGAT\n"
<< "+\n"
<< "II?5";
ss.seekg(0);
SEQAN_ASSERT_EQ(qualityDistributionFromFastQFile(ss, qualDist, pmOptions), 0);
SEQAN_ASSERT_EQ(length(qualDist), 4u);
SEQAN_ASSERT_IN_DELTA(qualDist[0], 9.999e-05, 1.0e-07);
SEQAN_ASSERT_IN_DELTA(qualDist[1], 9.999e-05, 1.0e-07);
SEQAN_ASSERT_IN_DELTA(qualDist[2], 0.000999001, 1.0e-07);
SEQAN_ASSERT_IN_DELTA(qualDist[3], 0.00990099, 1.0e-07);
}
SEQAN_DEFINE_TEST(test_param_chooser_quality_distribution_from_fastq_int_file)
{
seqan::ParamChooserOptions pmOptions;
pmOptions.totalN = 4; // Read length.
pmOptions.verbose = false;
pmOptions.qualityCutoff = 10; // Ignore reads with smaller average quality than threshold.
seqan::String<double> qualDist;
std::stringstream ss;
ss << "@1\n"
<< "CGAT\n"
<< "+\n"
<< "40 40 30 20\n"
// << "@2\n" // see prb test, but from FASTQ does not kick out bad reads
// << "CGAT\n"
// << "+\n"
// << "+!*+\n"
<< "@3\n"
<< "CGAT\n"
<< "+\n"
<< "40 40 30 20";
ss.seekg(0);
SEQAN_ASSERT_EQ(qualityDistributionFromFastQIntFile(ss, qualDist, pmOptions), 0);
SEQAN_ASSERT_EQ(length(qualDist), 4u);
SEQAN_ASSERT_IN_DELTA(qualDist[0], 9.999e-05, 1.0e-07);
SEQAN_ASSERT_IN_DELTA(qualDist[1], 9.999e-05, 1.0e-07);
SEQAN_ASSERT_IN_DELTA(qualDist[2], 0.000999001, 1.0e-07);
SEQAN_ASSERT_IN_DELTA(qualDist[3], 0.00990099, 1.0e-07);
}
SEQAN_DEFINE_TEST(test_param_chooser_parse_read_gapped_params)
{
seqan::ParamChooserOptions pmOptions;
pmOptions.totalN = 4; // Read length.
pmOptions.verbose = false;
pmOptions.chooseOneGappedOnly = false;
pmOptions.chooseUngappedOnly = false;
pmOptions.minThreshold = 3;
pmOptions.optionLossRate = 0.01;
seqan::RazerSOptions<> rOptions;
std::stringstream ss;
ss << "errors shape t lossrate PM\n"
<< "\n"
<< "0 11000000100100101 3 0 40895\n"
<< "1 11000000100100101 2 0 492286\n"
<< "2 11000000100100101 1 0.0293446 48417798\n"
<< "3 11000000100100101 1 0.195237 48417798\n"
<< "0 1111100001 10 0 40484\n"
<< "1 1111100001 7 0.163535 48622\n"
<< "1 1111100001 6 0.0497708 51290\n"
<< "1 1111100001 5 0 61068\n"
<< "1 1111101 4 0 61068";
ss.seekg(0);
SEQAN_ASSERT(parseGappedParams(rOptions, ss, pmOptions));
SEQAN_ASSERT_EQ(rOptions.shape, "1111100001");
SEQAN_ASSERT_EQ(rOptions.threshold, 10);
pmOptions.chooseOneGappedOnly = true;
ss.clear();
ss.seekg(0);
SEQAN_ASSERT(parseGappedParams(rOptions, ss, pmOptions));
SEQAN_ASSERT_EQ(rOptions.shape, "1111100001");
SEQAN_ASSERT_EQ(rOptions.threshold, 10);
pmOptions.chooseUngappedOnly = true;
ss.clear();
ss.seekg(0);
SEQAN_ASSERT_NOT(parseGappedParams(rOptions, ss, pmOptions));
}
SEQAN_BEGIN_TESTSUITE(test_param_chooser)
{
SEQAN_CALL_TEST(test_param_chooser_quality_distribution_from_prb_file);
SEQAN_CALL_TEST(test_param_chooser_quality_distribution_from_fastq_file);
SEQAN_CALL_TEST(test_param_chooser_quality_distribution_from_fastq_int_file);
SEQAN_CALL_TEST(test_param_chooser_parse_read_gapped_params);
}
SEQAN_END_TESTSUITE
<|endoftext|>
|
<commit_before>// $Id$
//**************************************************************************
//* This file is property of and copyright by the ALICE HLT Project *
//* ALICE Experiment at CERN, All rights reserved. *
//* *
//* Primary Authors: Matthias Richter <[email protected]> *
//* *
//* Permission to use, copy, modify and distribute this software and its *
//* documentation strictly for non-commercial purposes is hereby granted *
//* without fee, provided that the above copyright notice appears in all *
//* copies and that both the copyright notice and this permission notice *
//* appear in the supporting documentation. The authors make no claims *
//* about the suitability of this software for any purpose. It is *
//* provided "as is" without express or implied warranty. *
//**************************************************************************
/** @file AliHLTTPCOfflineTrackerComponent.cxx
@author Jacek Otwinowski & Matthias Richter
@date
@brief Wrapper component to the TPC offline tracker
*/
#include "AliHLTTPCOfflineTrackerComponent.h"
#include "TString.h"
#include "TClonesArray.h"
#include "TObjArray.h"
#include "TObjString.h"
#include "AliVParticle.h"
#include "AliCDBManager.h"
#include "AliCDBEntry.h"
#include "AliGeomManager.h"
#include "AliMagFMaps.h"
#include "AliTPCReconstructor.h"
#include "AliTPCParam.h"
#include "AliTPCRecoParam.h"
#include "AliTPCParamSR.h"
#include "AliTPCtrackerMI.h"
#include "AliTPCClustersRow.h"
#include "AliTPCseed.h"
#include "AliESDEvent.h"
#include "AliESDfriend.h"
#include "AliHLTTPCDefinitions.h"
/** ROOT macro for the implementation of ROOT specific class methods */
ClassImp(AliHLTTPCOfflineTrackerComponent)
AliHLTTPCOfflineTrackerComponent::AliHLTTPCOfflineTrackerComponent() : AliHLTProcessor(),
fGeometryFileName(""),
fTPCGeomParam(0),
fTracker(0),
fESD(0),
fESDfriend(0)
{
// Default constructor
fGeometryFileName = getenv("ALICE_ROOT");
fGeometryFileName += "/HLT/TPCLib/offline/geometry.root";
}
AliHLTTPCOfflineTrackerComponent::~AliHLTTPCOfflineTrackerComponent()
{
// see header file for class documentation
}
const char* AliHLTTPCOfflineTrackerComponent::GetComponentID()
{
// see header file for class documentation
return "TPCOfflineTracker";
}
void AliHLTTPCOfflineTrackerComponent::GetInputDataTypes( vector<AliHLTComponentDataType>& list)
{
// get input data type
list.push_back(kAliHLTDataTypeTObjArray|kAliHLTDataOriginTPC/*AliHLTTPCDefinitions::fgkOfflineClustersDataType*/);
}
AliHLTComponentDataType AliHLTTPCOfflineTrackerComponent::GetOutputDataType()
{
// create output data type
return kAliHLTDataTypeESDObject|kAliHLTDataOriginTPC/*AliHLTTPCDefinitions::fgkOfflineTrackSegmentsDataType*/;
}
void AliHLTTPCOfflineTrackerComponent::GetOutputDataSize(unsigned long& constBase, double& inputMultiplier)
{
// get output data size
constBase = 2000000;
inputMultiplier = 1;
}
AliHLTComponent* AliHLTTPCOfflineTrackerComponent::Spawn()
{
// create instance of the component
return new AliHLTTPCOfflineTrackerComponent;
}
int AliHLTTPCOfflineTrackerComponent::DoInit( int argc, const char** argv )
{
// init configuration
//
int iResult=0;
#ifdef HAVE_NOT_TPCOFFLINE_REC
HLTFatal("AliRoot version > v4-13-Release required");
return -ENOSYS;
#endif
TString argument="";
TString configuration="";
int bMissingParam=0;
// loop over input parameters
for (int i=0; i<argc && iResult>=0; i++) {
argument=argv[i];
if (argument.IsNull()) continue;
if (argument.CompareTo("-geometry")==0) {
if ((bMissingParam=(++i>=argc))) break;
HLTInfo("got \'-geometry\' argument: %s", argv[i]);
fGeometryFileName = argv[i];
HLTInfo("Geometry file is: %s", fGeometryFileName.c_str());
// the remaining arguments are treated as configuration
} else {
if (!configuration.IsNull()) configuration+=" ";
configuration+=argument;
}
} // end loop
if (bMissingParam) {
HLTError("missing parameter for argument %s", argument.Data());
iResult=-EINVAL;
}
if (iResult>=0 && !configuration.IsNull()) {
iResult=Configure(configuration.Data());
} else {
iResult=Reconfigure(NULL, NULL);
}
//
// initialisation
//
// Load geometry
HLTInfo("Geometry file %s",fGeometryFileName.c_str());
AliGeomManager::LoadGeometry(fGeometryFileName.c_str());
if((AliGeomManager::GetGeometry()) == 0) {
HLTError("Cannot load geometry from file %s",fGeometryFileName.c_str());
iResult=-EINVAL;
}
// TPC reconstruction parameters
//AliTPCRecoParam * tpcRecoParam = AliTPCRecoParam::GetLowFluxParam();
AliTPCRecoParam * tpcRecoParam = AliTPCRecoParam::GetHLTParam();
if(tpcRecoParam) {
AliTPCReconstructor::SetRecoParam(tpcRecoParam);
}
// TPC geometry parameters
fTPCGeomParam = new AliTPCParamSR;
if (fTPCGeomParam) {
fTPCGeomParam->ReadGeoMatrices();
}
// Init tracker
fTracker = new AliTPCtrackerMI(fTPCGeomParam);
// AliESDEvent event needed by AliTPCtrackerMI
// output of the component
fESD = new AliESDEvent();
if (fESD) {
fESD->CreateStdContent();
// add ESD friend
fESDfriend = new AliESDfriend();
if(fESDfriend) fESD->AddObject(fESDfriend);
}
if (!fTracker || !fESD || !fTPCGeomParam) {
HLTError("failed creating internal objects");
iResult=-ENOMEM;
}
if (iResult>=0) {
// read the default CDB entries
iResult=Reconfigure(NULL, NULL);
}
return iResult;
}
int AliHLTTPCOfflineTrackerComponent::DoDeinit()
{
// deinit configuration
if(fTPCGeomParam) delete fTPCGeomParam; fTPCGeomParam = 0;
if(fTracker) delete fTracker; fTracker = 0;
if(fESD) delete fESD; fESD = 0;
//Note: fESD is owner of fESDfriends
return 0;
}
int AliHLTTPCOfflineTrackerComponent::DoEvent( const AliHLTComponentEventData& /*evtData*/, AliHLTComponentTriggerData& /*trigData*/)
{
// tracker function
HLTInfo("DoEvent processing data");
int iResult=0;
TClonesArray *clusterArray=0;
TObjArray *seedArray=0;
int slice, patch;
const AliHLTComponentBlockData* pBlock=GetFirstInputBlock(kAliHLTDataTypeTObjArray|kAliHLTDataOriginTPC);
if(!pBlock) {
HLTError("Cannot get first data block 0x%08x ",pBlock);
iResult=-ENOMEM; return iResult;
}
int minSlice=AliHLTTPCDefinitions::GetMinSliceNr(pBlock->fSpecification);
int maxSlice=AliHLTTPCDefinitions::GetMaxSliceNr(pBlock->fSpecification);
int minPatch=AliHLTTPCDefinitions::GetMinPatchNr(pBlock->fSpecification);
int maxPatch=AliHLTTPCDefinitions::GetMaxPatchNr(pBlock->fSpecification);
if (fTracker && fESD) {
// loop over input data blocks: TClonesArrays of clusters
for (TObject *pObj = (TObject *)GetFirstInputObject(kAliHLTDataTypeTObjArray|kAliHLTDataOriginTPC/*AliHLTTPCDefinitions::fgkOfflineClustersDataType*/,"TClonesArray",0);
pObj !=0 && iResult>=0;
pObj = (TObject *)GetNextInputObject(0)) {
clusterArray = dynamic_cast<TClonesArray*>(pObj);
if (!clusterArray) continue;
HLTInfo("load %d clusters from block %s 0x%08x", clusterArray->GetEntries(), DataType2Text(GetDataType(pObj)).c_str(), GetSpecification(pObj));
slice=AliHLTTPCDefinitions::GetMinSliceNr(GetSpecification(pObj));
patch=AliHLTTPCDefinitions::GetMinPatchNr(GetSpecification(pObj));
if(slice < minSlice) minSlice=slice;
if(slice > maxSlice) maxSlice=slice;
if(patch < minPatch) minPatch=patch;
if(patch > maxPatch) maxPatch=patch;
#ifndef HAVE_NOT_TPCOFFLINE_REC
fTracker->LoadClusters(clusterArray);
#endif //HAVE_NOT_TPCOFFLINE_REC
clusterArray->Delete();
}// end loop over input objects
#ifndef HAVE_NOT_TPCOFFLINE_REC
// Load outer sectors
fTracker->LoadOuterSectors();
// Load inner sectors
fTracker->LoadInnerSectors();
#endif
// set magnetic field for the ESD, assumes correct initialization of
// the field map
fESD->SetMagneticField(AliTracker::GetBz());
// run tracker
fTracker->Clusters2Tracks(fESD);
// add TPC seed to the AliESDtrack
seedArray = fTracker->GetSeeds();
if(seedArray) {
Int_t nseed = seedArray->GetEntriesFast();
HLTInfo("Number TPC seeds %d",nseed);
for(Int_t i=0; i<nseed; ++i) {
AliTPCseed *seed = (AliTPCseed*)seedArray->UncheckedAt(i);
if(!seed) continue;
//HLTInfo("TPC seed: sec %d, row %d",seed->GetSector(), seed->GetRow());
AliESDtrack *esdtrack=fESD->GetTrack(i);
if(esdtrack) esdtrack->AddCalibObject((TObject*)seed);
else
HLTInfo("Cannot add TPC seed to AliESDtrack %d", i);
}
seedArray->Clear();
}
// reset ESDs friends (no Reset function!)
fESDfriend->~AliESDfriend();
new (fESDfriend) AliESDfriend(); // Reset ...
// add ESDfriend to AliESDEvent
fESD->GetESDfriend(fESDfriend);
// unload clusters
fTracker->UnloadClusters();
Int_t nTracks = fESD->GetNumberOfTracks();
HLTInfo("Number of tracks %d", nTracks);
// calculate specification from the specification of input data blocks
AliHLTUInt32_t iSpecification = AliHLTTPCDefinitions::EncodeDataSpecification( minSlice, maxSlice, minPatch, maxPatch );
HLTInfo("minSlice %d, maxSlice %d, minPatch %d, maxPatch %d", minSlice, maxSlice, minPatch, maxPatch);
// send data
PushBack(fESD, kAliHLTDataTypeESDObject|kAliHLTDataOriginTPC, iSpecification);
// reset ESDs and ESDs friends
fESD->Reset();
} else {
HLTError("component not initialized");
iResult=-ENOMEM;
}
return iResult;
}
int AliHLTTPCOfflineTrackerComponent::Configure(const char* arguments)
{
// see header file for class documentation
int iResult=0;
if (!arguments) return iResult;
TString allArgs=arguments;
TString argument;
int bMissingParam=0;
TObjArray* pTokens=allArgs.Tokenize(" ");
if (pTokens) {
for (int i=0; i<pTokens->GetEntries() && iResult>=0; i++) {
argument=((TObjString*)pTokens->At(i))->GetString();
if (argument.IsNull()) continue;
if (argument.CompareTo("-solenoidBz")==0) {
if ((bMissingParam=(++i>=pTokens->GetEntries()))) break;
// TODO: check if there is common functionality in the AliMagF* classes
float SolenoidBz=((TObjString*)pTokens->At(i))->GetString().Atof();
if (SolenoidBz<kAlmost0Field) SolenoidBz=kAlmost0Field;
float factor=1.;
int map=AliMagFMaps::k2kG;
if (SolenoidBz<3.) {
map=AliMagFMaps::k2kG;
factor=SolenoidBz/2;
} else if (SolenoidBz>=3. && SolenoidBz<4.5) {
map=AliMagFMaps::k4kG;
factor=SolenoidBz/4;
} else {
map=AliMagFMaps::k5kG;
factor=SolenoidBz/5;
}
// the magnetic field map is not supposed to change
// field initialization should be done once in the beginning
// TODO: does the factor need adjustment?
const AliMagF* currentMap=AliTracker::GetFieldMap();
if (!currentMap) {
AliMagFMaps* field = new AliMagFMaps("Maps","Maps", 2, 1., 10., map);
AliTracker::SetFieldMap(field,kTRUE);
HLTInfo("Solenoid Field set to: %f map %d", SolenoidBz, map);
} else if (currentMap->Map()!=map) {
HLTWarning("omitting request to override field map %s with %s", currentMap->Map(), map);
}
continue;
} else {
HLTError("unknown argument %s", argument.Data());
iResult=-EINVAL;
break;
}
}
delete pTokens;
}
if (bMissingParam) {
HLTError("missing parameter for argument %s", argument.Data());
iResult=-EINVAL;
}
return iResult;
}
int AliHLTTPCOfflineTrackerComponent::Reconfigure(const char* cdbEntry, const char* chainId)
{
// see header file for class documentation
int iResult=0;
const char* path=kAliHLTCDBSolenoidBz;
const char* defaultNotify="";
if (cdbEntry) {
path=cdbEntry;
defaultNotify=" (default)";
}
if (path) {
if (chainId) {} // just to get rid of warning, can not comment argument due to debug message
HLTDebug("reconfigure from entry %s%s, chain id %s", path, defaultNotify,(chainId!=NULL && chainId[0]!=0)?chainId:"<none>");
AliCDBEntry *pEntry = AliCDBManager::Instance()->Get(path/*,GetRunNo()*/);
if (pEntry) {
TObjString* pString=dynamic_cast<TObjString*>(pEntry->GetObject());
if (pString) {
HLTDebug("received configuration object string: \'%s\'", pString->GetString().Data());
iResult=Configure(pString->GetString().Data());
} else {
HLTError("configuration object \"%s\" has wrong type, required TObjString", path);
}
} else {
HLTError("can not fetch object \"%s\" from CDB", path);
}
}
return iResult;
}
<commit_msg>using non-uniform field option for tracking (Jacek)<commit_after>// $Id$
//**************************************************************************
//* This file is property of and copyright by the ALICE HLT Project *
//* ALICE Experiment at CERN, All rights reserved. *
//* *
//* Primary Authors: Matthias Richter <[email protected]> *
//* *
//* Permission to use, copy, modify and distribute this software and its *
//* documentation strictly for non-commercial purposes is hereby granted *
//* without fee, provided that the above copyright notice appears in all *
//* copies and that both the copyright notice and this permission notice *
//* appear in the supporting documentation. The authors make no claims *
//* about the suitability of this software for any purpose. It is *
//* provided "as is" without express or implied warranty. *
//**************************************************************************
/** @file AliHLTTPCOfflineTrackerComponent.cxx
@author Jacek Otwinowski & Matthias Richter
@date
@brief Wrapper component to the TPC offline tracker
*/
#include "AliHLTTPCOfflineTrackerComponent.h"
#include "TString.h"
#include "TClonesArray.h"
#include "TObjArray.h"
#include "TObjString.h"
#include "AliVParticle.h"
#include "AliCDBManager.h"
#include "AliCDBEntry.h"
#include "AliGeomManager.h"
#include "AliMagFMaps.h"
#include "AliTPCReconstructor.h"
#include "AliTPCParam.h"
#include "AliTPCRecoParam.h"
#include "AliTPCParamSR.h"
#include "AliTPCtrackerMI.h"
#include "AliTPCClustersRow.h"
#include "AliTPCseed.h"
#include "AliESDEvent.h"
#include "AliESDfriend.h"
#include "AliHLTTPCDefinitions.h"
/** ROOT macro for the implementation of ROOT specific class methods */
ClassImp(AliHLTTPCOfflineTrackerComponent)
AliHLTTPCOfflineTrackerComponent::AliHLTTPCOfflineTrackerComponent() : AliHLTProcessor(),
fGeometryFileName(""),
fTPCGeomParam(0),
fTracker(0),
fESD(0),
fESDfriend(0)
{
// Default constructor
fGeometryFileName = getenv("ALICE_ROOT");
fGeometryFileName += "/HLT/TPCLib/offline/geometry.root";
}
AliHLTTPCOfflineTrackerComponent::~AliHLTTPCOfflineTrackerComponent()
{
// see header file for class documentation
}
const char* AliHLTTPCOfflineTrackerComponent::GetComponentID()
{
// see header file for class documentation
return "TPCOfflineTracker";
}
void AliHLTTPCOfflineTrackerComponent::GetInputDataTypes( vector<AliHLTComponentDataType>& list)
{
// get input data type
list.push_back(kAliHLTDataTypeTObjArray|kAliHLTDataOriginTPC/*AliHLTTPCDefinitions::fgkOfflineClustersDataType*/);
}
AliHLTComponentDataType AliHLTTPCOfflineTrackerComponent::GetOutputDataType()
{
// create output data type
return kAliHLTDataTypeESDObject|kAliHLTDataOriginTPC/*AliHLTTPCDefinitions::fgkOfflineTrackSegmentsDataType*/;
}
void AliHLTTPCOfflineTrackerComponent::GetOutputDataSize(unsigned long& constBase, double& inputMultiplier)
{
// get output data size
constBase = 2000000;
inputMultiplier = 1;
}
AliHLTComponent* AliHLTTPCOfflineTrackerComponent::Spawn()
{
// create instance of the component
return new AliHLTTPCOfflineTrackerComponent;
}
int AliHLTTPCOfflineTrackerComponent::DoInit( int argc, const char** argv )
{
// init configuration
//
int iResult=0;
#ifdef HAVE_NOT_TPCOFFLINE_REC
HLTFatal("AliRoot version > v4-13-Release required");
return -ENOSYS;
#endif
TString argument="";
TString configuration="";
int bMissingParam=0;
// loop over input parameters
for (int i=0; i<argc && iResult>=0; i++) {
argument=argv[i];
if (argument.IsNull()) continue;
if (argument.CompareTo("-geometry")==0) {
if ((bMissingParam=(++i>=argc))) break;
HLTInfo("got \'-geometry\' argument: %s", argv[i]);
fGeometryFileName = argv[i];
HLTInfo("Geometry file is: %s", fGeometryFileName.c_str());
// the remaining arguments are treated as configuration
} else {
if (!configuration.IsNull()) configuration+=" ";
configuration+=argument;
}
} // end loop
if (bMissingParam) {
HLTError("missing parameter for argument %s", argument.Data());
iResult=-EINVAL;
}
if (iResult>=0 && !configuration.IsNull()) {
iResult=Configure(configuration.Data());
} else {
iResult=Reconfigure(NULL, NULL);
}
//
// initialisation
//
// Load geometry
HLTInfo("Geometry file %s",fGeometryFileName.c_str());
AliGeomManager::LoadGeometry(fGeometryFileName.c_str());
if((AliGeomManager::GetGeometry()) == 0) {
HLTError("Cannot load geometry from file %s",fGeometryFileName.c_str());
iResult=-EINVAL;
}
// TPC reconstruction parameters
//AliTPCRecoParam * tpcRecoParam = AliTPCRecoParam::GetLowFluxParam();
AliTPCRecoParam * tpcRecoParam = AliTPCRecoParam::GetHLTParam();
if(tpcRecoParam) {
AliTPCReconstructor::SetRecoParam(tpcRecoParam);
}
// TPC geometry parameters
fTPCGeomParam = new AliTPCParamSR;
if (fTPCGeomParam) {
fTPCGeomParam->ReadGeoMatrices();
}
// Init tracker
fTracker = new AliTPCtrackerMI(fTPCGeomParam);
// AliESDEvent event needed by AliTPCtrackerMI
// output of the component
fESD = new AliESDEvent();
if (fESD) {
fESD->CreateStdContent();
// add ESD friend
fESDfriend = new AliESDfriend();
if(fESDfriend) fESD->AddObject(fESDfriend);
}
if (!fTracker || !fESD || !fTPCGeomParam) {
HLTError("failed creating internal objects");
iResult=-ENOMEM;
}
if (iResult>=0) {
// read the default CDB entries
iResult=Reconfigure(NULL, NULL);
}
return iResult;
}
int AliHLTTPCOfflineTrackerComponent::DoDeinit()
{
// deinit configuration
if(fTPCGeomParam) delete fTPCGeomParam; fTPCGeomParam = 0;
if(fTracker) delete fTracker; fTracker = 0;
if(fESD) delete fESD; fESD = 0;
//Note: fESD is owner of fESDfriends
return 0;
}
int AliHLTTPCOfflineTrackerComponent::DoEvent( const AliHLTComponentEventData& /*evtData*/, AliHLTComponentTriggerData& /*trigData*/)
{
// tracker function
HLTInfo("DoEvent processing data");
int iResult=0;
TClonesArray *clusterArray=0;
TObjArray *seedArray=0;
int slice, patch;
const AliHLTComponentBlockData* pBlock=GetFirstInputBlock(kAliHLTDataTypeTObjArray|kAliHLTDataOriginTPC);
if(!pBlock) {
HLTError("Cannot get first data block 0x%08x ",pBlock);
iResult=-ENOMEM; return iResult;
}
int minSlice=AliHLTTPCDefinitions::GetMinSliceNr(pBlock->fSpecification);
int maxSlice=AliHLTTPCDefinitions::GetMaxSliceNr(pBlock->fSpecification);
int minPatch=AliHLTTPCDefinitions::GetMinPatchNr(pBlock->fSpecification);
int maxPatch=AliHLTTPCDefinitions::GetMaxPatchNr(pBlock->fSpecification);
if (fTracker && fESD) {
// loop over input data blocks: TClonesArrays of clusters
for (TObject *pObj = (TObject *)GetFirstInputObject(kAliHLTDataTypeTObjArray|kAliHLTDataOriginTPC/*AliHLTTPCDefinitions::fgkOfflineClustersDataType*/,"TClonesArray",0);
pObj !=0 && iResult>=0;
pObj = (TObject *)GetNextInputObject(0)) {
clusterArray = dynamic_cast<TClonesArray*>(pObj);
if (!clusterArray) continue;
HLTInfo("load %d clusters from block %s 0x%08x", clusterArray->GetEntries(), DataType2Text(GetDataType(pObj)).c_str(), GetSpecification(pObj));
slice=AliHLTTPCDefinitions::GetMinSliceNr(GetSpecification(pObj));
patch=AliHLTTPCDefinitions::GetMinPatchNr(GetSpecification(pObj));
if(slice < minSlice) minSlice=slice;
if(slice > maxSlice) maxSlice=slice;
if(patch < minPatch) minPatch=patch;
if(patch > maxPatch) maxPatch=patch;
#ifndef HAVE_NOT_TPCOFFLINE_REC
fTracker->LoadClusters(clusterArray);
#endif //HAVE_NOT_TPCOFFLINE_REC
clusterArray->Delete();
}// end loop over input objects
#ifndef HAVE_NOT_TPCOFFLINE_REC
// Load outer sectors
fTracker->LoadOuterSectors();
// Load inner sectors
fTracker->LoadInnerSectors();
#endif
// set magnetic field for the ESD, assumes correct initialization of
// the field map
fESD->SetMagneticField(AliTracker::GetBz());
// run tracker
fTracker->Clusters2Tracks(fESD);
// add TPC seed to the AliESDtrack
seedArray = fTracker->GetSeeds();
if(seedArray) {
Int_t nseed = seedArray->GetEntriesFast();
HLTInfo("Number TPC seeds %d",nseed);
for(Int_t i=0; i<nseed; ++i) {
AliTPCseed *seed = (AliTPCseed*)seedArray->UncheckedAt(i);
if(!seed) continue;
//HLTInfo("TPC seed: sec %d, row %d",seed->GetSector(), seed->GetRow());
AliESDtrack *esdtrack=fESD->GetTrack(i);
if(esdtrack) esdtrack->AddCalibObject((TObject*)seed);
else
HLTInfo("Cannot add TPC seed to AliESDtrack %d", i);
}
seedArray->Clear();
}
// reset ESDs friends (no Reset function!)
fESDfriend->~AliESDfriend();
new (fESDfriend) AliESDfriend(); // Reset ...
// add ESDfriend to AliESDEvent
fESD->GetESDfriend(fESDfriend);
// unload clusters
fTracker->UnloadClusters();
Int_t nTracks = fESD->GetNumberOfTracks();
HLTInfo("Number of tracks %d", nTracks);
// calculate specification from the specification of input data blocks
AliHLTUInt32_t iSpecification = AliHLTTPCDefinitions::EncodeDataSpecification( minSlice, maxSlice, minPatch, maxPatch );
HLTInfo("minSlice %d, maxSlice %d, minPatch %d, maxPatch %d", minSlice, maxSlice, minPatch, maxPatch);
// send data
PushBack(fESD, kAliHLTDataTypeESDObject|kAliHLTDataOriginTPC, iSpecification);
// reset ESDs and ESDs friends
fESD->Reset();
} else {
HLTError("component not initialized");
iResult=-ENOMEM;
}
return iResult;
}
int AliHLTTPCOfflineTrackerComponent::Configure(const char* arguments)
{
// see header file for class documentation
int iResult=0;
if (!arguments) return iResult;
TString allArgs=arguments;
TString argument;
int bMissingParam=0;
TObjArray* pTokens=allArgs.Tokenize(" ");
if (pTokens) {
for (int i=0; i<pTokens->GetEntries() && iResult>=0; i++) {
argument=((TObjString*)pTokens->At(i))->GetString();
if (argument.IsNull()) continue;
if (argument.CompareTo("-solenoidBz")==0) {
if ((bMissingParam=(++i>=pTokens->GetEntries()))) break;
// TODO: check if there is common functionality in the AliMagF* classes
float SolenoidBz=((TObjString*)pTokens->At(i))->GetString().Atof();
if (SolenoidBz<kAlmost0Field) SolenoidBz=kAlmost0Field;
float factor=1.;
int map=AliMagFMaps::k2kG;
if (SolenoidBz<3.) {
map=AliMagFMaps::k2kG;
factor=SolenoidBz/2;
} else if (SolenoidBz>=3. && SolenoidBz<4.5) {
map=AliMagFMaps::k4kG;
factor=SolenoidBz/4;
} else {
map=AliMagFMaps::k5kG;
factor=SolenoidBz/5;
}
// the magnetic field map is not supposed to change
// field initialization should be done once in the beginning
// TODO: does the factor need adjustment?
const AliMagF* currentMap=AliTracker::GetFieldMap();
if (!currentMap) {
AliMagFMaps* field = new AliMagFMaps("Maps","Maps", 2, 1., 10., map);
AliTracker::SetFieldMap(field,kFALSE);
HLTInfo("Solenoid Field set to: %f map %d", SolenoidBz, map);
} else if (currentMap->Map()!=map) {
HLTWarning("omitting request to override field map %s with %s", currentMap->Map(), map);
}
continue;
} else {
HLTError("unknown argument %s", argument.Data());
iResult=-EINVAL;
break;
}
}
delete pTokens;
}
if (bMissingParam) {
HLTError("missing parameter for argument %s", argument.Data());
iResult=-EINVAL;
}
return iResult;
}
int AliHLTTPCOfflineTrackerComponent::Reconfigure(const char* cdbEntry, const char* chainId)
{
// see header file for class documentation
int iResult=0;
const char* path=kAliHLTCDBSolenoidBz;
const char* defaultNotify="";
if (cdbEntry) {
path=cdbEntry;
defaultNotify=" (default)";
}
if (path) {
if (chainId) {} // just to get rid of warning, can not comment argument due to debug message
HLTDebug("reconfigure from entry %s%s, chain id %s", path, defaultNotify,(chainId!=NULL && chainId[0]!=0)?chainId:"<none>");
AliCDBEntry *pEntry = AliCDBManager::Instance()->Get(path/*,GetRunNo()*/);
if (pEntry) {
TObjString* pString=dynamic_cast<TObjString*>(pEntry->GetObject());
if (pString) {
HLTDebug("received configuration object string: \'%s\'", pString->GetString().Data());
iResult=Configure(pString->GetString().Data());
} else {
HLTError("configuration object \"%s\" has wrong type, required TObjString", path);
}
} else {
HLTError("can not fetch object \"%s\" from CDB", path);
}
}
return iResult;
}
<|endoftext|>
|
<commit_before>/*
Copyright (C) 2014-2017 Alexandr Akulich <[email protected]>
This file is a part of TelegramQt library.
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.
*/
#include "Utils.hpp"
#include <openssl/aes.h>
#include <openssl/bn.h>
#include <openssl/pem.h>
#include <openssl/rsa.h>
#include <openssl/opensslv.h>
#include <zlib.h>
#include <QBuffer>
#include <QCryptographicHash>
#include <QDebug>
#include <QFileInfo>
#include "CRawStream.hpp"
#include "RandomGenerator.hpp"
struct SslBigNumberContext {
SslBigNumberContext() :
m_context(BN_CTX_new())
{
}
~SslBigNumberContext()
{
BN_CTX_free(m_context);
}
BN_CTX *context() { return m_context; }
private:
BN_CTX *m_context;
};
struct SslBigNumber {
SslBigNumber() :
m_number(BN_new())
{
}
SslBigNumber(SslBigNumber &&number) :
m_number(number.m_number)
{
number.m_number = nullptr;
}
SslBigNumber(const SslBigNumber &number) :
m_number(BN_new())
{
BN_copy(m_number, number.m_number);
}
~SslBigNumber()
{
if (m_number) {
BN_free(m_number);
}
}
static SslBigNumber fromHex(const QByteArray &hex)
{
SslBigNumber result;
if (BN_hex2bn(&result.m_number, hex.constData()) != 0) {
return result;
}
return SslBigNumber();
}
static SslBigNumber fromByteArray(const QByteArray &bin)
{
SslBigNumber result;
if (BN_bin2bn((uchar *) bin.constData(), bin.length(), result.m_number) != 0) {
return result;
}
return SslBigNumber();
}
static QByteArray toByteArray(const BIGNUM *number)
{
QByteArray result;
result.resize(BN_num_bytes(number));
BN_bn2bin(number, (uchar *) result.data());
return result;
}
QByteArray toByteArray() const
{
return toByteArray(m_number);
}
SslBigNumber mod_exp(const SslBigNumber &exponent, const SslBigNumber &modulus) const
{
SslBigNumberContext context;
SslBigNumber result;
BN_mod_exp(result.m_number, number(), exponent.number(), modulus.number(), context.context());
return result;
}
const BIGNUM *number() const { return m_number; }
BIGNUM *number() { return m_number; }
private:
BIGNUM *m_number;
};
static const QByteArray s_hardcodedRsaDataKey("0c150023e2f70db7985ded064759cfecf0af328e69a41daf4d6f01b53813"
"5a6f91f8f8b2a0ec9ba9720ce352efcf6c5680ffc424bd634864902de0b4"
"bd6d49f4e580230e3ae97d95c8b19442b3c0a10d8f5633fecedd6926a7f6"
"dab0ddb7d457f9ea81b8465fcd6fffeed114011df91c059caedaf97625f6"
"c96ecc74725556934ef781d866b34f011fce4d835a090196e9a5f0e4449a"
"f7eb697ddb9076494ca5f81104a305b6dd27665722c46b60e5df680fb16b"
"210607ef217652e60236c255f6a28315f4083a96791d7214bf64c1df4fd0"
"db1944fb26a2a57031b32eee64ad15a8ba68885cde74a5bfc920f6abf59b"
"a5c75506373e7130f9042da922179251f");
static const QByteArray s_hardcodedRsaDataExp("010001");
static const quint64 s_hardcodedRsaDataFingersprint(0xc3b42b026ce86b21);
namespace Telegram {
int Utils::randomBytes(void *buffer, int count)
{
return RandomGenerator::instance()->generate(buffer, count);
}
// Slightly modified version of Euclidean algorithm. Once we are looking for prime numbers, we can drop parity of asked numbers.
quint64 Utils::greatestCommonOddDivisor(quint64 a, quint64 b)
{
while (a != 0 && b != 0) {
while (!(b & 1)) {
b >>= 1;
}
while (!(a & 1)) {
a >>= 1;
}
if (a > b) {
a -= b;
} else {
b -= a;
}
}
return b == 0 ? a : b;
}
// Yet another copy of some unknown pq-solver algorithm.
// Links:
// https://github.com/DrKLO/Telegram/blob/433f59c5b9ed17543d8e206c83f0bc7c7edb43a6/TMessagesProj/jni/jni.c#L86
// https://github.com/ex3ndr/telegram-mt/blob/91b1186e567b0484d6f371b8e5c61c425daf867e/src/main/java/org/telegram/mtproto/secure/pq/PQLopatin.java#L35
// https://github.com/vysheng/tg/blob/1dad2e89933085ea1e3d9fb1becb1907ce5de55f/mtproto-client.c#L296
quint64 Utils::findDivider(quint64 number)
{
int it = 0;
quint64 g = 0;
for (int i = 0; i < 3 || it < 10000; i++) {
const quint64 q = ((rand() & 15) + 17) % number;
quint64 x = (quint64) rand() % (number - 1) + 1;
quint64 y = x;
const quint32 lim = 1 << (i + 18);
for (quint32 j = 1; j < lim; j++) {
++it;
quint64 a = x;
quint64 b = x;
quint64 c = q;
while (b) {
if (b & 1) {
c += a;
if (c >= number) {
c -= number;
}
}
a += a;
if (a >= number) {
a -= number;
}
b >>= 1;
}
x = c;
const quint64 z = x < y ? number + x - y : x - y;
g = greatestCommonOddDivisor(z, number);
if (g != 1) {
return g;
}
if (!(j & (j - 1))) {
y = x;
}
}
if (g > 1 && g < number) {
return g;
}
}
return 1;
}
QByteArray Utils::sha1(const QByteArray &data)
{
return QCryptographicHash::hash(data, QCryptographicHash::Sha1);
}
QByteArray Utils::sha256(const QByteArray &data)
{
return QCryptographicHash::hash(data, QCryptographicHash::Sha256);
}
bool hexArrayToBN(const QByteArray &hex, BIGNUM **n)
{
return BN_hex2bn(n, hex.constData()) != 0;
}
bool binArrayToBN(const QByteArray &bin, BIGNUM **n)
{
return BN_bin2bn((uchar *) bin.constData(), bin.length(), *n) != 0;
}
quint64 Utils::getFingerprints(const QByteArray &data, bool lowerOrderBits)
{
QByteArray shaSum = sha1(data);
if (lowerOrderBits) {
return *((quint64 *) shaSum.mid(12).constData());
} else {
return *((quint64 *) shaSum.constData());
}
}
quint64 Utils::getRsaFingerprints(const Telegram::RsaKey &key)
{
if (key.modulus.isEmpty() || key.exponent.isEmpty()) {
return 0;
}
QBuffer buffer;
buffer.open(QIODevice::WriteOnly);
CRawStreamEx stream(&buffer);
stream << key.modulus;
stream << key.exponent;
return getFingerprints(buffer.data());
}
Telegram::RsaKey Utils::loadHardcodedKey()
{
Telegram::RsaKey result;
result.modulus = SslBigNumber::fromHex(s_hardcodedRsaDataKey).toByteArray();
result.exponent = SslBigNumber::fromHex(s_hardcodedRsaDataExp).toByteArray();
result.fingerprint = s_hardcodedRsaDataFingersprint;
return result;
}
Telegram::RsaKey Utils::loadRsaKeyFromFile(const QString &fileName)
{
Telegram::RsaKey result;
FILE *file = fopen(fileName.toLocal8Bit().constData(), "r");
if (!file) {
qWarning() << "Can not open RSA key file.";
return result;
}
// Try SubjectPublicKeyInfo structure (BEGIN PUBLIC KEY)
RSA *key = PEM_read_RSA_PUBKEY(file, 0, 0, 0);
if (!key) {
// Try PKCS#1 RSAPublicKey structure (BEGIN RSA PUBLIC KEY)
key = PEM_read_RSAPublicKey(file, 0, 0, 0);
}
fclose(file);
if (!key) {
qWarning() << "Can not read RSA key.";
return result;
}
const BIGNUM *n, *e;
#if OPENSSL_VERSION_NUMBER < 0x10100000L
n=key->n;
e=key->e;
#else
RSA_get0_key(key, &n, &e, nullptr);
#endif
result.modulus = SslBigNumber::toByteArray(n);
result.exponent = SslBigNumber::toByteArray(e);
result.fingerprint = getRsaFingerprints(result);
RSA_free(key);
return result;
}
Telegram::RsaKey Utils::loadRsaPrivateKeyFromFile(const QString &fileName)
{
Telegram::RsaKey result;
if (!QFileInfo::exists(fileName)) {
qWarning() << "The RSA key file" << fileName << "does not exist";
return result;
}
FILE *file = fopen(fileName.toLocal8Bit().constData(), "r");
if (!file) {
qWarning() << "Can not open RSA key file.";
return result;
}
RSA *key = PEM_read_RSAPrivateKey(file, NULL, NULL, NULL);
fclose(file);
if (!key) {
qWarning() << "Can not read RSA key.";
return result;
}
const BIGNUM *n, *e, *d;
#if OPENSSL_VERSION_NUMBER < 0x10100000L
n=key->n;
e=key->e;
d=key->d;
#else
RSA_get0_key(key, &n, &e, &d);
#endif
result.modulus = SslBigNumber::toByteArray(n);
result.exponent = SslBigNumber::toByteArray(e);
result.secretExponent = SslBigNumber::toByteArray(d);
result.fingerprint = getRsaFingerprints(result);
RSA_free(key);
return result;
}
Telegram::RsaKey Utils::loadRsaKey()
{
return loadHardcodedKey();
}
QByteArray Utils::binaryNumberModExp(const QByteArray &data, const QByteArray &mod, const QByteArray &exp)
{
const SslBigNumber dataNum = SslBigNumber::fromByteArray(data);
const SslBigNumber pubModulus = SslBigNumber::fromByteArray(mod);
const SslBigNumber pubExponent = SslBigNumber::fromByteArray(exp);
const SslBigNumber resultNum = dataNum.mod_exp(pubExponent, pubModulus);
return resultNum.toByteArray();
}
QByteArray Utils::aesDecrypt(const QByteArray &data, const SAesKey &key)
{
if (data.length() % AES_BLOCK_SIZE) {
qCritical() << Q_FUNC_INFO << "Data is not padded (the size %" << AES_BLOCK_SIZE << " is not zero)";
return QByteArray();
}
QByteArray result = data;
QByteArray initVector = key.iv;
AES_KEY dec_key;
AES_set_decrypt_key((const uchar *) key.key.constData(), key.key.length() * 8, &dec_key);
AES_ige_encrypt((const uchar *) data.constData(), (uchar *) result.data(), data.length(), &dec_key, (uchar *) initVector.data(), AES_DECRYPT);
return result;
}
QByteArray Utils::aesEncrypt(const QByteArray &data, const SAesKey &key)
{
if (data.length() % AES_BLOCK_SIZE) {
qCritical() << Q_FUNC_INFO << "Data is not padded (the size %" << AES_BLOCK_SIZE << " is not zero)";
return QByteArray();
}
QByteArray result = data;
QByteArray initVector = key.iv;
AES_KEY enc_key;
AES_set_encrypt_key((const uchar *) key.key.constData(), key.key.length() * 8, &enc_key);
AES_ige_encrypt((const uchar *) data.constData(), (uchar *) result.data(), data.length(), &enc_key, (uchar *) initVector.data(), AES_ENCRYPT);
return result;
}
QByteArray Utils::unpackGZip(const QByteArray &data)
{
if (data.size() <= 4) {
qDebug() << Q_FUNC_INFO << "Input data is too small to be gzip package";
return QByteArray();
}
QByteArray result;
int inflateResult;
z_stream stream;
static const int CHUNK_SIZE = 1024;
char out[CHUNK_SIZE];
/* allocate inflate state */
stream.zalloc = Z_NULL;
stream.zfree = Z_NULL;
stream.opaque = Z_NULL;
stream.avail_in = data.size();
stream.next_in = (Bytef*)(data.data());
inflateResult = inflateInit2(&stream, 15 + 32); // gzip decoding
if (inflateResult != Z_OK) {
return QByteArray();
}
do {
stream.avail_out = CHUNK_SIZE;
stream.next_out = (Bytef*)(out);
inflateResult = inflate(&stream, Z_NO_FLUSH);
switch (inflateResult) {
case Z_NEED_DICT:
case Z_DATA_ERROR:
case Z_MEM_ERROR:
case Z_STREAM_ERROR:
inflateEnd(&stream);
return QByteArray();
default:
break;
}
result.append(out, CHUNK_SIZE - stream.avail_out);
} while (stream.avail_out == 0);
inflateEnd(&stream);
return result;
}
} // Telegram
<commit_msg>Utils: Reformat debug message<commit_after>/*
Copyright (C) 2014-2017 Alexandr Akulich <[email protected]>
This file is a part of TelegramQt library.
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.
*/
#include "Utils.hpp"
#include <openssl/aes.h>
#include <openssl/bn.h>
#include <openssl/pem.h>
#include <openssl/rsa.h>
#include <openssl/opensslv.h>
#include <zlib.h>
#include <QBuffer>
#include <QCryptographicHash>
#include <QDebug>
#include <QFileInfo>
#include "CRawStream.hpp"
#include "RandomGenerator.hpp"
struct SslBigNumberContext {
SslBigNumberContext() :
m_context(BN_CTX_new())
{
}
~SslBigNumberContext()
{
BN_CTX_free(m_context);
}
BN_CTX *context() { return m_context; }
private:
BN_CTX *m_context;
};
struct SslBigNumber {
SslBigNumber() :
m_number(BN_new())
{
}
SslBigNumber(SslBigNumber &&number) :
m_number(number.m_number)
{
number.m_number = nullptr;
}
SslBigNumber(const SslBigNumber &number) :
m_number(BN_new())
{
BN_copy(m_number, number.m_number);
}
~SslBigNumber()
{
if (m_number) {
BN_free(m_number);
}
}
static SslBigNumber fromHex(const QByteArray &hex)
{
SslBigNumber result;
if (BN_hex2bn(&result.m_number, hex.constData()) != 0) {
return result;
}
return SslBigNumber();
}
static SslBigNumber fromByteArray(const QByteArray &bin)
{
SslBigNumber result;
if (BN_bin2bn((uchar *) bin.constData(), bin.length(), result.m_number) != 0) {
return result;
}
return SslBigNumber();
}
static QByteArray toByteArray(const BIGNUM *number)
{
QByteArray result;
result.resize(BN_num_bytes(number));
BN_bn2bin(number, (uchar *) result.data());
return result;
}
QByteArray toByteArray() const
{
return toByteArray(m_number);
}
SslBigNumber mod_exp(const SslBigNumber &exponent, const SslBigNumber &modulus) const
{
SslBigNumberContext context;
SslBigNumber result;
BN_mod_exp(result.m_number, number(), exponent.number(), modulus.number(), context.context());
return result;
}
const BIGNUM *number() const { return m_number; }
BIGNUM *number() { return m_number; }
private:
BIGNUM *m_number;
};
static const QByteArray s_hardcodedRsaDataKey("0c150023e2f70db7985ded064759cfecf0af328e69a41daf4d6f01b53813"
"5a6f91f8f8b2a0ec9ba9720ce352efcf6c5680ffc424bd634864902de0b4"
"bd6d49f4e580230e3ae97d95c8b19442b3c0a10d8f5633fecedd6926a7f6"
"dab0ddb7d457f9ea81b8465fcd6fffeed114011df91c059caedaf97625f6"
"c96ecc74725556934ef781d866b34f011fce4d835a090196e9a5f0e4449a"
"f7eb697ddb9076494ca5f81104a305b6dd27665722c46b60e5df680fb16b"
"210607ef217652e60236c255f6a28315f4083a96791d7214bf64c1df4fd0"
"db1944fb26a2a57031b32eee64ad15a8ba68885cde74a5bfc920f6abf59b"
"a5c75506373e7130f9042da922179251f");
static const QByteArray s_hardcodedRsaDataExp("010001");
static const quint64 s_hardcodedRsaDataFingersprint(0xc3b42b026ce86b21);
namespace Telegram {
int Utils::randomBytes(void *buffer, int count)
{
return RandomGenerator::instance()->generate(buffer, count);
}
// Slightly modified version of Euclidean algorithm. Once we are looking for prime numbers, we can drop parity of asked numbers.
quint64 Utils::greatestCommonOddDivisor(quint64 a, quint64 b)
{
while (a != 0 && b != 0) {
while (!(b & 1)) {
b >>= 1;
}
while (!(a & 1)) {
a >>= 1;
}
if (a > b) {
a -= b;
} else {
b -= a;
}
}
return b == 0 ? a : b;
}
// Yet another copy of some unknown pq-solver algorithm.
// Links:
// https://github.com/DrKLO/Telegram/blob/433f59c5b9ed17543d8e206c83f0bc7c7edb43a6/TMessagesProj/jni/jni.c#L86
// https://github.com/ex3ndr/telegram-mt/blob/91b1186e567b0484d6f371b8e5c61c425daf867e/src/main/java/org/telegram/mtproto/secure/pq/PQLopatin.java#L35
// https://github.com/vysheng/tg/blob/1dad2e89933085ea1e3d9fb1becb1907ce5de55f/mtproto-client.c#L296
quint64 Utils::findDivider(quint64 number)
{
int it = 0;
quint64 g = 0;
for (int i = 0; i < 3 || it < 10000; i++) {
const quint64 q = ((rand() & 15) + 17) % number;
quint64 x = (quint64) rand() % (number - 1) + 1;
quint64 y = x;
const quint32 lim = 1 << (i + 18);
for (quint32 j = 1; j < lim; j++) {
++it;
quint64 a = x;
quint64 b = x;
quint64 c = q;
while (b) {
if (b & 1) {
c += a;
if (c >= number) {
c -= number;
}
}
a += a;
if (a >= number) {
a -= number;
}
b >>= 1;
}
x = c;
const quint64 z = x < y ? number + x - y : x - y;
g = greatestCommonOddDivisor(z, number);
if (g != 1) {
return g;
}
if (!(j & (j - 1))) {
y = x;
}
}
if (g > 1 && g < number) {
return g;
}
}
return 1;
}
QByteArray Utils::sha1(const QByteArray &data)
{
return QCryptographicHash::hash(data, QCryptographicHash::Sha1);
}
QByteArray Utils::sha256(const QByteArray &data)
{
return QCryptographicHash::hash(data, QCryptographicHash::Sha256);
}
bool hexArrayToBN(const QByteArray &hex, BIGNUM **n)
{
return BN_hex2bn(n, hex.constData()) != 0;
}
bool binArrayToBN(const QByteArray &bin, BIGNUM **n)
{
return BN_bin2bn((uchar *) bin.constData(), bin.length(), *n) != 0;
}
quint64 Utils::getFingerprints(const QByteArray &data, bool lowerOrderBits)
{
QByteArray shaSum = sha1(data);
if (lowerOrderBits) {
return *((quint64 *) shaSum.mid(12).constData());
} else {
return *((quint64 *) shaSum.constData());
}
}
quint64 Utils::getRsaFingerprints(const Telegram::RsaKey &key)
{
if (key.modulus.isEmpty() || key.exponent.isEmpty()) {
return 0;
}
QBuffer buffer;
buffer.open(QIODevice::WriteOnly);
CRawStreamEx stream(&buffer);
stream << key.modulus;
stream << key.exponent;
return getFingerprints(buffer.data());
}
Telegram::RsaKey Utils::loadHardcodedKey()
{
Telegram::RsaKey result;
result.modulus = SslBigNumber::fromHex(s_hardcodedRsaDataKey).toByteArray();
result.exponent = SslBigNumber::fromHex(s_hardcodedRsaDataExp).toByteArray();
result.fingerprint = s_hardcodedRsaDataFingersprint;
return result;
}
Telegram::RsaKey Utils::loadRsaKeyFromFile(const QString &fileName)
{
Telegram::RsaKey result;
FILE *file = fopen(fileName.toLocal8Bit().constData(), "r");
if (!file) {
qWarning() << "Can not open RSA key file.";
return result;
}
// Try SubjectPublicKeyInfo structure (BEGIN PUBLIC KEY)
RSA *key = PEM_read_RSA_PUBKEY(file, 0, 0, 0);
if (!key) {
// Try PKCS#1 RSAPublicKey structure (BEGIN RSA PUBLIC KEY)
key = PEM_read_RSAPublicKey(file, 0, 0, 0);
}
fclose(file);
if (!key) {
qWarning() << "Can not read RSA key.";
return result;
}
const BIGNUM *n, *e;
#if OPENSSL_VERSION_NUMBER < 0x10100000L
n=key->n;
e=key->e;
#else
RSA_get0_key(key, &n, &e, nullptr);
#endif
result.modulus = SslBigNumber::toByteArray(n);
result.exponent = SslBigNumber::toByteArray(e);
result.fingerprint = getRsaFingerprints(result);
RSA_free(key);
return result;
}
Telegram::RsaKey Utils::loadRsaPrivateKeyFromFile(const QString &fileName)
{
Telegram::RsaKey result;
if (!QFileInfo::exists(fileName)) {
qWarning() << "The RSA key file" << fileName << "does not exist";
return result;
}
FILE *file = fopen(fileName.toLocal8Bit().constData(), "r");
if (!file) {
qWarning() << "Can not open RSA key file.";
return result;
}
RSA *key = PEM_read_RSAPrivateKey(file, NULL, NULL, NULL);
fclose(file);
if (!key) {
qWarning() << "Can not read RSA key.";
return result;
}
const BIGNUM *n, *e, *d;
#if OPENSSL_VERSION_NUMBER < 0x10100000L
n=key->n;
e=key->e;
d=key->d;
#else
RSA_get0_key(key, &n, &e, &d);
#endif
result.modulus = SslBigNumber::toByteArray(n);
result.exponent = SslBigNumber::toByteArray(e);
result.secretExponent = SslBigNumber::toByteArray(d);
result.fingerprint = getRsaFingerprints(result);
RSA_free(key);
return result;
}
Telegram::RsaKey Utils::loadRsaKey()
{
return loadHardcodedKey();
}
QByteArray Utils::binaryNumberModExp(const QByteArray &data, const QByteArray &mod, const QByteArray &exp)
{
const SslBigNumber dataNum = SslBigNumber::fromByteArray(data);
const SslBigNumber pubModulus = SslBigNumber::fromByteArray(mod);
const SslBigNumber pubExponent = SslBigNumber::fromByteArray(exp);
const SslBigNumber resultNum = dataNum.mod_exp(pubExponent, pubModulus);
return resultNum.toByteArray();
}
QByteArray Utils::aesDecrypt(const QByteArray &data, const SAesKey &key)
{
if (data.length() % AES_BLOCK_SIZE) {
qCritical() << Q_FUNC_INFO << "Data is not padded (size %" << AES_BLOCK_SIZE << "!= 0)";
return QByteArray();
}
QByteArray result = data;
QByteArray initVector = key.iv;
AES_KEY dec_key;
AES_set_decrypt_key((const uchar *) key.key.constData(), key.key.length() * 8, &dec_key);
AES_ige_encrypt((const uchar *) data.constData(), (uchar *) result.data(), data.length(), &dec_key, (uchar *) initVector.data(), AES_DECRYPT);
return result;
}
QByteArray Utils::aesEncrypt(const QByteArray &data, const SAesKey &key)
{
if (data.length() % AES_BLOCK_SIZE) {
qCritical() << Q_FUNC_INFO << "Data is not padded (the size %" << AES_BLOCK_SIZE << " is not zero)";
return QByteArray();
}
QByteArray result = data;
QByteArray initVector = key.iv;
AES_KEY enc_key;
AES_set_encrypt_key((const uchar *) key.key.constData(), key.key.length() * 8, &enc_key);
AES_ige_encrypt((const uchar *) data.constData(), (uchar *) result.data(), data.length(), &enc_key, (uchar *) initVector.data(), AES_ENCRYPT);
return result;
}
QByteArray Utils::unpackGZip(const QByteArray &data)
{
if (data.size() <= 4) {
qDebug() << Q_FUNC_INFO << "Input data is too small to be gzip package";
return QByteArray();
}
QByteArray result;
int inflateResult;
z_stream stream;
static const int CHUNK_SIZE = 1024;
char out[CHUNK_SIZE];
/* allocate inflate state */
stream.zalloc = Z_NULL;
stream.zfree = Z_NULL;
stream.opaque = Z_NULL;
stream.avail_in = data.size();
stream.next_in = (Bytef*)(data.data());
inflateResult = inflateInit2(&stream, 15 + 32); // gzip decoding
if (inflateResult != Z_OK) {
return QByteArray();
}
do {
stream.avail_out = CHUNK_SIZE;
stream.next_out = (Bytef*)(out);
inflateResult = inflate(&stream, Z_NO_FLUSH);
switch (inflateResult) {
case Z_NEED_DICT:
case Z_DATA_ERROR:
case Z_MEM_ERROR:
case Z_STREAM_ERROR:
inflateEnd(&stream);
return QByteArray();
default:
break;
}
result.append(out, CHUNK_SIZE - stream.avail_out);
} while (stream.avail_out == 0);
inflateEnd(&stream);
return result;
}
} // Telegram
<|endoftext|>
|
<commit_before>//
// TIA.hpp
// Clock Signal
//
// Created by Thomas Harte on 28/01/2017.
// Copyright © 2017 Thomas Harte. All rights reserved.
//
#ifndef TIA_hpp
#define TIA_hpp
#include <cstdint>
#include "../CRTMachine.hpp"
namespace Atari2600 {
class TIA {
public:
TIA();
~TIA();
enum class OutputMode {
NTSC, PAL
};
/*!
Advances the TIA by @c number_of_cycles cycles. Any queued setters take effect in the
first cycle performed.
*/
void run_for_cycles(int number_of_cycles);
void set_output_mode(OutputMode output_mode);
void set_sync(bool sync);
void set_blank(bool blank);
void reset_horizontal_counter(); // Reset is delayed by four cycles.
int get_cycles_until_horizontal_blank(unsigned int from_offset);
void set_background_colour(uint8_t colour);
void set_playfield(uint16_t offset, uint8_t value);
void set_playfield_control_and_ball_size(uint8_t value);
void set_playfield_ball_colour(uint8_t colour);
void set_player_number_and_size(int player, uint8_t value);
void set_player_graphic(int player, uint8_t value);
void set_player_reflected(int player, bool reflected);
void set_player_delay(int player, bool delay);
void set_player_position(int player);
void set_player_motion(int player, uint8_t motion);
void set_player_missile_colour(int player, uint8_t colour);
void set_missile_enable(int missile, bool enabled);
void set_missile_position(int missile);
void set_missile_position_to_player(int missile);
void set_missile_motion(int missile, uint8_t motion);
void set_ball_enable(bool enabled);
void set_ball_delay(bool delay);
void set_ball_position();
void set_ball_motion(uint8_t motion);
void move();
void clear_motion();
uint8_t get_collision_flags(int offset);
void clear_collision_flags();
virtual std::shared_ptr<Outputs::CRT::CRT> get_crt() { return crt_; }
private:
std::shared_ptr<Outputs::CRT::CRT> crt_;
// drawing methods
inline void output_for_cycles(int number_of_cycles);
inline void output_line();
inline void draw_playfield(int start, int end);
int pixels_start_location_;
uint8_t *pixel_target_;
inline void output_pixels(int start, int end);
// the master counter; counts from 0 to 228 with all visible pixels being in the final 160
int horizontal_counter_;
// contains flags to indicate whether sync or blank are currently active
int output_mode_;
// keeps track of the target pixel buffer for this line and when it was acquired, and a corresponding collision buffer
uint8_t collision_buffer_[160];
enum class CollisionType : uint8_t {
Playfield = (1 << 0),
Ball = (1 << 1),
Player0 = (1 << 2),
Player1 = (1 << 3),
Missile0 = (1 << 4),
Missile1 = (1 << 5)
};
int collision_flags_;
int collision_flags_by_buffer_vaules_[64];
// colour mapping tables
enum class ColourMode {
Standard = 0,
ScoreLeft,
ScoreRight,
OnTop
};
uint8_t colour_mask_by_mode_collision_flags_[4][64]; // maps from [ColourMode][CollisionMark] to colour_pallete_ entry
enum class ColourIndex {
Background = 0,
PlayfieldBall,
PlayerMissile1,
PlayerMissile0
};
uint8_t colour_palette_[4];
// playfield state
int background_half_mask_;
enum class PlayfieldPriority {
Standard,
Score,
OnTop
} playfield_priority_;
uint32_t background_[2]; // contains two 20-bit bitfields representing the background state;
// at index 0 is the left-hand side of the playfield with bit 0 being
// the first bit to display, bit 1 the second, etc. Index 1 contains
// a mirror image of index 0. If the playfield is being displayed in
// mirroring mode, background_[0] will be output on the left and
// background_[1] on the right; otherwise background_[0] will be
// output twice.
int latched_playfield_value_;
// player state
struct Player {
int size; // 0 = normal, 1 = double, 2 = quad
int copy_flags; // a bit field, corresponding to the first few values of NUSIZ
uint8_t graphic; // the player graphic
int reverse_mask; // 7 for a reflected player, 0 for normal
uint8_t motion; // low four bits used
uint8_t position; // in the range [0, 160) to indicate offset from the left margin, i.e. phase difference
// between the player counter and the background pixel counter.
} player_[2];
// missile state
struct Missile {
int size; // 0 = 1 pixel, 1 = 2 pixels, etc
} missile_[2];
};
}
#endif /* TIA_hpp */
<commit_msg>Changed index naming order to ensure no out-of-bounds accesses.<commit_after>//
// TIA.hpp
// Clock Signal
//
// Created by Thomas Harte on 28/01/2017.
// Copyright © 2017 Thomas Harte. All rights reserved.
//
#ifndef TIA_hpp
#define TIA_hpp
#include <cstdint>
#include "../CRTMachine.hpp"
namespace Atari2600 {
class TIA {
public:
TIA();
~TIA();
enum class OutputMode {
NTSC, PAL
};
/*!
Advances the TIA by @c number_of_cycles cycles. Any queued setters take effect in the
first cycle performed.
*/
void run_for_cycles(int number_of_cycles);
void set_output_mode(OutputMode output_mode);
void set_sync(bool sync);
void set_blank(bool blank);
void reset_horizontal_counter(); // Reset is delayed by four cycles.
int get_cycles_until_horizontal_blank(unsigned int from_offset);
void set_background_colour(uint8_t colour);
void set_playfield(uint16_t offset, uint8_t value);
void set_playfield_control_and_ball_size(uint8_t value);
void set_playfield_ball_colour(uint8_t colour);
void set_player_number_and_size(int player, uint8_t value);
void set_player_graphic(int player, uint8_t value);
void set_player_reflected(int player, bool reflected);
void set_player_delay(int player, bool delay);
void set_player_position(int player);
void set_player_motion(int player, uint8_t motion);
void set_player_missile_colour(int player, uint8_t colour);
void set_missile_enable(int missile, bool enabled);
void set_missile_position(int missile);
void set_missile_position_to_player(int missile);
void set_missile_motion(int missile, uint8_t motion);
void set_ball_enable(bool enabled);
void set_ball_delay(bool delay);
void set_ball_position();
void set_ball_motion(uint8_t motion);
void move();
void clear_motion();
uint8_t get_collision_flags(int offset);
void clear_collision_flags();
virtual std::shared_ptr<Outputs::CRT::CRT> get_crt() { return crt_; }
private:
std::shared_ptr<Outputs::CRT::CRT> crt_;
// drawing methods
inline void output_for_cycles(int number_of_cycles);
inline void output_line();
inline void draw_playfield(int start, int end);
int pixels_start_location_;
uint8_t *pixel_target_;
inline void output_pixels(int start, int end);
// the master counter; counts from 0 to 228 with all visible pixels being in the final 160
int horizontal_counter_;
// contains flags to indicate whether sync or blank are currently active
int output_mode_;
// keeps track of the target pixel buffer for this line and when it was acquired, and a corresponding collision buffer
uint8_t collision_buffer_[160];
enum class CollisionType : uint8_t {
Playfield = (1 << 0),
Ball = (1 << 1),
Player0 = (1 << 2),
Player1 = (1 << 3),
Missile0 = (1 << 4),
Missile1 = (1 << 5)
};
int collision_flags_;
int collision_flags_by_buffer_vaules_[64];
// colour mapping tables
enum class ColourMode {
Standard = 0,
ScoreLeft,
ScoreRight,
OnTop
};
uint8_t colour_mask_by_mode_collision_flags_[4][64]; // maps from [ColourMode][CollisionMark] to colour_pallete_ entry
enum class ColourIndex {
Background = 0,
PlayfieldBall,
PlayerMissile0,
PlayerMissile1
};
uint8_t colour_palette_[4];
// playfield state
int background_half_mask_;
enum class PlayfieldPriority {
Standard,
Score,
OnTop
} playfield_priority_;
uint32_t background_[2]; // contains two 20-bit bitfields representing the background state;
// at index 0 is the left-hand side of the playfield with bit 0 being
// the first bit to display, bit 1 the second, etc. Index 1 contains
// a mirror image of index 0. If the playfield is being displayed in
// mirroring mode, background_[0] will be output on the left and
// background_[1] on the right; otherwise background_[0] will be
// output twice.
int latched_playfield_value_;
// player state
struct Player {
int size; // 0 = normal, 1 = double, 2 = quad
int copy_flags; // a bit field, corresponding to the first few values of NUSIZ
uint8_t graphic; // the player graphic
int reverse_mask; // 7 for a reflected player, 0 for normal
uint8_t motion; // low four bits used
uint8_t position; // in the range [0, 160) to indicate offset from the left margin, i.e. phase difference
// between the player counter and the background pixel counter.
} player_[2];
// missile state
struct Missile {
int size; // 0 = 1 pixel, 1 = 2 pixels, etc
} missile_[2];
};
}
#endif /* TIA_hpp */
<|endoftext|>
|
<commit_before>/*=========================================================================
Program: Visualization Toolkit
Module: TestMySQLDatabase.cxx
Copyright (c) Ken Martin, Will Schroeder, Bill Lorensen
All rights reserved.
See Copyright.txt or http://www.kitware.com/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 notice for more information.
=========================================================================*/
/*----------------------------------------------------------------------------
Copyright (c) Sandia Corporation
See Copyright.txt or http://www.paraview.org/HTML/Copyright.html for details.
----------------------------------------------------------------------------*/
// .SECTION Thanks
// Thanks to Andrew Wilson and Philippe Pebay from Sandia National Laboratories
// for implementing this test.
#include "vtkMySQLDatabase.h"
#include "vtkSQLQuery.h"
#include "vtkRowQueryToTable.h"
#include "vtkSQLDatabaseSchema.h"
#include "vtkStdString.h"
#include "vtkTable.h"
#include "vtkVariant.h"
#include "vtkVariantArray.h"
#include "vtkToolkits.h"
#include <vtkstd/vector>
int TestMySQLDatabase( int, char ** const )
{
vtkMySQLDatabase* db = vtkMySQLDatabase::SafeDownCast( vtkSQLDatabase::CreateFromURL( VTK_MYSQL_TEST_URL ) );
bool status = db->Open();
if ( ! status )
{
cerr << "Couldn't open database.\n";
return 1;
}
vtkSQLQuery* query = db->GetQueryInstance();
vtkStdString createQuery( "CREATE TABLE IF NOT EXISTS people (name TEXT, age INTEGER, weight FLOAT)" );
cout << createQuery << endl;
query->SetQuery( createQuery.c_str() );
if ( !query->Execute() )
{
cerr << "Create query failed" << endl;
return 1;
}
for ( int i = 0; i < 40; ++ i )
{
char insertQuery[200];
sprintf( insertQuery, "INSERT INTO people VALUES('John Doe %d', %d, %d)",
i, i, 10*i );
cout << insertQuery << endl;
query->SetQuery( insertQuery );
if ( !query->Execute() )
{
cerr << "Insert query " << i << " failed" << endl;
return 1;
}
}
const char* queryText = "SELECT name, age, weight FROM people WHERE age <= 20";
query->SetQuery( queryText );
cerr << endl << "Running query: " << query->GetQuery() << endl;
cerr << endl << "Using vtkSQLQuery directly to execute query:" << endl;
if ( !query->Execute() )
{
cerr << "Query failed" << endl;
return 1;
}
for ( int col = 0; col < query->GetNumberOfFields(); ++ col )
{
if ( col > 0 )
{
cerr << ", ";
}
cerr << query->GetFieldName( col );
}
cerr << endl;
while ( query->NextRow() )
{
for ( int field = 0; field < query->GetNumberOfFields(); ++ field )
{
if ( field > 0 )
{
cerr << ", ";
}
cerr << query->DataValue( field ).ToString().c_str();
}
cerr << endl;
}
cerr << endl << "Using vtkSQLQuery to execute query and retrieve by row:" << endl;
if ( !query->Execute() )
{
cerr << "Query failed" << endl;
return 1;
}
for ( int col = 0; col < query->GetNumberOfFields(); ++ col )
{
if ( col > 0 )
{
cerr << ", ";
}
cerr << query->GetFieldName( col );
}
cerr << endl;
vtkVariantArray* va = vtkVariantArray::New();
while ( query->NextRow( va ) )
{
for ( int field = 0; field < va->GetNumberOfValues(); ++ field )
{
if ( field > 0 )
{
cerr << ", ";
}
cerr << va->GetValue( field ).ToString().c_str();
}
cerr << endl;
}
va->Delete();
cerr << endl << "Using vtkRowQueryToTable to execute query:" << endl;
vtkRowQueryToTable* reader = vtkRowQueryToTable::New();
reader->SetQuery( query );
reader->Update();
vtkTable* table = reader->GetOutput();
for ( vtkIdType col = 0; col < table->GetNumberOfColumns(); ++ col )
{
table->GetColumn( col )->Print( cerr );
}
cerr << endl;
for ( vtkIdType row = 0; row < table->GetNumberOfRows(); ++ row )
{
for ( vtkIdType col = 0; col < table->GetNumberOfColumns(); ++ col )
{
vtkVariant v = table->GetValue( row, col );
cerr << "row " << row << ", col " << col << " - "
<< v.ToString() << " ( " << vtkImageScalarTypeNameMacro( v.GetType()) << " )" << endl;
}
}
query->SetQuery( "DROP TABLE people" );
if ( ! query->Execute() )
{
cerr << "DROP TABLE people query failed" << endl;
return 1;
}
reader->Delete();
query->Delete();
db->Delete();
// ----------------------------------------------------------------------
// Testing transformation of a schema into a MySQL database
// 1. Create the schema
#include "DatabaseSchemaWith2Tables.cxx"
// 2. Convert the schema into a MySQL database
cerr << "@@ Converting the schema into a MySQL database...";
db = vtkMySQLDatabase::SafeDownCast( vtkSQLDatabase::CreateFromURL( VTK_MYSQL_TEST_URL ) );
status = db->Open();
if ( ! status )
{
cerr << "Couldn't open database.\n";
return 1;
}
status = db->EffectSchema( schema );
if ( ! status )
{
cerr << "Could not effect test schema.\n";
return 1;
}
cerr << " done." << endl;
// 3. Count tables of the newly created database
cerr << "@@ Counting tables of the newly created database... ";
query = db->GetQueryInstance();
query->SetQuery( "SHOW TABLES" );
if ( ! query->Execute() )
{
cerr << "Query failed" << endl;
return 1;
}
vtkstd::vector<vtkStdString> tables;
while ( query->NextRow() )
{
tables.push_back( query->DataValue( 0 ).ToString() );
}
int numTbl = tables.size();
if ( numTbl != schema->GetNumberOfTables() )
{
cerr << "Found an incorrect number of tables: "
<< numTbl
<< " != "
<< schema->GetNumberOfTables()
<< endl;
return 1;
}
cerr << numTbl
<< " found.\n";
// 4. Inspect these tables
cerr << "@@ Inspecting these tables..." << "\n";
vtkStdString queryStr;
for ( tblHandle = 0; tblHandle < numTbl; ++ tblHandle )
{
vtkStdString tblName( schema->GetTableNameFromHandle( tblHandle ) );
cerr << " Table: "
<< tblName
<< "\n";
if ( tblName != tables[tblHandle] )
{
cerr << "Fetched an incorrect name: "
<< tables[tblHandle]
<< " != "
<< tblName
<< endl;
return 1;
}
// 4.1 Check columns
queryStr = "DESCRIBE ";
queryStr += tblName;
query->SetQuery( queryStr );
if ( ! query->Execute() )
{
cerr << "Query failed" << endl;
return 1;
}
int numFields = query->GetNumberOfFields();
int colHandle = 0;
for ( ; query->NextRow(); ++ colHandle )
{
for ( int field = 0; field < numFields; ++ field )
{
if ( field )
{
cerr << ", ";
}
else // if ( field )
{
vtkStdString colName ( schema->GetColumnNameFromHandle( tblHandle, colHandle ) );
if ( colName != query->DataValue( field ).ToString() )
{
cerr << "Found an incorrect column name: "
<< query->DataValue( field ).ToString()
<< " != "
<< colName
<< endl;
return 1;
}
cerr << " Column: ";
}
cerr << query->DataValue( field ).ToString().c_str();
}
cerr << endl;
}
if ( colHandle != schema->GetNumberOfColumnsInTable( tblHandle ) )
{
cerr << "Found an incorrect number of columns: "
<< colHandle
<< " != "
<< schema->GetNumberOfColumnsInTable( tblHandle )
<< endl;
return 1;
}
// 4.2 Check indices
queryStr = "SHOW INDEX FROM ";
queryStr += tblName;
query->SetQuery( queryStr );
if ( ! query->Execute() )
{
cerr << "Query failed" << endl;
return 1;
}
numFields = query->GetNumberOfFields();
int idxHandle = -1;
while ( query->NextRow() )
{
int cnmHandle = atoi( query->DataValue( 3 ).ToString() ) - 1;
if ( ! cnmHandle )
{
++ idxHandle;
}
vtkStdString colName ( schema->GetIndexColumnNameFromHandle( tblHandle, idxHandle, cnmHandle ) );
for ( int field = 0; field < numFields; ++ field )
{
if ( field )
{
cerr << ", ";
}
else // if ( field )
{
cerr << " Index: ";
}
cerr << query->DataValue( field ).ToString().c_str();
}
cerr << endl;
if ( colName != query->DataValue( 4 ).ToString() )
{
cerr << "Fetched an incorrect column name: "
<< query->DataValue( 4 ).ToString()
<< " != "
<< colName
<< endl;
return 1;
}
}
if ( idxHandle + 1 != schema->GetNumberOfIndicesInTable( tblHandle ) )
{
cerr << "Found an incorrect number of indices: "
<< idxHandle + 1
<< " != "
<< schema->GetNumberOfIndicesInTable( tblHandle )
<< endl;
return 1;
}
}
// 5. Populate these tables using the trigger mechanism
cerr << "@@ Populating table atable...";
queryStr = "INSERT INTO atable (somename,somenmbr) VALUES ( 'Bas-Rhin', 67 )";
query->SetQuery( queryStr );
if ( ! query->Execute() )
{
cerr << "Query failed" << endl;
schema->Delete();
query->Delete();
db->Delete();
return 1;
}
queryStr = "INSERT INTO atable (somename,somenmbr) VALUES ( 'Hautes-Pyrenees', 65 )";
query->SetQuery( queryStr );
if ( ! query->Execute() )
{
cerr << "Query failed" << endl;
schema->Delete();
query->Delete();
db->Delete();
return 1;
}
queryStr = "INSERT INTO atable (somename,somenmbr) VALUES ( 'Vosges', 88 )";
query->SetQuery( queryStr );
if ( ! query->Execute() )
{
cerr << "Query failed" << endl;
schema->Delete();
query->Delete();
db->Delete();
return 1;
}
cerr << " done." << endl;
// 6. Check that the trigger-dependent table has indeed been populated
cerr << "@@ Checking trigger-dependent table btable...\n";
queryStr = "SELECT somevalue FROM btable ORDER BY somevalue DESC";
query->SetQuery( queryStr );
if ( ! query->Execute() )
{
cerr << "Query failed" << endl;
schema->Delete();
query->Delete();
db->Delete();
return 1;
}
cerr << " Entries in column somevalue of table btable, in descending order:\n";
static const char *dpts[] = { "88", "67", "65" };
int numDpt = 0;
for ( ; query->NextRow(); ++ numDpt )
{
if ( query->DataValue( 0 ).ToString() != dpts[numDpt] )
{
cerr << "Found an incorrect value: "
<< query->DataValue( 0 ).ToString()
<< " != "
<< dpts[numDpt]
<< endl;
schema->Delete();
query->Delete();
db->Delete();
return 1;
}
cerr << " "
<< query->DataValue( 0 ).ToString()
<< "\n";
}
if ( numDpt != 3 )
{
cerr << "Found an incorrect number of entries: "
<< numDpt
<< " != "
<< 3
<< endl;
schema->Delete();
query->Delete();
db->Delete();
return 1;
}
cerr << " done." << endl;
// 7. Drop tables
cerr << "@@ Dropping these tables...";
for ( vtkstd::vector<vtkStdString>::iterator it = tables.begin();
it != tables.end(); ++ it )
{
vtkStdString queryStr = "DROP TABLE ";
queryStr += *it;
query->SetQuery( queryStr );
if ( ! query->Execute() )
{
cerr << "Query failed" << endl;
return 1;
}
}
cerr << " done." << endl;
// Clean up
db->Delete();
schema->Delete();
query->Delete();
return 0;
}
<commit_msg>COMP: eliminated a warning.<commit_after>/*=========================================================================
Program: Visualization Toolkit
Module: TestMySQLDatabase.cxx
Copyright (c) Ken Martin, Will Schroeder, Bill Lorensen
All rights reserved.
See Copyright.txt or http://www.kitware.com/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 notice for more information.
=========================================================================*/
/*----------------------------------------------------------------------------
Copyright (c) Sandia Corporation
See Copyright.txt or http://www.paraview.org/HTML/Copyright.html for details.
----------------------------------------------------------------------------*/
// .SECTION Thanks
// Thanks to Andrew Wilson and Philippe Pebay from Sandia National Laboratories
// for implementing this test.
#include "vtkMySQLDatabase.h"
#include "vtkSQLQuery.h"
#include "vtkRowQueryToTable.h"
#include "vtkSQLDatabaseSchema.h"
#include "vtkStdString.h"
#include "vtkTable.h"
#include "vtkVariant.h"
#include "vtkVariantArray.h"
#include "vtkToolkits.h"
#include <vtkstd/vector>
int TestMySQLDatabase( int, char ** const )
{
vtkMySQLDatabase* db = vtkMySQLDatabase::SafeDownCast( vtkSQLDatabase::CreateFromURL( VTK_MYSQL_TEST_URL ) );
bool status = db->Open();
if ( ! status )
{
cerr << "Couldn't open database.\n";
return 1;
}
vtkSQLQuery* query = db->GetQueryInstance();
vtkStdString createQuery( "CREATE TABLE IF NOT EXISTS people (name TEXT, age INTEGER, weight FLOAT)" );
cout << createQuery << endl;
query->SetQuery( createQuery.c_str() );
if ( !query->Execute() )
{
cerr << "Create query failed" << endl;
return 1;
}
for ( int i = 0; i < 40; ++ i )
{
char insertQuery[200];
sprintf( insertQuery, "INSERT INTO people VALUES('John Doe %d', %d, %d)",
i, i, 10*i );
cout << insertQuery << endl;
query->SetQuery( insertQuery );
if ( !query->Execute() )
{
cerr << "Insert query " << i << " failed" << endl;
return 1;
}
}
const char* queryText = "SELECT name, age, weight FROM people WHERE age <= 20";
query->SetQuery( queryText );
cerr << endl << "Running query: " << query->GetQuery() << endl;
cerr << endl << "Using vtkSQLQuery directly to execute query:" << endl;
if ( !query->Execute() )
{
cerr << "Query failed" << endl;
return 1;
}
for ( int col = 0; col < query->GetNumberOfFields(); ++ col )
{
if ( col > 0 )
{
cerr << ", ";
}
cerr << query->GetFieldName( col );
}
cerr << endl;
while ( query->NextRow() )
{
for ( int field = 0; field < query->GetNumberOfFields(); ++ field )
{
if ( field > 0 )
{
cerr << ", ";
}
cerr << query->DataValue( field ).ToString().c_str();
}
cerr << endl;
}
cerr << endl << "Using vtkSQLQuery to execute query and retrieve by row:" << endl;
if ( !query->Execute() )
{
cerr << "Query failed" << endl;
return 1;
}
for ( int col = 0; col < query->GetNumberOfFields(); ++ col )
{
if ( col > 0 )
{
cerr << ", ";
}
cerr << query->GetFieldName( col );
}
cerr << endl;
vtkVariantArray* va = vtkVariantArray::New();
while ( query->NextRow( va ) )
{
for ( int field = 0; field < va->GetNumberOfValues(); ++ field )
{
if ( field > 0 )
{
cerr << ", ";
}
cerr << va->GetValue( field ).ToString().c_str();
}
cerr << endl;
}
va->Delete();
cerr << endl << "Using vtkRowQueryToTable to execute query:" << endl;
vtkRowQueryToTable* reader = vtkRowQueryToTable::New();
reader->SetQuery( query );
reader->Update();
vtkTable* table = reader->GetOutput();
for ( vtkIdType col = 0; col < table->GetNumberOfColumns(); ++ col )
{
table->GetColumn( col )->Print( cerr );
}
cerr << endl;
for ( vtkIdType row = 0; row < table->GetNumberOfRows(); ++ row )
{
for ( vtkIdType col = 0; col < table->GetNumberOfColumns(); ++ col )
{
vtkVariant v = table->GetValue( row, col );
cerr << "row " << row << ", col " << col << " - "
<< v.ToString() << " ( " << vtkImageScalarTypeNameMacro( v.GetType()) << " )" << endl;
}
}
query->SetQuery( "DROP TABLE people" );
if ( ! query->Execute() )
{
cerr << "DROP TABLE people query failed" << endl;
return 1;
}
reader->Delete();
query->Delete();
db->Delete();
// ----------------------------------------------------------------------
// Testing transformation of a schema into a MySQL database
// 1. Create the schema
#include "DatabaseSchemaWith2Tables.cxx"
// 2. Convert the schema into a MySQL database
cerr << "@@ Converting the schema into a MySQL database...";
db = vtkMySQLDatabase::SafeDownCast( vtkSQLDatabase::CreateFromURL( VTK_MYSQL_TEST_URL ) );
status = db->Open();
if ( ! status )
{
cerr << "Couldn't open database.\n";
return 1;
}
status = db->EffectSchema( schema );
if ( ! status )
{
cerr << "Could not effect test schema.\n";
return 1;
}
cerr << " done." << endl;
// 3. Count tables of the newly created database
cerr << "@@ Counting tables of the newly created database... ";
query = db->GetQueryInstance();
query->SetQuery( "SHOW TABLES" );
if ( ! query->Execute() )
{
cerr << "Query failed" << endl;
return 1;
}
vtkstd::vector<vtkStdString> tables;
while ( query->NextRow() )
{
tables.push_back( query->DataValue( 0 ).ToString() );
}
int numTbl = tables.size();
if ( numTbl != schema->GetNumberOfTables() )
{
cerr << "Found an incorrect number of tables: "
<< numTbl
<< " != "
<< schema->GetNumberOfTables()
<< endl;
return 1;
}
cerr << numTbl
<< " found.\n";
// 4. Inspect these tables
cerr << "@@ Inspecting these tables..." << "\n";
vtkStdString queryStr;
for ( tblHandle = 0; tblHandle < numTbl; ++ tblHandle )
{
vtkStdString tblName( schema->GetTableNameFromHandle( tblHandle ) );
cerr << " Table: "
<< tblName
<< "\n";
if ( tblName != tables[tblHandle] )
{
cerr << "Fetched an incorrect name: "
<< tables[tblHandle]
<< " != "
<< tblName
<< endl;
return 1;
}
// 4.1 Check columns
queryStr = "DESCRIBE ";
queryStr += tblName;
query->SetQuery( queryStr );
if ( ! query->Execute() )
{
cerr << "Query failed" << endl;
return 1;
}
int numFields = query->GetNumberOfFields();
int colHandle = 0;
for ( ; query->NextRow(); ++ colHandle )
{
for ( int field = 0; field < numFields; ++ field )
{
if ( field )
{
cerr << ", ";
}
else // if ( field )
{
vtkStdString colName ( schema->GetColumnNameFromHandle( tblHandle, colHandle ) );
if ( colName != query->DataValue( field ).ToString() )
{
cerr << "Found an incorrect column name: "
<< query->DataValue( field ).ToString()
<< " != "
<< colName
<< endl;
return 1;
}
cerr << " Column: ";
}
cerr << query->DataValue( field ).ToString().c_str();
}
cerr << endl;
}
if ( colHandle != schema->GetNumberOfColumnsInTable( tblHandle ) )
{
cerr << "Found an incorrect number of columns: "
<< colHandle
<< " != "
<< schema->GetNumberOfColumnsInTable( tblHandle )
<< endl;
return 1;
}
// 4.2 Check indices
queryStr = "SHOW INDEX FROM ";
queryStr += tblName;
query->SetQuery( queryStr );
if ( ! query->Execute() )
{
cerr << "Query failed" << endl;
return 1;
}
numFields = query->GetNumberOfFields();
int idxHandle = -1;
while ( query->NextRow() )
{
int cnmHandle = atoi( query->DataValue( 3 ).ToString() ) - 1;
if ( ! cnmHandle )
{
++ idxHandle;
}
vtkStdString colName ( schema->GetIndexColumnNameFromHandle( tblHandle, idxHandle, cnmHandle ) );
for ( int field = 0; field < numFields; ++ field )
{
if ( field )
{
cerr << ", ";
}
else // if ( field )
{
cerr << " Index: ";
}
cerr << query->DataValue( field ).ToString().c_str();
}
cerr << endl;
if ( colName != query->DataValue( 4 ).ToString() )
{
cerr << "Fetched an incorrect column name: "
<< query->DataValue( 4 ).ToString()
<< " != "
<< colName
<< endl;
return 1;
}
}
if ( idxHandle + 1 != schema->GetNumberOfIndicesInTable( tblHandle ) )
{
cerr << "Found an incorrect number of indices: "
<< idxHandle + 1
<< " != "
<< schema->GetNumberOfIndicesInTable( tblHandle )
<< endl;
return 1;
}
}
// 5. Populate these tables using the trigger mechanism
cerr << "@@ Populating table atable...";
queryStr = "INSERT INTO atable (somename,somenmbr) VALUES ( 'Bas-Rhin', 67 )";
query->SetQuery( queryStr );
if ( ! query->Execute() )
{
cerr << "Query failed" << endl;
schema->Delete();
query->Delete();
db->Delete();
return 1;
}
queryStr = "INSERT INTO atable (somename,somenmbr) VALUES ( 'Hautes-Pyrenees', 65 )";
query->SetQuery( queryStr );
if ( ! query->Execute() )
{
cerr << "Query failed" << endl;
schema->Delete();
query->Delete();
db->Delete();
return 1;
}
queryStr = "INSERT INTO atable (somename,somenmbr) VALUES ( 'Vosges', 88 )";
query->SetQuery( queryStr );
if ( ! query->Execute() )
{
cerr << "Query failed" << endl;
schema->Delete();
query->Delete();
db->Delete();
return 1;
}
cerr << " done." << endl;
// 6. Check that the trigger-dependent table has indeed been populated
cerr << "@@ Checking trigger-dependent table btable...\n";
queryStr = "SELECT somevalue FROM btable ORDER BY somevalue DESC";
query->SetQuery( queryStr );
if ( ! query->Execute() )
{
cerr << "Query failed" << endl;
schema->Delete();
query->Delete();
db->Delete();
return 1;
}
cerr << " Entries in column somevalue of table btable, in descending order:\n";
static const char *dpts[] = { "88", "67", "65" };
int numDpt = 0;
for ( ; query->NextRow(); ++ numDpt )
{
if ( query->DataValue( 0 ).ToString() != dpts[numDpt] )
{
cerr << "Found an incorrect value: "
<< query->DataValue( 0 ).ToString()
<< " != "
<< dpts[numDpt]
<< endl;
schema->Delete();
query->Delete();
db->Delete();
return 1;
}
cerr << " "
<< query->DataValue( 0 ).ToString()
<< "\n";
}
if ( numDpt != 3 )
{
cerr << "Found an incorrect number of entries: "
<< numDpt
<< " != "
<< 3
<< endl;
schema->Delete();
query->Delete();
db->Delete();
return 1;
}
cerr << " done." << endl;
// 7. Drop tables
cerr << "@@ Dropping these tables...";
for ( vtkstd::vector<vtkStdString>::iterator it = tables.begin();
it != tables.end(); ++ it )
{
queryStr = "DROP TABLE ";
queryStr += *it;
query->SetQuery( queryStr );
if ( ! query->Execute() )
{
cerr << "Query failed" << endl;
return 1;
}
}
cerr << " done." << endl;
// Clean up
db->Delete();
schema->Delete();
query->Delete();
return 0;
}
<|endoftext|>
|
<commit_before>#include "RaZ/RaZ.hpp"
using namespace std::literals;
constexpr unsigned int sceneWidth = 1280;
constexpr unsigned int sceneHeight = 720;
constexpr std::string_view geomFragSource = R"(
struct Material {
vec3 baseColor;
vec3 emissive;
float metallicFactor;
float roughnessFactor;
sampler2D baseColorMap;
sampler2D emissiveMap;
sampler2D normalMap;
sampler2D metallicMap;
sampler2D roughnessMap;
sampler2D ambientMap;
};
in struct MeshInfo {
vec3 vertPosition;
vec2 vertTexcoords;
mat3 vertTBNMatrix;
} vertMeshInfo;
layout(std140) uniform uboCameraInfo {
mat4 uniViewMat;
mat4 uniInvViewMat;
mat4 uniProjectionMat;
mat4 uniInvProjectionMat;
mat4 uniViewProjectionMat;
vec3 uniCameraPos;
};
uniform Material uniMaterial;
layout(location = 0) out vec4 fragColor;
layout(location = 1) out vec4 fragNormal;
void main() {
vec3 albedo = pow(texture(uniMaterial.baseColorMap, vertMeshInfo.vertTexcoords).rgb, vec3(2.2)) * uniMaterial.baseColor;
vec3 emissive = texture(uniMaterial.emissiveMap, vertMeshInfo.vertTexcoords).rgb * uniMaterial.emissive;
float metallic = texture(uniMaterial.metallicMap, vertMeshInfo.vertTexcoords).r * uniMaterial.metallicFactor;
float roughness = texture(uniMaterial.roughnessMap, vertMeshInfo.vertTexcoords).r * uniMaterial.roughnessFactor;
vec3 normal = texture(uniMaterial.normalMap, vertMeshInfo.vertTexcoords).rgb;
normal = normalize(normal * 2.0 - 1.0);
normal = normalize(vertMeshInfo.vertTBNMatrix * normal);
// Using the emissive (which will always be 0 here) to avoid many warnings about unrecognized uniform names
fragColor = vec4(albedo + emissive, metallic);
fragNormal = vec4(normal, roughness);
}
)";
constexpr std::string_view displayFragSource = R"(
struct Buffers {
sampler2D depth;
sampler2D color;
sampler2D normal;
};
in vec2 fragTexcoords;
uniform Buffers uniSceneBuffers;
layout(location = 0) out vec4 fragColor;
void main() {
float depth = texture(uniSceneBuffers.depth, fragTexcoords).r;
vec4 color = texture(uniSceneBuffers.color, fragTexcoords).rgba;
vec4 normalRough = texture(uniSceneBuffers.normal, fragTexcoords).rgba;
vec3 normal = normalRough.rgb;
float roughness = normalRough.a;
if (int(gl_FragCoord.y) > 360) {
if (int(gl_FragCoord.x) < 640)
fragColor = vec4(vec3(depth), 1.0);
else
fragColor = vec4(normal, 1.0);
} else {
if (int(gl_FragCoord.x) < 640)
fragColor = vec4(vec3(roughness), 1.0);
else
fragColor = color;
}
}
)";
int main() {
try {
////////////////////
// Initialization //
////////////////////
Raz::Application app;
Raz::World& world = app.addWorld(2);
Raz::Logger::setLoggingLevel(Raz::LoggingLevel::ALL);
///////////////
// Rendering //
///////////////
auto& render = world.addSystem<Raz::RenderSystem>(sceneWidth, sceneHeight, "RaZ");
Raz::Window& window = render.getWindow();
///////////////////
// Render passes //
///////////////////
Raz::RenderGraph& renderGraph = render.getRenderGraph();
// Creating the render graph's texture buffers
const auto depthBuffer = Raz::Texture::create(sceneWidth, sceneHeight, Raz::ImageColorspace::DEPTH);
const auto colorBuffer = Raz::Texture::create(sceneWidth, sceneHeight, Raz::ImageColorspace::RGBA);
const auto normalBuffer = Raz::Texture::create(sceneWidth, sceneHeight, Raz::ImageColorspace::RGBA);
// Setting the geometry pass' write buffers
Raz::RenderPass& geomPass = renderGraph.getGeometryPass();
geomPass.addWriteTexture(depthBuffer);
geomPass.addWriteTexture(colorBuffer);
geomPass.addWriteTexture(normalBuffer);
// Adding the second pass & defining its read buffers
Raz::RenderPass& splitPass = renderGraph.addNode(Raz::FragmentShader::loadFromSource(displayFragSource));
splitPass.addReadTexture(depthBuffer, "uniSceneBuffers.depth");
splitPass.addReadTexture(colorBuffer, "uniSceneBuffers.color");
splitPass.addReadTexture(normalBuffer, "uniSceneBuffers.normal");
geomPass.addChildren(splitPass);
//////////
// Mesh //
//////////
// Importing the mesh & transforming it so that it can be fully visible
Raz::Entity& mesh = world.addEntity();
auto [meshData, meshRenderData] = Raz::ObjFormat::load(RAZ_ROOT "assets/meshes/shield.obj");
mesh.addComponent<Raz::Mesh>(std::move(meshData));
mesh.addComponent<Raz::MeshRenderer>(std::move(meshRenderData));
auto& meshTrans = mesh.addComponent<Raz::Transform>();
meshTrans.scale(0.2f);
////////////
// Camera //
////////////
Raz::Entity& camera = world.addEntity();
auto& cameraComp = camera.addComponent<Raz::Camera>(sceneWidth, sceneHeight);
auto& cameraTrans = camera.addComponent<Raz::Transform>(Raz::Vec3f(0.f, 0.f, 5.f));
float cameraSpeed = 1.f;
window.addKeyCallback(Raz::Keyboard::LEFT_SHIFT,
[&cameraSpeed] (float /* deltaTime */) noexcept { cameraSpeed = 2.f; },
Raz::Input::ONCE,
[&cameraSpeed] () noexcept { cameraSpeed = 1.f; });
window.addKeyCallback(Raz::Keyboard::SPACE, [&cameraTrans, &cameraSpeed] (float deltaTime) {
cameraTrans.move(0.f, (10.f * deltaTime) * cameraSpeed, 0.f);
});
window.addKeyCallback(Raz::Keyboard::V, [&cameraTrans, &cameraSpeed] (float deltaTime) {
cameraTrans.move(0.f, (-10.f * deltaTime) * cameraSpeed, 0.f);
});
window.addKeyCallback(Raz::Keyboard::W, [&cameraTrans, &cameraSpeed] (float deltaTime) {
cameraTrans.move(0.f, 0.f, (-10.f * deltaTime) * cameraSpeed);
});
window.addKeyCallback(Raz::Keyboard::S, [&cameraTrans, &cameraSpeed] (float deltaTime) {
cameraTrans.move(0.f, 0.f, (10.f * deltaTime) * cameraSpeed);
});
window.addKeyCallback(Raz::Keyboard::A, [&cameraTrans, &cameraSpeed] (float deltaTime) {
cameraTrans.move((-10.f * deltaTime) * cameraSpeed, 0.f, 0.f);
});
window.addKeyCallback(Raz::Keyboard::D, [&cameraTrans, &cameraSpeed] (float deltaTime) {
cameraTrans.move((10.f * deltaTime) * cameraSpeed, 0.f, 0.f);
});
window.setMouseMoveCallback([&cameraTrans, &window] (double xMove, double yMove) {
// Dividing move by window size to scale between -1 and 1
cameraTrans.rotate(-90_deg * static_cast<float>(yMove) / window.getHeight(),
-90_deg * static_cast<float>(xMove) / window.getWidth());
});
//////////////////////
// Window callbacks //
//////////////////////
// Toggling the render pass' enabled state
window.addKeyCallback(Raz::Keyboard::R, [&splitPass] (float /* deltaTime */) noexcept { splitPass.enable(!splitPass.isEnabled()); }, Raz::Input::ONCE);
// Allowing to quit the application by pressing the Esc key
window.addKeyCallback(Raz::Keyboard::ESCAPE, [&app] (float /* deltaTime */) noexcept { app.quit(); });
// Allowing to quit the application when the close button is clicked
window.setCloseCallback([&app] () noexcept { app.quit(); });
/////////////
// Overlay //
/////////////
#if !defined(RAZ_NO_OVERLAY)
Raz::OverlayWindow& overlay = window.getOverlay().addWindow("RaZ - Deferred demo", Raz::Vec2f(sceneWidth / 4, sceneHeight));
overlay.addTexture(*depthBuffer, sceneWidth / 4, sceneHeight / 4);
overlay.addTexture(*colorBuffer, sceneWidth / 4, sceneHeight / 4);
overlay.addTexture(*normalBuffer, sceneWidth / 4, sceneHeight / 4);
overlay.addSeparator();
overlay.addFrameTime("Frame time: %.3f ms/frame"); // Frame time's & FPS counter's texts must be formatted
overlay.addFpsCounter("FPS: %.1f");
#endif
//////////////////////////
// Starting application //
//////////////////////////
app.run();
} catch (const std::exception& exception) {
Raz::Logger::error("Exception occured: "s + exception.what());
}
return EXIT_SUCCESS;
}
<commit_msg>[Examples/DeferredDemo] Fixed the deferred demo<commit_after>#include "RaZ/RaZ.hpp"
using namespace std::literals;
constexpr unsigned int sceneWidth = 1280;
constexpr unsigned int sceneHeight = 720;
constexpr std::string_view geomFragSource = R"(
struct Material {
vec3 baseColor;
vec3 emissive;
float metallicFactor;
float roughnessFactor;
sampler2D baseColorMap;
sampler2D emissiveMap;
sampler2D normalMap;
sampler2D metallicMap;
sampler2D roughnessMap;
sampler2D ambientMap;
};
in struct MeshInfo {
vec3 vertPosition;
vec2 vertTexcoords;
mat3 vertTBNMatrix;
} vertMeshInfo;
layout(std140) uniform uboCameraInfo {
mat4 uniViewMat;
mat4 uniInvViewMat;
mat4 uniProjectionMat;
mat4 uniInvProjectionMat;
mat4 uniViewProjectionMat;
vec3 uniCameraPos;
};
uniform Material uniMaterial;
layout(location = 0) out vec4 fragColor;
layout(location = 1) out vec4 fragNormal;
void main() {
vec3 albedo = pow(texture(uniMaterial.baseColorMap, vertMeshInfo.vertTexcoords).rgb, vec3(2.2)) * uniMaterial.baseColor;
vec3 emissive = texture(uniMaterial.emissiveMap, vertMeshInfo.vertTexcoords).rgb * uniMaterial.emissive;
float metallic = texture(uniMaterial.metallicMap, vertMeshInfo.vertTexcoords).r * uniMaterial.metallicFactor;
float roughness = texture(uniMaterial.roughnessMap, vertMeshInfo.vertTexcoords).r * uniMaterial.roughnessFactor;
float ambOcc = texture(uniMaterial.ambientMap, vertMeshInfo.vertTexcoords).r;
vec3 normal = texture(uniMaterial.normalMap, vertMeshInfo.vertTexcoords).rgb;
normal = normalize(normal * 2.0 - 1.0);
normal = normalize(vertMeshInfo.vertTBNMatrix * normal);
// Using the emissive (which will always be 0 here) to avoid many warnings about unrecognized uniform names
fragColor = vec4(albedo + (ambOcc - 1.0) + emissive, metallic);
fragNormal = vec4(normal, roughness);
}
)";
constexpr std::string_view displayFragSource = R"(
struct Buffers {
sampler2D depth;
sampler2D color;
sampler2D normal;
};
in vec2 fragTexcoords;
uniform Buffers uniSceneBuffers;
layout(location = 0) out vec4 fragColor;
void main() {
float depth = texture(uniSceneBuffers.depth, fragTexcoords).r;
vec4 colorMetal = texture(uniSceneBuffers.color, fragTexcoords).rgba;
vec3 color = colorMetal.rgb;
float metalness = colorMetal.a;
vec4 normalRough = texture(uniSceneBuffers.normal, fragTexcoords).rgba;
vec3 normal = normalRough.rgb;
float roughness = normalRough.a;
if (int(gl_FragCoord.y) > 360) {
if (int(gl_FragCoord.x) < 640)
fragColor = vec4(vec3(depth), 1.0);
else
fragColor = vec4(normal, 1.0);
} else {
if (int(gl_FragCoord.x) < 640)
fragColor = vec4(1.0, metalness, roughness, 1.0);
else
fragColor = vec4(color, 1.0);
}
}
)";
int main() {
try {
////////////////////
// Initialization //
////////////////////
Raz::Application app;
Raz::World& world = app.addWorld(2);
Raz::Logger::setLoggingLevel(Raz::LoggingLevel::ALL);
///////////////
// Rendering //
///////////////
auto& render = world.addSystem<Raz::RenderSystem>(sceneWidth, sceneHeight, "RaZ");
Raz::Window& window = render.getWindow();
///////////////////
// Render passes //
///////////////////
Raz::RenderGraph& renderGraph = render.getRenderGraph();
// Creating the render graph's texture buffers
const auto depthBuffer = Raz::Texture::create(sceneWidth, sceneHeight, Raz::ImageColorspace::DEPTH);
const auto colorBuffer = Raz::Texture::create(sceneWidth, sceneHeight, Raz::ImageColorspace::RGBA);
const auto normalBuffer = Raz::Texture::create(sceneWidth, sceneHeight, Raz::ImageColorspace::RGBA);
// Setting the geometry pass' write buffers
Raz::RenderPass& geomPass = renderGraph.getGeometryPass();
geomPass.addWriteTexture(depthBuffer);
geomPass.addWriteTexture(colorBuffer);
geomPass.addWriteTexture(normalBuffer);
// Adding the second pass & defining its read buffers
Raz::RenderPass& splitPass = renderGraph.addNode(Raz::FragmentShader::loadFromSource(displayFragSource));
splitPass.addReadTexture(depthBuffer, "uniSceneBuffers.depth");
splitPass.addReadTexture(colorBuffer, "uniSceneBuffers.color");
splitPass.addReadTexture(normalBuffer, "uniSceneBuffers.normal");
geomPass.addChildren(splitPass);
//////////
// Mesh //
//////////
// Importing the mesh & transforming it so that it can be fully visible
Raz::Entity& mesh = world.addEntity();
auto& meshRenderer = mesh.addComponent<Raz::MeshRenderer>(Raz::ObjFormat::load(RAZ_ROOT "assets/meshes/shield.obj").second);
Raz::RenderShaderProgram& shaderProgram = meshRenderer.getMaterials().front().getProgram();
shaderProgram.setFragmentShader(Raz::FragmentShader::loadFromSource(geomFragSource));
shaderProgram.link();
auto& meshTrans = mesh.addComponent<Raz::Transform>();
meshTrans.scale(0.2f);
////////////
// Camera //
////////////
Raz::Entity& camera = world.addEntity();
auto& cameraComp = camera.addComponent<Raz::Camera>(sceneWidth, sceneHeight);
auto& cameraTrans = camera.addComponent<Raz::Transform>(Raz::Vec3f(0.f, 0.f, 5.f));
float cameraSpeed = 1.f;
window.addKeyCallback(Raz::Keyboard::LEFT_SHIFT,
[&cameraSpeed] (float /* deltaTime */) noexcept { cameraSpeed = 2.f; },
Raz::Input::ONCE,
[&cameraSpeed] () noexcept { cameraSpeed = 1.f; });
window.addKeyCallback(Raz::Keyboard::SPACE, [&cameraTrans, &cameraSpeed] (float deltaTime) {
cameraTrans.move(0.f, (10.f * deltaTime) * cameraSpeed, 0.f);
});
window.addKeyCallback(Raz::Keyboard::V, [&cameraTrans, &cameraSpeed] (float deltaTime) {
cameraTrans.move(0.f, (-10.f * deltaTime) * cameraSpeed, 0.f);
});
window.addKeyCallback(Raz::Keyboard::W, [&cameraTrans, &cameraSpeed] (float deltaTime) {
cameraTrans.move(0.f, 0.f, (-10.f * deltaTime) * cameraSpeed);
});
window.addKeyCallback(Raz::Keyboard::S, [&cameraTrans, &cameraSpeed] (float deltaTime) {
cameraTrans.move(0.f, 0.f, (10.f * deltaTime) * cameraSpeed);
});
window.addKeyCallback(Raz::Keyboard::A, [&cameraTrans, &cameraSpeed] (float deltaTime) {
cameraTrans.move((-10.f * deltaTime) * cameraSpeed, 0.f, 0.f);
});
window.addKeyCallback(Raz::Keyboard::D, [&cameraTrans, &cameraSpeed] (float deltaTime) {
cameraTrans.move((10.f * deltaTime) * cameraSpeed, 0.f, 0.f);
});
window.setMouseMoveCallback([&cameraTrans, &window] (double xMove, double yMove) {
// Dividing move by window size to scale between -1 and 1
cameraTrans.rotate(-90_deg * static_cast<float>(yMove) / window.getHeight(),
-90_deg * static_cast<float>(xMove) / window.getWidth());
});
//////////////////////
// Window callbacks //
//////////////////////
// Toggling the render pass' enabled state
window.addKeyCallback(Raz::Keyboard::R, [&splitPass] (float /* deltaTime */) noexcept { splitPass.enable(!splitPass.isEnabled()); }, Raz::Input::ONCE);
// Allowing to quit the application by pressing the Esc key
window.addKeyCallback(Raz::Keyboard::ESCAPE, [&app] (float /* deltaTime */) noexcept { app.quit(); });
// Allowing to quit the application when the close button is clicked
window.setCloseCallback([&app] () noexcept { app.quit(); });
/////////////
// Overlay //
/////////////
#if !defined(RAZ_NO_OVERLAY)
Raz::OverlayWindow& overlay = window.getOverlay().addWindow("RaZ - Deferred demo", Raz::Vec2f(sceneWidth / 4, sceneHeight));
overlay.addTexture(*depthBuffer, sceneWidth / 4, sceneHeight / 4);
overlay.addTexture(*colorBuffer, sceneWidth / 4, sceneHeight / 4);
overlay.addTexture(*normalBuffer, sceneWidth / 4, sceneHeight / 4);
overlay.addSeparator();
overlay.addFrameTime("Frame time: %.3f ms/frame"); // Frame time's & FPS counter's texts must be formatted
overlay.addFpsCounter("FPS: %.1f");
#endif
//////////////////////////
// Starting application //
//////////////////////////
app.run();
} catch (const std::exception& exception) {
Raz::Logger::error("Exception occured: "s + exception.what());
}
return EXIT_SUCCESS;
}
<|endoftext|>
|
<commit_before>#include <cstdio>
#include <cstring>
#include <iostream>
#include <memory>
#include "block.hpp"
#include "functors.hpp"
#include "hash.hpp"
#include "slice.hpp"
#include "threadpool.hpp"
int main (int argc, char** argv) {
std::unique_ptr<processFunctor_t> delegate;
size_t memoryAlloc = 200 * 1024 * 1024;
size_t nThreads = 1;
// parse command line arguments
for (auto i = 1; i < argc; ++i) {
const auto arg = argv[i];
size_t functorIndex = 0;
if (sscanf(arg, "-f%lu", &functorIndex) == 1) {
assert(delegate == nullptr);
if (functorIndex == 0) delegate.reset(new dumpHeaders());
else if (functorIndex == 1) delegate.reset(new dumpScripts());
else if (functorIndex == 2) delegate.reset(new dumpScriptIndexMap());
else if (functorIndex == 3) delegate.reset(new dumpScriptIndex());
else if (functorIndex == 4) delegate.reset(new dumpStatistics());
continue;
}
if (sscanf(arg, "-j%lu", &nThreads) == 1) continue;
if (sscanf(arg, "-m%lu", &memoryAlloc) == 1) continue;
if (delegate && delegate->initialize(arg)) continue;
assert(false);
}
assert(delegate != nullptr);
// pre-allocate buffers
const auto halfMemoryAlloc = memoryAlloc / 2;
FixedSlice buffer(halfMemoryAlloc);
std::cerr << "Initialized compute buffer (" << halfMemoryAlloc << " bytes)" << std::endl;
FixedSlice iobuffer(halfMemoryAlloc);
std::cerr << "Initialized IO buffer (" << halfMemoryAlloc << " bytes)" << std::endl;
ThreadPool<std::function<void(void)>> pool(nThreads);
std::cerr << "Initialized " << nThreads << " threads in the thread pool" << std::endl;
size_t count = 0;
size_t remainder = 0;
while (true) {
const auto rbuf = iobuffer.drop(remainder);
const auto read = fread(rbuf.begin, 1, rbuf.length(), stdin);
const auto eof = static_cast<size_t>(read) < rbuf.length();
// wait for all workers before overwrite
pool.wait();
// copy iobuffer to buffer, allows iobuffer to be modified independently after
memcpy(buffer.begin, iobuffer.begin, halfMemoryAlloc);
auto data = buffer.take(remainder + read);
std::cerr << "-- Parsed " << count << " blocks (read " << data.length() / 1024 << " KiB)" << (eof ? " EOF" : "") << std::endl;
while (data.length() >= 88) {
// skip bad data (e.g bitcoind zero pre-allocations)
if (data.peek<uint32_t>() != 0xd9b4bef9) {
data.popFrontN(1);
continue;
}
// skip bad data cont.
const auto header = data.drop(8).take(80);
if (!Block(header).verify()) {
data.popFrontN(1);
std::cerr << "--- Invalid block" << std::endl;
continue;
}
// do we have enough data?
const auto length = data.drop(4).peek<uint32_t>();
const auto total = 8 + length;
if (total > data.length()) break;
data.popFrontN(8);
// send the block data to the threadpool
const auto block = Block(data.take(80), data.drop(80));
pool.push([block, &delegate]() {
delegate->operator()(block);
});
count++;
data.popFrontN(length);
}
if (eof) break;
// assign remainder to front of iobuffer (rbuf is offset to avoid overwrite on rawRead)
remainder = data.length();
memcpy(iobuffer.begin, data.begin, remainder);
}
return 0;
}
<commit_msg>parser: better debug text<commit_after>#include <cstdio>
#include <cstring>
#include <iostream>
#include <memory>
#include "block.hpp"
#include "functors.hpp"
#include "hash.hpp"
#include "slice.hpp"
#include "threadpool.hpp"
int main (int argc, char** argv) {
std::unique_ptr<processFunctor_t> delegate;
size_t memoryAlloc = 200 * 1024 * 1024;
size_t nThreads = 1;
// parse command line arguments
for (auto i = 1; i < argc; ++i) {
const auto arg = argv[i];
size_t functorIndex = 0;
if (sscanf(arg, "-f%lu", &functorIndex) == 1) {
assert(delegate == nullptr);
if (functorIndex == 0) delegate.reset(new dumpHeaders());
else if (functorIndex == 1) delegate.reset(new dumpScripts());
else if (functorIndex == 2) delegate.reset(new dumpScriptIndexMap());
else if (functorIndex == 3) delegate.reset(new dumpScriptIndex());
else if (functorIndex == 4) delegate.reset(new dumpStatistics());
continue;
}
if (sscanf(arg, "-j%lu", &nThreads) == 1) continue;
if (sscanf(arg, "-m%lu", &memoryAlloc) == 1) continue;
if (delegate && delegate->initialize(arg)) continue;
assert(false);
}
assert(delegate != nullptr);
// pre-allocate buffers
const auto halfMemoryAlloc = memoryAlloc / 2;
FixedSlice iobuffer(halfMemoryAlloc);
std::cerr << "Allocated IO buffer (" << halfMemoryAlloc << " bytes)" << std::endl;
FixedSlice buffer(halfMemoryAlloc);
std::cerr << "Allocated active buffer (" << halfMemoryAlloc << " bytes)" << std::endl;
ThreadPool<std::function<void(void)>> pool(nThreads);
std::cerr << "Initialized " << nThreads << " threads in the thread pool" << std::endl;
size_t count = 0;
size_t remainder = 0;
while (true) {
const auto rbuf = iobuffer.drop(remainder);
const auto read = fread(rbuf.begin, 1, rbuf.length(), stdin);
const auto eof = static_cast<size_t>(read) < rbuf.length();
// wait for all workers before overwrite
pool.wait();
// copy iobuffer to buffer, allows iobuffer to be modified independently after
memcpy(buffer.begin, iobuffer.begin, halfMemoryAlloc);
auto data = buffer.take(remainder + read);
std::cerr << "-- Parsed " << count << " blocks (read " << data.length() / 1024 << " KiB)" << (eof ? " EOF" : "") << std::endl;
while (data.length() >= 88) {
// skip bad data (e.g bitcoind zero pre-allocations)
if (data.peek<uint32_t>() != 0xd9b4bef9) {
data.popFrontN(1);
continue;
}
// skip bad data cont.
const auto header = data.drop(8).take(80);
if (!Block(header).verify()) {
data.popFrontN(1);
std::cerr << "--- Invalid block" << std::endl;
continue;
}
// do we have enough data?
const auto length = data.drop(4).peek<uint32_t>();
const auto total = 8 + length;
if (total > data.length()) break;
data.popFrontN(8);
// send the block data to the threadpool
const auto block = Block(data.take(80), data.drop(80));
pool.push([block, &delegate]() {
delegate->operator()(block);
});
count++;
data.popFrontN(length);
}
if (eof) break;
// assign remainder to front of iobuffer (rbuf is offset to avoid overwrite on rawRead)
remainder = data.length();
memcpy(iobuffer.begin, data.begin, remainder);
}
return 0;
}
<|endoftext|>
|
<commit_before>//-------------------------------------------------------------------------------------------------------
// Copyright (C) Microsoft. All rights reserved.
// Licensed under the MIT license. See LICENSE.txt file in the project root for full license information.
//-------------------------------------------------------------------------------------------------------
#ifndef __APPLE__
// todo: for BSD consider moving this file into macOS folder
#include "../Linux/DateTime.cpp"
#else
#include "Common.h"
#include "ChakraPlatform.h"
#include <CoreFoundation/CFDate.h>
#include <CoreFoundation/CFTimeZone.h>
namespace PlatformAgnostic
{
namespace DateTime
{
const WCHAR *Utility::GetStandardName(size_t *nameLength, const DateTime::YMD *ymd)
{
AssertMsg(ymd != NULL, "xplat needs DateTime::YMD is defined for this call");
double tv = Js::DateUtilities::TvFromDate(ymd->year, ymd->mon, ymd->mday, ymd->time);
int64_t absoluteTime = tv / 1000;
absoluteTime -= kCFAbsoluteTimeIntervalSince1970;
CFTimeZoneRef timeZone = CFTimeZoneCopySystem();
int offset = (int)CFTimeZoneGetSecondsFromGMT(timeZone, (CFAbsoluteTime)absoluteTime);
absoluteTime -= offset;
char tz_name[128];
CFStringRef abbr = CFTimeZoneCopyAbbreviation(timeZone, absoluteTime);
CFStringGetCString(abbr, tz_name, sizeof(tz_name), kCFStringEncodingUTF16);
wcscpy_s(data.standardName, 32, reinterpret_cast<WCHAR*>(tz_name));
data.standardNameLength = CFStringGetLength(abbr);
CFRelease(abbr);
*nameLength = data.standardNameLength;
return data.standardName;
}
const WCHAR *Utility::GetDaylightName(size_t *nameLength, const DateTime::YMD *ymd)
{
// xplat only gets the actual zone name for the given date
return GetStandardName(nameLength, ymd);
}
static time_t IsDST(double tv, int *offset)
{
CFTimeZoneRef timeZone = CFTimeZoneCopySystem();
int64_t absoluteTime = tv / 1000;
absoluteTime -= kCFAbsoluteTimeIntervalSince1970;
*offset = (int)CFTimeZoneGetSecondsFromGMT(timeZone, (CFAbsoluteTime)absoluteTime);
return CFTimeZoneIsDaylightSavingTime(timeZone, (CFAbsoluteTime)absoluteTime);
}
static void YMDLocalToUtc(double localtv, YMD *utc)
{
int mOffset = 0;
bool isDST = IsDST(localtv, &mOffset);
localtv -= DateTimeTicks_PerSecond * mOffset;
Js::DateUtilities::GetYmdFromTv(localtv, utc);
}
static void YMDUtcToLocal(double utctv, YMD *local,
int &bias, int &offset, bool &isDaylightSavings)
{
int mOffset = 0;
bool isDST = IsDST(utctv, &mOffset);
utctv += DateTimeTicks_PerSecond * mOffset;
Js::DateUtilities::GetYmdFromTv(utctv, local);
isDaylightSavings = isDST;
bias = mOffset / 60;
offset = bias;
}
// DaylightTimeHelper ******
double DaylightTimeHelper::UtcToLocal(double utcTime, int &bias,
int &offset, bool &isDaylightSavings)
{
YMD local;
YMDUtcToLocal(utcTime, &local, bias, offset, isDaylightSavings);
return Js::DateUtilities::TvFromDate(local.year, local.mon, local.mday, local.time);
}
double DaylightTimeHelper::LocalToUtc(double localTime)
{
YMD utc;
YMDLocalToUtc(localTime, &utc);
return Js::DateUtilities::TvFromDate(utc.year, utc.mon, utc.mday, utc.time);
}
} // namespace DateTime
} // namespace PlatformAgnostic
#endif
<commit_msg>osx: fix timezone leak<commit_after>//-------------------------------------------------------------------------------------------------------
// Copyright (C) Microsoft. All rights reserved.
// Licensed under the MIT license. See LICENSE.txt file in the project root for full license information.
//-------------------------------------------------------------------------------------------------------
#ifndef __APPLE__
// todo: for BSD consider moving this file into macOS folder
#include "../Linux/DateTime.cpp"
#else
#include "Common.h"
#include "ChakraPlatform.h"
#include <CoreFoundation/CFDate.h>
#include <CoreFoundation/CFTimeZone.h>
namespace PlatformAgnostic
{
namespace DateTime
{
const WCHAR *Utility::GetStandardName(size_t *nameLength, const DateTime::YMD *ymd)
{
AssertMsg(ymd != NULL, "xplat needs DateTime::YMD is defined for this call");
double tv = Js::DateUtilities::TvFromDate(ymd->year, ymd->mon, ymd->mday, ymd->time);
int64_t absoluteTime = tv / 1000;
absoluteTime -= kCFAbsoluteTimeIntervalSince1970;
CFTimeZoneRef timeZone = CFTimeZoneCopySystem();
int offset = (int)CFTimeZoneGetSecondsFromGMT(timeZone, (CFAbsoluteTime)absoluteTime);
absoluteTime -= offset;
char tz_name[128];
CFStringRef abbr = CFTimeZoneCopyAbbreviation(timeZone, absoluteTime);
CFRelease(timeZone);
CFStringGetCString(abbr, tz_name, sizeof(tz_name), kCFStringEncodingUTF16);
wcscpy_s(data.standardName, 32, reinterpret_cast<WCHAR*>(tz_name));
data.standardNameLength = CFStringGetLength(abbr);
CFRelease(abbr);
*nameLength = data.standardNameLength;
return data.standardName;
}
const WCHAR *Utility::GetDaylightName(size_t *nameLength, const DateTime::YMD *ymd)
{
// xplat only gets the actual zone name for the given date
return GetStandardName(nameLength, ymd);
}
static time_t IsDST(double tv, int *offset)
{
CFTimeZoneRef timeZone = CFTimeZoneCopySystem();
int64_t absoluteTime = tv / 1000;
absoluteTime -= kCFAbsoluteTimeIntervalSince1970;
*offset = (int)CFTimeZoneGetSecondsFromGMT(timeZone, (CFAbsoluteTime)absoluteTime);
time_t result = CFTimeZoneIsDaylightSavingTime(timeZone, (CFAbsoluteTime)absoluteTime);
CFRelease(timeZone);
return result;
}
static void YMDLocalToUtc(double localtv, YMD *utc)
{
int mOffset = 0;
bool isDST = IsDST(localtv, &mOffset);
localtv -= DateTimeTicks_PerSecond * mOffset;
Js::DateUtilities::GetYmdFromTv(localtv, utc);
}
static void YMDUtcToLocal(double utctv, YMD *local,
int &bias, int &offset, bool &isDaylightSavings)
{
int mOffset = 0;
bool isDST = IsDST(utctv, &mOffset);
utctv += DateTimeTicks_PerSecond * mOffset;
Js::DateUtilities::GetYmdFromTv(utctv, local);
isDaylightSavings = isDST;
bias = mOffset / 60;
offset = bias;
}
// DaylightTimeHelper ******
double DaylightTimeHelper::UtcToLocal(double utcTime, int &bias,
int &offset, bool &isDaylightSavings)
{
YMD local;
YMDUtcToLocal(utcTime, &local, bias, offset, isDaylightSavings);
return Js::DateUtilities::TvFromDate(local.year, local.mon, local.mday, local.time);
}
double DaylightTimeHelper::LocalToUtc(double localTime)
{
YMD utc;
YMDLocalToUtc(localTime, &utc);
return Js::DateUtilities::TvFromDate(utc.year, utc.mon, utc.mday, utc.time);
}
} // namespace DateTime
} // namespace PlatformAgnostic
#endif
<|endoftext|>
|
<commit_before>#ifndef __Z2H_PARSER__
#define __Z2H_PARSER__ = 1
#include <cmath>
#include <string>
#include <vector>
#include <fstream>
#include <iostream>
#include <stddef.h>
#include <sys/stat.h>
#include <functional>
#include "token.hpp"
#include "symbol.hpp"
#include "binder.hpp"
using namespace std::placeholders;
namespace z2h {
template <typename TAst>
class Token;
template <typename TAst>
class Symbol;
template <typename TAst>
class Grammar;
class ParserException : public std::exception {
std::string _message;
public:
ParserException(const std::string &message)
: _message(message) {}
virtual const char * what() const throw() {
return _message.c_str();
}
};
template <typename TAst, typename TParser>
struct Parser : public Binder<TAst, TParser> {
std::string source;
size_t position;
std::vector<Token<TAst> *> tokens;
size_t index;
~Parser() {
while (!tokens.empty())
delete tokens.back(), tokens.pop_back();
}
Parser()
: source("")
, position(0)
, tokens({})
, index(0) {
}
// Symbols must be defined by the inheriting parser
virtual std::vector<Symbol<TAst> *> Symbols() = 0;
std::string Load(const std::string &filename) {
struct stat buffer;
if (stat (filename.c_str(), &buffer) != 0)
ParserException(filename + " doesn't exist or is unreadable");
std::ifstream file(filename);
std::string text((std::istreambuf_iterator<char>(file)), std::istreambuf_iterator<char>());
return text;
}
Token<TAst> * Take(Token<TAst> *token) {
tokens.push_back(token);
return token;
}
Token<TAst> * Emit() {
if (index < tokens.size()) {
return tokens[index++];
}
return Scan();
}
Token<TAst> * Scan() {
size_t end = position;
Symbol<TAst> *match = nullptr;
bool skip = false;
if (position < source.length()) {
std::cout << "position: " << position << std::endl;
std::cout << "Symbols().size(): " << Symbols().size() << std::endl;
for (auto symbol : Symbols()) {
std::cout << "symbol: " << *symbol << std::endl;
long delta = symbol->Scan(symbol, source.substr(position, source.length() - position), position);
if (delta) {
std::cout << "found: " << source.substr(position, abs(delta) ) << std::endl;
if (abs(delta) > 0 || (match != nullptr && symbol->lbp > match->lbp && position + abs(delta) == end)) {
match = symbol;
end = position + abs(delta);
skip = delta < 0;
}
}
}
if (position == end) {
throw ParserException("Parser::Scan: invalid symbol");
}
std::cout << "match: " << *match << std::endl;
return new Token<TAst>(match, source, position, end - position, skip);
}
std::cout << "failed to match anything" << std::endl;
return new Token<TAst>(); //eof
}
TAst ParseFile(const std::string &filename) {
auto source = Load(filename);
return Parse(source);
}
TAst Parse(std::string source) {
this->source = source;
return Expression();
}
TAst Expression(size_t rbp = 0) {
auto *curr = Consume();
if (curr->symbol->type) {
std::cout << "first used" << std::endl;
return nullptr;
}
TAst left = curr->symbol->Nud(curr);
auto *next = LookAhead(1);
if (next->symbol->type) {
std::cout << "second used" << std::endl;
return left;
}
while (rbp < next->symbol->lbp) {
next = Consume();
if (next->symbol->type) {
std::cout << "third used" << std::endl;
return left;
}
left = next->symbol->Led(left, next);
}
return left;
}
TAst Statement() {
auto *la1 = LookAhead(1);
if (la1->symbol->Std) {
Consume();
return la1->symbol->Std();
}
auto ast = Expression();
Consume(1, "EndOfStatement expected!");
return ast;
}
Token<TAst> * LookAhead(size_t distance) {
if (distance == 0)
return tokens[index];
while(distance > tokens.size() - index) {
auto *token = Scan();
if (token->skip) {
position += token->length;
continue;
}
Take(Scan());
}
return Emit();
}
Token<TAst> * Consume() {
LookAhead(1);
auto curr = Emit();
position += curr->length;
return curr;
}
Token<TAst> * Consume(const size_t &expected, const std::string &message) {
auto token = Consume();
if (token->symbol->type != expected)
throw ParserException(message);
return token;
}
size_t Line() {
return 0;
}
size_t Column() {
return 0;
}
};
}
#endif /*__Z2H_PARSER__*/
<commit_msg>changed debug printing... -sai<commit_after>#ifndef __Z2H_PARSER__
#define __Z2H_PARSER__ = 1
#include <cmath>
#include <string>
#include <vector>
#include <fstream>
#include <iostream>
#include <stddef.h>
#include <sys/stat.h>
#include <functional>
#include "token.hpp"
#include "symbol.hpp"
#include "binder.hpp"
using namespace std::placeholders;
namespace z2h {
template <typename TAst>
class Token;
template <typename TAst>
class Symbol;
template <typename TAst>
class Grammar;
class ParserException : public std::exception {
std::string _message;
public:
ParserException(const std::string &message)
: _message(message) {}
virtual const char * what() const throw() {
return _message.c_str();
}
};
template <typename TAst, typename TParser>
struct Parser : public Binder<TAst, TParser> {
std::string source;
size_t position;
std::vector<Token<TAst> *> tokens;
size_t index;
~Parser() {
while (!tokens.empty())
delete tokens.back(), tokens.pop_back();
}
Parser()
: source("")
, position(0)
, tokens({})
, index(0) {
}
// Symbols must be defined by the inheriting parser
virtual std::vector<Symbol<TAst> *> Symbols() = 0;
std::string Load(const std::string &filename) {
struct stat buffer;
if (stat (filename.c_str(), &buffer) != 0)
ParserException(filename + " doesn't exist or is unreadable");
std::ifstream file(filename);
std::string text((std::istreambuf_iterator<char>(file)), std::istreambuf_iterator<char>());
return text;
}
Token<TAst> * Take(Token<TAst> *token) {
tokens.push_back(token);
return token;
}
Token<TAst> * Emit() {
if (index < tokens.size()) {
return tokens[index++];
}
return Scan();
}
Token<TAst> * Scan() {
size_t end = position;
Symbol<TAst> *match = nullptr;
bool skip = false;
if (position < source.length()) {
for (auto symbol : Symbols()) {
long delta = symbol->Scan(symbol, source.substr(position, source.length() - position), position);
if (delta) {
if (abs(delta) > 0 || (match != nullptr && symbol->lbp > match->lbp && position + abs(delta) == end)) {
match = symbol;
end = position + abs(delta);
skip = delta < 0;
}
}
}
if (position == end) {
throw ParserException("Parser::Scan: invalid symbol");
}
return new Token<TAst>(match, source, position, end - position, skip);
}
std::cout << "failed to match anything" << std::endl;
return new Token<TAst>(); //eof
}
TAst ParseFile(const std::string &filename) {
auto source = Load(filename);
return Parse(source);
}
TAst Parse(std::string source) {
this->source = source;
return Expression();
}
TAst Expression(size_t rbp = 0) {
auto *curr = Consume();
std::cout << "curr: " << *curr << std::endl;
if (nullptr == curr->symbol->Nud)
throw ParserException("unexpected: nullptr == Nud");
TAst left = curr->symbol->Nud(curr);
auto *next = LookAhead(1);
std::cout << "next: " << *next << std::endl;
while (rbp < next->symbol->lbp) {
next = Consume();
std::cout << "inner next: " << *next << std::endl;
left = next->symbol->Led(left, next);
std::cout << "left: " << left->Print() << std::endl;
}
return left;
}
TAst Statement() {
auto *la1 = LookAhead(1);
if (la1->symbol->Std) {
Consume();
return la1->symbol->Std();
}
auto ast = Expression();
Consume(1, "EndOfStatement expected!");
return ast;
}
Token<TAst> * LookAhead(size_t distance) {
if (distance == 0)
return tokens[index];
while(distance > tokens.size() - index) {
auto *token = Scan();
if (token->skip) {
position += token->length;
continue;
}
Take(Scan());
}
return Emit();
}
Token<TAst> * Consume() {
LookAhead(1);
auto curr = Emit();
position += curr->length;
return curr;
}
Token<TAst> * Consume(const size_t &expected, const std::string &message) {
auto token = Consume();
if (token->symbol->type != expected)
throw ParserException(message);
return token;
}
size_t Line() {
return 0;
}
size_t Column() {
return 0;
}
};
}
#endif /*__Z2H_PARSER__*/
<|endoftext|>
|
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.