hexsha
stringlengths 40
40
| size
int64 7
1.05M
| ext
stringclasses 13
values | lang
stringclasses 1
value | max_stars_repo_path
stringlengths 4
269
| max_stars_repo_name
stringlengths 5
108
| max_stars_repo_head_hexsha
stringlengths 40
40
| max_stars_repo_licenses
sequencelengths 1
9
| max_stars_count
int64 1
191k
⌀ | max_stars_repo_stars_event_min_datetime
stringlengths 24
24
⌀ | max_stars_repo_stars_event_max_datetime
stringlengths 24
24
⌀ | max_issues_repo_path
stringlengths 4
269
| max_issues_repo_name
stringlengths 5
116
| max_issues_repo_head_hexsha
stringlengths 40
40
| max_issues_repo_licenses
sequencelengths 1
9
| max_issues_count
int64 1
67k
⌀ | max_issues_repo_issues_event_min_datetime
stringlengths 24
24
⌀ | max_issues_repo_issues_event_max_datetime
stringlengths 24
24
⌀ | max_forks_repo_path
stringlengths 4
269
| max_forks_repo_name
stringlengths 5
116
| max_forks_repo_head_hexsha
stringlengths 40
40
| max_forks_repo_licenses
sequencelengths 1
9
| max_forks_count
int64 1
105k
⌀ | max_forks_repo_forks_event_min_datetime
stringlengths 24
24
⌀ | max_forks_repo_forks_event_max_datetime
stringlengths 24
24
⌀ | content
stringlengths 7
1.05M
| avg_line_length
float64 1.21
330k
| max_line_length
int64 6
990k
| alphanum_fraction
float64 0.01
0.99
| author_id
stringlengths 2
40
|
---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|
9cbb8ad66a5af0377ccab696a2c6d5093cdb3095 | 4,975 | cc | C++ | mindspore/lite/src/runtime/kernel/opencl/kernel/gl_to_cl.cc | PowerOlive/mindspore | bda20724a94113cedd12c3ed9083141012da1f15 | [
"Apache-2.0"
] | null | null | null | mindspore/lite/src/runtime/kernel/opencl/kernel/gl_to_cl.cc | PowerOlive/mindspore | bda20724a94113cedd12c3ed9083141012da1f15 | [
"Apache-2.0"
] | null | null | null | mindspore/lite/src/runtime/kernel/opencl/kernel/gl_to_cl.cc | PowerOlive/mindspore | bda20724a94113cedd12c3ed9083141012da1f15 | [
"Apache-2.0"
] | null | null | null | /**
* Copyright 2021 Huawei Technologies Co., Ltd
*
* 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.
*/
#ifdef ENABLE_OPENGL_TEXTURE
#include "src/runtime/kernel/opencl/kernel/gl_to_cl.h"
#include <map>
#include <string>
#include "include/errorcode.h"
#include "src/kernel_registry.h"
#include "src/runtime/kernel/opencl/cl/gl_to_cl.cl.inc"
namespace mindspore::kernel {
int GLToCLOpenCLKernel::CheckSpecs() { return RET_OK; }
int GLToCLOpenCLKernel::PreProcess() {
if (this->out_mem_type_ == lite::opencl::MemType::IMG) return OpenCLKernel::PreProcess();
auto ret = ReSize();
if (ret != RET_OK) {
return ret;
}
return RET_OK;
}
int GLToCLOpenCLKernel::SetConstArgs() { return RET_OK; }
void GLToCLOpenCLKernel::SetGlobalLocal() {
global_size_ = {W_ * UP_DIV(C_, C4NUM), N_ * H_};
local_size_ = {1, 1};
OpenCLKernel::AlignGlobalLocal(global_size_, local_size_);
}
int GLToCLOpenCLKernel::Prepare() {
auto out_tensor = out_tensors_.front();
auto in_tensor = in_tensors_.front();
std::string kernel_name;
if (out_mem_type_ == lite::opencl::MemType::IMG) {
kernel_name = "GLTexture2D_to_IMG";
auto output = GpuTensorInfo(out_tensor);
N_ = output.N;
H_ = output.H;
W_ = output.W;
C_ = output.C;
} else {
kernel_name = "IMG_to_GLTexture2D";
auto input = GpuTensorInfo(in_tensor);
N_ = input.N;
H_ = input.H;
W_ = input.W;
C_ = input.C;
}
this->set_name(kernel_name);
const std::string program_name = "GLTexture2D_to_img";
std::string source = gl_to_cl_source;
if (!ocl_runtime_->LoadSource(program_name, source)) {
MS_LOG(ERROR) << "Load source failed.";
return RET_ERROR;
}
auto ret = ocl_runtime_->BuildKernel(kernel_, program_name, kernel_name);
if (ret != RET_OK) {
MS_LOG(ERROR) << "Build kernel failed.";
return ret;
}
SetGlobalLocal();
if (SetConstArgs() != RET_OK) {
MS_LOG(ERROR) << "SeConstArgs failed.";
return RET_ERROR;
}
MS_LOG(DEBUG) << kernel_name << " Init Done!";
return RET_OK;
}
int GLToCLOpenCLKernel::Run() {
MS_LOG(DEBUG) << this->name() << " Running!";
cl::Context *context = ocl_runtime_->Context();
auto dst_mem_type = out_mem_type_;
cl_int status;
if (dst_mem_type == lite::opencl::MemType::IMG) {
auto in_tensor = in_tensors_.front();
auto data_type = in_tensor->data_type();
if (data_type != kNumberTypeGLUInt) {
MS_LOG(ERROR) << "Unsupported data type " << data_type;
return RET_ERROR;
}
cl_GLuint *gl_texture_id = reinterpret_cast<cl_GLuint *>(in_tensor->data());
auto img_gl = cl::ImageGL(*context, CL_MEM_READ_ONLY, GL_TEXTURE_2D, 0, *gl_texture_id, &status);
if (status != CL_SUCCESS) {
MS_LOG(ERROR) << "Create ImageGL failed : " << status << std::endl;
return RET_ERROR;
}
if (kernel_.setArg(0, sizeof(cl_mem), &img_gl) != CL_SUCCESS) {
MS_LOG(ERROR) << "SetKernelArg failed.";
return RET_ERROR;
}
if (ocl_runtime_->SetKernelArg(kernel_, 1, out_tensors_.front()->data(),
(dst_mem_type == lite::opencl::MemType::BUF)) != CL_SUCCESS) {
MS_LOG(ERROR) << "SetKernelArg failed.";
return RET_ERROR;
}
if (ocl_runtime_->RunKernel(kernel_, global_range_, local_range_, nullptr, &event_) != RET_OK) {
MS_LOG(ERROR) << "RunKernel failed.";
return RET_ERROR;
}
} else {
auto out_tensor = out_tensors_.front();
cl_GLuint *gl_texture_id = reinterpret_cast<cl_GLuint *>(out_tensor->data());
auto img_gl = cl::ImageGL(*context, CL_MEM_WRITE_ONLY, GL_TEXTURE_2D, 0, *gl_texture_id, &status);
if (status != CL_SUCCESS) {
MS_LOG(ERROR) << "Create ImageGL failed : " << status << std::endl;
return RET_ERROR;
}
if (ocl_runtime_->SetKernelArg(kernel_, 0, in_tensors_.front()->data()) != CL_SUCCESS) {
MS_LOG(ERROR) << "SetKernelArg failed.";
return RET_ERROR;
}
if (kernel_.setArg(1, sizeof(cl_mem), &img_gl) != CL_SUCCESS) {
MS_LOG(ERROR) << "SetKernelArg failed.";
return RET_ERROR;
}
if (ocl_runtime_->RunKernel(kernel_, global_range_, local_range_, nullptr, &event_) != RET_OK) {
MS_LOG(ERROR) << "RunKernel failed.";
return RET_ERROR;
}
}
return RET_OK;
}
int GLToCLOpenCLKernel::InferShape() {
if (!InferShapeDone()) {
out_tensors_.front()->set_shape(in_tensors_.front()->shape());
}
return RET_OK;
}
} // namespace mindspore::kernel
#endif
| 32.730263 | 102 | 0.66995 | PowerOlive |
9cbdf76959e02f4f0ea1003b30ed05b043de9ede | 31,578 | cpp | C++ | be/src/exec/tablet_sink.cpp | Xuxue1/incubator-doris | 3ea12dd5932b90ea949782e7ebf6a282cb75652b | [
"Apache-2.0"
] | null | null | null | be/src/exec/tablet_sink.cpp | Xuxue1/incubator-doris | 3ea12dd5932b90ea949782e7ebf6a282cb75652b | [
"Apache-2.0"
] | null | null | null | be/src/exec/tablet_sink.cpp | Xuxue1/incubator-doris | 3ea12dd5932b90ea949782e7ebf6a282cb75652b | [
"Apache-2.0"
] | null | null | null | // 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.
#include "exec/tablet_sink.h"
#include <sstream>
#include "exprs/expr.h"
#include "runtime/exec_env.h"
#include "runtime/row_batch.h"
#include "runtime/runtime_state.h"
#include "runtime/tuple_row.h"
#include "util/brpc_stub_cache.h"
#include "util/uid_util.h"
#include "service/brpc.h"
namespace doris {
namespace stream_load {
NodeChannel::NodeChannel(OlapTableSink* parent, int64_t index_id,
int64_t node_id, int32_t schema_hash)
: _parent(parent), _index_id(index_id),
_node_id(node_id), _schema_hash(schema_hash) {
}
NodeChannel::~NodeChannel() {
if (_open_closure != nullptr) {
if (_open_closure->unref()) {
delete _open_closure;
}
_open_closure = nullptr;
}
if (_add_batch_closure != nullptr) {
if (_add_batch_closure->unref()) {
delete _add_batch_closure;
}
_add_batch_closure = nullptr;
}
_add_batch_request.release_id();
}
Status NodeChannel::init(RuntimeState* state) {
_tuple_desc = _parent->_output_tuple_desc;
_node_info = _parent->_nodes_info->find_node(_node_id);
if (_node_info == nullptr) {
std::stringstream ss;
ss << "unknown node id, id=" << _node_id;
return Status::InternalError(ss.str());
}
RowDescriptor row_desc(_tuple_desc, false);
_batch.reset(new RowBatch(row_desc, state->batch_size(), _parent->_mem_tracker));
_stub = state->exec_env()->brpc_stub_cache()->get_stub(
_node_info->host, _node_info->brpc_port);
if (_stub == nullptr) {
LOG(WARNING) << "Get rpc stub failed, host=" << _node_info->host
<< ", port=" << _node_info->brpc_port;
return Status::InternalError("get rpc stub failed");
}
// Initialize _add_batch_request
_add_batch_request.set_allocated_id(&_parent->_load_id);
_add_batch_request.set_index_id(_index_id);
_add_batch_request.set_sender_id(_parent->_sender_id);
return Status::OK();
}
void NodeChannel::open() {
PTabletWriterOpenRequest request;
request.set_allocated_id(&_parent->_load_id);
request.set_index_id(_index_id);
request.set_txn_id(_parent->_txn_id);
request.set_allocated_schema(_parent->_schema->to_protobuf());
for (auto& tablet : _all_tablets) {
auto ptablet = request.add_tablets();
ptablet->set_partition_id(tablet.partition_id);
ptablet->set_tablet_id(tablet.tablet_id);
}
request.set_num_senders(_parent->_num_senders);
request.set_need_gen_rollup(_parent->_need_gen_rollup);
_open_closure = new RefCountClosure<PTabletWriterOpenResult>();
_open_closure->ref();
// This ref is for RPC's reference
_open_closure->ref();
_open_closure->cntl.set_timeout_ms(_rpc_timeout_ms);
_stub->tablet_writer_open(&_open_closure->cntl,
&request,
&_open_closure->result,
_open_closure);
request.release_id();
request.release_schema();
}
Status NodeChannel::open_wait() {
_open_closure->join();
if (_open_closure->cntl.Failed()) {
LOG(WARNING) << "failed to open tablet writer, error="
<< berror(_open_closure->cntl.ErrorCode())
<< ", error_text=" << _open_closure->cntl.ErrorText();
return Status::InternalError("failed to open tablet writer");
}
Status status(_open_closure->result.status());
if (_open_closure->unref()) {
delete _open_closure;
}
_open_closure = nullptr;
// add batch closure
_add_batch_closure = new RefCountClosure<PTabletWriterAddBatchResult>();
_add_batch_closure->ref();
return status;
}
Status NodeChannel::add_row(Tuple* input_tuple, int64_t tablet_id) {
auto row_no = _batch->add_row();
if (row_no == RowBatch::INVALID_ROW_INDEX) {
RETURN_IF_ERROR(_send_cur_batch());
row_no = _batch->add_row();
}
DCHECK_NE(row_no, RowBatch::INVALID_ROW_INDEX);
auto tuple = input_tuple->deep_copy(*_tuple_desc, _batch->tuple_data_pool());
_batch->get_row(row_no)->set_tuple(0, tuple);
_batch->commit_last_row();
_add_batch_request.add_tablet_ids(tablet_id);
return Status::OK();
}
Status NodeChannel::close(RuntimeState* state) {
auto st = _close(state);
_batch.reset();
return st;
}
Status NodeChannel::_close(RuntimeState* state) {
RETURN_IF_ERROR(_wait_in_flight_packet());
return _send_cur_batch(true);
}
Status NodeChannel::close_wait(RuntimeState* state) {
RETURN_IF_ERROR(_wait_in_flight_packet());
Status status(_add_batch_closure->result.status());
if (status.ok()) {
for (auto& tablet : _add_batch_closure->result.tablet_vec()) {
TTabletCommitInfo commit_info;
commit_info.tabletId = tablet.tablet_id();
commit_info.backendId = _node_id;
state->tablet_commit_infos().emplace_back(std::move(commit_info));
}
}
// clear batch after sendt
_batch.reset();
return status;
}
void NodeChannel::cancel() {
// Do we need to wait last rpc finished???
PTabletWriterCancelRequest request;
request.set_allocated_id(&_parent->_load_id);
request.set_index_id(_index_id);
request.set_sender_id(_parent->_sender_id);
auto closure = new RefCountClosure<PTabletWriterCancelResult>();
closure->ref();
closure->cntl.set_timeout_ms(_rpc_timeout_ms);
_stub->tablet_writer_cancel(&closure->cntl,
&request,
&closure->result,
closure);
request.release_id();
// reset batch
_batch.reset();
}
Status NodeChannel::_wait_in_flight_packet() {
if (!_has_in_flight_packet) {
return Status::OK();
}
SCOPED_RAW_TIMER(_parent->mutable_wait_in_flight_packet_ns());
_add_batch_closure->join();
_has_in_flight_packet = false;
if (_add_batch_closure->cntl.Failed()) {
LOG(WARNING) << "failed to send batch, error="
<< berror(_add_batch_closure->cntl.ErrorCode())
<< ", error_text=" << _add_batch_closure->cntl.ErrorText();
return Status::InternalError("failed to send batch");
}
return {_add_batch_closure->result.status()};
}
Status NodeChannel::_send_cur_batch(bool eos) {
RETURN_IF_ERROR(_wait_in_flight_packet());
// tablet_ids has already set when add row
_add_batch_request.set_eos(eos);
_add_batch_request.set_packet_seq(_next_packet_seq);
if (_batch->num_rows() > 0) {
SCOPED_RAW_TIMER(_parent->mutable_serialize_batch_ns());
_batch->serialize(_add_batch_request.mutable_row_batch());
}
_add_batch_closure->ref();
_add_batch_closure->cntl.Reset();
_add_batch_closure->cntl.set_timeout_ms(_rpc_timeout_ms);
if (eos) {
for (auto pid : _parent->_partition_ids) {
_add_batch_request.add_partition_ids(pid);
}
}
_stub->tablet_writer_add_batch(&_add_batch_closure->cntl,
&_add_batch_request,
&_add_batch_closure->result,
_add_batch_closure);
_add_batch_request.clear_tablet_ids();
_add_batch_request.clear_row_batch();
_add_batch_request.clear_partition_ids();
_has_in_flight_packet = true;
_next_packet_seq++;
_batch->reset();
return Status::OK();
}
IndexChannel::~IndexChannel() {
}
Status IndexChannel::init(RuntimeState* state,
const std::vector<TTabletWithPartition>& tablets) {
// nodeId -> tabletIds
std::map<int64_t, std::vector<int64_t>> tablets_by_node;
for (auto& tablet : tablets) {
auto location = _parent->_location->find_tablet(tablet.tablet_id);
if (location == nullptr) {
LOG(WARNING) << "unknow tablet, tablet_id=" << tablet.tablet_id;
return Status::InternalError("unknown tablet");
}
std::vector<NodeChannel*> channels;
for (auto& node_id : location->node_ids) {
NodeChannel* channel = nullptr;
auto it = _node_channels.find(node_id);
if (it == std::end(_node_channels)) {
channel = _parent->_pool->add(
new NodeChannel(_parent, _index_id, node_id, _schema_hash));
_node_channels.emplace(node_id, channel);
} else {
channel = it->second;
}
channel->add_tablet(tablet);
channels.push_back(channel);
}
_channels_by_tablet.emplace(tablet.tablet_id, std::move(channels));
}
for (auto& it : _node_channels) {
RETURN_IF_ERROR(it.second->init(state));
}
return Status::OK();
}
Status IndexChannel::open() {
for (auto& it : _node_channels) {
it.second->open();
}
for (auto& it : _node_channels) {
auto channel = it.second;
auto st = channel->open_wait();
if (!st.ok()) {
LOG(WARNING) << "tablet open failed, load_id=" << _parent->_load_id
<< ", node=" << channel->node_info()->host
<< ":" << channel->node_info()->brpc_port
<< ", errmsg=" << st.get_error_msg();
if (_handle_failed_node(channel)) {
LOG(WARNING) << "open failed, load_id=" << _parent->_load_id;
return st;
}
}
}
return Status::OK();
}
Status IndexChannel::add_row(Tuple* tuple, int64_t tablet_id) {
auto it = _channels_by_tablet.find(tablet_id);
DCHECK(it != std::end(_channels_by_tablet)) << "unknown tablet, tablet_id=" << tablet_id;
for (auto channel : it->second) {
if (channel->already_failed()) {
continue;
}
auto st = channel->add_row(tuple, tablet_id);
if (!st.ok()) {
LOG(WARNING) << "NodeChannel add row failed, load_id=" << _parent->_load_id
<< ", tablet_id=" << tablet_id
<< ", node=" << channel->node_info()->host
<< ":" << channel->node_info()->brpc_port
<< ", errmsg=" << st.get_error_msg();
if (_handle_failed_node(channel)) {
LOG(WARNING) << "add row failed, load_id=" << _parent->_load_id;
return st;
}
}
}
return Status::OK();
}
Status IndexChannel::close(RuntimeState* state) {
std::vector<NodeChannel*> need_wait_channels;
need_wait_channels.reserve(_node_channels.size());
Status close_status;
for (auto& it : _node_channels) {
auto channel = it.second;
if (channel->already_failed() || !close_status.ok()) {
channel->cancel();
continue;
}
auto st = channel->close(state);
if (st.ok()) {
need_wait_channels.push_back(channel);
} else {
LOG(WARNING) << "close node channel failed, load_id=" << _parent->_load_id
<< ", node=" << channel->node_info()->host
<< ":" << channel->node_info()->brpc_port
<< ", errmsg=" << st.get_error_msg();
if (_handle_failed_node(channel)) {
LOG(WARNING) << "close failed, load_id=" << _parent->_load_id;
close_status = st;
}
}
}
if (close_status.ok()) {
for (auto channel : need_wait_channels) {
auto st = channel->close_wait(state);
if (!st.ok()) {
LOG(WARNING) << "close_wait node channel failed, load_id=" << _parent->_load_id
<< ", node=" << channel->node_info()->host
<< ":" << channel->node_info()->brpc_port
<< ", errmsg=" << st.get_error_msg();
if (_handle_failed_node(channel)) {
LOG(WARNING) << "close_wait failed, load_id=" << _parent->_load_id;
return st;
}
}
}
}
return close_status;
}
void IndexChannel::cancel() {
for (auto& it : _node_channels) {
it.second->cancel();
}
}
bool IndexChannel::_handle_failed_node(NodeChannel* channel) {
DCHECK(!channel->already_failed());
channel->set_failed();
_num_failed_channels++;
return _num_failed_channels >= ((_parent->_num_repicas + 1) / 2);
}
OlapTableSink::OlapTableSink(ObjectPool* pool,
const RowDescriptor& row_desc,
const std::vector<TExpr>& texprs,
Status* status)
: _pool(pool), _input_row_desc(row_desc), _filter_bitmap(1024) {
if (!texprs.empty()) {
*status = Expr::create_expr_trees(_pool, texprs, &_output_expr_ctxs);
}
}
OlapTableSink::~OlapTableSink() {
}
Status OlapTableSink::init(const TDataSink& t_sink) {
DCHECK(t_sink.__isset.olap_table_sink);
auto& table_sink = t_sink.olap_table_sink;
_load_id.set_hi(table_sink.load_id.hi);
_load_id.set_lo(table_sink.load_id.lo);
_txn_id = table_sink.txn_id;
_db_id = table_sink.db_id;
_table_id = table_sink.table_id;
_num_repicas = table_sink.num_replicas;
_need_gen_rollup = table_sink.need_gen_rollup;
_db_name = table_sink.db_name;
_table_name = table_sink.table_name;
_tuple_desc_id = table_sink.tuple_id;
_schema.reset(new OlapTableSchemaParam());
RETURN_IF_ERROR(_schema->init(table_sink.schema));
_partition = _pool->add(new OlapTablePartitionParam(_schema, table_sink.partition));
RETURN_IF_ERROR(_partition->init());
_location = _pool->add(new OlapTableLocationParam(table_sink.location));
_nodes_info = _pool->add(new DorisNodesInfo(table_sink.nodes_info));
return Status::OK();
}
Status OlapTableSink::prepare(RuntimeState* state) {
RETURN_IF_ERROR(DataSink::prepare(state));
_sender_id = state->per_fragment_instance_idx();
_num_senders = state->num_per_fragment_instances();
// profile must add to state's object pool
_profile = state->obj_pool()->add(new RuntimeProfile(_pool, "OlapTableSink"));
_mem_tracker = _pool->add(
new MemTracker(-1, "OlapTableSink", state->instance_mem_tracker()));
SCOPED_TIMER(_profile->total_time_counter());
// Prepare the exprs to run.
RETURN_IF_ERROR(Expr::prepare(_output_expr_ctxs, state,
_input_row_desc, _expr_mem_tracker.get()));
// get table's tuple descriptor
_output_tuple_desc = state->desc_tbl().get_tuple_descriptor(_tuple_desc_id);
if (_output_tuple_desc == nullptr) {
LOG(WARNING) << "unknown destination tuple descriptor, id=" << _tuple_desc_id;
return Status::InternalError("unknown destination tuple descriptor");
}
if (!_output_expr_ctxs.empty()) {
if (_output_expr_ctxs.size() != _output_tuple_desc->slots().size()) {
LOG(WARNING) << "number of exprs is not same with slots, num_exprs="
<< _output_expr_ctxs.size()
<< ", num_slots=" << _output_tuple_desc->slots().size();
return Status::InternalError("number of exprs is not same with slots");
}
for (int i = 0; i < _output_expr_ctxs.size(); ++i) {
if (!is_type_compatible(_output_expr_ctxs[i]->root()->type().type,
_output_tuple_desc->slots()[i]->type().type)) {
LOG(WARNING) << "type of exprs is not match slot's, expr_type="
<< _output_expr_ctxs[i]->root()->type().type
<< ", slot_type=" << _output_tuple_desc->slots()[i]->type().type
<< ", slot_name=" << _output_tuple_desc->slots()[i]->col_name();
return Status::InternalError("expr's type is not same with slot's");
}
}
}
_output_row_desc = _pool->add(new RowDescriptor(_output_tuple_desc, false));
_output_batch.reset(new RowBatch(*_output_row_desc, state->batch_size(), _mem_tracker));
_max_decimal_val.resize(_output_tuple_desc->slots().size());
_min_decimal_val.resize(_output_tuple_desc->slots().size());
_max_decimalv2_val.resize(_output_tuple_desc->slots().size());
_min_decimalv2_val.resize(_output_tuple_desc->slots().size());
// check if need validate batch
for (int i = 0; i < _output_tuple_desc->slots().size(); ++i) {
auto slot = _output_tuple_desc->slots()[i];
switch (slot->type().type) {
case TYPE_DECIMAL:
_max_decimal_val[i].to_max_decimal(slot->type().precision, slot->type().scale);
_min_decimal_val[i].to_min_decimal(slot->type().precision, slot->type().scale);
_need_validate_data = true;
break;
case TYPE_DECIMALV2:
_max_decimalv2_val[i].to_max_decimal(slot->type().precision, slot->type().scale);
_min_decimalv2_val[i].to_min_decimal(slot->type().precision, slot->type().scale);
_need_validate_data = true;
break;
case TYPE_CHAR:
case TYPE_VARCHAR:
case TYPE_DATE:
case TYPE_DATETIME:
_need_validate_data = true;
break;
default:
break;
}
}
// add all counter
_input_rows_counter = ADD_COUNTER(_profile, "RowsRead", TUnit::UNIT);
_output_rows_counter = ADD_COUNTER(_profile, "RowsReturned", TUnit::UNIT);
_filtered_rows_counter = ADD_COUNTER(_profile, "RowsFiltered", TUnit::UNIT);
_send_data_timer = ADD_TIMER(_profile, "SendDataTime");
_convert_batch_timer = ADD_TIMER(_profile, "ConvertBatchTime");
_validate_data_timer = ADD_TIMER(_profile, "ValidateDataTime");
_open_timer = ADD_TIMER(_profile, "OpenTime");
_close_timer = ADD_TIMER(_profile, "CloseTime");
_wait_in_flight_packet_timer = ADD_TIMER(_profile, "WaitInFlightPacketTime");
_serialize_batch_timer = ADD_TIMER(_profile, "SerializeBatchTime");
// open all channels
auto& partitions = _partition->get_partitions();
for (int i = 0; i < _schema->indexes().size(); ++i) {
// collect all tablets belong to this rollup
std::vector<TTabletWithPartition> tablets;
auto index = _schema->indexes()[i];
for (auto part : partitions) {
for (auto tablet : part->indexes[i].tablets) {
TTabletWithPartition tablet_with_partition;
tablet_with_partition.partition_id = part->id;
tablet_with_partition.tablet_id = tablet;
tablets.emplace_back(std::move(tablet_with_partition));
}
}
auto channel = _pool->add(new IndexChannel(this, index->index_id, index->schema_hash));
RETURN_IF_ERROR(channel->init(state, tablets));
_channels.emplace_back(channel);
}
return Status::OK();
}
Status OlapTableSink::open(RuntimeState* state) {
SCOPED_TIMER(_profile->total_time_counter());
SCOPED_TIMER(_open_timer);
// Prepare the exprs to run.
RETURN_IF_ERROR(Expr::open(_output_expr_ctxs, state));
for (auto channel : _channels) {
RETURN_IF_ERROR(channel->open());
}
return Status::OK();
}
Status OlapTableSink::send(RuntimeState* state, RowBatch* input_batch) {
SCOPED_TIMER(_profile->total_time_counter());
_number_input_rows += input_batch->num_rows();
RowBatch* batch = input_batch;
if (!_output_expr_ctxs.empty()) {
SCOPED_RAW_TIMER(&_convert_batch_ns);
_output_batch->reset();
_convert_batch(state, input_batch, _output_batch.get());
batch = _output_batch.get();
}
int num_invalid_rows = 0;
if (_need_validate_data) {
SCOPED_RAW_TIMER(&_validate_data_ns);
_filter_bitmap.Reset(batch->num_rows());
num_invalid_rows = _validate_data(state, batch, &_filter_bitmap);
_number_filtered_rows += num_invalid_rows;
}
SCOPED_RAW_TIMER(&_send_data_ns);
for (int i = 0; i < batch->num_rows(); ++i) {
Tuple* tuple = batch->get_row(i)->get_tuple(0);
if (num_invalid_rows > 0 && _filter_bitmap.Get(i)) {
continue;
}
const OlapTablePartition* partition = nullptr;
uint32_t dist_hash = 0;
if (!_partition->find_tablet(tuple, &partition, &dist_hash)) {
std::stringstream ss;
ss << "no partition for this tuple. tuple="
<< Tuple::to_string(tuple, *_output_tuple_desc);
#if BE_TEST
LOG(INFO) << ss.str();
#else
state->append_error_msg_to_file("", ss.str());
#endif
_number_filtered_rows++;
continue;
}
_partition_ids.emplace(partition->id);
uint32_t tablet_index = dist_hash % partition->num_buckets;
for (int j = 0; j < partition->indexes.size(); ++j) {
int64_t tablet_id = partition->indexes[j].tablets[tablet_index];
RETURN_IF_ERROR(_channels[j]->add_row(tuple, tablet_id));
_number_output_rows++;
}
}
return Status::OK();
}
Status OlapTableSink::close(RuntimeState* state, Status close_status) {
Status status = close_status;
if (status.ok()) {
// SCOPED_TIMER should only be called is status is ok.
// if status is not ok, this OlapTableSink may not be prepared,
// so the `_profile` may be null.
SCOPED_TIMER(_profile->total_time_counter());
{
SCOPED_TIMER(_close_timer);
for (auto channel : _channels) {
status = channel->close(state);
if (!status.ok()) {
LOG(WARNING) << "close channel failed, load_id=" << _load_id
<< ", txn_id=" << _txn_id;
}
}
}
COUNTER_SET(_input_rows_counter, _number_input_rows);
COUNTER_SET(_output_rows_counter, _number_output_rows);
COUNTER_SET(_filtered_rows_counter, _number_filtered_rows);
COUNTER_SET(_send_data_timer, _send_data_ns);
COUNTER_SET(_convert_batch_timer, _convert_batch_ns);
COUNTER_SET(_validate_data_timer, _validate_data_ns);
COUNTER_SET(_wait_in_flight_packet_timer, _wait_in_flight_packet_ns);
COUNTER_SET(_serialize_batch_timer, _serialize_batch_ns);
state->update_num_rows_load_filtered(_number_filtered_rows);
} else {
for (auto channel : _channels) {
channel->cancel();
}
}
Expr::close(_output_expr_ctxs, state);
_output_batch.reset();
return status;
}
void OlapTableSink::_convert_batch(RuntimeState* state, RowBatch* input_batch, RowBatch* output_batch) {
DCHECK_GE(output_batch->capacity(), input_batch->num_rows());
int commit_rows = 0;
for (int i = 0; i < input_batch->num_rows(); ++i) {
auto src_row = input_batch->get_row(i);
Tuple* dst_tuple = (Tuple*)output_batch->tuple_data_pool()->allocate(
_output_tuple_desc->byte_size());
bool exist_null_value_for_not_null_col = false;
for (int j = 0; j < _output_expr_ctxs.size(); ++j) {
auto src_val = _output_expr_ctxs[j]->get_value(src_row);
auto slot_desc = _output_tuple_desc->slots()[j];
if (slot_desc->is_nullable()) {
if (src_val == nullptr) {
dst_tuple->set_null(slot_desc->null_indicator_offset());
continue;
} else {
dst_tuple->set_not_null(slot_desc->null_indicator_offset());
}
} else {
if (src_val == nullptr) {
std::stringstream ss;
ss << "null value for not null column, column=" << slot_desc->col_name();
#if BE_TEST
LOG(INFO) << ss.str();
#else
state->append_error_msg_to_file("", ss.str());
#endif
exist_null_value_for_not_null_col = true;
_number_filtered_rows++;
break;
}
}
void* slot = dst_tuple->get_slot(slot_desc->tuple_offset());
RawValue::write(src_val, slot, slot_desc->type(), _output_batch->tuple_data_pool());
}
if (!exist_null_value_for_not_null_col) {
output_batch->get_row(commit_rows)->set_tuple(0, dst_tuple);
commit_rows++;
}
}
output_batch->commit_rows(commit_rows);
}
int OlapTableSink::_validate_data(RuntimeState* state, RowBatch* batch, Bitmap* filter_bitmap) {
int filtered_rows = 0;
for (int row_no = 0; row_no < batch->num_rows(); ++row_no) {
Tuple* tuple = batch->get_row(row_no)->get_tuple(0);
bool row_valid = true;
for (int i = 0; row_valid && i < _output_tuple_desc->slots().size(); ++i) {
SlotDescriptor* desc = _output_tuple_desc->slots()[i];
if (tuple->is_null(desc->null_indicator_offset())) {
continue;
}
void* slot = tuple->get_slot(desc->tuple_offset());
switch (desc->type().type) {
case TYPE_CHAR:
case TYPE_VARCHAR: {
// Fixed length string
StringValue* str_val = (StringValue*)slot;
if (str_val->len > desc->type().len) {
std::stringstream ss;
ss << "the length of input is too long than schema. "
<< "column_name: " << desc->col_name() << "; "
<< "input_str: [" << std::string(str_val->ptr, str_val->len) << "] "
<< "schema length: " << desc->type().len << "; "
<< "actual length: " << str_val->len << "; ";
#if BE_TEST
LOG(INFO) << ss.str();
#else
state->append_error_msg_to_file("", ss.str());
#endif
filtered_rows++;
row_valid = false;
filter_bitmap->Set(row_no, true);
continue;
}
// padding 0 to CHAR field
if (desc->type().type == TYPE_CHAR
&& str_val->len < desc->type().len) {
auto new_ptr = (char*)batch->tuple_data_pool()->allocate(desc->type().len);
memcpy(new_ptr, str_val->ptr, str_val->len);
memset(new_ptr + str_val->len, 0, desc->type().len - str_val->len);
str_val->ptr = new_ptr;
str_val->len = desc->type().len;
}
break;
}
case TYPE_DECIMAL: {
DecimalValue* dec_val = (DecimalValue*)slot;
if (dec_val->scale() > desc->type().scale) {
int code = dec_val->round(dec_val, desc->type().scale, HALF_UP);
if (code != E_DEC_OK) {
std::stringstream ss;
ss << "round one decimal failed.value=" << dec_val->to_string();
#if BE_TEST
LOG(INFO) << ss.str();
#else
state->append_error_msg_to_file("", ss.str());
#endif
filtered_rows++;
row_valid = false;
filter_bitmap->Set(row_no, true);
continue;
}
}
if (*dec_val > _max_decimal_val[i] || *dec_val < _min_decimal_val[i]) {
std::stringstream ss;
ss << "decimal value is not valid for defination, column=" << desc->col_name()
<< ", value=" << dec_val->to_string()
<< ", precision=" << desc->type().precision
<< ", scale=" << desc->type().scale;
#if BE_TEST
LOG(INFO) << ss.str();
#else
state->append_error_msg_to_file("", ss.str());
#endif
filtered_rows++;
row_valid = false;
filter_bitmap->Set(row_no, true);
continue;
}
break;
}
case TYPE_DECIMALV2: {
DecimalV2Value dec_val(reinterpret_cast<const PackedInt128*>(slot)->value);
if (dec_val.greater_than_scale(desc->type().scale)) {
int code = dec_val.round(&dec_val, desc->type().scale, HALF_UP);
reinterpret_cast<PackedInt128*>(slot)->value = dec_val.value();
if (code != E_DEC_OK) {
std::stringstream ss;
ss << "round one decimal failed.value=" << dec_val.to_string();
#if BE_TEST
LOG(INFO) << ss.str();
#else
state->append_error_msg_to_file("", ss.str());
#endif
filtered_rows++;
row_valid = false;
filter_bitmap->Set(row_no, true);
continue;
}
}
if (dec_val > _max_decimalv2_val[i] || dec_val < _min_decimalv2_val[i]) {
std::stringstream ss;
ss << "decimal value is not valid for defination, column=" << desc->col_name()
<< ", value=" << dec_val.to_string()
<< ", precision=" << desc->type().precision
<< ", scale=" << desc->type().scale;
#if BE_TEST
LOG(INFO) << ss.str();
#else
state->append_error_msg_to_file("", ss.str());
#endif
filtered_rows++;
row_valid = false;
filter_bitmap->Set(row_no, true);
continue;
}
break;
}
case TYPE_DATE:
case TYPE_DATETIME: {
static DateTimeValue s_min_value = DateTimeValue(19000101000000UL);
// static DateTimeValue s_max_value = DateTimeValue(99991231235959UL);
DateTimeValue* date_val = (DateTimeValue*)slot;
if (*date_val < s_min_value) {
std::stringstream ss;
ss << "datetime value is not valid, column=" << desc->col_name()
<< ", value=" << date_val->debug_string();
#if BE_TEST
LOG(INFO) << ss.str();
#else
state->append_error_msg_to_file("", ss.str());
#endif
filtered_rows++;
row_valid = false;
filter_bitmap->Set(row_no, true);
continue;
}
}
default:
break;
}
}
}
return filtered_rows;
}
}
}
| 38.416058 | 104 | 0.586991 | Xuxue1 |
9cbe30c285c0a5ceedf852f0e51262d3e9cefa12 | 9,915 | hxx | C++ | opencascade/Graphic3d_GraduatedTrihedron.hxx | mgreminger/OCP | 92eacb99497cd52b419c8a4a8ab0abab2330ed42 | [
"Apache-2.0"
] | null | null | null | opencascade/Graphic3d_GraduatedTrihedron.hxx | mgreminger/OCP | 92eacb99497cd52b419c8a4a8ab0abab2330ed42 | [
"Apache-2.0"
] | null | null | null | opencascade/Graphic3d_GraduatedTrihedron.hxx | mgreminger/OCP | 92eacb99497cd52b419c8a4a8ab0abab2330ed42 | [
"Apache-2.0"
] | null | null | null | // Created on: 2011-03-06
// Created by: Sergey ZERCHANINOV
// Copyright (c) 2011-2014 OPEN CASCADE SAS
//
// This file is part of Open CASCADE Technology software library.
//
// 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, with special exception defined in the file
// OCCT_LGPL_EXCEPTION.txt. Consult the file LICENSE_LGPL_21.txt included in OCCT
// distribution for complete text of the license and disclaimer of any warranty.
//
// Alternatively, this file may be used under the terms of Open CASCADE
// commercial license or contractual agreement.
#ifndef _Graphic3d_GraduatedTrihedron_HeaderFile
#define _Graphic3d_GraduatedTrihedron_HeaderFile
#include <Font_FontAspect.hxx>
#include <NCollection_Array1.hxx>
#include <Quantity_Color.hxx>
#include <Standard_Boolean.hxx>
#include <Standard_Integer.hxx>
#include <TCollection_AsciiString.hxx>
#include <TCollection_ExtendedString.hxx>
class Graphic3d_CView;
//! Defines the class of a graduated trihedron.
//! It contains main style parameters for implementation of graduated trihedron
//! @sa OpenGl_GraduatedTrihedron
class Graphic3d_GraduatedTrihedron
{
public:
//! Class that stores style for one graduated trihedron axis such as colors, lengths and customization flags.
//! It is used in Graphic3d_GraduatedTrihedron.
class AxisAspect
{
public:
AxisAspect (const TCollection_ExtendedString theName = "", const Quantity_Color theNameColor = Quantity_NOC_BLACK,
const Quantity_Color theColor = Quantity_NOC_BLACK,
const Standard_Integer theValuesOffset = 10, const Standard_Integer theNameOffset = 30,
const Standard_Integer theTickmarksNumber = 5, const Standard_Integer theTickmarksLength = 10,
const Standard_Boolean theToDrawName = Standard_True,
const Standard_Boolean theToDrawValues = Standard_True,
const Standard_Boolean theToDrawTickmarks = Standard_True)
: myName (theName),
myToDrawName (theToDrawName),
myToDrawTickmarks (theToDrawTickmarks),
myToDrawValues (theToDrawValues),
myNameColor (theNameColor),
myTickmarksNumber (theTickmarksNumber),
myTickmarksLength (theTickmarksLength),
myColor (theColor),
myValuesOffset (theValuesOffset),
myNameOffset (theNameOffset)
{ }
public:
void SetName (const TCollection_ExtendedString& theName) { myName = theName; }
const TCollection_ExtendedString& Name() const { return myName; }
Standard_Boolean ToDrawName() const { return myToDrawName; }
void SetDrawName (const Standard_Boolean theToDraw) { myToDrawName = theToDraw; }
Standard_Boolean ToDrawTickmarks() const { return myToDrawTickmarks; }
void SetDrawTickmarks (const Standard_Boolean theToDraw) { myToDrawTickmarks = theToDraw; }
Standard_Boolean ToDrawValues() const { return myToDrawValues; }
void SetDrawValues (const Standard_Boolean theToDraw) { myToDrawValues = theToDraw; }
const Quantity_Color& NameColor() const { return myNameColor; }
void SetNameColor (const Quantity_Color& theColor) { myNameColor = theColor; }
//! Color of axis and values
const Quantity_Color& Color() const { return myColor; }
//! Sets color of axis and values
void SetColor (const Quantity_Color& theColor) { myColor = theColor; }
Standard_Integer TickmarksNumber() const { return myTickmarksNumber; }
void SetTickmarksNumber (const Standard_Integer theValue) { myTickmarksNumber = theValue; }
Standard_Integer TickmarksLength() const { return myTickmarksLength; }
void SetTickmarksLength (const Standard_Integer theValue) { myTickmarksLength = theValue; }
Standard_Integer ValuesOffset() const { return myValuesOffset; }
void SetValuesOffset (const Standard_Integer theValue) { myValuesOffset = theValue; }
Standard_Integer NameOffset() const { return myNameOffset; }
void SetNameOffset (const Standard_Integer theValue) { myNameOffset = theValue; }
protected:
TCollection_ExtendedString myName;
Standard_Boolean myToDrawName;
Standard_Boolean myToDrawTickmarks;
Standard_Boolean myToDrawValues;
Quantity_Color myNameColor;
Standard_Integer myTickmarksNumber; //!< Number of splits along axes
Standard_Integer myTickmarksLength; //!< Length of tickmarks
Quantity_Color myColor; //!< Color of axis and values
Standard_Integer myValuesOffset; //!< Offset for drawing values
Standard_Integer myNameOffset; //!< Offset for drawing name of axis
};
public:
typedef void (*MinMaxValuesCallback) (Graphic3d_CView*);
public:
//! Default constructor
//! Constructs the default graduated trihedron with grid, X, Y, Z axes, and tickmarks
Graphic3d_GraduatedTrihedron (const TCollection_AsciiString& theNamesFont = "Arial",
const Font_FontAspect& theNamesStyle = Font_FA_Bold, const Standard_Integer theNamesSize = 12,
const TCollection_AsciiString& theValuesFont = "Arial",
const Font_FontAspect& theValuesStyle = Font_FA_Regular, const Standard_Integer theValuesSize = 12,
const Standard_ShortReal theArrowsLength = 30.0f, const Quantity_Color theGridColor = Quantity_NOC_WHITE,
const Standard_Boolean theToDrawGrid = Standard_True, const Standard_Boolean theToDrawAxes = Standard_True)
: myCubicAxesCallback (NULL),
myNamesFont (theNamesFont),
myNamesStyle (theNamesStyle),
myNamesSize (theNamesSize),
myValuesFont (theValuesFont),
myValuesStyle (theValuesStyle),
myValuesSize (theValuesSize),
myArrowsLength (theArrowsLength),
myGridColor (theGridColor),
myToDrawGrid (theToDrawGrid),
myToDrawAxes (theToDrawAxes),
myAxes(0, 2)
{
myAxes (0) = AxisAspect ("X", Quantity_NOC_RED, Quantity_NOC_RED);
myAxes (1) = AxisAspect ("Y", Quantity_NOC_GREEN, Quantity_NOC_GREEN);
myAxes (2) = AxisAspect ("Z", Quantity_NOC_BLUE1, Quantity_NOC_BLUE1);
}
public:
AxisAspect& ChangeXAxisAspect() { return myAxes(0); }
AxisAspect& ChangeYAxisAspect() { return myAxes(1); }
AxisAspect& ChangeZAxisAspect() { return myAxes(2); }
AxisAspect& ChangeAxisAspect (const Standard_Integer theIndex)
{
Standard_OutOfRange_Raise_if (theIndex < 0 || theIndex > 2, "Graphic3d_GraduatedTrihedron::ChangeAxisAspect: theIndex is out of bounds [0,2].");
return myAxes (theIndex);
}
const AxisAspect& XAxisAspect() const { return myAxes(0); }
const AxisAspect& YAxisAspect() const { return myAxes(1); }
const AxisAspect& ZAxisAspect() const { return myAxes(2); }
const AxisAspect& AxisAspectAt (const Standard_Integer theIndex) const
{
Standard_OutOfRange_Raise_if (theIndex < 0 || theIndex > 2, "Graphic3d_GraduatedTrihedron::AxisAspect: theIndex is out of bounds [0,2].");
return myAxes (theIndex);
}
Standard_ShortReal ArrowsLength() const { return myArrowsLength; }
void SetArrowsLength (const Standard_ShortReal theValue) { myArrowsLength = theValue; }
const Quantity_Color& GridColor() const { return myGridColor; }
void SetGridColor (const Quantity_Color& theColor) {myGridColor = theColor; }
Standard_Boolean ToDrawGrid() const { return myToDrawGrid; }
void SetDrawGrid (const Standard_Boolean theToDraw) { myToDrawGrid = theToDraw; }
Standard_Boolean ToDrawAxes() const { return myToDrawAxes; }
void SetDrawAxes (const Standard_Boolean theToDraw) { myToDrawAxes = theToDraw; }
const TCollection_AsciiString& NamesFont() const { return myNamesFont; }
void SetNamesFont (const TCollection_AsciiString& theFont) { myNamesFont = theFont; }
Font_FontAspect NamesFontAspect() const { return myNamesStyle; }
void SetNamesFontAspect (Font_FontAspect theAspect) { myNamesStyle = theAspect; }
Standard_Integer NamesSize() const { return myNamesSize; }
void SetNamesSize (const Standard_Integer theValue) { myNamesSize = theValue; }
const TCollection_AsciiString& ValuesFont () const { return myValuesFont; }
void SetValuesFont (const TCollection_AsciiString& theFont) { myValuesFont = theFont; }
Font_FontAspect ValuesFontAspect() const { return myValuesStyle; }
void SetValuesFontAspect (Font_FontAspect theAspect) { myValuesStyle = theAspect; }
Standard_Integer ValuesSize() const { return myValuesSize; }
void SetValuesSize (const Standard_Integer theValue) { myValuesSize = theValue; }
Standard_Boolean CubicAxesCallback(Graphic3d_CView* theView) const
{
if (myCubicAxesCallback != NULL)
{
myCubicAxesCallback (theView);
return Standard_True;
}
return Standard_False;
}
void SetCubicAxesCallback (const MinMaxValuesCallback theCallback) { myCubicAxesCallback = theCallback; }
protected:
MinMaxValuesCallback myCubicAxesCallback; //!< Callback function to define boundary box of displayed objects
TCollection_AsciiString myNamesFont; //!< Font name of names of axes: Courier, Arial, ...
Font_FontAspect myNamesStyle; //!< Style of names of axes: OSD_FA_Regular, OSD_FA_Bold,..
Standard_Integer myNamesSize; //!< Size of names of axes: 8, 10,..
protected:
TCollection_AsciiString myValuesFont; //!< Font name of values: Courier, Arial, ...
Font_FontAspect myValuesStyle; //!< Style of values: OSD_FA_Regular, OSD_FA_Bold, ...
Standard_Integer myValuesSize; //!< Size of values: 8, 10, 12, 14, ...
protected:
Standard_ShortReal myArrowsLength;
Quantity_Color myGridColor;
Standard_Boolean myToDrawGrid;
Standard_Boolean myToDrawAxes;
NCollection_Array1<AxisAspect> myAxes; //!< X, Y and Z axes parameters
};
#endif // Graphic3d_GraduatedTrihedron_HeaderFile
| 42.012712 | 148 | 0.741503 | mgreminger |
9cbf916c5c0e62e0ae3121a996046b06b986d0b4 | 5,119 | cpp | C++ | multiview/multiview_cpp/src/perceive/movie/ffmpeg.cpp | prcvlabs/multiview | 1a03e14855292967ffb0c0ec7fff855c5abbc9d2 | [
"Apache-2.0"
] | 5 | 2021-09-03T23:12:08.000Z | 2022-03-04T21:43:32.000Z | multiview/multiview_cpp/src/perceive/movie/ffmpeg.cpp | prcvlabs/multiview | 1a03e14855292967ffb0c0ec7fff855c5abbc9d2 | [
"Apache-2.0"
] | 3 | 2021-09-08T02:57:46.000Z | 2022-02-26T05:33:02.000Z | multiview/multiview_cpp/src/perceive/movie/ffmpeg.cpp | prcvlabs/multiview | 1a03e14855292967ffb0c0ec7fff855c5abbc9d2 | [
"Apache-2.0"
] | 2 | 2021-09-26T03:14:40.000Z | 2022-01-26T06:42:52.000Z |
#include "ffmpeg.hpp"
#include <opencv2/core/core.hpp>
#include <opencv2/highgui/highgui.hpp>
#include <boost/process.hpp>
#define This StreamingFFMpegEncoder
namespace perceive::movie
{
namespace bp = boost::process;
// ----------------------------------------------------- call ffmpeg to make mp4
//
int call_ffmpeg_to_make_mp4(const string_view input_fnames,
const real frame_duration,
const string_view output_fname) noexcept
{
const string command = format("ffmpeg -y -r {} -i {} -c:v libxvid -qscale:v 2 {} "
"1>/dev/null 2>/dev/null",
(1.0 / frame_duration),
input_fnames,
output_fname);
return system(command.c_str());
}
// -----------------------------------------------------
//
struct This::Pimpl
{
bp::pipe pipe;
bp::child subprocess;
vector<uint8_t> raw;
string output_fname;
int width = 0;
int height = 0;
real frame_rate; //
~Pimpl() { close(); }
void init(const string_view output_fname, int w, int h, real frame_rate)
{
this->output_fname = output_fname;
this->width = w;
this->height = h;
this->frame_rate = frame_rate;
raw.resize(size_t(width * 3)); // rgb
auto find_ffmpeg_exe = [&]() { // attempt to find the ffmpeg executable
const char* exe = "ffmpeg";
const auto path = bp::search_path(exe);
if(path.empty())
throw std::runtime_error(
format("failed to find executable '{}' on path, aborting", exe));
return path;
};
const auto exe_path = find_ffmpeg_exe();
// bp::std_out > stdout,
subprocess = bp::child(exe_path,
"-hide_banner", // really
"-y", // allow overwrite
"-f", // input format
"rawvideo",
"-pix_fmt", // input pixel format
"rgb24",
"-video_size", // input format
format("{}x{}", width, height),
"-r", // framerate
str(frame_rate),
"-i", // input
"-",
"-c:v", // video codec
"libxvid",
"-qscale:v", // quality
"2",
output_fname.data(),
bp::std_out > bp::null,
bp::std_err > bp::null,
bp::std_in < pipe);
}
void push_frame(const cv::Mat& im)
{
if((im.rows != height) || (im.cols != width))
throw std::runtime_error(format("frame shape mismatch"));
if(im.type() == CV_8UC3) {
for(auto y = 0; y < height; ++y) {
const uint8_t* row = im.ptr(y); // BGR format
uint8_t* out = &raw[0];
for(auto x = 0; x < width; ++x) {
uint8_t b = *row++;
uint8_t g = *row++;
uint8_t r = *row++;
*out++ = r;
*out++ = g;
*out++ = b;
}
Expects(out == &raw[0] + raw.size());
pipe.write(reinterpret_cast<char*>(&raw[0]), int(raw.size()));
}
} else if(im.type() == CV_8UC1 || im.type() == CV_8U) {
for(auto y = 0; y < height; ++y) {
const uint8_t* row = im.ptr(y); // gray format
uint8_t* out = &raw[0];
for(auto x = 0; x < width; ++x) {
uint8_t g = *row++;
*out++ = g;
*out++ = g;
*out++ = g;
}
Expects(out == &raw[0] + raw.size());
pipe.write(reinterpret_cast<char*>(&raw[0]), int(raw.size()));
}
} else {
FATAL(format("input movie was in unsupport color space: cv::Mat.type() == {}",
im.type()));
}
}
int close()
{
if(pipe.is_open()) {
pipe.close();
std::error_code ec;
subprocess.wait(ec);
if(ec) {
throw std::runtime_error(
format("error waiting for ffmpeg to end: {}", ec.message()));
}
}
return subprocess.exit_code();
}
};
This::This()
: pimpl_(new Pimpl)
{}
This::~This() = default;
void This::push_frame(const cv::Mat& frame) { pimpl_->push_frame(frame); }
int This::close() { return pimpl_->close(); }
StreamingFFMpegEncoder This::create(const string_view output_fname,
const int width,
const int height,
const real frame_rate)
{
StreamingFFMpegEncoder o;
o.pimpl_->init(output_fname, width, height, frame_rate);
return o;
}
} // namespace perceive::movie
| 32.398734 | 87 | 0.436413 | prcvlabs |
9cbf95027924eb40ae799b2ba58d260f249d76e3 | 405 | cpp | C++ | BasicPhysicsEngine/main.cpp | adityadutta/BasicPhysicsEngine | dfd85f1f3a25e573c09ca420115c2a4e701c5dc0 | [
"MIT"
] | 1 | 2018-12-12T21:20:37.000Z | 2018-12-12T21:20:37.000Z | BasicPhysicsEngine/main.cpp | adityadutta/BasicPhysicsEngine | dfd85f1f3a25e573c09ca420115c2a4e701c5dc0 | [
"MIT"
] | null | null | null | BasicPhysicsEngine/main.cpp | adityadutta/BasicPhysicsEngine | dfd85f1f3a25e573c09ca420115c2a4e701c5dc0 | [
"MIT"
] | 1 | 2018-12-12T21:21:23.000Z | 2018-12-12T21:21:23.000Z | #include "GameManager.h"
#include <iostream>
int main(int argc, char* args[])
{
GameManager *ptr = new GameManager();
bool status = ptr->OnCreate();
if (status == true) {
ptr->Run();
}
else if (status == false) {
/// You should have learned about stderr (std::cerr) in Operating Systems
std::cerr << "Fatal error occured. Cannot start this program" << std::endl;
}
delete ptr;
return 0;
} | 22.5 | 77 | 0.654321 | adityadutta |
9cbfd885c90882a6be0bdce8711a31eca6ce93be | 13,157 | cc | C++ | Alignment/ReferenceTrajectories/src/VMatrix.cc | pasmuss/cmssw | 566f40c323beef46134485a45ea53349f59ae534 | [
"Apache-2.0"
] | null | null | null | Alignment/ReferenceTrajectories/src/VMatrix.cc | pasmuss/cmssw | 566f40c323beef46134485a45ea53349f59ae534 | [
"Apache-2.0"
] | null | null | null | Alignment/ReferenceTrajectories/src/VMatrix.cc | pasmuss/cmssw | 566f40c323beef46134485a45ea53349f59ae534 | [
"Apache-2.0"
] | null | null | null | /*
* VMatrix.cpp
*
* Created on: Feb 15, 2012
* Author: kleinwrt
*/
/** \file
* VMatrix methods.
*
* \author Claus Kleinwort, DESY, 2011 (Claus.Kleinwort@desy.de)
*
* \copyright
* Copyright (c) 2011 - 2016 Deutsches Elektronen-Synchroton,
* Member of the Helmholtz Association, (DESY), HAMBURG, GERMANY \n\n
* 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. \n\n
* 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. \n\n
* You should have received a copy of the GNU Library General Public
* License along with this program (see the file COPYING.LIB for more
* details); if not, write to the Free Software Foundation, Inc.,
* 675 Mass Ave, Cambridge, MA 02139, USA.
*/
#include "Alignment/ReferenceTrajectories/interface/VMatrix.h"
//! Namespace for the general broken lines package
namespace gbl {
/*********** simple Matrix based on std::vector<double> **********/
VMatrix::VMatrix(const unsigned int nRows, const unsigned int nCols) :
numRows(nRows), numCols(nCols), theVec(nRows * nCols)
{
}
VMatrix::VMatrix(const VMatrix &aMatrix) :
numRows(aMatrix.numRows), numCols(aMatrix.numCols), theVec(aMatrix.theVec)
{
}
VMatrix::~VMatrix() {
}
/// Resize Matrix.
/**
* \param [in] nRows Number of rows.
* \param [in] nCols Number of columns.
*/
void VMatrix::resize(const unsigned int nRows, const unsigned int nCols) {
numRows = nRows;
numCols = nCols;
theVec.resize(nRows * nCols);
}
/// Get transposed matrix.
/**
* \return Transposed matrix.
*/
VMatrix VMatrix::transpose() const {
VMatrix aResult(numCols, numRows);
for (unsigned int i = 0; i < numRows; ++i) {
for (unsigned int j = 0; j < numCols; ++j) {
aResult(j, i) = theVec[numCols * i + j];
}
}
return aResult;
}
/// Get number of rows.
/**
* \return Number of rows.
*/
unsigned int VMatrix::getNumRows() const {
return numRows;
}
/// Get number of columns.
/**
* \return Number of columns.
*/
unsigned int VMatrix::getNumCols() const {
return numCols;
}
/// Print matrix.
void VMatrix::print() const {
std::cout << " VMatrix: " << numRows << "*" << numCols << std::endl;
for (unsigned int i = 0; i < numRows; ++i) {
for (unsigned int j = 0; j < numCols; ++j) {
if (j % 5 == 0) {
std::cout << std::endl << std::setw(4) << i << ","
<< std::setw(4) << j << "-" << std::setw(4)
<< std::min(j + 4, numCols) << ":";
}
std::cout << std::setw(13) << theVec[numCols * i + j];
}
}
std::cout << std::endl << std::endl;
}
/// Multiplication Matrix*Vector.
VVector VMatrix::operator*(const VVector &aVector) const {
VVector aResult(numRows);
for (unsigned int i = 0; i < this->numRows; ++i) {
double sum = 0.0;
for (unsigned int j = 0; j < this->numCols; ++j) {
sum += theVec[numCols * i + j] * aVector(j);
}
aResult(i) = sum;
}
return aResult;
}
/// Multiplication Matrix*Matrix.
VMatrix VMatrix::operator*(const VMatrix &aMatrix) const {
VMatrix aResult(numRows, aMatrix.numCols);
for (unsigned int i = 0; i < numRows; ++i) {
for (unsigned int j = 0; j < aMatrix.numCols; ++j) {
double sum = 0.0;
for (unsigned int k = 0; k < numCols; ++k) {
sum += theVec[numCols * i + k] * aMatrix(k, j);
}
aResult(i, j) = sum;
}
}
return aResult;
}
/// Addition Matrix+Matrix.
VMatrix VMatrix::operator+(const VMatrix &aMatrix) const {
VMatrix aResult(numRows, numCols);
for (unsigned int i = 0; i < numRows; ++i) {
for (unsigned int j = 0; j < numCols; ++j) {
aResult(i, j) = theVec[numCols * i + j] + aMatrix(i, j);
}
}
return aResult;
}
/// Assignment Matrix=Matrix.
VMatrix &VMatrix::operator=(const VMatrix &aMatrix) {
if (this != &aMatrix) { // Gracefully handle self assignment
numRows = aMatrix.getNumRows();
numCols = aMatrix.getNumCols();
theVec.resize(numRows * numCols);
for (unsigned int i = 0; i < numRows; ++i) {
for (unsigned int j = 0; j < numCols; ++j) {
theVec[numCols * i + j] = aMatrix(i, j);
}
}
}
return *this;
}
/*********** simple symmetric Matrix based on std::vector<double> **********/
VSymMatrix::VSymMatrix(const unsigned int nRows) :
numRows(nRows), theVec((nRows * nRows + nRows) / 2) {
}
VSymMatrix::~VSymMatrix() {
}
/// Resize symmetric matrix.
/**
* \param [in] nRows Number of rows.
*/
void VSymMatrix::resize(const unsigned int nRows) {
numRows = nRows;
theVec.resize((nRows * nRows + nRows) / 2);
}
/// Get number of rows (= number of colums).
/**
* \return Number of rows.
*/
unsigned int VSymMatrix::getNumRows() const {
return numRows;
}
/// Print matrix.
void VSymMatrix::print() const {
std::cout << " VSymMatrix: " << numRows << "*" << numRows << std::endl;
for (unsigned int i = 0; i < numRows; ++i) {
for (unsigned int j = 0; j <= i; ++j) {
if (j % 5 == 0) {
std::cout << std::endl << std::setw(4) << i << ","
<< std::setw(4) << j << "-" << std::setw(4)
<< std::min(j + 4, i) << ":";
}
std::cout << std::setw(13) << theVec[(i * i + i) / 2 + j];
}
}
std::cout << std::endl << std::endl;
}
/// Subtraction SymMatrix-(sym)Matrix.
VSymMatrix VSymMatrix::operator-(const VMatrix &aMatrix) const {
VSymMatrix aResult(numRows);
for (unsigned int i = 0; i < numRows; ++i) {
for (unsigned int j = 0; j <= i; ++j) {
aResult(i, j) = theVec[(i * i + i) / 2 + j] - aMatrix(i, j);
}
}
return aResult;
}
/// Multiplication SymMatrix*Vector.
VVector VSymMatrix::operator*(const VVector &aVector) const {
VVector aResult(numRows);
for (unsigned int i = 0; i < numRows; ++i) {
aResult(i) = theVec[(i * i + i) / 2 + i] * aVector(i);
for (unsigned int j = 0; j < i; ++j) {
aResult(j) += theVec[(i * i + i) / 2 + j] * aVector(i);
aResult(i) += theVec[(i * i + i) / 2 + j] * aVector(j);
}
}
return aResult;
}
/// Multiplication SymMatrix*Matrix.
VMatrix VSymMatrix::operator*(const VMatrix &aMatrix) const {
unsigned int nCol = aMatrix.getNumCols();
VMatrix aResult(numRows, nCol);
for (unsigned int l = 0; l < nCol; ++l) {
for (unsigned int i = 0; i < numRows; ++i) {
aResult(i, l) = theVec[(i * i + i) / 2 + i] * aMatrix(i, l);
for (unsigned int j = 0; j < i; ++j) {
aResult(j, l) += theVec[(i * i + i) / 2 + j] * aMatrix(i, l);
aResult(i, l) += theVec[(i * i + i) / 2 + j] * aMatrix(j, l);
}
}
}
return aResult;
}
/*********** simple Vector based on std::vector<double> **********/
VVector::VVector(const unsigned int nRows) :
numRows(nRows), theVec(nRows) {
}
VVector::VVector(const VVector &aVector) :
numRows(aVector.numRows), theVec(aVector.theVec) {
}
VVector::~VVector() {
}
/// Resize vector.
/**
* \param [in] nRows Number of rows.
*/
void VVector::resize(const unsigned int nRows) {
numRows = nRows;
theVec.resize(nRows);
}
/// Get part of vector.
/**
* \param [in] len Length of part.
* \param [in] start Offset of part.
* \return Part of vector.
*/
VVector VVector::getVec(unsigned int len, unsigned int start) const {
VVector aResult(len);
std::memcpy(&aResult.theVec[0], &theVec[start], sizeof(double) * len);
return aResult;
}
/// Put part of vector.
/**
* \param [in] aVector Vector with part.
* \param [in] start Offset of part.
*/
void VVector::putVec(const VVector &aVector, unsigned int start) {
std::memcpy(&theVec[start], &aVector.theVec[0],
sizeof(double) * aVector.numRows);
}
/// Get number of rows.
/**
* \return Number of rows.
*/
unsigned int VVector::getNumRows() const {
return numRows;
}
/// Print vector.
void VVector::print() const {
std::cout << " VVector: " << numRows << std::endl;
for (unsigned int i = 0; i < numRows; ++i) {
if (i % 5 == 0) {
std::cout << std::endl << std::setw(4) << i << "-" << std::setw(4)
<< std::min(i + 4, numRows) << ":";
}
std::cout << std::setw(13) << theVec[i];
}
std::cout << std::endl << std::endl;
}
/// Subtraction Vector-Vector.
VVector VVector::operator-(const VVector &aVector) const {
VVector aResult(numRows);
for (unsigned int i = 0; i < numRows; ++i) {
aResult(i) = theVec[i] - aVector(i);
}
return aResult;
}
/// Assignment Vector=Vector.
VVector &VVector::operator=(const VVector &aVector) {
if (this != &aVector) { // Gracefully handle self assignment
numRows = aVector.getNumRows();
theVec.resize(numRows);
for (unsigned int i = 0; i < numRows; ++i) {
theVec[i] = aVector(i);
}
}
return *this;
}
/*============================================================================
from mpnum.F (MillePede-II by V. Blobel, Univ. Hamburg)
============================================================================*/
/// Matrix inversion.
/**
* Invert symmetric N-by-N matrix V in symmetric storage mode
* V(1) = V11, V(2) = V12, V(3) = V22, V(4) = V13, . . .
* replaced by inverse matrix
*
* Method of solution is by elimination selecting the pivot on the
* diagonal each stage. The rank of the matrix is returned in NRANK.
* For NRANK ne N, all remaining rows and cols of the resulting
* matrix V are set to zero.
* \exception 1 : matrix is singular.
* \return Rank of matrix.
*/
unsigned int VSymMatrix::invert() {
const double eps = 1.0E-10;
unsigned int aSize = numRows;
std::vector<int> next(aSize);
std::vector<double> diag(aSize);
int nSize = aSize;
int first = 1;
for (int i = 1; i <= nSize; ++i) {
next[i - 1] = i + 1; // set "next" pointer
diag[i - 1] = fabs(theVec[(i * i + i) / 2 - 1]); // save abs of diagonal elements
}
next[aSize - 1] = -1; // end flag
unsigned int nrank = 0;
for (int i = 1; i <= nSize; ++i) { // start of loop
int k = 0;
double vkk = 0.0;
int j = first;
int previous = 0;
int last = previous;
// look for pivot
while (j > 0) {
int jj = (j * j + j) / 2 - 1;
if (fabs(theVec[jj]) > std::max(fabs(vkk), eps * diag[j - 1])) {
vkk = theVec[jj];
k = j;
last = previous;
}
previous = j;
j = next[j - 1];
}
// pivot found
if (k > 0) {
int kk = (k * k + k) / 2 - 1;
if (last <= 0) {
first = next[k - 1];
} else {
next[last - 1] = next[k - 1];
}
next[k - 1] = 0; // index is used, reset
nrank++; // increase rank and ...
vkk = 1.0 / vkk;
theVec[kk] = -vkk;
int jk = kk - k;
int jl = -1;
for (int j = 1; j <= nSize; ++j) { // elimination
if (j == k) {
jk = kk;
jl += j;
} else {
if (j < k) {
++jk;
} else {
jk += j - 1;
}
double vjk = theVec[jk];
theVec[jk] = vkk * vjk;
int lk = kk - k;
if (j >= k) {
for (int l = 1; l <= k - 1; ++l) {
++jl;
++lk;
theVec[jl] -= theVec[lk] * vjk;
}
++jl;
lk = kk;
for (int l = k + 1; l <= j; ++l) {
++jl;
lk += l - 1;
theVec[jl] -= theVec[lk] * vjk;
}
} else {
for (int l = 1; l <= j; ++l) {
++jl;
++lk;
theVec[jl] -= theVec[lk] * vjk;
}
}
}
}
} else {
for (int k = 1; k <= nSize; ++k) {
if (next[k - 1] >= 0) {
int kk = (k * k - k) / 2 - 1;
for (int j = 1; j <= nSize; ++j) {
if (next[j - 1] >= 0) {
theVec[kk + j] = 0.0; // clear matrix row/col
}
}
}
}
throw 1; // singular
}
}
for (int ij = 0; ij < (nSize * nSize + nSize) / 2; ++ij) {
theVec[ij] = -theVec[ij]; // finally reverse sign of all matrix elements
}
return nrank;
}
}
| 29.04415 | 87 | 0.512807 | pasmuss |
9cc07313177f18bb06a2ce21d9ad1294e39fa0d5 | 1,636 | hpp | C++ | Nana.Cpp03/include/nana/threads/thread.hpp | gfannes/nana | 3b8d33f9a98579684ea0440b6952deabe61bd978 | [
"BSL-1.0"
] | 1 | 2018-02-09T21:25:13.000Z | 2018-02-09T21:25:13.000Z | Nana.Cpp03/include/nana/threads/thread.hpp | gfannes/nana | 3b8d33f9a98579684ea0440b6952deabe61bd978 | [
"BSL-1.0"
] | null | null | null | Nana.Cpp03/include/nana/threads/thread.hpp | gfannes/nana | 3b8d33f9a98579684ea0440b6952deabe61bd978 | [
"BSL-1.0"
] | null | null | null | /*
* Thread Implementation
* Copyright(C) 2003-2013 Jinhao(cnjinhao@hotmail.com)
*
* Distributed under the Boost Software License, Version 1.0.
* (See accompanying file LICENSE_1_0.txt or copy at
* http://www.boost.org/LICENSE_1_0.txt)
*
* @file: nana/threads/thread.hpp
*/
#ifndef NANA_THREADS_THREAD_HPP
#define NANA_THREADS_THREAD_HPP
#include <map>
#include "mutex.hpp"
#include "../exceptions.hpp"
#include "../traits.hpp"
#include <nana/functor.hpp>
namespace nana
{
namespace threads
{
class thread;
namespace detail
{
struct thread_object_impl;
class thread_holder
{
public:
void insert(unsigned tid, thread* obj);
thread* get(unsigned tid);
void remove(unsigned tid);
private:
threads::recursive_mutex mutex_;
std::map<unsigned, thread*> map_;
};
}//end namespace detail
class thread
:nana::noncopyable
{
typedef thread self_type;
public:
thread();
~thread();
template<typename Functor>
void start(const Functor& f)
{
close();
_m_start_thread(f);
}
template<typename Object, typename Concept>
void start(Object& obj, void (Concept::*memf)())
{
close();
_m_start_thread(nana::functor<void()>(obj, memf));
}
bool empty() const;
unsigned tid() const;
void close();
static void check_break(int retval);
private:
void _m_start_thread(const nana::functor<void()>& f);
private:
void _m_add_tholder();
unsigned _m_thread_routine();
private:
detail::thread_object_impl* impl_;
static detail::thread_holder tholder;
};
}//end namespace threads
}//end namespace nana
#endif
| 19.47619 | 61 | 0.680318 | gfannes |
9cc1d9aa5ffe9e9c8a2e701fe211822c907f10ca | 488 | cpp | C++ | gen/blink/modules/serviceworkers/ClientQueryOptions.cpp | gergul/MiniBlink | 7a11c52f141d54d5f8e1a9af31867cd120a2c3c4 | [
"Apache-2.0"
] | 8 | 2019-05-05T16:38:05.000Z | 2021-11-09T11:45:38.000Z | gen/blink/modules/serviceworkers/ClientQueryOptions.cpp | gergul/MiniBlink | 7a11c52f141d54d5f8e1a9af31867cd120a2c3c4 | [
"Apache-2.0"
] | null | null | null | gen/blink/modules/serviceworkers/ClientQueryOptions.cpp | gergul/MiniBlink | 7a11c52f141d54d5f8e1a9af31867cd120a2c3c4 | [
"Apache-2.0"
] | 4 | 2018-12-14T07:52:46.000Z | 2021-06-11T18:06:09.000Z | // 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.
// This file has been auto-generated by code_generator_v8.py. DO NOT MODIFY!
#include "config.h"
#include "ClientQueryOptions.h"
namespace blink {
ClientQueryOptions::ClientQueryOptions()
{
setIncludeUncontrolled(false);
setType(String("window"));
}
DEFINE_TRACE(ClientQueryOptions)
{
}
} // namespace blink
| 20.333333 | 76 | 0.747951 | gergul |
9cc246112cbf1f8e0aca0977fa0fea216c914593 | 277 | hpp | C++ | cmdstan/stan/src/stan/lang/ast/fun/is_space_def.hpp | yizhang-cae/torsten | dc82080ca032325040844cbabe81c9a2b5e046f9 | [
"BSD-3-Clause"
] | 1 | 2019-07-05T01:40:40.000Z | 2019-07-05T01:40:40.000Z | cmdstan/stan/src/stan/lang/ast/fun/is_space_def.hpp | yizhang-cae/torsten | dc82080ca032325040844cbabe81c9a2b5e046f9 | [
"BSD-3-Clause"
] | null | null | null | cmdstan/stan/src/stan/lang/ast/fun/is_space_def.hpp | yizhang-cae/torsten | dc82080ca032325040844cbabe81c9a2b5e046f9 | [
"BSD-3-Clause"
] | null | null | null | #ifndef STAN_LANG_AST_FUN_IS_SPACE_DEF_HPP
#define STAN_LANG_AST_FUN_IS_SPACE_DEF_HPP
#include <stan/lang/ast/fun/is_space.hpp>
namespace stan {
namespace lang {
bool is_space(char c) {
return c == ' ' || c == '\n' || c == '\r' || c == '\t';
}
}
}
#endif
| 17.3125 | 61 | 0.624549 | yizhang-cae |
9cc2e24bf7b5e3b4ed7273dc58aa9e325c66ed91 | 1,671 | hpp | C++ | io/PVPFile.hpp | PetaVision/ObsoletePV | e99a42bf4292e944b252e144b5e07442b0715697 | [
"MIT"
] | null | null | null | io/PVPFile.hpp | PetaVision/ObsoletePV | e99a42bf4292e944b252e144b5e07442b0715697 | [
"MIT"
] | null | null | null | io/PVPFile.hpp | PetaVision/ObsoletePV | e99a42bf4292e944b252e144b5e07442b0715697 | [
"MIT"
] | null | null | null | /*
* PVPFile.hpp
*
* Created on: Jun 4, 2014
* Author: pschultz
*
* The goal of the PVPFile class is to encapsulate all interaction with
* PVPFiles---opening and closing, reading and writing, gathering and
* scattering---into a form where, even in the MPI context, all processes
* call the same public methods at the same time.
*
* All interaction with a PVP file from outside this class should use
* this class to work with the file.
*/
#ifndef PVPFILE_HPP_
#define PVPFILE_HPP_
#include <assert.h>
#include <sys/stat.h>
#include "../columns/InterColComm.hpp"
#include "fileio.hpp"
#include "io.h"
#define PVPFILE_SIZEOF_INT 4
#define PVPFILE_SIZEOF_LONG 8
#define PVPFILE_SIZEOF_SHORT 2
#define PVPFILE_SIZEOF_DOUBLE 8
#define PVPFILE_SIZEOF_FLOAT 4
enum PVPFileMode { PVPFILE_READ, PVPFILE_WRITE, PVPFILE_WRITE_READBACK, PVPFILE_APPEND };
namespace PV {
class PVPFile {
// Member functions
public:
PVPFile(const char * path, enum PVPFileMode mode, int pvpfileType, InterColComm * icComm);
int rank() { return icComm->commRank(); }
int rootProc() { return 0; }
bool isRoot() { return rank()==rootProc(); }
~PVPFile();
protected:
PVPFile();
int initialize(const char * path, enum PVPFileMode mode, int pvpfileType, InterColComm * icComm);
int initfile(const char * path, enum PVPFileMode mode, InterColComm * icComm);
private:
int initialize_base();
// Member variables
private:
int PVPFileType;
enum PVPFileMode mode;
int numFrames;
int currentFrame;
InterColComm * icComm;
int * header;
double headertime;
PV_Stream * stream;
};
} /* namespace PV */
#endif /* PVPFILE_HPP_ */
| 24.217391 | 100 | 0.715739 | PetaVision |
9cc3b7753bcf17838c04abb48065fe9452d89026 | 12,129 | cpp | C++ | parrlibdx/Texture.cpp | AlessandroParrotta/parrlibdx | 0b3cb26358f7831c6043ebc3ce0893b3a5fadcfe | [
"MIT"
] | null | null | null | parrlibdx/Texture.cpp | AlessandroParrotta/parrlibdx | 0b3cb26358f7831c6043ebc3ce0893b3a5fadcfe | [
"MIT"
] | null | null | null | parrlibdx/Texture.cpp | AlessandroParrotta/parrlibdx | 0b3cb26358f7831c6043ebc3ce0893b3a5fadcfe | [
"MIT"
] | null | null | null | #include "Texture.h"
#include <SOIL/SOIL.h>
#include "common.h"
#include "debug.h"
#include "util.h"
namespace prb {
void Texture::defInit(unsigned char* data) {
D3D11_TEXTURE2D_DESC tdesc;
// ...
// Fill out width, height, mip levels, format, etc...
// ...
tdesc.Width = width;
tdesc.Height = height;
tdesc.MipLevels = 1;
tdesc.SampleDesc.Count = 1; //how many textures
tdesc.SampleDesc.Quality = 0;
tdesc.ArraySize = 1; //number of textures
tdesc.Format = format;
tdesc.Usage = D3D11_USAGE_DYNAMIC;
tdesc.BindFlags = D3D11_BIND_SHADER_RESOURCE; // Add D3D11_BIND_RENDER_TARGET if you want to go
// with the auto-generate mips route.
tdesc.CPUAccessFlags = D3D11_CPU_ACCESS_WRITE;
tdesc.MiscFlags = 0; // or D3D11_RESOURCE_MISC_GENERATE_MIPS for auto-mip gen.
D3D11_SUBRESOURCE_DATA srd; // (or an array of these if you have more than one mip level)
srd.pSysMem = data; // This data should be in raw pixel format
srd.SysMemPitch = linesize != 0 && linesize != width ? linesize : tdesc.Width * 4; // Sometimes pixel rows may be padded so this might not be as simple as width * pixel_size_in_bytes.
srd.SysMemSlicePitch = 0; // tdesc.Width* tdesc.Height * 4;
ThrowIfFailed(dev->CreateTexture2D(&tdesc, &srd, &texture));
D3D11_SHADER_RESOURCE_VIEW_DESC srDesc;
srDesc.Format = format;
srDesc.ViewDimension = viewDimension; //D3D11_SRV_DIMENSION_TEXTURE2D;
srDesc.Texture2D.MostDetailedMip = 0;
srDesc.Texture2D.MostDetailedMip = 0;
srDesc.Texture2D.MipLevels = 1;
ThrowIfFailed(dev->CreateShaderResourceView(texture, &srDesc, &resView));
//devcon->GenerateMips(resView);
D3D11_SAMPLER_DESC samplerDesc;
// Create a texture sampler state description.
//samplerDesc.Filter = D3D11_FILTER_MIN_MAG_MIP_LINEAR;
//samplerDesc.Filter = D3D11_FILTER_MIN_MAG_MIP_POINT;
samplerDesc.Filter = filtering;
samplerDesc.AddressU = D3D11_TEXTURE_ADDRESS_WRAP;
samplerDesc.AddressV = D3D11_TEXTURE_ADDRESS_WRAP;
samplerDesc.AddressW = D3D11_TEXTURE_ADDRESS_WRAP;
samplerDesc.MipLODBias = 0.0f;
samplerDesc.MaxAnisotropy = 1;
samplerDesc.ComparisonFunc = D3D11_COMPARISON_ALWAYS;
samplerDesc.BorderColor[0] = 0;
samplerDesc.BorderColor[1] = 0;
samplerDesc.BorderColor[2] = 0;
samplerDesc.BorderColor[3] = 0;
samplerDesc.MinLOD = 0;
samplerDesc.MaxLOD = D3D11_FLOAT32_MAX;
// Create the texture sampler state.
ThrowIfFailed(dev->CreateSamplerState(&samplerDesc, &sampler));
}
void Texture::init(unsigned char* data, vec2 size) {
this->width = size.x;
this->height = size.y;
defInit(data);
}
Texture::Texture() {}
Texture::Texture(std::wstring const& path) {
std::wstring ppath = strup::fallbackPath(path);
this->path = ppath;
unsigned char* data = SOIL_load_image(deb::toutf8(ppath).c_str(), &width, &height, &channels, SOIL_LOAD_RGBA);
if (data) defInit(data);
else deb::pr("could not load texture '", ppath, "'\n('", deb::toutf8(ppath).c_str(),"')\n");
delete[] data;
}
Texture::Texture(std::string const& path) : Texture(deb::tos(path)) {}
Texture::Texture(unsigned char* data, vec2 size) {
this->width = size.x;
this->height = size.y;
defInit(data);
}
Texture::Texture(unsigned char* data, vec2 size, int linesize) {
if (linesize == width) linesize *= 4;
this->width = size.x;
this->height = size.y;
this->linesize = linesize;
defInit(data);
//TODO right now the texture is uploaded twice in this constructor
D3D11_MAPPED_SUBRESOURCE mappedResource;
ThrowIfFailed(devcon->Map(texture, 0, D3D11_MAP_WRITE_DISCARD, 0, &mappedResource));
unsigned char* tdata = data;
BYTE* mappedData = reinterpret_cast<BYTE*>(mappedResource.pData);
for (UINT i = 0; i < height; i++)
{
memcpy(mappedData, tdata, linesize);
mappedData += mappedResource.RowPitch;
tdata += linesize;
}
devcon->Unmap(texture, 0);
}
Texture::Texture(vec2 size) {
this->linesize = size.x;
unsigned char* sData = new unsigned char[size.x * size.y * 4];
memset(sData, 0, size.x * size.y * 4);
init(sData, size);
delete[] sData;
}
Texture::Texture(vec2 size, int linesize, DXGI_FORMAT format, D3D_SRV_DIMENSION viewDimension) {
if (linesize == (int)size.x) linesize *= 4;
this->linesize = size.x;
this->format = format;
this->viewDimension = viewDimension;
unsigned char* sData = new unsigned char[linesize * size.y];
memset(sData, 0, linesize * size.y);
init(sData, size);
delete[] sData;
}
Texture::Texture(vec2 size, int linesize) : Texture(size, linesize, DXGI_FORMAT_R8G8B8A8_UNORM, D3D11_SRV_DIMENSION_TEXTURE2D) {}
bool Texture::operator==(Texture const& ot) const {
return this->texture == ot.texture &&
this->resView == ot.resView &&
this->sampler == ot.sampler &&
this->width == ot.width &&
this->height == ot.height &&
this->channels == ot.channels &&
this->linesize == ot.linesize;
}
bool Texture::operator!=(Texture const& ot) const { return !(*this == ot); }
bool Texture::null() const { return !texture || !resView || !sampler; }
vec2 Texture::getSize() const { return { (float)width, (float)height }; }
vec2 Texture::size() const { return getSize(); }
void Texture::setData(unsigned char* data, vec2 size, int linesize) {
if (linesize == width) linesize *= 4;
this->width = size.x;
this->height = size.y;
this->linesize = linesize;
D3D11_MAPPED_SUBRESOURCE mappedResource;
ThrowIfFailed(devcon->Map(texture, 0, D3D11_MAP_WRITE_DISCARD, 0, &mappedResource));
unsigned char* tdata = data;
BYTE* mappedData = reinterpret_cast<BYTE*>(mappedResource.pData);
for (UINT i = 0; i < height; i++)
{
memcpy(mappedData, tdata, linesize);
mappedData += mappedResource.RowPitch;
tdata += linesize;
}
devcon->Unmap(texture, 0);
}
void Texture::setData(unsigned char* data, vec2 size) {
this->width = size.x;
this->height = size.y;
D3D11_MAPPED_SUBRESOURCE mappedResource;
ThrowIfFailed(devcon->Map(texture, 0, D3D11_MAP_WRITE_DISCARD, 0, &mappedResource));
memcpy(mappedResource.pData, data, height * width * 4);
devcon->Unmap(texture, 0);
}
void Texture::setData(vec4 data) {
if (width <= 0 || height <= 0) return;
//data.clamp(0.f, 1.f);
unsigned char* ndata = new unsigned char[this->width * this->height * 4];
for(int i=0; i< this->width * this->height * 4; i+=4){
ndata[i + 0] = (unsigned char)(data.x*255.f);
ndata[i + 1] = (unsigned char)(data.y*255.f);
ndata[i + 2] = (unsigned char)(data.z*255.f);
ndata[i + 3] = (unsigned char)(data.w*255.f);
}
setData(ndata, vec2(width, height));
delete[] ndata;
}
D3D11_FILTER Texture::getFromFiltering(TEXTURE_FILTERING min, TEXTURE_FILTERING mag, TEXTURE_FILTERING mip) const {
return prb::getFromFiltering(min, mag, mip);
}
void Texture::calcMinMagMip(D3D11_FILTER filter) {
std::tuple<TEXTURE_FILTERING, TEXTURE_FILTERING, TEXTURE_FILTERING> ret = prb::calcMinMagMip(filter);
min = std::get<0>(ret); mag = std::get<1>(ret); mip = std::get<2>(ret);
}
void Texture::setFiltering(D3D11_FILTER filter) {
this->filtering = filter;
if (!texture || !resView || !sampler) return;
calcMinMagMip(filter);
if (sampler) { sampler->Release(); sampler = NULL; }
D3D11_SAMPLER_DESC samplerDesc;
samplerDesc.Filter = filtering;
samplerDesc.AddressU = D3D11_TEXTURE_ADDRESS_WRAP;
samplerDesc.AddressV = D3D11_TEXTURE_ADDRESS_WRAP;
samplerDesc.AddressW = D3D11_TEXTURE_ADDRESS_WRAP;
samplerDesc.MipLODBias = 0.0f;
samplerDesc.MaxAnisotropy = 1;
samplerDesc.ComparisonFunc = D3D11_COMPARISON_ALWAYS;
samplerDesc.BorderColor[0] = 0;
samplerDesc.BorderColor[1] = 0;
samplerDesc.BorderColor[2] = 0;
samplerDesc.BorderColor[3] = 0;
samplerDesc.MinLOD = 0;
samplerDesc.MaxLOD = D3D11_FLOAT32_MAX;
// Create the texture sampler state.
ThrowIfFailed(dev->CreateSamplerState(&samplerDesc, &sampler));
}
void Texture::setFiltering(TEXTURE_FILTERING min, TEXTURE_FILTERING mag, TEXTURE_FILTERING mip) { this->min = min; this->mag = mag; this->mip = mip; setFiltering(getFromFiltering(min, mag, mip)); }
void Texture::setFiltering(TEXTURE_FILTERING min, TEXTURE_FILTERING mag) { this->min = min; this->mag = mag; mip = mag; setFiltering(getFromFiltering(min, mag, mip)); }
void Texture::setFiltering(TEXTURE_FILTERING filter) { min = mag = mip = filter; setFiltering(getFromFiltering(min, mag, mip)); }
void Texture::drawImmediate(std::vector<float> const& verts) const {
util::drawTexture(*this, verts);
}
void Texture::drawImmediate(vec2 pos, vec2 size) const {
vec2 start = pos, end = pos + size;
std::vector<float> verts = { //clockwise order
start.x,start.y, 1.f,1.f,1.f,1.f, 0.f,1.f,
start.x,end.y, 1.f,1.f,1.f,1.f, 0.f,0.f,
end.x,end.y, 1.f,1.f,1.f,1.f, 1.f,0.f,
end.x,end.y, 1.f,1.f,1.f,1.f, 1.f,0.f,
end.x,start.y, 1.f,1.f,1.f,1.f, 1.f,1.f,
start.x,start.y, 1.f,1.f,1.f,1.f, 0.f,1.f,
};
drawImmediate(verts);
}
void Texture::bind() const {
devcon->PSSetShaderResources(0, 1, &resView);
devcon->PSSetSamplers(0, 1, &sampler);
}
void Texture::dispose() {
if(resView) resView->Release();
if(texture) texture->Release();
if(sampler) sampler->Release();
}
}
///////////////////////////////////////
//OLD DRAWTEXTURE
////create a temporary vertex buffer
//ID3D11Buffer* tempVBuffer = NULL;
//// create the vertex buffer
//D3D11_BUFFER_DESC bd;
//ZeroMemory(&bd, sizeof(bd));
//bd.Usage = D3D11_USAGE_DYNAMIC; // write access access by CPU and GPU
//bd.ByteWidth = sizeof(float) * verts.size(); // size is the VERTEX struct * 3
//bd.BindFlags = D3D11_BIND_VERTEX_BUFFER; // use as a vertex buffer
//bd.CPUAccessFlags = D3D11_CPU_ACCESS_WRITE; // allow CPU to write in buffer
//dev->CreateBuffer(&bd, NULL, &tempVBuffer); // create the buffer
//// copy the vertices into the buffer
//D3D11_MAPPED_SUBRESOURCE ms;
//devcon->Map(tempVBuffer, NULL, D3D11_MAP_WRITE_DISCARD, NULL, &ms);
//memcpy(ms.pData, &verts[0], sizeof(float) * verts.size());
//devcon->Unmap(tempVBuffer, NULL);
//devcon->PSSetShaderResources(0, 1, &resView);
//devcon->PSSetSamplers(0, 1, &sampler);
//// select which vertex buffer to display
//UINT stride = sizeof(float) * 2 + sizeof(float) * 4 + sizeof(float) * 2;
//UINT offset = 0;
//devcon->IASetVertexBuffers(0, 1, &tempVBuffer, &stride, &offset);
//// select which primtive type we are using
//devcon->IASetPrimitiveTopology(D3D11_PRIMITIVE_TOPOLOGY_TRIANGLELIST);
//// draw the vertex buffer to the back buffer
//devcon->Draw(6, 0);
////release the temporary buffer
//tempVBuffer->Release(); | 36.314371 | 202 | 0.608294 | AlessandroParrotta |
9cc603ec457fa5a3c9cea08bc0b1c62763431e92 | 1,566 | cpp | C++ | src/Grid.cpp | perezite/o2-blocks | c021f9eaddfefe619d3e41508c0fbdb81a95c276 | [
"MIT"
] | null | null | null | src/Grid.cpp | perezite/o2-blocks | c021f9eaddfefe619d3e41508c0fbdb81a95c276 | [
"MIT"
] | null | null | null | src/Grid.cpp | perezite/o2-blocks | c021f9eaddfefe619d3e41508c0fbdb81a95c276 | [
"MIT"
] | null | null | null | #include "Grid.h"
#include "DrawTarget.h"
namespace blocks {
void Grid::computeLine(const sb::Vector2f& start, const sb::Vector2f& end) {
Line line(_thickness, _color);
line.addPoint(start);
line.addPoint(end);
_vertices.insert(_vertices.end(), line.getVertices().begin(), line.getVertices().end());
}
void Grid::computeVerticalLines() {
sb::Vector2f size = getSize();
sb::Vector2f halfSize = 0.5f * size;
float delta = size.x / _gridSize.x;
for (int i = 0; i <= _gridSize.x; i++) {
sb::Vector2f start(i * delta - halfSize.x, -halfSize.y);
sb::Vector2f end(i * delta - halfSize.x, +halfSize.y);
computeLine(start, end);
}
}
void Grid::computeHorizontalLines() {
sb::Vector2f size = getSize();
sb::Vector2f halfSize = 0.5f * size;
float delta = size.y / _gridSize.y;
for (int i = 0; i <= _gridSize.y; i++) {
sb::Vector2f start(-halfSize.x, i * delta - halfSize.y);
sb::Vector2f end(+halfSize.x, i * delta - halfSize.y);
computeLine(start, end);
}
}
void Grid::computeLines() {
_vertices.clear();
sb::Vector2f delta(1.f / _gridSize.x, 1.f / _gridSize.y);
computeVerticalLines();
computeHorizontalLines();
}
Grid::Grid(sb::Vector2i gridSize, float thickness, const sb::Color& color)
: _gridSize(gridSize), _thickness(thickness), _color(color)
{
computeLines();
}
void Grid::draw(sb::DrawTarget& target, sb::DrawStates states) {
states.transform *= getTransform();
target.draw(_vertices, sb::PrimitiveType::TriangleStrip, states);
}
}
| 29.54717 | 91 | 0.646232 | perezite |
9cc711561074bd40d99fb14975ce6d1012c1b892 | 10,794 | cpp | C++ | ugene/src/plugins/dna_export/src/ExportTasks.cpp | iganna/lspec | c75cba3e4fa9a46abeecbf31b5d467827cf4fec0 | [
"MIT"
] | null | null | null | ugene/src/plugins/dna_export/src/ExportTasks.cpp | iganna/lspec | c75cba3e4fa9a46abeecbf31b5d467827cf4fec0 | [
"MIT"
] | null | null | null | ugene/src/plugins/dna_export/src/ExportTasks.cpp | iganna/lspec | c75cba3e4fa9a46abeecbf31b5d467827cf4fec0 | [
"MIT"
] | null | null | null | /**
* UGENE - Integrated Bioinformatics Tools.
* Copyright (C) 2008-2012 UniPro <ugene@unipro.ru>
* http://ugene.unipro.ru
*
* 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; if not, write to the Free Software
* Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston,
* MA 02110-1301, USA.
*/
#include "ExportTasks.h"
#include <U2Core/DocumentModel.h>
#include <U2Core/IOAdapter.h>
#include <U2Core/IOAdapterUtils.h>
#include <U2Core/AppContext.h>
#include <U2Core/DNATranslation.h>
#include <U2Core/DNATranslationImpl.h>
#include <U2Core/Counter.h>
#include <U2Core/DNAChromatogramObject.h>
#include <U2Core/GObjectRelationRoles.h>
#include <U2Core/LoadDocumentTask.h>
#include <U2Core/AddDocumentTask.h>
#include <U2Core/MSAUtils.h>
#include <U2Core/TextUtils.h>
#include <U2Core/ProjectModel.h>
#include <U2Core/MAlignmentObject.h>
#include <U2Core/U2SafePoints.h>
#include <U2Core/U2SequenceUtils.h>
#include <U2Formats/SCFFormat.h>
#include <U2Gui/OpenViewTask.h>
namespace U2 {
//////////////////////////////////////////////////////////////////////////
// AddDocumentAndOpenViewTask
AddExportedDocumentAndOpenViewTask::AddExportedDocumentAndOpenViewTask(DocumentProviderTask* t)
: Task("Export sequence to document", TaskFlags_NR_FOSCOE)
{
exportTask = t;
addSubTask(exportTask);
}
QList<Task*> AddExportedDocumentAndOpenViewTask::onSubTaskFinished( Task* subTask ) {
QList<Task*> subTasks;
if (subTask == exportTask && !subTask->hasError()) {
Document* doc = exportTask->getDocument();
const GUrl& fullPath = doc->getURL();
Project* prj = AppContext::getProject();
if (prj) {
Document* sameURLdoc = prj->findDocumentByURL(fullPath);
if (sameURLdoc) {
taskLog.trace(tr("Document is already added to the project %1").arg(doc->getURL().getURLString()));
subTasks << new LoadUnloadedDocumentAndOpenViewTask(sameURLdoc);
return subTasks;
}
}
exportTask->takeDocument();
subTasks << new AddDocumentTask(doc);
subTasks << new LoadUnloadedDocumentAndOpenViewTask(doc);
}
//TODO: provide a report if subtask fails
return subTasks;
}
//////////////////////////////////////////////////////////////////////////
// DNAExportAlignmentTask
ExportAlignmentTask::ExportAlignmentTask(const MAlignment& _ma, const QString& _fileName, DocumentFormatId _f)
: DocumentProviderTask("", TaskFlag_None), ma(_ma), fileName(_fileName), format(_f)
{
GCOUNTER( cvar, tvar, "ExportAlignmentTask" );
setTaskName(tr("Export alignment to '%1'").arg(QFileInfo(fileName).fileName()));
setVerboseLogMode(true);
assert(!ma.isEmpty());
}
void ExportAlignmentTask::run() {
DocumentFormatRegistry* r = AppContext::getDocumentFormatRegistry();
DocumentFormat* f = r->getFormatById(format);
IOAdapterFactory* iof = AppContext::getIOAdapterRegistry()->getIOAdapterFactoryById(IOAdapterUtils::url2io(fileName));
resultDocument = f->createNewLoadedDocument(iof, fileName, stateInfo);
CHECK_OP(stateInfo, );
resultDocument->addObject(new MAlignmentObject(ma));
f->storeDocument(resultDocument, stateInfo);
}
//////////////////////////////////////////////////////////////////////////
// export alignment 2 sequence format
ExportMSA2SequencesTask::ExportMSA2SequencesTask(const MAlignment& _ma, const QString& _url, bool _trimAli, DocumentFormatId _format)
: DocumentProviderTask(tr("Export alignment to sequence: %1").arg(_url), TaskFlag_None),
ma(_ma), url(_url), trimAli(_trimAli), format(_format)
{
GCOUNTER( cvar, tvar, "ExportMSA2SequencesTask");
setVerboseLogMode(true);
}
void ExportMSA2SequencesTask::run() {
DocumentFormatRegistry* r = AppContext::getDocumentFormatRegistry();
DocumentFormat* f = r->getFormatById(format);
IOAdapterFactory* iof = AppContext::getIOAdapterRegistry()->getIOAdapterFactoryById(IOAdapterUtils::url2io(url));
resultDocument = f->createNewLoadedDocument(iof, url, stateInfo);
CHECK_OP(stateInfo, );
QList<DNASequence> lst = MSAUtils::ma2seq(ma, trimAli);
QSet<QString> usedNames;
foreach(DNASequence s, lst) {
QString name = s.getName();
if (usedNames.contains(name)) {
name = TextUtils::variate(name, " ", usedNames, false, 1);
s.setName(name);
}
U2EntityRef seqRef = U2SequenceUtils::import(resultDocument->getDbiRef(), s, stateInfo);
CHECK_OP(stateInfo, );
resultDocument->addObject(new U2SequenceObject(name, seqRef));
usedNames.insert(name);
}
f->storeDocument(resultDocument, stateInfo);
}
//////////////////////////////////////////////////////////////////////////
// export nucleic alignment 2 amino alignment
ExportMSA2MSATask::ExportMSA2MSATask(const MAlignment& _ma, int _offset, int _len, const QString& _url,
const QList<DNATranslation*>& _aminoTranslations, DocumentFormatId _format)
: DocumentProviderTask(tr("Export alignment to alignment: %1").arg(_url), TaskFlag_None),
ma(_ma), offset(_offset), len(_len), url(_url), format(_format), aminoTranslations(_aminoTranslations)
{
GCOUNTER( cvar, tvar, "ExportMSA2MSATask" );
setVerboseLogMode(true);
}
void ExportMSA2MSATask::run() {
DocumentFormatRegistry* r = AppContext::getDocumentFormatRegistry();
DocumentFormat* f = r->getFormatById(format);
IOAdapterFactory* iof = AppContext::getIOAdapterRegistry()->getIOAdapterFactoryById(IOAdapterUtils::url2io(url));
resultDocument = f->createNewLoadedDocument(iof, url, stateInfo);
CHECK_OP(stateInfo, );
QList<DNASequence> lst = MSAUtils::ma2seq(ma, true);
QList<DNASequence> seqList;
for (int i = offset; i < offset + len; i++) {
DNASequence& s = lst[i];
QString name = s.getName();
if (!aminoTranslations.isEmpty()) {
DNATranslation* aminoTT = aminoTranslations.first();
name += "(translated)";
QByteArray seq = s.seq;
int len = seq.length() / 3;
QByteArray resseq(len, '\0');
if (resseq.isNull() && len != 0) {
stateInfo.setError( tr("Out of memory") );
return;
}
assert(aminoTT->isThree2One());
aminoTT->translate(seq.constData(), seq.length(), resseq.data(), resseq.length());
resseq.replace("*","X");
DNASequence rs(name, resseq, aminoTT->getDstAlphabet());
seqList << rs;
} else {
seqList << s;
}
}
MAlignment ma = MSAUtils::seq2ma(seqList, stateInfo);
CHECK_OP(stateInfo, );
resultDocument->addObject(new MAlignmentObject(ma));
f->storeDocument(resultDocument, stateInfo);
}
//////////////////////////////////////////////////////////////////////////
// export chromatogram to SCF
ExportDNAChromatogramTask::ExportDNAChromatogramTask( DNAChromatogramObject* _obj, const ExportChromatogramTaskSettings& _settings)
: DocumentProviderTask(tr("Export chromatogram to SCF"), TaskFlags_NR_FOSCOE),
cObj(_obj), settings(_settings), loadTask(NULL)
{
GCOUNTER( cvar, tvar, "ExportDNAChromatogramTask" );
setVerboseLogMode(true);
}
void ExportDNAChromatogramTask::prepare() {
Document* d = cObj->getDocument();
assert(d != NULL);
if (d == NULL ) {
stateInfo.setError("Chromatogram object document is not found!");
return;
}
QList<GObjectRelation> relatedObjs = cObj->findRelatedObjectsByRole(GObjectRelationRole::SEQUENCE);
assert(relatedObjs.count() == 1);
if (relatedObjs.count() != 1) {
stateInfo.setError("Sequence related to chromatogram is not found!");
}
QString seqObjName = relatedObjs.first().ref.objName;
GObject* resObj = d->findGObjectByName(seqObjName);
U2SequenceObject * sObj = qobject_cast<U2SequenceObject*>(resObj);
assert(sObj != NULL);
DNAChromatogram cd = cObj->getChromatogram();
QByteArray seq = sObj->getWholeSequenceData();
if (settings.reverse) {
TextUtils::reverse(seq.data(), seq.length());
reverseVector(cd.A);
reverseVector(cd.C);
reverseVector(cd.G);
reverseVector(cd.T);
int offset = 0;
if (cObj->getDocument()->getDocumentFormatId() == BaseDocumentFormats::ABIF) {
int baseNum = cd.baseCalls.count();
int seqLen = cd.seqLength;
// this is required for base <-> peak correspondence
if (baseNum > seqLen) {
cd.baseCalls.remove(baseNum - 1);
cd.prob_A.remove(baseNum - 1);
cd.prob_C.remove(baseNum - 1);
cd.prob_G.remove(baseNum - 1);
cd.prob_T.remove(baseNum - 1);
}
} else if (cObj->getDocument()->getDocumentFormatId() == BaseDocumentFormats::SCF) {
// SCF format particularities
offset = -1;
}
for (int i = 0; i < cd.seqLength; ++i) {
cd.baseCalls[i] = cd.traceLength - cd.baseCalls[i] + offset;
}
reverseVector(cd.baseCalls);
reverseVector(cd.prob_A);
reverseVector(cd.prob_C);
reverseVector(cd.prob_G);
reverseVector(cd.prob_T);
}
if (settings.complement) {
DNATranslation* tr = AppContext::getDNATranslationRegistry()->lookupTranslation(BaseDNATranslationIds::NUCL_DNA_DEFAULT_COMPLEMENT);
tr->translate(seq.data(), seq.length());
qSwap(cd.A,cd.T);
qSwap(cd.C, cd.G);
qSwap(cd.prob_A, cd.prob_T);
qSwap(cd.prob_C, cd.prob_G);
}
SCFFormat::exportDocumentToSCF(settings.url, cd, seq, stateInfo);
CHECK_OP(stateInfo, );
if (settings.loadDocument) {
IOAdapterFactory* iof = AppContext::getIOAdapterRegistry()->getIOAdapterFactoryById(BaseIOAdapters::LOCAL_FILE);
loadTask = new LoadDocumentTask(BaseDocumentFormats::SCF, settings.url, iof );
addSubTask( loadTask );
}
}
QList<Task*> ExportDNAChromatogramTask::onSubTaskFinished(Task* subTask) {
if (subTask == loadTask) {
resultDocument = loadTask->takeDocument();
}
return QList<Task*>();
}
}//namespace
| 38.141343 | 140 | 0.650547 | iganna |
9cc7e19f882f9a7c2d3610709ce6d3746ca0244b | 3,589 | cpp | C++ | src/importer/onnx/ops/lpnorm.cpp | xhuohai/nncase | cf7921c273c7446090939c64f57ef783a62bf29c | [
"Apache-2.0"
] | 510 | 2018-12-29T06:49:36.000Z | 2022-03-30T08:36:29.000Z | src/importer/onnx/ops/lpnorm.cpp | xhuohai/nncase | cf7921c273c7446090939c64f57ef783a62bf29c | [
"Apache-2.0"
] | 459 | 2019-02-17T13:31:29.000Z | 2022-03-31T05:55:38.000Z | src/importer/onnx/ops/lpnorm.cpp | xhuohai/nncase | cf7921c273c7446090939c64f57ef783a62bf29c | [
"Apache-2.0"
] | 155 | 2019-04-16T08:43:24.000Z | 2022-03-21T07:27:26.000Z | /* Copyright 2020 Alexey Chernov <4ernov@gmail.com>
*
* 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 "../onnx_importer.h"
#include <cassert>
#include <nncase/ir/graph.h>
#include <nncase/ir/ops/binary.h>
#include <nncase/ir/ops/constant.h>
#include <nncase/ir/ops/reduce.h>
#include <nncase/ir/ops/unary.h>
using namespace nncase;
using namespace nncase::importer;
using namespace nncase::ir;
using namespace onnx;
void onnx_importer::convert_op_LpNormalization(const NodeProto &node)
{
const auto &op_name { generate_name(node) };
const auto &input = node.input()[0];
const auto &output = node.output()[0];
const auto &input_shape = get_shape(input);
axis_t reduce_axis { static_cast<int>(real_axis(get_attribute<int>(node, "axis").value(), input_shape.size())) };
const auto p = get_attribute<int>(node, "p").value();
assert(p >= 1 && p <= 2);
switch (p)
{
case 1:
{
auto abs = graph_.emplace<unary>(unary_abs, input_shape);
abs->name(op_name + ".abs(L1Normalization)");
auto sum = graph_.emplace<reduce>(reduce_sum, abs->output().shape(), reduce_axis, 0.f, true);
sum->name(op_name + ".reduce_sum(L1Normalization)");
auto div = graph_.emplace<binary>(binary_div, input_shape, sum->output().shape(), value_range<float>::full());
div->name(op_name + ".div(L1Normalization)");
sum->input().connect(abs->output());
div->input_b().connect(sum->output());
input_tensors_.emplace(&abs->input(), input);
input_tensors_.emplace(&div->input_a(), input);
output_tensors_.emplace(output, &div->output());
break;
}
case 2:
{
auto square = graph_.emplace<unary>(unary_square, input_shape);
square->name(op_name + ".square(L2Normalization)");
auto sum = graph_.emplace<reduce>(reduce_sum, square->output().shape(), reduce_axis, 0.f, true);
sum->name(op_name + ".reduce_sum(L2Normalization)");
auto epsilon = graph_.emplace<constant>(1e-10f);
epsilon->name(op_name + ".eps(L2Normalization)");
auto max = graph_.emplace<binary>(binary_max, sum->output().shape(), epsilon->output().shape(), value_range<float>::full());
max->name(op_name + ".stab(L2Normalization)");
auto sqrt = graph_.emplace<unary>(unary_sqrt, max->output().shape());
sqrt->name(op_name + ".sqrt(L2Normalization)");
auto div = graph_.emplace<binary>(binary_div, input_shape, sqrt->output().shape(), value_range<float>::full());
div->name(op_name + ".div(L2Normalization)");
sum->input().connect(square->output());
max->input_a().connect(sum->output());
max->input_b().connect(epsilon->output());
sqrt->input().connect(max->output());
div->input_b().connect(sqrt->output());
input_tensors_.emplace(&square->input(), input);
input_tensors_.emplace(&div->input_a(), input);
output_tensors_.emplace(output, &div->output());
break;
}
default:
{
break;
}
}
}
| 38.180851 | 132 | 0.650878 | xhuohai |
9cc80e7d11b7225ad9f738f0d2e4c04c0ca96330 | 716 | cpp | C++ | test/main.cpp | mbeckh/code-quality-actions | b58b6ee06589f68fa0fea550a7852e66c1b12246 | [
"Apache-2.0"
] | null | null | null | test/main.cpp | mbeckh/code-quality-actions | b58b6ee06589f68fa0fea550a7852e66c1b12246 | [
"Apache-2.0"
] | 28 | 2021-05-09T20:54:00.000Z | 2022-03-28T02:12:47.000Z | test/main.cpp | mbeckh/code-quality-actions | b58b6ee06589f68fa0fea550a7852e66c1b12246 | [
"Apache-2.0"
] | null | null | null | //
// Test Object which contains:
// - Two errors to be found by clang-tidy.
// - Test coverage for all lines except the ones marked with 'no coverage'.
//
int called_always() {
#ifdef _DEBUG
const char sz[] = "Debug"; // testing: deliberate error for clang-tidy
#else
const char sz[] = "Release"; // testing: deliberate error for clang-tidy
#endif
return sz[0];
}
int called_optional() { // testing: no coverage
return 1; // testing: no coverage
} // testing: no coverage
int main(int argc, char**) {
int result = called_always() == 'Z' ? 1 : 0;
if (argc > 1) {
result += called_optional(); // testing: no coverage
}
return result;
}
| 26.518519 | 76 | 0.601955 | mbeckh |
9cc87b9935d8eb6a783a5ea41d3c7a14c30e40ec | 1,495 | cpp | C++ | mhlo_builder/csrc/mlir/mhlo/builder/batch_norm.cpp | JamesTheZ/BladeDISC | e6c76ee557ebfccd560d44f6b6276bbc4e0a8a34 | [
"Apache-2.0"
] | 328 | 2021-12-20T03:29:35.000Z | 2022-03-31T14:27:23.000Z | mhlo_builder/csrc/mlir/mhlo/builder/batch_norm.cpp | JamesTheZ/BladeDISC | e6c76ee557ebfccd560d44f6b6276bbc4e0a8a34 | [
"Apache-2.0"
] | 82 | 2021-12-20T09:15:16.000Z | 2022-03-31T09:33:48.000Z | mhlo_builder/csrc/mlir/mhlo/builder/batch_norm.cpp | JamesTheZ/BladeDISC | e6c76ee557ebfccd560d44f6b6276bbc4e0a8a34 | [
"Apache-2.0"
] | 66 | 2021-12-21T17:28:27.000Z | 2022-03-29T12:08:34.000Z | // Copyright 2021 The BladeDISC 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 "mlir/mhlo/builder/batch_norm.h"
#include "mlir-hlo/Dialect/mhlo/IR/chlo_ops.h"
#include "mlir-hlo/Dialect/mhlo/IR/hlo_ops.h"
#include "mlir/mhlo/builder/mlir_attr_utils.h"
namespace mlir {
namespace mhlo {
mlir::Value BuildBatchNormInference(
mlir::OpBuilder& builder, const mlir::Location& loc,
const mlir::Value& input, const mlir::Value& scale,
const mlir::Value& offset, const mlir::Value& mean,
const mlir::Value& variance, float eps, mlir_dim_t feature_index) {
mlir::FloatAttr eps_attr = builder.getF32FloatAttr(eps);
mlir::IntegerAttr feature_index_attr =
builder.getI64IntegerAttr(feature_index);
auto bn_op = builder.create<mlir::mhlo::BatchNormInferenceOp>(
loc, input.getType(), input, scale, offset, mean, variance, eps_attr,
feature_index_attr);
return bn_op.getResult();
}
} // namespace mhlo
} // namespace mlir
| 39.342105 | 75 | 0.745819 | JamesTheZ |
9cc8d63d5231ad4e74966d401bbc844759622952 | 5,304 | cc | C++ | ppapi/proxy/ppb_flash_menu_proxy.cc | junmin-zhu/chromium-rivertrail | eb1a57aca71fe68d96e48af8998dcfbe45171ee1 | [
"BSD-3-Clause"
] | 5 | 2018-03-10T13:08:42.000Z | 2021-07-26T15:02:11.000Z | proxy/ppb_flash_menu_proxy.cc | ajirios/pepper | 6411800940d2e236de2ac0a667aeea00e028fc35 | [
"BSD-3-Clause"
] | 1 | 2015-07-21T08:02:01.000Z | 2015-07-21T08:02:01.000Z | proxy/ppb_flash_menu_proxy.cc | ajirios/pepper | 6411800940d2e236de2ac0a667aeea00e028fc35 | [
"BSD-3-Clause"
] | 6 | 2016-11-14T10:13:35.000Z | 2021-01-23T15:29:53.000Z | // Copyright (c) 2012 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 "ppapi/proxy/ppb_flash_menu_proxy.h"
#include "ppapi/c/pp_errors.h"
#include "ppapi/c/private/ppb_flash_menu.h"
#include "ppapi/proxy/enter_proxy.h"
#include "ppapi/proxy/ppapi_messages.h"
#include "ppapi/shared_impl/tracked_callback.h"
#include "ppapi/thunk/enter.h"
#include "ppapi/thunk/ppb_flash_menu_api.h"
#include "ppapi/thunk/resource_creation_api.h"
using ppapi::thunk::PPB_Flash_Menu_API;
using ppapi::thunk::ResourceCreationAPI;
namespace ppapi {
namespace proxy {
class FlashMenu : public PPB_Flash_Menu_API, public Resource {
public:
explicit FlashMenu(const HostResource& resource);
virtual ~FlashMenu();
// Resource overrides.
virtual PPB_Flash_Menu_API* AsPPB_Flash_Menu_API() OVERRIDE;
// PPB_Flash_Menu_API implementation.
virtual int32_t Show(const PP_Point* location,
int32_t* selected_id,
scoped_refptr<TrackedCallback> callback) OVERRIDE;
void ShowACK(int32_t selected_id, int32_t result);
private:
scoped_refptr<TrackedCallback> callback_;
int32_t* selected_id_ptr_;
DISALLOW_COPY_AND_ASSIGN(FlashMenu);
};
FlashMenu::FlashMenu(const HostResource& resource)
: Resource(OBJECT_IS_PROXY, resource),
selected_id_ptr_(NULL) {
}
FlashMenu::~FlashMenu() {
}
PPB_Flash_Menu_API* FlashMenu::AsPPB_Flash_Menu_API() {
return this;
}
int32_t FlashMenu::Show(const struct PP_Point* location,
int32_t* selected_id,
scoped_refptr<TrackedCallback> callback) {
if (TrackedCallback::IsPending(callback_))
return PP_ERROR_INPROGRESS;
selected_id_ptr_ = selected_id;
callback_ = callback;
PluginDispatcher::GetForResource(this)->Send(
new PpapiHostMsg_PPBFlashMenu_Show(
API_ID_PPB_FLASH_MENU, host_resource(), *location));
return PP_OK_COMPLETIONPENDING;
}
void FlashMenu::ShowACK(int32_t selected_id, int32_t result) {
*selected_id_ptr_ = selected_id;
TrackedCallback::ClearAndRun(&callback_, result);
}
PPB_Flash_Menu_Proxy::PPB_Flash_Menu_Proxy(Dispatcher* dispatcher)
: InterfaceProxy(dispatcher),
callback_factory_(ALLOW_THIS_IN_INITIALIZER_LIST(this)) {
}
PPB_Flash_Menu_Proxy::~PPB_Flash_Menu_Proxy() {
}
// static
PP_Resource PPB_Flash_Menu_Proxy::CreateProxyResource(
PP_Instance instance_id,
const PP_Flash_Menu* menu_data) {
PluginDispatcher* dispatcher = PluginDispatcher::GetForInstance(instance_id);
if (!dispatcher)
return 0;
HostResource result;
SerializedFlashMenu serialized_menu;
if (!serialized_menu.SetPPMenu(menu_data))
return 0;
dispatcher->Send(new PpapiHostMsg_PPBFlashMenu_Create(
API_ID_PPB_FLASH_MENU, instance_id, serialized_menu, &result));
if (result.is_null())
return 0;
return (new FlashMenu(result))->GetReference();
}
bool PPB_Flash_Menu_Proxy::OnMessageReceived(const IPC::Message& msg) {
if (!dispatcher()->permissions().HasPermission(PERMISSION_FLASH))
return false;
bool handled = true;
IPC_BEGIN_MESSAGE_MAP(PPB_Flash_Menu_Proxy, msg)
IPC_MESSAGE_HANDLER(PpapiHostMsg_PPBFlashMenu_Create,
OnMsgCreate)
IPC_MESSAGE_HANDLER(PpapiHostMsg_PPBFlashMenu_Show,
OnMsgShow)
IPC_MESSAGE_HANDLER(PpapiMsg_PPBFlashMenu_ShowACK,
OnMsgShowACK)
IPC_MESSAGE_UNHANDLED(handled = false)
IPC_END_MESSAGE_MAP()
// FIXME(brettw) handle bad messages!
return handled;
}
void PPB_Flash_Menu_Proxy::OnMsgCreate(PP_Instance instance,
const SerializedFlashMenu& menu_data,
HostResource* result) {
thunk::EnterResourceCreation enter(instance);
if (enter.succeeded()) {
result->SetHostResource(
instance,
enter.functions()->CreateFlashMenu(instance, menu_data.pp_menu()));
}
}
struct PPB_Flash_Menu_Proxy::ShowRequest {
HostResource menu;
int32_t selected_id;
};
void PPB_Flash_Menu_Proxy::OnMsgShow(const HostResource& menu,
const PP_Point& location) {
ShowRequest* request = new ShowRequest;
request->menu = menu;
EnterHostFromHostResourceForceCallback<PPB_Flash_Menu_API> enter(
menu, callback_factory_, &PPB_Flash_Menu_Proxy::SendShowACKToPlugin,
request);
if (enter.succeeded()) {
enter.SetResult(enter.object()->Show(&location, &request->selected_id,
enter.callback()));
}
}
void PPB_Flash_Menu_Proxy::OnMsgShowACK(const HostResource& menu,
int32_t selected_id,
int32_t result) {
EnterPluginFromHostResource<PPB_Flash_Menu_API> enter(menu);
if (enter.failed())
return;
static_cast<FlashMenu*>(enter.object())->ShowACK(selected_id, result);
}
void PPB_Flash_Menu_Proxy::SendShowACKToPlugin(
int32_t result,
ShowRequest* request) {
dispatcher()->Send(new PpapiMsg_PPBFlashMenu_ShowACK(
API_ID_PPB_FLASH_MENU,
request->menu,
request->selected_id,
result));
delete request;
}
} // namespace proxy
} // namespace ppapi
| 30.308571 | 79 | 0.71003 | junmin-zhu |
9cc9823e10b363dd5ebbe9759f53dc502a450c6e | 7,149 | cpp | C++ | source/laplace/platform/linux/linux_input.cpp | automainint/laplace | 66956df506918d48d79527e524ff606bb197d8af | [
"MIT"
] | 3 | 2021-05-17T21:15:28.000Z | 2021-09-06T23:01:52.000Z | source/laplace/platform/linux/linux_input.cpp | automainint/laplace | 66956df506918d48d79527e524ff606bb197d8af | [
"MIT"
] | 33 | 2021-10-20T10:47:07.000Z | 2022-02-26T02:24:20.000Z | source/laplace/platform/linux/linux_input.cpp | automainint/laplace | 66956df506918d48d79527e524ff606bb197d8af | [
"MIT"
] | null | null | null | /* Copyright (c) 2021 Mitya Selivanov
*
* This file is part of the Laplace project.
*
* Laplace 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 MIT License for more details.
*/
#include "input.h"
namespace laplace::linux {
using namespace core::keys;
using std::array;
sl::index const input::default_wheel_scale = 120;
input::input() noexcept {
set_wheel_scale(default_wheel_scale);
}
void input::use_system_cursor(bool) noexcept { }
void input::set_cursor_enabled(bool) noexcept { }
void input::set_mouse_resolution(sl::whole, sl::whole) noexcept { }
void input::set_clamp(bool, bool) noexcept { }
auto input::get_mouse_resolution_x() const noexcept -> sl::whole {
return 0;
}
auto input::get_mouse_resolution_y() const noexcept -> sl::whole {
return 0;
}
auto input::get_mouse_x() const noexcept -> sl::index {
return get_cursor_x();
}
auto input::get_mouse_y() const noexcept -> sl::index {
return get_cursor_y();
}
auto input::get_mouse_delta_x() const noexcept -> sl::index {
return get_cursor_delta_x();
}
auto input::get_mouse_delta_y() const noexcept -> sl::index {
return get_cursor_delta_y();
}
void input::update_button(sl::index button, bool is_down) noexcept {
if (button == Button1)
update_key(in_lbutton, is_down);
if (button == Button2)
update_key(in_mbutton, is_down);
if (button == Button3)
update_key(in_rbutton, is_down);
}
void input::update_controls(sl::index key, bool is_down) noexcept {
auto const code = map_key(key);
switch (code) {
case key_lshift:
case key_rshift: update_key(in_shift, is_down); break;
case key_lcontrol:
case key_rcontrol: update_key(in_control, is_down); break;
case key_lalt:
case key_ralt: update_key(in_alt, is_down); break;
case key_capslock_toggle:
toggle(in_capslock, is_down, m_toggle_capslock);
break;
case key_numlock_toggle:
toggle(in_numlock, is_down, m_toggle_numlock);
break;
case key_scrolllock_toggle:
toggle(in_scrolllock, is_down, m_toggle_scrolllock);
break;
default:;
}
}
void input::init_keymap(Display *display) noexcept {
adjust_and_set_keymap(load_keymap(display));
}
auto input::load_keymap(Display *display) noexcept -> keymap_table {
auto v = keymap_table {};
auto const code = [&](KeySym k) {
return XKeysymToKeycode(display, k);
};
v[code(XK_Left)] = key_left;
v[code(XK_Right)] = key_right;
v[code(XK_Up)] = key_up;
v[code(XK_Down)] = key_down;
v[code(XK_1)] = key_1;
v[code(XK_2)] = key_2;
v[code(XK_3)] = key_3;
v[code(XK_4)] = key_4;
v[code(XK_5)] = key_5;
v[code(XK_6)] = key_6;
v[code(XK_7)] = key_7;
v[code(XK_8)] = key_8;
v[code(XK_9)] = key_9;
v[code(XK_0)] = key_0;
v[code(XK_A)] = key_a;
v[code(XK_B)] = key_b;
v[code(XK_C)] = key_c;
v[code(XK_D)] = key_d;
v[code(XK_E)] = key_e;
v[code(XK_F)] = key_f;
v[code(XK_G)] = key_g;
v[code(XK_H)] = key_h;
v[code(XK_I)] = key_i;
v[code(XK_J)] = key_j;
v[code(XK_K)] = key_k;
v[code(XK_L)] = key_l;
v[code(XK_M)] = key_m;
v[code(XK_N)] = key_n;
v[code(XK_O)] = key_o;
v[code(XK_P)] = key_p;
v[code(XK_Q)] = key_q;
v[code(XK_R)] = key_r;
v[code(XK_S)] = key_s;
v[code(XK_T)] = key_t;
v[code(XK_V)] = key_v;
v[code(XK_W)] = key_w;
v[code(XK_X)] = key_x;
v[code(XK_Y)] = key_y;
v[code(XK_Z)] = key_z;
v[code(XK_space)] = key_space;
v[code(XK_braceleft)] = key_open;
v[code(XK_braceright)] = key_close;
v[code(XK_colon)] = key_semicolon;
v[code(XK_quotedbl)] = key_quote;
v[code(XK_asciitilde)] = key_tilda;
v[code(XK_backslash)] = key_backslash;
v[code(XK_comma)] = key_comma;
v[code(XK_greater)] = key_period;
v[code(XK_question)] = key_slash;
v[code(XK_F1)] = key_f1;
v[code(XK_F2)] = key_f2;
v[code(XK_F3)] = key_f3;
v[code(XK_F4)] = key_f4;
v[code(XK_F5)] = key_f5;
v[code(XK_F6)] = key_f6;
v[code(XK_F7)] = key_f7;
v[code(XK_F8)] = key_f8;
v[code(XK_F9)] = key_f9;
v[code(XK_F10)] = key_f10;
v[code(XK_F11)] = key_f11;
v[code(XK_F12)] = key_f12;
v[code(XK_Control_L)] = key_lcontrol;
v[code(XK_Control_R)] = key_rcontrol;
v[code(XK_Shift_L)] = key_lshift;
v[code(XK_Shift_R)] = key_rshift;
v[code(XK_Alt_L)] = key_lalt;
v[code(XK_Alt_R)] = key_ralt;
v[code(XK_Escape)] = key_escape;
v[code(XK_BackSpace)] = key_backspace;
v[code(XK_Tab)] = key_tab;
v[code(XK_Return)] = key_enter;
v[code(XK_Print)] = key_printscreen;
v[code(XK_Delete)] = key_delete;
v[code(XK_Pause)] = key_pause;
v[code(XK_Insert)] = key_insert;
v[code(XK_Home)] = key_home;
v[code(XK_End)] = key_end;
v[code(XK_Page_Up)] = key_pageup;
v[code(XK_Page_Down)] = key_pagedown;
v[code(XK_KP_0)] = key_numpad0;
v[code(XK_KP_1)] = key_numpad1;
v[code(XK_KP_2)] = key_numpad2;
v[code(XK_KP_3)] = key_numpad3;
v[code(XK_KP_4)] = key_numpad4;
v[code(XK_KP_5)] = key_numpad5;
v[code(XK_KP_6)] = key_numpad6;
v[code(XK_KP_7)] = key_numpad7;
v[code(XK_KP_8)] = key_numpad8;
v[code(XK_KP_9)] = key_numpad9;
v[code(XK_KP_Delete)] = key_delete;
v[code(XK_KP_Enter)] = key_enter;
v[code(XK_KP_Divide)] = key_divide;
v[code(XK_KP_Multiply)] = key_multiply;
v[code(XK_KP_Add)] = key_add;
v[code(XK_KP_Subtract)] = key_subtract;
v[code(XK_KP_Decimal)] = key_decimal;
v[code(XK_KP_Separator)] = key_separator;
v[code(XK_Caps_Lock)] = key_capslock_toggle;
v[code(XK_Num_Lock)] = key_numlock_toggle;
v[code(XK_Scroll_Lock)] = key_scrolllock_toggle;
v[0] = 0;
return v;
}
void input::adjust_and_set_keymap(keymap_table v) noexcept {
auto const find_empty = [&](uint8_t &n) -> uint8_t {
for (n = 1; n != 0; n++)
if (v[n] == 0)
return n;
return 0;
};
v[find_empty(in_lbutton)] = key_lbutton;
v[find_empty(in_rbutton)] = key_rbutton;
v[find_empty(in_mbutton)] = key_mbutton;
v[find_empty(in_xbutton1)] = key_xbutton1;
v[find_empty(in_xbutton2)] = key_xbutton2;
v[find_empty(in_shift)] = key_shift;
v[find_empty(in_control)] = key_control;
v[find_empty(in_alt)] = key_alt;
v[find_empty(in_capslock)] = key_capslock;
v[find_empty(in_numlock)] = key_numlock;
v[find_empty(in_scrolllock)] = key_scrolllock;
v[0] = 0;
set_keymap(v);
}
void input::toggle(sl::index key,
bool is_down,
bool &state) noexcept {
if (is_down)
state = !state;
if (state == is_down)
update_key(key, is_down);
}
}
| 28.710843 | 70 | 0.615611 | automainint |
9cca2064ad3f216a6de0e346f3f9674514489d0e | 591 | cpp | C++ | Plugin/abci/Foundation/aiLogger.cpp | afterwise/AlembicForUnity | c6aa8478f7f5e9278350f29dcbffdaa8422028be | [
"MIT"
] | null | null | null | Plugin/abci/Foundation/aiLogger.cpp | afterwise/AlembicForUnity | c6aa8478f7f5e9278350f29dcbffdaa8422028be | [
"MIT"
] | null | null | null | Plugin/abci/Foundation/aiLogger.cpp | afterwise/AlembicForUnity | c6aa8478f7f5e9278350f29dcbffdaa8422028be | [
"MIT"
] | null | null | null | #include "pch.h"
#include <cstdarg>
void aiLogPrint(const char* fmt, ...)
{
va_list vl;
va_start(vl, fmt);
#ifdef _WIN32
char buf[2048];
vsprintf(buf, fmt, vl);
::OutputDebugStringA(buf);
::OutputDebugStringA("\n");
#else
vprintf(fmt, vl);
#endif
va_end(vl);
}
void aiLogPrint(const wchar_t* fmt, ...)
{
va_list vl;
va_start(vl, fmt);
#ifdef _WIN32
wchar_t buf[2048];
vswprintf(buf, fmt, vl);
::OutputDebugStringW(buf);
::OutputDebugStringW(L"\n");
#else
vwprintf(fmt, vl);
#endif
va_end(vl);
}
| 17.909091 | 41 | 0.582064 | afterwise |
9ccb51e327129e22ecb045c63e79a73ff16eaeb6 | 553 | cpp | C++ | BlackVision/Test/Engine/TestShaderCompilation/Source/TestCombinations.cpp | black-vision-engine/bv-engine | 85089d41bb22afeaa9de070646e12aa1777ecedf | [
"MIT"
] | 1 | 2022-01-28T11:43:47.000Z | 2022-01-28T11:43:47.000Z | BlackVision/Test/Engine/TestShaderCompilation/Source/TestCombinations.cpp | black-vision-engine/bv-engine | 85089d41bb22afeaa9de070646e12aa1777ecedf | [
"MIT"
] | null | null | null | BlackVision/Test/Engine/TestShaderCompilation/Source/TestCombinations.cpp | black-vision-engine/bv-engine | 85089d41bb22afeaa9de070646e12aa1777ecedf | [
"MIT"
] | null | null | null | #include "Framework/FrameworkTest.h"
#include "ShaderCompiler.h"
#include "System/Path.h"
// ***********************
// Tries to compile and link all shaders in combination folder.
SIMPLE_FRAMEWORK_TEST_IN_SUITE( Shaders_Compilation, TestCombinations )
{
auto vsShadersList = Path::List( "Assets/Shaders/Combinations/", true, ".*\\.vert" );
for( auto & vsShaderPath : vsShadersList )
{
auto psPath = FindMatchingPS( vsShaderPath );
TestCompilation( vsShaderPath.Str(), psPath.Str() );
}
}
| 23.041667 | 90 | 0.632911 | black-vision-engine |
9ccc275048bdc734f411beaf2d3e1821e45320d2 | 421 | hpp | C++ | book/cpp_templates/tmplbook/basics/stack8decl.hpp | houruixiang/day_day_learning | 208f70a4f0a85dd99191087835903d279452fd54 | [
"MIT"
] | null | null | null | book/cpp_templates/tmplbook/basics/stack8decl.hpp | houruixiang/day_day_learning | 208f70a4f0a85dd99191087835903d279452fd54 | [
"MIT"
] | null | null | null | book/cpp_templates/tmplbook/basics/stack8decl.hpp | houruixiang/day_day_learning | 208f70a4f0a85dd99191087835903d279452fd54 | [
"MIT"
] | null | null | null | template<typename T,
template<typename Elem> class Cont = std::deque>
class Stack {
private:
Cont<T> elems; // elements
public:
void push(T const&); // push element
void pop(); // pop element
T const& top() const; // return top element
bool empty() const { // return whether the stack is empty
return elems.empty();
}
//...
};
| 26.3125 | 67 | 0.534442 | houruixiang |
9ccd0a2ec195ccb9022d296b0c3adb82d940a1f2 | 4,580 | cpp | C++ | Controls4U/SplitterButton.cpp | XOULID/Anboto | 2743b066f23bf2db9cc062d3adedfd044bc69ec1 | [
"Apache-2.0"
] | null | null | null | Controls4U/SplitterButton.cpp | XOULID/Anboto | 2743b066f23bf2db9cc062d3adedfd044bc69ec1 | [
"Apache-2.0"
] | null | null | null | Controls4U/SplitterButton.cpp | XOULID/Anboto | 2743b066f23bf2db9cc062d3adedfd044bc69ec1 | [
"Apache-2.0"
] | null | null | null | #include <CtrlLib/CtrlLib.h>
#include "SplitterButton.h"
namespace Upp {
SplitterButton::SplitterButton() {
Add(splitter.SizePos());
Add(button1.LeftPosZ(80, 10).TopPosZ(30, 40));
Add(button2.LeftPosZ(80, 10).TopPosZ(30, 40));
splitter.WhenLayout = THISBACK(OnLayout);
button1.WhenAction = THISBACK1(SetButton, 0);
button2.WhenAction = THISBACK1(SetButton, 1);
movingRight = true;
buttonWidth = int(2.5*splitter.GetSplitWidth());
positionId = 0;
SetButtonNumber(2);
splitter.SetPos(5000);
}
SplitterButton& SplitterButton::Horz(Ctrl &left, Ctrl &right) {
splitter.Horz(left, right);
SetPositions(0, 5000, 10000);
SetInitialPositionId(1);
SetArrows();
return *this;
}
SplitterButton& SplitterButton::Vert(Ctrl& top, Ctrl& bottom) {
splitter.Vert(top, bottom);
SetPositions(0, 5000, 10000);
SetInitialPositionId(1);
SetArrows();
return *this;
}
SplitterButton &SplitterButton::SetPositions(const Vector<int> &_positions) {
positions = clone(_positions);
Sort(positions);
if (positionId >= positions.GetCount() || positionId < 0)
positionId = 0;
splitter.SetPos(positions[positionId]);
return *this;
}
SplitterButton &SplitterButton::SetPositions(int pos1) {
Vector<int> pos;
pos << pos1;
SetPositions(pos);
return *this;
}
SplitterButton &SplitterButton::SetPositions(int pos1, int pos2) {
Vector<int> pos;
pos << pos1 << pos2;
SetPositions(pos);
return *this;
}
SplitterButton &SplitterButton::SetPositions(int pos1, int pos2, int pos3) {
Vector<int> pos;
pos << pos1 << pos2 << pos3;
SetPositions(pos);
return *this;
}
SplitterButton &SplitterButton::SetInitialPositionId(int id) {
positionId = id;
splitter.SetPos(positions[positionId]);
SetArrows();
return *this;
}
void SplitterButton::OnLayout(int pos) {
int cwidth, cheight;
if (splitter.IsVert()) {
cwidth = GetSize().cy;
cheight = GetSize().cx;
} else {
cwidth = GetSize().cx;
cheight = GetSize().cy;
}
int posx = max(0, pos - buttonWidth/2);
posx = min(cwidth - buttonWidth, posx);
int posy = (2*cheight)/5;
int widthy;
if (buttonNumber == 1)
widthy = cheight/5;
else
widthy = cheight/8;
if (splitter.IsVert()) {
if (buttonNumber == 1)
button1.SetPos(PosLeft(posy, widthy), PosTop(posx, buttonWidth));
else {
button1.SetPos(PosLeft(posy - widthy/2, widthy), PosTop(posx, buttonWidth));
button2.SetPos(PosLeft(posy + widthy/2, widthy), PosTop(posx, buttonWidth));
}
} else {
if (buttonNumber == 1)
button1.SetPos(PosLeft(posx, buttonWidth), PosTop(posy, widthy));
else {
button1.SetPos(PosLeft(posx, buttonWidth), PosTop(posy - widthy/2, widthy));
button2.SetPos(PosLeft(posx, buttonWidth), PosTop(posy + widthy/2, widthy));
}
}
WhenAction();
}
void SplitterButton::SetButton(int id) {
ASSERT(positions.GetCount() > 1);
int pos = splitter.GetPos();
int closerPositionId = Null;
int closerPosition = 10000;
for (int i = 0; i < positions.GetCount(); ++i)
if (abs(positions[i] - pos) < closerPosition) {
closerPosition = abs(positions[i] - pos);
closerPositionId = i;
}
//bool arrowRight;
if (buttonNumber == 1) {
if (movingRight) {
if (closerPositionId == (positions.GetCount() - 1)) {
movingRight = false;
positionId = positions.GetCount() - 2;
} else
positionId = closerPositionId + 1;
} else {
if (closerPositionId == 0) {
movingRight = true;
positionId = 1;
} else
positionId = closerPositionId - 1;
}
} else {
if (id == 1) {
if (positionId < positions.GetCount() - 1)
positionId++;
} else {
if (positionId > 0)
positionId--;
}
}
splitter.SetPos(positions[positionId]);
SetArrows();
WhenAction();
}
void SplitterButton::SetArrows() {
if (buttonNumber == 1) {
bool arrowRight = movingRight;
if (positionId == (positions.GetCount() - 1))
arrowRight = false;
if (positionId == 0)
arrowRight = true;
if (arrowRight)
button1.SetImage(splitter.IsVert() ? CtrlImg::smalldown() : CtrlImg::smallright());
else
button1.SetImage(splitter.IsVert() ? CtrlImg::smallup() : CtrlImg::smallleft());
} else {
button1.SetImage(splitter.IsVert() ? CtrlImg::smallup() : CtrlImg::smallleft());
button2.SetImage(splitter.IsVert() ? CtrlImg::smalldown() : CtrlImg::smallright());
}
}
CH_STYLE(Box, Style, StyleDefault) {
width = Ctrl::HorzLayoutZoom(2);
vert[0] = horz[0] = SColorFace();
vert[1] = horz[1] = GUI_GlobalStyle() >= GUISTYLE_XP ? Blend(SColorHighlight, SColorFace)
: SColorShadow();
dots = false;
}
} | 23.608247 | 90 | 0.667904 | XOULID |
9ccedb89aa2d4f62ea91fed1ba7baee9a0720032 | 1,471 | cc | C++ | src/base/kaldi-utils.cc | LanceaKing/kaldi | eb205a83f08fb8056ba1deb03c505ec8b722d4d9 | [
"Apache-2.0"
] | 36 | 2019-11-12T22:41:43.000Z | 2022-02-01T15:24:02.000Z | src/base/kaldi-utils.cc | LanceaKing/kaldi | eb205a83f08fb8056ba1deb03c505ec8b722d4d9 | [
"Apache-2.0"
] | 8 | 2017-09-06T00:12:00.000Z | 2019-03-22T08:03:19.000Z | src/base/kaldi-utils.cc | LanceaKing/kaldi | eb205a83f08fb8056ba1deb03c505ec8b722d4d9 | [
"Apache-2.0"
] | 29 | 2020-01-03T22:28:27.000Z | 2022-03-30T23:00:27.000Z | // base/kaldi-utils.cc
// Copyright 2009-2011 Karel Vesely; Yanmin Qian; Microsoft Corporation
// See ../../COPYING for clarification regarding multiple 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
// THIS CODE IS PROVIDED *AS IS* BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
// KIND, EITHER EXPRESS OR IMPLIED, INCLUDING WITHOUT LIMITATION ANY IMPLIED
// WARRANTIES OR CONDITIONS OF TITLE, FITNESS FOR A PARTICULAR PURPOSE,
// MERCHANTABLITY OR NON-INFRINGEMENT.
// See the Apache 2 License for the specific language governing permissions and
// limitations under the License.
#include "base/kaldi-utils.h"
#include <chrono>
#include <cstdio>
#include <thread>
namespace kaldi {
std::string CharToString(const char &c) {
char buf[20];
if (std::isprint(c))
std::snprintf(buf, sizeof(buf), "\'%c\'", c);
else
std::snprintf(buf, sizeof(buf), "[character %d]", static_cast<int>(c));
return buf;
}
void Sleep(double sec) {
// duration_cast<> rounds down, add 0.5 to compensate.
auto dur_nanos = std::chrono::duration<double, std::nano>(sec * 1E9 + 0.5);
auto dur_syshires = std::chrono::duration_cast<
typename std::chrono::high_resolution_clock::duration>(dur_nanos);
std::this_thread::sleep_for(dur_syshires);
}
} // end namespace kaldi
| 31.978261 | 79 | 0.719239 | LanceaKing |
9cd069d0706763fea075a2cff1e7ea529f888998 | 774 | cpp | C++ | src/NoOpReply.cpp | mikz/capybara-webkit | 1ffa80566570cdb33ef17fd197575c07842e51de | [
"MIT"
] | 37 | 2015-01-28T07:34:34.000Z | 2021-06-14T02:17:51.000Z | src/NoOpReply.cpp | mikz/capybara-webkit | 1ffa80566570cdb33ef17fd197575c07842e51de | [
"MIT"
] | 18 | 2015-01-28T08:26:55.000Z | 2018-02-20T14:04:58.000Z | src/NoOpReply.cpp | mikz/capybara-webkit | 1ffa80566570cdb33ef17fd197575c07842e51de | [
"MIT"
] | 36 | 2015-01-29T09:42:47.000Z | 2021-01-22T11:45:43.000Z | #include <QTimer>
#include "NoOpReply.h"
NoOpReply::NoOpReply(QNetworkRequest &request, QObject *parent) : QNetworkReply(parent) {
open(ReadOnly | Unbuffered);
setAttribute(QNetworkRequest::HttpStatusCodeAttribute, 200);
setHeader(QNetworkRequest::ContentLengthHeader, QVariant(0));
setHeader(QNetworkRequest::ContentTypeHeader, QVariant(QString("text/plain")));
setUrl(request.url());
QTimer::singleShot( 0, this, SIGNAL(readyRead()) );
QTimer::singleShot( 0, this, SIGNAL(finished()) );
}
void NoOpReply::abort() {
// NO-OP
}
qint64 NoOpReply::bytesAvailable() const {
return 0;
}
bool NoOpReply::isSequential() const {
return true;
}
qint64 NoOpReply::readData(char *data, qint64 maxSize) {
Q_UNUSED(data);
Q_UNUSED(maxSize);
return 0;
}
| 23.454545 | 89 | 0.726098 | mikz |
9cd1db45f0ccad502076d68221a3c730bd14020f | 1,941 | hpp | C++ | src/ftxui/component/checkbox.hpp | JacobFV/JOSS | f7fa6869764e13387b6ceca862a68cfac64d9047 | [
"MIT"
] | null | null | null | src/ftxui/component/checkbox.hpp | JacobFV/JOSS | f7fa6869764e13387b6ceca862a68cfac64d9047 | [
"MIT"
] | null | null | null | src/ftxui/component/checkbox.hpp | JacobFV/JOSS | f7fa6869764e13387b6ceca862a68cfac64d9047 | [
"MIT"
] | null | null | null | #ifndef FTXUI_COMPONENT_CHECKBOX_HPP
#define FTXUI_COMPONENT_CHECKBOX_HPP
#include <functional> // for function
#include <string> // for allocator, wstring
#include "ftxui/component/component.hpp" // for Component
#include "ftxui/component/component_base.hpp" // for ComponentBase
#include "ftxui/dom/elements.hpp" // for Element, Decorator, inverted, nothing
#include "ftxui/screen/box.hpp" // for Box
#include "ftxui/screen/string.hpp" // for ConstStringRef
namespace ftxui {
struct Event;
/// @brief A Checkbox. It can be checked or unchecked.Display an element on a
/// ftxui::Screen.
/// @ingroup dom
class CheckboxBase : public ComponentBase {
public:
// Access this interface from a Component
static CheckboxBase* From(Component component);
// Constructor.
CheckboxBase(ConstStringRef label, bool* state);
~CheckboxBase() override = default;
#if defined(_WIN32)
std::wstring checked = L"[X] "; /// Prefix for a "checked" state.
std::wstring unchecked = L"[ ] "; /// Prefix for an "unchecked" state.
#else
std::wstring checked = L"▣ "; /// Prefix for a "checked" state.
std::wstring unchecked = L"☐ "; /// Prefix for a "unchecked" state.
#endif
Decorator focused_style = inverted; /// Decorator used when focused.
Decorator unfocused_style = nothing; /// Decorator used when unfocused.
/// Called when the user change the state of the CheckboxBase.
std::function<void()> on_change = []() {};
// Component implementation.
Element Render() override;
bool OnEvent(Event) override;
private:
bool OnMouseEvent(Event event);
ConstStringRef label_;
bool* const state_;
int cursor_position = 0;
Box box_;
};
} // namespace ftxui
#endif /* end of include guard: FTXUI_COMPONENT_CHECKBOX_HPP */
// Copyright 2020 Arthur Sonzogni. All rights reserved.
// Use of this source code is governed by the MIT license that can be found in
// the LICENSE file.
| 31.306452 | 80 | 0.710459 | JacobFV |
9cd2f3499185401f61ebc61e59f089ba8c9ff59f | 161 | hpp | C++ | win32/include/swt/graphics/Resource.hpp | deianvn/swt-plus-plus | e85236e8279b4e6f5993d94d1bd14e6fc7e1dd1b | [
"Apache-2.0"
] | null | null | null | win32/include/swt/graphics/Resource.hpp | deianvn/swt-plus-plus | e85236e8279b4e6f5993d94d1bd14e6fc7e1dd1b | [
"Apache-2.0"
] | null | null | null | win32/include/swt/graphics/Resource.hpp | deianvn/swt-plus-plus | e85236e8279b4e6f5993d94d1bd14e6fc7e1dd1b | [
"Apache-2.0"
] | null | null | null | #ifndef SWT_PLUS_PLUS_RESOURCE_H
#define SWT_PLUS_PLUS_RESOURCE_H
namespace swt
{
class Resource {
public:
};
}
#endif //SWT_PLUS_PLUS_RESOURCE_H
| 12.384615 | 33 | 0.745342 | deianvn |
9cd334187a6698cd26fde563fc57f4b08c76503b | 2,603 | cpp | C++ | src/SerialWombatWS2812.cpp | BroadwellConsultingInc/SerialWombatArdLib | 856fdb89074892caf94f939cff4c4eb5ece2d7c3 | [
"MIT"
] | null | null | null | src/SerialWombatWS2812.cpp | BroadwellConsultingInc/SerialWombatArdLib | 856fdb89074892caf94f939cff4c4eb5ece2d7c3 | [
"MIT"
] | 2 | 2021-08-14T01:04:06.000Z | 2022-01-30T15:04:24.000Z | src/SerialWombatWS2812.cpp | BroadwellConsultingInc/SerialWombatArdLib | 856fdb89074892caf94f939cff4c4eb5ece2d7c3 | [
"MIT"
] | 1 | 2022-01-30T14:46:38.000Z | 2022-01-30T14:46:38.000Z | #include "SerialWombat.h"
SerialWombatWS2812::SerialWombatWS2812(SerialWombat& serialWombat)
{
_sw = &serialWombat;
}
int16_t SerialWombatWS2812::begin(uint8_t pin, uint8_t numberOfLEDs, uint16_t userBufferIndex)
{
_pin = pin;
_numLEDS = numberOfLEDs;
_userBufferIndex = userBufferIndex;
uint8_t tx[8] = { 200,_pin,12,SW_LE16(userBufferIndex),_numLEDS,0x55 };
return (_sw->sendPacket(tx));
}
int16_t SerialWombatWS2812::write(uint8_t led, uint32_t color)
{
uint8_t tx[8] = { 201,_pin,12,led,SW_LE32(color) };
tx[7] = 0x55;
return _sw->sendPacket(tx);
}
int16_t SerialWombatWS2812::write(uint8_t led, int16_t color)
{
return write(led, (uint32_t)color);
}
int16_t SerialWombatWS2812::write(uint8_t led, int32_t color)
{
return write(led, (uint32_t)color);
}
int16_t SerialWombatWS2812::write(uint8_t led, uint8_t length, uint32_t colors[])
{
for (int i = 0; i < length; ++i)
{
int16_t result =
write(led + i, colors[i]);
if (result < 0)
{
return (result);
}
}
return(0);
}
int16_t SerialWombatWS2812::writeAnimationLED(uint8_t frame, uint8_t led, uint32_t color)
{
uint8_t tx[8] = { 203,_pin,12,frame,led,(color >>16 ) & 0xFF,(color >> 8) & 0xFF, color & 0xFF };
return _sw->sendPacket(tx);
}
int16_t SerialWombatWS2812::writeAnimationLED(uint8_t frame, uint8_t led, int16_t color)
{
writeAnimationLED(frame, led,(uint32_t)color);
}
int16_t SerialWombatWS2812::writeAnimationLED(uint8_t frame, uint8_t led, int32_t color)
{
writeAnimationLED(frame, led, (uint32_t)color);
}
int16_t SerialWombatWS2812::writeAnimationFrame(uint8_t frame, uint32_t colors[])
{
for (int i = 0; i < _numLEDS; ++i)
{
int16_t result;
result = writeAnimationLED(frame, i, colors[i]);
if (result < 0)
{
return (result);
}
}
return(0);
}
int16_t SerialWombatWS2812::writeAnimationFrameDelay(uint8_t frame, uint16_t delay_mS)
{
uint8_t tx[8] = { 205,_pin,12,frame,SW_LE16(delay_mS),0x55,0x55 };
return (_sw->sendPacket(tx));
}
int16_t SerialWombatWS2812::writeAnimationUserBufferIndex(uint16_t index, uint8_t numberOfFrames)
{
uint8_t tx[8] = { 204,_pin,12,SW_LE16(index),numberOfFrames,0x55,0x55 };
return (_sw->sendPacket(tx));
}
int16_t SerialWombatWS2812::readBufferSize()
{
uint8_t tx[8] = { 202,_pin,12,_numLEDS,0x55,0x55,0x55,0x55 };
uint8_t rx[8];
int16_t result = _sw->sendPacket(tx,rx);
if (result >= 0)
{
return (rx[3] + rx[4] * 256);
}
else
{
return (result);
}
return int16_t();
}
int16_t SerialWombatWS2812::setMode(SWWS2812Mode mode)
{
uint8_t tx[8] = { 206,_pin,12,mode,0x55,0x55,0x55,0x55 };
return _sw->sendPacket(tx);
}
| 22.059322 | 98 | 0.71456 | BroadwellConsultingInc |
9cd339c28828916e740dc3b0c182a88726a87240 | 1,949 | hpp | C++ | tests/system/test_boost_parts/sources_changed/interprocess/sync/windows/named_recursive_mutex.hpp | iazarov/metrixplusplus | 322777cba4e089502dd6053749b07a7be9da65b2 | [
"MIT"
] | 198 | 2015-01-13T05:47:18.000Z | 2022-03-09T04:46:46.000Z | tests/system/test_boost_parts/sources_changed/interprocess/sync/windows/named_recursive_mutex.hpp | iazarov/metrixplusplus | 322777cba4e089502dd6053749b07a7be9da65b2 | [
"MIT"
] | 197 | 2017-07-06T16:53:59.000Z | 2019-05-31T17:57:51.000Z | tests/system/test_boost_parts/sources_changed/interprocess/sync/windows/named_recursive_mutex.hpp | iazarov/metrixplusplus | 322777cba4e089502dd6053749b07a7be9da65b2 | [
"MIT"
] | 139 | 2015-01-15T20:09:31.000Z | 2022-01-31T15:21:16.000Z | //////////////////////////////////////////////////////////////////////////////
//
// (C) Copyright Ion Gaztanaga 2011-2012. Distributed under the Boost
// Software License, Version 1.0. (See accompanying file
// LICENSE_1_0.txt or copy at http://www.boost.org/LICENSE_1_0.txt)
//
// See http://www.boost.org/libs/interprocess for documentation.
//
//////////////////////////////////////////////////////////////////////////////
#ifndef BOOST_INTERPROCESS_WINDOWS_RECURSIVE_NAMED_MUTEX_HPP
#define BOOST_INTERPROCESS_WINDOWS_RECURSIVE_NAMED_MUTEX_HPP
#if (defined _MSC_VER) && (_MSC_VER >= 1200)
# pragma once
#endif
#include <boost/interprocess/detail/config_begin.hpp>
#include <boost/interprocess/detail/workaround.hpp>
#include <boost/interprocess/sync/windows/named_mutex.hpp>
namespace boost {
namespace interprocess {
namespace ipcdetail {
class windows_named_recursive_mutex
//Windows mutexes based on CreateMutex are already recursive...
: public windows_named_mutex
{
/// @cond
//Non-copyable
windows_named_recursive_mutex();
windows_named_recursive_mutex(const windows_named_mutex &);
windows_named_recursive_mutex &operator=(const windows_named_mutex &);
/// @endcond
public:
windows_named_recursive_mutex(create_only_t, const char *name, const permissions &perm = permissions())
: windows_named_mutex(create_only_t(), name, perm)
{}
windows_named_recursive_mutex(open_or_create_t, const char *name, const permissions &perm = permissions())
: windows_named_mutex(open_or_create_t(), name, perm)
{}
windows_named_recursive_mutex(open_only_t, const char *name)
: windows_named_mutex(open_only_t(), name)
{}
};
} //namespace ipcdetail {
} //namespace interprocess {
} //namespace boost {
#include <boost/interprocess/detail/config_end.hpp>
#endif //BOOST_INTERPROCESS_WINDOWS_RECURSIVE_NAMED_MUTEX_HPP
| 33.033898 | 110 | 0.680862 | iazarov |
9cd3490cce2905d6bc02a256eaa3c48c8bb088aa | 6,506 | hpp | C++ | libraries/chain/include/enumivo/chain/database_utils.hpp | TP-Lab/enumivo | 76d81a36d2db8cea93fb54cd95a6ec5f6c407f97 | [
"MIT"
] | null | null | null | libraries/chain/include/enumivo/chain/database_utils.hpp | TP-Lab/enumivo | 76d81a36d2db8cea93fb54cd95a6ec5f6c407f97 | [
"MIT"
] | null | null | null | libraries/chain/include/enumivo/chain/database_utils.hpp | TP-Lab/enumivo | 76d81a36d2db8cea93fb54cd95a6ec5f6c407f97 | [
"MIT"
] | null | null | null | /**
* @file
* @copyright defined in enumivo/LICENSE
*/
#pragma once
#include <enumivo/chain/types.hpp>
#include <fc/io/raw.hpp>
#include <softfloat.hpp>
namespace enumivo { namespace chain {
template<typename ...Indices>
class index_set;
template<typename Index>
class index_utils {
public:
using index_t = Index;
template<typename F>
static void walk( const chainbase::database& db, F function ) {
auto const& index = db.get_index<Index>().indices();
const auto& first = index.begin();
const auto& last = index.end();
for (auto itr = first; itr != last; ++itr) {
function(*itr);
}
}
template<typename Secondary, typename Key, typename F>
static void walk_range( const chainbase::database& db, const Key& begin_key, const Key& end_key, F function ) {
const auto& idx = db.get_index<Index, Secondary>();
auto begin_itr = idx.lower_bound(begin_key);
auto end_itr = idx.lower_bound(end_key);
for (auto itr = begin_itr; itr != end_itr; ++itr) {
function(*itr);
}
}
template<typename Secondary, typename Key>
static size_t size_range( const chainbase::database& db, const Key& begin_key, const Key& end_key ) {
const auto& idx = db.get_index<Index, Secondary>();
auto begin_itr = idx.lower_bound(begin_key);
auto end_itr = idx.lower_bound(end_key);
size_t res = 0;
while (begin_itr != end_itr) {
res++; ++begin_itr;
}
return res;
}
template<typename F>
static void create( chainbase::database& db, F cons ) {
db.create<typename index_t::value_type>(cons);
}
};
template<typename Index>
class index_set<Index> {
public:
static void add_indices( chainbase::database& db ) {
db.add_index<Index>();
}
template<typename F>
static void walk_indices( F function ) {
function( index_utils<Index>() );
}
};
template<typename FirstIndex, typename ...RemainingIndices>
class index_set<FirstIndex, RemainingIndices...> {
public:
static void add_indices( chainbase::database& db ) {
index_set<FirstIndex>::add_indices(db);
index_set<RemainingIndices...>::add_indices(db);
}
template<typename F>
static void walk_indices( F function ) {
index_set<FirstIndex>::walk_indices(function);
index_set<RemainingIndices...>::walk_indices(function);
}
};
template<typename DataStream>
DataStream& operator << ( DataStream& ds, const shared_blob& b ) {
fc::raw::pack(ds, static_cast<const shared_string&>(b));
return ds;
}
template<typename DataStream>
DataStream& operator >> ( DataStream& ds, shared_blob& b ) {
fc::raw::unpack(ds, static_cast<shared_string &>(b));
return ds;
}
} }
namespace fc {
// overloads for to/from_variant
template<typename OidType>
void to_variant( const chainbase::oid<OidType>& oid, variant& v ) {
v = variant(oid._id);
}
template<typename OidType>
void from_variant( const variant& v, chainbase::oid<OidType>& oid ) {
from_variant(v, oid._id);
}
inline
void to_variant( const float64_t& f, variant& v ) {
v = variant(*reinterpret_cast<const double*>(&f));
}
inline
void from_variant( const variant& v, float64_t& f ) {
from_variant(v, *reinterpret_cast<double*>(&f));
}
inline
void to_variant( const float128_t& f, variant& v ) {
v = variant(*reinterpret_cast<const uint128_t*>(&f));
}
inline
void from_variant( const variant& v, float128_t& f ) {
from_variant(v, *reinterpret_cast<uint128_t*>(&f));
}
inline
void to_variant( const enumivo::chain::shared_string& s, variant& v ) {
v = variant(std::string(s.begin(), s.end()));
}
inline
void from_variant( const variant& v, enumivo::chain::shared_string& s ) {
string _s;
from_variant(v, _s);
s = enumivo::chain::shared_string(_s.begin(), _s.end(), s.get_allocator());
}
inline
void to_variant( const enumivo::chain::shared_blob& b, variant& v ) {
v = variant(base64_encode(b.data(), b.size()));
}
inline
void from_variant( const variant& v, enumivo::chain::shared_blob& b ) {
string _s = base64_decode(v.as_string());
b = enumivo::chain::shared_blob(_s.begin(), _s.end(), b.get_allocator());
}
inline
void to_variant( const blob& b, variant& v ) {
v = variant(base64_encode(b.data.data(), b.data.size()));
}
inline
void from_variant( const variant& v, blob& b ) {
string _s = base64_decode(v.as_string());
b.data = std::vector<char>(_s.begin(), _s.end());
}
template<typename T>
void to_variant( const enumivo::chain::shared_vector<T>& sv, variant& v ) {
to_variant(std::vector<T>(sv.begin(), sv.end()), v);
}
template<typename T>
void from_variant( const variant& v, enumivo::chain::shared_vector<T>& sv ) {
std::vector<T> _v;
from_variant(v, _v);
sv = enumivo::chain::shared_vector<T>(_v.begin(), _v.end(), sv.get_allocator());
}
}
namespace chainbase {
// overloads for OID packing
template<typename DataStream, typename OidType>
DataStream& operator << ( DataStream& ds, const oid<OidType>& oid ) {
fc::raw::pack(ds, oid._id);
return ds;
}
template<typename DataStream, typename OidType>
DataStream& operator >> ( DataStream& ds, oid<OidType>& oid ) {
fc::raw::unpack(ds, oid._id);
return ds;
}
}
// overloads for softfloat packing
template<typename DataStream>
DataStream& operator << ( DataStream& ds, const float64_t& v ) {
fc::raw::pack(ds, *reinterpret_cast<const double *>(&v));
return ds;
}
template<typename DataStream>
DataStream& operator >> ( DataStream& ds, float64_t& v ) {
fc::raw::unpack(ds, *reinterpret_cast<double *>(&v));
return ds;
}
template<typename DataStream>
DataStream& operator << ( DataStream& ds, const float128_t& v ) {
fc::raw::pack(ds, *reinterpret_cast<const enumivo::chain::uint128_t*>(&v));
return ds;
}
template<typename DataStream>
DataStream& operator >> ( DataStream& ds, float128_t& v ) {
fc::raw::unpack(ds, *reinterpret_cast<enumivo::chain::uint128_t*>(&v));
return ds;
}
| 29.707763 | 120 | 0.618352 | TP-Lab |
9cd3dda963caab637c859dd1c34fc157105b11fc | 3,411 | cpp | C++ | tests/test_coefficient_ops.cpp | PayasR/DwellRegions-open | 72d8c4a7a5e6d2981005b2ac1182441e227d7314 | [
"BSD-3-Clause"
] | null | null | null | tests/test_coefficient_ops.cpp | PayasR/DwellRegions-open | 72d8c4a7a5e6d2981005b2ac1182441e227d7314 | [
"BSD-3-Clause"
] | null | null | null | tests/test_coefficient_ops.cpp | PayasR/DwellRegions-open | 72d8c4a7a5e6d2981005b2ac1182441e227d7314 | [
"BSD-3-Clause"
] | null | null | null | #include "../include/coefficient.hpp"
#include <iostream>
#include <random>
#include <vector>
using DwellRegions::Coefficient;
auto
generate_random_coefficients(size_t num_points)
{
std::random_device rd; // Will be used to obtain a seed for the random number engine
std::mt19937 gen(rd()); // Standard mersenne_twister_engine seeded with rd()
std::uniform_real_distribution<> distribution(0.0, 180.0);
std::vector<Coefficient> coefficients;
coefficients.reserve(num_points);
for (size_t i = 0; i < num_points; i++) {
// Use dis to transform the random unsigned int generated by gen into a
// double in [1, 2). Each call to dis(gen) generates a new random double
coefficients.emplace_back(DwellRegions::Coefficient::from_double(distribution(gen)));
}
return coefficients;
}
void
print_coefficients(const std::vector<Coefficient>& coefficients)
{
for (const auto& c : coefficients) {
std::cout << c.val() << " " << c.as_float() << std::endl;
}
}
// Pairwise subtract the coefficients
void
subtraction_test(const std::vector<Coefficient>& coefficients)
{
std::cout << "---------- Subtraction test--------------" << std::endl;
for (size_t i = 1; i < coefficients.size(); i++) {
std::cout << coefficients[i - 1].as_float() << " - " << coefficients[i].as_float() << " = ";
const auto res = (coefficients[i - 1] - coefficients[i]).as_float();
const auto float_res = coefficients[i - 1].as_float() - coefficients[i].as_float();
if (res != float_res) {
std::cout << "Error: mismatch! res = " << res << " \t Float res = " << float_res << std::endl;
} else {
std::cout << "Ok." << std::endl;
}
}
}
// Pairwise multiply the coefficients
void
multiplication_test(const std::vector<Coefficient>& coefficients)
{
std::cout << "---------- Multiplication test--------------" << std::endl;
for (size_t i = 1; i < coefficients.size(); i++) {
std::cout << coefficients[i - 1].as_float() << " * " << coefficients[i].as_float() << " = ";
const auto res = (coefficients[i - 1] * coefficients[i]).as_float();
const auto float_res = coefficients[i - 1].as_float() * coefficients[i].as_float();
if (res != float_res) {
std::cout << "Error: mismatch! res = " << res << " \t Float res = " << float_res << std::endl;
} else {
std::cout << "Ok." << std::endl;
}
}
}
// Pairwise divide the coefficients
void
division_test(const std::vector<Coefficient>& coefficients)
{
std::cout << "---------- Division test--------------" << std::endl;
for (size_t i = 1; i < coefficients.size(); i++) {
std::cout << coefficients[i - 1].as_float() << " / " << coefficients[i].as_float() << " = ";
const auto res = (coefficients[i - 1] / coefficients[i]).as_float();
const auto float_res = coefficients[i - 1].as_float() / coefficients[i].as_float();
if (res != float_res) {
std::cout << "Error: mismatch! res = " << res << " \t Float res = " << float_res << std::endl;
} else {
std::cout << "Ok." << std::endl;
}
}
}
int
main()
{
const size_t num_coefficients = 10;
const auto coefficients = generate_random_coefficients(num_coefficients);
std::cout << "---------- Original Coefficients --------------" << std::endl;
print_coefficients(coefficients);
subtraction_test(coefficients);
multiplication_test(coefficients);
division_test(coefficients);
return 0;
} | 34.11 | 100 | 0.623864 | PayasR |
9cd48a50320620a02d83b09e89fdf0a874192d11 | 18,036 | cpp | C++ | groups/lsp/lspcore/lspcore_arithmeticutil.cpp | dgoffredo/bdelisp | ea1411cd99aa69605f0a8281fe3be89db09c4aac | [
"blessing"
] | null | null | null | groups/lsp/lspcore/lspcore_arithmeticutil.cpp | dgoffredo/bdelisp | ea1411cd99aa69605f0a8281fe3be89db09c4aac | [
"blessing"
] | null | null | null | groups/lsp/lspcore/lspcore_arithmeticutil.cpp | dgoffredo/bdelisp | ea1411cd99aa69605f0a8281fe3be89db09c4aac | [
"blessing"
] | null | null | null | #include <bdlb_arrayutil.h>
#include <bdlb_bitutil.h>
#include <bdld_datummaker.h>
#include <bdldfp_decimal.h>
#include <bdldfp_decimalutil.h>
#include <bsl_algorithm.h>
#include <bsl_cmath.h>
#include <bsl_functional.h>
#include <bsl_limits.h>
#include <bsl_numeric.h>
#include <bsl_utility.h>
#include <bslmf_assert.h>
#include <bsls_assert.h>
#include <bsls_types.h>
#include <lspcore_arithmeticutil.h>
#include <math.h> // isnan
using namespace BloombergLP;
namespace lspcore {
namespace {
template <typename RESULT>
RESULT the(const bdld::Datum&);
template <>
bdldfp::Decimal64 the<bdldfp::Decimal64>(const bdld::Datum& datum) {
return datum.theDecimal64();
}
template <>
bsls::Types::Int64 the<bsls::Types::Int64>(const bdld::Datum& datum) {
return datum.theInteger64();
}
template <>
int the<int>(const bdld::Datum& datum) {
return datum.theInteger();
}
template <>
double the<double>(const bdld::Datum& datum) {
return datum.theDouble();
}
template <template <typename> class OPERATOR, typename NUMBER>
struct Operator {
NUMBER operator()(NUMBER soFar, const bdld::Datum& number) const {
return OPERATOR<NUMBER>()(soFar, the<NUMBER>(number));
}
};
struct Classification {
enum Kind {
e_COMMON_TYPE,
e_SAME_TYPE,
e_ERROR_INCOMPATIBLE_NUMBER_TYPES,
e_ERROR_NON_NUMERIC_TYPE
};
Kind kind;
bdld::Datum::DataType type;
};
typedef bsls::Types::Uint64 Bits;
// There must be no more than 64 types of 'bdld::Datum', otherwise we wouldn't
// be able to use the type 'Bits' as a bitmask. In some far infinite future, we
// could switch to 'std::bitset' if necessary.
BSLMF_ASSERT(bdld::Datum::k_NUM_TYPES <= bsl::numeric_limits<Bits>::digits);
Classification classify(Bits types) {
// cases:
//
// - any non-number types → e_ERROR_NON_NUMERIC_TYPE
// - incompatible type combinations → e_ERROR_INCOMPATIBLE_NUMBER_TYPES
// - all the same → e_SAME_TYPE
// - otherwise, pick out the common type → e_COMMON_TYPE
#define TYPE(NAME) (Bits(1) << bdld::Datum::e_##NAME)
const Bits numbers =
TYPE(INTEGER) | TYPE(INTEGER64) | TYPE(DOUBLE) | TYPE(DECIMAL64);
const Bits invalidCombos[] = { TYPE(INTEGER64) | TYPE(DOUBLE),
TYPE(INTEGER64) | TYPE(DECIMAL64),
TYPE(DOUBLE) | TYPE(DECIMAL64) };
// check for non-number types
if (types & ~numbers) {
Classification result;
result.kind = Classification::e_ERROR_NON_NUMERIC_TYPE;
return result;
}
// check for incompatible combinations of number types
for (bsl::size_t i = 0; i < bdlb::ArrayUtil::size(invalidCombos); ++i) {
if ((types & invalidCombos[i]) == invalidCombos[i]) {
Classification result;
result.kind = Classification::e_ERROR_INCOMPATIBLE_NUMBER_TYPES;
return result;
}
}
// check for all-the-same-number-type
Classification result;
switch (types) {
case TYPE(INTEGER):
result.kind = Classification::e_SAME_TYPE;
result.type = bdld::Datum::e_INTEGER;
return result;
case TYPE(INTEGER64):
result.kind = Classification::e_SAME_TYPE;
result.type = bdld::Datum::e_INTEGER64;
return result;
case TYPE(DOUBLE):
result.kind = Classification::e_SAME_TYPE;
result.type = bdld::Datum::e_DOUBLE;
return result;
case TYPE(DECIMAL64):
result.kind = Classification::e_SAME_TYPE;
result.type = bdld::Datum::e_DECIMAL64;
return result;
default:
break;
}
// At this point, we have exactly two number types, and one of them is int.
// The common type is just the other type.
result.kind = Classification::e_COMMON_TYPE;
switch (const Bits other = types & ~TYPE(INTEGER)) {
case TYPE(INTEGER64):
result.type = bdld::Datum::e_INTEGER64;
return result;
case TYPE(DOUBLE):
result.type = bdld::Datum::e_DOUBLE;
return result;
default:
(void)other;
BSLS_ASSERT(other == TYPE(DECIMAL64));
result.type = bdld::Datum::e_DECIMAL64;
return result;
}
}
Classification classify(const bsl::vector<bdld::Datum>& data) {
Bits types = 0;
for (bsl::size_t i = 0; i < data.size(); ++i) {
types |= Bits(1) << data[i].type();
}
return classify(types);
}
template <typename NUMBER>
void homogeneousAdd(bsl::vector<bdld::Datum>& argsAndOutput,
bslma::Allocator* allocator) {
const NUMBER result = bsl::accumulate(argsAndOutput.begin(),
argsAndOutput.end(),
NUMBER(0),
Operator<bsl::plus, NUMBER>());
argsAndOutput.resize(1);
argsAndOutput[0] = bdld::DatumMaker(allocator)(result);
}
template <typename NUMBER>
void homogeneousSubtract(bsl::vector<bdld::Datum>& argsAndOutput,
bslma::Allocator* allocator) {
BSLS_ASSERT(!argsAndOutput.empty());
NUMBER result;
if (argsAndOutput.size() == 1) {
result = -the<NUMBER>(argsAndOutput[0]);
}
else {
result = bsl::accumulate(argsAndOutput.begin() + 1,
argsAndOutput.end(),
the<NUMBER>(argsAndOutput[0]),
Operator<bsl::minus, NUMBER>());
}
argsAndOutput.resize(1);
argsAndOutput[0] = bdld::DatumMaker(allocator)(result);
}
template <typename NUMBER>
void homogeneousMultiply(bsl::vector<bdld::Datum>& argsAndOutput,
bslma::Allocator* allocator) {
const NUMBER result = bsl::accumulate(argsAndOutput.begin(),
argsAndOutput.end(),
NUMBER(1),
Operator<bsl::multiplies, NUMBER>());
argsAndOutput.resize(1);
argsAndOutput[0] = bdld::DatumMaker(allocator)(result);
}
template <typename NUMBER>
void homogeneousDivide(bsl::vector<bdld::Datum>& argsAndOutput,
bslma::Allocator* allocator) {
BSLS_ASSERT(!argsAndOutput.empty());
NUMBER result;
if (argsAndOutput.size() == 1) {
result = the<NUMBER>(argsAndOutput[0]);
}
else {
result = bsl::accumulate(argsAndOutput.begin() + 1,
argsAndOutput.end(),
the<NUMBER>(argsAndOutput[0]),
Operator<bsl::divides, NUMBER>());
}
argsAndOutput.resize(1);
argsAndOutput[0] = bdld::DatumMaker(allocator)(result);
}
template <typename OUTPUT>
class NumericConvert {
bdld::DatumMaker d_make;
public:
explicit NumericConvert(bslma::Allocator* allocator)
: d_make(allocator) {
}
bdld::Datum operator()(const bdld::Datum& datum) const {
if (datum.type() == bdld::Datum::e_INTEGER) {
OUTPUT number(datum.theInteger());
return d_make(number);
}
return datum;
}
};
// TODO: document
bdld::Datum::DataType normalizeTypes(bsl::vector<bdld::Datum>& data,
bslma::Allocator* allocator) {
Classification result = classify(data);
switch (result.kind) {
case Classification::e_COMMON_TYPE:
switch (result.type) {
case bdld::Datum::e_INTEGER64:
bsl::transform(
data.begin(),
data.end(),
data.begin(),
NumericConvert<bsls::Types::Int64>(allocator));
break;
case bdld::Datum::e_DOUBLE:
bsl::transform(data.begin(),
data.end(),
data.begin(),
NumericConvert<double>(allocator));
break;
default:
BSLS_ASSERT(result.type == bdld::Datum::e_DECIMAL64);
bsl::transform(
data.begin(),
data.end(),
data.begin(),
NumericConvert<bdldfp::Decimal64>(allocator));
}
// fall through
case Classification::e_SAME_TYPE:
return result.type;
case Classification::e_ERROR_INCOMPATIBLE_NUMBER_TYPES:
throw bdld::Datum::createError(
-1,
"incompatible numeric types passed to an arithmetic procedure",
allocator);
default:
BSLS_ASSERT(result.kind ==
Classification::e_ERROR_NON_NUMERIC_TYPE);
throw bdld::Datum::createError(
-1,
"non-numeric type passed to an arithmetic procedure",
allocator);
}
}
int divideFives(bsl::uint64_t* ptr) {
BSLS_ASSERT(ptr);
bsl::uint64_t& value = *ptr;
BSLS_ASSERT(value != 0);
int count;
for (count = 0; value % 5 == 0; ++count) {
value /= 5;
}
return count;
}
bool notEqual(double binary, bdldfp::Decimal64 decimal) {
// Ladies and gentlemen, I present to you the least efficient equality
// predicate ever devised.
//
// The plan is to divide out the factors of 2 and 5 from the significands
// of 'binary' and 'decimal'. Since the radix of 'binary' is 2 and the
// radix of 'decimal' is 10 (which is 2*5), we can then compare the reduced
// significands and the exponents.
//
// One optimization is possible for "find the factors of two in the
// significand." For nonzero values, we can count the number of trailing
// zero bits (that's the number of factors of two) and then shift right
// that many bits.
//
// Factors of five we'll have to do the hard way, but we need check the
// powers of five only if the powers of two happen to be equal.
// 'bsl::uint64_t' and 'bsls::Types::Uint64' can be different types, and
// the compiler will complain about aliasing. Here I just pick one and
// copy to the other where necessary.
typedef bsl::uint64_t Uint64;
bsls::Types::Uint64 decimalMantissaArg; // long vs. long long ugh...
int decimalSign; // -1 or +1
int decimalExponent;
switch (
const int kind = bdldfp::DecimalUtil::decompose(
&decimalSign, &decimalMantissaArg, &decimalExponent, decimal)) {
case FP_NAN:
return true;
case FP_INFINITE:
return binary !=
bsl::numeric_limits<double>::infinity() * decimalSign;
case FP_SUBNORMAL:
// same handling as in the 'FP_NORMAL' case ('default', below)
break;
case FP_ZERO:
return binary != 0;
default:
(void)kind;
BSLS_ASSERT(kind == FP_NORMAL);
}
Uint64 decimalMantissa = decimalMantissaArg; // long vs. long long ugh...
// Skip the calculations below if the values have different signs.
const int binarySign = binary < 0 ? -1 : 1;
if (decimalSign != binarySign) {
return true;
}
// To decompose the binary floating point value, we use the standard
// library function 'frexp' followed by a multiplication to guarantee an
// integer-valued significand. This multiplication will not lose precision.
int binaryExponent;
const double binaryNormalizedSignificand =
std::frexp(binary, &binaryExponent);
if (binaryNormalizedSignificand == 0 ||
isnan(binaryNormalizedSignificand) ||
binaryNormalizedSignificand ==
std::numeric_limits<double>::infinity() ||
binaryNormalizedSignificand ==
-std::numeric_limits<double>::infinity()) {
return true;
}
const int precision = 53;
Uint64 binaryMantissa =
binaryNormalizedSignificand * (Uint64(1) << (precision - 1));
binaryExponent -= precision - 1;
BSLS_ASSERT(binaryMantissa != 0);
BSLS_ASSERT(decimalMantissa != 0);
const int binaryUnset =
bdlb::BitUtil::numTrailingUnsetBits(binaryMantissa);
const int binaryTwos = binaryExponent + binaryUnset;
const int decimalUnset =
bdlb::BitUtil::numTrailingUnsetBits(decimalMantissa);
const int decimalTwos = decimalExponent + decimalUnset;
if (binaryTwos != decimalTwos) {
return true;
}
binaryMantissa >>= binaryUnset;
decimalMantissa >>= decimalUnset;
const int binaryFives = divideFives(&binaryMantissa);
const int decimalFives = decimalExponent + divideFives(&decimalMantissa);
return binaryFives != decimalFives || binaryMantissa != decimalMantissa;
}
class NotEqual {
bslma::Allocator* d_allocator_p;
public:
explicit NotEqual(bslma::Allocator* allocator)
: d_allocator_p(allocator) {
}
bool operator()(const bdld::Datum& left, const bdld::Datum& right) const {
if (left.type() == right.type()) {
return left != right;
}
#define TYPE_PAIR(LEFT, RIGHT) \
((bsl::uint64_t(LEFT) << 32) | bsl::uint64_t(RIGHT))
switch (TYPE_PAIR(left.type(), right.type())) {
case TYPE_PAIR(bdld::Datum::e_INTEGER, bdld::Datum::e_INTEGER64):
return left.theInteger() != right.theInteger64();
case TYPE_PAIR(bdld::Datum::e_INTEGER64, bdld::Datum::e_INTEGER):
return right.theInteger() != left.theInteger64();
case TYPE_PAIR(bdld::Datum::e_INTEGER, bdld::Datum::e_DOUBLE):
return left.theInteger() != right.theDouble();
case TYPE_PAIR(bdld::Datum::e_DOUBLE, bdld::Datum::e_INTEGER):
return right.theInteger() != left.theDouble();
case TYPE_PAIR(bdld::Datum::e_INTEGER, bdld::Datum::e_DECIMAL64):
return bdldfp::Decimal64(left.theInteger()) !=
right.theDecimal64();
case TYPE_PAIR(bdld::Datum::e_DECIMAL64, bdld::Datum::e_INTEGER):
return bdldfp::Decimal64(right.theInteger()) !=
left.theDecimal64();
case TYPE_PAIR(bdld::Datum::e_DOUBLE, bdld::Datum::e_DECIMAL64):
return notEqual(left.theDouble(), right.theDecimal64());
case TYPE_PAIR(bdld::Datum::e_DECIMAL64, bdld::Datum::e_DOUBLE):
return notEqual(right.theDouble(), left.theDecimal64());
default: {
bsl::ostringstream error;
error << "Numbers have incompatible types: " << left << " and "
<< right;
throw bdld::Datum::createError(-1, error.str(), d_allocator_p);
}
}
#undef TYPE_PAIR
}
};
} // namespace
#define DISPATCH(FUNCTION) \
switch (bdld::Datum::DataType type = \
normalizeTypes(*args.argsAndOutput, args.allocator)) { \
case bdld::Datum::e_INTEGER: \
return FUNCTION<int>(*args.argsAndOutput, args.allocator); \
case bdld::Datum::e_INTEGER64: \
return FUNCTION<bsls::Types::Int64>(*args.argsAndOutput, \
args.allocator); \
case bdld::Datum::e_DOUBLE: \
return FUNCTION<double>(*args.argsAndOutput, args.allocator); \
default: \
(void)type; \
BSLS_ASSERT(type == bdld::Datum::e_DECIMAL64); \
return FUNCTION<bdldfp::Decimal64>(*args.argsAndOutput, \
args.allocator); \
}
void ArithmeticUtil::add(const NativeProcedureUtil::Arguments& args) {
DISPATCH(homogeneousAdd)
}
void ArithmeticUtil::subtract(const NativeProcedureUtil::Arguments& args) {
if (args.argsAndOutput->empty()) {
throw bdld::Datum::createError(
-1, "substraction requires at least one operand", args.allocator);
}
DISPATCH(homogeneousSubtract)
}
void ArithmeticUtil::multiply(const NativeProcedureUtil::Arguments& args) {
DISPATCH(homogeneousMultiply)
}
void ArithmeticUtil::divide(const NativeProcedureUtil::Arguments& args) {
if (args.argsAndOutput->empty()) {
throw bdld::Datum::createError(
-1, "division requires at least one operand", args.allocator);
}
DISPATCH(homogeneousDivide)
}
#undef DISPATCH
void ArithmeticUtil::equal(const NativeProcedureUtil::Arguments& args) {
if (args.argsAndOutput->empty()) {
throw bdld::Datum::createError(
-1,
"equality comparison requires at least one operand",
args.allocator);
}
if (classify(*args.argsAndOutput).kind ==
Classification::e_ERROR_NON_NUMERIC_TYPE) {
throw bdld::Datum::createError(
-1,
"equality comparison requires all numeric operands",
args.allocator);
}
bool result;
if (args.argsAndOutput->size() == 1) {
result = true;
}
else {
result = std::adjacent_find(args.argsAndOutput->begin(),
args.argsAndOutput->end(),
NotEqual(args.allocator)) ==
args.argsAndOutput->end();
}
args.argsAndOutput->resize(1);
args.argsAndOutput->front() = bdld::Datum::createBoolean(result);
}
} // namespace lspcore
| 34.88588 | 79 | 0.575904 | dgoffredo |
9cd59c8ea20b2758e329764ff335fff9e25608ed | 658 | cc | C++ | test/sync_call.cc | shayanalia/msgpack-rpc-cpp | 3fd73f9a58b899774dca13a1c478fad7924dd8fd | [
"Apache-2.0"
] | 28 | 2015-01-15T13:50:05.000Z | 2022-03-01T13:41:33.000Z | test/sync_call.cc | shayanalia/msgpack-rpc-cpp | 3fd73f9a58b899774dca13a1c478fad7924dd8fd | [
"Apache-2.0"
] | 1 | 2016-10-03T22:45:49.000Z | 2016-10-04T01:11:57.000Z | test/sync_call.cc | shayanalia/msgpack-rpc-cpp | 3fd73f9a58b899774dca13a1c478fad7924dd8fd | [
"Apache-2.0"
] | 13 | 2015-11-27T15:30:59.000Z | 2020-09-30T20:43:00.000Z | #include "echo_server.h"
#include <msgpack/rpc/server.h>
#include <msgpack/rpc/client.h>
#include <cclog/cclog.h>
#include <cclog/cclog_tty.h>
int main(void)
{
cclog::reset(new cclog_tty(cclog::TRACE, std::cout));
signal(SIGPIPE, SIG_IGN);
// run server {
rpc::server svr;
std::auto_ptr<rpc::dispatcher> dp(new myecho);
svr.serve(dp.get());
svr.listen("0.0.0.0", 18811);
svr.start(4);
// }
// create client
rpc::client cli("127.0.0.1", 18811);
// call
std::string msg("MessagePack-RPC");
std::string ret = cli.call("echo", msg).get<std::string>();
std::cout << "call: echo(\"MessagePack-RPC\") = " << ret << std::endl;
return 0;
}
| 18.277778 | 71 | 0.641337 | shayanalia |
9cd621b858b8e9299e55bfcbc0b206454cdf4b22 | 15,046 | cc | C++ | src/devices/power/drivers/aml-meson-power/aml-power.cc | dahlia-os/fuchsia-pine64-pinephone | 57aace6f0b0bd75306426c98ab9eb3ff4524a61d | [
"BSD-3-Clause"
] | 10 | 2020-12-28T17:04:44.000Z | 2022-03-12T03:20:43.000Z | src/devices/power/drivers/aml-meson-power/aml-power.cc | oshunter/fuchsia | 2196fc8c176d01969466b97bba3f31ec55f7767b | [
"BSD-3-Clause"
] | 1 | 2022-01-14T23:38:40.000Z | 2022-01-14T23:38:40.000Z | src/devices/power/drivers/aml-meson-power/aml-power.cc | oshunter/fuchsia | 2196fc8c176d01969466b97bba3f31ec55f7767b | [
"BSD-3-Clause"
] | 4 | 2020-12-28T17:04:45.000Z | 2022-03-12T03:20:44.000Z | // Copyright 2020 The Fuchsia 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 "aml-power.h"
#include <lib/device-protocol/pdev.h>
#include <algorithm>
#include <ddk/binding.h>
#include <ddk/debug.h>
#include <ddk/platform-defs.h>
#include <ddk/protocol/platform/device.h>
#include <ddktl/protocol/composite.h>
#include <ddktl/protocol/pwm.h>
#include <fbl/alloc_checker.h>
#include <soc/aml-common/aml-pwm-regs.h>
namespace power {
namespace {
constexpr size_t kFragmentPdev = 0;
constexpr size_t kFragmentPwmBigCluster = 1;
constexpr size_t kFragmentPwmLittleCluster = 2;
constexpr size_t kFragmentCount = 3;
// Sleep for 200 microseconds inorder to let the voltage change
// take effect. Source: Amlogic SDK.
constexpr uint32_t kVoltageSettleTimeUs = 200;
// Step up or down 3 steps in the voltage table while changing
// voltage and not directly. Source: Amlogic SDK
constexpr int kMaxVoltageChangeSteps = 3;
zx_status_t InitPwmProtocolClient(zx_device_t* dev, ddk::PwmProtocolClient* client) {
if (dev == nullptr || client == nullptr) {
zxlogf(ERROR, "%s: neither dev nor client can be null\n", __func__);
return ZX_ERR_INVALID_ARGS;
}
*client = ddk::PwmProtocolClient(dev);
if (client->is_valid() == false) {
zxlogf(ERROR, "%s: failed to get PWM fragment\n", __func__);
return ZX_ERR_INTERNAL;
}
zx_status_t result;
if ((result = client->Enable()) != ZX_OK) {
zxlogf(ERROR, "%s: Could not enable PWM", __func__);
}
return result;
}
bool IsSortedDescending(const std::vector<aml_voltage_table_t>& vt) {
for (size_t i = 0; i < vt.size() - 1; i++) {
if (vt[i].microvolt < vt[i + 1].microvolt)
// Bail early if we find a voltage that isn't strictly descending.
return false;
}
return true;
}
zx_status_t GetAmlVoltageTable(zx_device_t* parent,
std::vector<aml_voltage_table_t>* voltage_table) {
size_t metadata_size;
zx_status_t st =
device_get_metadata_size(parent, DEVICE_METADATA_AML_VOLTAGE_TABLE, &metadata_size);
if (st != ZX_OK) {
zxlogf(ERROR, "%s: Failed to get Voltage Table size, st = %d", __func__, st);
return st;
}
// The metadata is an array of aml_voltage_table_t so the metadata size must be an
// integer multiple of sizeof(aml_voltage_table_t).
if (metadata_size % (sizeof(aml_voltage_table_t)) != 0) {
zxlogf(
ERROR,
"%s: Metadata size [%lu] was not an integer multiple of sizeof(aml_voltage_table_t) [%lu]",
__func__, metadata_size, sizeof(aml_voltage_table_t));
return ZX_ERR_INTERNAL;
}
const size_t voltage_table_count = metadata_size / sizeof(aml_voltage_table_t);
auto voltage_table_metadata = std::make_unique<aml_voltage_table_t[]>(voltage_table_count);
size_t actual;
st = device_get_metadata(parent, DEVICE_METADATA_AML_VOLTAGE_TABLE, voltage_table_metadata.get(),
metadata_size, &actual);
if (st != ZX_OK) {
zxlogf(ERROR, "%s: Failed to get Voltage Table, st = %d", __func__, st);
return st;
}
if (actual != metadata_size) {
zxlogf(ERROR, "%s: device_get_metadata expected to read %lu bytes, actual read %lu", __func__,
metadata_size, actual);
return ZX_ERR_INTERNAL;
}
voltage_table->reserve(voltage_table_count);
std::copy(&voltage_table_metadata[0], &voltage_table_metadata[0] + voltage_table_count,
std::back_inserter(*voltage_table));
if (!IsSortedDescending(*voltage_table)) {
zxlogf(ERROR, "%s: Voltage table was not sorted in strictly descending order", __func__);
return ZX_ERR_INTERNAL;
}
return ZX_OK;
}
zx_status_t GetAmlPwmPeriod(zx_device_t* parent, voltage_pwm_period_ns_t* result) {
size_t metadata_size;
zx_status_t st =
device_get_metadata_size(parent, DEVICE_METADATA_AML_PWM_PERIOD_NS, &metadata_size);
if (st != ZX_OK) {
zxlogf(ERROR, "%s: Failed to get PWM Period Metadata, st = %d", __func__, st);
return st;
}
if (metadata_size != sizeof(*result)) {
zxlogf(ERROR, "%s: Expected PWM Period metadata to be %lu bytes, got %lu", __func__,
sizeof(*result), metadata_size);
return ZX_ERR_INTERNAL;
}
size_t actual;
st = device_get_metadata(parent, DEVICE_METADATA_AML_PWM_PERIOD_NS, result, sizeof(*result),
&actual);
if (actual != sizeof(*result)) {
zxlogf(ERROR, "%s: Expected PWM metadata size = %lu, got %lu", __func__, sizeof(*result),
actual);
}
return st;
}
} // namespace
zx_status_t AmlPower::PowerImplWritePmicCtrlReg(uint32_t index, uint32_t addr, uint32_t value) {
return ZX_ERR_NOT_SUPPORTED;
}
zx_status_t AmlPower::PowerImplReadPmicCtrlReg(uint32_t index, uint32_t addr, uint32_t* value) {
return ZX_ERR_NOT_SUPPORTED;
}
zx_status_t AmlPower::PowerImplDisablePowerDomain(uint32_t index) {
if (index >= num_domains_) {
zxlogf(ERROR, "%s: Requested Disable for a domain that doesn't exist, idx = %u", __func__,
index);
return ZX_ERR_OUT_OF_RANGE;
}
return ZX_OK;
}
zx_status_t AmlPower::PowerImplEnablePowerDomain(uint32_t index) {
if (index >= num_domains_) {
zxlogf(ERROR, "%s: Requested Enable for a domain that doesn't exist, idx = %u", __func__,
index);
return ZX_ERR_OUT_OF_RANGE;
}
return ZX_OK;
}
zx_status_t AmlPower::PowerImplGetPowerDomainStatus(uint32_t index,
power_domain_status_t* out_status) {
if (index >= num_domains_) {
zxlogf(ERROR,
"%s: Requested PowerImplGetPowerDomainStatus for a domain that doesn't exist, idx = %u",
__func__, index);
return ZX_ERR_OUT_OF_RANGE;
}
if (out_status == nullptr) {
zxlogf(ERROR, "%s: out_status must not be null", __func__);
return ZX_ERR_INVALID_ARGS;
}
// All domains are always enabled.
*out_status = POWER_DOMAIN_STATUS_ENABLED;
return ZX_OK;
}
zx_status_t AmlPower::PowerImplGetSupportedVoltageRange(uint32_t index, uint32_t* min_voltage,
uint32_t* max_voltage) {
if (index >= num_domains_) {
zxlogf(ERROR,
"%s: Requested GetSupportedVoltageRange for a domain that doesn't exist, idx = %u",
__func__, index);
return ZX_ERR_OUT_OF_RANGE;
}
// Voltage table is sorted in descending order so the minimum voltage is the last element and the
// maximum voltage is the first element.
*min_voltage = voltage_table_.back().microvolt;
*max_voltage = voltage_table_.front().microvolt;
return ZX_OK;
}
zx_status_t AmlPower::RequestVoltage(const ddk::PwmProtocolClient& pwm, uint32_t u_volts,
int* current_voltage_index) {
// Find the largest voltage that does not exceed u_volts.
const aml_voltage_table_t target_voltage = {.microvolt = u_volts, .duty_cycle = 0};
const auto& target =
std::lower_bound(voltage_table_.begin(), voltage_table_.end(), target_voltage,
[](const aml_voltage_table_t& l, const aml_voltage_table_t& r) {
return l.microvolt > r.microvolt;
});
if (target == voltage_table_.end()) {
zxlogf(ERROR, "%s: Could not find a voltage less than or equal to %u\n", __func__, u_volts);
return ZX_ERR_NOT_SUPPORTED;
}
size_t target_idx = target - voltage_table_.begin();
if (target_idx >= INT_MAX || target_idx >= voltage_table_.size()) {
zxlogf(ERROR, "%s: voltage target index out of bounds", __func__);
return ZX_ERR_OUT_OF_RANGE;
}
int target_index = static_cast<int>(target_idx);
zx_status_t status = ZX_OK;
// If this is the first time we are setting up the voltage
// we directly set it.
if (*current_voltage_index == kInvalidIndex) {
// Update new duty cycle.
aml_pwm::mode_config on = {aml_pwm::ON, {}};
pwm_config_t cfg = {false, pwm_period_, static_cast<float>(target->duty_cycle), &on,
sizeof(on)};
if ((status = pwm.SetConfig(&cfg)) != ZX_OK) {
zxlogf(ERROR, "%s: Could not initialize PWM", __func__);
return status;
}
usleep(kVoltageSettleTimeUs);
*current_voltage_index = target_index;
return ZX_OK;
}
// Otherwise we adjust to the target voltage step by step.
while (*current_voltage_index != target_index) {
if (*current_voltage_index < target_index) {
if (*current_voltage_index < target_index - kMaxVoltageChangeSteps) {
// Step up by 3 in the voltage table.
*current_voltage_index += kMaxVoltageChangeSteps;
} else {
*current_voltage_index = target_index;
}
} else {
if (*current_voltage_index > target_index + kMaxVoltageChangeSteps) {
// Step down by 3 in the voltage table.
*current_voltage_index -= kMaxVoltageChangeSteps;
} else {
*current_voltage_index = target_index;
}
}
// Update new duty cycle.
aml_pwm::mode_config on = {aml_pwm::ON, {}};
pwm_config_t cfg = {false, pwm_period_,
static_cast<float>(voltage_table_[*current_voltage_index].duty_cycle), &on,
sizeof(on)};
if ((status = pwm.SetConfig(&cfg)) != ZX_OK) {
zxlogf(ERROR, "%s: Could not initialize PWM", __func__);
return status;
}
usleep(kVoltageSettleTimeUs);
}
return ZX_OK;
}
zx_status_t AmlPower::PowerImplRequestVoltage(uint32_t index, uint32_t voltage,
uint32_t* actual_voltage) {
if (index >= num_domains_) {
zxlogf(ERROR, "%s: Requested voltage for a range that doesn't exist, idx = %u", __func__,
index);
return ZX_ERR_OUT_OF_RANGE;
}
zx_status_t st = ZX_ERR_OUT_OF_RANGE;
if (index == kBigClusterDomain) {
st = RequestVoltage(big_cluster_pwm_.value(), voltage, ¤t_big_cluster_voltage_index_);
if (st == ZX_OK) {
*actual_voltage = voltage_table_[current_big_cluster_voltage_index_].microvolt;
}
} else if (index == kLittleClusterDomain) {
st = RequestVoltage(little_cluster_pwm_.value(), voltage,
¤t_little_cluster_voltage_index_);
if (st == ZX_OK) {
*actual_voltage = voltage_table_[current_little_cluster_voltage_index_].microvolt;
}
}
return st;
}
zx_status_t AmlPower::PowerImplGetCurrentVoltage(uint32_t index, uint32_t* current_voltage) {
if (index >= num_domains_) {
zxlogf(ERROR, "%s: Requested voltage for a range that doesn't exist, idx = %u", __func__,
index);
return ZX_ERR_OUT_OF_RANGE;
}
switch (index) {
case kBigClusterDomain:
if (current_big_cluster_voltage_index_ == kInvalidIndex)
return ZX_ERR_BAD_STATE;
*current_voltage = voltage_table_[current_big_cluster_voltage_index_].microvolt;
break;
case kLittleClusterDomain:
if (current_little_cluster_voltage_index_ == kInvalidIndex)
return ZX_ERR_BAD_STATE;
*current_voltage = voltage_table_[current_little_cluster_voltage_index_].microvolt;
break;
default:
return ZX_ERR_OUT_OF_RANGE;
}
return ZX_OK;
}
void AmlPower::DdkRelease() { delete this; }
void AmlPower::DdkUnbindNew(ddk::UnbindTxn txn) { txn.Reply(); }
zx_status_t AmlPower::Create(void* ctx, zx_device_t* parent) {
zx_status_t st;
ddk::CompositeProtocolClient composite(parent);
if (!composite.is_valid()) {
zxlogf(ERROR, "%s: failed to get composite protocol\n", __func__);
return ZX_ERR_INTERNAL;
}
// We may get 2 or 3 fragments depending upon the number of power domains that this
// core supports.
size_t actual;
zx_device_t* fragments[kFragmentCount];
composite.GetFragments(fragments, kFragmentCount, &actual);
if (actual < 1) {
zxlogf(ERROR, "%s: failed to get pdev fragment", __func__);
return ZX_ERR_INTERNAL;
}
ddk::PDev pdev(fragments[kFragmentPdev]);
if (!pdev.is_valid()) {
zxlogf(ERROR, "%s: failed to get pdev protocol", __func__);
return ZX_ERR_INTERNAL;
}
pdev_device_info_t device_info;
st = pdev.GetDeviceInfo(&device_info);
if (st != ZX_OK) {
zxlogf(ERROR, "%s: failed to get DeviceInfo, st = %d", __func__, st);
return st;
}
std::vector<aml_voltage_table_t> voltage_table;
st = GetAmlVoltageTable(parent, &voltage_table);
if (st != ZX_OK) {
zxlogf(ERROR, "%s: Failed to get aml voltage table, st = %d", __func__, st);
return st;
}
voltage_pwm_period_ns_t pwm_period;
st = GetAmlPwmPeriod(parent, &pwm_period);
if (st != ZX_OK) {
zxlogf(ERROR, "%s: Failed to get aml pwm period table, st = %d", __func__, st);
return st;
}
std::optional<ddk::PwmProtocolClient> big_cluster_pwm;
if (actual > kFragmentPwmBigCluster) {
ddk::PwmProtocolClient client;
st = InitPwmProtocolClient(fragments[kFragmentPwmBigCluster], &client);
if (st != ZX_OK) {
zxlogf(ERROR, "%s: Failed to initialize Big Cluster PWM Client, st = %d", __func__, st);
return st;
}
big_cluster_pwm = client;
} else {
zxlogf(ERROR, "%s: Failed to get big cluster pwm", __func__);
return ZX_ERR_INTERNAL;
}
std::optional<ddk::PwmProtocolClient> little_cluster_pwm;
if (actual > kFragmentPwmLittleCluster) {
ddk::PwmProtocolClient client;
st = InitPwmProtocolClient(fragments[kFragmentPwmLittleCluster], &client);
if (st != ZX_OK) {
zxlogf(ERROR, "%s: Failed to initialize Little Cluster PWM Client, st = %d", __func__, st);
return st;
}
little_cluster_pwm = client;
}
auto power_impl_device =
std::make_unique<AmlPower>(parent, std::move(big_cluster_pwm), std::move(little_cluster_pwm),
std::move(voltage_table), pwm_period);
st = power_impl_device->DdkAdd("power-impl", DEVICE_ADD_ALLOW_MULTI_COMPOSITE);
if (st != ZX_OK) {
zxlogf(ERROR, "%s: DdkAdd failed, st = %d", __func__, st);
}
// Let device runner take ownership of this object.
__UNUSED auto* dummy = power_impl_device.release();
return st;
}
static constexpr zx_driver_ops_t aml_power_driver_ops = []() {
zx_driver_ops_t driver_ops = {};
driver_ops.version = DRIVER_OPS_VERSION;
driver_ops.bind = AmlPower::Create;
// driver_ops.run_unit_tests = run_test; # TODO(gkalsi).
return driver_ops;
}();
} // namespace power
// clang-format off
ZIRCON_DRIVER_BEGIN(aml_power, power::aml_power_driver_ops, "zircon", "0.1", 4)
BI_ABORT_IF(NE, BIND_PROTOCOL, ZX_PROTOCOL_COMPOSITE),
BI_ABORT_IF(NE, BIND_PLATFORM_DEV_VID, PDEV_VID_AMLOGIC),
BI_ABORT_IF(NE, BIND_PLATFORM_DEV_DID, PDEV_DID_AMLOGIC_POWER),
// The following are supported SoCs
BI_MATCH_IF(EQ, BIND_PLATFORM_DEV_PID, PDEV_PID_AMLOGIC_S905D2),
// TODO(gkalsi): Support the following two AMLogic SoCs
// BI_MATCH_IF(EQ, BIND_PLATFORM_DEV_PID, PDEV_PID_AMLOGIC_T931),
// BI_MATCH_IF(EQ, BIND_PLATFORM_DEV_PID, PDEV_PID_AMLOGIC_S905D3),
ZIRCON_DRIVER_END(aml_power)
//clang-format on
| 34.040724 | 99 | 0.684966 | dahlia-os |
9cd6a3619b467bb50fc0754649f1e75ffaf60f6c | 7,084 | hpp | C++ | openstudiocore/src/project/AnalysisRecord.hpp | jasondegraw/OpenStudio | 2ab13f6e5e48940929041444e40ad9d36f80f552 | [
"blessing"
] | 1 | 2016-12-29T08:45:03.000Z | 2016-12-29T08:45:03.000Z | openstudiocore/src/project/AnalysisRecord.hpp | jasondegraw/OpenStudio | 2ab13f6e5e48940929041444e40ad9d36f80f552 | [
"blessing"
] | null | null | null | openstudiocore/src/project/AnalysisRecord.hpp | jasondegraw/OpenStudio | 2ab13f6e5e48940929041444e40ad9d36f80f552 | [
"blessing"
] | null | null | null | /**********************************************************************
* Copyright (c) 2008-2016, Alliance for Sustainable Energy.
* All rights reserved.
*
* This library is free software; you can redistribute it and/or
* modify it under the terms of the GNU Lesser General Public
* License as published by the Free Software Foundation; either
* version 2.1 of the License, or (at your option) any later version.
*
* This library is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
* Lesser General Public License for more details.
*
* You should have received a copy of the GNU Lesser General Public
* License along with this library; if not, write to the Free Software
* Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA
**********************************************************************/
#ifndef PROJECT_ANALYSISRECORD_HPP
#define PROJECT_ANALYSISRECORD_HPP
#include "ProjectAPI.hpp"
#include "ObjectRecord.hpp"
namespace openstudio {
namespace analysis {
class Analysis;
} // analysis
namespace project {
class ProblemRecord;
class AlgorithmRecord;
class FileReferenceRecord;
class DataPointRecord;
namespace detail {
class AnalysisRecord_Impl;
} // detail
/** \class AnalysisRecordColumns
* \brief Column definitions for the AnalysisRecords table.
* \details See the OPENSTUDIO_ENUM documentation in utilities/core/Enum.hpp. The actual
* macro call is:
* \code
OPENSTUDIO_ENUM( AnalysisRecordColumns,
((id)(INTEGER PRIMARY KEY)(0))
((handle)(TEXT)(1))
((name)(TEXT)(2))
((displayName)(TEXT)(3))
((description)(TEXT)(4))
((timestampCreate)(TEXT)(5))
((timestampLast)(TEXT)(6))
((uuidLast)(TEXT)(7))
((problemRecordId)(INTEGER)(8))
((algorithmRecordId)(INTEGER)(9))
((seedFileReferenceRecordId)(INTEGER)(10))
((weatherFileReferenceRecordId)(INTEGER)(11))
((resultsAreInvalid)(BOOLEAN)(12))
((dataPointsAreInvalid)(BOOLEAN)(13))
);
* \endcode */
OPENSTUDIO_ENUM( AnalysisRecordColumns,
((id)(INTEGER PRIMARY KEY)(0))
((handle)(TEXT)(1))
((name)(TEXT)(2))
((displayName)(TEXT)(3))
((description)(TEXT)(4))
((timestampCreate)(TEXT)(5))
((timestampLast)(TEXT)(6))
((uuidLast)(TEXT)(7))
((problemRecordId)(INTEGER)(8))
((algorithmRecordId)(INTEGER)(9))
((seedFileReferenceRecordId)(INTEGER)(10))
((weatherFileReferenceRecordId)(INTEGER)(11))
((resultsAreInvalid)(BOOLEAN)(12))
((dataPointsAreInvalid)(BOOLEAN)(13))
);
/** AnalysisRecord is a ObjectRecord*/
class PROJECT_API AnalysisRecord : public ObjectRecord {
public:
typedef detail::AnalysisRecord_Impl ImplType;
typedef AnalysisRecordColumns ColumnsType;
typedef AnalysisRecord ObjectRecordType;
/** @name Constructors and Destructors */
//@{
AnalysisRecord(const analysis::Analysis& analysis, ProjectDatabase& database);
AnalysisRecord(const QSqlQuery& query, ProjectDatabase& database);
virtual ~AnalysisRecord() {}
//@}
static std::string databaseTableName();
static UpdateByIdQueryData updateByIdQueryData();
static void updatePathData(ProjectDatabase database,
const openstudio::path& originalBase,
const openstudio::path& newBase);
static boost::optional<AnalysisRecord> factoryFromQuery(const QSqlQuery& query,
ProjectDatabase& database);
static std::vector<AnalysisRecord> getAnalysisRecords(ProjectDatabase& database);
static boost::optional<AnalysisRecord> getAnalysisRecord(int id, ProjectDatabase& database);
/** @name Getters */
//@{
/** Returns the ProblemRecord (required resource) associated with this AnalysisRecord. */
ProblemRecord problemRecord() const;
/** Returns the AlgorithmRecord (optional resource) associated with this AnalysisRecord. */
boost::optional<AlgorithmRecord> algorithmRecord() const;
/** Returns the seed FileReferenceRecord (required child) of this AnalysisRecord. */
FileReferenceRecord seedFileReferenceRecord() const;
/** Returns the weather FileReferenceRecord (optional child) of this AnalysisRecord. */
boost::optional<FileReferenceRecord> weatherFileReferenceRecord() const;
/** Returns the \link DataPointRecord DataPointRecords \endlink (children) of this
* AnalysisRecord. */
std::vector<DataPointRecord> dataPointRecords() const;
/** Returns the DataPointRecords with complete == false. */
std::vector<DataPointRecord> incompleteDataPointRecords() const;
/** Returns the DataPointRecords with complete == true. */
std::vector<DataPointRecord> completeDataPointRecords() const;
/** Returns the completeDataPointRecords with failed == false. */
std::vector<DataPointRecord> successfulDataPointRecords() const;
/** Returns the completeDataPointRecords with failed == true. */
std::vector<DataPointRecord> failedDataPointRecords() const;
std::vector<DataPointRecord> getDataPointRecords(
const std::vector<QVariant>& variableValues) const;
std::vector<DataPointRecord> getDataPointRecords(
const std::vector<int>& discretePerturbationRecordIds) const;
std::vector<DataPointRecord> getDataPointRecords(const std::string& tag) const;
/** Returns true if this AnalysisRecord holds DataPointRecords with invalid results still
* attached. */
bool resultsAreInvalid() const;
/** Returns true if this AnalysisRecord holds DataPointRecords that are invalid in light of
* changes to the problem formulation. */
bool dataPointsAreInvalid() const;
/** Deserializes this record and all its children and resources to analysis::Analysis. */
analysis::Analysis analysis() const;
//@}
/** @name Setters */
//@{
/** Provided for callers operating directly on the database, not holding a copy of this
* analysis in memory. Use with caution. */
void setResultsAreInvalid(bool value);
/** Provided for callers operating directly on the database, not holding a copy of this
* analysis in memory. Use with caution. */
void setDataPointsAreInvalid(bool value);
//@}
protected:
/// @cond
friend class Record;
friend class ProjectDatabase;
friend class detail::AnalysisRecord_Impl;
/** Construct from impl. */
AnalysisRecord(std::shared_ptr<detail::AnalysisRecord_Impl> impl,
ProjectDatabase database);
/// Construct from impl. Does not register in the database, so use with caution.
explicit AnalysisRecord(std::shared_ptr<detail::AnalysisRecord_Impl> impl);
/// @endcond
private:
REGISTER_LOGGER("openstudio.project.AnalysisRecord");
void removeDataPointRecords(const std::vector<UUID>& uuidsToKeep,
ProjectDatabase& database);
};
/** \relates AnalysisRecord*/
typedef boost::optional<AnalysisRecord> OptionalAnalysisRecord;
/** \relates AnalysisRecord*/
typedef std::vector<AnalysisRecord> AnalysisRecordVector;
} // project
} // openstudio
#endif // PROJECT_ANALYSISRECORD_HPP
| 33.733333 | 94 | 0.714992 | jasondegraw |
9cd6c31f764122214136fff6589293c7a8c871b9 | 3,148 | cpp | C++ | src/Shader.cpp | the13fools/fieldgen | 6b1757e1a75cd65b73526aa9c200303fbee4d669 | [
"Unlicense",
"MIT"
] | 93 | 2019-06-04T06:56:49.000Z | 2022-03-30T08:44:58.000Z | src/Shader.cpp | the13fools/fieldgen | 6b1757e1a75cd65b73526aa9c200303fbee4d669 | [
"Unlicense",
"MIT"
] | 1 | 2020-02-06T14:56:41.000Z | 2020-07-15T17:31:29.000Z | src/Shader.cpp | the13fools/fieldgen | 6b1757e1a75cd65b73526aa9c200303fbee4d669 | [
"Unlicense",
"MIT"
] | 11 | 2019-06-06T21:11:29.000Z | 2021-08-14T05:06:16.000Z | #include "Shader.h"
#include <fstream>
#include <iostream>
using namespace std;
namespace DDG
{
Shader::Shader( void )
// constructor -- shader is initially invalid
: vertexShader( 0 ),
fragmentShader( 0 ),
geometryShader( 0 ),
program( 0 ),
linked( false )
{}
Shader::~Shader( void )
{
if( program ) glDeleteProgram( program );
if( vertexShader ) glDeleteShader( vertexShader );
if( fragmentShader ) glDeleteShader( fragmentShader );
if( geometryShader ) glDeleteShader( geometryShader );
}
void Shader::loadVertex( const char* filename )
{
load( GL_VERTEX_SHADER, filename, vertexShader );
}
void Shader::loadFragment( const char* filename )
{
load( GL_FRAGMENT_SHADER, filename, fragmentShader );
}
void Shader::loadGeometry( const char* filename )
{
#ifdef GL_GEOMETRY_SHADER_EXT
load( GL_GEOMETRY_SHADER_EXT, filename, geometryShader );
#else
cerr << "Error: geometry shaders not supported!" << endl;
#endif
}
void Shader::enable( void )
{
if( !linked )
{
glLinkProgram( program );
linked = true;
}
glUseProgram( program );
}
void Shader::disable( void ) const
{
glUseProgram( 0 );
}
Shader::operator GLuint( void ) const
{
return program;
}
void Shader::load( GLenum shaderType, const char* filename, GLuint& shader )
// read vertex shader from GLSL source file, compile, and attach to program
{
string source;
if( !readSource( filename, source ))
{
return;
}
if( program == 0 )
{
program = glCreateProgram();
}
if( shader != 0 )
{
glDetachShader( program, shader );
}
shader = glCreateShader( shaderType );
const char* source_c_str = source.c_str();
glShaderSource( shader, 1, &(source_c_str), NULL );
glCompileShader( shader );
GLint compileStatus;
glGetShaderiv( shader, GL_COMPILE_STATUS, &compileStatus );
if( compileStatus == GL_TRUE )
{
glAttachShader( program, shader );
linked = false;
}
else
{
GLsizei maxLength = 0;
glGetShaderiv( shader, GL_INFO_LOG_LENGTH, &maxLength );
if( maxLength > 0 )
{
GLchar* infoLog = new char[ maxLength ];
GLsizei length;
glGetShaderInfoLog( shader, maxLength, &length, infoLog );
cerr << "GLSL Error: " << infoLog << endl;
delete[] infoLog;
}
}
}
bool Shader::readSource( const char* filename, std::string& source )
// reads GLSL source file into a string
{
source = "";
ifstream in( filename );
if( !in.is_open() )
{
cerr << "Error: could not open shader file ";
cerr << filename;
cerr << " for input!" << endl;
return false;
}
string line;
while( getline( in, line ))
{
source += line;
}
return true;
}
}
| 22.013986 | 79 | 0.558132 | the13fools |
9cd9ec1315f44ba17406216a8e849bbde7e6f376 | 1,263 | cpp | C++ | Stack/Check for redundent braces.cpp | Dharaneeshwar/DataStructures | 9fab95b8d58c39cb3bb9cd6d635f2f5d4fdec9df | [
"MIT"
] | 11 | 2020-09-12T03:05:30.000Z | 2020-11-12T00:18:08.000Z | Stack/Check for redundent braces.cpp | g-o-l-d-y/DataStructures | 7049c6d0e7e3d54bad3b380d8048c5215698c78e | [
"MIT"
] | 1 | 2020-10-19T10:10:08.000Z | 2020-10-19T10:10:08.000Z | Stack/Check for redundent braces.cpp | g-o-l-d-y/DataStructures | 7049c6d0e7e3d54bad3b380d8048c5215698c78e | [
"MIT"
] | 1 | 2020-10-19T06:48:16.000Z | 2020-10-19T06:48:16.000Z | #include <iostream>
#include <cstring>
using namespace std;
// class declaration
class Node
{
public:
char data;
Node *next;
} *head = NULL;
void append(char data)
{
// adds the element to the top of Stack
Node *newnode = new Node();
newnode->data = data;
newnode->next = NULL;
if (head == NULL)
{
head = newnode;
}
else
{
newnode->next = head;
head = newnode;
}
}
char poptop()
{
// removes and returns the top of stack
char val = head->data;
Node *temp = head;
head = head->next;
temp->next = NULL;
free(temp);
return val;
}
int main()
{
string s;
cin >> s;
for (char a : s)
{
if (a == ')')
{
int flag = 0;
char t = poptop();
while (t != '(')
{
// removes all character till opening paranthesis
if (strchr("+-*/", t))
{
flag = 1;
}
t = poptop();
}
if (flag == 0)
{
cout << "Yes";
return 0;
}
}
else
{
append(a);
}
}
cout << "No";
return 0;
} | 17.30137 | 65 | 0.409343 | Dharaneeshwar |
9cda1c4fa4683eda4b13d22725cb0328104f8dde | 13,167 | cpp | C++ | third_party/CppAD/cppad_lib/json_parser.cpp | eric-heiden/tds-merge | 1e18447b0096efbb6df5d9ad7d69c8b0cc282747 | [
"Apache-2.0"
] | null | null | null | third_party/CppAD/cppad_lib/json_parser.cpp | eric-heiden/tds-merge | 1e18447b0096efbb6df5d9ad7d69c8b0cc282747 | [
"Apache-2.0"
] | null | null | null | third_party/CppAD/cppad_lib/json_parser.cpp | eric-heiden/tds-merge | 1e18447b0096efbb6df5d9ad7d69c8b0cc282747 | [
"Apache-2.0"
] | null | null | null | /* --------------------------------------------------------------------------
CppAD: C++ Algorithmic Differentiation: Copyright (C) 2003-20 Bradley M. Bell
CppAD is distributed under the terms of the
Eclipse Public License Version 2.0.
This Source Code may also be made available under the following
Secondary License when the conditions for such availability set forth
in the Eclipse Public License, Version 2.0 are satisfied:
GNU General Public License, Version 2.0 or later.
---------------------------------------------------------------------------- */
# include <cppad/core/graph/cpp_graph.hpp>
# include <cppad/local/graph/json_lexer.hpp>
# include <cppad/local/define.hpp>
# include <cppad/local/atomic_index.hpp>
# include <cppad/utility/to_string.hpp>
// documentation for this routine is in the file below
# include <cppad/local/graph/json_parser.hpp>
void CppAD::local::graph::json_parser(
const std::string& json ,
cpp_graph& graph_obj )
{ using std::string;
//
//
// match_any_string
const string match_any_string = "";
//
// initilize atomic_name_vec
graph_obj.initialize();
//
// The values in this vector will be set while parsing op_define_vec.
// Note that the values in op_code2enum[0] are not used.
CppAD::vector<graph_op_enum> op_code2enum(1);
//
// -----------------------------------------------------------------------
// json_lexer constructor checks for { at beginning
CppAD::local::graph::json_lexer json_lexer(json);
//
// "function_name" : function_name
json_lexer.check_next_string("function_name");
json_lexer.check_next_char(':');
json_lexer.check_next_string(match_any_string);
std::string function_name = json_lexer.token();
graph_obj.function_name_set(function_name);
json_lexer.set_function_name(function_name);
json_lexer.check_next_char(',');
//
// -----------------------------------------------------------------------
// "op_define_vec" : [ n_define, [
json_lexer.check_next_string("op_define_vec");
json_lexer.check_next_char(':');
json_lexer.check_next_char('[');
//
json_lexer.next_non_neg_int();
size_t n_define = json_lexer.token2size_t();
json_lexer.check_next_char(',');
//
json_lexer.check_next_char('[');
for(size_t i = 0; i < n_define; ++i)
{ // {
json_lexer.check_next_char('{');
//
// "op_code" : op_code,
json_lexer.check_next_string("op_code");
json_lexer.check_next_char(':');
json_lexer.next_non_neg_int();
# ifndef NDEBUG
size_t op_code = json_lexer.token2size_t();
CPPAD_ASSERT_UNKNOWN( op_code == op_code2enum.size() );
# endif
json_lexer.check_next_char(',');
//
// "name" : name
json_lexer.check_next_string("name");
json_lexer.check_next_char(':');
json_lexer.check_next_string(match_any_string);
string name = json_lexer.token();
graph_op_enum op_enum = op_name2enum[name];
# if ! CPPAD_USE_CPLUSPLUS_2011
switch( op_enum )
{
case acosh_graph_op:
case asinh_graph_op:
case atanh_graph_op:
case erf_graph_op:
case erfc_graph_op:
case expm1_graph_op:
case log1p_graph_op:
{ string expected = "a C++98 function";
string found = name + " which is a C++11 function.";
json_lexer.report_error(expected, found);
}
break;
default:
break;
}
# endif
//
// op_code2enum for this op_code
op_code2enum.push_back(op_enum);
//
size_t n_arg = op_enum2fixed_n_arg[op_enum];
if( n_arg > 0 )
{ // , "narg" : n_arg
json_lexer.check_next_char(',');
json_lexer.check_next_string("n_arg");
json_lexer.check_next_char(':');
json_lexer.next_non_neg_int();
if( n_arg != json_lexer.token2size_t() )
{ string expected = CppAD::to_string(n_arg);
string found = json_lexer.token();
json_lexer.report_error(expected, found);
}
}
json_lexer.check_next_char('}');
//
// , (if not last entry)
if( i + 1 < n_define )
json_lexer.check_next_char(',');
}
json_lexer.check_next_char(']');
// ],
json_lexer.check_next_char(']');
json_lexer.check_next_char(',');
//
// -----------------------------------------------------------------------
// "n_dynamic_ind" : n_dynamic_ind ,
json_lexer.check_next_string("n_dynamic_ind");
json_lexer.check_next_char(':');
//
json_lexer.next_non_neg_int();
size_t n_dynamic_ind = json_lexer.token2size_t();
graph_obj.n_dynamic_ind_set(n_dynamic_ind);
//
json_lexer.check_next_char(',');
// -----------------------------------------------------------------------
// "n_variable_ind" : n_variable_ind ,
json_lexer.check_next_string("n_variable_ind");
json_lexer.check_next_char(':');
//
json_lexer.next_non_neg_int();
size_t n_variable_ind = json_lexer.token2size_t();
graph_obj.n_variable_ind_set(n_variable_ind);
//
json_lexer.check_next_char(',');
// -----------------------------------------------------------------------
// "constant_vec": [ n_constant, [ first_constant, ..., last_constant ] ],
json_lexer.check_next_string("constant_vec");
json_lexer.check_next_char(':');
json_lexer.check_next_char('[');
//
json_lexer.next_non_neg_int();
size_t n_constant = json_lexer.token2size_t();
//
json_lexer.check_next_char(',');
//
// [ first_constant, ... , last_constant ]
json_lexer.check_next_char('[');
for(size_t i = 0; i < n_constant; ++i)
{ json_lexer.next_float();
graph_obj.constant_vec_push_back( json_lexer.token2double() );
//
if( i + 1 < n_constant )
json_lexer.check_next_char(',');
}
json_lexer.check_next_char(']');
json_lexer.check_next_char(']');
json_lexer.check_next_char(',');
// -----------------------------------------------------------------------
// "op_usage_vec": [ n_usage, [ first_op_usage, ..., last_op_usage ] ],
json_lexer.check_next_string("op_usage_vec");
json_lexer.check_next_char(':');
json_lexer.check_next_char('[');
//
json_lexer.next_non_neg_int();
size_t n_usage = json_lexer.token2size_t();
//
json_lexer.check_next_char(',');
json_lexer.check_next_char('[');
//
// index for strings in current operator
CppAD::vector<size_t> str_index;
for(size_t i = 0; i < n_usage; ++i)
{ str_index.resize(0);
//
// [ op_code,
json_lexer.check_next_char('[');
//
// op_enum
json_lexer.next_non_neg_int();
graph_op_enum op_enum = op_code2enum[ json_lexer.token2size_t() ];
json_lexer.check_next_char(',');
//
size_t n_result = 1;
size_t n_arg = op_enum2fixed_n_arg[op_enum];
//
// check if number of arguments is fixed
bool fixed = n_arg > 0;
if( ! fixed )
{ if( op_enum == discrete_graph_op )
{ // name,
json_lexer.check_next_string(match_any_string);
string name = json_lexer.token();
json_lexer.check_next_char(',');
//
size_t name_index = graph_obj.discrete_name_vec_find(name);
if( name_index == graph_obj.discrete_name_vec_size() )
graph_obj.discrete_name_vec_push_back( name );
str_index.push_back(name_index);
}
else if( op_enum == atom_graph_op )
{ // name
json_lexer.check_next_string(match_any_string);
string name = json_lexer.token();
json_lexer.check_next_char(',');
//
size_t name_index = graph_obj.atomic_name_vec_find(name);
if( name_index == graph_obj.atomic_name_vec_size() )
graph_obj.atomic_name_vec_push_back( name );
str_index.push_back(name_index);
}
else if( op_enum == print_graph_op )
{ // before
json_lexer.check_next_string(match_any_string);
string before = json_lexer.token();
json_lexer.check_next_char(',');
//
size_t before_index = graph_obj.print_text_vec_find(before);
if( before_index == graph_obj.print_text_vec_size() )
graph_obj.print_text_vec_push_back(before);
str_index.push_back(before_index);
//
// aftere
json_lexer.check_next_string(match_any_string);
string after = json_lexer.token();
json_lexer.check_next_char(',');
//
size_t after_index = graph_obj.print_text_vec_find(after);
if( after_index == graph_obj.print_text_vec_size() )
graph_obj.print_text_vec_push_back(after);
str_index.push_back(after_index);
}
else CPPAD_ASSERT_UNKNOWN(
op_enum == comp_eq_graph_op ||
op_enum == comp_le_graph_op ||
op_enum == comp_lt_graph_op ||
op_enum == comp_ne_graph_op ||
op_enum == sum_graph_op
);
// n_result,
json_lexer.next_non_neg_int();
n_result = json_lexer.token2size_t();
json_lexer.check_next_char(',');
//
// n_arg, [
json_lexer.next_non_neg_int();
n_arg = json_lexer.token2size_t();
json_lexer.check_next_char(',');
json_lexer.check_next_char('[');
}
//
// atom_graph_op: name_index, n_result, n_arg
// come before first argument
if( op_enum == atom_graph_op )
{ // name_index, n_result, n_arg come before first_node
size_t name_index = str_index[0];
CPPAD_ASSERT_UNKNOWN(
name_index < graph_obj.atomic_name_vec_size()
);
graph_obj.operator_arg_push_back( name_index );
graph_obj.operator_arg_push_back( n_result );
graph_obj.operator_arg_push_back( n_arg );
}
// discrete_op: name_index comes before first argument
if( op_enum == discrete_graph_op )
{ size_t name_index = str_index[0];
graph_obj.operator_arg_push_back( name_index );
}
// print_op: before_index, after_index come before first argument
if( op_enum == print_graph_op )
{ size_t before_index = str_index[0];
size_t after_index = str_index[1];
graph_obj.operator_arg_push_back( before_index );
graph_obj.operator_arg_push_back( after_index );
}
//
// sum_graph_op: n_arg comes before first argument
if( op_enum == sum_graph_op )
graph_obj.operator_arg_push_back( n_arg );
//
// operator_vec
graph_op_enum op_usage;
op_usage = op_enum;
graph_obj.operator_vec_push_back( op_usage );
for(size_t j = 0; j < n_arg; ++j)
{ // next_arg
json_lexer.next_non_neg_int();
size_t argument_node = json_lexer.token2size_t();
graph_obj.operator_arg_push_back( argument_node );
//
// , (if not last entry)
if( j + 1 < n_arg )
json_lexer.check_next_char(',');
}
json_lexer.check_next_char(']');
if( ! fixed )
json_lexer.check_next_char(']');
//
// , (if not last entry)
if( i + 1 < n_usage )
json_lexer.check_next_char(',');
}
json_lexer.check_next_char(']');
json_lexer.check_next_char(']');
json_lexer.check_next_char(',');
// -----------------------------------------------------------------------
// "dependent_vec": [ n_dependent, [first_dependent, ..., last_dependent] ]
json_lexer.check_next_string("dependent_vec");
json_lexer.check_next_char(':');
json_lexer.check_next_char('[');
//
json_lexer.next_non_neg_int();
size_t n_dependent = json_lexer.token2size_t();
json_lexer.check_next_char(',');
//
json_lexer.check_next_char('[');
for(size_t i = 0; i < n_dependent; ++i)
{ json_lexer.next_float();
graph_obj.dependent_vec_push_back( json_lexer.token2size_t() );
//
if( i + 1 < n_dependent )
json_lexer.check_next_char(',');
}
json_lexer.check_next_char(']');
json_lexer.check_next_char(']');
// -----------------------------------------------------------------------
// end of Json object
json_lexer.check_next_char('}');
//
return;
}
| 37.836207 | 79 | 0.55715 | eric-heiden |
9cdbfd728fbd218182b08609f6be804d202a8279 | 9,495 | hxx | C++ | src/libserver/html/html_block.hxx | msuslu/rspamd | 95764f816a9e1251a755c6edad339637345cfe28 | [
"Apache-2.0"
] | 1 | 2017-10-24T22:23:44.000Z | 2017-10-24T22:23:44.000Z | src/libserver/html/html_block.hxx | msuslu/rspamd | 95764f816a9e1251a755c6edad339637345cfe28 | [
"Apache-2.0"
] | null | null | null | src/libserver/html/html_block.hxx | msuslu/rspamd | 95764f816a9e1251a755c6edad339637345cfe28 | [
"Apache-2.0"
] | 1 | 2022-02-20T17:41:48.000Z | 2022-02-20T17:41:48.000Z | /*-
* Copyright 2021 Vsevolod Stakhov
*
* 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 RSPAMD_HTML_BLOCK_HXX
#define RSPAMD_HTML_BLOCK_HXX
#pragma once
#include "libserver/css/css_value.hxx"
#include <cmath>
namespace rspamd::html {
/*
* Block tag definition
*/
struct html_block {
rspamd::css::css_color fg_color;
rspamd::css::css_color bg_color;
std::int16_t height;
std::int16_t width;
rspamd::css::css_display_value display;
std::int8_t font_size;
unsigned fg_color_mask : 2;
unsigned bg_color_mask : 2;
unsigned height_mask : 2;
unsigned width_mask : 2;
unsigned font_mask : 2;
unsigned display_mask : 2;
unsigned visibility_mask : 2;
constexpr static const auto unset = 0;
constexpr static const auto inherited = 1;
constexpr static const auto implicit = 1;
constexpr static const auto set = 3;
constexpr static const auto invisible_flag = 1;
constexpr static const auto transparent_flag = 2;
/* Helpers to set mask when setting the elements */
auto set_fgcolor(const rspamd::css::css_color &c, int how = html_block::set) -> void {
fg_color = c;
fg_color_mask = how;
}
auto set_bgcolor(const rspamd::css::css_color &c, int how = html_block::set) -> void {
bg_color = c;
bg_color_mask = how;
}
auto set_height(float h, bool is_percent = false, int how = html_block::set) -> void {
h = is_percent ? (-h) : h;
if (h < INT16_MIN) {
/* Negative numbers encode percents... */
height = -100;
}
else if (h > INT16_MAX) {
height = INT16_MAX;
}
else {
height = h;
}
height_mask = how;
}
auto set_width(float w, bool is_percent = false, int how = html_block::set) -> void {
w = is_percent ? (-w) : w;
if (w < INT16_MIN) {
width = INT16_MIN;
}
else if (w > INT16_MAX) {
width = INT16_MAX;
}
else {
width = w;
}
width_mask = how;
}
auto set_display(bool v, int how = html_block::set) -> void {
if (v) {
display = rspamd::css::css_display_value::DISPLAY_INLINE;
}
else {
display = rspamd::css::css_display_value::DISPLAY_HIDDEN;
}
display_mask = how;
}
auto set_display(rspamd::css::css_display_value v, int how = html_block::set) -> void {
display = v;
display_mask = how;
}
auto set_font_size(float fs, bool is_percent = false, int how = html_block::set) -> void {
fs = is_percent ? (-fs) : fs;
if (fs < INT8_MIN) {
font_size = -100;
}
else if (fs > INT8_MAX) {
font_size = INT8_MAX;
}
else {
font_size = fs;
}
font_mask = how;
}
private:
template<typename T, typename MT>
static constexpr auto simple_prop(MT mask_val, MT other_mask, T &our_val,
T other_val) -> MT
{
if (other_mask && other_mask > mask_val) {
our_val = other_val;
mask_val = html_block::inherited;
}
return mask_val;
}
/* Sizes propagation logic
* We can have multiple cases:
* 1) Our size is > 0 and we can use it as is
* 2) Parent size is > 0 and our size is undefined, so propagate parent
* 3) Parent size is < 0 and our size is undefined - propagate parent
* 4) Parent size is > 0 and our size is < 0 - multiply parent by abs(ours)
* 5) Parent size is undefined and our size is < 0 - tricky stuff, assume some defaults
*/
template<typename T, typename MT>
static constexpr auto size_prop (MT mask_val, MT other_mask, T &our_val,
T other_val, T default_val) -> MT
{
if (mask_val) {
/* We have our value */
if (our_val < 0) {
if (other_mask > 0) {
if (other_val >= 0) {
our_val = other_val * (-our_val / 100.0);
}
else {
our_val *= (-other_val / 100.0);
}
}
else {
/* Parent value is not defined and our value is relative */
our_val = default_val * (-our_val / 100.0);
}
}
else if (other_mask && other_mask > mask_val) {
our_val = other_val;
mask_val = html_block::inherited;
}
}
else {
/* We propagate parent if defined */
if (other_mask && other_mask > mask_val) {
our_val = other_val;
mask_val = html_block::inherited;
}
/* Otherwise do nothing */
}
return mask_val;
}
public:
/**
* Propagate values from the block if they are not defined by the current block
* @param other
* @return
*/
auto propagate_block(const html_block &other) -> void {
fg_color_mask = html_block::simple_prop(fg_color_mask, other.fg_color_mask,
fg_color, other.fg_color);
bg_color_mask = html_block::simple_prop(bg_color_mask, other.bg_color_mask,
bg_color, other.bg_color);
display_mask = html_block::simple_prop(display_mask, other.display_mask,
display, other.display);
height_mask = html_block::size_prop(height_mask, other.height_mask,
height, other.height, static_cast<std::int16_t>(800));
width_mask = html_block::size_prop(width_mask, other.width_mask,
width, other.width, static_cast<std::int16_t>(1024));
font_mask = html_block::size_prop(font_mask, other.font_mask,
font_size, other.font_size, static_cast<std::int8_t>(10));
}
/*
* Set block overriding all inherited values
*/
auto set_block(const html_block &other) -> void {
constexpr auto set_value = [](auto mask_val, auto other_mask, auto &our_val,
auto other_val) constexpr -> int {
if (other_mask && mask_val != html_block::set) {
our_val = other_val;
mask_val = other_mask;
}
return mask_val;
};
fg_color_mask = set_value(fg_color_mask, other.fg_color_mask, fg_color, other.fg_color);
bg_color_mask = set_value(bg_color_mask, other.bg_color_mask, bg_color, other.bg_color);
display_mask = set_value(display_mask, other.display_mask, display, other.display);
height_mask = set_value(height_mask, other.height_mask, height, other.height);
width_mask = set_value(width_mask, other.width_mask, width, other.width);
font_mask = set_value(font_mask, other.font_mask, font_size, other.font_size);
}
auto compute_visibility(void) -> void {
if (display_mask) {
if (display == css::css_display_value::DISPLAY_HIDDEN) {
visibility_mask = html_block::invisible_flag;
return;
}
}
if (font_mask) {
if (font_size == 0) {
visibility_mask = html_block::invisible_flag;
return;
}
}
auto is_similar_colors = [](const rspamd::css::css_color &fg, const rspamd::css::css_color &bg) -> bool {
constexpr const auto min_visible_diff = 0.1f;
auto diff_r = ((float)fg.r - bg.r);
auto diff_g = ((float)fg.g - bg.g);
auto diff_b = ((float)fg.b - bg.b);
auto ravg = ((float)fg.r + bg.r) / 2.0f;
/* Square diffs */
diff_r *= diff_r;
diff_g *= diff_g;
diff_b *= diff_b;
auto diff = std::sqrt(2.0f * diff_r + 4.0f * diff_g + 3.0f * diff_b +
(ravg * (diff_r - diff_b) / 256.0f)) / 256.0f;
return diff < min_visible_diff;
};
/* Check if we have both bg/fg colors */
if (fg_color_mask && bg_color_mask) {
if (fg_color.alpha < 10) {
/* Too transparent */
visibility_mask = html_block::transparent_flag;
return;
}
if (bg_color.alpha > 10) {
if (is_similar_colors(fg_color, bg_color)) {
visibility_mask = html_block::transparent_flag;
return;
}
}
}
else if (fg_color_mask) {
/* Merely fg color */
if (fg_color.alpha < 10) {
/* Too transparent */
visibility_mask = html_block::transparent_flag;
return;
}
/* Implicit fg color */
if (is_similar_colors(fg_color, rspamd::css::css_color::white())) {
visibility_mask = html_block::transparent_flag;
return;
}
}
else if (bg_color_mask) {
if (bg_color.alpha > 10) {
if (is_similar_colors(rspamd::css::css_color::black(), bg_color)) {
visibility_mask = html_block::transparent_flag;
return;
}
}
}
visibility_mask = html_block::unset;
}
constexpr auto is_visible(void) const -> bool {
return visibility_mask == html_block::unset;
}
constexpr auto is_transparent(void) const -> bool {
return visibility_mask == html_block::transparent_flag;
}
constexpr auto has_display(int how = html_block::set) const -> bool {
return display_mask >= how;
}
/**
* Returns a default html block for root HTML element
* @return
*/
static auto default_html_block(void) -> html_block {
return html_block{.fg_color = rspamd::css::css_color::black(),
.bg_color = rspamd::css::css_color::white(),
.height = 0,
.width = 0,
.display = rspamd::css::css_display_value::DISPLAY_INLINE,
.font_size = 12,
.fg_color_mask = html_block::inherited,
.bg_color_mask = html_block::inherited,
.height_mask = html_block::unset,
.width_mask = html_block::unset,
.font_mask = html_block::unset,
.display_mask = html_block::inherited,
.visibility_mask = html_block::unset};
}
/**
* Produces html block with no defined values allocated from the pool
* @param pool
* @return
*/
static auto undefined_html_block_pool(rspamd_mempool_t *pool) -> html_block* {
auto *bl = rspamd_mempool_alloc0_type(pool, html_block);
return bl;
}
};
}
#endif //RSPAMD_HTML_BLOCK_HXX
| 27.763158 | 107 | 0.67288 | msuslu |
9cdcb7d8b7ee69bc1dedd8cda1a889a343814e31 | 41,185 | cpp | C++ | tests/unit/TAO/API/tokens.cpp | cyptoman/LLL-TAO | dfaad5497e280df576b6d2e7959f82874c42fe3e | [
"MIT"
] | null | null | null | tests/unit/TAO/API/tokens.cpp | cyptoman/LLL-TAO | dfaad5497e280df576b6d2e7959f82874c42fe3e | [
"MIT"
] | null | null | null | tests/unit/TAO/API/tokens.cpp | cyptoman/LLL-TAO | dfaad5497e280df576b6d2e7959f82874c42fe3e | [
"MIT"
] | null | null | null | /*__________________________________________________________________________________________
(c) Hash(BEGIN(Satoshi[2010]), END(Sunny[2012])) == Videlicet[2014] ++
(c) Copyright The Nexus Developers 2014 - 2019
Distributed under the MIT software license, see the accompanying
file COPYING or http://www.opensource.org/licenses/mit-license.php.
"ad vocem populi" - To the Voice of the People
____________________________________________________________________________________________*/
#include "util.h"
#include <LLC/include/random.h>
#include <unit/catch2/catch.hpp>
#include <LLD/include/global.h>
#include <TAO/Ledger/types/transaction.h>
#include <TAO/Ledger/include/chainstate.h>
#include <TAO/Operation/include/enum.h>
#include <TAO/Operation/include/execute.h>
#include <TAO/Register/include/create.h>
#include <TAO/API/types/names.h>
TEST_CASE( "Test Tokens API - create token", "[tokens/create/token]")
{
/* Declare variables shared across test cases */
json::json params;
json::json ret;
json::json result;
json::json error;
/* Generate random token name */
std::string strToken = "TOKEN" + std::to_string(LLC::GetRand());
/* Ensure user is created and logged in for testing */
InitializeUser(USERNAME1, PASSWORD, PIN, GENESIS1, SESSION1);
/* tokens/create/token fail with missing pin (only relevant for multiuser)*/
if(config::fMultiuser.load())
{
/* Build the parameters to pass to the API */
params.clear();
params["session"] = SESSION1;
/* Invoke the API */
ret = APICall("tokens/create/token", params);
/* Check response is an error and validate error code */
REQUIRE(ret.find("error") != ret.end());
REQUIRE(ret["error"]["code"].get<int32_t>() == -129);
}
/* tokens/create/token fail with missing session (only relevant for multiuser)*/
if(config::fMultiuser.load())
{
/* Build the parameters to pass to the API */
params.clear();
params["pin"] = PIN;
/* Invoke the API */
ret = APICall("tokens/create/token", params);
/* Check response is an error and validate error code */
REQUIRE(ret.find("error") != ret.end());
REQUIRE(ret["error"]["code"].get<int32_t>() == -12);
}
/* tokens/create/token fail with missing supply */
{
/* Build the parameters to pass to the API */
params.clear();
params["pin"] = PIN;
params["session"] = SESSION1;
params["name"] = strToken;
/* Invoke the API */
ret = APICall("tokens/create/token", params);
/* Check response is an error and validate error code */
REQUIRE(ret.find("error") != ret.end());
REQUIRE(ret["error"]["code"].get<int32_t>() == -119);
}
/* tokens/create/token success */
{
/* Build the parameters to pass to the API */
params.clear();
params["pin"] = PIN;
params["session"] = SESSION1;
params["name"] = strToken;
params["supply"] = "10000";
params["decimals"] = "2";
/* Invoke the API */
ret = APICall("tokens/create/token", params);
/* Check that the result is as we expect it to be */
REQUIRE(ret.find("result") != ret.end());
result = ret["result"];
REQUIRE(result.find("txid") != result.end());
REQUIRE(result.find("address") != result.end());
}
}
TEST_CASE( "Test Tokens API - debit token", "[tokens/debit/token]")
{
/* Declare variables shared across test cases */
json::json params;
json::json ret;
json::json result;
json::json error;
/* Generate random token name */
std::string strToken = "TOKEN" +std::to_string(LLC::GetRand());
/* Ensure user is created and logged in for testing */
InitializeUser(USERNAME1, PASSWORD, PIN, GENESIS1, SESSION1);
/* Create Token */
{
/* Build the parameters to pass to the API */
params.clear();
params["pin"] = PIN;
params["session"] = SESSION1;
params["name"] = strToken;
params["supply"] = "10000";
params["decimals"] = "2";
/* Invoke the API */
ret = APICall("tokens/create/token", params);
/* Check that the result is as we expect it to be */
REQUIRE(ret.find("result") != ret.end());
result = ret["result"];
REQUIRE(result.find("txid") != result.end());
REQUIRE(result.find("address") != result.end());
}
/* Test fail with missing amount */
{
/* Build the parameters to pass to the API */
params.clear();
params["pin"] = PIN;
params["session"] = SESSION1;
/* Invoke the API */
ret = APICall("tokens/debit/token", params);
/* Check response is an error and validate error code */
REQUIRE(ret.find("error") != ret.end());
REQUIRE(ret["error"]["code"].get<int32_t>() == -46);
}
/* Test fail with missing name / address*/
{
/* Build the parameters to pass to the API */
params.clear();
params["pin"] = PIN;
params["session"] = SESSION1;
params["amount"] = "100";
params["address_to"] = TAO::Register::Address(TAO::Register::Address::ACCOUNT).ToString();
/* Invoke the API */
ret = APICall("tokens/debit/token", params);
/* Check response is an error and validate error code */
REQUIRE(ret.find("error") != ret.end());
REQUIRE(ret["error"]["code"].get<int32_t>() == -33);
}
/* Test fail with invalid name */
{
/* Build the parameters to pass to the API */
params.clear();
params["pin"] = PIN;
params["session"] = SESSION1;
params["amount"] = "100";
params["name_to"] = "random";
params["name"] = "random";
/* Invoke the API */
ret = APICall("tokens/debit/token", params);
/* Check response is an error and validate error code */
REQUIRE(ret.find("error") != ret.end());
REQUIRE(ret["error"]["code"].get<int32_t>() == -101);
}
/* Test fail with invalid address */
{
/* Build the parameters to pass to the API */
params.clear();
params["pin"] = PIN;
params["session"] = SESSION1;
params["amount"] = "100";
params["address_to"] = TAO::Register::Address(TAO::Register::Address::ACCOUNT).ToString();
params["address"] = TAO::Register::Address(TAO::Register::Address::TOKEN).ToString();
/* Invoke the API */
ret = APICall("tokens/debit/token", params);
/* Check response is an error and validate error code */
REQUIRE(ret.find("error") != ret.end());
REQUIRE(ret["error"]["code"].get<int32_t>() == -122);
}
/* Test fail with missing name_to / address_to */
{
/* Build the parameters to pass to the API */
params.clear();
params["pin"] = PIN;
params["session"] = SESSION1;
params["name"] = strToken;
params["amount"] = "100";
/* Invoke the API */
ret = APICall("tokens/debit/token", params);
/* Check response is an error and validate error code */
REQUIRE(ret.find("error") != ret.end());
REQUIRE(ret["error"]["code"].get<int32_t>() == -64);
}
/* Test fail with invalid name_to */
{
/* Build the parameters to pass to the API */
params.clear();
params["pin"] = PIN;
params["session"] = SESSION1;
params["name"] = strToken;
params["amount"] = "100";
params["name_to"] = "random";
/* Invoke the API */
ret = APICall("tokens/debit/token", params);
/* Check response is an error and validate error code */
REQUIRE(ret.find("error") != ret.end());
REQUIRE(ret["error"]["code"].get<int32_t>() == -101);
}
/* Create an account to send to */
std::string strAccountAddress;
{
/* Build the parameters to pass to the API */
params.clear();
params["pin"] = PIN;
params["session"] = SESSION1;
params["name"] = "main";
params["token_name"] = strToken;
/* Invoke the API */
ret = APICall("tokens/create/account", params);
/* Check that the result is as we expect it to be */
REQUIRE(ret.find("result") != ret.end());
result = ret["result"];
REQUIRE(result.find("txid") != result.end());
REQUIRE(result.find("address") != result.end());
strAccountAddress = result["address"].get<std::string>();
}
/* Test success case by name_to */
{
/* Build the parameters to pass to the API */
params.clear();
params["pin"] = PIN;
params["session"] = SESSION1;
params["name"] = strToken;
params["amount"] = "100";
params["name_to"] = "main";
/* Invoke the API */
ret = APICall("tokens/debit/token", params);
REQUIRE(result.find("txid") != result.end());
}
/* Test success case by address_to */
{
/* Build the parameters to pass to the API */
params.clear();
params["pin"] = PIN;
params["session"] = SESSION1;
params["name"] = strToken;
params["amount"] = "100";
params["address_to"] = strAccountAddress;
/* Invoke the API */
ret = APICall("tokens/debit/token", params);
REQUIRE(result.find("txid") != result.end());
}
}
TEST_CASE( "Test Tokens API - credit token", "[tokens/credit/token]")
{
/* Declare variables shared across test cases */
json::json params;
json::json ret;
json::json result;
json::json error;
/* Generate random token name */
std::string strToken = "TOKEN" +std::to_string(LLC::GetRand());
std::string strTXID;
/* Ensure user is created and logged in for testing */
InitializeUser(USERNAME1, PASSWORD, PIN, GENESIS1, SESSION1);
/* Create Token to debit and then credit*/
{
/* Build the parameters to pass to the API */
params.clear();
params["pin"] = PIN;
params["session"] = SESSION1;
params["name"] = strToken;
params["supply"] = "10000";
params["decimals"] = "2";
/* Invoke the API */
ret = APICall("tokens/create/token", params);
/* Check that the result is as we expect it to be */
REQUIRE(ret.find("result") != ret.end());
result = ret["result"];
REQUIRE(result.find("txid") != result.end());
REQUIRE(result.find("address") != result.end());
}
/* Create debit transaction to random address (we will be crediting it back to ourselves so it doesn't matter where it goes) */
{
/* Build the parameters to pass to the API */
params.clear();
params["pin"] = PIN;
params["session"] = SESSION1;
params["name"] = strToken;
params["amount"] = "100";
params["address_to"] = TAO::Register::Address(TAO::Register::Address::ACCOUNT).ToString();
/* Invoke the API */
ret = APICall("tokens/debit/token", params);
REQUIRE(result.find("txid") != result.end());
strTXID = result["txid"].get<std::string>();
}
/* Test fail with missing txid */
{
/* Build the parameters to pass to the API */
params.clear();
params["pin"] = PIN;
params["session"] = SESSION1;
/* Invoke the API */
ret = APICall("tokens/credit/token", params);
/* Check response is an error and validate error code */
REQUIRE(ret.find("error") != ret.end());
REQUIRE(ret["error"]["code"].get<int32_t>() == -50);
}
/* Test fail with invalid txid */
{
/* Build the parameters to pass to the API */
params.clear();
params["pin"] = PIN;
params["session"] = SESSION1;
params["txid"] = LLC::GetRand256().GetHex();
/* Invoke the API */
ret = APICall("tokens/credit/token", params);
/* Check response is an error and validate error code */
REQUIRE(ret.find("error") != ret.end());
REQUIRE(ret["error"]["code"].get<int32_t>() == -40);
}
/* Test success case */
{
/* Build the parameters to pass to the API */
params.clear();
params["pin"] = PIN;
params["session"] = SESSION1;
params["txid"] = strTXID;
/* Invoke the API */
ret = APICall("tokens/credit/token", params);
REQUIRE(result.find("txid") != result.end());
}
}
TEST_CASE( "Test Tokens API - get token", "[tokens/get/token]")
{
/* Declare variables shared across test cases */
json::json params;
json::json ret;
json::json result;
json::json error;
/* Generate random token name */
std::string strToken = "TOKEN" +std::to_string(LLC::GetRand());
std::string strTokenAddress;
std::string strTXID;
/* Ensure user is created and logged in for testing */
InitializeUser(USERNAME1, PASSWORD, PIN, GENESIS1, SESSION1);
/* Create Token to retrieve */
{
/* Build the parameters to pass to the API */
params.clear();
params["pin"] = PIN;
params["session"] = SESSION1;
params["name"] = strToken;
params["supply"] = "10000";
params["decimals"] = "2";
/* Invoke the API */
ret = APICall("tokens/create/token", params);
/* Check that the result is as we expect it to be */
REQUIRE(ret.find("result") != ret.end());
result = ret["result"];
REQUIRE(result.find("txid") != result.end());
REQUIRE(result.find("address") != result.end());
strTokenAddress = result["address"].get<std::string>();
}
/* Test fail with missing name / address */
{
/* Build the parameters to pass to the API */
params.clear();
params["pin"] = PIN;
params["session"] = SESSION1;
/* Invoke the API */
ret = APICall("tokens/get/token", params);
/* Check response is an error and validate error code */
REQUIRE(ret.find("error") != ret.end());
REQUIRE(ret["error"]["code"].get<int32_t>() == -33);
}
/* Test fail with invalid name */
{
/* Build the parameters to pass to the API */
params.clear();
params["pin"] = PIN;
params["session"] = SESSION1;
params["name"] = "asdfsdfsdf";
/* Invoke the API */
ret = APICall("tokens/get/token", params);
/* Check response is an error and validate error code */
REQUIRE(ret.find("error") != ret.end());
REQUIRE(ret["error"]["code"].get<int32_t>() == -101);
}
/* Test fail with invalid address */
{
/* Build the parameters to pass to the API */
params.clear();
params["pin"] = PIN;
params["session"] = SESSION1;
params["address"] = TAO::Register::Address(TAO::Register::Address::TOKEN).ToString();
/* Invoke the API */
ret = APICall("tokens/get/token", params);
/* Check response is an error and validate error code */
REQUIRE(ret.find("error") != ret.end());
REQUIRE(ret["error"]["code"].get<int32_t>() == -122);
}
/* Test successful get by name */
{
/* Build the parameters to pass to the API */
params.clear();
params["pin"] = PIN;
params["session"] = SESSION1;
params["name"] = strToken;
/* Invoke the API */
ret = APICall("tokens/get/token", params);
/* Check that the result is as we expect it to be */
REQUIRE(ret.find("result") != ret.end());
result = ret["result"];
REQUIRE(result.find("owner") != result.end());
REQUIRE(result.find("created") != result.end());
REQUIRE(result.find("modified") != result.end());
REQUIRE(result.find("name") != result.end());
REQUIRE(result.find("address") != result.end());
REQUIRE(result.find("balance") != result.end());
REQUIRE(result.find("maxsupply") != result.end());
REQUIRE(result.find("currentsupply") != result.end());
REQUIRE(result.find("decimals") != result.end());
}
/* Test successful get by address */
{
/* Build the parameters to pass to the API */
params.clear();
params["pin"] = PIN;
params["session"] = SESSION1;
params["address"] = strTokenAddress;
/* Invoke the API */
ret = APICall("tokens/get/token", params);
/* Check that the result is as we expect it to be */
REQUIRE(ret.find("result") != ret.end());
result = ret["result"];
REQUIRE(result.find("owner") != result.end());
REQUIRE(result.find("created") != result.end());
REQUIRE(result.find("modified") != result.end());
REQUIRE(result.find("name") != result.end());
REQUIRE(result.find("address") != result.end());
REQUIRE(result.find("balance") != result.end());
REQUIRE(result.find("maxsupply") != result.end());
REQUIRE(result.find("currentsupply") != result.end());
REQUIRE(result.find("decimals") != result.end());
}
}
TEST_CASE( "Test Tokens API - create account", "[tokens/create/account]")
{
/* Declare variables shared across test cases */
json::json params;
json::json ret;
json::json result;
json::json error;
/* Generate random token name */
std::string strToken = "TOKEN" +std::to_string(LLC::GetRand());
std::string strTokenAddress;
/* Ensure user is created and logged in for testing */
InitializeUser(USERNAME1, PASSWORD, PIN, GENESIS1, SESSION1);
/* create token to create account for */
{
/* Build the parameters to pass to the API */
params.clear();
params["pin"] = PIN;
params["session"] = SESSION1;
params["name"] = strToken;
params["supply"] = "10000";
params["decimals"] = "2";
/* Invoke the API */
ret = APICall("tokens/create/token", params);
/* Check that the result is as we expect it to be */
REQUIRE(ret.find("result") != ret.end());
result = ret["result"];
REQUIRE(result.find("txid") != result.end());
REQUIRE(result.find("address") != result.end());
strTokenAddress = result["address"].get<std::string>();
}
/* tokens/create/account fail with missing pin (only relevant for multiuser)*/
if(config::fMultiuser.load())
{
/* Build the parameters to pass to the API */
params.clear();
params["session"] = SESSION1;
/* Invoke the API */
ret = APICall("tokens/create/account", params);
/* Check response is an error and validate error code */
REQUIRE(ret.find("error") != ret.end());
REQUIRE(ret["error"]["code"].get<int32_t>() == -129);
}
/* tokens/create/account fail with missing session (only relevant for multiuser)*/
if(config::fMultiuser.load())
{
/* Build the parameters to pass to the API */
params.clear();
params["pin"] = PIN;
/* Invoke the API */
ret = APICall("tokens/create/account", params);
/* Check response is an error and validate error code */
REQUIRE(ret.find("error") != ret.end());
REQUIRE(ret["error"]["code"].get<int32_t>() == -12);
}
/* tokens/create/account fail with missing token name / address*/
{
/* Build the parameters to pass to the API */
params.clear();
params["pin"] = PIN;
params["session"] = SESSION1;
/* Invoke the API */
ret = APICall("tokens/create/account", params);
/* Check response is an error and validate error code */
REQUIRE(ret.find("error") != ret.end());
REQUIRE(ret["error"]["code"].get<int32_t>() == -37);
}
/* tokens/create/account by token name success */
{
/* Build the parameters to pass to the API */
params.clear();
params["pin"] = PIN;
params["session"] = SESSION1;
params["token_name"] = strToken;
/* Invoke the API */
ret = APICall("tokens/create/account", params);
/* Check that the result is as we expect it to be */
REQUIRE(ret.find("result") != ret.end());
result = ret["result"];
REQUIRE(result.find("txid") != result.end());
REQUIRE(result.find("address") != result.end());
}
/* tokens/create/account by token address success */
{
/* Build the parameters to pass to the API */
params.clear();
params["pin"] = PIN;
params["session"] = SESSION1;
params["token"] = strTokenAddress;
/* Invoke the API */
ret = APICall("tokens/create/account", params);
/* Check that the result is as we expect it to be */
REQUIRE(ret.find("result") != ret.end());
result = ret["result"];
REQUIRE(result.find("txid") != result.end());
REQUIRE(result.find("address") != result.end());
}
}
TEST_CASE( "Test Tokens API - debit account", "[tokens/debit/account]")
{
/* Declare variables shared across test cases */
json::json params;
json::json ret;
json::json result;
json::json error;
/* Generate random token name */
std::string strToken = "TOKEN" +std::to_string(LLC::GetRand());
TAO::Register::Address hashToken = TAO::Register::Address(TAO::Register::Address::TOKEN);
std::string strAccount = "ACCOUNT" +std::to_string(LLC::GetRand());
TAO::Register::Address hashAccount = TAO::Register::Address(TAO::Register::Address::ACCOUNT);
uint512_t hashDebitTx;
/* Ensure user is created and logged in for testing */
InitializeUser(USERNAME1, PASSWORD, PIN, GENESIS1, SESSION1);
/* create token to create account for */
{
//create the transaction object
TAO::Ledger::Transaction tx;
tx.hashGenesis = GENESIS1;
tx.nSequence = 0;
tx.nTimestamp = runtime::timestamp();
//create object
TAO::Register::Object token = TAO::Register::CreateToken(hashToken, 1000000, 2);
//payload
tx[0] << uint8_t(TAO::Operation::OP::CREATE) << hashToken << uint8_t(TAO::Register::REGISTER::OBJECT) << token.GetState();
//create name
tx[1] = TAO::API::Names::CreateName(GENESIS1, strToken, "", hashToken);
//generate the prestates and poststates
REQUIRE(tx.Build());
//verify the prestates and poststates
REQUIRE(tx.Verify());
//commit to disk
REQUIRE(Execute(tx[0], TAO::Ledger::FLAGS::BLOCK));
//commit to disk
REQUIRE(Execute(tx[1], TAO::Ledger::FLAGS::BLOCK));
}
/* create account to debit */
{
//create the transaction object
TAO::Ledger::Transaction tx;
tx.hashGenesis = GENESIS1;
tx.nSequence = 1;
tx.nTimestamp = runtime::timestamp();
//create object
TAO::Register::Object account = TAO::Register::CreateAccount(hashToken);
//payload
tx[0] << uint8_t(TAO::Operation::OP::CREATE) << hashAccount << uint8_t(TAO::Register::REGISTER::OBJECT) << account.GetState();
//create name
tx[1] = TAO::API::Names::CreateName(GENESIS1, strAccount, "", hashAccount);
//generate the prestates and poststates
REQUIRE(tx.Build());
//verify the prestates and poststates
REQUIRE(tx.Verify());
//commit to disk
REQUIRE(Execute(tx[0], TAO::Ledger::FLAGS::BLOCK));
//commit to disk
REQUIRE(Execute(tx[1], TAO::Ledger::FLAGS::BLOCK));
}
/* Test fail with missing amount */
{
/* Build the parameters to pass to the API */
params.clear();
params["pin"] = PIN;
params["session"] = SESSION1;
/* Invoke the API */
ret = APICall("tokens/debit/account", params);
/* Check response is an error and validate error code */
REQUIRE(ret.find("error") != ret.end());
REQUIRE(ret["error"]["code"].get<int32_t>() == -46);
}
/* Test fail with missing name / address*/
{
/* Build the parameters to pass to the API */
params.clear();
params["pin"] = PIN;
params["session"] = SESSION1;
params["amount"] = "100";
params["address_to"] = TAO::Register::Address(TAO::Register::Address::ACCOUNT).ToString();
/* Invoke the API */
ret = APICall("tokens/debit/account", params);
/* Check response is an error and validate error code */
REQUIRE(ret.find("error") != ret.end());
REQUIRE(ret["error"]["code"].get<int32_t>() == -33);
}
/* Test fail with invalid name */
{
/* Build the parameters to pass to the API */
params.clear();
params["pin"] = PIN;
params["session"] = SESSION1;
params["amount"] = "100";
params["name_to"] = "random";
params["name"] = "random";
/* Invoke the API */
ret = APICall("tokens/debit/account", params);
/* Check response is an error and validate error code */
REQUIRE(ret.find("error") != ret.end());
REQUIRE(ret["error"]["code"].get<int32_t>() == -101);
}
/* Test fail with invalid address */
{
/* Build the parameters to pass to the API */
params.clear();
params["pin"] = PIN;
params["session"] = SESSION1;
params["amount"] = "100";
params["address_to"] = TAO::Register::Address(TAO::Register::Address::ACCOUNT).ToString();
params["address"] = TAO::Register::Address(TAO::Register::Address::ACCOUNT).ToString();
/* Invoke the API */
ret = APICall("tokens/debit/account", params);
/* Check response is an error and validate error code */
REQUIRE(ret.find("error") != ret.end());
REQUIRE(ret["error"]["code"].get<int32_t>() == -122);
}
/* Test fail with missing name_to / address_to */
{
/* Build the parameters to pass to the API */
params.clear();
params["pin"] = PIN;
params["session"] = SESSION1;
params["address"] = hashAccount.ToString();
params["amount"] = "100";
/* Invoke the API */
ret = APICall("tokens/debit/account", params);
/* Check response is an error and validate error code */
REQUIRE(ret.find("error") != ret.end());
REQUIRE(ret["error"]["code"].get<int32_t>() == -64);
}
/* Test fail with invalid name_to */
{
/* Build the parameters to pass to the API */
params.clear();
params["pin"] = PIN;
params["session"] = SESSION1;
params["address"] = hashAccount.ToString();
params["amount"] = "100";
params["name_to"] = "random";
/* Invoke the API */
ret = APICall("tokens/debit/account", params);
/* Check response is an error and validate error code */
REQUIRE(ret.find("error") != ret.end());
REQUIRE(ret["error"]["code"].get<int32_t>() == -101);
}
/* Test fail with insufficient funds */
{
/* Build the parameters to pass to the API */
params.clear();
params["pin"] = PIN;
params["session"] = SESSION1;
params["address"] = hashAccount.ToString();
params["amount"] = "100";
params["address_to"] = hashToken.ToString();
/* Invoke the API */
ret = APICall("tokens/debit/account", params);
/* Check response is an error and validate error code */
REQUIRE(ret.find("error") != ret.end());
REQUIRE(ret["error"]["code"].get<int32_t>() == -69);
}
/* Debit the token and credit the account so that we have some funds to debit */
{
TAO::Ledger::Transaction tx;
tx.hashGenesis = GENESIS1;
tx.nSequence = 0;
tx.nTimestamp = runtime::timestamp();
//payload
tx[0] << uint8_t(TAO::Operation::OP::DEBIT) << hashToken << hashAccount << uint64_t(100000) << uint64_t(0);
//generate the prestates and poststates
REQUIRE(tx.Build());
//verify the prestates and poststates
REQUIRE(tx.Verify());
//write transaction
REQUIRE(LLD::Ledger->WriteTx(tx.GetHash(), tx));
REQUIRE(LLD::Ledger->IndexBlock(tx.GetHash(), TAO::Ledger::ChainState::Genesis()));
//commit to disk
REQUIRE(Execute(tx[0], TAO::Ledger::FLAGS::BLOCK));
hashDebitTx = tx.GetHash();
}
{
TAO::Ledger::Transaction tx;
tx.hashGenesis = GENESIS1;
tx.nSequence = 1;
tx.nTimestamp = runtime::timestamp();
//payload
tx[0] << uint8_t(TAO::Operation::OP::CREDIT) << hashDebitTx << uint32_t(0) << hashAccount << hashToken << uint64_t(100000);
//generate the prestates and poststates
REQUIRE(tx.Build());
//verify the prestates and poststates
REQUIRE(tx.Verify());
//write transaction
REQUIRE(LLD::Ledger->WriteTx(tx.GetHash(), tx));
REQUIRE(LLD::Ledger->IndexBlock(tx.GetHash(), TAO::Ledger::ChainState::Genesis()));
//commit to disk
REQUIRE(Execute(tx[0], TAO::Ledger::FLAGS::BLOCK));
}
/* Test success case by name_to */
{
/* Build the parameters to pass to the API */
params.clear();
params["pin"] = PIN;
params["session"] = SESSION1;
params["name"] = strAccount;
params["amount"] = "100";
params["name_to"] = strToken;
/* Invoke the API */
ret = APICall("tokens/debit/account", params);
REQUIRE(ret.find("result") != ret.end());
result = ret["result"];
REQUIRE(result.find("txid") != result.end());
}
/* Test success case by address_to */
{
/* Build the parameters to pass to the API */
params.clear();
params["pin"] = PIN;
params["session"] = SESSION1;
params["address"] = hashAccount.ToString();
params["amount"] = "100";
params["address_to"] = hashToken.ToString();
/* Invoke the API */
ret = APICall("tokens/debit/account", params);
REQUIRE(ret.find("result") != ret.end());
result = ret["result"];
REQUIRE(result.find("txid") != result.end());
}
}
TEST_CASE( "Test Tokens API - credit account", "[tokens/credit/account]")
{
/* Declare variables shared across test cases */
json::json params;
json::json ret;
json::json result;
json::json error;
/* Generate random token name */
std::string strToken = "TOKEN" + std::to_string(LLC::GetRand());
TAO::Register::Address hashToken = TAO::Register::Address(TAO::Register::Address::TOKEN);
std::string strAccount = "ACCOUNT" + std::to_string(LLC::GetRand());
TAO::Register::Address hashAccount = TAO::Register::Address(TAO::Register::Address::ACCOUNT);
std::string strTXID;
/* Ensure user is created and logged in for testing */
InitializeUser(USERNAME1, PASSWORD, PIN, GENESIS1, SESSION1);
/* create token to create account for */
{
//create the transaction object
TAO::Ledger::Transaction tx;
tx.hashGenesis = GENESIS1;
tx.nSequence = 0;
tx.nTimestamp = runtime::timestamp();
//create object
TAO::Register::Object token = TAO::Register::CreateToken(hashToken, 10000, 2);
//payload
tx[0] << uint8_t(TAO::Operation::OP::CREATE) << hashToken << uint8_t(TAO::Register::REGISTER::OBJECT) << token.GetState();
//create name
tx[1] = TAO::API::Names::CreateName(GENESIS1, strToken, "", hashToken);
//generate the prestates and poststates
REQUIRE(tx.Build());
//verify the prestates and poststates
REQUIRE(tx.Verify());
//commit to disk
REQUIRE(Execute(tx[0], TAO::Ledger::FLAGS::BLOCK));
//commit to disk
REQUIRE(Execute(tx[1], TAO::Ledger::FLAGS::BLOCK));
}
/* create account to debit */
{
//create the transaction object
TAO::Ledger::Transaction tx;
tx.hashGenesis = GENESIS1;
tx.nSequence = 1;
tx.nTimestamp = runtime::timestamp();
//create object
TAO::Register::Object account = TAO::Register::CreateAccount(hashToken);
//create name
TAO::Register::Object name = TAO::Register::CreateName("", strToken, hashAccount);
//payload
tx[0] << uint8_t(TAO::Operation::OP::CREATE) << hashAccount << uint8_t(TAO::Register::REGISTER::OBJECT) << account.GetState();
//create name
tx[1] = TAO::API::Names::CreateName(GENESIS1, strAccount, "", hashAccount);
//generate the prestates and poststates
REQUIRE(tx.Build());
//verify the prestates and poststates
REQUIRE(tx.Verify());
//commit to disk
REQUIRE(Execute(tx[0], TAO::Ledger::FLAGS::BLOCK));
//commit to disk
REQUIRE(Execute(tx[1], TAO::Ledger::FLAGS::BLOCK));
}
/* Debit the token and credit the account so that we have some funds to debit */
{
TAO::Ledger::Transaction tx;
tx.hashGenesis = GENESIS1;
tx.nSequence = 2;
tx.nTimestamp = runtime::timestamp();
//payload
tx[0] << uint8_t(TAO::Operation::OP::DEBIT) << hashToken << hashAccount << uint64_t(1000) << uint64_t(0);
//generate the prestates and poststates
REQUIRE(tx.Build());
//verify the prestates and poststates
REQUIRE(tx.Verify());
//write transaction
REQUIRE(LLD::Ledger->WriteTx(tx.GetHash(), tx));
REQUIRE(LLD::Ledger->IndexBlock(tx.GetHash(), TAO::Ledger::ChainState::Genesis()));
//commit to disk
REQUIRE(Execute(tx[0], TAO::Ledger::FLAGS::BLOCK));
strTXID = tx.GetHash().GetHex();
}
/* Test fail with missing txid */
{
/* Build the parameters to pass to the API */
params.clear();
params["pin"] = PIN;
params["session"] = SESSION1;
/* Invoke the API */
ret = APICall("tokens/credit/account", params);
/* Check response is an error and validate error code */
REQUIRE(ret.find("error") != ret.end());
REQUIRE(ret["error"]["code"].get<int32_t>() == -50);
}
/* Test fail with invalid txid */
{
/* Build the parameters to pass to the API */
params.clear();
params["pin"] = PIN;
params["session"] = SESSION1;
params["txid"] = LLC::GetRand256().GetHex();
/* Invoke the API */
ret = APICall("tokens/credit/account", params);
/* Check response is an error and validate error code */
REQUIRE(ret.find("error") != ret.end());
REQUIRE(ret["error"]["code"].get<int32_t>() == -40);
}
/* Test success case */
{
/* Build the parameters to pass to the API */
params.clear();
params["pin"] = PIN;
params["session"] = SESSION1;
params["txid"] = strTXID;
/* Invoke the API */
ret = APICall("tokens/credit/account", params);
/* Check the result */
REQUIRE(ret.find("result") != ret.end());
result = ret["result"];
REQUIRE(result.find("txid") != result.end());
}
}
TEST_CASE( "Test Tokens API - get account", "[tokens/get/account]")
{
/* Declare variables shared across test cases */
json::json params;
json::json ret;
json::json result;
json::json error;
/* Generate random token name */
std::string strToken = "TOKEN" +std::to_string(LLC::GetRand());
TAO::Register::Address hashToken = TAO::Register::Address(TAO::Register::Address::TOKEN);
std::string strAccount = "ACCOUNT" +std::to_string(LLC::GetRand());
TAO::Register::Address hashAccount = TAO::Register::Address(TAO::Register::Address::ACCOUNT);
std::string strTXID;
/* Ensure user is created and logged in for testing */
InitializeUser(USERNAME1, PASSWORD, PIN, GENESIS1, SESSION1);
/* create token to create account for */
{
/* Build the parameters to pass to the API */
params.clear();
params["pin"] = PIN;
params["session"] = SESSION1;
params["name"] = strToken;
params["supply"] = "10000";
params["decimals"] = "2";
/* Invoke the API */
ret = APICall("tokens/create/token", params);
/* Check that the result is as we expect it to be */
REQUIRE(ret.find("result") != ret.end());
result = ret["result"];
REQUIRE(result.find("txid") != result.end());
REQUIRE(result.find("address") != result.end());
hashToken.SetBase58( result["address"].get<std::string>());
}
/* tokens/create/account by token address success */
{
/* Build the parameters to pass to the API */
params.clear();
params["pin"] = PIN;
params["session"] = SESSION1;
params["name"] = strAccount;
params["token"] = hashToken.ToString();
/* Invoke the API */
ret = APICall("tokens/create/account", params);
/* Check that the result is as we expect it to be */
REQUIRE(ret.find("result") != ret.end());
result = ret["result"];
REQUIRE(result.find("txid") != result.end());
REQUIRE(result.find("address") != result.end());
hashAccount.SetBase58( result["address"].get<std::string>());
}
/* Test fail with missing name / address */
{
/* Build the parameters to pass to the API */
params.clear();
params["pin"] = PIN;
params["session"] = SESSION1;
/* Invoke the API */
ret = APICall("tokens/get/account", params);
/* Check response is an error and validate error code */
REQUIRE(ret.find("error") != ret.end());
REQUIRE(ret["error"]["code"].get<int32_t>() == -33);
}
/* Test fail with invalid name */
{
/* Build the parameters to pass to the API */
params.clear();
params["pin"] = PIN;
params["session"] = SESSION1;
params["name"] = "asdfsdfsdf";
/* Invoke the API */
ret = APICall("tokens/get/account", params);
/* Check response is an error and validate error code */
REQUIRE(ret.find("error") != ret.end());
REQUIRE(ret["error"]["code"].get<int32_t>() == -101);
}
/* Test fail with invalid address */
{
/* Build the parameters to pass to the API */
params.clear();
params["pin"] = PIN;
params["session"] = SESSION1;
params["address"] = TAO::Register::Address(TAO::Register::Address::ACCOUNT).ToString();
/* Invoke the API */
ret = APICall("tokens/get/account", params);
/* Check response is an error and validate error code */
REQUIRE(ret.find("error") != ret.end());
REQUIRE(ret["error"]["code"].get<int32_t>() == -122);
}
/* Test successful get by name */
{
/* Build the parameters to pass to the API */
params.clear();
params["pin"] = PIN;
params["session"] = SESSION1;
params["name"] = strAccount;
/* Invoke the API */
ret = APICall("tokens/get/account", params);
/* Check that the result is as we expect it to be */
REQUIRE(ret.find("result") != ret.end());
result = ret["result"];
REQUIRE(result.find("owner") != result.end());
REQUIRE(result.find("created") != result.end());
REQUIRE(result.find("modified") != result.end());
REQUIRE(result.find("name") != result.end());
REQUIRE(result.find("address") != result.end());
REQUIRE(result.find("token_name") != result.end());
REQUIRE(result.find("token") != result.end());
REQUIRE(result.find("balance") != result.end());
}
/* Test successful get by address */
{
/* Build the parameters to pass to the API */
params.clear();
params["pin"] = PIN;
params["session"] = SESSION1;
params["address"] = hashAccount.ToString();
/* Invoke the API */
ret = APICall("tokens/get/account", params);
/* Check that the result is as we expect it to be */
REQUIRE(ret.find("result") != ret.end());
result = ret["result"];
REQUIRE(result.find("owner") != result.end());
REQUIRE(result.find("created") != result.end());
REQUIRE(result.find("modified") != result.end());
REQUIRE(result.find("name") != result.end());
REQUIRE(result.find("address") != result.end());
REQUIRE(result.find("token_name") != result.end());
REQUIRE(result.find("token") != result.end());
REQUIRE(result.find("balance") != result.end());
}
}
| 31.705158 | 134 | 0.566808 | cyptoman |
9cdcee2c61b64c8f4d0e8d25efdd8f038d2a1ed0 | 3,040 | cpp | C++ | Source/Engine/ING/Source/ING/Rendering/Pipeline/Pipeline.cpp | n-c0d3r/ING | f858c973e1b31ffc6deb324fa52eda6323d2c165 | [
"MIT"
] | 2 | 2022-01-21T04:03:55.000Z | 2022-03-19T08:54:00.000Z | Source/Engine/ING/Source/ING/Rendering/Pipeline/Pipeline.cpp | n-c0d3r/ING | f858c973e1b31ffc6deb324fa52eda6323d2c165 | [
"MIT"
] | null | null | null | Source/Engine/ING/Source/ING/Rendering/Pipeline/Pipeline.cpp | n-c0d3r/ING | f858c973e1b31ffc6deb324fa52eda6323d2c165 | [
"MIT"
] | null | null | null |
/**
* Include Header
*/
#include "Pipeline.h"
/**
* Include Camera
*/
#include <ING/Camera/Camera.h>
/**
* Include Renderer
*/
#include <ING/Rendering/Renderer/Renderer.h>
/**
* Include Rendering API
*/
#include <ING/Rendering/API/API.h>
/**
* Include Rendering Device Context
*/
#include <ING/Rendering/API/Device/Context/Context.h>
/**
* Include Rendering Device
*/
#include <ING/Rendering/API/Device/Device.h>
/**
* Include Rendering Pass
*/
#include <ING/Rendering/Pass/Pass.h>
namespace ING {
namespace Rendering {
/**IIDeviceContext
* Constructors And Destructor
*/
IPipeline::IPipeline (const String& name) :
renderer(0)
{
this->name = name;
isRendering = false;
}
IPipeline::~IPipeline () {
}
/**
* Release Methods
*/
void IPipeline::Release() {
for (unsigned int i = 0; i < passVector.size(); ++i) {
passVector[i]->Release();
}
passVector.clear();
for (Camera* camera : CameraManager::GetInstance()->GetCameraList()) {
if (camera->GetRenderingPipeline() == this) {
ClearCameraData(camera);
camera->SetRenderingPipeline(0);
}
}
delete this;
}
/**
* Methods
*/
void IPipeline::AddPass(IPass* pass) {
AddPass(pass, passVector.size());
}
void IPipeline::AddPass(IPass* pass, unsigned int index) {
if (passVector.size() == index) {
passVector.push_back(pass);
}
else {
passVector.insert(passVector.begin() + index, pass);
unsigned int passCount = passVector.size();
for (unsigned int i = index + 1; i < passCount; ++i) {
name2PassIndex[passVector[i]->GetName()]++;
}
}
name2PassIndex[pass->GetName()] = index;
pass->parent = 0;
pass->SetPipeline(this);
}
void IPipeline::RemovePass(unsigned int index) {
String passName = GetPass(index)->GetName();
GetPass(index)->SetPipeline(0);
passVector.erase(passVector.begin() + index);
unsigned int passCount = passVector.size();
for (unsigned int i = index + 1; i < passCount; ++i) {
name2PassIndex[passVector[i]->GetName()]--;
}
name2PassIndex.erase(passName);
}
void IPipeline::RemovePass(const String& name) {
RemovePass(name2PassIndex[name]);
}
void IPipeline::RemovePass(IPass* pass) {
RemovePass(pass->GetName());
}
void IPipeline::SetupCamera (IDeviceContext* context, Camera* camera) {
}
void IPipeline::ClearCameraData(Camera* camera) {
camera->SetRenderingData(0);
}
bool IPipeline::Render (IDeviceContext* context) {
BeginRender(context);
EndRender(context);
return true;
}
void IPipeline::BeginRender(IDeviceContext* context) {
isRendering = true;
for (Camera* camera : CameraManager::GetInstance()->GetCameraList()) {
if (camera->GetRenderingPipeline() == this && camera->GetRenderingData() == 0) {
SetupCamera(context, camera);
}
}
}
void IPipeline::EndRender(IDeviceContext* context) {
isRendering = false;
}
}
} | 13.755656 | 84 | 0.630921 | n-c0d3r |
9ce343bbf398a54f1d484a4b09fd7f41522fba03 | 3,681 | cpp | C++ | code_reading/oceanbase-master/src/sql/engine/expr/ob_expr_rownum.cpp | wangcy6/weekly_read | 3a8837ee9cd957787ee1785e4066dd623e02e13a | [
"Apache-2.0"
] | null | null | null | code_reading/oceanbase-master/src/sql/engine/expr/ob_expr_rownum.cpp | wangcy6/weekly_read | 3a8837ee9cd957787ee1785e4066dd623e02e13a | [
"Apache-2.0"
] | null | null | null | code_reading/oceanbase-master/src/sql/engine/expr/ob_expr_rownum.cpp | wangcy6/weekly_read | 3a8837ee9cd957787ee1785e4066dd623e02e13a | [
"Apache-2.0"
] | 1 | 2020-10-18T12:59:31.000Z | 2020-10-18T12:59:31.000Z | /**
* Copyright (c) 2021 OceanBase
* OceanBase CE is licensed under Mulan PubL v2.
* You can use this software according to the terms and conditions of the Mulan PubL v2.
* You may obtain a copy of Mulan PubL v2 at:
* http://license.coscl.org.cn/MulanPubL-2.0
* THIS SOFTWARE IS PROVIDED ON AN "AS IS" BASIS, WITHOUT WARRANTIES OF ANY KIND,
* EITHER EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO NON-INFRINGEMENT,
* MERCHANTABILITY OR FIT FOR A PARTICULAR PURPOSE.
* See the Mulan PubL v2 for more details.
*/
#define USING_LOG_PREFIX SQL_ENG
#include "sql/engine/expr/ob_expr_rownum.h"
#include "sql/engine/basic/ob_count.h"
#include "sql/engine/basic/ob_count_op.h"
#include "sql/engine/ob_exec_context.h"
#include "sql/code_generator/ob_static_engine_expr_cg.h"
#include "sql/engine/expr/ob_expr_util.h"
namespace oceanbase {
using namespace common;
namespace sql {
OB_SERIALIZE_MEMBER((ObExprRowNum, ObFuncExprOperator), operator_id_);
ObExprRowNum::ObExprRowNum(ObIAllocator& alloc)
: ObFuncExprOperator(alloc, T_FUN_SYS_ROWNUM, "rownum", 0, NOT_ROW_DIMENSION), operator_id_(OB_INVALID_ID)
{}
ObExprRowNum::~ObExprRowNum()
{}
int ObExprRowNum::calc_result_type0(ObExprResType& type, ObExprTypeCtx& type_ctx) const
{
UNUSED(type_ctx);
type.set_number();
type.set_scale(ObAccuracy::DDL_DEFAULT_ACCURACY[ObNumberType].scale_);
type.set_precision(ObAccuracy::DDL_DEFAULT_ACCURACY[ObNumberType].precision_);
return OB_SUCCESS;
}
int ObExprRowNum::calc_result0(ObObj& result, ObExprCtx& expr_ctx) const
{
int ret = OB_SUCCESS;
if (OB_ISNULL(expr_ctx.exec_ctx_) || OB_ISNULL(expr_ctx.calc_buf_)) {
ret = OB_ERR_UNEXPECTED;
LOG_WARN("exec ctx is null", K(ret), K(expr_ctx.exec_ctx_), K(expr_ctx.calc_buf_));
} else {
ObExecContext& exec_ctx = *expr_ctx.exec_ctx_;
ObCount::ObCountCtx* count_ctx = NULL;
number::ObNumber num;
uint64_t count_op_id = OB_INVALID_ID == operator_id_ ? expr_ctx.phy_operator_ctx_id_ : operator_id_;
if (OB_ISNULL(count_ctx = GET_PHY_OPERATOR_CTX(ObCount::ObCountCtx, exec_ctx, count_op_id))) {
ret = OB_ERR_UNEXPECTED;
LOG_WARN("get physical operator ctx failed", K(ret));
} else if (OB_FAIL(num.from(count_ctx->cur_rownum_, *expr_ctx.calc_buf_))) {
LOG_WARN("failed to convert int as number", K(ret));
} else {
result.set_number(num);
}
}
return ret;
}
int ObExprRowNum::cg_expr(ObExprCGCtx& op_cg_ctx, const ObRawExpr& raw_expr, ObExpr& rt_expr) const
{
int ret = OB_SUCCESS;
UNUSED(raw_expr);
UNUSED(op_cg_ctx);
rt_expr.extra_ = operator_id_;
rt_expr.eval_func_ = &rownum_eval;
return ret;
}
int ObExprRowNum::rownum_eval(const ObExpr& expr, ObEvalCtx& ctx, ObDatum& expr_datum)
{
int ret = OB_SUCCESS;
uint64_t operator_id = expr.extra_;
ObOperatorKit* kit = ctx.exec_ctx_.get_operator_kit(operator_id);
if (OB_ISNULL(kit) || OB_ISNULL(kit->op_)) {
ret = OB_ERR_UNEXPECTED;
LOG_WARN("operator is NULL", K(ret), K(operator_id), KP(kit));
} else if (OB_UNLIKELY(PHY_COUNT != kit->op_->get_spec().type_)) {
ret = OB_ERR_UNEXPECTED;
LOG_WARN("is not count operator", K(ret), K(operator_id), "spec", kit->op_->get_spec());
} else {
char local_buff[number::ObNumber::MAX_BYTE_LEN];
ObDataBuffer local_alloc(local_buff, number::ObNumber::MAX_BYTE_LEN);
number::ObNumber num;
ObCountOp* count_op = static_cast<ObCountOp*>(kit->op_);
if (OB_FAIL(num.from(count_op->get_cur_rownum(), local_alloc))) {
LOG_WARN("failed to convert int to number", K(ret));
} else {
expr_datum.set_number(num);
}
}
return ret;
}
} /* namespace sql */
} /* namespace oceanbase */
| 35.737864 | 110 | 0.728063 | wangcy6 |
9ce435b973be57cb06a17dbf338393469e151eec | 11,192 | cc | C++ | ns3/ns-3.26/src/internet/model/ipv4-raw-socket-impl.cc | Aedemon/clusim | 7f09cdb79b5f02cf0fed1bd44842981941f29f32 | [
"Apache-2.0"
] | 7 | 2017-08-11T06:06:47.000Z | 2022-02-27T07:34:33.000Z | ns3/ns-3.26/src/internet/model/ipv4-raw-socket-impl.cc | Aedemon/clusim | 7f09cdb79b5f02cf0fed1bd44842981941f29f32 | [
"Apache-2.0"
] | 3 | 2017-08-11T03:04:59.000Z | 2017-09-11T14:01:14.000Z | ns3/ns-3.26/src/internet/model/ipv4-raw-socket-impl.cc | Aedemon/clusim | 7f09cdb79b5f02cf0fed1bd44842981941f29f32 | [
"Apache-2.0"
] | 3 | 2017-08-08T13:36:30.000Z | 2018-07-04T09:49:41.000Z | /* -*- Mode:C++; c-file-style:"gnu"; indent-tabs-mode:nil; -*- */
#include <netinet/in.h>
#include <sys/socket.h>
#include <sys/types.h>
#include "ipv4-raw-socket-impl.h"
#include "ipv4-l3-protocol.h"
#include "icmpv4.h"
#include "ns3/ipv4-packet-info-tag.h"
#include "ns3/inet-socket-address.h"
#include "ns3/node.h"
#include "ns3/packet.h"
#include "ns3/uinteger.h"
#include "ns3/boolean.h"
#include "ns3/log.h"
namespace ns3 {
NS_LOG_COMPONENT_DEFINE ("Ipv4RawSocketImpl");
NS_OBJECT_ENSURE_REGISTERED (Ipv4RawSocketImpl);
TypeId
Ipv4RawSocketImpl::GetTypeId (void)
{
static TypeId tid = TypeId ("ns3::Ipv4RawSocketImpl")
.SetParent<Socket> ()
.SetGroupName ("Internet")
.AddAttribute ("Protocol", "Protocol number to match.",
UintegerValue (0),
MakeUintegerAccessor (&Ipv4RawSocketImpl::m_protocol),
MakeUintegerChecker<uint16_t> ())
.AddAttribute ("IcmpFilter",
"Any icmp header whose type field matches a bit in this filter is dropped. Type must be less than 32.",
UintegerValue (0),
MakeUintegerAccessor (&Ipv4RawSocketImpl::m_icmpFilter),
MakeUintegerChecker<uint32_t> ())
//
// from raw (7), linux, returned length of Send/Recv should be
//
// | IP_HDRINC on | off |
// ----------+---------------+-------------+-
// Send(Ipv4)| hdr + payload | payload |
// Recv(Ipv4)| hdr + payload | hdr+payload |
// ----------+---------------+-------------+-
.AddAttribute ("IpHeaderInclude",
"Include IP Header information (a.k.a setsockopt (IP_HDRINCL)).",
BooleanValue (false),
MakeBooleanAccessor (&Ipv4RawSocketImpl::m_iphdrincl),
MakeBooleanChecker ())
;
return tid;
}
Ipv4RawSocketImpl::Ipv4RawSocketImpl ()
{
NS_LOG_FUNCTION (this);
m_err = Socket::ERROR_NOTERROR;
m_node = 0;
m_src = Ipv4Address::GetAny ();
m_dst = Ipv4Address::GetAny ();
m_protocol = 0;
m_shutdownSend = false;
m_shutdownRecv = false;
}
void
Ipv4RawSocketImpl::SetNode (Ptr<Node> node)
{
NS_LOG_FUNCTION (this << node);
m_node = node;
}
void
Ipv4RawSocketImpl::DoDispose (void)
{
NS_LOG_FUNCTION (this);
m_node = 0;
Socket::DoDispose ();
}
enum Socket::SocketErrno
Ipv4RawSocketImpl::GetErrno (void) const
{
NS_LOG_FUNCTION (this);
return m_err;
}
enum Socket::SocketType
Ipv4RawSocketImpl::GetSocketType (void) const
{
NS_LOG_FUNCTION (this);
return NS3_SOCK_RAW;
}
Ptr<Node>
Ipv4RawSocketImpl::GetNode (void) const
{
NS_LOG_FUNCTION (this);
return m_node;
}
int
Ipv4RawSocketImpl::Bind (const Address &address)
{
NS_LOG_FUNCTION (this << address);
if (!InetSocketAddress::IsMatchingType (address))
{
m_err = Socket::ERROR_INVAL;
return -1;
}
InetSocketAddress ad = InetSocketAddress::ConvertFrom (address);
m_src = ad.GetIpv4 ();
return 0;
}
int
Ipv4RawSocketImpl::Bind (void)
{
NS_LOG_FUNCTION (this);
m_src = Ipv4Address::GetAny ();
return 0;
}
int
Ipv4RawSocketImpl::Bind6 (void)
{
NS_LOG_FUNCTION (this);
return (-1);
}
int
Ipv4RawSocketImpl::GetSockName (Address &address) const
{
NS_LOG_FUNCTION (this << address);
address = InetSocketAddress (m_src, 0);
return 0;
}
int
Ipv4RawSocketImpl::GetPeerName (Address &address) const
{
NS_LOG_FUNCTION (this << address);
if (m_dst == Ipv4Address::GetAny ())
{
m_err = ERROR_NOTCONN;
return -1;
}
address = InetSocketAddress (m_dst, 0);
return 0;
}
int
Ipv4RawSocketImpl::Close (void)
{
NS_LOG_FUNCTION (this);
Ptr<Ipv4> ipv4 = m_node->GetObject<Ipv4> ();
if (ipv4 != 0)
{
ipv4->DeleteRawSocket (this);
}
return 0;
}
int
Ipv4RawSocketImpl::ShutdownSend (void)
{
NS_LOG_FUNCTION (this);
m_shutdownSend = true;
return 0;
}
int
Ipv4RawSocketImpl::ShutdownRecv (void)
{
NS_LOG_FUNCTION (this);
m_shutdownRecv = true;
return 0;
}
int
Ipv4RawSocketImpl::Connect (const Address &address)
{
NS_LOG_FUNCTION (this << address);
if (!InetSocketAddress::IsMatchingType (address))
{
m_err = Socket::ERROR_INVAL;
return -1;
}
InetSocketAddress ad = InetSocketAddress::ConvertFrom (address);
m_dst = ad.GetIpv4 ();
SetIpTos (ad.GetTos ());
return 0;
}
int
Ipv4RawSocketImpl::Listen (void)
{
NS_LOG_FUNCTION (this);
m_err = Socket::ERROR_OPNOTSUPP;
return -1;
}
uint32_t
Ipv4RawSocketImpl::GetTxAvailable (void) const
{
NS_LOG_FUNCTION (this);
return 0xffffffff;
}
int
Ipv4RawSocketImpl::Send (Ptr<Packet> p, uint32_t flags)
{
NS_LOG_FUNCTION (this << p << flags);
InetSocketAddress to = InetSocketAddress (m_dst, m_protocol);
to.SetTos (GetIpTos ());
return SendTo (p, flags, to);
}
int
Ipv4RawSocketImpl::SendTo (Ptr<Packet> p, uint32_t flags,
const Address &toAddress)
{
NS_LOG_FUNCTION (this << p << flags << toAddress);
if (!InetSocketAddress::IsMatchingType (toAddress))
{
m_err = Socket::ERROR_INVAL;
return -1;
}
if (m_shutdownSend)
{
return 0;
}
InetSocketAddress ad = InetSocketAddress::ConvertFrom (toAddress);
Ptr<Ipv4> ipv4 = m_node->GetObject<Ipv4> ();
Ipv4Address dst = ad.GetIpv4 ();
Ipv4Address src = m_src;
uint8_t tos = ad.GetTos ();
uint8_t priority = GetPriority ();
if (tos)
{
SocketIpTosTag ipTosTag;
ipTosTag.SetTos (tos);
// This packet may already have a SocketIpTosTag (see BUG 2440)
p->ReplacePacketTag (ipTosTag);
priority = IpTos2Priority (tos);
}
if (priority)
{
SocketPriorityTag priorityTag;
priorityTag.SetPriority (priority);
p->ReplacePacketTag (priorityTag);
}
if (IsManualIpTtl () && GetIpTtl () != 0 && !dst.IsMulticast () && !dst.IsBroadcast ())
{
SocketIpTtlTag tag;
tag.SetTtl (GetIpTtl ());
p->AddPacketTag (tag);
}
if (ipv4->GetRoutingProtocol ())
{
Ipv4Header header;
if (!m_iphdrincl)
{
header.SetDestination (dst);
header.SetProtocol (m_protocol);
}
else
{
p->RemoveHeader (header);
dst = header.GetDestination ();
src = header.GetSource ();
}
SocketErrno errno_ = ERROR_NOTERROR; //do not use errno as it is the standard C last error number
Ptr<Ipv4Route> route;
Ptr<NetDevice> oif = m_boundnetdevice; //specify non-zero if bound to a source address
if (!oif && src != Ipv4Address::GetAny ())
{
int32_t index = ipv4->GetInterfaceForAddress (src);
NS_ASSERT (index >= 0);
oif = ipv4->GetNetDevice (index);
NS_LOG_LOGIC ("Set index " << oif << "from source " << src);
}
// TBD-- we could cache the route and just check its validity
route = ipv4->GetRoutingProtocol ()->RouteOutput (p, header, oif, errno_);
if (route != 0)
{
NS_LOG_LOGIC ("Route exists");
uint32_t pktSize = p->GetSize ();
if (!m_iphdrincl)
{
ipv4->Send (p, route->GetSource (), dst, m_protocol, route);
}
else
{
pktSize += header.GetSerializedSize ();
ipv4->SendWithHeader (p, header, route);
}
NotifyDataSent (pktSize);
NotifySend (GetTxAvailable ());
return pktSize;
}
else
{
NS_LOG_DEBUG ("dropped because no outgoing route.");
return -1;
}
}
return 0;
}
uint32_t
Ipv4RawSocketImpl::GetRxAvailable (void) const
{
NS_LOG_FUNCTION (this);
uint32_t rx = 0;
for (std::list<Data>::const_iterator i = m_recv.begin (); i != m_recv.end (); ++i)
{
rx += (i->packet)->GetSize ();
}
return rx;
}
Ptr<Packet>
Ipv4RawSocketImpl::Recv (uint32_t maxSize, uint32_t flags)
{
NS_LOG_FUNCTION (this << maxSize << flags);
Address tmp;
return RecvFrom (maxSize, flags, tmp);
}
Ptr<Packet>
Ipv4RawSocketImpl::RecvFrom (uint32_t maxSize, uint32_t flags,
Address &fromAddress)
{
NS_LOG_FUNCTION (this << maxSize << flags << fromAddress);
if (m_recv.empty ())
{
return 0;
}
struct Data data = m_recv.front ();
m_recv.pop_front ();
InetSocketAddress inet = InetSocketAddress (data.fromIp, data.fromProtocol);
fromAddress = inet;
if (data.packet->GetSize () > maxSize)
{
Ptr<Packet> first = data.packet->CreateFragment (0, maxSize);
if (!(flags & MSG_PEEK))
{
data.packet->RemoveAtStart (maxSize);
}
m_recv.push_front (data);
return first;
}
return data.packet;
}
void
Ipv4RawSocketImpl::SetProtocol (uint16_t protocol)
{
NS_LOG_FUNCTION (this << protocol);
m_protocol = protocol;
}
bool
Ipv4RawSocketImpl::ForwardUp (Ptr<const Packet> p, Ipv4Header ipHeader, Ptr<Ipv4Interface> incomingInterface)
{
NS_LOG_FUNCTION (this << *p << ipHeader << incomingInterface);
if (m_shutdownRecv)
{
return false;
}
Ptr<NetDevice> boundNetDevice = Socket::GetBoundNetDevice();
if (boundNetDevice)
{
if (boundNetDevice != incomingInterface->GetDevice())
{
return false;
}
}
NS_LOG_LOGIC ("src = " << m_src << " dst = " << m_dst);
if ((m_src == Ipv4Address::GetAny () || ipHeader.GetDestination () == m_src) &&
(m_dst == Ipv4Address::GetAny () || ipHeader.GetSource () == m_dst) &&
ipHeader.GetProtocol () == m_protocol)
{
Ptr<Packet> copy = p->Copy ();
// Should check via getsockopt ()..
if (IsRecvPktInfo ())
{
Ipv4PacketInfoTag tag;
copy->RemovePacketTag (tag);
tag.SetRecvIf (incomingInterface->GetDevice ()->GetIfIndex ());
copy->AddPacketTag (tag);
}
//Check only version 4 options
if (IsIpRecvTos ())
{
SocketIpTosTag ipTosTag;
ipTosTag.SetTos (ipHeader.GetTos ());
copy->AddPacketTag (ipTosTag);
}
if (IsIpRecvTtl ())
{
SocketIpTtlTag ipTtlTag;
ipTtlTag.SetTtl (ipHeader.GetTtl ());
copy->AddPacketTag (ipTtlTag);
}
if (m_protocol == 1)
{
Icmpv4Header icmpHeader;
copy->PeekHeader (icmpHeader);
uint8_t type = icmpHeader.GetType ();
if (type < 32 &&
((uint32_t(1) << type) & m_icmpFilter))
{
// filter out icmp packet.
return false;
}
}
copy->AddHeader (ipHeader);
struct Data data;
data.packet = copy;
data.fromIp = ipHeader.GetSource ();
data.fromProtocol = ipHeader.GetProtocol ();
m_recv.push_back (data);
NotifyDataRecv ();
return true;
}
return false;
}
bool
Ipv4RawSocketImpl::SetAllowBroadcast (bool allowBroadcast)
{
NS_LOG_FUNCTION (this << allowBroadcast);
if (!allowBroadcast)
{
return false;
}
return true;
}
bool
Ipv4RawSocketImpl::GetAllowBroadcast () const
{
NS_LOG_FUNCTION (this);
return true;
}
} // namespace ns3
| 24.982143 | 122 | 0.608917 | Aedemon |
9ce4ebac3eb6cf5e5f748d0e54b3afb8a9f0a016 | 9,147 | cpp | C++ | src/qt/src/gui/widgets/qradiobutton.cpp | martende/phantomjs | 5cecd7dde7b8fd04ad2c036d16f09a8d2a139854 | [
"BSD-3-Clause"
] | 1 | 2015-03-16T20:49:09.000Z | 2015-03-16T20:49:09.000Z | src/qt/src/gui/widgets/qradiobutton.cpp | firedfox/phantomjs | afb0707c9db7b5e693ad1b216a50081565c08ebb | [
"BSD-3-Clause"
] | null | null | null | src/qt/src/gui/widgets/qradiobutton.cpp | firedfox/phantomjs | afb0707c9db7b5e693ad1b216a50081565c08ebb | [
"BSD-3-Clause"
] | null | null | null | /****************************************************************************
**
** Copyright (C) 2011 Nokia Corporation and/or its subsidiary(-ies).
** All rights reserved.
** Contact: Nokia Corporation (qt-info@nokia.com)
**
** This file is part of the QtGui module of the Qt Toolkit.
**
** $QT_BEGIN_LICENSE:LGPL$
** GNU Lesser General Public License Usage
** This file may be used under the terms of the GNU Lesser General Public
** License version 2.1 as published by the Free Software Foundation and
** appearing in the file LICENSE.LGPL included in the packaging of this
** file. Please review the following information to ensure the GNU Lesser
** General Public License version 2.1 requirements will be met:
** http://www.gnu.org/licenses/old-licenses/lgpl-2.1.html.
**
** In addition, as a special exception, Nokia gives you certain additional
** rights. These rights are described in the Nokia Qt LGPL Exception
** version 1.1, included in the file LGPL_EXCEPTION.txt in this package.
**
** GNU General Public License Usage
** Alternatively, this file may be used under the terms of the GNU General
** Public License version 3.0 as published by the Free Software Foundation
** and appearing in the file LICENSE.GPL included in the packaging of this
** file. Please review the following information to ensure the GNU General
** Public License version 3.0 requirements will be met:
** http://www.gnu.org/copyleft/gpl.html.
**
** Other Usage
** Alternatively, this file may be used in accordance with the terms and
** conditions contained in a signed written agreement between you and Nokia.
**
**
**
**
**
** $QT_END_LICENSE$
**
****************************************************************************/
#include "qradiobutton.h"
#include "qapplication.h"
#include "qbitmap.h"
#include "qbuttongroup.h"
#include "qstylepainter.h"
#include "qstyle.h"
#include "qstyleoption.h"
#include "qevent.h"
#include "private/qabstractbutton_p.h"
QT_BEGIN_NAMESPACE
class QRadioButtonPrivate : public QAbstractButtonPrivate
{
Q_DECLARE_PUBLIC(QRadioButton)
public:
QRadioButtonPrivate() : QAbstractButtonPrivate(QSizePolicy::RadioButton), hovering(true) {}
void init();
uint hovering : 1;
};
/*
Initializes the radio button.
*/
void QRadioButtonPrivate::init()
{
Q_Q(QRadioButton);
q->setCheckable(true);
q->setAutoExclusive(true);
q->setMouseTracking(true);
q->setForegroundRole(QPalette::WindowText);
setLayoutItemMargins(QStyle::SE_RadioButtonLayoutItem);
}
/*!
\class QRadioButton
\brief The QRadioButton widget provides a radio button with a text label.
\ingroup basicwidgets
A QRadioButton is an option button that can be switched on (checked) or
off (unchecked). Radio buttons typically present the user with a "one
of many" choice. In a group of radio buttons only one radio button at
a time can be checked; if the user selects another button, the
previously selected button is switched off.
Radio buttons are autoExclusive by default. If auto-exclusive is
enabled, radio buttons that belong to the same parent widget
behave as if they were part of the same exclusive button group. If
you need multiple exclusive button groups for radio buttons that
belong to the same parent widget, put them into a QButtonGroup.
Whenever a button is switched on or off it emits the toggled() signal.
Connect to this signal if you want to trigger an action each time the
button changes state. Use isChecked() to see if a particular button is
selected.
Just like QPushButton, a radio button displays text, and
optionally a small icon. The icon is set with setIcon(). The text
can be set in the constructor or with setText(). A shortcut key
can be specified by preceding the preferred character with an
ampersand in the text. For example:
\snippet doc/src/snippets/code/src_gui_widgets_qradiobutton.cpp 0
In this example the shortcut is \e{Alt+c}. See the \l
{QShortcut#mnemonic}{QShortcut} documentation for details (to
display an actual ampersand, use '&&').
Important inherited members: text(), setText(), text(),
setDown(), isDown(), autoRepeat(), group(), setAutoRepeat(),
toggle(), pressed(), released(), clicked(), and toggled().
\table 100%
\row \o \inlineimage plastique-radiobutton.png Screenshot of a Plastique radio button
\o A radio button shown in the \l{Plastique Style Widget Gallery}{Plastique widget style}.
\row \o \inlineimage windows-radiobutton.png Screenshot of a Windows XP radio button
\o A radio button shown in the \l{Windows XP Style Widget Gallery}{Windows XP widget style}.
\row \o \inlineimage macintosh-radiobutton.png Screenshot of a Macintosh radio button
\o A radio button shown in the \l{Macintosh Style Widget Gallery}{Macintosh widget style}.
\endtable
\sa QPushButton, QToolButton, QCheckBox, {fowler}{GUI Design Handbook: Radio Button},
{Group Box Example}
*/
/*!
Constructs a radio button with the given \a parent, but with no text or
pixmap.
The \a parent argument is passed on to the QAbstractButton constructor.
*/
QRadioButton::QRadioButton(QWidget *parent)
: QAbstractButton(*new QRadioButtonPrivate, parent)
{
Q_D(QRadioButton);
d->init();
}
/*!
Constructs a radio button with the given \a parent and a \a text string.
The \a parent argument is passed on to the QAbstractButton constructor.
*/
QRadioButton::QRadioButton(const QString &text, QWidget *parent)
: QAbstractButton(*new QRadioButtonPrivate, parent)
{
Q_D(QRadioButton);
d->init();
setText(text);
}
/*!
Initialize \a option with the values from this QRadioButton. This method is useful
for subclasses when they need a QStyleOptionButton, but don't want to fill
in all the information themselves.
\sa QStyleOption::initFrom()
*/
void QRadioButton::initStyleOption(QStyleOptionButton *option) const
{
if (!option)
return;
Q_D(const QRadioButton);
option->initFrom(this);
option->text = d->text;
option->icon = d->icon;
option->iconSize = iconSize();
if (d->down)
option->state |= QStyle::State_Sunken;
option->state |= (d->checked) ? QStyle::State_On : QStyle::State_Off;
if (testAttribute(Qt::WA_Hover) && underMouse()) {
if (d->hovering)
option->state |= QStyle::State_MouseOver;
else
option->state &= ~QStyle::State_MouseOver;
}
}
/*!
\reimp
*/
QSize QRadioButton::sizeHint() const
{
Q_D(const QRadioButton);
if (d->sizeHint.isValid())
return d->sizeHint;
ensurePolished();
QStyleOptionButton opt;
initStyleOption(&opt);
QSize sz = style()->itemTextRect(fontMetrics(), QRect(), Qt::TextShowMnemonic,
false, text()).size();
if (!opt.icon.isNull())
sz = QSize(sz.width() + opt.iconSize.width() + 4, qMax(sz.height(), opt.iconSize.height()));
d->sizeHint = (style()->sizeFromContents(QStyle::CT_RadioButton, &opt, sz, this).
expandedTo(QApplication::globalStrut()));
return d->sizeHint;
}
/*!
\reimp
\since 4.8
*/
QSize QRadioButton::minimumSizeHint() const
{
return sizeHint();
}
/*!
\reimp
*/
bool QRadioButton::hitButton(const QPoint &pos) const
{
QStyleOptionButton opt;
initStyleOption(&opt);
return style()->subElementRect(QStyle::SE_RadioButtonClickRect, &opt, this).contains(pos);
}
/*!
\reimp
*/
void QRadioButton::mouseMoveEvent(QMouseEvent *e)
{
Q_D(QRadioButton);
if (testAttribute(Qt::WA_Hover)) {
bool hit = false;
if (underMouse())
hit = hitButton(e->pos());
if (hit != d->hovering) {
update();
d->hovering = hit;
}
}
QAbstractButton::mouseMoveEvent(e);
}
/*!\reimp
*/
void QRadioButton::paintEvent(QPaintEvent *)
{
QStylePainter p(this);
QStyleOptionButton opt;
initStyleOption(&opt);
p.drawControl(QStyle::CE_RadioButton, opt);
}
/*! \reimp */
bool QRadioButton::event(QEvent *e)
{
Q_D(QRadioButton);
if (e->type() == QEvent::StyleChange
#ifdef Q_WS_MAC
|| e->type() == QEvent::MacSizeChange
#endif
)
d->setLayoutItemMargins(QStyle::SE_RadioButtonLayoutItem);
return QAbstractButton::event(e);
}
#ifdef QT3_SUPPORT
/*!
Use one of the constructors that doesn't take the \a name
argument and then use setObjectName() instead.
*/
QRadioButton::QRadioButton(QWidget *parent, const char* name)
: QAbstractButton(*new QRadioButtonPrivate, parent)
{
Q_D(QRadioButton);
d->init();
setObjectName(QString::fromAscii(name));
}
/*!
Use one of the constructors that doesn't take the \a name
argument and then use setObjectName() instead.
*/
QRadioButton::QRadioButton(const QString &text, QWidget *parent, const char* name)
: QAbstractButton(*new QRadioButtonPrivate, parent)
{
Q_D(QRadioButton);
d->init();
setObjectName(QString::fromAscii(name));
setText(text);
}
#endif
QT_END_NAMESPACE
| 30.694631 | 101 | 0.682738 | martende |
9ce5ba2980bfdd790af15c855244c8c74f6c7895 | 7,747 | cpp | C++ | src/engine/core/src/graphics/sprite/particles.cpp | code-disaster/halley | 5c85c889b76c69c6bdef6f4801c6aba282b7af80 | [
"Apache-2.0"
] | 3,262 | 2016-04-10T15:24:10.000Z | 2022-03-31T17:47:08.000Z | src/engine/core/src/graphics/sprite/particles.cpp | code-disaster/halley | 5c85c889b76c69c6bdef6f4801c6aba282b7af80 | [
"Apache-2.0"
] | 53 | 2016-10-09T16:25:04.000Z | 2022-01-10T13:52:37.000Z | src/engine/core/src/graphics/sprite/particles.cpp | code-disaster/halley | 5c85c889b76c69c6bdef6f4801c6aba282b7af80 | [
"Apache-2.0"
] | 193 | 2017-10-23T06:08:41.000Z | 2022-03-22T12:59:58.000Z | #include "graphics/sprite/particles.h"
#include "halley/maths/random.h"
#include "halley/support/logger.h"
using namespace Halley;
Particles::Particles()
: rng(&Random::getGlobal())
{
}
Particles::Particles(const ConfigNode& node, Resources& resources)
: rng(&Random::getGlobal())
{
spawnRate = node["spawnRate"].asFloat(100);
spawnArea = node["spawnArea"].asVector2f(Vector2f(0, 0));
ttl = node["ttl"].asFloat(1.0f);
ttlScatter = node["ttlScatter"].asFloat(0.0f);
speed = node["speed"].asFloat(100.0f);
speedScatter = node["speedScatter"].asFloat(0.0f);
speedDamp = node["speedDamp"].asFloat(0.0f);
acceleration = node["acceleration"].asVector2f(Vector2f());
angle = node["angle"].asFloat(0.0f);
angleScatter = node["angleScatter"].asFloat(0.0f);
startScale = node["startScale"].asFloat(1.0f);
endScale = node["endScale"].asFloat(1.0f);
fadeInTime = node["fadeInTime"].asFloat(0.0f);
fadeOutTime = node["fadeOutTime"].asFloat(0.0f);
stopTime = node["stopTime"].asFloat(0.0f);
directionScatter = node["directionScatter"].asFloat(0.0f);
rotateTowardsMovement = node["rotateTowardsMovement"].asBool(false);
destroyWhenDone = node["destroyWhenDone"].asBool(false);
if (node.hasKey("maxParticles")) {
maxParticles = node["maxParticles"].asInt();
}
if (node.hasKey("burst")) {
burst = node["burst"].asInt();
}
}
ConfigNode Particles::toConfigNode() const
{
ConfigNode::MapType result;
result["spawnRate"] = spawnRate;
result["spawnArea"] = spawnArea;
result["ttl"] = ttl;
result["ttlScatter"] = ttlScatter;
result["speed"] = speed;
result["speedScatter"] = speedScatter;
result["speedDamp"] = speedDamp;
result["acceleration"] = acceleration;
result["angle"] = angle;
result["angleScatter"] = angleScatter;
result["startScale"] = startScale;
result["endScale"] = endScale;
result["fadeInTime"] = fadeInTime;
result["fadeOutTime"] = fadeOutTime;
result["stopTime"] = stopTime;
result["directionScatter"] = directionScatter;
result["rotateTowardsMovement"] = rotateTowardsMovement;
result["destroyWhenDone"] = destroyWhenDone;
if (maxParticles) {
result["maxParticles"] = static_cast<int>(maxParticles.value());
}
if (burst) {
result["burst"] = static_cast<int>(burst.value());
}
return result;
}
void Particles::setEnabled(bool e)
{
enabled = e;
}
bool Particles::isEnabled() const
{
return enabled;
}
void Particles::setSpawnRateMultiplier(float value)
{
spawnRateMultiplier = value;
}
float Particles::getSpawnRateMultiplier() const
{
return spawnRateMultiplier;
}
void Particles::setPosition(Vector2f pos)
{
position = pos;
}
void Particles::setSpawnArea(Vector2f area)
{
spawnArea = area;
}
void Particles::setAngle(float newAngle)
{
angle = newAngle;
}
void Particles::start()
{
if (burst) {
spawn(burst.value());
}
}
void Particles::update(Time t)
{
if (firstUpdate) {
firstUpdate = false;
start();
}
pendingSpawn += static_cast<float>(t * spawnRate * (enabled && !burst ? spawnRateMultiplier : 0));
const int toSpawn = static_cast<int>(floor(pendingSpawn));
pendingSpawn = pendingSpawn - static_cast<float>(toSpawn);
// Spawn new particles
spawn(static_cast<size_t>(toSpawn));
// Update particles
updateParticles(static_cast<float>(t));
// Remove dead particles
for (size_t i = 0; i < nParticlesAlive; ) {
if (!particles[i].alive) {
if (i != nParticlesAlive - 1) {
// Swap with last particle that's alive
std::swap(particles[i], particles[nParticlesAlive - 1]);
std::swap(sprites[i], sprites[nParticlesAlive - 1]);
if (isAnimated()) {
std::swap(animationPlayers[i], animationPlayers[nParticlesAlive - 1]);
}
}
--nParticlesAlive;
// Don't increment i here, since i is now a new particle that's still alive
} else {
++i;
}
}
// Update visibility
nParticlesVisible = nParticlesAlive;
if (nParticlesVisible > 0 && !sprites[0].hasMaterial()) {
nParticlesVisible = 0;
}
}
void Particles::setSprites(std::vector<Sprite> sprites)
{
baseSprites = std::move(sprites);
}
void Particles::setAnimation(std::shared_ptr<const Animation> animation)
{
baseAnimation = std::move(animation);
}
bool Particles::isAnimated() const
{
return !!baseAnimation;
}
bool Particles::isAlive() const
{
return nParticlesAlive > 0 || !destroyWhenDone;
}
gsl::span<Sprite> Particles::getSprites()
{
return gsl::span<Sprite>(sprites).subspan(0, nParticlesVisible);
}
gsl::span<const Sprite> Particles::getSprites() const
{
return gsl::span<const Sprite>(sprites).subspan(0, nParticlesVisible);
}
void Particles::spawn(size_t n)
{
if (maxParticles) {
n = std::min(n, maxParticles.value() - nParticlesAlive);
}
const size_t start = nParticlesAlive;
nParticlesAlive += n;
const size_t size = std::max(size_t(8), nextPowerOf2(nParticlesAlive));
if (particles.size() < size) {
particles.resize(size);
sprites.resize(size);
if (isAnimated()) {
animationPlayers.resize(size, AnimationPlayerLite(baseAnimation));
}
}
for (size_t i = start; i < nParticlesAlive; ++i) {
initializeParticle(i);
}
}
void Particles::initializeParticle(size_t index)
{
const auto startDirection = Angle1f::fromDegrees(rng->getFloat(angle - angleScatter, angle + angleScatter));
auto& particle = particles[index];
particle.alive = true;
particle.time = 0;
particle.ttl = rng->getFloat(ttl - ttlScatter, ttl + ttlScatter);
particle.pos = getSpawnPosition();
particle.angle = rotateTowardsMovement ? startDirection : Angle1f();
particle.scale = startScale;
particle.vel = Vector2f(rng->getFloat(speed - speedScatter, speed + speedScatter), startDirection);
auto& sprite = sprites[index];
if (isAnimated()) {
auto& anim = animationPlayers[index];
anim.update(0, sprite);
} else if (!baseSprites.empty()) {
sprite = rng->getRandomElement(baseSprites);
}
}
void Particles::updateParticles(float time)
{
const bool hasAnim = isAnimated();
for (size_t i = 0; i < nParticlesAlive; ++i) {
if (hasAnim) {
animationPlayers[i].update(time, sprites[i]);
}
auto& particle = particles[i];
particle.time += time;
if (particle.time >= particle.ttl) {
particle.alive = false;
} else {
particle.vel += acceleration * time;
if (stopTime > 0.00001f && particle.time + stopTime >= particle.ttl) {
particle.vel = damp(particle.vel, Vector2f(), 10.0f, time);
}
if (speedDamp > 0.0001f) {
particle.vel = damp(particle.vel, Vector2f(), speedDamp, time);
}
if (directionScatter > 0.00001f) {
particle.vel = particle.vel.rotate(Angle1f::fromDegrees(rng->getFloat(-directionScatter * time, directionScatter * time)));
}
particle.pos += particle.vel * time;
if (rotateTowardsMovement && particle.vel.squaredLength() > 0.001f) {
particle.angle = particle.vel.angle();
}
particle.scale = lerp(startScale, endScale, particle.time / particle.ttl);
if (fadeInTime > 0.000001f || fadeOutTime > 0.00001f) {
const float alpha = clamp(std::min(particle.time / fadeInTime, (particle.ttl - particle.time) / fadeOutTime), 0.0f, 1.0f);
sprites[i].getColour().a = alpha;
}
sprites[i]
.setPosition(particle.pos)
.setRotation(particle.angle)
.setScale(particle.scale);
}
}
}
Vector2f Particles::getSpawnPosition() const
{
return position + Vector2f(rng->getFloat(-spawnArea.x * 0.5f, spawnArea.x * 0.5f), rng->getFloat(-spawnArea.y * 0.5f, spawnArea.y * 0.5f));
}
ConfigNode ConfigNodeSerializer<Particles>::serialize(const Particles& particles, const ConfigNodeSerializationContext& context)
{
return particles.toConfigNode();
}
Particles ConfigNodeSerializer<Particles>::deserialize(const ConfigNodeSerializationContext& context, const ConfigNode& node)
{
return Particles(node, *context.resources);
}
| 25.909699 | 140 | 0.702595 | code-disaster |
9ce7ea7fb4855c7e3170a351895aa88d36813e37 | 10,616 | cpp | C++ | src/objects/smoke/SmokeIcon-gen.cpp | steptosky/3DsMax-X-Obj-Exporter | c70f5a60056ee71aba1569f1189c38b9e01d2f0e | [
"BSD-3-Clause"
] | 20 | 2017-07-07T06:07:30.000Z | 2022-03-09T12:00:57.000Z | src/objects/smoke/SmokeIcon-gen.cpp | steptosky/3DsMax-X-Obj-Exporter | c70f5a60056ee71aba1569f1189c38b9e01d2f0e | [
"BSD-3-Clause"
] | 28 | 2017-07-07T06:08:27.000Z | 2022-03-09T12:09:23.000Z | src/objects/smoke/SmokeIcon-gen.cpp | steptosky/3DsMax-X-Obj-Exporter | c70f5a60056ee71aba1569f1189c38b9e01d2f0e | [
"BSD-3-Clause"
] | 7 | 2018-01-24T19:43:22.000Z | 2020-01-06T00:05:40.000Z | #include "SmokeIcon-gen.h"
#pragma warning(push, 0)
#include <max.h>
#pragma warning(pop)
/* Auto-generated file */
void SmokeIcon::fillMesh(Mesh & outMesh, const float scale) {
outMesh.setNumVerts(48);
outMesh.setNumFaces(42);
outMesh.verts[0].x = scale * 0.500000f;
outMesh.verts[0].y = scale * 0.000000f;
outMesh.verts[0].z = scale * 0.000000f;
outMesh.verts[1].x = scale * 0.460672f;
outMesh.verts[1].y = scale * 0.194517f;
outMesh.verts[1].z = scale * 0.000000f;
outMesh.verts[2].x = scale * 0.353460f;
outMesh.verts[2].y = scale * 0.353460f;
outMesh.verts[2].z = scale * 0.000000f;
outMesh.verts[3].x = scale * 0.194517f;
outMesh.verts[3].y = scale * 0.460672f;
outMesh.verts[3].z = scale * 0.000000f;
outMesh.verts[4].x = scale * -0.000000f;
outMesh.verts[4].y = scale * 0.500000f;
outMesh.verts[4].z = scale * 0.000000f;
outMesh.verts[5].x = scale * -0.194517f;
outMesh.verts[5].y = scale * 0.460672f;
outMesh.verts[5].z = scale * 0.000000f;
outMesh.verts[6].x = scale * -0.353460f;
outMesh.verts[6].y = scale * 0.353460f;
outMesh.verts[6].z = scale * 0.000000f;
outMesh.verts[7].x = scale * -0.460672f;
outMesh.verts[7].y = scale * 0.194517f;
outMesh.verts[7].z = scale * 0.000000f;
outMesh.verts[8].x = scale * -0.500000f;
outMesh.verts[8].y = scale * -0.000000f;
outMesh.verts[8].z = scale * 0.000000f;
outMesh.verts[9].x = scale * -0.460672f;
outMesh.verts[9].y = scale * -0.194517f;
outMesh.verts[9].z = scale * 0.000000f;
outMesh.verts[10].x = scale * -0.353460f;
outMesh.verts[10].y = scale * -0.353460f;
outMesh.verts[10].z = scale * 0.000000f;
outMesh.verts[11].x = scale * -0.194517f;
outMesh.verts[11].y = scale * -0.460672f;
outMesh.verts[11].z = scale * 0.000000f;
outMesh.verts[12].x = scale * 0.000000f;
outMesh.verts[12].y = scale * -0.500000f;
outMesh.verts[12].z = scale * 0.000000f;
outMesh.verts[13].x = scale * 0.194517f;
outMesh.verts[13].y = scale * -0.460672f;
outMesh.verts[13].z = scale * 0.000000f;
outMesh.verts[14].x = scale * 0.353460f;
outMesh.verts[14].y = scale * -0.353460f;
outMesh.verts[14].z = scale * 0.000000f;
outMesh.verts[15].x = scale * 0.460672f;
outMesh.verts[15].y = scale * -0.194517f;
outMesh.verts[15].z = scale * 0.000000f;
outMesh.verts[16].x = scale * 0.500000f;
outMesh.verts[16].y = scale * 0.000000f;
outMesh.verts[16].z = scale * 0.000000f;
outMesh.verts[17].x = scale * 0.460672f;
outMesh.verts[17].y = scale * -0.000000f;
outMesh.verts[17].z = scale * 0.194517f;
outMesh.verts[18].x = scale * 0.353460f;
outMesh.verts[18].y = scale * -0.000000f;
outMesh.verts[18].z = scale * 0.353460f;
outMesh.verts[19].x = scale * 0.194517f;
outMesh.verts[19].y = scale * -0.000000f;
outMesh.verts[19].z = scale * 0.460672f;
outMesh.verts[20].x = scale * -0.000000f;
outMesh.verts[20].y = scale * -0.000000f;
outMesh.verts[20].z = scale * 0.500000f;
outMesh.verts[21].x = scale * -0.194517f;
outMesh.verts[21].y = scale * -0.000000f;
outMesh.verts[21].z = scale * 0.460672f;
outMesh.verts[22].x = scale * -0.353460f;
outMesh.verts[22].y = scale * -0.000000f;
outMesh.verts[22].z = scale * 0.353460f;
outMesh.verts[23].x = scale * -0.460672f;
outMesh.verts[23].y = scale * -0.000000f;
outMesh.verts[23].z = scale * 0.194517f;
outMesh.verts[24].x = scale * -0.500000f;
outMesh.verts[24].y = scale * 0.000000f;
outMesh.verts[24].z = scale * -0.000000f;
outMesh.verts[25].x = scale * -0.460672f;
outMesh.verts[25].y = scale * 0.000000f;
outMesh.verts[25].z = scale * -0.194517f;
outMesh.verts[26].x = scale * -0.353460f;
outMesh.verts[26].y = scale * 0.000000f;
outMesh.verts[26].z = scale * -0.353460f;
outMesh.verts[27].x = scale * -0.194517f;
outMesh.verts[27].y = scale * 0.000000f;
outMesh.verts[27].z = scale * -0.460672f;
outMesh.verts[28].x = scale * 0.000000f;
outMesh.verts[28].y = scale * 0.000000f;
outMesh.verts[28].z = scale * -0.500000f;
outMesh.verts[29].x = scale * 0.194517f;
outMesh.verts[29].y = scale * 0.000000f;
outMesh.verts[29].z = scale * -0.460672f;
outMesh.verts[30].x = scale * 0.353460f;
outMesh.verts[30].y = scale * 0.000000f;
outMesh.verts[30].z = scale * -0.353460f;
outMesh.verts[31].x = scale * 0.460672f;
outMesh.verts[31].y = scale * 0.000000f;
outMesh.verts[31].z = scale * -0.194517f;
outMesh.verts[32].x = scale * -0.000000f;
outMesh.verts[32].y = scale * -0.500000f;
outMesh.verts[32].z = scale * 0.000000f;
outMesh.verts[33].x = scale * -0.000000f;
outMesh.verts[33].y = scale * -0.460672f;
outMesh.verts[33].z = scale * 0.194517f;
outMesh.verts[34].x = scale * -0.000000f;
outMesh.verts[34].y = scale * -0.353460f;
outMesh.verts[34].z = scale * 0.353460f;
outMesh.verts[35].x = scale * -0.000000f;
outMesh.verts[35].y = scale * -0.194517f;
outMesh.verts[35].z = scale * 0.460672f;
outMesh.verts[36].x = scale * -0.000000f;
outMesh.verts[36].y = scale * 0.000000f;
outMesh.verts[36].z = scale * 0.500000f;
outMesh.verts[37].x = scale * -0.000000f;
outMesh.verts[37].y = scale * 0.194517f;
outMesh.verts[37].z = scale * 0.460672f;
outMesh.verts[38].x = scale * 0.000000f;
outMesh.verts[38].y = scale * 0.353460f;
outMesh.verts[38].z = scale * 0.353460f;
outMesh.verts[39].x = scale * 0.000000f;
outMesh.verts[39].y = scale * 0.460672f;
outMesh.verts[39].z = scale * 0.194517f;
outMesh.verts[40].x = scale * 0.000000f;
outMesh.verts[40].y = scale * 0.500000f;
outMesh.verts[40].z = scale * -0.000000f;
outMesh.verts[41].x = scale * 0.000000f;
outMesh.verts[41].y = scale * 0.460672f;
outMesh.verts[41].z = scale * -0.194517f;
outMesh.verts[42].x = scale * 0.000000f;
outMesh.verts[42].y = scale * 0.353460f;
outMesh.verts[42].z = scale * -0.353460f;
outMesh.verts[43].x = scale * 0.000000f;
outMesh.verts[43].y = scale * 0.194517f;
outMesh.verts[43].z = scale * -0.460672f;
outMesh.verts[44].x = scale * 0.000000f;
outMesh.verts[44].y = scale * -0.000000f;
outMesh.verts[44].z = scale * -0.500000f;
outMesh.verts[45].x = scale * 0.000000f;
outMesh.verts[45].y = scale * -0.194517f;
outMesh.verts[45].z = scale * -0.460672f;
outMesh.verts[46].x = scale * 0.000000f;
outMesh.verts[46].y = scale * -0.353460f;
outMesh.verts[46].z = scale * -0.353460f;
outMesh.verts[47].x = scale * -0.000000f;
outMesh.verts[47].y = scale * -0.460672f;
outMesh.verts[47].z = scale * -0.194517f;
outMesh.faces[0].setVerts(11, 12, 13);
outMesh.faces[0].setEdgeVisFlags(1, 2, 0);
outMesh.faces[1].setVerts(11, 13, 14);
outMesh.faces[1].setEdgeVisFlags(0, 2, 0);
outMesh.faces[2].setVerts(10, 11, 14);
outMesh.faces[2].setEdgeVisFlags(1, 0, 0);
outMesh.faces[3].setVerts(10, 14, 15);
outMesh.faces[3].setEdgeVisFlags(0, 2, 0);
outMesh.faces[4].setVerts(10, 15, 0);
outMesh.faces[4].setEdgeVisFlags(0, 2, 0);
outMesh.faces[5].setVerts(10, 0, 1);
outMesh.faces[5].setEdgeVisFlags(0, 2, 0);
outMesh.faces[6].setVerts(10, 1, 2);
outMesh.faces[6].setEdgeVisFlags(0, 2, 0);
outMesh.faces[7].setVerts(10, 2, 3);
outMesh.faces[7].setEdgeVisFlags(0, 2, 0);
outMesh.faces[8].setVerts(10, 3, 4);
outMesh.faces[8].setEdgeVisFlags(0, 2, 0);
outMesh.faces[9].setVerts(10, 4, 5);
outMesh.faces[9].setEdgeVisFlags(0, 2, 0);
outMesh.faces[10].setVerts(10, 5, 6);
outMesh.faces[10].setEdgeVisFlags(0, 2, 0);
outMesh.faces[11].setVerts(10, 6, 7);
outMesh.faces[11].setEdgeVisFlags(0, 2, 0);
outMesh.faces[12].setVerts(10, 7, 8);
outMesh.faces[12].setEdgeVisFlags(0, 2, 0);
outMesh.faces[13].setVerts(10, 8, 9);
outMesh.faces[13].setEdgeVisFlags(0, 2, 4);
outMesh.faces[14].setVerts(27, 28, 29);
outMesh.faces[14].setEdgeVisFlags(1, 2, 0);
outMesh.faces[15].setVerts(27, 29, 30);
outMesh.faces[15].setEdgeVisFlags(0, 2, 0);
outMesh.faces[16].setVerts(26, 27, 30);
outMesh.faces[16].setEdgeVisFlags(1, 0, 0);
outMesh.faces[17].setVerts(26, 30, 31);
outMesh.faces[17].setEdgeVisFlags(0, 2, 0);
outMesh.faces[18].setVerts(26, 31, 16);
outMesh.faces[18].setEdgeVisFlags(0, 2, 0);
outMesh.faces[19].setVerts(26, 16, 17);
outMesh.faces[19].setEdgeVisFlags(0, 2, 0);
outMesh.faces[20].setVerts(26, 17, 18);
outMesh.faces[20].setEdgeVisFlags(0, 2, 0);
outMesh.faces[21].setVerts(26, 18, 19);
outMesh.faces[21].setEdgeVisFlags(0, 2, 0);
outMesh.faces[22].setVerts(26, 19, 20);
outMesh.faces[22].setEdgeVisFlags(0, 2, 0);
outMesh.faces[23].setVerts(26, 20, 21);
outMesh.faces[23].setEdgeVisFlags(0, 2, 0);
outMesh.faces[24].setVerts(26, 21, 22);
outMesh.faces[24].setEdgeVisFlags(0, 2, 0);
outMesh.faces[25].setVerts(26, 22, 23);
outMesh.faces[25].setEdgeVisFlags(0, 2, 0);
outMesh.faces[26].setVerts(26, 23, 24);
outMesh.faces[26].setEdgeVisFlags(0, 2, 0);
outMesh.faces[27].setVerts(26, 24, 25);
outMesh.faces[27].setEdgeVisFlags(0, 2, 4);
outMesh.faces[28].setVerts(43, 44, 45);
outMesh.faces[28].setEdgeVisFlags(1, 2, 0);
outMesh.faces[29].setVerts(43, 45, 46);
outMesh.faces[29].setEdgeVisFlags(0, 2, 0);
outMesh.faces[30].setVerts(42, 43, 46);
outMesh.faces[30].setEdgeVisFlags(1, 0, 0);
outMesh.faces[31].setVerts(42, 46, 47);
outMesh.faces[31].setEdgeVisFlags(0, 2, 0);
outMesh.faces[32].setVerts(42, 47, 32);
outMesh.faces[32].setEdgeVisFlags(0, 2, 0);
outMesh.faces[33].setVerts(42, 32, 33);
outMesh.faces[33].setEdgeVisFlags(0, 2, 0);
outMesh.faces[34].setVerts(42, 33, 34);
outMesh.faces[34].setEdgeVisFlags(0, 2, 0);
outMesh.faces[35].setVerts(42, 34, 35);
outMesh.faces[35].setEdgeVisFlags(0, 2, 0);
outMesh.faces[36].setVerts(42, 35, 36);
outMesh.faces[36].setEdgeVisFlags(0, 2, 0);
outMesh.faces[37].setVerts(42, 36, 37);
outMesh.faces[37].setEdgeVisFlags(0, 2, 0);
outMesh.faces[38].setVerts(42, 37, 38);
outMesh.faces[38].setEdgeVisFlags(0, 2, 0);
outMesh.faces[39].setVerts(42, 38, 39);
outMesh.faces[39].setEdgeVisFlags(0, 2, 0);
outMesh.faces[40].setVerts(42, 39, 40);
outMesh.faces[40].setEdgeVisFlags(0, 2, 0);
outMesh.faces[41].setVerts(42, 40, 41);
outMesh.faces[41].setEdgeVisFlags(0, 2, 4);
outMesh.InvalidateGeomCache();
}
| 43.330612 | 61 | 0.62905 | steptosky |
9ce801751ff185cf1c4837105a9b4cdeb1187ecc | 6,460 | cpp | C++ | Tests/LibC/strlcpy-correctness.cpp | shubhdev/serenity | 9321d9d83d366ad4cf686c856063ff9ac97c18a4 | [
"BSD-2-Clause"
] | 4 | 2021-02-23T05:35:25.000Z | 2021-06-08T06:11:06.000Z | Tests/LibC/strlcpy-correctness.cpp | shubhdev/serenity | 9321d9d83d366ad4cf686c856063ff9ac97c18a4 | [
"BSD-2-Clause"
] | 4 | 2021-04-27T20:44:44.000Z | 2021-06-30T18:07:10.000Z | Tests/LibC/strlcpy-correctness.cpp | shubhdev/serenity | 9321d9d83d366ad4cf686c856063ff9ac97c18a4 | [
"BSD-2-Clause"
] | 1 | 2022-01-10T08:02:34.000Z | 2022-01-10T08:02:34.000Z | /*
* Copyright (c) 2020, Ben Wiederhake <BenWiederhake.GitHub@gmx.de>
*
* SPDX-License-Identifier: BSD-2-Clause
*/
#include <LibTest/TestCase.h>
#include <AK/ByteBuffer.h>
#include <AK/Random.h>
#include <AK/StringBuilder.h>
#include <ctype.h>
#include <stdio.h>
#include <string.h>
struct Testcase {
const char* dest;
size_t dest_n;
const char* src;
size_t src_n;
const char* dest_expected;
size_t dest_expected_n; // == dest_n
};
static String show(const ByteBuffer& buf)
{
StringBuilder builder;
for (size_t i = 0; i < buf.size(); ++i) {
builder.appendff("{:02x}", buf[i]);
}
builder.append(' ');
builder.append('(');
for (size_t i = 0; i < buf.size(); ++i) {
if (isprint(buf[i]))
builder.append(buf[i]);
else
builder.append('_');
}
builder.append(')');
return builder.build();
}
static bool test_single(const Testcase& testcase)
{
constexpr size_t SANDBOX_CANARY_SIZE = 8;
// Preconditions:
if (testcase.dest_n != testcase.dest_expected_n) {
warnln("dest length {} != expected dest length {}? Check testcase! (Probably miscounted.)", testcase.dest_n, testcase.dest_expected_n);
return false;
}
if (testcase.src_n != strlen(testcase.src)) {
warnln("src length {} != actual src length {}? src can't contain NUL bytes!", testcase.src_n, strlen(testcase.src));
return false;
}
// Setup
ByteBuffer actual = ByteBuffer::create_uninitialized(SANDBOX_CANARY_SIZE + testcase.dest_n + SANDBOX_CANARY_SIZE);
fill_with_random(actual.data(), actual.size());
ByteBuffer expected = actual;
VERIFY(actual.offset_pointer(0) != expected.offset_pointer(0));
actual.overwrite(SANDBOX_CANARY_SIZE, testcase.dest, testcase.dest_n);
expected.overwrite(SANDBOX_CANARY_SIZE, testcase.dest_expected, testcase.dest_expected_n);
// "unsigned char" != "char", so we have to convince the compiler to allow this.
char* dst = reinterpret_cast<char*>(actual.offset_pointer(SANDBOX_CANARY_SIZE));
// The actual call:
size_t actual_return = strlcpy(dst, testcase.src, testcase.dest_n);
// Checking the results:
bool return_ok = actual_return == testcase.src_n;
bool canary_1_ok = actual.slice(0, SANDBOX_CANARY_SIZE) == expected.slice(0, SANDBOX_CANARY_SIZE);
bool main_ok = actual.slice(SANDBOX_CANARY_SIZE, testcase.dest_n) == expected.slice(SANDBOX_CANARY_SIZE, testcase.dest_n);
bool canary_2_ok = actual.slice(SANDBOX_CANARY_SIZE + testcase.dest_n, SANDBOX_CANARY_SIZE) == expected.slice(SANDBOX_CANARY_SIZE + testcase.dest_n, SANDBOX_CANARY_SIZE);
bool buf_ok = actual == expected;
// Evaluate gravity:
if (buf_ok && (!canary_1_ok || !main_ok || !canary_2_ok)) {
warnln("Internal error! ({} != {} | {} | {})", buf_ok, canary_1_ok, main_ok, canary_2_ok);
buf_ok = false;
}
if (!canary_1_ok) {
warnln("Canary 1 overwritten: Expected canary {}\n"
" instead got {}",
show(expected.slice(0, SANDBOX_CANARY_SIZE)),
show(actual.slice(0, SANDBOX_CANARY_SIZE)));
}
if (!main_ok) {
warnln("Wrong output: Expected {}\n"
" instead got {}",
show(expected.slice(SANDBOX_CANARY_SIZE, testcase.dest_n)),
show(actual.slice(SANDBOX_CANARY_SIZE, testcase.dest_n)));
}
if (!canary_2_ok) {
warnln("Canary 2 overwritten: Expected {}\n"
" instead got {}",
show(expected.slice(SANDBOX_CANARY_SIZE + testcase.dest_n, SANDBOX_CANARY_SIZE)),
show(actual.slice(SANDBOX_CANARY_SIZE + testcase.dest_n, SANDBOX_CANARY_SIZE)));
}
if (!return_ok) {
warnln("Wrong return value: Expected {}, got {} instead!", testcase.src_n, actual_return);
}
return buf_ok && return_ok;
}
// Drop the NUL terminator added by the C++ compiler.
#define LITERAL(x) x, (sizeof(x) - 1)
//static Testcase TESTCASES[] = {
// // Golden path:
// // Hitting the border:
// // Too long:
// { LITERAL("Hello World!\0"), LITERAL("Hello Friend!"), LITERAL("Hello Friend\0") },
// { LITERAL("Hello World!\0"), LITERAL("This source is just *way* too long!"), LITERAL("This source \0") },
// { LITERAL("x"), LITERAL("This source is just *way* too long!"), LITERAL("\0") },
// // Other special cases:
// { LITERAL(""), LITERAL(""), LITERAL("") },
// { LITERAL(""), LITERAL("Empty test"), LITERAL("") },
// { LITERAL("x"), LITERAL(""), LITERAL("\0") },
// { LITERAL("xx"), LITERAL(""), LITERAL("\0x") },
// { LITERAL("xxx"), LITERAL(""), LITERAL("\0xx") },
//};
TEST_CASE(golden_path)
{
EXPECT(test_single({ LITERAL("Hello World!\0\0\0"), LITERAL("Hello Friend!"), LITERAL("Hello Friend!\0\0") }));
EXPECT(test_single({ LITERAL("Hello World!\0\0\0"), LITERAL("Hello Friend!"), LITERAL("Hello Friend!\0\0") }));
EXPECT(test_single({ LITERAL("aaaaaaaaaa"), LITERAL("whf"), LITERAL("whf\0aaaaaa") }));
}
TEST_CASE(exact_fit)
{
EXPECT(test_single({ LITERAL("Hello World!\0\0"), LITERAL("Hello Friend!"), LITERAL("Hello Friend!\0") }));
EXPECT(test_single({ LITERAL("AAAA"), LITERAL("aaa"), LITERAL("aaa\0") }));
}
TEST_CASE(off_by_one)
{
EXPECT(test_single({ LITERAL("AAAAAAAAAA"), LITERAL("BBBBB"), LITERAL("BBBBB\0AAAA") }));
EXPECT(test_single({ LITERAL("AAAAAAAAAA"), LITERAL("BBBBBBBCC"), LITERAL("BBBBBBBCC\0") }));
EXPECT(test_single({ LITERAL("AAAAAAAAAA"), LITERAL("BBBBBBBCCX"), LITERAL("BBBBBBBCC\0") }));
EXPECT(test_single({ LITERAL("AAAAAAAAAA"), LITERAL("BBBBBBBCCXY"), LITERAL("BBBBBBBCC\0") }));
}
TEST_CASE(nearly_empty)
{
EXPECT(test_single({ LITERAL(""), LITERAL(""), LITERAL("") }));
EXPECT(test_single({ LITERAL(""), LITERAL("Empty test"), LITERAL("") }));
EXPECT(test_single({ LITERAL("x"), LITERAL(""), LITERAL("\0") }));
EXPECT(test_single({ LITERAL("xx"), LITERAL(""), LITERAL("\0x") }));
EXPECT(test_single({ LITERAL("x"), LITERAL("y"), LITERAL("\0") }));
}
static char* const POISON = (char*)1;
TEST_CASE(to_nullptr)
{
EXPECT_EQ(0u, strlcpy(POISON, "", 0));
EXPECT_EQ(1u, strlcpy(POISON, "x", 0));
EXPECT(test_single({ LITERAL("Hello World!\0\0\0"), LITERAL("Hello Friend!"), LITERAL("Hello Friend!\0\0") }));
EXPECT(test_single({ LITERAL("aaaaaaaaaa"), LITERAL("whf"), LITERAL("whf\0aaaaaa") }));
}
| 39.151515 | 174 | 0.632353 | shubhdev |
9ce809c9485d906290ddf8e8833099a7a8f05573 | 2,623 | cpp | C++ | bootloader/bootloader32/src/RealMode.cpp | Rzuwik/FunnyOS | a93a45babf575d08cf2704a8394ac1455f3ad4db | [
"MIT"
] | null | null | null | bootloader/bootloader32/src/RealMode.cpp | Rzuwik/FunnyOS | a93a45babf575d08cf2704a8394ac1455f3ad4db | [
"MIT"
] | null | null | null | bootloader/bootloader32/src/RealMode.cpp | Rzuwik/FunnyOS | a93a45babf575d08cf2704a8394ac1455f3ad4db | [
"MIT"
] | null | null | null | #include "RealMode.hpp"
#include <FunnyOS/Hardware/Interrupts.hpp>
// Defined in real_mode.asm
extern FunnyOS::Bootloader32::Registers32 g_savedRegisters;
extern uint8_t g_realBuffer;
extern uint8_t g_realBufferTop;
F_CDECL extern void do_real_mode_interrupt();
namespace FunnyOS::Bootloader32 {
using namespace Stdlib;
constexpr static uint32_t MAX_REAL_MODE_ADDR = 0xFFFF * 16 + 0xFFFF;
Memory::SizedBuffer<uint8_t>& GetRealModeBuffer() {
static Memory::SizedBuffer<uint8_t> c_realModeBuffer{
&g_realBuffer, reinterpret_cast<size_t>(&g_realBufferTop) - reinterpret_cast<size_t>(&g_realBuffer)};
return c_realModeBuffer;
}
void GetRealModeAddress(void* address, uint16_t& segment, uint16_t& offset) {
GetRealModeAddress(reinterpret_cast<uint32_t>(address), segment, offset);
}
void GetRealModeAddress(uint32_t address, uint16_t& segment, uint16_t& offset) {
F_ASSERT(address < MAX_REAL_MODE_ADDR, "address >= MAX_REAL_MODE_ADDR");
segment = static_cast<uint16_t>((address & 0xF0000) >> 4);
offset = static_cast<uint16_t>(address & 0xFFFF);
}
void GetRealModeBufferAddress(uint16_t& segment, uint16_t& offset) {
auto address = reinterpret_cast<uintptr_t>(GetRealModeBuffer().Data);
GetRealModeAddress(address, segment, offset);
}
void RealModeInt(uint8_t interrupt, Registers32& registers) {
HW::NoInterruptsBlock noInterrupts;
Memory::Copy(static_cast<void*>(&g_savedRegisters), static_cast<void*>(®isters), sizeof(Registers32));
#ifdef __GNUC__
asm(
// Save state
"pushfl \n"
"pushal \n"
"pushw %%es \n"
"pushw %%fs \n"
"pushw %%gs \n"
// Push interrupt number and call do_real_mode_interrupt
"pushl %[int_number] \n"
"call do_real_mode_interrupt \n"
"add $4, %%esp \n"
// Restore state
"popw %%gs \n"
"popw %%fs \n"
"popw %%es \n"
"popal \n"
"popfl \n"
:
: [ int_number ] "a"(static_cast<uintmax_t>(interrupt))
: "memory");
#endif
Memory::Copy(static_cast<void*>(®isters), static_cast<void*>(&g_savedRegisters), sizeof(Registers32));
}
} // namespace FunnyOS::Bootloader32 | 36.430556 | 113 | 0.581014 | Rzuwik |
9ce835cce2288e438bee59f8376b8331e6e442ab | 831 | hpp | C++ | libs/core/include/fcppt/string_literal.hpp | pmiddend/fcppt | 9f437acbb10258e6df6982a550213a05815eb2be | [
"BSL-1.0"
] | null | null | null | libs/core/include/fcppt/string_literal.hpp | pmiddend/fcppt | 9f437acbb10258e6df6982a550213a05815eb2be | [
"BSL-1.0"
] | null | null | null | libs/core/include/fcppt/string_literal.hpp | pmiddend/fcppt | 9f437acbb10258e6df6982a550213a05815eb2be | [
"BSL-1.0"
] | null | null | null | // Copyright Carl Philipp Reh 2009 - 2018.
// Distributed under the Boost Software License, Version 1.0.
// (See accompanying file LICENSE_1_0.txt or copy at
// http://www.boost.org/LICENSE_1_0.txt)
#ifndef FCPPT_STRING_LITERAL_HPP_INCLUDED
#define FCPPT_STRING_LITERAL_HPP_INCLUDED
#include <fcppt/detail/string_literal.hpp>
/**
\brief A char or wchar_t string literal depending on a type.
\ingroup fcpptvarious
If \a _type is char, then the literal will be of type <code>char const *</code>.
If \a _type is wchar_t, then the literal will be of type <code>wchar_t const *</code>.
\param _type Must be char or wchar_t.
\param _literal Must be a string literal.
*/
#define FCPPT_STRING_LITERAL(\
_type,\
_literal\
)\
fcppt::detail::string_literal<\
_type\
>(\
_literal, \
L ## _literal \
)
#endif
| 23.083333 | 86 | 0.724428 | pmiddend |
9ce97fa30f1816d72221b1abc841dfdf364782c0 | 630 | hpp | C++ | engine/Component.hpp | shenchi/gllab | 5d8fe33cd763d5fe5033da106b715751ae2e87ef | [
"MIT"
] | null | null | null | engine/Component.hpp | shenchi/gllab | 5d8fe33cd763d5fe5033da106b715751ae2e87ef | [
"MIT"
] | null | null | null | engine/Component.hpp | shenchi/gllab | 5d8fe33cd763d5fe5033da106b715751ae2e87ef | [
"MIT"
] | null | null | null | #ifndef COMPONENT_H
#define COMPONENT_H
#include "Object.hpp"
class SceneObject;
class Component : public Object
{
public:
enum Type
{
TYPE_UNKNOWN = -1,
TYPE_MESHFILTER,
TYPE_MESHRENDERER,
};
public:
Component( int type ) : m_enabled( true ), m_type( type ), m_owner( 0 ) {}
virtual ~Component() {}
int getType() const { return m_type; }
SceneObject* getOwner() { return m_owner; }
void setOwner( SceneObject* owner ) { m_owner = owner; }
virtual bool onAddToOwner( SceneObject* owner ) { return true; }
protected:
bool m_enabled;
int m_type;
SceneObject* m_owner;
};
#endif // COMPONENT_H | 16.578947 | 75 | 0.687302 | shenchi |
9cea5ca39c94fb894f7d3142ad95c0b527c50fdc | 6,890 | cpp | C++ | waf/src/v20180125/model/CreateAttackDownloadTaskRequest.cpp | suluner/tencentcloud-sdk-cpp | a56c73cc3f488c4d1e10755704107bb15c5e000d | [
"Apache-2.0"
] | 43 | 2019-08-14T08:14:12.000Z | 2022-03-30T12:35:09.000Z | waf/src/v20180125/model/CreateAttackDownloadTaskRequest.cpp | suluner/tencentcloud-sdk-cpp | a56c73cc3f488c4d1e10755704107bb15c5e000d | [
"Apache-2.0"
] | 12 | 2019-07-15T10:44:59.000Z | 2021-11-02T12:35:00.000Z | waf/src/v20180125/model/CreateAttackDownloadTaskRequest.cpp | suluner/tencentcloud-sdk-cpp | a56c73cc3f488c4d1e10755704107bb15c5e000d | [
"Apache-2.0"
] | 28 | 2019-07-12T09:06:22.000Z | 2022-03-30T08:04:18.000Z | /*
* Copyright (c) 2017-2019 THL A29 Limited, a Tencent company. 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 <tencentcloud/waf/v20180125/model/CreateAttackDownloadTaskRequest.h>
#include <tencentcloud/core/utils/rapidjson/document.h>
#include <tencentcloud/core/utils/rapidjson/writer.h>
#include <tencentcloud/core/utils/rapidjson/stringbuffer.h>
using namespace TencentCloud::Waf::V20180125::Model;
using namespace std;
CreateAttackDownloadTaskRequest::CreateAttackDownloadTaskRequest() :
m_domainHasBeenSet(false),
m_fromTimeHasBeenSet(false),
m_toTimeHasBeenSet(false),
m_nameHasBeenSet(false),
m_riskLevelHasBeenSet(false),
m_statusHasBeenSet(false),
m_ruleIdHasBeenSet(false),
m_attackIpHasBeenSet(false),
m_attackTypeHasBeenSet(false)
{
}
string CreateAttackDownloadTaskRequest::ToJsonString() const
{
rapidjson::Document d;
d.SetObject();
rapidjson::Document::AllocatorType& allocator = d.GetAllocator();
if (m_domainHasBeenSet)
{
rapidjson::Value iKey(rapidjson::kStringType);
string key = "Domain";
iKey.SetString(key.c_str(), allocator);
d.AddMember(iKey, rapidjson::Value(m_domain.c_str(), allocator).Move(), allocator);
}
if (m_fromTimeHasBeenSet)
{
rapidjson::Value iKey(rapidjson::kStringType);
string key = "FromTime";
iKey.SetString(key.c_str(), allocator);
d.AddMember(iKey, rapidjson::Value(m_fromTime.c_str(), allocator).Move(), allocator);
}
if (m_toTimeHasBeenSet)
{
rapidjson::Value iKey(rapidjson::kStringType);
string key = "ToTime";
iKey.SetString(key.c_str(), allocator);
d.AddMember(iKey, rapidjson::Value(m_toTime.c_str(), allocator).Move(), allocator);
}
if (m_nameHasBeenSet)
{
rapidjson::Value iKey(rapidjson::kStringType);
string key = "Name";
iKey.SetString(key.c_str(), allocator);
d.AddMember(iKey, rapidjson::Value(m_name.c_str(), allocator).Move(), allocator);
}
if (m_riskLevelHasBeenSet)
{
rapidjson::Value iKey(rapidjson::kStringType);
string key = "RiskLevel";
iKey.SetString(key.c_str(), allocator);
d.AddMember(iKey, m_riskLevel, allocator);
}
if (m_statusHasBeenSet)
{
rapidjson::Value iKey(rapidjson::kStringType);
string key = "Status";
iKey.SetString(key.c_str(), allocator);
d.AddMember(iKey, m_status, allocator);
}
if (m_ruleIdHasBeenSet)
{
rapidjson::Value iKey(rapidjson::kStringType);
string key = "RuleId";
iKey.SetString(key.c_str(), allocator);
d.AddMember(iKey, m_ruleId, allocator);
}
if (m_attackIpHasBeenSet)
{
rapidjson::Value iKey(rapidjson::kStringType);
string key = "AttackIp";
iKey.SetString(key.c_str(), allocator);
d.AddMember(iKey, rapidjson::Value(m_attackIp.c_str(), allocator).Move(), allocator);
}
if (m_attackTypeHasBeenSet)
{
rapidjson::Value iKey(rapidjson::kStringType);
string key = "AttackType";
iKey.SetString(key.c_str(), allocator);
d.AddMember(iKey, rapidjson::Value(m_attackType.c_str(), allocator).Move(), allocator);
}
rapidjson::StringBuffer buffer;
rapidjson::Writer<rapidjson::StringBuffer> writer(buffer);
d.Accept(writer);
return buffer.GetString();
}
string CreateAttackDownloadTaskRequest::GetDomain() const
{
return m_domain;
}
void CreateAttackDownloadTaskRequest::SetDomain(const string& _domain)
{
m_domain = _domain;
m_domainHasBeenSet = true;
}
bool CreateAttackDownloadTaskRequest::DomainHasBeenSet() const
{
return m_domainHasBeenSet;
}
string CreateAttackDownloadTaskRequest::GetFromTime() const
{
return m_fromTime;
}
void CreateAttackDownloadTaskRequest::SetFromTime(const string& _fromTime)
{
m_fromTime = _fromTime;
m_fromTimeHasBeenSet = true;
}
bool CreateAttackDownloadTaskRequest::FromTimeHasBeenSet() const
{
return m_fromTimeHasBeenSet;
}
string CreateAttackDownloadTaskRequest::GetToTime() const
{
return m_toTime;
}
void CreateAttackDownloadTaskRequest::SetToTime(const string& _toTime)
{
m_toTime = _toTime;
m_toTimeHasBeenSet = true;
}
bool CreateAttackDownloadTaskRequest::ToTimeHasBeenSet() const
{
return m_toTimeHasBeenSet;
}
string CreateAttackDownloadTaskRequest::GetName() const
{
return m_name;
}
void CreateAttackDownloadTaskRequest::SetName(const string& _name)
{
m_name = _name;
m_nameHasBeenSet = true;
}
bool CreateAttackDownloadTaskRequest::NameHasBeenSet() const
{
return m_nameHasBeenSet;
}
uint64_t CreateAttackDownloadTaskRequest::GetRiskLevel() const
{
return m_riskLevel;
}
void CreateAttackDownloadTaskRequest::SetRiskLevel(const uint64_t& _riskLevel)
{
m_riskLevel = _riskLevel;
m_riskLevelHasBeenSet = true;
}
bool CreateAttackDownloadTaskRequest::RiskLevelHasBeenSet() const
{
return m_riskLevelHasBeenSet;
}
uint64_t CreateAttackDownloadTaskRequest::GetStatus() const
{
return m_status;
}
void CreateAttackDownloadTaskRequest::SetStatus(const uint64_t& _status)
{
m_status = _status;
m_statusHasBeenSet = true;
}
bool CreateAttackDownloadTaskRequest::StatusHasBeenSet() const
{
return m_statusHasBeenSet;
}
uint64_t CreateAttackDownloadTaskRequest::GetRuleId() const
{
return m_ruleId;
}
void CreateAttackDownloadTaskRequest::SetRuleId(const uint64_t& _ruleId)
{
m_ruleId = _ruleId;
m_ruleIdHasBeenSet = true;
}
bool CreateAttackDownloadTaskRequest::RuleIdHasBeenSet() const
{
return m_ruleIdHasBeenSet;
}
string CreateAttackDownloadTaskRequest::GetAttackIp() const
{
return m_attackIp;
}
void CreateAttackDownloadTaskRequest::SetAttackIp(const string& _attackIp)
{
m_attackIp = _attackIp;
m_attackIpHasBeenSet = true;
}
bool CreateAttackDownloadTaskRequest::AttackIpHasBeenSet() const
{
return m_attackIpHasBeenSet;
}
string CreateAttackDownloadTaskRequest::GetAttackType() const
{
return m_attackType;
}
void CreateAttackDownloadTaskRequest::SetAttackType(const string& _attackType)
{
m_attackType = _attackType;
m_attackTypeHasBeenSet = true;
}
bool CreateAttackDownloadTaskRequest::AttackTypeHasBeenSet() const
{
return m_attackTypeHasBeenSet;
}
| 25.518519 | 95 | 0.723077 | suluner |
9cee429080c82d731cdcf91453ceee424a088661 | 150 | hpp | C++ | src/events/interactions/delete-entity.hpp | guillaume-haerinck/imac-tower-defense | 365a32642ea0d3ad8b2b7d63347d585c44d9f670 | [
"MIT"
] | 44 | 2019-06-06T21:33:30.000Z | 2022-03-26T06:18:23.000Z | src/events/interactions/delete-entity.hpp | guillaume-haerinck/imac-tower-defense | 365a32642ea0d3ad8b2b7d63347d585c44d9f670 | [
"MIT"
] | 1 | 2019-09-27T12:04:52.000Z | 2019-09-29T13:30:42.000Z | src/events/interactions/delete-entity.hpp | guillaume-haerinck/imac-tower-defense | 365a32642ea0d3ad8b2b7d63347d585c44d9f670 | [
"MIT"
] | 8 | 2019-07-26T16:44:26.000Z | 2020-11-24T17:56:18.000Z | #pragma once
namespace evnt {
struct DeleteEntity {
DeleteEntity(std::uint32_t entityId) : entityId(entityId) {}
std::uint32_t entityId;
};
}
| 15 | 62 | 0.713333 | guillaume-haerinck |
9ceef42127f999b3cd649487f49ef5175eee3fc0 | 2,149 | cpp | C++ | src/CppUtil/Basic/StrAPI/StrAPI.cpp | huangx916/RenderLab | a0059705d5694146bbe51442e0cabdcbcd750fe7 | [
"MIT"
] | 1 | 2019-09-20T03:04:12.000Z | 2019-09-20T03:04:12.000Z | src/CppUtil/Basic/StrAPI/StrAPI.cpp | huangx916/RenderLab | a0059705d5694146bbe51442e0cabdcbcd750fe7 | [
"MIT"
] | null | null | null | src/CppUtil/Basic/StrAPI/StrAPI.cpp | huangx916/RenderLab | a0059705d5694146bbe51442e0cabdcbcd750fe7 | [
"MIT"
] | null | null | null | #include <CppUtil/Basic/StrAPI.h>
#include <cassert>
#include <algorithm>
using namespace CppUtil::Basic;
using namespace std;
const string StrAPI::Head(const string & str, int n) {
assert(n >= 0);
return str.substr(0, std::min(static_cast<size_t>(n), str.size()));
}
const string StrAPI::Tail(const string & str, int n) {
assert(n >= 0);
return str.substr(str.size() - n, n);
}
const string StrAPI::TailAfter(const string & str, char c) {
auto idx = str.find_last_of(c);
if (idx == string::npos)
return "";
return str.substr(idx + 1);
}
bool StrAPI::IsBeginWith(const string & str, const string & suffix) {
return Head(str, static_cast<int>(suffix.size())) == suffix;
}
bool StrAPI::IsEndWith(const string & str, const string & postfix) {
return Tail(str, static_cast<int>(postfix.size())) == postfix;
}
const vector<string> StrAPI::Spilt(const string & str, const string & separator) {
vector<string> rst;
if (separator.empty())
return rst;
size_t beginIdx = 0;
while(true){
size_t targetIdx = str.find(separator, beginIdx);
if (targetIdx == string::npos) {
rst.push_back(str.substr(beginIdx, str.size() - beginIdx));
break;
}
rst.push_back(str.substr(beginIdx, targetIdx - beginIdx));
beginIdx = targetIdx + separator.size();
}
return rst;
}
const string StrAPI::Join(const vector<string> & strs, const string & separator) {
string rst;
for (size_t i = 0; i < strs.size()-1; i++) {
rst += strs[i];
rst += separator;
}
rst += strs.back();
return rst;
}
const string StrAPI::Replace(const string & str, const string & orig, const string & target) {
return Join(Spilt(str, orig), target);
}
const std::string StrAPI::DelTailAfter(const std::string & str, char c) {
for (size_t i = str.size() - 1; i >= 0; i--) {
if (str[i] == c)
return str.substr(0, i);
}
return str;
}
const string StrAPI::Between(const string & str, char left, char right) {
auto start = str.find_first_of(left, 0);
if (start == string::npos)
return "";
auto end = str.find_last_of(right);
if (end == string::npos || end == start)
return "";
return str.substr(start + 1, end - (start + 1));
}
| 23.107527 | 94 | 0.658911 | huangx916 |
9cef88cd9b8cdde8848478b889a98ca49fb44843 | 9,530 | cpp | C++ | libs/obs/src/CSimpleMap.cpp | feroze/mrpt-shivang | 95bf524c5e10ed2e622bd199f1b0597951b45370 | [
"BSD-3-Clause"
] | 2 | 2017-03-25T18:09:17.000Z | 2017-05-22T08:14:48.000Z | libs/obs/src/CSimpleMap.cpp | feroze/mrpt-shivang | 95bf524c5e10ed2e622bd199f1b0597951b45370 | [
"BSD-3-Clause"
] | null | null | null | libs/obs/src/CSimpleMap.cpp | feroze/mrpt-shivang | 95bf524c5e10ed2e622bd199f1b0597951b45370 | [
"BSD-3-Clause"
] | 1 | 2018-07-29T09:40:46.000Z | 2018-07-29T09:40:46.000Z | /* +---------------------------------------------------------------------------+
| Mobile Robot Programming Toolkit (MRPT) |
| http://www.mrpt.org/ |
| |
| Copyright (c) 2005-2017, Individual contributors, see AUTHORS file |
| See: http://www.mrpt.org/Authors - All rights reserved. |
| Released under BSD License. See details in http://www.mrpt.org/License |
+---------------------------------------------------------------------------+ */
#include "obs-precomp.h" // Precompiled headers
#include <mrpt/maps/CSimpleMap.h>
#include <mrpt/utils/CFileGZInputStream.h>
#include <mrpt/utils/CFileGZOutputStream.h>
#include <mrpt/utils/CStream.h>
using namespace mrpt::obs;
using namespace mrpt::maps;
using namespace mrpt::utils;
using namespace mrpt::poses;
using namespace mrpt::poses;
using namespace std;
#include <mrpt/utils/metaprogramming.h>
using namespace mrpt::utils::metaprogramming;
IMPLEMENTS_SERIALIZABLE(CSimpleMap, CSerializable,mrpt::maps)
/*---------------------------------------------------------------
Constructor
---------------------------------------------------------------*/
CSimpleMap::CSimpleMap() : m_posesObsPairs()
{
}
/*---------------------------------------------------------------
Copy
---------------------------------------------------------------*/
CSimpleMap::CSimpleMap( const CSimpleMap &o ) :
m_posesObsPairs( o.m_posesObsPairs )
{
for_each( m_posesObsPairs.begin(), m_posesObsPairs.end(), ObjectPairMakeUnique() );
}
/*---------------------------------------------------------------
Copy
---------------------------------------------------------------*/
CSimpleMap & CSimpleMap::operator = ( const CSimpleMap& o)
{
MRPT_START
//TPosePDFSensFramePair pair;
if (this == &o) return *this; // It may be used sometimes
m_posesObsPairs = o.m_posesObsPairs;
for_each( m_posesObsPairs.begin(), m_posesObsPairs.end(), ObjectPairMakeUnique() );
return *this;
MRPT_END
}
/*---------------------------------------------------------------
size
---------------------------------------------------------------*/
size_t CSimpleMap::size() const
{
return m_posesObsPairs.size();
}
bool CSimpleMap::empty() const {
return m_posesObsPairs.empty();
}
/*---------------------------------------------------------------
clear
---------------------------------------------------------------*/
void CSimpleMap::clear()
{
m_posesObsPairs.clear();
}
/*---------------------------------------------------------------
Destructor
---------------------------------------------------------------*/
CSimpleMap::~CSimpleMap()
{
clear();
}
/*---------------------------------------------------------------
get const
---------------------------------------------------------------*/
void CSimpleMap::get(
size_t index,
CPose3DPDFPtr &out_posePDF,
CSensoryFramePtr &out_SF ) const
{
if (index>=m_posesObsPairs.size())
THROW_EXCEPTION("Index out of bounds");
out_posePDF = m_posesObsPairs[index].first;
out_SF = m_posesObsPairs[index].second;
}
/*---------------------------------------------------------------
remove
---------------------------------------------------------------*/
void CSimpleMap::remove(size_t index)
{
MRPT_START
if (index>=m_posesObsPairs.size())
THROW_EXCEPTION("Index out of bounds");
m_posesObsPairs.erase( m_posesObsPairs.begin() + index );
MRPT_END
}
/*---------------------------------------------------------------
set
---------------------------------------------------------------*/
void CSimpleMap::set(
size_t index,
const CPose3DPDFPtr &in_posePDF,
const CSensoryFramePtr & in_SF )
{
MRPT_START
if (index>=m_posesObsPairs.size())
THROW_EXCEPTION("Index out of bounds");
if (in_posePDF) m_posesObsPairs[index].first = in_posePDF;
if (in_SF) m_posesObsPairs[index].second = in_SF;
MRPT_END
}
/*---------------------------------------------------------------
set 2D
---------------------------------------------------------------*/
void CSimpleMap::set(
size_t index,
const CPosePDFPtr &in_posePDF,
const CSensoryFramePtr &in_SF )
{
MRPT_START
if (index>=m_posesObsPairs.size())
THROW_EXCEPTION("Index out of bounds");
if (in_posePDF) m_posesObsPairs[index].first = CPose3DPDFPtr( CPose3DPDF::createFrom2D( *in_posePDF ) );
if (in_SF) m_posesObsPairs[index].second = in_SF;
MRPT_END
}
/*---------------------------------------------------------------
insert
---------------------------------------------------------------*/
void CSimpleMap::insert( const CPose3DPDF *in_posePDF, const CSensoryFramePtr &in_SF )
{
MRPT_START
TPosePDFSensFramePair pair;
pair.second = in_SF;
pair.first = CPose3DPDFPtr( static_cast<CPose3DPDF*>(in_posePDF->duplicate()) );
m_posesObsPairs.push_back( pair );
MRPT_END
}
/*---------------------------------------------------------------
insert
---------------------------------------------------------------*/
void CSimpleMap::insert(
const CPose3DPDFPtr &in_posePDF,
const CSensoryFramePtr &in_SF )
{
MRPT_START
TPosePDFSensFramePair pair;
pair.second = in_SF;
pair.first = in_posePDF;
m_posesObsPairs.push_back( pair );
MRPT_END
}
/*---------------------------------------------------------------
insert
---------------------------------------------------------------*/
void CSimpleMap::insert( const CPose3DPDF *in_posePDF, const CSensoryFrame &in_SF )
{
MRPT_START
TPosePDFSensFramePair pair;
pair.second = CSensoryFramePtr( new CSensoryFrame(in_SF) );
pair.first = CPose3DPDFPtr( static_cast<CPose3DPDF*>(in_posePDF->duplicate()) );
m_posesObsPairs.push_back( pair );
MRPT_END
}
/*---------------------------------------------------------------
insert
---------------------------------------------------------------*/
void CSimpleMap::insert( const CPosePDF *in_posePDF, const CSensoryFrame &in_SF )
{
MRPT_START
TPosePDFSensFramePair pair;
pair.second = CSensoryFramePtr( new CSensoryFrame(in_SF) );
pair.first = CPose3DPDFPtr( static_cast<CPose3DPDF*>(in_posePDF->duplicate()) );
m_posesObsPairs.push_back( pair );
MRPT_END
}
/*---------------------------------------------------------------
insert
---------------------------------------------------------------*/
void CSimpleMap::insert( const CPosePDF *in_posePDF, const CSensoryFramePtr &in_SF )
{
MRPT_START
TPosePDFSensFramePair pair;
pair.second = in_SF;
pair.first = CPose3DPDFPtr( static_cast<CPose3DPDF*>(in_posePDF->duplicate()) );
m_posesObsPairs.push_back( pair );
MRPT_END
}
/*---------------------------------------------------------------
insert 2D
---------------------------------------------------------------*/
void CSimpleMap::insert(
const CPosePDFPtr &in_posePDF,
const CSensoryFramePtr &in_SF )
{
insert( CPose3DPDFPtr( CPose3DPDF::createFrom2D( *in_posePDF ) ) ,in_SF);
}
/*---------------------------------------------------------------
writeToStream
Implements the writing to a CStream capability of
CSerializable objects
---------------------------------------------------------------*/
void CSimpleMap::writeToStream(mrpt::utils::CStream &out,int *version) const
{
if (version)
*version = 1;
else
{
uint32_t i,n;
n = m_posesObsPairs.size();
out << n;
for (i=0;i<n;i++)
out << *m_posesObsPairs[i].first << *m_posesObsPairs[i].second;
}
}
/*---------------------------------------------------------------
readFromStream
---------------------------------------------------------------*/
void CSimpleMap::readFromStream(mrpt::utils::CStream &in, int version)
{
switch(version)
{
case 1:
{
uint32_t i,n;
clear();
in >> n;
m_posesObsPairs.resize(n);
for (i=0;i<n;i++)
in >> m_posesObsPairs[i].first >> m_posesObsPairs[i].second;
} break;
case 0:
{
// There are 2D poses PDF instead of 3D: transform them:
uint32_t i,n;
clear();
in >> n;
m_posesObsPairs.resize(n);
for (i=0;i<n;i++)
{
CPosePDFPtr aux2Dpose;
in >> aux2Dpose >> m_posesObsPairs[i].second;
m_posesObsPairs[i].first = CPose3DPDFPtr( CPose3DPDF::createFrom2D( *aux2Dpose ) );
}
} break;
default:
MRPT_THROW_UNKNOWN_SERIALIZATION_VERSION(version)
};
}
/*---------------------------------------------------------------
changeCoordinatesOrigin
---------------------------------------------------------------*/
void CSimpleMap::changeCoordinatesOrigin( const CPose3D &newOrigin )
{
for (TPosePDFSensFramePairList::iterator it=m_posesObsPairs.begin(); it!=m_posesObsPairs.end(); ++it)
it->first->changeCoordinatesReference(newOrigin);
}
/** Save this object to a .simplemap binary file (compressed with gzip)
* \sa loadFromFile
* \return false on any error.
*/
bool CSimpleMap::saveToFile(const std::string &filName) const
{
try
{
mrpt::utils::CFileGZOutputStream f(filName);
f << *this;
return true;
}
catch (...)
{
return false;
}
}
/** Load the contents of this object from a .simplemap binary file (possibly compressed with gzip)
* \sa saveToFile
* \return false on any error.
*/
bool CSimpleMap::loadFromFile(const std::string &filName)
{
try
{
mrpt::utils::CFileGZInputStream f(filName);
f >> *this;
return true;
}
catch (...)
{
return false;
}
}
| 26.545961 | 106 | 0.495173 | feroze |
9cf11266dce10f9681f3b02109fbecfdde39a2af | 78,227 | cpp | C++ | bench/ml2cpp-demo/XGBClassifier/BreastCancer/ml2cpp-demo_XGBClassifier_BreastCancer.cpp | antoinecarme/ml2cpp | 2b241d44de00eafda620c2b605690276faf5f8fb | [
"BSD-3-Clause"
] | null | null | null | bench/ml2cpp-demo/XGBClassifier/BreastCancer/ml2cpp-demo_XGBClassifier_BreastCancer.cpp | antoinecarme/ml2cpp | 2b241d44de00eafda620c2b605690276faf5f8fb | [
"BSD-3-Clause"
] | 33 | 2020-09-13T09:55:01.000Z | 2022-01-06T11:53:55.000Z | bench/ml2cpp-demo/XGBClassifier/BreastCancer/ml2cpp-demo_XGBClassifier_BreastCancer.cpp | antoinecarme/ml2cpp | 2b241d44de00eafda620c2b605690276faf5f8fb | [
"BSD-3-Clause"
] | 1 | 2021-01-26T14:41:58.000Z | 2021-01-26T14:41:58.000Z | // ********************************************************
// This C++ code was automatically generated by ml2cpp (development version).
// Copyright 2020
// https://github.com/antoinecarme/ml2cpp
// Model : XGBClassifier
// Dataset : BreastCancer
// This CPP code can be compiled using any C++-17 compiler.
// g++ -Wall -Wno-unused-function -std=c++17 -g -o ml2cpp-demo_XGBClassifier_BreastCancer.exe ml2cpp-demo_XGBClassifier_BreastCancer.cpp
// Model deployment code
// ********************************************************
#include "../../Generic.i"
namespace {
std::vector<std::any> get_classes(){
std::vector<std::any> lClasses = { 0, 1 };
return lClasses;
}
namespace XGB_Tree_0_0 {
std::vector<std::any> get_classes(){
std::vector<std::any> lClasses = { 0, 1 };
return lClasses;
}
typedef std::vector<double> tNodeData;
std::map<int, tNodeData> Decision_Tree_Node_data = {
{ 3 , {0.577859819 }} ,
{ 4 , {0.104347833 }} ,
{ 5 , {-0.381818205 }} ,
{ 6 , {-0.578181803 }}
};
int get_decision_tree_node_index(std::any Feature_0, std::any Feature_1, std::any Feature_2, std::any Feature_3, std::any Feature_4, std::any Feature_5, std::any Feature_6, std::any Feature_7, std::any Feature_8, std::any Feature_9, std::any Feature_10, std::any Feature_11, std::any Feature_12, std::any Feature_13, std::any Feature_14, std::any Feature_15, std::any Feature_16, std::any Feature_17, std::any Feature_18, std::any Feature_19, std::any Feature_20, std::any Feature_21, std::any Feature_22, std::any Feature_23, std::any Feature_24, std::any Feature_25, std::any Feature_26, std::any Feature_27, std::any Feature_28, std::any Feature_29) {
int lNodeIndex = ( Feature_27 < 0.145449996 ) ? ( ( Feature_22 < 105.850006 ) ? ( 3 ) : ( 4 ) ) : ( ( Feature_0 < 15.2600002 ) ? ( 5 ) : ( 6 ) );
return lNodeIndex;
}
std::vector<std::string> get_input_names(){
std::vector<std::string> lFeatures = { "Feature_0", "Feature_1", "Feature_2", "Feature_3", "Feature_4", "Feature_5", "Feature_6", "Feature_7", "Feature_8", "Feature_9", "Feature_10", "Feature_11", "Feature_12", "Feature_13", "Feature_14", "Feature_15", "Feature_16", "Feature_17", "Feature_18", "Feature_19", "Feature_20", "Feature_21", "Feature_22", "Feature_23", "Feature_24", "Feature_25", "Feature_26", "Feature_27", "Feature_28", "Feature_29" };
return lFeatures;
}
std::vector<std::string> get_output_names(){
std::vector<std::string> lOutputs = {
"Score_0", "Score_1",
"Proba_0", "Proba_1",
"LogProba_0", "LogProba_1" };
return lOutputs;
}
tTable compute_classification_scores(std::any Feature_0, std::any Feature_1, std::any Feature_2, std::any Feature_3, std::any Feature_4, std::any Feature_5, std::any Feature_6, std::any Feature_7, std::any Feature_8, std::any Feature_9, std::any Feature_10, std::any Feature_11, std::any Feature_12, std::any Feature_13, std::any Feature_14, std::any Feature_15, std::any Feature_16, std::any Feature_17, std::any Feature_18, std::any Feature_19, std::any Feature_20, std::any Feature_21, std::any Feature_22, std::any Feature_23, std::any Feature_24, std::any Feature_25, std::any Feature_26, std::any Feature_27, std::any Feature_28, std::any Feature_29) {
auto lClasses = get_classes();
int lNodeIndex = get_decision_tree_node_index(Feature_0, Feature_1, Feature_2, Feature_3, Feature_4, Feature_5, Feature_6, Feature_7, Feature_8, Feature_9, Feature_10, Feature_11, Feature_12, Feature_13, Feature_14, Feature_15, Feature_16, Feature_17, Feature_18, Feature_19, Feature_20, Feature_21, Feature_22, Feature_23, Feature_24, Feature_25, Feature_26, Feature_27, Feature_28, Feature_29);
std::vector<double> lNodeValue = Decision_Tree_Node_data[ lNodeIndex ];
tTable lTable;
lTable["Score"] = {
lNodeValue [0],
1.0 - lNodeValue [0]
} ;
lTable["Proba"] = {
std::any(),
std::any()
} ;
recompute_log_probas( lTable );
return lTable;
}
tTable compute_model_outputs_from_table( tTable const & iTable) {
tTable lTable = compute_classification_scores(iTable.at("Feature_0")[0], iTable.at("Feature_1")[0], iTable.at("Feature_2")[0], iTable.at("Feature_3")[0], iTable.at("Feature_4")[0], iTable.at("Feature_5")[0], iTable.at("Feature_6")[0], iTable.at("Feature_7")[0], iTable.at("Feature_8")[0], iTable.at("Feature_9")[0], iTable.at("Feature_10")[0], iTable.at("Feature_11")[0], iTable.at("Feature_12")[0], iTable.at("Feature_13")[0], iTable.at("Feature_14")[0], iTable.at("Feature_15")[0], iTable.at("Feature_16")[0], iTable.at("Feature_17")[0], iTable.at("Feature_18")[0], iTable.at("Feature_19")[0], iTable.at("Feature_20")[0], iTable.at("Feature_21")[0], iTable.at("Feature_22")[0], iTable.at("Feature_23")[0], iTable.at("Feature_24")[0], iTable.at("Feature_25")[0], iTable.at("Feature_26")[0], iTable.at("Feature_27")[0], iTable.at("Feature_28")[0], iTable.at("Feature_29")[0]);
return lTable;
}
} // eof namespace XGB_Tree_0_0
namespace XGB_Tree_0_1 {
std::vector<std::any> get_classes(){
std::vector<std::any> lClasses = { 0, 1 };
return lClasses;
}
typedef std::vector<double> tNodeData;
std::map<int, tNodeData> Decision_Tree_Node_data = {
{ 2 , {-0.443791091 }} ,
{ 3 , {0.452014327 }} ,
{ 4 , {0.0273430217 }}
};
int get_decision_tree_node_index(std::any Feature_0, std::any Feature_1, std::any Feature_2, std::any Feature_3, std::any Feature_4, std::any Feature_5, std::any Feature_6, std::any Feature_7, std::any Feature_8, std::any Feature_9, std::any Feature_10, std::any Feature_11, std::any Feature_12, std::any Feature_13, std::any Feature_14, std::any Feature_15, std::any Feature_16, std::any Feature_17, std::any Feature_18, std::any Feature_19, std::any Feature_20, std::any Feature_21, std::any Feature_22, std::any Feature_23, std::any Feature_24, std::any Feature_25, std::any Feature_26, std::any Feature_27, std::any Feature_28, std::any Feature_29) {
int lNodeIndex = ( Feature_22 < 114.399994 ) ? ( ( Feature_7 < 0.0489199981 ) ? ( 3 ) : ( 4 ) ) : ( 2 );
return lNodeIndex;
}
std::vector<std::string> get_input_names(){
std::vector<std::string> lFeatures = { "Feature_0", "Feature_1", "Feature_2", "Feature_3", "Feature_4", "Feature_5", "Feature_6", "Feature_7", "Feature_8", "Feature_9", "Feature_10", "Feature_11", "Feature_12", "Feature_13", "Feature_14", "Feature_15", "Feature_16", "Feature_17", "Feature_18", "Feature_19", "Feature_20", "Feature_21", "Feature_22", "Feature_23", "Feature_24", "Feature_25", "Feature_26", "Feature_27", "Feature_28", "Feature_29" };
return lFeatures;
}
std::vector<std::string> get_output_names(){
std::vector<std::string> lOutputs = {
"Score_0", "Score_1",
"Proba_0", "Proba_1",
"LogProba_0", "LogProba_1" };
return lOutputs;
}
tTable compute_classification_scores(std::any Feature_0, std::any Feature_1, std::any Feature_2, std::any Feature_3, std::any Feature_4, std::any Feature_5, std::any Feature_6, std::any Feature_7, std::any Feature_8, std::any Feature_9, std::any Feature_10, std::any Feature_11, std::any Feature_12, std::any Feature_13, std::any Feature_14, std::any Feature_15, std::any Feature_16, std::any Feature_17, std::any Feature_18, std::any Feature_19, std::any Feature_20, std::any Feature_21, std::any Feature_22, std::any Feature_23, std::any Feature_24, std::any Feature_25, std::any Feature_26, std::any Feature_27, std::any Feature_28, std::any Feature_29) {
auto lClasses = get_classes();
int lNodeIndex = get_decision_tree_node_index(Feature_0, Feature_1, Feature_2, Feature_3, Feature_4, Feature_5, Feature_6, Feature_7, Feature_8, Feature_9, Feature_10, Feature_11, Feature_12, Feature_13, Feature_14, Feature_15, Feature_16, Feature_17, Feature_18, Feature_19, Feature_20, Feature_21, Feature_22, Feature_23, Feature_24, Feature_25, Feature_26, Feature_27, Feature_28, Feature_29);
std::vector<double> lNodeValue = Decision_Tree_Node_data[ lNodeIndex ];
tTable lTable;
lTable["Score"] = {
lNodeValue [0],
1.0 - lNodeValue [0]
} ;
lTable["Proba"] = {
std::any(),
std::any()
} ;
recompute_log_probas( lTable );
return lTable;
}
tTable compute_model_outputs_from_table( tTable const & iTable) {
tTable lTable = compute_classification_scores(iTable.at("Feature_0")[0], iTable.at("Feature_1")[0], iTable.at("Feature_2")[0], iTable.at("Feature_3")[0], iTable.at("Feature_4")[0], iTable.at("Feature_5")[0], iTable.at("Feature_6")[0], iTable.at("Feature_7")[0], iTable.at("Feature_8")[0], iTable.at("Feature_9")[0], iTable.at("Feature_10")[0], iTable.at("Feature_11")[0], iTable.at("Feature_12")[0], iTable.at("Feature_13")[0], iTable.at("Feature_14")[0], iTable.at("Feature_15")[0], iTable.at("Feature_16")[0], iTable.at("Feature_17")[0], iTable.at("Feature_18")[0], iTable.at("Feature_19")[0], iTable.at("Feature_20")[0], iTable.at("Feature_21")[0], iTable.at("Feature_22")[0], iTable.at("Feature_23")[0], iTable.at("Feature_24")[0], iTable.at("Feature_25")[0], iTable.at("Feature_26")[0], iTable.at("Feature_27")[0], iTable.at("Feature_28")[0], iTable.at("Feature_29")[0]);
return lTable;
}
} // eof namespace XGB_Tree_0_1
namespace XGB_Tree_0_2 {
std::vector<std::any> get_classes(){
std::vector<std::any> lClasses = { 0, 1 };
return lClasses;
}
typedef std::vector<double> tNodeData;
std::map<int, tNodeData> Decision_Tree_Node_data = {
{ 3 , {0.396163613 }} ,
{ 4 , {0.0294305328 }} ,
{ 5 , {-0.232830554 }} ,
{ 6 , {-0.411204338 }}
};
int get_decision_tree_node_index(std::any Feature_0, std::any Feature_1, std::any Feature_2, std::any Feature_3, std::any Feature_4, std::any Feature_5, std::any Feature_6, std::any Feature_7, std::any Feature_8, std::any Feature_9, std::any Feature_10, std::any Feature_11, std::any Feature_12, std::any Feature_13, std::any Feature_14, std::any Feature_15, std::any Feature_16, std::any Feature_17, std::any Feature_18, std::any Feature_19, std::any Feature_20, std::any Feature_21, std::any Feature_22, std::any Feature_23, std::any Feature_24, std::any Feature_25, std::any Feature_26, std::any Feature_27, std::any Feature_28, std::any Feature_29) {
int lNodeIndex = ( Feature_27 < 0.145449996 ) ? ( ( Feature_13 < 32.8499985 ) ? ( 3 ) : ( 4 ) ) : ( ( Feature_21 < 26.2200012 ) ? ( 5 ) : ( 6 ) );
return lNodeIndex;
}
std::vector<std::string> get_input_names(){
std::vector<std::string> lFeatures = { "Feature_0", "Feature_1", "Feature_2", "Feature_3", "Feature_4", "Feature_5", "Feature_6", "Feature_7", "Feature_8", "Feature_9", "Feature_10", "Feature_11", "Feature_12", "Feature_13", "Feature_14", "Feature_15", "Feature_16", "Feature_17", "Feature_18", "Feature_19", "Feature_20", "Feature_21", "Feature_22", "Feature_23", "Feature_24", "Feature_25", "Feature_26", "Feature_27", "Feature_28", "Feature_29" };
return lFeatures;
}
std::vector<std::string> get_output_names(){
std::vector<std::string> lOutputs = {
"Score_0", "Score_1",
"Proba_0", "Proba_1",
"LogProba_0", "LogProba_1" };
return lOutputs;
}
tTable compute_classification_scores(std::any Feature_0, std::any Feature_1, std::any Feature_2, std::any Feature_3, std::any Feature_4, std::any Feature_5, std::any Feature_6, std::any Feature_7, std::any Feature_8, std::any Feature_9, std::any Feature_10, std::any Feature_11, std::any Feature_12, std::any Feature_13, std::any Feature_14, std::any Feature_15, std::any Feature_16, std::any Feature_17, std::any Feature_18, std::any Feature_19, std::any Feature_20, std::any Feature_21, std::any Feature_22, std::any Feature_23, std::any Feature_24, std::any Feature_25, std::any Feature_26, std::any Feature_27, std::any Feature_28, std::any Feature_29) {
auto lClasses = get_classes();
int lNodeIndex = get_decision_tree_node_index(Feature_0, Feature_1, Feature_2, Feature_3, Feature_4, Feature_5, Feature_6, Feature_7, Feature_8, Feature_9, Feature_10, Feature_11, Feature_12, Feature_13, Feature_14, Feature_15, Feature_16, Feature_17, Feature_18, Feature_19, Feature_20, Feature_21, Feature_22, Feature_23, Feature_24, Feature_25, Feature_26, Feature_27, Feature_28, Feature_29);
std::vector<double> lNodeValue = Decision_Tree_Node_data[ lNodeIndex ];
tTable lTable;
lTable["Score"] = {
lNodeValue [0],
1.0 - lNodeValue [0]
} ;
lTable["Proba"] = {
std::any(),
std::any()
} ;
recompute_log_probas( lTable );
return lTable;
}
tTable compute_model_outputs_from_table( tTable const & iTable) {
tTable lTable = compute_classification_scores(iTable.at("Feature_0")[0], iTable.at("Feature_1")[0], iTable.at("Feature_2")[0], iTable.at("Feature_3")[0], iTable.at("Feature_4")[0], iTable.at("Feature_5")[0], iTable.at("Feature_6")[0], iTable.at("Feature_7")[0], iTable.at("Feature_8")[0], iTable.at("Feature_9")[0], iTable.at("Feature_10")[0], iTable.at("Feature_11")[0], iTable.at("Feature_12")[0], iTable.at("Feature_13")[0], iTable.at("Feature_14")[0], iTable.at("Feature_15")[0], iTable.at("Feature_16")[0], iTable.at("Feature_17")[0], iTable.at("Feature_18")[0], iTable.at("Feature_19")[0], iTable.at("Feature_20")[0], iTable.at("Feature_21")[0], iTable.at("Feature_22")[0], iTable.at("Feature_23")[0], iTable.at("Feature_24")[0], iTable.at("Feature_25")[0], iTable.at("Feature_26")[0], iTable.at("Feature_27")[0], iTable.at("Feature_28")[0], iTable.at("Feature_29")[0]);
return lTable;
}
} // eof namespace XGB_Tree_0_2
namespace XGB_Tree_0_3 {
std::vector<std::any> get_classes(){
std::vector<std::any> lClasses = { 0, 1 };
return lClasses;
}
typedef std::vector<double> tNodeData;
std::map<int, tNodeData> Decision_Tree_Node_data = {
{ 2 , {-0.369929641 }} ,
{ 3 , {0.352983713 }} ,
{ 4 , {0.0058717085 }}
};
int get_decision_tree_node_index(std::any Feature_0, std::any Feature_1, std::any Feature_2, std::any Feature_3, std::any Feature_4, std::any Feature_5, std::any Feature_6, std::any Feature_7, std::any Feature_8, std::any Feature_9, std::any Feature_10, std::any Feature_11, std::any Feature_12, std::any Feature_13, std::any Feature_14, std::any Feature_15, std::any Feature_16, std::any Feature_17, std::any Feature_18, std::any Feature_19, std::any Feature_20, std::any Feature_21, std::any Feature_22, std::any Feature_23, std::any Feature_24, std::any Feature_25, std::any Feature_26, std::any Feature_27, std::any Feature_28, std::any Feature_29) {
int lNodeIndex = ( Feature_22 < 117.449997 ) ? ( ( Feature_27 < 0.122299999 ) ? ( 3 ) : ( 4 ) ) : ( 2 );
return lNodeIndex;
}
std::vector<std::string> get_input_names(){
std::vector<std::string> lFeatures = { "Feature_0", "Feature_1", "Feature_2", "Feature_3", "Feature_4", "Feature_5", "Feature_6", "Feature_7", "Feature_8", "Feature_9", "Feature_10", "Feature_11", "Feature_12", "Feature_13", "Feature_14", "Feature_15", "Feature_16", "Feature_17", "Feature_18", "Feature_19", "Feature_20", "Feature_21", "Feature_22", "Feature_23", "Feature_24", "Feature_25", "Feature_26", "Feature_27", "Feature_28", "Feature_29" };
return lFeatures;
}
std::vector<std::string> get_output_names(){
std::vector<std::string> lOutputs = {
"Score_0", "Score_1",
"Proba_0", "Proba_1",
"LogProba_0", "LogProba_1" };
return lOutputs;
}
tTable compute_classification_scores(std::any Feature_0, std::any Feature_1, std::any Feature_2, std::any Feature_3, std::any Feature_4, std::any Feature_5, std::any Feature_6, std::any Feature_7, std::any Feature_8, std::any Feature_9, std::any Feature_10, std::any Feature_11, std::any Feature_12, std::any Feature_13, std::any Feature_14, std::any Feature_15, std::any Feature_16, std::any Feature_17, std::any Feature_18, std::any Feature_19, std::any Feature_20, std::any Feature_21, std::any Feature_22, std::any Feature_23, std::any Feature_24, std::any Feature_25, std::any Feature_26, std::any Feature_27, std::any Feature_28, std::any Feature_29) {
auto lClasses = get_classes();
int lNodeIndex = get_decision_tree_node_index(Feature_0, Feature_1, Feature_2, Feature_3, Feature_4, Feature_5, Feature_6, Feature_7, Feature_8, Feature_9, Feature_10, Feature_11, Feature_12, Feature_13, Feature_14, Feature_15, Feature_16, Feature_17, Feature_18, Feature_19, Feature_20, Feature_21, Feature_22, Feature_23, Feature_24, Feature_25, Feature_26, Feature_27, Feature_28, Feature_29);
std::vector<double> lNodeValue = Decision_Tree_Node_data[ lNodeIndex ];
tTable lTable;
lTable["Score"] = {
lNodeValue [0],
1.0 - lNodeValue [0]
} ;
lTable["Proba"] = {
std::any(),
std::any()
} ;
recompute_log_probas( lTable );
return lTable;
}
tTable compute_model_outputs_from_table( tTable const & iTable) {
tTable lTable = compute_classification_scores(iTable.at("Feature_0")[0], iTable.at("Feature_1")[0], iTable.at("Feature_2")[0], iTable.at("Feature_3")[0], iTable.at("Feature_4")[0], iTable.at("Feature_5")[0], iTable.at("Feature_6")[0], iTable.at("Feature_7")[0], iTable.at("Feature_8")[0], iTable.at("Feature_9")[0], iTable.at("Feature_10")[0], iTable.at("Feature_11")[0], iTable.at("Feature_12")[0], iTable.at("Feature_13")[0], iTable.at("Feature_14")[0], iTable.at("Feature_15")[0], iTable.at("Feature_16")[0], iTable.at("Feature_17")[0], iTable.at("Feature_18")[0], iTable.at("Feature_19")[0], iTable.at("Feature_20")[0], iTable.at("Feature_21")[0], iTable.at("Feature_22")[0], iTable.at("Feature_23")[0], iTable.at("Feature_24")[0], iTable.at("Feature_25")[0], iTable.at("Feature_26")[0], iTable.at("Feature_27")[0], iTable.at("Feature_28")[0], iTable.at("Feature_29")[0]);
return lTable;
}
} // eof namespace XGB_Tree_0_3
namespace XGB_Tree_0_4 {
std::vector<std::any> get_classes(){
std::vector<std::any> lClasses = { 0, 1 };
return lClasses;
}
typedef std::vector<double> tNodeData;
std::map<int, tNodeData> Decision_Tree_Node_data = {
{ 3 , {0.331853092 }} ,
{ 4 , {0.0621976517 }} ,
{ 5 , {-0.196852133 }} ,
{ 6 , {-0.360705614 }}
};
int get_decision_tree_node_index(std::any Feature_0, std::any Feature_1, std::any Feature_2, std::any Feature_3, std::any Feature_4, std::any Feature_5, std::any Feature_6, std::any Feature_7, std::any Feature_8, std::any Feature_9, std::any Feature_10, std::any Feature_11, std::any Feature_12, std::any Feature_13, std::any Feature_14, std::any Feature_15, std::any Feature_16, std::any Feature_17, std::any Feature_18, std::any Feature_19, std::any Feature_20, std::any Feature_21, std::any Feature_22, std::any Feature_23, std::any Feature_24, std::any Feature_25, std::any Feature_26, std::any Feature_27, std::any Feature_28, std::any Feature_29) {
int lNodeIndex = ( Feature_20 < 16.7950001 ) ? ( ( Feature_7 < 0.0447399989 ) ? ( 3 ) : ( 4 ) ) : ( ( Feature_1 < 20.2350006 ) ? ( 5 ) : ( 6 ) );
return lNodeIndex;
}
std::vector<std::string> get_input_names(){
std::vector<std::string> lFeatures = { "Feature_0", "Feature_1", "Feature_2", "Feature_3", "Feature_4", "Feature_5", "Feature_6", "Feature_7", "Feature_8", "Feature_9", "Feature_10", "Feature_11", "Feature_12", "Feature_13", "Feature_14", "Feature_15", "Feature_16", "Feature_17", "Feature_18", "Feature_19", "Feature_20", "Feature_21", "Feature_22", "Feature_23", "Feature_24", "Feature_25", "Feature_26", "Feature_27", "Feature_28", "Feature_29" };
return lFeatures;
}
std::vector<std::string> get_output_names(){
std::vector<std::string> lOutputs = {
"Score_0", "Score_1",
"Proba_0", "Proba_1",
"LogProba_0", "LogProba_1" };
return lOutputs;
}
tTable compute_classification_scores(std::any Feature_0, std::any Feature_1, std::any Feature_2, std::any Feature_3, std::any Feature_4, std::any Feature_5, std::any Feature_6, std::any Feature_7, std::any Feature_8, std::any Feature_9, std::any Feature_10, std::any Feature_11, std::any Feature_12, std::any Feature_13, std::any Feature_14, std::any Feature_15, std::any Feature_16, std::any Feature_17, std::any Feature_18, std::any Feature_19, std::any Feature_20, std::any Feature_21, std::any Feature_22, std::any Feature_23, std::any Feature_24, std::any Feature_25, std::any Feature_26, std::any Feature_27, std::any Feature_28, std::any Feature_29) {
auto lClasses = get_classes();
int lNodeIndex = get_decision_tree_node_index(Feature_0, Feature_1, Feature_2, Feature_3, Feature_4, Feature_5, Feature_6, Feature_7, Feature_8, Feature_9, Feature_10, Feature_11, Feature_12, Feature_13, Feature_14, Feature_15, Feature_16, Feature_17, Feature_18, Feature_19, Feature_20, Feature_21, Feature_22, Feature_23, Feature_24, Feature_25, Feature_26, Feature_27, Feature_28, Feature_29);
std::vector<double> lNodeValue = Decision_Tree_Node_data[ lNodeIndex ];
tTable lTable;
lTable["Score"] = {
lNodeValue [0],
1.0 - lNodeValue [0]
} ;
lTable["Proba"] = {
std::any(),
std::any()
} ;
recompute_log_probas( lTable );
return lTable;
}
tTable compute_model_outputs_from_table( tTable const & iTable) {
tTable lTable = compute_classification_scores(iTable.at("Feature_0")[0], iTable.at("Feature_1")[0], iTable.at("Feature_2")[0], iTable.at("Feature_3")[0], iTable.at("Feature_4")[0], iTable.at("Feature_5")[0], iTable.at("Feature_6")[0], iTable.at("Feature_7")[0], iTable.at("Feature_8")[0], iTable.at("Feature_9")[0], iTable.at("Feature_10")[0], iTable.at("Feature_11")[0], iTable.at("Feature_12")[0], iTable.at("Feature_13")[0], iTable.at("Feature_14")[0], iTable.at("Feature_15")[0], iTable.at("Feature_16")[0], iTable.at("Feature_17")[0], iTable.at("Feature_18")[0], iTable.at("Feature_19")[0], iTable.at("Feature_20")[0], iTable.at("Feature_21")[0], iTable.at("Feature_22")[0], iTable.at("Feature_23")[0], iTable.at("Feature_24")[0], iTable.at("Feature_25")[0], iTable.at("Feature_26")[0], iTable.at("Feature_27")[0], iTable.at("Feature_28")[0], iTable.at("Feature_29")[0]);
return lTable;
}
} // eof namespace XGB_Tree_0_4
namespace XGB_Tree_0_5 {
std::vector<std::any> get_classes(){
std::vector<std::any> lClasses = { 0, 1 };
return lClasses;
}
typedef std::vector<double> tNodeData;
std::map<int, tNodeData> Decision_Tree_Node_data = {
{ 2 , {-0.299602687 }} ,
{ 3 , {0.323272616 }} ,
{ 4 , {-0.00179177092 }}
};
int get_decision_tree_node_index(std::any Feature_0, std::any Feature_1, std::any Feature_2, std::any Feature_3, std::any Feature_4, std::any Feature_5, std::any Feature_6, std::any Feature_7, std::any Feature_8, std::any Feature_9, std::any Feature_10, std::any Feature_11, std::any Feature_12, std::any Feature_13, std::any Feature_14, std::any Feature_15, std::any Feature_16, std::any Feature_17, std::any Feature_18, std::any Feature_19, std::any Feature_20, std::any Feature_21, std::any Feature_22, std::any Feature_23, std::any Feature_24, std::any Feature_25, std::any Feature_26, std::any Feature_27, std::any Feature_28, std::any Feature_29) {
int lNodeIndex = ( Feature_27 < 0.150749996 ) ? ( ( Feature_13 < 29.3899994 ) ? ( 3 ) : ( 4 ) ) : ( 2 );
return lNodeIndex;
}
std::vector<std::string> get_input_names(){
std::vector<std::string> lFeatures = { "Feature_0", "Feature_1", "Feature_2", "Feature_3", "Feature_4", "Feature_5", "Feature_6", "Feature_7", "Feature_8", "Feature_9", "Feature_10", "Feature_11", "Feature_12", "Feature_13", "Feature_14", "Feature_15", "Feature_16", "Feature_17", "Feature_18", "Feature_19", "Feature_20", "Feature_21", "Feature_22", "Feature_23", "Feature_24", "Feature_25", "Feature_26", "Feature_27", "Feature_28", "Feature_29" };
return lFeatures;
}
std::vector<std::string> get_output_names(){
std::vector<std::string> lOutputs = {
"Score_0", "Score_1",
"Proba_0", "Proba_1",
"LogProba_0", "LogProba_1" };
return lOutputs;
}
tTable compute_classification_scores(std::any Feature_0, std::any Feature_1, std::any Feature_2, std::any Feature_3, std::any Feature_4, std::any Feature_5, std::any Feature_6, std::any Feature_7, std::any Feature_8, std::any Feature_9, std::any Feature_10, std::any Feature_11, std::any Feature_12, std::any Feature_13, std::any Feature_14, std::any Feature_15, std::any Feature_16, std::any Feature_17, std::any Feature_18, std::any Feature_19, std::any Feature_20, std::any Feature_21, std::any Feature_22, std::any Feature_23, std::any Feature_24, std::any Feature_25, std::any Feature_26, std::any Feature_27, std::any Feature_28, std::any Feature_29) {
auto lClasses = get_classes();
int lNodeIndex = get_decision_tree_node_index(Feature_0, Feature_1, Feature_2, Feature_3, Feature_4, Feature_5, Feature_6, Feature_7, Feature_8, Feature_9, Feature_10, Feature_11, Feature_12, Feature_13, Feature_14, Feature_15, Feature_16, Feature_17, Feature_18, Feature_19, Feature_20, Feature_21, Feature_22, Feature_23, Feature_24, Feature_25, Feature_26, Feature_27, Feature_28, Feature_29);
std::vector<double> lNodeValue = Decision_Tree_Node_data[ lNodeIndex ];
tTable lTable;
lTable["Score"] = {
lNodeValue [0],
1.0 - lNodeValue [0]
} ;
lTable["Proba"] = {
std::any(),
std::any()
} ;
recompute_log_probas( lTable );
return lTable;
}
tTable compute_model_outputs_from_table( tTable const & iTable) {
tTable lTable = compute_classification_scores(iTable.at("Feature_0")[0], iTable.at("Feature_1")[0], iTable.at("Feature_2")[0], iTable.at("Feature_3")[0], iTable.at("Feature_4")[0], iTable.at("Feature_5")[0], iTable.at("Feature_6")[0], iTable.at("Feature_7")[0], iTable.at("Feature_8")[0], iTable.at("Feature_9")[0], iTable.at("Feature_10")[0], iTable.at("Feature_11")[0], iTable.at("Feature_12")[0], iTable.at("Feature_13")[0], iTable.at("Feature_14")[0], iTable.at("Feature_15")[0], iTable.at("Feature_16")[0], iTable.at("Feature_17")[0], iTable.at("Feature_18")[0], iTable.at("Feature_19")[0], iTable.at("Feature_20")[0], iTable.at("Feature_21")[0], iTable.at("Feature_22")[0], iTable.at("Feature_23")[0], iTable.at("Feature_24")[0], iTable.at("Feature_25")[0], iTable.at("Feature_26")[0], iTable.at("Feature_27")[0], iTable.at("Feature_28")[0], iTable.at("Feature_29")[0]);
return lTable;
}
} // eof namespace XGB_Tree_0_5
namespace XGB_Tree_0_6 {
std::vector<std::any> get_classes(){
std::vector<std::any> lClasses = { 0, 1 };
return lClasses;
}
typedef std::vector<double> tNodeData;
std::map<int, tNodeData> Decision_Tree_Node_data = {
{ 2 , {-0.257835239 }} ,
{ 3 , {0.318035483 }} ,
{ 4 , {0.0797671974 }}
};
int get_decision_tree_node_index(std::any Feature_0, std::any Feature_1, std::any Feature_2, std::any Feature_3, std::any Feature_4, std::any Feature_5, std::any Feature_6, std::any Feature_7, std::any Feature_8, std::any Feature_9, std::any Feature_10, std::any Feature_11, std::any Feature_12, std::any Feature_13, std::any Feature_14, std::any Feature_15, std::any Feature_16, std::any Feature_17, std::any Feature_18, std::any Feature_19, std::any Feature_20, std::any Feature_21, std::any Feature_22, std::any Feature_23, std::any Feature_24, std::any Feature_25, std::any Feature_26, std::any Feature_27, std::any Feature_28, std::any Feature_29) {
int lNodeIndex = ( Feature_22 < 113.149994 ) ? ( ( Feature_21 < 25.1800003 ) ? ( 3 ) : ( 4 ) ) : ( 2 );
return lNodeIndex;
}
std::vector<std::string> get_input_names(){
std::vector<std::string> lFeatures = { "Feature_0", "Feature_1", "Feature_2", "Feature_3", "Feature_4", "Feature_5", "Feature_6", "Feature_7", "Feature_8", "Feature_9", "Feature_10", "Feature_11", "Feature_12", "Feature_13", "Feature_14", "Feature_15", "Feature_16", "Feature_17", "Feature_18", "Feature_19", "Feature_20", "Feature_21", "Feature_22", "Feature_23", "Feature_24", "Feature_25", "Feature_26", "Feature_27", "Feature_28", "Feature_29" };
return lFeatures;
}
std::vector<std::string> get_output_names(){
std::vector<std::string> lOutputs = {
"Score_0", "Score_1",
"Proba_0", "Proba_1",
"LogProba_0", "LogProba_1" };
return lOutputs;
}
tTable compute_classification_scores(std::any Feature_0, std::any Feature_1, std::any Feature_2, std::any Feature_3, std::any Feature_4, std::any Feature_5, std::any Feature_6, std::any Feature_7, std::any Feature_8, std::any Feature_9, std::any Feature_10, std::any Feature_11, std::any Feature_12, std::any Feature_13, std::any Feature_14, std::any Feature_15, std::any Feature_16, std::any Feature_17, std::any Feature_18, std::any Feature_19, std::any Feature_20, std::any Feature_21, std::any Feature_22, std::any Feature_23, std::any Feature_24, std::any Feature_25, std::any Feature_26, std::any Feature_27, std::any Feature_28, std::any Feature_29) {
auto lClasses = get_classes();
int lNodeIndex = get_decision_tree_node_index(Feature_0, Feature_1, Feature_2, Feature_3, Feature_4, Feature_5, Feature_6, Feature_7, Feature_8, Feature_9, Feature_10, Feature_11, Feature_12, Feature_13, Feature_14, Feature_15, Feature_16, Feature_17, Feature_18, Feature_19, Feature_20, Feature_21, Feature_22, Feature_23, Feature_24, Feature_25, Feature_26, Feature_27, Feature_28, Feature_29);
std::vector<double> lNodeValue = Decision_Tree_Node_data[ lNodeIndex ];
tTable lTable;
lTable["Score"] = {
lNodeValue [0],
1.0 - lNodeValue [0]
} ;
lTable["Proba"] = {
std::any(),
std::any()
} ;
recompute_log_probas( lTable );
return lTable;
}
tTable compute_model_outputs_from_table( tTable const & iTable) {
tTable lTable = compute_classification_scores(iTable.at("Feature_0")[0], iTable.at("Feature_1")[0], iTable.at("Feature_2")[0], iTable.at("Feature_3")[0], iTable.at("Feature_4")[0], iTable.at("Feature_5")[0], iTable.at("Feature_6")[0], iTable.at("Feature_7")[0], iTable.at("Feature_8")[0], iTable.at("Feature_9")[0], iTable.at("Feature_10")[0], iTable.at("Feature_11")[0], iTable.at("Feature_12")[0], iTable.at("Feature_13")[0], iTable.at("Feature_14")[0], iTable.at("Feature_15")[0], iTable.at("Feature_16")[0], iTable.at("Feature_17")[0], iTable.at("Feature_18")[0], iTable.at("Feature_19")[0], iTable.at("Feature_20")[0], iTable.at("Feature_21")[0], iTable.at("Feature_22")[0], iTable.at("Feature_23")[0], iTable.at("Feature_24")[0], iTable.at("Feature_25")[0], iTable.at("Feature_26")[0], iTable.at("Feature_27")[0], iTable.at("Feature_28")[0], iTable.at("Feature_29")[0]);
return lTable;
}
} // eof namespace XGB_Tree_0_6
namespace XGB_Tree_0_7 {
std::vector<std::any> get_classes(){
std::vector<std::any> lClasses = { 0, 1 };
return lClasses;
}
typedef std::vector<double> tNodeData;
std::map<int, tNodeData> Decision_Tree_Node_data = {
{ 2 , {-0.183022752 }} ,
{ 3 , {0.148378 }} ,
{ 4 , {0.320678353 }}
};
int get_decision_tree_node_index(std::any Feature_0, std::any Feature_1, std::any Feature_2, std::any Feature_3, std::any Feature_4, std::any Feature_5, std::any Feature_6, std::any Feature_7, std::any Feature_8, std::any Feature_9, std::any Feature_10, std::any Feature_11, std::any Feature_12, std::any Feature_13, std::any Feature_14, std::any Feature_15, std::any Feature_16, std::any Feature_17, std::any Feature_18, std::any Feature_19, std::any Feature_20, std::any Feature_21, std::any Feature_22, std::any Feature_23, std::any Feature_24, std::any Feature_25, std::any Feature_26, std::any Feature_27, std::any Feature_28, std::any Feature_29) {
int lNodeIndex = ( Feature_7 < 0.0489199981 ) ? ( ( Feature_15 < 0.0144750001 ) ? ( 3 ) : ( 4 ) ) : ( 2 );
return lNodeIndex;
}
std::vector<std::string> get_input_names(){
std::vector<std::string> lFeatures = { "Feature_0", "Feature_1", "Feature_2", "Feature_3", "Feature_4", "Feature_5", "Feature_6", "Feature_7", "Feature_8", "Feature_9", "Feature_10", "Feature_11", "Feature_12", "Feature_13", "Feature_14", "Feature_15", "Feature_16", "Feature_17", "Feature_18", "Feature_19", "Feature_20", "Feature_21", "Feature_22", "Feature_23", "Feature_24", "Feature_25", "Feature_26", "Feature_27", "Feature_28", "Feature_29" };
return lFeatures;
}
std::vector<std::string> get_output_names(){
std::vector<std::string> lOutputs = {
"Score_0", "Score_1",
"Proba_0", "Proba_1",
"LogProba_0", "LogProba_1" };
return lOutputs;
}
tTable compute_classification_scores(std::any Feature_0, std::any Feature_1, std::any Feature_2, std::any Feature_3, std::any Feature_4, std::any Feature_5, std::any Feature_6, std::any Feature_7, std::any Feature_8, std::any Feature_9, std::any Feature_10, std::any Feature_11, std::any Feature_12, std::any Feature_13, std::any Feature_14, std::any Feature_15, std::any Feature_16, std::any Feature_17, std::any Feature_18, std::any Feature_19, std::any Feature_20, std::any Feature_21, std::any Feature_22, std::any Feature_23, std::any Feature_24, std::any Feature_25, std::any Feature_26, std::any Feature_27, std::any Feature_28, std::any Feature_29) {
auto lClasses = get_classes();
int lNodeIndex = get_decision_tree_node_index(Feature_0, Feature_1, Feature_2, Feature_3, Feature_4, Feature_5, Feature_6, Feature_7, Feature_8, Feature_9, Feature_10, Feature_11, Feature_12, Feature_13, Feature_14, Feature_15, Feature_16, Feature_17, Feature_18, Feature_19, Feature_20, Feature_21, Feature_22, Feature_23, Feature_24, Feature_25, Feature_26, Feature_27, Feature_28, Feature_29);
std::vector<double> lNodeValue = Decision_Tree_Node_data[ lNodeIndex ];
tTable lTable;
lTable["Score"] = {
lNodeValue [0],
1.0 - lNodeValue [0]
} ;
lTable["Proba"] = {
std::any(),
std::any()
} ;
recompute_log_probas( lTable );
return lTable;
}
tTable compute_model_outputs_from_table( tTable const & iTable) {
tTable lTable = compute_classification_scores(iTable.at("Feature_0")[0], iTable.at("Feature_1")[0], iTable.at("Feature_2")[0], iTable.at("Feature_3")[0], iTable.at("Feature_4")[0], iTable.at("Feature_5")[0], iTable.at("Feature_6")[0], iTable.at("Feature_7")[0], iTable.at("Feature_8")[0], iTable.at("Feature_9")[0], iTable.at("Feature_10")[0], iTable.at("Feature_11")[0], iTable.at("Feature_12")[0], iTable.at("Feature_13")[0], iTable.at("Feature_14")[0], iTable.at("Feature_15")[0], iTable.at("Feature_16")[0], iTable.at("Feature_17")[0], iTable.at("Feature_18")[0], iTable.at("Feature_19")[0], iTable.at("Feature_20")[0], iTable.at("Feature_21")[0], iTable.at("Feature_22")[0], iTable.at("Feature_23")[0], iTable.at("Feature_24")[0], iTable.at("Feature_25")[0], iTable.at("Feature_26")[0], iTable.at("Feature_27")[0], iTable.at("Feature_28")[0], iTable.at("Feature_29")[0]);
return lTable;
}
} // eof namespace XGB_Tree_0_7
namespace XGB_Tree_0_8 {
std::vector<std::any> get_classes(){
std::vector<std::any> lClasses = { 0, 1 };
return lClasses;
}
typedef std::vector<double> tNodeData;
std::map<int, tNodeData> Decision_Tree_Node_data = {
{ 1 , {0.26075694 }} ,
{ 2 , {-0.140906826 }}
};
int get_decision_tree_node_index(std::any Feature_0, std::any Feature_1, std::any Feature_2, std::any Feature_3, std::any Feature_4, std::any Feature_5, std::any Feature_6, std::any Feature_7, std::any Feature_8, std::any Feature_9, std::any Feature_10, std::any Feature_11, std::any Feature_12, std::any Feature_13, std::any Feature_14, std::any Feature_15, std::any Feature_16, std::any Feature_17, std::any Feature_18, std::any Feature_19, std::any Feature_20, std::any Feature_21, std::any Feature_22, std::any Feature_23, std::any Feature_24, std::any Feature_25, std::any Feature_26, std::any Feature_27, std::any Feature_28, std::any Feature_29) {
int lNodeIndex = ( Feature_23 < 739.199951 ) ? ( 1 ) : ( 2 );
return lNodeIndex;
}
std::vector<std::string> get_input_names(){
std::vector<std::string> lFeatures = { "Feature_0", "Feature_1", "Feature_2", "Feature_3", "Feature_4", "Feature_5", "Feature_6", "Feature_7", "Feature_8", "Feature_9", "Feature_10", "Feature_11", "Feature_12", "Feature_13", "Feature_14", "Feature_15", "Feature_16", "Feature_17", "Feature_18", "Feature_19", "Feature_20", "Feature_21", "Feature_22", "Feature_23", "Feature_24", "Feature_25", "Feature_26", "Feature_27", "Feature_28", "Feature_29" };
return lFeatures;
}
std::vector<std::string> get_output_names(){
std::vector<std::string> lOutputs = {
"Score_0", "Score_1",
"Proba_0", "Proba_1",
"LogProba_0", "LogProba_1" };
return lOutputs;
}
tTable compute_classification_scores(std::any Feature_0, std::any Feature_1, std::any Feature_2, std::any Feature_3, std::any Feature_4, std::any Feature_5, std::any Feature_6, std::any Feature_7, std::any Feature_8, std::any Feature_9, std::any Feature_10, std::any Feature_11, std::any Feature_12, std::any Feature_13, std::any Feature_14, std::any Feature_15, std::any Feature_16, std::any Feature_17, std::any Feature_18, std::any Feature_19, std::any Feature_20, std::any Feature_21, std::any Feature_22, std::any Feature_23, std::any Feature_24, std::any Feature_25, std::any Feature_26, std::any Feature_27, std::any Feature_28, std::any Feature_29) {
auto lClasses = get_classes();
int lNodeIndex = get_decision_tree_node_index(Feature_0, Feature_1, Feature_2, Feature_3, Feature_4, Feature_5, Feature_6, Feature_7, Feature_8, Feature_9, Feature_10, Feature_11, Feature_12, Feature_13, Feature_14, Feature_15, Feature_16, Feature_17, Feature_18, Feature_19, Feature_20, Feature_21, Feature_22, Feature_23, Feature_24, Feature_25, Feature_26, Feature_27, Feature_28, Feature_29);
std::vector<double> lNodeValue = Decision_Tree_Node_data[ lNodeIndex ];
tTable lTable;
lTable["Score"] = {
lNodeValue [0],
1.0 - lNodeValue [0]
} ;
lTable["Proba"] = {
std::any(),
std::any()
} ;
recompute_log_probas( lTable );
return lTable;
}
tTable compute_model_outputs_from_table( tTable const & iTable) {
tTable lTable = compute_classification_scores(iTable.at("Feature_0")[0], iTable.at("Feature_1")[0], iTable.at("Feature_2")[0], iTable.at("Feature_3")[0], iTable.at("Feature_4")[0], iTable.at("Feature_5")[0], iTable.at("Feature_6")[0], iTable.at("Feature_7")[0], iTable.at("Feature_8")[0], iTable.at("Feature_9")[0], iTable.at("Feature_10")[0], iTable.at("Feature_11")[0], iTable.at("Feature_12")[0], iTable.at("Feature_13")[0], iTable.at("Feature_14")[0], iTable.at("Feature_15")[0], iTable.at("Feature_16")[0], iTable.at("Feature_17")[0], iTable.at("Feature_18")[0], iTable.at("Feature_19")[0], iTable.at("Feature_20")[0], iTable.at("Feature_21")[0], iTable.at("Feature_22")[0], iTable.at("Feature_23")[0], iTable.at("Feature_24")[0], iTable.at("Feature_25")[0], iTable.at("Feature_26")[0], iTable.at("Feature_27")[0], iTable.at("Feature_28")[0], iTable.at("Feature_29")[0]);
return lTable;
}
} // eof namespace XGB_Tree_0_8
namespace XGB_Tree_0_9 {
std::vector<std::any> get_classes(){
std::vector<std::any> lClasses = { 0, 1 };
return lClasses;
}
typedef std::vector<double> tNodeData;
std::map<int, tNodeData> Decision_Tree_Node_data = {
{ 1 , {0.257348537 }} ,
{ 2 , {-0.121567562 }}
};
int get_decision_tree_node_index(std::any Feature_0, std::any Feature_1, std::any Feature_2, std::any Feature_3, std::any Feature_4, std::any Feature_5, std::any Feature_6, std::any Feature_7, std::any Feature_8, std::any Feature_9, std::any Feature_10, std::any Feature_11, std::any Feature_12, std::any Feature_13, std::any Feature_14, std::any Feature_15, std::any Feature_16, std::any Feature_17, std::any Feature_18, std::any Feature_19, std::any Feature_20, std::any Feature_21, std::any Feature_22, std::any Feature_23, std::any Feature_24, std::any Feature_25, std::any Feature_26, std::any Feature_27, std::any Feature_28, std::any Feature_29) {
int lNodeIndex = ( Feature_26 < 0.224800006 ) ? ( 1 ) : ( 2 );
return lNodeIndex;
}
std::vector<std::string> get_input_names(){
std::vector<std::string> lFeatures = { "Feature_0", "Feature_1", "Feature_2", "Feature_3", "Feature_4", "Feature_5", "Feature_6", "Feature_7", "Feature_8", "Feature_9", "Feature_10", "Feature_11", "Feature_12", "Feature_13", "Feature_14", "Feature_15", "Feature_16", "Feature_17", "Feature_18", "Feature_19", "Feature_20", "Feature_21", "Feature_22", "Feature_23", "Feature_24", "Feature_25", "Feature_26", "Feature_27", "Feature_28", "Feature_29" };
return lFeatures;
}
std::vector<std::string> get_output_names(){
std::vector<std::string> lOutputs = {
"Score_0", "Score_1",
"Proba_0", "Proba_1",
"LogProba_0", "LogProba_1" };
return lOutputs;
}
tTable compute_classification_scores(std::any Feature_0, std::any Feature_1, std::any Feature_2, std::any Feature_3, std::any Feature_4, std::any Feature_5, std::any Feature_6, std::any Feature_7, std::any Feature_8, std::any Feature_9, std::any Feature_10, std::any Feature_11, std::any Feature_12, std::any Feature_13, std::any Feature_14, std::any Feature_15, std::any Feature_16, std::any Feature_17, std::any Feature_18, std::any Feature_19, std::any Feature_20, std::any Feature_21, std::any Feature_22, std::any Feature_23, std::any Feature_24, std::any Feature_25, std::any Feature_26, std::any Feature_27, std::any Feature_28, std::any Feature_29) {
auto lClasses = get_classes();
int lNodeIndex = get_decision_tree_node_index(Feature_0, Feature_1, Feature_2, Feature_3, Feature_4, Feature_5, Feature_6, Feature_7, Feature_8, Feature_9, Feature_10, Feature_11, Feature_12, Feature_13, Feature_14, Feature_15, Feature_16, Feature_17, Feature_18, Feature_19, Feature_20, Feature_21, Feature_22, Feature_23, Feature_24, Feature_25, Feature_26, Feature_27, Feature_28, Feature_29);
std::vector<double> lNodeValue = Decision_Tree_Node_data[ lNodeIndex ];
tTable lTable;
lTable["Score"] = {
lNodeValue [0],
1.0 - lNodeValue [0]
} ;
lTable["Proba"] = {
std::any(),
std::any()
} ;
recompute_log_probas( lTable );
return lTable;
}
tTable compute_model_outputs_from_table( tTable const & iTable) {
tTable lTable = compute_classification_scores(iTable.at("Feature_0")[0], iTable.at("Feature_1")[0], iTable.at("Feature_2")[0], iTable.at("Feature_3")[0], iTable.at("Feature_4")[0], iTable.at("Feature_5")[0], iTable.at("Feature_6")[0], iTable.at("Feature_7")[0], iTable.at("Feature_8")[0], iTable.at("Feature_9")[0], iTable.at("Feature_10")[0], iTable.at("Feature_11")[0], iTable.at("Feature_12")[0], iTable.at("Feature_13")[0], iTable.at("Feature_14")[0], iTable.at("Feature_15")[0], iTable.at("Feature_16")[0], iTable.at("Feature_17")[0], iTable.at("Feature_18")[0], iTable.at("Feature_19")[0], iTable.at("Feature_20")[0], iTable.at("Feature_21")[0], iTable.at("Feature_22")[0], iTable.at("Feature_23")[0], iTable.at("Feature_24")[0], iTable.at("Feature_25")[0], iTable.at("Feature_26")[0], iTable.at("Feature_27")[0], iTable.at("Feature_28")[0], iTable.at("Feature_29")[0]);
return lTable;
}
} // eof namespace XGB_Tree_0_9
namespace XGB_Tree_0_10 {
std::vector<std::any> get_classes(){
std::vector<std::any> lClasses = { 0, 1 };
return lClasses;
}
typedef std::vector<double> tNodeData;
std::map<int, tNodeData> Decision_Tree_Node_data = {
{ 1 , {0.271092504 }} ,
{ 2 , {-0.100576989 }}
};
int get_decision_tree_node_index(std::any Feature_0, std::any Feature_1, std::any Feature_2, std::any Feature_3, std::any Feature_4, std::any Feature_5, std::any Feature_6, std::any Feature_7, std::any Feature_8, std::any Feature_9, std::any Feature_10, std::any Feature_11, std::any Feature_12, std::any Feature_13, std::any Feature_14, std::any Feature_15, std::any Feature_16, std::any Feature_17, std::any Feature_18, std::any Feature_19, std::any Feature_20, std::any Feature_21, std::any Feature_22, std::any Feature_23, std::any Feature_24, std::any Feature_25, std::any Feature_26, std::any Feature_27, std::any Feature_28, std::any Feature_29) {
int lNodeIndex = ( Feature_21 < 23.0250015 ) ? ( 1 ) : ( 2 );
return lNodeIndex;
}
std::vector<std::string> get_input_names(){
std::vector<std::string> lFeatures = { "Feature_0", "Feature_1", "Feature_2", "Feature_3", "Feature_4", "Feature_5", "Feature_6", "Feature_7", "Feature_8", "Feature_9", "Feature_10", "Feature_11", "Feature_12", "Feature_13", "Feature_14", "Feature_15", "Feature_16", "Feature_17", "Feature_18", "Feature_19", "Feature_20", "Feature_21", "Feature_22", "Feature_23", "Feature_24", "Feature_25", "Feature_26", "Feature_27", "Feature_28", "Feature_29" };
return lFeatures;
}
std::vector<std::string> get_output_names(){
std::vector<std::string> lOutputs = {
"Score_0", "Score_1",
"Proba_0", "Proba_1",
"LogProba_0", "LogProba_1" };
return lOutputs;
}
tTable compute_classification_scores(std::any Feature_0, std::any Feature_1, std::any Feature_2, std::any Feature_3, std::any Feature_4, std::any Feature_5, std::any Feature_6, std::any Feature_7, std::any Feature_8, std::any Feature_9, std::any Feature_10, std::any Feature_11, std::any Feature_12, std::any Feature_13, std::any Feature_14, std::any Feature_15, std::any Feature_16, std::any Feature_17, std::any Feature_18, std::any Feature_19, std::any Feature_20, std::any Feature_21, std::any Feature_22, std::any Feature_23, std::any Feature_24, std::any Feature_25, std::any Feature_26, std::any Feature_27, std::any Feature_28, std::any Feature_29) {
auto lClasses = get_classes();
int lNodeIndex = get_decision_tree_node_index(Feature_0, Feature_1, Feature_2, Feature_3, Feature_4, Feature_5, Feature_6, Feature_7, Feature_8, Feature_9, Feature_10, Feature_11, Feature_12, Feature_13, Feature_14, Feature_15, Feature_16, Feature_17, Feature_18, Feature_19, Feature_20, Feature_21, Feature_22, Feature_23, Feature_24, Feature_25, Feature_26, Feature_27, Feature_28, Feature_29);
std::vector<double> lNodeValue = Decision_Tree_Node_data[ lNodeIndex ];
tTable lTable;
lTable["Score"] = {
lNodeValue [0],
1.0 - lNodeValue [0]
} ;
lTable["Proba"] = {
std::any(),
std::any()
} ;
recompute_log_probas( lTable );
return lTable;
}
tTable compute_model_outputs_from_table( tTable const & iTable) {
tTable lTable = compute_classification_scores(iTable.at("Feature_0")[0], iTable.at("Feature_1")[0], iTable.at("Feature_2")[0], iTable.at("Feature_3")[0], iTable.at("Feature_4")[0], iTable.at("Feature_5")[0], iTable.at("Feature_6")[0], iTable.at("Feature_7")[0], iTable.at("Feature_8")[0], iTable.at("Feature_9")[0], iTable.at("Feature_10")[0], iTable.at("Feature_11")[0], iTable.at("Feature_12")[0], iTable.at("Feature_13")[0], iTable.at("Feature_14")[0], iTable.at("Feature_15")[0], iTable.at("Feature_16")[0], iTable.at("Feature_17")[0], iTable.at("Feature_18")[0], iTable.at("Feature_19")[0], iTable.at("Feature_20")[0], iTable.at("Feature_21")[0], iTable.at("Feature_22")[0], iTable.at("Feature_23")[0], iTable.at("Feature_24")[0], iTable.at("Feature_25")[0], iTable.at("Feature_26")[0], iTable.at("Feature_27")[0], iTable.at("Feature_28")[0], iTable.at("Feature_29")[0]);
return lTable;
}
} // eof namespace XGB_Tree_0_10
namespace XGB_Tree_0_11 {
std::vector<std::any> get_classes(){
std::vector<std::any> lClasses = { 0, 1 };
return lClasses;
}
typedef std::vector<double> tNodeData;
std::map<int, tNodeData> Decision_Tree_Node_data = {
{ 1 , {0.172649145 }} ,
{ 2 , {-0.193059087 }}
};
int get_decision_tree_node_index(std::any Feature_0, std::any Feature_1, std::any Feature_2, std::any Feature_3, std::any Feature_4, std::any Feature_5, std::any Feature_6, std::any Feature_7, std::any Feature_8, std::any Feature_9, std::any Feature_10, std::any Feature_11, std::any Feature_12, std::any Feature_13, std::any Feature_14, std::any Feature_15, std::any Feature_16, std::any Feature_17, std::any Feature_18, std::any Feature_19, std::any Feature_20, std::any Feature_21, std::any Feature_22, std::any Feature_23, std::any Feature_24, std::any Feature_25, std::any Feature_26, std::any Feature_27, std::any Feature_28, std::any Feature_29) {
int lNodeIndex = ( Feature_13 < 34.4049988 ) ? ( 1 ) : ( 2 );
return lNodeIndex;
}
std::vector<std::string> get_input_names(){
std::vector<std::string> lFeatures = { "Feature_0", "Feature_1", "Feature_2", "Feature_3", "Feature_4", "Feature_5", "Feature_6", "Feature_7", "Feature_8", "Feature_9", "Feature_10", "Feature_11", "Feature_12", "Feature_13", "Feature_14", "Feature_15", "Feature_16", "Feature_17", "Feature_18", "Feature_19", "Feature_20", "Feature_21", "Feature_22", "Feature_23", "Feature_24", "Feature_25", "Feature_26", "Feature_27", "Feature_28", "Feature_29" };
return lFeatures;
}
std::vector<std::string> get_output_names(){
std::vector<std::string> lOutputs = {
"Score_0", "Score_1",
"Proba_0", "Proba_1",
"LogProba_0", "LogProba_1" };
return lOutputs;
}
tTable compute_classification_scores(std::any Feature_0, std::any Feature_1, std::any Feature_2, std::any Feature_3, std::any Feature_4, std::any Feature_5, std::any Feature_6, std::any Feature_7, std::any Feature_8, std::any Feature_9, std::any Feature_10, std::any Feature_11, std::any Feature_12, std::any Feature_13, std::any Feature_14, std::any Feature_15, std::any Feature_16, std::any Feature_17, std::any Feature_18, std::any Feature_19, std::any Feature_20, std::any Feature_21, std::any Feature_22, std::any Feature_23, std::any Feature_24, std::any Feature_25, std::any Feature_26, std::any Feature_27, std::any Feature_28, std::any Feature_29) {
auto lClasses = get_classes();
int lNodeIndex = get_decision_tree_node_index(Feature_0, Feature_1, Feature_2, Feature_3, Feature_4, Feature_5, Feature_6, Feature_7, Feature_8, Feature_9, Feature_10, Feature_11, Feature_12, Feature_13, Feature_14, Feature_15, Feature_16, Feature_17, Feature_18, Feature_19, Feature_20, Feature_21, Feature_22, Feature_23, Feature_24, Feature_25, Feature_26, Feature_27, Feature_28, Feature_29);
std::vector<double> lNodeValue = Decision_Tree_Node_data[ lNodeIndex ];
tTable lTable;
lTable["Score"] = {
lNodeValue [0],
1.0 - lNodeValue [0]
} ;
lTable["Proba"] = {
std::any(),
std::any()
} ;
recompute_log_probas( lTable );
return lTable;
}
tTable compute_model_outputs_from_table( tTable const & iTable) {
tTable lTable = compute_classification_scores(iTable.at("Feature_0")[0], iTable.at("Feature_1")[0], iTable.at("Feature_2")[0], iTable.at("Feature_3")[0], iTable.at("Feature_4")[0], iTable.at("Feature_5")[0], iTable.at("Feature_6")[0], iTable.at("Feature_7")[0], iTable.at("Feature_8")[0], iTable.at("Feature_9")[0], iTable.at("Feature_10")[0], iTable.at("Feature_11")[0], iTable.at("Feature_12")[0], iTable.at("Feature_13")[0], iTable.at("Feature_14")[0], iTable.at("Feature_15")[0], iTable.at("Feature_16")[0], iTable.at("Feature_17")[0], iTable.at("Feature_18")[0], iTable.at("Feature_19")[0], iTable.at("Feature_20")[0], iTable.at("Feature_21")[0], iTable.at("Feature_22")[0], iTable.at("Feature_23")[0], iTable.at("Feature_24")[0], iTable.at("Feature_25")[0], iTable.at("Feature_26")[0], iTable.at("Feature_27")[0], iTable.at("Feature_28")[0], iTable.at("Feature_29")[0]);
return lTable;
}
} // eof namespace XGB_Tree_0_11
namespace XGB_Tree_0_12 {
std::vector<std::any> get_classes(){
std::vector<std::any> lClasses = { 0, 1 };
return lClasses;
}
typedef std::vector<double> tNodeData;
std::map<int, tNodeData> Decision_Tree_Node_data = {
{ 1 , {0.181349665 }} ,
{ 2 , {-0.152797535 }}
};
int get_decision_tree_node_index(std::any Feature_0, std::any Feature_1, std::any Feature_2, std::any Feature_3, std::any Feature_4, std::any Feature_5, std::any Feature_6, std::any Feature_7, std::any Feature_8, std::any Feature_9, std::any Feature_10, std::any Feature_11, std::any Feature_12, std::any Feature_13, std::any Feature_14, std::any Feature_15, std::any Feature_16, std::any Feature_17, std::any Feature_18, std::any Feature_19, std::any Feature_20, std::any Feature_21, std::any Feature_22, std::any Feature_23, std::any Feature_24, std::any Feature_25, std::any Feature_26, std::any Feature_27, std::any Feature_28, std::any Feature_29) {
int lNodeIndex = ( Feature_27 < 0.130999997 ) ? ( 1 ) : ( 2 );
return lNodeIndex;
}
std::vector<std::string> get_input_names(){
std::vector<std::string> lFeatures = { "Feature_0", "Feature_1", "Feature_2", "Feature_3", "Feature_4", "Feature_5", "Feature_6", "Feature_7", "Feature_8", "Feature_9", "Feature_10", "Feature_11", "Feature_12", "Feature_13", "Feature_14", "Feature_15", "Feature_16", "Feature_17", "Feature_18", "Feature_19", "Feature_20", "Feature_21", "Feature_22", "Feature_23", "Feature_24", "Feature_25", "Feature_26", "Feature_27", "Feature_28", "Feature_29" };
return lFeatures;
}
std::vector<std::string> get_output_names(){
std::vector<std::string> lOutputs = {
"Score_0", "Score_1",
"Proba_0", "Proba_1",
"LogProba_0", "LogProba_1" };
return lOutputs;
}
tTable compute_classification_scores(std::any Feature_0, std::any Feature_1, std::any Feature_2, std::any Feature_3, std::any Feature_4, std::any Feature_5, std::any Feature_6, std::any Feature_7, std::any Feature_8, std::any Feature_9, std::any Feature_10, std::any Feature_11, std::any Feature_12, std::any Feature_13, std::any Feature_14, std::any Feature_15, std::any Feature_16, std::any Feature_17, std::any Feature_18, std::any Feature_19, std::any Feature_20, std::any Feature_21, std::any Feature_22, std::any Feature_23, std::any Feature_24, std::any Feature_25, std::any Feature_26, std::any Feature_27, std::any Feature_28, std::any Feature_29) {
auto lClasses = get_classes();
int lNodeIndex = get_decision_tree_node_index(Feature_0, Feature_1, Feature_2, Feature_3, Feature_4, Feature_5, Feature_6, Feature_7, Feature_8, Feature_9, Feature_10, Feature_11, Feature_12, Feature_13, Feature_14, Feature_15, Feature_16, Feature_17, Feature_18, Feature_19, Feature_20, Feature_21, Feature_22, Feature_23, Feature_24, Feature_25, Feature_26, Feature_27, Feature_28, Feature_29);
std::vector<double> lNodeValue = Decision_Tree_Node_data[ lNodeIndex ];
tTable lTable;
lTable["Score"] = {
lNodeValue [0],
1.0 - lNodeValue [0]
} ;
lTable["Proba"] = {
std::any(),
std::any()
} ;
recompute_log_probas( lTable );
return lTable;
}
tTable compute_model_outputs_from_table( tTable const & iTable) {
tTable lTable = compute_classification_scores(iTable.at("Feature_0")[0], iTable.at("Feature_1")[0], iTable.at("Feature_2")[0], iTable.at("Feature_3")[0], iTable.at("Feature_4")[0], iTable.at("Feature_5")[0], iTable.at("Feature_6")[0], iTable.at("Feature_7")[0], iTable.at("Feature_8")[0], iTable.at("Feature_9")[0], iTable.at("Feature_10")[0], iTable.at("Feature_11")[0], iTable.at("Feature_12")[0], iTable.at("Feature_13")[0], iTable.at("Feature_14")[0], iTable.at("Feature_15")[0], iTable.at("Feature_16")[0], iTable.at("Feature_17")[0], iTable.at("Feature_18")[0], iTable.at("Feature_19")[0], iTable.at("Feature_20")[0], iTable.at("Feature_21")[0], iTable.at("Feature_22")[0], iTable.at("Feature_23")[0], iTable.at("Feature_24")[0], iTable.at("Feature_25")[0], iTable.at("Feature_26")[0], iTable.at("Feature_27")[0], iTable.at("Feature_28")[0], iTable.at("Feature_29")[0]);
return lTable;
}
} // eof namespace XGB_Tree_0_12
namespace XGB_Tree_0_13 {
std::vector<std::any> get_classes(){
std::vector<std::any> lClasses = { 0, 1 };
return lClasses;
}
typedef std::vector<double> tNodeData;
std::map<int, tNodeData> Decision_Tree_Node_data = {
{ 1 , {0.153317034 }} ,
{ 2 , {-0.155450851 }}
};
int get_decision_tree_node_index(std::any Feature_0, std::any Feature_1, std::any Feature_2, std::any Feature_3, std::any Feature_4, std::any Feature_5, std::any Feature_6, std::any Feature_7, std::any Feature_8, std::any Feature_9, std::any Feature_10, std::any Feature_11, std::any Feature_12, std::any Feature_13, std::any Feature_14, std::any Feature_15, std::any Feature_16, std::any Feature_17, std::any Feature_18, std::any Feature_19, std::any Feature_20, std::any Feature_21, std::any Feature_22, std::any Feature_23, std::any Feature_24, std::any Feature_25, std::any Feature_26, std::any Feature_27, std::any Feature_28, std::any Feature_29) {
int lNodeIndex = ( Feature_23 < 822.849976 ) ? ( 1 ) : ( 2 );
return lNodeIndex;
}
std::vector<std::string> get_input_names(){
std::vector<std::string> lFeatures = { "Feature_0", "Feature_1", "Feature_2", "Feature_3", "Feature_4", "Feature_5", "Feature_6", "Feature_7", "Feature_8", "Feature_9", "Feature_10", "Feature_11", "Feature_12", "Feature_13", "Feature_14", "Feature_15", "Feature_16", "Feature_17", "Feature_18", "Feature_19", "Feature_20", "Feature_21", "Feature_22", "Feature_23", "Feature_24", "Feature_25", "Feature_26", "Feature_27", "Feature_28", "Feature_29" };
return lFeatures;
}
std::vector<std::string> get_output_names(){
std::vector<std::string> lOutputs = {
"Score_0", "Score_1",
"Proba_0", "Proba_1",
"LogProba_0", "LogProba_1" };
return lOutputs;
}
tTable compute_classification_scores(std::any Feature_0, std::any Feature_1, std::any Feature_2, std::any Feature_3, std::any Feature_4, std::any Feature_5, std::any Feature_6, std::any Feature_7, std::any Feature_8, std::any Feature_9, std::any Feature_10, std::any Feature_11, std::any Feature_12, std::any Feature_13, std::any Feature_14, std::any Feature_15, std::any Feature_16, std::any Feature_17, std::any Feature_18, std::any Feature_19, std::any Feature_20, std::any Feature_21, std::any Feature_22, std::any Feature_23, std::any Feature_24, std::any Feature_25, std::any Feature_26, std::any Feature_27, std::any Feature_28, std::any Feature_29) {
auto lClasses = get_classes();
int lNodeIndex = get_decision_tree_node_index(Feature_0, Feature_1, Feature_2, Feature_3, Feature_4, Feature_5, Feature_6, Feature_7, Feature_8, Feature_9, Feature_10, Feature_11, Feature_12, Feature_13, Feature_14, Feature_15, Feature_16, Feature_17, Feature_18, Feature_19, Feature_20, Feature_21, Feature_22, Feature_23, Feature_24, Feature_25, Feature_26, Feature_27, Feature_28, Feature_29);
std::vector<double> lNodeValue = Decision_Tree_Node_data[ lNodeIndex ];
tTable lTable;
lTable["Score"] = {
lNodeValue [0],
1.0 - lNodeValue [0]
} ;
lTable["Proba"] = {
std::any(),
std::any()
} ;
recompute_log_probas( lTable );
return lTable;
}
tTable compute_model_outputs_from_table( tTable const & iTable) {
tTable lTable = compute_classification_scores(iTable.at("Feature_0")[0], iTable.at("Feature_1")[0], iTable.at("Feature_2")[0], iTable.at("Feature_3")[0], iTable.at("Feature_4")[0], iTable.at("Feature_5")[0], iTable.at("Feature_6")[0], iTable.at("Feature_7")[0], iTable.at("Feature_8")[0], iTable.at("Feature_9")[0], iTable.at("Feature_10")[0], iTable.at("Feature_11")[0], iTable.at("Feature_12")[0], iTable.at("Feature_13")[0], iTable.at("Feature_14")[0], iTable.at("Feature_15")[0], iTable.at("Feature_16")[0], iTable.at("Feature_17")[0], iTable.at("Feature_18")[0], iTable.at("Feature_19")[0], iTable.at("Feature_20")[0], iTable.at("Feature_21")[0], iTable.at("Feature_22")[0], iTable.at("Feature_23")[0], iTable.at("Feature_24")[0], iTable.at("Feature_25")[0], iTable.at("Feature_26")[0], iTable.at("Feature_27")[0], iTable.at("Feature_28")[0], iTable.at("Feature_29")[0]);
return lTable;
}
} // eof namespace XGB_Tree_0_13
namespace XGB_Tree_0_14 {
std::vector<std::any> get_classes(){
std::vector<std::any> lClasses = { 0, 1 };
return lClasses;
}
typedef std::vector<double> tNodeData;
std::map<int, tNodeData> Decision_Tree_Node_data = {
{ 1 , {0.153998569 }} ,
{ 2 , {-0.142487958 }}
};
int get_decision_tree_node_index(std::any Feature_0, std::any Feature_1, std::any Feature_2, std::any Feature_3, std::any Feature_4, std::any Feature_5, std::any Feature_6, std::any Feature_7, std::any Feature_8, std::any Feature_9, std::any Feature_10, std::any Feature_11, std::any Feature_12, std::any Feature_13, std::any Feature_14, std::any Feature_15, std::any Feature_16, std::any Feature_17, std::any Feature_18, std::any Feature_19, std::any Feature_20, std::any Feature_21, std::any Feature_22, std::any Feature_23, std::any Feature_24, std::any Feature_25, std::any Feature_26, std::any Feature_27, std::any Feature_28, std::any Feature_29) {
int lNodeIndex = ( Feature_1 < 19.4699993 ) ? ( 1 ) : ( 2 );
return lNodeIndex;
}
std::vector<std::string> get_input_names(){
std::vector<std::string> lFeatures = { "Feature_0", "Feature_1", "Feature_2", "Feature_3", "Feature_4", "Feature_5", "Feature_6", "Feature_7", "Feature_8", "Feature_9", "Feature_10", "Feature_11", "Feature_12", "Feature_13", "Feature_14", "Feature_15", "Feature_16", "Feature_17", "Feature_18", "Feature_19", "Feature_20", "Feature_21", "Feature_22", "Feature_23", "Feature_24", "Feature_25", "Feature_26", "Feature_27", "Feature_28", "Feature_29" };
return lFeatures;
}
std::vector<std::string> get_output_names(){
std::vector<std::string> lOutputs = {
"Score_0", "Score_1",
"Proba_0", "Proba_1",
"LogProba_0", "LogProba_1" };
return lOutputs;
}
tTable compute_classification_scores(std::any Feature_0, std::any Feature_1, std::any Feature_2, std::any Feature_3, std::any Feature_4, std::any Feature_5, std::any Feature_6, std::any Feature_7, std::any Feature_8, std::any Feature_9, std::any Feature_10, std::any Feature_11, std::any Feature_12, std::any Feature_13, std::any Feature_14, std::any Feature_15, std::any Feature_16, std::any Feature_17, std::any Feature_18, std::any Feature_19, std::any Feature_20, std::any Feature_21, std::any Feature_22, std::any Feature_23, std::any Feature_24, std::any Feature_25, std::any Feature_26, std::any Feature_27, std::any Feature_28, std::any Feature_29) {
auto lClasses = get_classes();
int lNodeIndex = get_decision_tree_node_index(Feature_0, Feature_1, Feature_2, Feature_3, Feature_4, Feature_5, Feature_6, Feature_7, Feature_8, Feature_9, Feature_10, Feature_11, Feature_12, Feature_13, Feature_14, Feature_15, Feature_16, Feature_17, Feature_18, Feature_19, Feature_20, Feature_21, Feature_22, Feature_23, Feature_24, Feature_25, Feature_26, Feature_27, Feature_28, Feature_29);
std::vector<double> lNodeValue = Decision_Tree_Node_data[ lNodeIndex ];
tTable lTable;
lTable["Score"] = {
lNodeValue [0],
1.0 - lNodeValue [0]
} ;
lTable["Proba"] = {
std::any(),
std::any()
} ;
recompute_log_probas( lTable );
return lTable;
}
tTable compute_model_outputs_from_table( tTable const & iTable) {
tTable lTable = compute_classification_scores(iTable.at("Feature_0")[0], iTable.at("Feature_1")[0], iTable.at("Feature_2")[0], iTable.at("Feature_3")[0], iTable.at("Feature_4")[0], iTable.at("Feature_5")[0], iTable.at("Feature_6")[0], iTable.at("Feature_7")[0], iTable.at("Feature_8")[0], iTable.at("Feature_9")[0], iTable.at("Feature_10")[0], iTable.at("Feature_11")[0], iTable.at("Feature_12")[0], iTable.at("Feature_13")[0], iTable.at("Feature_14")[0], iTable.at("Feature_15")[0], iTable.at("Feature_16")[0], iTable.at("Feature_17")[0], iTable.at("Feature_18")[0], iTable.at("Feature_19")[0], iTable.at("Feature_20")[0], iTable.at("Feature_21")[0], iTable.at("Feature_22")[0], iTable.at("Feature_23")[0], iTable.at("Feature_24")[0], iTable.at("Feature_25")[0], iTable.at("Feature_26")[0], iTable.at("Feature_27")[0], iTable.at("Feature_28")[0], iTable.at("Feature_29")[0]);
return lTable;
}
} // eof namespace XGB_Tree_0_14
namespace XGB_Tree_0_15 {
std::vector<std::any> get_classes(){
std::vector<std::any> lClasses = { 0, 1 };
return lClasses;
}
typedef std::vector<double> tNodeData;
std::map<int, tNodeData> Decision_Tree_Node_data = {
{ 1 , {0.141609788 }} ,
{ 2 , {-0.121677577 }}
};
int get_decision_tree_node_index(std::any Feature_0, std::any Feature_1, std::any Feature_2, std::any Feature_3, std::any Feature_4, std::any Feature_5, std::any Feature_6, std::any Feature_7, std::any Feature_8, std::any Feature_9, std::any Feature_10, std::any Feature_11, std::any Feature_12, std::any Feature_13, std::any Feature_14, std::any Feature_15, std::any Feature_16, std::any Feature_17, std::any Feature_18, std::any Feature_19, std::any Feature_20, std::any Feature_21, std::any Feature_22, std::any Feature_23, std::any Feature_24, std::any Feature_25, std::any Feature_26, std::any Feature_27, std::any Feature_28, std::any Feature_29) {
int lNodeIndex = ( Feature_27 < 0.130999997 ) ? ( 1 ) : ( 2 );
return lNodeIndex;
}
std::vector<std::string> get_input_names(){
std::vector<std::string> lFeatures = { "Feature_0", "Feature_1", "Feature_2", "Feature_3", "Feature_4", "Feature_5", "Feature_6", "Feature_7", "Feature_8", "Feature_9", "Feature_10", "Feature_11", "Feature_12", "Feature_13", "Feature_14", "Feature_15", "Feature_16", "Feature_17", "Feature_18", "Feature_19", "Feature_20", "Feature_21", "Feature_22", "Feature_23", "Feature_24", "Feature_25", "Feature_26", "Feature_27", "Feature_28", "Feature_29" };
return lFeatures;
}
std::vector<std::string> get_output_names(){
std::vector<std::string> lOutputs = {
"Score_0", "Score_1",
"Proba_0", "Proba_1",
"LogProba_0", "LogProba_1" };
return lOutputs;
}
tTable compute_classification_scores(std::any Feature_0, std::any Feature_1, std::any Feature_2, std::any Feature_3, std::any Feature_4, std::any Feature_5, std::any Feature_6, std::any Feature_7, std::any Feature_8, std::any Feature_9, std::any Feature_10, std::any Feature_11, std::any Feature_12, std::any Feature_13, std::any Feature_14, std::any Feature_15, std::any Feature_16, std::any Feature_17, std::any Feature_18, std::any Feature_19, std::any Feature_20, std::any Feature_21, std::any Feature_22, std::any Feature_23, std::any Feature_24, std::any Feature_25, std::any Feature_26, std::any Feature_27, std::any Feature_28, std::any Feature_29) {
auto lClasses = get_classes();
int lNodeIndex = get_decision_tree_node_index(Feature_0, Feature_1, Feature_2, Feature_3, Feature_4, Feature_5, Feature_6, Feature_7, Feature_8, Feature_9, Feature_10, Feature_11, Feature_12, Feature_13, Feature_14, Feature_15, Feature_16, Feature_17, Feature_18, Feature_19, Feature_20, Feature_21, Feature_22, Feature_23, Feature_24, Feature_25, Feature_26, Feature_27, Feature_28, Feature_29);
std::vector<double> lNodeValue = Decision_Tree_Node_data[ lNodeIndex ];
tTable lTable;
lTable["Score"] = {
lNodeValue [0],
1.0 - lNodeValue [0]
} ;
lTable["Proba"] = {
std::any(),
std::any()
} ;
recompute_log_probas( lTable );
return lTable;
}
tTable compute_model_outputs_from_table( tTable const & iTable) {
tTable lTable = compute_classification_scores(iTable.at("Feature_0")[0], iTable.at("Feature_1")[0], iTable.at("Feature_2")[0], iTable.at("Feature_3")[0], iTable.at("Feature_4")[0], iTable.at("Feature_5")[0], iTable.at("Feature_6")[0], iTable.at("Feature_7")[0], iTable.at("Feature_8")[0], iTable.at("Feature_9")[0], iTable.at("Feature_10")[0], iTable.at("Feature_11")[0], iTable.at("Feature_12")[0], iTable.at("Feature_13")[0], iTable.at("Feature_14")[0], iTable.at("Feature_15")[0], iTable.at("Feature_16")[0], iTable.at("Feature_17")[0], iTable.at("Feature_18")[0], iTable.at("Feature_19")[0], iTable.at("Feature_20")[0], iTable.at("Feature_21")[0], iTable.at("Feature_22")[0], iTable.at("Feature_23")[0], iTable.at("Feature_24")[0], iTable.at("Feature_25")[0], iTable.at("Feature_26")[0], iTable.at("Feature_27")[0], iTable.at("Feature_28")[0], iTable.at("Feature_29")[0]);
return lTable;
}
} // eof namespace XGB_Tree_0_15
std::vector<std::string> get_input_names(){
std::vector<std::string> lFeatures = { "Feature_0", "Feature_1", "Feature_2", "Feature_3", "Feature_4", "Feature_5", "Feature_6", "Feature_7", "Feature_8", "Feature_9", "Feature_10", "Feature_11", "Feature_12", "Feature_13", "Feature_14", "Feature_15", "Feature_16", "Feature_17", "Feature_18", "Feature_19", "Feature_20", "Feature_21", "Feature_22", "Feature_23", "Feature_24", "Feature_25", "Feature_26", "Feature_27", "Feature_28", "Feature_29" };
return lFeatures;
}
std::vector<std::string> get_output_names(){
std::vector<std::string> lOutputs = {
"Score_0", "Score_1",
"Proba_0", "Proba_1",
"LogProba_0", "LogProba_1",
"Decision", "DecisionProba" };
return lOutputs;
}
tTable compute_classification_scores(std::any Feature_0, std::any Feature_1, std::any Feature_2, std::any Feature_3, std::any Feature_4, std::any Feature_5, std::any Feature_6, std::any Feature_7, std::any Feature_8, std::any Feature_9, std::any Feature_10, std::any Feature_11, std::any Feature_12, std::any Feature_13, std::any Feature_14, std::any Feature_15, std::any Feature_16, std::any Feature_17, std::any Feature_18, std::any Feature_19, std::any Feature_20, std::any Feature_21, std::any Feature_22, std::any Feature_23, std::any Feature_24, std::any Feature_25, std::any Feature_26, std::any Feature_27, std::any Feature_28, std::any Feature_29) {
auto lClasses = get_classes();
std::vector<tTable> lTreeScores = {
XGB_Tree_0_0::compute_classification_scores(Feature_0, Feature_1, Feature_2, Feature_3, Feature_4, Feature_5, Feature_6, Feature_7, Feature_8, Feature_9, Feature_10, Feature_11, Feature_12, Feature_13, Feature_14, Feature_15, Feature_16, Feature_17, Feature_18, Feature_19, Feature_20, Feature_21, Feature_22, Feature_23, Feature_24, Feature_25, Feature_26, Feature_27, Feature_28, Feature_29),
XGB_Tree_0_1::compute_classification_scores(Feature_0, Feature_1, Feature_2, Feature_3, Feature_4, Feature_5, Feature_6, Feature_7, Feature_8, Feature_9, Feature_10, Feature_11, Feature_12, Feature_13, Feature_14, Feature_15, Feature_16, Feature_17, Feature_18, Feature_19, Feature_20, Feature_21, Feature_22, Feature_23, Feature_24, Feature_25, Feature_26, Feature_27, Feature_28, Feature_29),
XGB_Tree_0_2::compute_classification_scores(Feature_0, Feature_1, Feature_2, Feature_3, Feature_4, Feature_5, Feature_6, Feature_7, Feature_8, Feature_9, Feature_10, Feature_11, Feature_12, Feature_13, Feature_14, Feature_15, Feature_16, Feature_17, Feature_18, Feature_19, Feature_20, Feature_21, Feature_22, Feature_23, Feature_24, Feature_25, Feature_26, Feature_27, Feature_28, Feature_29),
XGB_Tree_0_3::compute_classification_scores(Feature_0, Feature_1, Feature_2, Feature_3, Feature_4, Feature_5, Feature_6, Feature_7, Feature_8, Feature_9, Feature_10, Feature_11, Feature_12, Feature_13, Feature_14, Feature_15, Feature_16, Feature_17, Feature_18, Feature_19, Feature_20, Feature_21, Feature_22, Feature_23, Feature_24, Feature_25, Feature_26, Feature_27, Feature_28, Feature_29),
XGB_Tree_0_4::compute_classification_scores(Feature_0, Feature_1, Feature_2, Feature_3, Feature_4, Feature_5, Feature_6, Feature_7, Feature_8, Feature_9, Feature_10, Feature_11, Feature_12, Feature_13, Feature_14, Feature_15, Feature_16, Feature_17, Feature_18, Feature_19, Feature_20, Feature_21, Feature_22, Feature_23, Feature_24, Feature_25, Feature_26, Feature_27, Feature_28, Feature_29),
XGB_Tree_0_5::compute_classification_scores(Feature_0, Feature_1, Feature_2, Feature_3, Feature_4, Feature_5, Feature_6, Feature_7, Feature_8, Feature_9, Feature_10, Feature_11, Feature_12, Feature_13, Feature_14, Feature_15, Feature_16, Feature_17, Feature_18, Feature_19, Feature_20, Feature_21, Feature_22, Feature_23, Feature_24, Feature_25, Feature_26, Feature_27, Feature_28, Feature_29),
XGB_Tree_0_6::compute_classification_scores(Feature_0, Feature_1, Feature_2, Feature_3, Feature_4, Feature_5, Feature_6, Feature_7, Feature_8, Feature_9, Feature_10, Feature_11, Feature_12, Feature_13, Feature_14, Feature_15, Feature_16, Feature_17, Feature_18, Feature_19, Feature_20, Feature_21, Feature_22, Feature_23, Feature_24, Feature_25, Feature_26, Feature_27, Feature_28, Feature_29),
XGB_Tree_0_7::compute_classification_scores(Feature_0, Feature_1, Feature_2, Feature_3, Feature_4, Feature_5, Feature_6, Feature_7, Feature_8, Feature_9, Feature_10, Feature_11, Feature_12, Feature_13, Feature_14, Feature_15, Feature_16, Feature_17, Feature_18, Feature_19, Feature_20, Feature_21, Feature_22, Feature_23, Feature_24, Feature_25, Feature_26, Feature_27, Feature_28, Feature_29),
XGB_Tree_0_8::compute_classification_scores(Feature_0, Feature_1, Feature_2, Feature_3, Feature_4, Feature_5, Feature_6, Feature_7, Feature_8, Feature_9, Feature_10, Feature_11, Feature_12, Feature_13, Feature_14, Feature_15, Feature_16, Feature_17, Feature_18, Feature_19, Feature_20, Feature_21, Feature_22, Feature_23, Feature_24, Feature_25, Feature_26, Feature_27, Feature_28, Feature_29),
XGB_Tree_0_9::compute_classification_scores(Feature_0, Feature_1, Feature_2, Feature_3, Feature_4, Feature_5, Feature_6, Feature_7, Feature_8, Feature_9, Feature_10, Feature_11, Feature_12, Feature_13, Feature_14, Feature_15, Feature_16, Feature_17, Feature_18, Feature_19, Feature_20, Feature_21, Feature_22, Feature_23, Feature_24, Feature_25, Feature_26, Feature_27, Feature_28, Feature_29),
XGB_Tree_0_10::compute_classification_scores(Feature_0, Feature_1, Feature_2, Feature_3, Feature_4, Feature_5, Feature_6, Feature_7, Feature_8, Feature_9, Feature_10, Feature_11, Feature_12, Feature_13, Feature_14, Feature_15, Feature_16, Feature_17, Feature_18, Feature_19, Feature_20, Feature_21, Feature_22, Feature_23, Feature_24, Feature_25, Feature_26, Feature_27, Feature_28, Feature_29),
XGB_Tree_0_11::compute_classification_scores(Feature_0, Feature_1, Feature_2, Feature_3, Feature_4, Feature_5, Feature_6, Feature_7, Feature_8, Feature_9, Feature_10, Feature_11, Feature_12, Feature_13, Feature_14, Feature_15, Feature_16, Feature_17, Feature_18, Feature_19, Feature_20, Feature_21, Feature_22, Feature_23, Feature_24, Feature_25, Feature_26, Feature_27, Feature_28, Feature_29),
XGB_Tree_0_12::compute_classification_scores(Feature_0, Feature_1, Feature_2, Feature_3, Feature_4, Feature_5, Feature_6, Feature_7, Feature_8, Feature_9, Feature_10, Feature_11, Feature_12, Feature_13, Feature_14, Feature_15, Feature_16, Feature_17, Feature_18, Feature_19, Feature_20, Feature_21, Feature_22, Feature_23, Feature_24, Feature_25, Feature_26, Feature_27, Feature_28, Feature_29),
XGB_Tree_0_13::compute_classification_scores(Feature_0, Feature_1, Feature_2, Feature_3, Feature_4, Feature_5, Feature_6, Feature_7, Feature_8, Feature_9, Feature_10, Feature_11, Feature_12, Feature_13, Feature_14, Feature_15, Feature_16, Feature_17, Feature_18, Feature_19, Feature_20, Feature_21, Feature_22, Feature_23, Feature_24, Feature_25, Feature_26, Feature_27, Feature_28, Feature_29),
XGB_Tree_0_14::compute_classification_scores(Feature_0, Feature_1, Feature_2, Feature_3, Feature_4, Feature_5, Feature_6, Feature_7, Feature_8, Feature_9, Feature_10, Feature_11, Feature_12, Feature_13, Feature_14, Feature_15, Feature_16, Feature_17, Feature_18, Feature_19, Feature_20, Feature_21, Feature_22, Feature_23, Feature_24, Feature_25, Feature_26, Feature_27, Feature_28, Feature_29),
XGB_Tree_0_15::compute_classification_scores(Feature_0, Feature_1, Feature_2, Feature_3, Feature_4, Feature_5, Feature_6, Feature_7, Feature_8, Feature_9, Feature_10, Feature_11, Feature_12, Feature_13, Feature_14, Feature_15, Feature_16, Feature_17, Feature_18, Feature_19, Feature_20, Feature_21, Feature_22, Feature_23, Feature_24, Feature_25, Feature_26, Feature_27, Feature_28, Feature_29)
};
tTable lAggregatedTable = aggregate_xgb_scores(lTreeScores, {"Score"});
tTable lTable;
lTable["Score"] = {
std::any(),
std::any()
} ;
lTable["Proba"] = {
1.0 - logistic(lAggregatedTable["Score"][0]),
logistic(lAggregatedTable["Score"][0])
} ;
int lBestClass = get_arg_max( lTable["Proba"] );
auto lDecision = lClasses[lBestClass];
lTable["Decision"] = { lDecision } ;
lTable["DecisionProba"] = { lTable["Proba"][lBestClass] };
recompute_log_probas( lTable );
return lTable;
}
tTable compute_model_outputs_from_table( tTable const & iTable) {
tTable lTable = compute_classification_scores(iTable.at("Feature_0")[0], iTable.at("Feature_1")[0], iTable.at("Feature_2")[0], iTable.at("Feature_3")[0], iTable.at("Feature_4")[0], iTable.at("Feature_5")[0], iTable.at("Feature_6")[0], iTable.at("Feature_7")[0], iTable.at("Feature_8")[0], iTable.at("Feature_9")[0], iTable.at("Feature_10")[0], iTable.at("Feature_11")[0], iTable.at("Feature_12")[0], iTable.at("Feature_13")[0], iTable.at("Feature_14")[0], iTable.at("Feature_15")[0], iTable.at("Feature_16")[0], iTable.at("Feature_17")[0], iTable.at("Feature_18")[0], iTable.at("Feature_19")[0], iTable.at("Feature_20")[0], iTable.at("Feature_21")[0], iTable.at("Feature_22")[0], iTable.at("Feature_23")[0], iTable.at("Feature_24")[0], iTable.at("Feature_25")[0], iTable.at("Feature_26")[0], iTable.at("Feature_27")[0], iTable.at("Feature_28")[0], iTable.at("Feature_29")[0]);
return lTable;
}
} // eof namespace
int main() {
score_csv_file("outputs/ml2cpp-demo/datasets/BreastCancer.csv");
return 0;
}
| 63.495942 | 879 | 0.705294 | antoinecarme |
9cf1ff5ce94f952820716473210d2675e3b89cc1 | 543 | cpp | C++ | Day-08/Day-08-CodeForces/492B-VanyaAndLanterns.cpp | LawranceMichaelite/100-Days-of-Code | de80015c2ab7c94956d4fe39f6e143627cdd7bc9 | [
"Apache-2.0"
] | null | null | null | Day-08/Day-08-CodeForces/492B-VanyaAndLanterns.cpp | LawranceMichaelite/100-Days-of-Code | de80015c2ab7c94956d4fe39f6e143627cdd7bc9 | [
"Apache-2.0"
] | null | null | null | Day-08/Day-08-CodeForces/492B-VanyaAndLanterns.cpp | LawranceMichaelite/100-Days-of-Code | de80015c2ab7c94956d4fe39f6e143627cdd7bc9 | [
"Apache-2.0"
] | null | null | null | #include<bits/stdc++.h>
using namespace std;
int main()
{
int num , atMost ;
cin >> num >> atMost ;
vector<double>ans(num , 0.0);
for(int i = 0; i < num ; i++)
{
cin >> ans[i];
}
sort(ans.begin(),ans.end());
double max_dist = 0.0;
for(int i = 0 ; i < num-1 ; i++)
{
if(ans[i+1]-ans[i] > max_dist)
max_dist = ans[i+1]-ans[i];
}
max_dist = max(max_dist/2 , max(ans[0]-0 , atMost-ans[num-1]));
cout << fixed << setprecision(10) << max_dist << endl;
return 0;
}
| 22.625 | 67 | 0.499079 | LawranceMichaelite |
9cf3494c496be8d4a09de63ab8d54bd69a6d7f72 | 3,541 | hpp | C++ | hwlib_examples/hwlib/hwlib-pin.hpp | DavidDriessen/IPASS-MFRC522 | 283b0aecce704b0df367a57ac6923ab51b788056 | [
"BSL-1.0"
] | null | null | null | hwlib_examples/hwlib/hwlib-pin.hpp | DavidDriessen/IPASS-MFRC522 | 283b0aecce704b0df367a57ac6923ab51b788056 | [
"BSL-1.0"
] | null | null | null | hwlib_examples/hwlib/hwlib-pin.hpp | DavidDriessen/IPASS-MFRC522 | 283b0aecce704b0df367a57ac6923ab51b788056 | [
"BSL-1.0"
] | null | null | null | // ==========================================================================
//
// File : hwlib-pin.hpp
// Part of : hwlib library for V1OOPC and V1IPAS
// Copyright : wouter@voti.nl 2016
//
// Distributed under the Boost Software License, Version 1.0.
// (See accompanying file LICENSE_1_0.txt or copy at
// http://www.boost.org/LICENSE_1_0.txt)
//
// ==========================================================================
/// @file
#ifndef HWLIB_PIN_H
#define HWLIB_PIN_H
#include "hwlib-wait.hpp"
namespace hwlib {
/// input pin interface
//
/// This class abstracts the interface for an input-only pin.
class pin_in {
public:
/// read the pin
//
/// This function returns the level of the pin.
/// When the pin level is high the value true is returned,
/// when the pin level is low the value false is returned.
virtual bool get() = 0;
};
/// output pin interface
//
/// This class abstracts the interface for an output-only pin.
class pin_out {
public:
/// write the pin
//
/// This function sets the level of the pin to
/// the value v. A value of true makes the pin high, a value of
/// false makes it low.
virtual void set( bool v ) = 0;
};
/// input/output pin interface
//
/// This class abstracts the interface for an input/output pin.
class pin_in_out {
public:
/// set the direction of a pin to input.
//
/// Calling this function sets the pin identified by p to input.
virtual void direction_set_input() = 0;
/// read the pin
//
/// This function returns the level of the pin.
/// When the pin level is high the value true is returned,
/// when the pin level is low the value false is returned.
///
/// Before calling this function the pin direction must have been
/// set to input by calling direction_set_input().
virtual bool get() = 0;
/// set the direction of a pin to output
//
/// Calling this function sets the pin identified by p to output.
virtual void direction_set_output() = 0;
/// write the pin
//
/// This function sets the level of the pin to
/// the value v. A value of true makes the pin high, a value of
/// false makes it low.
///
/// Before calling this function the pin direction must have been
/// set to output by calling direction_set_output().
virtual void set( bool x ) = 0;
};
/// open-collector input/output pin interface
//
/// This class abstracts the interface for
/// an open-collector input/output pin.
class pin_oc {
public:
/// read the pin
//
/// This function returns the level of the pin.
/// When the pin level is high the value true is returned,
/// when the pin level is low the value false is returned.
///
/// This function can be called after set( false ) has been called
/// on the pin, but then the level will read low (false).
/// Call set( true ) to let the line float
/// (presumably pulled high by a pull-up resistor)
/// to read the level put on the line by
/// an external device.
virtual bool get() = 0;
/// write the pin
//
/// This function sets the level of the pin to
/// the value v. A value of true makes the pin hihg-impedance
/// (presumably pulled high by a pull-up resistor),
/// a value of false makes it low.
virtual void set( bool x ) = 0;
};
/*
class pin_oc_from_out {
private:
pin_out & pin;
public:
pin_oc_from_out( pin_out & pin ):
pin{ pin }
{
}
};
*/
}; // namespace hwlib
#endif // HWLIB_PIN_H | 26.22963 | 77 | 0.620164 | DavidDriessen |
9cf4f4d54a34373d40e5e0a366a6396a2e2110f4 | 2,608 | cpp | C++ | src/game/shared/cstrike/hegrenade_projectile.cpp | DeadZoneLuna/csso-src | 6c978ea304ee2df3796bc9c0d2916bac550050d5 | [
"Unlicense"
] | 3 | 2020-12-15T23:09:28.000Z | 2022-01-13T15:55:04.000Z | src/game/shared/cstrike/hegrenade_projectile.cpp | DeadZoneLuna/csso-src | 6c978ea304ee2df3796bc9c0d2916bac550050d5 | [
"Unlicense"
] | null | null | null | src/game/shared/cstrike/hegrenade_projectile.cpp | DeadZoneLuna/csso-src | 6c978ea304ee2df3796bc9c0d2916bac550050d5 | [
"Unlicense"
] | 2 | 2021-12-30T02:28:31.000Z | 2022-03-05T08:34:15.000Z | //========= Copyright Valve Corporation, All rights reserved. ============//
//
// Purpose:
//
//=============================================================================//
#include "cbase.h"
#include "hegrenade_projectile.h"
#include "soundent.h"
#include "cs_player.h"
#include "KeyValues.h"
#include "weapon_csbase.h"
#define GRENADE_MODEL "models/weapons/w_eq_fraggrenade_thrown.mdl"
LINK_ENTITY_TO_CLASS( hegrenade_projectile, CHEGrenadeProjectile );
PRECACHE_WEAPON_REGISTER( hegrenade_projectile );
CHEGrenadeProjectile* CHEGrenadeProjectile::Create(
const Vector &position,
const QAngle &angles,
const Vector &velocity,
const AngularImpulse &angVelocity,
CBaseCombatCharacter *pOwner,
float timer )
{
CHEGrenadeProjectile *pGrenade = (CHEGrenadeProjectile*)CBaseEntity::Create( "hegrenade_projectile", position, angles, pOwner );
// Set the timer for 1 second less than requested. We're going to issue a SOUND_DANGER
// one second before detonation.
pGrenade->SetDetonateTimerLength( 1.5 );
pGrenade->SetAbsVelocity( velocity );
pGrenade->SetupInitialTransmittedGrenadeVelocity( velocity );
pGrenade->SetThrower( pOwner );
pGrenade->SetGravity( BaseClass::GetGrenadeGravity() );
pGrenade->SetFriction( BaseClass::GetGrenadeFriction() );
pGrenade->SetElasticity( BaseClass::GetGrenadeElasticity() );
pGrenade->m_flDamage = 100;
pGrenade->m_DmgRadius = pGrenade->m_flDamage * 3.5f;
pGrenade->ChangeTeam( pOwner->GetTeamNumber() );
pGrenade->ApplyLocalAngularVelocityImpulse( angVelocity );
// make NPCs afaid of it while in the air
pGrenade->SetThink( &CHEGrenadeProjectile::DangerSoundThink );
pGrenade->SetNextThink( gpGlobals->curtime );
pGrenade->m_pWeaponInfo = GetWeaponInfo( WEAPON_HEGRENADE );
return pGrenade;
}
void CHEGrenadeProjectile::Spawn()
{
SetModel( GRENADE_MODEL );
BaseClass::Spawn();
}
void CHEGrenadeProjectile::Precache()
{
PrecacheModel( GRENADE_MODEL );
PrecacheScriptSound( "HEGrenade.Bounce" );
BaseClass::Precache();
}
void CHEGrenadeProjectile::BounceSound( void )
{
EmitSound( "HEGrenade.Bounce" );
}
void CHEGrenadeProjectile::Detonate()
{
BaseClass::Detonate();
// tell the bots an HE grenade has exploded
CCSPlayer *player = ToCSPlayer(GetThrower());
if ( player )
{
IGameEvent * event = gameeventmanager->CreateEvent( "hegrenade_detonate" );
if ( event )
{
event->SetInt( "userid", player->GetUserID() );
event->SetFloat( "x", GetAbsOrigin().x );
event->SetFloat( "y", GetAbsOrigin().y );
event->SetFloat( "z", GetAbsOrigin().z );
gameeventmanager->FireEvent( event );
}
}
}
| 27.452632 | 129 | 0.716641 | DeadZoneLuna |
9cf5a2016c9919d128baac752b11f9053840225c | 924 | cpp | C++ | rdma/UdQueuePair.cpp | pfent/exchangeableTransports | a17ddcf99eba16b401df8f0865c1264e11c15c85 | [
"MIT"
] | 32 | 2018-12-14T16:54:11.000Z | 2022-02-28T13:07:17.000Z | rdma/UdQueuePair.cpp | pfent/exchangeableTransports | a17ddcf99eba16b401df8f0865c1264e11c15c85 | [
"MIT"
] | null | null | null | rdma/UdQueuePair.cpp | pfent/exchangeableTransports | a17ddcf99eba16b401df8f0865c1264e11c15c85 | [
"MIT"
] | 5 | 2020-05-25T07:05:29.000Z | 2022-03-05T02:59:38.000Z | #include "UdQueuePair.h"
void rdma::UdQueuePair::connect(const rdma::Address &) {
connect(defaultPort);
}
void rdma::UdQueuePair::connect(uint8_t port, uint32_t packetSequenceNumber) {
using Mod = ibv::queuepair::AttrMask;
{
ibv::queuepair::Attributes attr{};
attr.setQpState(ibv::queuepair::State::INIT);
attr.setPkeyIndex(0);
attr.setPortNum(port);
attr.setQkey(0x22222222); // todo: bad magic constant
qp->modify(attr, {Mod::STATE, Mod::PKEY_INDEX, Mod::PORT, Mod::QKEY});
}
{ // RTR
ibv::queuepair::Attributes attr{};
attr.setQpState(ibv::queuepair::State::RTR);
qp->modify(attr, {Mod::STATE});
}
{ // RTS
ibv::queuepair::Attributes attr{};
attr.setQpState(ibv::queuepair::State::RTS);
attr.setSqPsn(packetSequenceNumber);
qp->modify(attr, {Mod::STATE, Mod::SQ_PSN});
}
}
| 26.4 | 78 | 0.609307 | pfent |
9cf6c32549d863e360858d3e90445c96c91a2ac7 | 2,417 | cpp | C++ | examples/priority-schedule.cpp | dan65prc/conduit | 6f73416c8b5526a84a21415d5079bb2b61772144 | [
"BSD-3-Clause"
] | 5 | 2018-08-01T02:52:11.000Z | 2020-09-19T08:12:07.000Z | examples/priority-schedule.cpp | dan65prc/conduit | 6f73416c8b5526a84a21415d5079bb2b61772144 | [
"BSD-3-Clause"
] | null | null | null | examples/priority-schedule.cpp | dan65prc/conduit | 6f73416c8b5526a84a21415d5079bb2b61772144 | [
"BSD-3-Clause"
] | 1 | 2021-12-02T21:05:35.000Z | 2021-12-02T21:05:35.000Z |
#include <fmt/format.h>
#define CONDUIT_NO_LUA
#define CONDUIT_NO_PYTHON
#include <conduit/conduit.h>
#include <conduit/function.h>
#include <string>
#include <iostream>
#include <algorithm>
#include <queue>
#include <random>
struct QueueEntry
{
int priority;
conduit::Function<void()> event;
friend bool operator <(const QueueEntry &lhs, const QueueEntry &rhs)
{
return lhs.priority < rhs.priority;
}
};
int main(int argc, char const *argv[])
{
conduit::Registrar reg("reg", nullptr);
// This example uses 2 channels to demonstrate how our queue can hold
// channels of any signature.
auto int_print = reg.lookup<void(int, int)>("int print channel");
auto float_print = reg.lookup<void(int, int, float)>("float print channel");
reg.lookup<void(int, int)>("int print channel").hook([] (int i, int priority) {
fmt::print("{} was inserted with priority {}\n", i, priority);
});
reg.lookup<void(int, int, float)>("float print channel").hook([] (int i, int priority, float value) {
fmt::print("{} was inserted with priority {} and with float value {}\n", i, priority, value);
});
// A priority queue of events. Each QueueEntry has a priority and a function
// wrapper holding the actual work to perform. The function wrapper can hold
// anything that can be called without arguments (QueueEntry::event is a
// nullary type erased function adapter).
std::priority_queue<QueueEntry> queue;
// Get our random number generator ready
std::random_device rd;
std::mt19937 eng(rd());
std::uniform_int_distribution<> dist(0, 100);
// Queue messages on either the int_print or float_print channels.
// conduit::make_delayed pairs a callable (in this case our channel) with its
// arguments and saves it for later. See below where we apply the arguments
// to the channel to send a message on the channel.
for (int i = 0; i < 10; ++i) {
auto r = dist(eng);
if (r & 1) {
queue.push(QueueEntry{r, conduit::make_delayed(int_print, i, r)});
} else {
queue.push(QueueEntry{r, conduit::make_delayed(float_print, i, r, static_cast<float>(i) / r)});
}
}
// Now that we have events in our priority_queue, execute them in priority
// order.
while (!queue.empty()) {
queue.top().event();
queue.pop();
}
}
| 34.042254 | 107 | 0.651634 | dan65prc |
9cf902b5780c0c03d9ad6e467919623831347b35 | 1,595 | cpp | C++ | AsyncTaskMsg.cpp | xaviarmengol/ESP32-Canyon | 2d2c876afa6c4b8f8a47e4f80c99d106754ac716 | [
"MIT"
] | null | null | null | AsyncTaskMsg.cpp | xaviarmengol/ESP32-Canyon | 2d2c876afa6c4b8f8a47e4f80c99d106754ac716 | [
"MIT"
] | null | null | null | AsyncTaskMsg.cpp | xaviarmengol/ESP32-Canyon | 2d2c876afa6c4b8f8a47e4f80c99d106754ac716 | [
"MIT"
] | null | null | null | #include "AsyncTaskMsg.hpp"
AsyncTaskMsg::AsyncTaskMsg(taskNames_t myTaskName) {
_myTaskName = myTaskName;
_taskId = static_cast<int>(myTaskName);
}
void AsyncTaskMsg::update(){
_ptrAsyncTask = &(tasksManager[_taskId]);
taskNames_t taskFrom = _ptrAsyncTask->getMsgTaskFrom();
asyncMsg_t msg = _ptrAsyncTask->getMsgName();
int index = _ptrAsyncTask->getMsgIndex();
int value = _ptrAsyncTask->getMsgValue();
if (msg == AsyncMsg::WRITE_VAR) {
_asyncValues.at(index) = value;
} else if (msg == AsyncMsg::READ_VAR) {
//Answer with specific message, and with the same index, and with the READ value
tasksManager[(int)taskFrom].sendMessage(
AsyncMsg::ANSWER_READ_VAR, (taskNames_t)_taskId, index, _asyncValues.at(index));
} else if (msg == AsyncMsg::ANSWER_READ_VAR) {
_asyncValuesRead.at(index) = value;
}
}
int AsyncTaskMsg::getLocalValue(int index) {
return(_asyncValues.at(index));
}
void AsyncTaskMsg::setLocalValue(int index, int value) {
_asyncValues.at(index) = value;
}
int AsyncTaskMsg::getLastRemoteValue(int index) {
return(_asyncValuesRead.at(index));
}
void AsyncTaskMsg::readRemoteValue(taskNames_t taskName, int index) {
tasksManager[(int)taskName].sendMessage(AsyncMsg::READ_VAR, _myTaskName, index, 0);
}
void AsyncTaskMsg::writeRemoteValue(taskNames_t taskName, int index, int value) {
tasksManager[(int)taskName].sendMessage(AsyncMsg::WRITE_VAR, _myTaskName, index, value);
}
AsyncTaskMsg::~AsyncTaskMsg() {
}
| 30.673077 | 93 | 0.689655 | xaviarmengol |
9cfc2622ac4bcc8a1cb572bdbadf085948225dc6 | 289 | cc | C++ | aoj/2/2216.cc | eagletmt/procon | adbe503eb3c1bbcc1538b2ee8988aa353937e8d4 | [
"MIT"
] | 1 | 2015-04-17T09:54:23.000Z | 2015-04-17T09:54:23.000Z | aoj/2/2216.cc | eagletmt/procon | adbe503eb3c1bbcc1538b2ee8988aa353937e8d4 | [
"MIT"
] | null | null | null | aoj/2/2216.cc | eagletmt/procon | adbe503eb3c1bbcc1538b2ee8988aa353937e8d4 | [
"MIT"
] | null | null | null | #include <iostream>
using namespace std;
int main()
{
int A, B;
while (cin >> A >> B && A != 0) {
int c = B - A;
const int c1000 = c / 1000;
c %= 1000;
const int c500 = c / 500;
c %= 500;
cout << c/100 << ' ' << c500 << ' ' << c1000 << endl;
}
return 0;
}
| 17 | 57 | 0.460208 | eagletmt |
9cfc7e33fccde3331d93c8a5618e718bc8dfc5c5 | 3,051 | cpp | C++ | share/src/policy/packages.cpp | MrCryptoBeast/WWW | 857e860df0aa1bc7fde2ee6f5918ff32933beeb3 | [
"MIT"
] | null | null | null | share/src/policy/packages.cpp | MrCryptoBeast/WWW | 857e860df0aa1bc7fde2ee6f5918ff32933beeb3 | [
"MIT"
] | null | null | null | share/src/policy/packages.cpp | MrCryptoBeast/WWW | 857e860df0aa1bc7fde2ee6f5918ff32933beeb3 | [
"MIT"
] | null | null | null | // Copyright (c) 2021 The worldwideweb Core developers
// Distributed under the MIT software license, see the accompanying
// file COPYING or http://www.opensource.org/licenses/mit-license.php.
#include <consensus/validation.h>
#include <policy/packages.h>
#include <primitives/transaction.h>
#include <uint256.h>
#include <util/hasher.h>
#include <numeric>
#include <unordered_set>
bool CheckPackage(const Package& txns, PackageValidationState& state)
{
const unsigned int package_count = txns.size();
if (package_count > MAX_PACKAGE_COUNT) {
return state.Invalid(PackageValidationResult::PCKG_POLICY, "package-too-many-transactions");
}
const int64_t total_size = std::accumulate(txns.cbegin(), txns.cend(), 0,
[](int64_t sum, const auto& tx) { return sum + GetVirtualTransactionSize(*tx); });
// If the package only contains 1 tx, it's better to report the policy violation on individual tx size.
if (package_count > 1 && total_size > MAX_PACKAGE_SIZE * 1000) {
return state.Invalid(PackageValidationResult::PCKG_POLICY, "package-too-large");
}
// Require the package to be sorted in order of dependency, i.e. parents appear before children.
// An unsorted package will fail anyway on missing-inputs, but it's better to quit earlier and
// fail on something less ambiguous (missing-inputs could also be an orphan or trying to
// spend nonexistent coins).
std::unordered_set<uint256, SaltedTxidHasher> later_txids;
std::transform(txns.cbegin(), txns.cend(), std::inserter(later_txids, later_txids.end()),
[](const auto& tx) { return tx->GetHash(); });
for (const auto& tx : txns) {
for (const auto& input : tx->vin) {
if (later_txids.find(input.prevout.hash) != later_txids.end()) {
// The parent is a subsequent transaction in the package.
return state.Invalid(PackageValidationResult::PCKG_POLICY, "package-not-sorted");
}
}
later_txids.erase(tx->GetHash());
}
// Don't allow any conflicting transactions, i.e. spending the same inputs, in a package.
std::unordered_set<COutPoint, SaltedOutpointHasher> inputs_seen;
for (const auto& tx : txns) {
for (const auto& input : tx->vin) {
if (inputs_seen.find(input.prevout) != inputs_seen.end()) {
// This input is also present in another tx in the package.
return state.Invalid(PackageValidationResult::PCKG_POLICY, "conflict-in-package");
}
}
// Batch-add all the inputs for a tx at a time. If we added them 1 at a time, we could
// catch duplicate inputs within a single tx. This is a more severe, consensus error,
// and we want to report that from CheckTransaction instead.
std::transform(tx->vin.cbegin(), tx->vin.cend(), std::inserter(inputs_seen, inputs_seen.end()),
[](const auto& input) { return input.prevout; });
}
return true;
}
| 48.428571 | 113 | 0.662078 | MrCryptoBeast |
9cfd319e71a48e152b4d8594b26db33988f7eed0 | 2,045 | cpp | C++ | src/problems/151-200/151/problem151.cpp | abeccaro/project-euler | c3b124bb973dc3a1cf29e8c96c3e70c8816d5fa3 | [
"MIT"
] | 1 | 2019-12-25T10:17:15.000Z | 2019-12-25T10:17:15.000Z | src/problems/151-200/151/problem151.cpp | abeccaro/project-euler | c3b124bb973dc3a1cf29e8c96c3e70c8816d5fa3 | [
"MIT"
] | null | null | null | src/problems/151-200/151/problem151.cpp | abeccaro/project-euler | c3b124bb973dc3a1cf29e8c96c3e70c8816d5fa3 | [
"MIT"
] | null | null | null | //
// Created by Alex Beccaro on 03/08/2021.
//
#include "problem151.hpp"
#include "generics.hpp"
#include <numeric>
#include <vector>
#include <unordered_map>
#include <unordered_set>
using std::vector;
using std::unordered_map;
using std::unordered_set;
using generics::digits;
using std::accumulate;
namespace problems {
double problem151::solve() {
// states are represented as a number where each digit, in order, represents the quantity of A2, A3, A4 and A5
// sheets in the envelope
unordered_map<uint32_t, double> p = {{1111, 1}};
vector<uint32_t> current = {1111};
unordered_set<uint32_t> next;
for (uint32_t batch = 2; batch <= 16; batch++) {
for (const auto& state : current) {
vector<uint32_t> d = digits(state);
uint32_t total = accumulate(d.begin(), d.end(), 0u); // total number of sheets in the envelope
// each mask represents a possible format (A2, A3, A4 or A5)
for (uint32_t mask = 1000; mask > 0; mask /= 10) {
uint32_t n = state % (mask * 10) / mask; // number of sheets of the mask format
if (n == 0)
continue;
// apply cuts to generate the new state and add it to the set for next batch
uint32_t to_add = 0;
for (uint32_t i = 1; i < mask; i *= 10)
to_add += i;
uint32_t new_state = state - mask + to_add;
next.insert(new_state);
// update probability of new state
double p_next = p[state] * n / total;
if (p.find(new_state) != p.end())
p[new_state] += p_next;
else
p.insert({new_state, p_next});
}
}
current.assign(next.begin(), next.end());
next.clear();
}
return p[1000] + p[100] + p[10];
}
} | 33.52459 | 118 | 0.51687 | abeccaro |
9cfd5987f8ad19c1b35cc090c3a5a954bce01e18 | 317 | cpp | C++ | Codeforces/ProblemSet/4C.cpp | Binary-bug/CP | f9f356d36bd252c71ee3ed2d0585cc372f2baf5e | [
"MIT"
] | null | null | null | Codeforces/ProblemSet/4C.cpp | Binary-bug/CP | f9f356d36bd252c71ee3ed2d0585cc372f2baf5e | [
"MIT"
] | null | null | null | Codeforces/ProblemSet/4C.cpp | Binary-bug/CP | f9f356d36bd252c71ee3ed2d0585cc372f2baf5e | [
"MIT"
] | null | null | null | #include<iostream>
#include<string>
#include<map>
using namespace std;
int main(){
int n;
string s;
map<string,int> ber;
cin >> n;
while(n--){
cin >> s;
if(ber.find(s) == ber.end()) cout << "OK" << endl , ber[s]++;
else{
s = s + to_string(ber[s]++);
cout << s << endl;
}
}
return 0;
}
| 12.192308 | 63 | 0.526814 | Binary-bug |
9cfd69060a1eec602154533c0f5d2678a13d4ee8 | 2,000 | cpp | C++ | src/common/osWrappersInitFunc.cpp | GPUOpen-Tools/common-src-AMDTOSWrappers | 80f8902c78d52435ac04f66ac190d689e5badbc1 | [
"MIT"
] | 2 | 2017-01-28T14:11:35.000Z | 2018-02-01T08:22:03.000Z | src/common/osWrappersInitFunc.cpp | GPUOpen-Tools/common-src-AMDTOSWrappers | 80f8902c78d52435ac04f66ac190d689e5badbc1 | [
"MIT"
] | null | null | null | src/common/osWrappersInitFunc.cpp | GPUOpen-Tools/common-src-AMDTOSWrappers | 80f8902c78d52435ac04f66ac190d689e5badbc1 | [
"MIT"
] | 2 | 2018-02-01T08:22:04.000Z | 2019-11-01T23:00:21.000Z | //=====================================================================
// Copyright 2016 (c), Advanced Micro Devices, Inc. All rights reserved.
//
/// \author AMD Developer Tools Team
/// \file osWrappersInitFunc.cpp
///
//=====================================================================
//------------------------------ osWrappersInitFunc.cpp ------------------------------
// Local:
#include <AMDTOSWrappers/Include/osTransferableObjectCreator.h>
#include <AMDTOSWrappers/Include/osTransferableObjectCreatorsManager.h>
#include <AMDTOSWrappers/Include/osFilePath.h>
#include <AMDTOSWrappers/Include/osDirectory.h>
#include <AMDTOSWrappers/Include/osWrappersInitFunc.h>
// ---------------------------------------------------------------------------
// Name: apiClassesInitFunc
// Description: Initialization function for the GROSWrappers library.
// Return Val: bool - Success / failure.
// Author: AMD Developer Tools Team
// Date: 2/6/2004
// Implementation Notes:
// Registeres all the GROSWrappers transferable objects in the transferable
// objects creator manager.
// ---------------------------------------------------------------------------
bool osWrappersInitFunc()
{
// Verify that this function code is executed only once:
static bool wasThisFunctionCalled = false;
if (!wasThisFunctionCalled)
{
wasThisFunctionCalled = true;
// Get the osTransferableObjectCreatorsManager single instance:
osTransferableObjectCreatorsManager& theTransfetableObsCreatorsManager = osTransferableObjectCreatorsManager::instance();
// ----------- Register transferable objects creators -----------
osTransferableObjectCreator<osFilePath> osFilePathCreator;
theTransfetableObsCreatorsManager.registerCreator(osFilePathCreator);
osTransferableObjectCreator<osDirectory> osDirectoryCreator;
theTransfetableObsCreatorsManager.registerCreator(osDirectoryCreator);
}
return true;
}
| 36.363636 | 129 | 0.614 | GPUOpen-Tools |
9cfd8a11f1c68322f65b5f1d2881365bcddd1145 | 4,017 | hpp | C++ | include/standard_dragon/dragon.hpp | yretenai/standard_dragon | 5989f3c40f47ee04788fc51f8486ef26f6ad1d25 | [
"MIT"
] | 1 | 2020-12-03T20:08:57.000Z | 2020-12-03T20:08:57.000Z | include/standard_dragon/dragon.hpp | yretenai/standard_dragon | 5989f3c40f47ee04788fc51f8486ef26f6ad1d25 | [
"MIT"
] | null | null | null | include/standard_dragon/dragon.hpp | yretenai/standard_dragon | 5989f3c40f47ee04788fc51f8486ef26f6ad1d25 | [
"MIT"
] | null | null | null | //
// Created by Lilith on 2020-05-28.
//
#pragma once
#include <deque>
#include <filesystem>
#include <fstream>
#include <iostream>
#include <iterator>
#include <set>
#include <type_traits>
#include "Array.hpp"
#include "macros.hpp"
#ifdef _WIN32
# ifndef WIN32_LEAN_AND_MEAN
# define WIN32_LEAN_AND_MEAN
# endif // WIN32_LEAN_AND_MEAN
# include <Windows.h>
#endif
namespace dragon {
template<typename T>
inline typename std::enable_if<std::is_integral<T>::value, T>::type Align(T value, T align) {
T v = value % align;
if (v != 0)
return value + align - v;
return value;
}
inline Array<uint8_t> read_file(const std::filesystem::path &path) {
#ifdef DRAGON_TOOLS
DRAGON_LOG("Reading file " << path);
#endif
std::ifstream file(path, std::ios::binary | std::ios::in);
auto size = (size_t) std::filesystem::file_size(path);
Array<uint8_t> bytes(size, nullptr);
file.seekg(0, std::ios::beg);
file.read(reinterpret_cast<char *>(bytes.data()), (std::streamsize) size);
file.close();
return bytes;
}
inline void write_file(const std::filesystem::path &path, const Array<uint8_t> &buffer) {
if (buffer.empty())
return;
#ifdef DRAGON_TOOLS
if (std::filesystem::exists(path)) {
DRAGON_ELOG("Overwriting file " << path);
} else {
DRAGON_LOG("Writing file " << path);
}
#endif
std::ofstream file(path, std::ios::binary | std::ios::out | std::ios::trunc);
file.write(reinterpret_cast<const char *>(buffer.data()), (std::streamsize) buffer.size());
file.flush();
file.close();
}
inline void str_to_lower(std::string &str) {
std::transform(str.begin(), str.end(), str.begin(), [](char c) { return std::tolower(c); });
}
inline void str_to_upper(std::string &str) {
std::transform(str.begin(), str.end(), str.begin(), [](char c) { return std::toupper(c); });
}
inline void find_paths(const std::filesystem::path &path, std::deque<std::filesystem::path> &container, const std::set<std::string> &filters = {}, std::filesystem::directory_options options = {}) {
if (!std::filesystem::exists(path)) {
return;
}
if (std::filesystem::is_directory(path)) {
for (const auto &entry : std::filesystem::recursive_directory_iterator(path, options)) {
if (entry.is_directory()) {
continue;
}
const auto &sub_path = entry.path();
auto ext = sub_path.extension();
if (!filters.empty()) {
bool found = false;
for (const auto &filter : filters) {
if (ext == filter) {
found = true;
break;
}
}
if (!found) {
continue;
}
}
container.emplace_back(sub_path);
}
} else {
container.emplace_back(path);
}
}
inline std::deque<std::filesystem::path> find_paths(std::deque<std::string> &paths, const std::set<std::string> &filters = {}, std::filesystem::directory_options options = {}) {
std::deque<std::filesystem::path> container;
for (const auto &path : paths) {
find_paths(path, container, filters, options);
}
return container;
}
inline std::deque<std::filesystem::path> find_paths(std::deque<std::filesystem::path> &paths, const std::set<std::string> &filters = {}, std::filesystem::directory_options options = {}) {
std::deque<std::filesystem::path> container;
for (const auto &path : paths) {
find_paths(path, container, filters, options);
}
return container;
}
} // namespace dragon
| 32.395161 | 201 | 0.552651 | yretenai |
9cfe59c2dad23c25e0f625bfe2d9dfda0a011759 | 5,163 | hpp | C++ | include/GTGE/SceneStateStackStagingArea.hpp | mackron/GTGameEngine | 380d1e01774fe6bc2940979e4e5983deef0bf082 | [
"BSD-3-Clause"
] | 31 | 2015-03-19T08:44:48.000Z | 2021-12-15T20:52:31.000Z | include/GTGE/SceneStateStackStagingArea.hpp | mackron/GTGameEngine | 380d1e01774fe6bc2940979e4e5983deef0bf082 | [
"BSD-3-Clause"
] | 19 | 2015-07-09T09:02:44.000Z | 2016-06-09T03:51:03.000Z | include/GTGE/SceneStateStackStagingArea.hpp | mackron/GTGameEngine | 380d1e01774fe6bc2940979e4e5983deef0bf082 | [
"BSD-3-Clause"
] | 3 | 2017-10-04T23:38:18.000Z | 2022-03-07T08:27:13.000Z | // Copyright (C) 2011 - 2014 David Reid. See included LICENCE.
#ifndef GT_SceneStateStackStagingArea
#define GT_SceneStateStackStagingArea
#include "SceneStateStackRestoreCommands.hpp"
#include "Serialization.hpp"
namespace GT
{
class Scene;
class SceneStateStackBranch;
/// Class representing the staging area.
class SceneStateStackStagingArea
{
public:
/// Constructor.
SceneStateStackStagingArea(SceneStateStackBranch &branch);
/// Destructor.
~SceneStateStackStagingArea();
/// Retrieves a reference to the branch that owns this staging area.
SceneStateStackBranch & GetBranch() { return this->branch; }
const SceneStateStackBranch & GetBranch() const { return this->branch; }
/// Retrieves a reference to the relevant scene.
Scene & GetScene();
const Scene & GetScene() const;
/// Stages an insert command of the given scene node.
///
/// @param sceneNodeID [in] The ID of the scene node that was inserted.
void StageInsert(uint64_t sceneNodeID);
/// Stages a delete command of the given scene node.
///
/// @param sceneNodeID [in] The ID of the scene node that was deleted.
void StageDelete(uint64_t sceneNodeID);
/// Stages an update command of the given scene node.
///
/// @param sceneNodeID [in] The ID of the scene node that was updated.
void StageUpdate(uint64_t sceneNodeID);
/// Clears the staging area.
void Clear();
/// Retrieves a reference to the insert commands.
Vector<uint64_t> & GetInserts() { return this->inserts; }
const Vector<uint64_t> & GetInserts() const { return this->inserts; }
/// Retrieves a reference to the delete commands.
Map<uint64_t, BasicSerializer*> & GetDeletes() { return this->deletes; }
const Map<uint64_t, BasicSerializer*> & GetDeletes() const { return this->deletes; }
/// Retrieves a reference to the update commands.
Vector<uint64_t> & GetUpdates() { return this->updates; }
const Vector<uint64_t> & GetUpdates() const { return this->updates; }
/// Retrieves a reference to the hierarchy.
Map<uint64_t, uint64_t> & GetHierarchy() { return this->hierarchy; }
const Map<uint64_t, uint64_t> & GetHierarchy() const { return this->hierarchy; }
/// Retrieves the set of commands to use to revert the scene from the changes in the staging area.
///
/// @param commands [out] A reference to the object that will receive the restore commands.
void GetRevertCommands(SceneStateStackRestoreCommands &commands);
/// Retrieves a set of commands that can be used to put the scene into a state as currently defined by the staging area.
///
/// @param commands [out] A reference to the object that will receive the restore commands.
void GetRestoreCommands(SceneStateStackRestoreCommands &commands);
/////////////////////////////////////////////////
// Serialization/Deserialization
/// Serializes the state stack staging area.
void Serialize(Serializer &serializer) const;
/// Deserializes the state stack staging area.
void Deserialize(Deserializer &deserializer);
private:
/// Adds the given scene node to the hierarchy.
///
/// @param sceneNodeID [in] The ID of the scene node that is being added to the hierarchy.
///
/// @remarks
/// This does nothing if the scene node does not have a parent.
void AddToHierarchy(uint64_t sceneNodeID);
/// Removes the given scene node from the hierarchy.
///
/// @param sceneNodeID [in] The ID of the scene node that is being removed from the hierarchy.
void RemoveFromHierarchy(uint64_t sceneNodeID);
/// Retrieves the ID of the parent node from the hierarchy, or 0 if it does not have a parent.
///
/// @param childSceneNodeID [in] The ID of the scene node whose parent ID is being retrieved.
uint64_t GetParentSceneNodeIDFromHierarchy(uint64_t childSceneNodeID) const;
private:
/// The branch that owns this staging area.
SceneStateStackBranch &branch;
/// The list of scene node ID's of newly inserted scene nodes in the staging area.
Vector<uint64_t> inserts;
/// The list of scene node ID's of newly deleted scene nodes in the staging area. We need to keep track of the serialized data
/// because the scene will want to delete the node, after which point we won't be able to retrieve the data.
Map<uint64_t, BasicSerializer*> deletes;
/// The list of scene node ID's of newly updated scene nodes in the staging area.
Vector<uint64_t> updates;
/// The hierarchy of the nodes containined in the staging area. The key is the child node ID and the value is the parent node ID.
Map<uint64_t, uint64_t> hierarchy;
};
}
#endif
| 36.617021 | 137 | 0.643812 | mackron |
9cff21f11dcf98244172ee0f99b46178975b7495 | 5,563 | cc | C++ | gnuradio-3.7.13.4/gr-qtgui/lib/histogramdisplayform.cc | v1259397/cosmic-gnuradio | 64c149520ac6a7d44179c3f4a38f38add45dd5dc | [
"BSD-3-Clause"
] | 1 | 2021-03-09T07:32:37.000Z | 2021-03-09T07:32:37.000Z | gnuradio-3.7.13.4/gr-qtgui/lib/histogramdisplayform.cc | v1259397/cosmic-gnuradio | 64c149520ac6a7d44179c3f4a38f38add45dd5dc | [
"BSD-3-Clause"
] | null | null | null | gnuradio-3.7.13.4/gr-qtgui/lib/histogramdisplayform.cc | v1259397/cosmic-gnuradio | 64c149520ac6a7d44179c3f4a38f38add45dd5dc | [
"BSD-3-Clause"
] | null | null | null | /* -*- c++ -*- */
/*
* Copyright 2013 Free Software Foundation, Inc.
*
* This file is part of GNU Radio
*
* GNU Radio 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, or (at your option)
* any later version.
*
* GNU Radio 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 GNU Radio; see the file COPYING. If not, write to
* the Free Software Foundation, Inc., 51 Franklin Street,
* Boston, MA 02110-1301, USA.
*/
#include <cmath>
#include <QMessageBox>
#include <gnuradio/qtgui/histogramdisplayform.h>
#include <iostream>
HistogramDisplayForm::HistogramDisplayForm(int nplots, QWidget* parent)
: DisplayForm(nplots, parent)
{
d_semilogx = false;
d_semilogy = false;
d_int_validator = new QIntValidator(this);
d_int_validator->setBottom(0);
d_layout = new QGridLayout(this);
d_display_plot = new HistogramDisplayPlot(nplots, this);
d_layout->addWidget(d_display_plot, 0, 0);
setLayout(d_layout);
d_nptsmenu = new NPointsMenu(this);
d_menu->addAction(d_nptsmenu);
connect(d_nptsmenu, SIGNAL(whichTrigger(int)),
this, SLOT(setNPoints(const int)));
d_nbinsmenu = new NPointsMenu(this);
d_nbinsmenu->setText("Number of Bins");
d_menu->addAction(d_nbinsmenu);
connect(d_nbinsmenu, SIGNAL(whichTrigger(int)),
this, SLOT(setNumBins(const int)));
d_accum_act = new QAction("Accumulate", this);
d_accum_act->setCheckable(true);
d_menu->addAction(d_accum_act);
connect(d_accum_act, SIGNAL(triggered(bool)),
this, SLOT(setAccumulate(bool)));
d_menu->removeAction(d_autoscale_act);
d_autoscale_act->setText(tr("Auto Scale Y"));
d_autoscale_act->setStatusTip(tr("Autoscale Y-axis"));
d_autoscale_act->setCheckable(true);
d_autoscale_act->setChecked(true);
d_autoscale_state = true;
d_menu->addAction(d_autoscale_act);
d_autoscalex_act = new QAction("Auto Scale X", this);
d_autoscalex_act->setStatusTip(tr("Update X-axis scale"));
d_autoscalex_act->setCheckable(false);
connect(d_autoscalex_act, SIGNAL(changed()),
this, SLOT(autoScaleX()));
d_autoscalex_state = false;
d_menu->addAction(d_autoscalex_act);
// d_semilogxmenu = new QAction("Semilog X", this);
// d_semilogxmenu->setCheckable(true);
// d_menu->addAction(d_semilogxmenu);
// connect(d_semilogxmenu, SIGNAL(triggered(bool)),
// this, SLOT(setSemilogx(bool)));
//
// d_semilogymenu = new QAction("Semilog Y", this);
// d_semilogymenu->setCheckable(true);
// d_menu->addAction(d_semilogymenu);
// connect(d_semilogymenu, SIGNAL(triggered(bool)),
// this, SLOT(setSemilogy(bool)));
Reset();
connect(d_display_plot, SIGNAL(plotPointSelected(const QPointF)),
this, SLOT(onPlotPointSelected(const QPointF)));
}
HistogramDisplayForm::~HistogramDisplayForm()
{
// Qt deletes children when parent is deleted
// Don't worry about deleting Display Plots - they are deleted when parents are deleted
delete d_int_validator;
}
HistogramDisplayPlot*
HistogramDisplayForm::getPlot()
{
return ((HistogramDisplayPlot*)d_display_plot);
}
void
HistogramDisplayForm::newData(const QEvent* updateEvent)
{
HistogramUpdateEvent *hevent = (HistogramUpdateEvent*)updateEvent;
const std::vector<double*> dataPoints = hevent->getDataPoints();
const uint64_t numDataPoints = hevent->getNumDataPoints();
getPlot()->plotNewData(dataPoints,
numDataPoints,
d_update_time);
}
void
HistogramDisplayForm::customEvent(QEvent * e)
{
if(e->type() == HistogramUpdateEvent::Type()) {
newData(e);
}
else if(e->type() == HistogramSetAccumulator::Type()) {
bool en = ((HistogramSetAccumulator*)e)->getAccumulator();
setAccumulate(en);
}
else if(e->type() == HistogramClearEvent::Type()) {
getPlot()->clear();
}
}
void
HistogramDisplayForm::setYaxis(double min, double max)
{
getPlot()->setYaxis(min, max);
}
void
HistogramDisplayForm::setXaxis(double min, double max)
{
getPlot()->setXaxis(min, max);
}
int
HistogramDisplayForm::getNPoints() const
{
return d_npoints;
}
void
HistogramDisplayForm::setNPoints(const int npoints)
{
d_npoints = npoints;
d_nptsmenu->setDiagText(npoints);
}
void
HistogramDisplayForm::autoScale(bool en)
{
d_autoscale_state = en;
d_autoscale_act->setChecked(en);
getPlot()->setAutoScale(d_autoscale_state);
getPlot()->replot();
}
void
HistogramDisplayForm::autoScaleX()
{
getPlot()->setAutoScaleX();
getPlot()->replot();
}
void
HistogramDisplayForm::setSemilogx(bool en)
{
d_semilogx = en;
d_semilogxmenu->setChecked(en);
getPlot()->setSemilogx(d_semilogx);
getPlot()->replot();
}
void
HistogramDisplayForm::setSemilogy(bool en)
{
d_semilogy = en;
d_semilogymenu->setChecked(en);
getPlot()->setSemilogy(d_semilogy);
getPlot()->replot();
}
void
HistogramDisplayForm::setNumBins(const int bins)
{
getPlot()->setNumBins(bins);
getPlot()->replot();
d_nbinsmenu->setDiagText(bins);
}
void
HistogramDisplayForm::setAccumulate(bool en)
{
// Turn on y-axis autoscaling when turning accumulate on.
if(en) {
autoScale(true);
}
d_accum_act->setChecked(en);
getPlot()->setAccumulate(en);
getPlot()->replot();
}
bool
HistogramDisplayForm::getAccumulate()
{
return getPlot()->getAccumulate();
}
| 25.401826 | 89 | 0.729103 | v1259397 |
140192140be1fd9aaf66af695951be1f2d1327b0 | 7,756 | hpp | C++ | Middlewares/ST/touchgfx_backup/framework/include/touchgfx/canvas_widget_renderer/Outline.hpp | koson/car-dash | 7be8f02a243d43b4fd9fd33b0a160faa5901f747 | [
"MIT"
] | 12 | 2020-06-25T13:10:17.000Z | 2022-01-27T01:48:26.000Z | Middlewares/ST/touchgfx_backup/framework/include/touchgfx/canvas_widget_renderer/Outline.hpp | koson/car-dash | 7be8f02a243d43b4fd9fd33b0a160faa5901f747 | [
"MIT"
] | 2 | 2021-05-23T05:02:48.000Z | 2021-05-24T11:15:56.000Z | Middlewares/ST/touchgfx_backup/framework/include/touchgfx/canvas_widget_renderer/Outline.hpp | koson/car-dash | 7be8f02a243d43b4fd9fd33b0a160faa5901f747 | [
"MIT"
] | 7 | 2020-08-27T08:23:49.000Z | 2021-09-19T12:54:30.000Z | /**
******************************************************************************
* This file is part of the TouchGFX 4.13.0 distribution.
*
* <h2><center>© Copyright (c) 2019 STMicroelectronics.
* All rights reserved.</center></h2>
*
* This software component is licensed by ST under Ultimate Liberty license
* SLA0044, the "License"; You may not use this file except in compliance with
* the License. You may obtain a copy of the License at:
* www.st.com/SLA0044
*
******************************************************************************
*/
#ifndef OUTLINE_HPP
#define OUTLINE_HPP
#include <touchgfx/canvas_widget_renderer/Cell.hpp>
namespace touchgfx
{
/**
* @class Outline Outline.hpp touchgfx/canvas_widget_renderer/Outline.hpp
*
* @brief An internal class that implements the main rasterization algorithm.
*
* An internal class that implements the main rasterization algorithm. Used in the
* Rasterizer. Should not be used direcly.
*/
class Outline
{
public:
/**
* @typedef unsigned int OutlineFlags_t
*
* @brief Defines an alias representing the outline flags.
*
* Defines an alias representing the outline flags.
*/
typedef unsigned int OutlineFlags_t;
static const OutlineFlags_t OUTLINE_NOT_CLOSED = 1U; ///< If this bit is set in flags, the current Outline has not yet been closed. Used for automatic closing an Outline before rendering the Outline.
static const OutlineFlags_t OUTLINE_SORT_REQUIRED = 2U; ///< If this bit is set in flags, Cell objects have been added to the Outline requiring the Cell list needs to be sorted.
/**
* @fn Outline::Outline();
*
* @brief Default constructor.
*
* Default constructor.
*/
Outline();
/**
* @fn Outline::~Outline();
*
* @brief Destructor.
*
* Destructor.
*/
virtual ~Outline();
/**
* @fn void Outline::reset();
*
* @brief Resets this object.
*
* Resets this object. This implies removing the current Cell objects and preparing
* for a new Outline.
*/
void reset();
/**
* @fn void Outline::moveTo(int x, int y);
*
* @brief Move a virtual pen to the specified coordinate.
*
* Move a virtual pen to the specified coordinate.
*
* @param x The x coordinate.
* @param y The y coordinate.
*/
void moveTo(int x, int y);
/**
* @fn void Outline::lineTo(int x, int y);
*
* @brief Create a line from the current virtual pen coordinate to the given coordinate
* creating an Outline.
*
* Create a line from the current virtual pen coordinate to the given coordinate
* creating an Outline.
*
* @param x The x coordinate.
* @param y The y coordinate.
*/
void lineTo(int x, int y);
/**
* @fn unsigned Outline::getNumCells() const
*
* @brief Gets number cells registered in the current drawn path for the Outline.
*
* Gets number cells registered in the current drawn path for the Outline.
*
* @return The number of cells.
*/
unsigned getNumCells() const
{
return numCells;
}
/**
* @fn const Cell* Outline::getCells();
*
* @brief Gets a pointer to the the Cell objects in the Outline.
*
* Gets a pointer to the the Cell objects in the Outline. If the Outline is not
* closed, it is closed. If the Outline is unsorted, it will be quick sorted first.
*
* @return A pointer to the sorted list of Cell objects in the Outline.
*/
const Cell* getCells();
/**
* @fn void Outline::setMaxRenderY(int y)
*
* @brief Sets maximum render y coordinate.
*
* Sets maximum render y coordinate. This is used to avoid registering any Cell that
* has a y coordinate less than zero of higher than the given y.
*
* @param y The max y coordinate to render for the Outline.
*/
void setMaxRenderY(int y)
{
maxRenderY = y;
}
/**
* @fn bool Outline::wasOutlineTooComplex()
*
* @brief Determines if there was enough memory to register the entire outline.
*
* Determines if there was enough memory to register the entire outline, of if the
* outline was too complex.
*
* @return false if the buffer for Outline Cell objects was too small.
*/
bool wasOutlineTooComplex()
{
return outlineTooComplex;
}
private:
/**
* @fn void Outline::setCurCell(int x, int y);
*
* @brief Sets coordinate of the current Cell.
*
* Sets coordinate of the current Cell.
*
* @param x The x coordinate.
* @param y The y coordinate.
*/
void setCurCell(int x, int y);
/**
* @fn void Outline::addCurCell();
*
* @brief Adds current cell to the Outline.
*
* Adds current cell to the Outline.
*/
void addCurCell();
/**
* @fn void Outline::sortCells();
*
* @brief Sort cells in the Outline.
*
* Sort cells in the Outline.
*/
void sortCells();
/**
* @fn void Outline::renderScanline(int ey, int x1, int y1, int x2, int y2);
*
* @brief Render the scanline in the special case where the line is on the same scanline.
*
* Render the scanline in the special case where the line is on the same scanline,
* though it might not be 100% horizontal as the fraction of the y endpoints might
* differ making the line tilt ever so slightly.
*
* @param ey The entire part of the from/to y coordinate (same for both from y and to y as it
* is a horizontal scanline).
* @param x1 The from x coordinate in poly format.
* @param y1 The from y coordinate fraction part in poly format.
* @param x2 The to x coordinate in poly format.
* @param y2 The to y coordinate fraction part in poly format.
*/
void renderScanline(int ey, int x1, int y1, int x2, int y2);
/**
* @fn void Outline::renderLine(int x1, int y1, int x2, int y2);
*
* @brief Render the line.
*
* Render the line. This is the general case which handles all cases regardless of
* the position of the from coordinate and the to coordinate.
*
* @param x1 The from x coordinate in poly format.
* @param y1 The from y coordinate in poly format.
* @param x2 The to x coordinate in poly format.
* @param y2 The to y coordinate in poly format.
*/
void renderLine(int x1, int y1, int x2, int y2);
/**
* @fn static void Outline::qsortCells(Cell* const start, unsigned num);
*
* @brief Quick sort Outline cells.
*
* Quick sort Outline cells.
*
* @param [in] start The first Cell object in the Cell array to sort.
* @param num Number of Cell objects to sort.
*/
static void qsortCells(Cell* const start, unsigned num);
private:
unsigned maxCells;
unsigned numCells;
Cell* cells;
Cell* curCellPtr;
Cell curCell;
int curX;
int curY;
int closeX;
int closeY;
int minX;
int minY;
int maxX;
int maxY;
unsigned int flags;
int maxRenderY;
bool outlineTooComplex;
#ifdef SIMULATOR
unsigned numCellsMissing;
unsigned numCellsUsed;
#endif
};
} // namespace touchgfx
#endif // OUTLINE_HPP
| 30.178988 | 206 | 0.587158 | koson |
1401ec61770b1f679360d68dc86f07046f28f7b1 | 1,573 | hpp | C++ | include/tao/pq/parameter_traits_aggregate.hpp | huzaifanazir/taopq | 8f939d33840f14d7c08311729745fe7bb8cd9898 | [
"BSL-1.0"
] | 69 | 2016-08-05T19:16:04.000Z | 2018-11-24T15:13:46.000Z | include/tao/pq/parameter_traits_aggregate.hpp | huzaifanazir/taopq | 8f939d33840f14d7c08311729745fe7bb8cd9898 | [
"BSL-1.0"
] | 13 | 2016-11-24T16:42:28.000Z | 2018-09-11T18:55:40.000Z | include/tao/pq/parameter_traits_aggregate.hpp | huzaifanazir/taopq | 8f939d33840f14d7c08311729745fe7bb8cd9898 | [
"BSL-1.0"
] | 13 | 2016-09-22T17:31:10.000Z | 2018-10-18T02:56:49.000Z | // Copyright (c) 2020-2022 Daniel Frey and Dr. Colin Hirsch
// Distributed under the Boost Software License, Version 1.0.
// (See accompanying file LICENSE_1_0.txt or copy at https://www.boost.org/LICENSE_1_0.txt)
#ifndef TAO_PQ_PARAMETER_TRAITS_AGGREGATE_HPP
#define TAO_PQ_PARAMETER_TRAITS_AGGREGATE_HPP
#include <tao/pq/internal/aggregate.hpp>
#include <tao/pq/is_aggregate.hpp>
#include <tao/pq/parameter_traits.hpp>
namespace tao::pq
{
namespace internal
{
template< typename T >
struct parameter_tie_aggregate
{
using result_t = decltype( internal::tie_aggregate( std::declval< const T& >() ) );
const result_t result;
explicit parameter_tie_aggregate( const T& t ) noexcept
: result( internal::tie_aggregate( t ) )
{}
};
} // namespace internal
template< typename T >
struct parameter_traits< T, std::enable_if_t< is_aggregate_parameter< T > > >
: private internal::parameter_tie_aggregate< T >,
public parameter_traits< typename internal::parameter_tie_aggregate< T >::result_t >
{
using typename internal::parameter_tie_aggregate< T >::result_t;
explicit parameter_traits( const T& t ) noexcept( noexcept( internal::parameter_tie_aggregate< T >( t ),
parameter_traits< result_t >( std::declval< result_t >() ) ) )
: internal::parameter_tie_aggregate< T >( t ),
parameter_traits< result_t >( this->result )
{}
};
} // namespace tao::pq
#endif
| 34.195652 | 128 | 0.655435 | huzaifanazir |
1404d6ff3e3d270bd730d4cbe961c81f10ade5a7 | 4,230 | cpp | C++ | Source/Drivers/PS1080/DDK/XnAudioStream.cpp | gajgeospatial/OpenNI2-2.2.0.33 | 86d57aa61bcf1fd96922af1960ab711c2e9c1ed5 | [
"Apache-2.0"
] | 925 | 2015-01-04T03:47:56.000Z | 2022-03-28T11:18:18.000Z | Source/Drivers/PS1080/DDK/XnAudioStream.cpp | gajgeospatial/OpenNI2-2.2.0.33 | 86d57aa61bcf1fd96922af1960ab711c2e9c1ed5 | [
"Apache-2.0"
] | 125 | 2015-01-12T11:28:09.000Z | 2021-03-29T09:38:04.000Z | Source/Drivers/PS1080/DDK/XnAudioStream.cpp | gajgeospatial/OpenNI2-2.2.0.33 | 86d57aa61bcf1fd96922af1960ab711c2e9c1ed5 | [
"Apache-2.0"
] | 475 | 2015-01-02T02:58:01.000Z | 2022-02-24T06:53:46.000Z | /*****************************************************************************
* *
* OpenNI 2.x Alpha *
* Copyright (C) 2012 PrimeSense Ltd. *
* *
* This file is part of OpenNI. *
* *
* 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. *
* *
*****************************************************************************/
//---------------------------------------------------------------------------
// Includes
//---------------------------------------------------------------------------
#include "XnAudioStream.h"
#include <XnOS.h>
//---------------------------------------------------------------------------
// Defines
//---------------------------------------------------------------------------
#define XN_AUDIO_STREAM_BUFFER_SIZE_IN_SECONDS 1.5
//---------------------------------------------------------------------------
// Code
//---------------------------------------------------------------------------
XnAudioStream::XnAudioStream(const XnChar* csName, XnUInt32 nMaxNumberOfChannels) :
XnStreamingStream(XN_STREAM_TYPE_AUDIO, csName),
m_SampleRate(XN_STREAM_PROPERTY_SAMPLE_RATE, "SampleRate", XN_SAMPLE_RATE_48K),
m_NumberOfChannels(XN_STREAM_PROPERTY_NUMBER_OF_CHANNELS, "NumChannels", 2),
m_nMaxNumberOfChannels(nMaxNumberOfChannels)
{
}
XnStatus XnAudioStream::Init()
{
XnStatus nRetVal = XN_STATUS_OK;
// init base
nRetVal = XnStreamingStream::Init();
XN_IS_STATUS_OK(nRetVal);
m_SampleRate.UpdateSetCallback(SetSampleRateCallback, this);
m_NumberOfChannels.UpdateSetCallback(SetNumberOfChannelsCallback, this);
XN_VALIDATE_ADD_PROPERTIES(this, &m_SampleRate, &m_NumberOfChannels);
// required size
nRetVal = RegisterRequiredSizeProperty(&m_SampleRate);
XN_IS_STATUS_OK(nRetVal);
return (XN_STATUS_OK);
}
XnStatus XnAudioStream::SetSampleRate(XnSampleRate nSampleRate)
{
XnStatus nRetVal = XN_STATUS_OK;
nRetVal = m_SampleRate.UnsafeUpdateValue(nSampleRate);
XN_IS_STATUS_OK(nRetVal);
return (XN_STATUS_OK);
}
XnStatus XnAudioStream::SetNumberOfChannels(XnUInt32 nNumberOfChannels)
{
XnStatus nRetVal = XN_STATUS_OK;
nRetVal = m_NumberOfChannels.UnsafeUpdateValue(nNumberOfChannels);
XN_IS_STATUS_OK(nRetVal);
return (XN_STATUS_OK);
}
XnStatus XnAudioStream::CalcRequiredSize(XnUInt32* pnRequiredSize) const
{
XnUInt32 nSampleSize = 2 * m_nMaxNumberOfChannels; // 16-bit per channel (2 bytes)
XnUInt32 nSamples = (XnUInt32)(GetSampleRate() * XN_AUDIO_STREAM_BUFFER_SIZE_IN_SECONDS);
*pnRequiredSize = nSamples * nSampleSize;
return (XN_STATUS_OK);
}
XnStatus XnAudioStream::SetSampleRateCallback(XnActualIntProperty* /*pSender*/, XnUInt64 nValue, void* pCookie)
{
XnAudioStream* pStream = (XnAudioStream*)pCookie;
return pStream->SetSampleRate((XnSampleRate)nValue);
}
XnStatus XnAudioStream::SetNumberOfChannelsCallback(XnActualIntProperty* /*pSender*/, XnUInt64 nValue, void* pCookie)
{
XnAudioStream* pStream = (XnAudioStream*)pCookie;
return pStream->SetNumberOfChannels((XnUInt32)nValue);
}
| 40.673077 | 117 | 0.528369 | gajgeospatial |
14057d3d9f7402d8601ce38a4d90ad7bb0d277ec | 9,905 | cpp | C++ | src/game/Object/Corpse.cpp | Zilvereyes/ServerOne | 92a792c4c5b9a5128e0086b5af21b51c214bb6a6 | [
"PostgreSQL",
"Zlib",
"OpenSSL"
] | null | null | null | src/game/Object/Corpse.cpp | Zilvereyes/ServerOne | 92a792c4c5b9a5128e0086b5af21b51c214bb6a6 | [
"PostgreSQL",
"Zlib",
"OpenSSL"
] | null | null | null | src/game/Object/Corpse.cpp | Zilvereyes/ServerOne | 92a792c4c5b9a5128e0086b5af21b51c214bb6a6 | [
"PostgreSQL",
"Zlib",
"OpenSSL"
] | null | null | null | /**
* MaNGOS is a full featured server for World of Warcraft, supporting
* the following clients: 1.12.x, 2.4.3, 3.3.5a, 4.3.4a and 5.4.8
*
* Copyright (C) 2005-2016 MaNGOS project <https://getmangos.eu>
*
* 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; if not, write to the Free Software
* Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA 02111-1307 USA
*
* World of Warcraft, and all World of Warcraft or Warcraft art, images,
* and lore are copyrighted by Blizzard Entertainment, Inc.
*/
#include "Corpse.h"
#include "Player.h"
#include "UpdateMask.h"
#include "ObjectAccessor.h"
#include "ObjectGuid.h"
#include "Database/DatabaseEnv.h"
#include "Opcodes.h"
#include "GossipDef.h"
#include "World.h"
#include "ObjectMgr.h"
Corpse::Corpse(CorpseType type) : WorldObject(),
loot(this),
lootRecipient(NULL),
lootForBody(false)
{
m_objectType |= TYPEMASK_CORPSE;
m_objectTypeId = TYPEID_CORPSE;
// 2.3.2 - 0x58
m_updateFlag = (UPDATEFLAG_LOWGUID | UPDATEFLAG_HIGHGUID | UPDATEFLAG_HAS_POSITION);
m_valuesCount = CORPSE_END;
m_type = type;
m_time = time(NULL);
}
Corpse::~Corpse()
{
}
void Corpse::AddToWorld()
{
///- Register the corpse for guid lookup
if (!IsInWorld())
{ sObjectAccessor.AddObject(this); }
Object::AddToWorld();
}
void Corpse::RemoveFromWorld()
{
///- Remove the corpse from the accessor
if (IsInWorld())
{ sObjectAccessor.RemoveObject(this); }
Object::RemoveFromWorld();
}
bool Corpse::Create(uint32 guidlow)
{
Object::_Create(guidlow, 0, HIGHGUID_CORPSE);
return true;
}
bool Corpse::Create(uint32 guidlow, Player* owner)
{
MANGOS_ASSERT(owner);
WorldObject::_Create(guidlow, HIGHGUID_CORPSE);
Relocate(owner->GetPositionX(), owner->GetPositionY(), owner->GetPositionZ(), owner->GetOrientation());
// we need to assign owner's map for corpse
// in other way we will get a crash in Corpse::SaveToDB()
SetMap(owner->GetMap());
if (!IsPositionValid())
{
sLog.outError("Corpse (guidlow %d, owner %s) not created. Suggested coordinates isn't valid (X: %f Y: %f)",
guidlow, owner->GetName(), owner->GetPositionX(), owner->GetPositionY());
return false;
}
SetObjectScale(DEFAULT_OBJECT_SCALE);
SetFloatValue(CORPSE_FIELD_POS_X, GetPositionX());
SetFloatValue(CORPSE_FIELD_POS_Y, GetPositionY());
SetFloatValue(CORPSE_FIELD_POS_Z, GetPositionZ());
SetFloatValue(CORPSE_FIELD_FACING, GetOrientation());
SetGuidValue(CORPSE_FIELD_OWNER, owner->GetObjectGuid());
m_grid = MaNGOS::ComputeGridPair(GetPositionX(), GetPositionY());
return true;
}
void Corpse::SaveToDB()
{
// bones should not be saved to DB (would be deleted on startup anyway)
MANGOS_ASSERT(GetType() != CORPSE_BONES);
// prevent DB data inconsistence problems and duplicates
CharacterDatabase.BeginTransaction();
DeleteFromDB();
std::ostringstream ss;
ss << "INSERT INTO corpse (guid,player,position_x,position_y,position_z,orientation,map,time,corpse_type,instance) VALUES ("
<< GetGUIDLow() << ", "
<< GetOwnerGuid().GetCounter() << ", "
<< GetPositionX() << ", "
<< GetPositionY() << ", "
<< GetPositionZ() << ", "
<< GetOrientation() << ", "
<< GetMapId() << ", "
<< uint64(m_time) << ", "
<< uint32(GetType()) << ", "
<< int(GetInstanceId()) << ")";
CharacterDatabase.Execute(ss.str().c_str());
CharacterDatabase.CommitTransaction();
}
void Corpse::DeleteBonesFromWorld()
{
MANGOS_ASSERT(GetType() == CORPSE_BONES);
Corpse* corpse = GetMap()->GetCorpse(GetObjectGuid());
if (!corpse)
{
sLog.outError("Bones %u not found in world.", GetGUIDLow());
return;
}
AddObjectToRemoveList();
}
void Corpse::DeleteFromDB()
{
// bones should not be saved to DB (would be deleted on startup anyway)
MANGOS_ASSERT(GetType() != CORPSE_BONES);
// all corpses (not bones)
static SqlStatementID id;
SqlStatement stmt = CharacterDatabase.CreateStatement(id, "DELETE FROM corpse WHERE player = ? AND corpse_type <> '0'");
stmt.PExecute(GetOwnerGuid().GetCounter());
}
bool Corpse::LoadFromDB(uint32 lowguid, Field* fields)
{
//// 0 1 2 3 4 5 6
// QueryResult *result = CharacterDatabase.Query("SELECT corpse.guid, player, corpse.position_x, corpse.position_y, corpse.position_z, corpse.orientation, corpse.map,"
//// 7 8 9 10 11 12 13 14 15 16 17
// "time, corpse_type, instance, gender, race, class, playerBytes, playerBytes2, equipmentCache, guildId, playerFlags FROM corpse"
uint32 playerLowGuid = fields[1].GetUInt32();
float positionX = fields[2].GetFloat();
float positionY = fields[3].GetFloat();
float positionZ = fields[4].GetFloat();
float orientation = fields[5].GetFloat();
uint32 mapid = fields[6].GetUInt32();
Object::_Create(lowguid, 0, HIGHGUID_CORPSE);
m_time = time_t(fields[7].GetUInt64());
m_type = CorpseType(fields[8].GetUInt32());
if (m_type >= MAX_CORPSE_TYPE)
{
sLog.outError("%s Owner %s have wrong corpse type (%i), not load.", GetGuidStr().c_str(), GetOwnerGuid().GetString().c_str(), m_type);
return false;
}
uint32 instanceid = fields[9].GetUInt32();
uint8 gender = fields[10].GetUInt8();
uint8 race = fields[11].GetUInt8();
uint8 _class = fields[12].GetUInt8();
uint32 playerBytes = fields[13].GetUInt32();
uint32 playerBytes2 = fields[14].GetUInt32();
uint32 guildId = fields[16].GetUInt32();
uint32 playerFlags = fields[17].GetUInt32();
ObjectGuid guid = ObjectGuid(HIGHGUID_CORPSE, lowguid);
ObjectGuid playerGuid = ObjectGuid(HIGHGUID_PLAYER, playerLowGuid);
// overwrite possible wrong/corrupted guid
SetGuidValue(OBJECT_FIELD_GUID, guid);
SetGuidValue(CORPSE_FIELD_OWNER, playerGuid);
SetObjectScale(DEFAULT_OBJECT_SCALE);
PlayerInfo const* info = sObjectMgr.GetPlayerInfo(race, _class);
if (!info)
{
sLog.outError("Player %u has incorrect race/class pair.", GetGUIDLow());
return false;
}
SetUInt32Value(CORPSE_FIELD_DISPLAY_ID, gender == GENDER_FEMALE ? info->displayId_f : info->displayId_m);
// Load equipment
Tokens data = StrSplit(fields[15].GetCppString(), " ");
for (uint8 slot = 0; slot < EQUIPMENT_SLOT_END; ++slot)
{
uint32 visualbase = slot * 2;
uint32 item_id = GetUInt32ValueFromArray(data, visualbase);
const ItemPrototype* proto = ObjectMgr::GetItemPrototype(item_id);
if (!proto)
{
SetUInt32Value(CORPSE_FIELD_ITEM + slot, 0);
continue;
}
SetUInt32Value(CORPSE_FIELD_ITEM + slot, proto->DisplayInfoID | (proto->InventoryType << 24));
}
uint8 skin = (uint8)(playerBytes);
uint8 face = (uint8)(playerBytes >> 8);
uint8 hairstyle = (uint8)(playerBytes >> 16);
uint8 haircolor = (uint8)(playerBytes >> 24);
uint8 facialhair = (uint8)(playerBytes2);
SetUInt32Value(CORPSE_FIELD_BYTES_1, ((0x00) | (race << 8) | (gender << 16) | (skin << 24)));
SetUInt32Value(CORPSE_FIELD_BYTES_2, ((face) | (hairstyle << 8) | (haircolor << 16) | (facialhair << 24)));
SetUInt32Value(CORPSE_FIELD_GUILD, guildId);
uint32 flags = CORPSE_FLAG_UNK2;
if (playerFlags & PLAYER_FLAGS_HIDE_HELM)
{ flags |= CORPSE_FLAG_HIDE_HELM; }
if (playerFlags & PLAYER_FLAGS_HIDE_CLOAK)
{ flags |= CORPSE_FLAG_HIDE_CLOAK; }
SetUInt32Value(CORPSE_FIELD_FLAGS, flags);
// no need to mark corpse as lootable, because corpses are not saved in battle grounds
// place
SetLocationInstanceId(instanceid);
SetLocationMapId(mapid);
Relocate(positionX, positionY, positionZ, orientation);
if (!IsPositionValid())
{
sLog.outError("%s Owner %s not created. Suggested coordinates isn't valid (X: %f Y: %f)",
GetGuidStr().c_str(), GetOwnerGuid().GetString().c_str(), GetPositionX(), GetPositionY());
return false;
}
m_grid = MaNGOS::ComputeGridPair(GetPositionX(), GetPositionY());
return true;
}
bool Corpse::IsVisibleForInState(Player const* u, WorldObject const* viewPoint, bool inVisibleList) const
{
return IsInWorld() && u->IsInWorld() && IsWithinDistInMap(viewPoint, GetMap()->GetVisibilityDistance() + (inVisibleList ? World::GetVisibleObjectGreyDistance() : 0.0f), false);
}
bool Corpse::IsHostileTo(Unit const* unit) const
{
if (Player* owner = sObjectMgr.GetPlayer(GetOwnerGuid()))
{ return owner->IsHostileTo(unit); }
else
{ return false; }
}
bool Corpse::IsFriendlyTo(Unit const* unit) const
{
if (Player* owner = sObjectMgr.GetPlayer(GetOwnerGuid()))
{ return owner->IsFriendlyTo(unit); }
else
{ return true; }
}
bool Corpse::IsExpired(time_t t) const
{
if (m_type == CORPSE_BONES)
{ return m_time < t - 60 * MINUTE; }
else
{ return m_time < t - 3 * DAY; }
}
| 33.921233 | 180 | 0.649571 | Zilvereyes |
140698983dfcde02a684576c884d1d551c33c6ac | 2,006 | cpp | C++ | samples/snippets/cpp/VS_Snippets_CLR/string.equals/CPP/equals.cpp | hamarb123/dotnet-api-docs | 6aeb55784944a2f1f5e773b657791cbd73a92dd4 | [
"CC-BY-4.0",
"MIT"
] | 421 | 2018-04-01T01:57:50.000Z | 2022-03-28T15:24:42.000Z | samples/snippets/cpp/VS_Snippets_CLR/string.equals/CPP/equals.cpp | hamarb123/dotnet-api-docs | 6aeb55784944a2f1f5e773b657791cbd73a92dd4 | [
"CC-BY-4.0",
"MIT"
] | 5,797 | 2018-04-02T21:12:23.000Z | 2022-03-31T23:54:38.000Z | samples/snippets/cpp/VS_Snippets_CLR/string.equals/CPP/equals.cpp | hamarb123/dotnet-api-docs | 6aeb55784944a2f1f5e773b657791cbd73a92dd4 | [
"CC-BY-4.0",
"MIT"
] | 1,482 | 2018-03-31T11:26:20.000Z | 2022-03-30T22:36:45.000Z |
//<snippet1>
// Sample for String::Equals(Object)
// String::Equals(String)
// String::Equals(String, String)
using namespace System;
using namespace System::Text;
int main()
{
StringBuilder^ sb = gcnew StringBuilder( "abcd" );
String^ str1 = "abcd";
String^ str2 = nullptr;
Object^ o2 = nullptr;
Console::WriteLine();
Console::WriteLine( " * The value of String str1 is '{0}'.", str1 );
Console::WriteLine( " * The value of StringBuilder sb is '{0}'.", sb );
Console::WriteLine();
Console::WriteLine( "1a) String::Equals(Object). Object is a StringBuilder, not a String." );
Console::WriteLine( " Is str1 equal to sb?: {0}", str1->Equals( sb ) );
Console::WriteLine();
Console::WriteLine( "1b) String::Equals(Object). Object is a String." );
str2 = sb->ToString();
o2 = str2;
Console::WriteLine( " * The value of Object o2 is '{0}'.", o2 );
Console::WriteLine( " Is str1 equal to o2?: {0}", str1->Equals( o2 ) );
Console::WriteLine();
Console::WriteLine( " 2) String::Equals(String)" );
Console::WriteLine( " * The value of String str2 is '{0}'.", str2 );
Console::WriteLine( " Is str1 equal to str2?: {0}", str1->Equals( str2 ) );
Console::WriteLine();
Console::WriteLine( " 3) String::Equals(String, String)" );
Console::WriteLine( " Is str1 equal to str2?: {0}", String::Equals( str1, str2 ) );
}
/*
This example produces the following results:
* The value of String str1 is 'abcd'.
* The value of StringBuilder sb is 'abcd'.
1a) String::Equals(Object). Object is a StringBuilder, not a String.
Is str1 equal to sb?: False
1b) String::Equals(Object). Object is a String.
* The value of Object o2 is 'abcd'.
Is str1 equal to o2?: True
2) String::Equals(String)
* The value of String str2 is 'abcd'.
Is str1 equal to str2?: True
3) String::Equals(String, String)
Is str1 equal to str2?: True
*/
//</snippet1>
| 35.821429 | 97 | 0.614158 | hamarb123 |
1406de2798c39a32a6fa42099bba06066254b323 | 4,720 | cpp | C++ | libs/vision/src/pnp/lhm.cpp | zarmomin/mrpt | 1baff7cf8ec9fd23e1a72714553bcbd88c201966 | [
"BSD-3-Clause"
] | 1 | 2021-12-10T06:24:08.000Z | 2021-12-10T06:24:08.000Z | libs/vision/src/pnp/lhm.cpp | gao-ouyang/mrpt | 4af5fdf7e45b00be4a64c3d4f009acb9ef415ec7 | [
"BSD-3-Clause"
] | null | null | null | libs/vision/src/pnp/lhm.cpp | gao-ouyang/mrpt | 4af5fdf7e45b00be4a64c3d4f009acb9ef415ec7 | [
"BSD-3-Clause"
] | 1 | 2019-09-11T02:55:04.000Z | 2019-09-11T02:55:04.000Z | /* +------------------------------------------------------------------------+
| Mobile Robot Programming Toolkit (MRPT) |
| https://www.mrpt.org/ |
| |
| Copyright (c) 2005-2019, Individual contributors, see AUTHORS file |
| See: https://www.mrpt.org/Authors - All rights reserved. |
| Released under BSD License. See: https://www.mrpt.org/License |
+------------------------------------------------------------------------+ */
#include <iostream>
#include "vision-precomp.h" // Precompiled headers
//#include <mrpt/math/types_math.h> // Eigen must be included first via MRPT to
// enable the plugin system
#include <Eigen/Dense>
#include <Eigen/SVD>
#include <Eigen/StdVector>
#include "lhm.h"
using namespace mrpt::vision::pnp;
lhm::lhm(
Eigen::MatrixXd obj_pts_, Eigen::MatrixXd img_pts_, Eigen::MatrixXd cam_,
int n0)
: F(n0)
{
obj_pts = obj_pts_;
img_pts = img_pts_;
cam_intrinsic = cam_;
n = n0;
// Store obj_pts as 3XN and img_projections as 2XN matrices
P = obj_pts.transpose();
Q = Eigen::MatrixXd::Ones(3, n);
Q = img_pts.transpose();
t.setZero();
}
void lhm::estimate_t()
{
Eigen::Vector3d sum_;
sum_.setZero();
for (int i = 0; i < n; i++) sum_ += F[i] * R * P.col(i);
t = G * sum_;
}
void lhm::xform()
{
for (int i = 0; i < n; i++) Q.col(i) = R * P.col(i) + t;
}
Eigen::Matrix4d lhm::qMatQ(Eigen::VectorXd q)
{
Eigen::Matrix4d Q_(4, 4);
Q_ << q(0), -q(1), -q(2), -q(3), q(1), q(0), -q(3), q(2), q(2), q(3), q(0),
-q(1), q(3), -q(2), q(1), q(0);
return Q_;
}
Eigen::Matrix4d lhm::qMatW(Eigen::VectorXd q)
{
Eigen::Matrix4d Q_(4, 4);
Q_ << q(0), -q(1), -q(2), -q(3), q(1), q(0), q(3), -q(2), q(2), -q(3), q(0),
q(1), q(3), q(2), -q(1), q(0);
return Q_;
}
void lhm::absKernel()
{
for (int i = 0; i < n; i++) Q.col(i) = F[i] * Q.col(i);
Eigen::Vector3d P_bar, Q_bar;
P_bar = P.rowwise().mean();
Q_bar = Q.rowwise().mean();
for (int i = 0; i < n; i++)
{
P.col(i) = P.col(i) - P_bar;
Q.col(i) = Q.col(i) - Q_bar;
}
//<------------------- Use SVD Solution ------------------->//
/*
Eigen::Matrix3d M;
M.setZero();
for (i = 0; i < n; i++)
M += P.col(i)*Q.col(i).transpose();
Eigen::JacobiSVD<Eigen::MatrixXd> svd(M, Eigen::ComputeThinU |
Eigen::ComputeThinV);
R = svd.matrixV()*svd.matrixU().transpose();
Eigen::Matrix3d dummy;
dummy.col(0) = -svd.matrixV().col(0);
dummy.col(1) = -svd.matrixV().col(1);
dummy.col(2) = svd.matrixV().col(2);
if (R.determinant() == 1)
{
estimate_t();
if (t(2) < 0)
{
R = dummy*svd.matrixU().transpose();
estimate_t();
}
}
else
{
R = -dummy*svd.matrixU().transpose();
estimate_t();
if (t(2) < 0)
{
R = -svd.matrixV()*svd.matrixU().transpose();
estimate_t();
}
}
err2 = 0;
xform();
Eigen::Vector3d vec;
Eigen::Matrix3d I3 = Eigen::MatrixXd::Identity(3, 3);
for (i = 0; i < n; i++)
{
vec = (I3 - F[i])*Q.col(i);
err2 += vec.squaredNorm();
}
*/
//<------------------- Use QTN Solution ------------------->//
Eigen::Matrix4d A;
A.setZero();
for (int i = 0; i < n; i++)
{
Eigen::Vector4d q1, q2;
q1 << 1, Q.col(i);
q2 << 1, P.col(i);
A += qMatQ(q1).transpose() * qMatW(q2);
}
Eigen::EigenSolver<Eigen::Matrix4d> es(A);
const Eigen::Matrix4d Ae = es.pseudoEigenvalueMatrix();
Eigen::Vector4d D; // Ae.diagonal(); for some reason this leads to an
// internal compiler error in MSVC11... (sigh)
for (int i = 0; i < 4; i++) D[i] = Ae(i, i);
Eigen::Matrix4d V_mat = es.pseudoEigenvectors();
Eigen::Vector4d::Index max_index;
D.maxCoeff(&max_index);
Eigen::Vector4d V;
V = V_mat.col(max_index);
Eigen::Quaterniond q(V(0), V(1), V(2), V(3));
R = q.toRotationMatrix();
estimate_t();
err2 = 0;
xform();
Eigen::Vector3d vec;
Eigen::Matrix3d I3 = Eigen::MatrixXd::Identity(3, 3);
for (int i = 0; i < n; i++)
{
vec = (I3 - F[i]) * Q.col(i);
err2 += vec.squaredNorm();
}
}
bool lhm::compute_pose(
Eigen::Ref<Eigen::Matrix3d> R_, Eigen::Ref<Eigen::Vector3d> t_)
{
int i, j = 0;
Eigen::VectorXd p_bar;
Eigen::Matrix3d sum_F, I3;
I3 = Eigen::MatrixXd::Identity(3, 3);
sum_F.setZero();
p_bar = P.rowwise().mean();
for (i = 0; i < n; i++)
{
P.col(i) -= p_bar;
F[i] = Q.col(i) * Q.col(i).transpose() / Q.col(i).squaredNorm();
sum_F = sum_F + F[i];
}
G = (I3 - sum_F / n).inverse() / n;
err = 0;
err2 = 1000;
absKernel();
while (std::abs(err2 - err) > TOL_LHM && err2 > EPSILON_LHM)
{
err = err2;
absKernel();
j += 1;
if (j > 100) break;
}
R_ = R;
t_ = t - R * p_bar;
return true;
}
| 20.792952 | 80 | 0.528178 | zarmomin |
14096755a4b69d0e141e87a956c5147ad7a26c71 | 6,436 | cpp | C++ | friend_functions.cpp | portfoliocourses/cplusplus-example-code | 629a16c52fdee1b59896951235be59be096b0359 | [
"MIT"
] | null | null | null | friend_functions.cpp | portfoliocourses/cplusplus-example-code | 629a16c52fdee1b59896951235be59be096b0359 | [
"MIT"
] | null | null | null | friend_functions.cpp | portfoliocourses/cplusplus-example-code | 629a16c52fdee1b59896951235be59be096b0359 | [
"MIT"
] | null | null | null | /*******************************************************************************
*
* Program: Friend Functions Examples
*
* Description: Examples of how to use friend functions in C++.
*
* YouTube Lesson: https://www.youtube.com/watch?v=lOfI1At3tKM
*
* Author: Kevin Browne @ https://portfoliocourses.com
*
*******************************************************************************/
#include <iostream>
using namespace std;
// A simple class with some private members
class MyClass
{
// We declare a 'friend function' double_x that will be allowed access to any
// protected and private members of MyClass objects. The friend function is
// NOT a member function of MyClass. We could put this declaration beneath
// the public or private access specifiers and it would work the same as it
// does here, because it is NOT a member of MyClass.
friend void double_x(MyClass &object);
private:
// a private member variable x
int x;
// a private member function add that adds an int argument provided to x
void add(int n)
{
x += n;
}
public:
// a constructor that sets the member variable x to the int argument provided
MyClass(int x) : x(x) {};
// A public member function that prints out the value of member variable x...
// MyClass CAN access private members of MyClass, but the "outside world"
// such as the main function cannot... friend functions will *also* be able
// to access private and protected members!
void print()
{
cout << "x: " << x << endl;
}
};
// We define the friend function double_x and because it is declared a friend
// function inside MyClass (notice the friend keyword is absent here) we can
// access the private and protected members of the MyClass object instance.
void double_x(MyClass &object)
{
// access the private member variable x, store it into current_x_value
int current_x_value = object.x;
// use the private member function add to add the current_x_value to itself,
// having the effect of doubling x
object.add(current_x_value);
// Alternatively we could have accessed the private member variable x directly
// in order to double it like this...
//
// object.x *= 2;
}
// A friend function can also be a friend to multiple classes, here we have an
// example of a friend function that is a friend to both a Revenue1 class and a
// Costs1 class.
// forward declaration of Costs1 so we can use it in the Revenue1 class
class Costs1;
// A very simple class for representing revenue
class Revenue1
{
// declare friend function profit1
friend bool profit1(Revenue1 rev, Costs1 cos);
private:
// private member variable revenue for representing revenue
int revenue;
public:
// construct sets the revenue member variable to the int argument provided
Revenue1(int revenue) : revenue(revenue) {}
};
// A very simple class for representing costs
class Costs1
{
// we ALSO declare the profit1 function as a friend of Costs1
friend bool profit1(Revenue1 rev, Costs1 cos);
private:
// private member variable for representing costs
int costs;
public:
// Constructor for setting the costs member variable
Costs1(int costs) : costs(costs) {}
};
// The profit1() function will have access to the protected and private members
// of BOTH Revenue1 AND Costs1 because both classes declare it as a friend
// function! We return true if revenue is greater than costs (as this would
// represent a profit), otherwise we return false.
bool profit1(Revenue1 rev, Costs1 cos)
{
if (rev.revenue > cos.costs) return true;
else return false;
}
// A friend function can also be a member function of another class! Here we
// re-work the above example to make the profit2 function a member of class
// Revenue2 and a friend function of Costs2.
// Again we provide a forward declaration of Costs2
class Costs2;
// A simple class for representing revenues
class Revenue2
{
private:
// a private member variable for representing the revenue
int revenue;
public:
// Construct sets revenue member variable to the int argument provided
Revenue2(int revenue) : revenue(revenue) {}
// profit2 is a member variable of Revenue2 (we will define it later) and it
// will be a friend function of the Costs2 class
bool profit2(Costs2 cos);
};
// A simple class for representing costs
class Costs2
{
// profit2 is a member function of Revenue2 (notice Revenue2::) BUT is also
// declared as a friend function of Class2 below
friend bool Revenue2::profit2(Costs2 cos);
private:
// private member variable for representing costs
int costs;
public:
// Constructor sets costs member variable to the int argument provided
Costs2(int costs) : costs(costs) {}
};
// Define the Revenue2 member function profit2... because it is a friend of
// Costs2 it will have access to the private and protected members of the
// Costs2 object. We return return if revenue is greater than costs, and
// false otherwise.
bool Revenue2::profit2(Costs2 cos)
{
if (revenue > cos.costs) return true;
else return false;
}
// Test out the above classes
int main()
{
// Create an instance of MyClass with x set to 7
MyClass myobject(7);
// Call print to print out the current value of x
myobject.print();
// Use friend function double_x() to double the value of x... notice how we
// do NOT call it like a member function (e.g. my.object.doublex(...)) because
// it is NOT a member function of MyClass objects.
double_x(myobject);
// Print out the current value of x again to verify that it has doubled to 14
myobject.print();
// Create Revenue1 and Costs1 objects, here revenue is greater than costs
Revenue1 revenue1(1000);
Costs1 costs1(500);
// Use the profit1() function which is a friend of both Revenue1 and Costs1
// classes, and we should report that a profit has occurred
if (profit1(revenue1, costs1)) cout << "Profit!" << endl;
else cout << "No profit!" << endl;
// Create Revenue2 and Costs2 objects, here revenue is not greater than costs
Revenue2 revenue2(500);
Costs2 costs2(1000);
// Use the profit2() member function of the Revenue2 object revenue2 which is
// ALSO a friend of the Costs2 class, and we should report no profit this time
if (revenue2.profit2(costs2)) cout << "Profit!" << endl;
else cout << "No profit!" << endl;
return 0;
} | 29.388128 | 80 | 0.699037 | portfoliocourses |
140defc8281e5d5db4e0b27685869396b61c5fed | 84 | cpp | C++ | ARM/NXP/LPC11xx/src/i2c_lpc11uxx.cpp | SoniaZotz/IOsonata | a0eaa1d0bf1d23785af6af037d84d87348dc4597 | [
"MIT"
] | 94 | 2015-03-12T14:49:43.000Z | 2021-08-05T00:43:50.000Z | ARM/NXP/LPC11xx/src/i2c_lpc11uxx.cpp | SoniaZotz/IOsonata | a0eaa1d0bf1d23785af6af037d84d87348dc4597 | [
"MIT"
] | 10 | 2019-10-16T19:02:47.000Z | 2022-02-27T21:35:56.000Z | ARM/NXP/LPC11xx/src/i2c_lpc11uxx.cpp | SoniaZotz/IOsonata | a0eaa1d0bf1d23785af6af037d84d87348dc4597 | [
"MIT"
] | 24 | 2015-04-22T20:35:28.000Z | 2022-01-10T13:08:40.000Z | /*
* i2c_lpc11uxx.cpp
*
* Created on: Mar. 1, 2019
* Author: hoan
*/
| 7.636364 | 28 | 0.5 | SoniaZotz |
140df09b935ce8eeea5e04c46b343522603269d5 | 3,686 | cpp | C++ | log/source/ConfiguracionLogger.cpp | miglesias91/herramientas_desarrollo | dad021289e6562b925444b04af2b06b1272fd70c | [
"MIT"
] | null | null | null | log/source/ConfiguracionLogger.cpp | miglesias91/herramientas_desarrollo | dad021289e6562b925444b04af2b06b1272fd70c | [
"MIT"
] | null | null | null | log/source/ConfiguracionLogger.cpp | miglesias91/herramientas_desarrollo | dad021289e6562b925444b04af2b06b1272fd70c | [
"MIT"
] | null | null | null | #include <log/include/ConfiguracionLogger.h>
using namespace herramientas::log;
// stl
#include <fstream>
#include <sstream>
// utiles
#include <utiles/include/Fecha.h>
#include <utiles/include/Json.h>
ConfiguracionLogger::ConfiguracionLogger(std::string path_archivo_configuracion)
{
if (false == path_archivo_configuracion.empty())
{
this->leerConfiguracion(path_archivo_configuracion);
}
}
ConfiguracionLogger::~ConfiguracionLogger()
{
}
void ConfiguracionLogger::leerConfiguracion(std::string path_archivo_configuracion)
{
std::ifstream archivo(path_archivo_configuracion);
if (false == archivo.good())
{
throw - 1;
}
std::ostringstream sstream;
sstream << archivo.rdbuf();
const std::string string_config(sstream.str());
herramientas::utiles::Json config_json(string_config);
herramientas::utiles::Json * config_log_json = config_json.getAtributoValorJson("log");
this->activado = config_log_json->getAtributoValorBool(ConfiguracionLogger::tagActivado());
this->nombre_logger = config_log_json->getAtributoValorString(ConfiguracionLogger::tagNombreLogger());
this->tamanio_cola_async = config_log_json->getAtributoValorUint(ConfiguracionLogger::tagTamanioColaAsync());
this->nivel_log = config_log_json->getAtributoValorString(ConfiguracionLogger::tagNivelLog().c_str());
this->nivel_flush = config_log_json->getAtributoValorString(ConfiguracionLogger::tagNivelFlush().c_str());
this->patron = config_log_json->getAtributoValorString(ConfiguracionLogger::tagPatron());
this->agrupar_por_fecha = config_log_json->getAtributoValorBool(ConfiguracionLogger::tagAgruparPorFecha());
this->salidas_logger = config_log_json->getAtributoArrayString(ConfiguracionLogger::tagSalidas());
delete config_log_json;
}
// CONFIGURACIONES
bool ConfiguracionLogger::getActivado()
{
return this->activado;
}
std::string ConfiguracionLogger::getNombreLogger()
{
return this->nombre_logger;
}
uint64_t ConfiguracionLogger::getTamanioColaAsync()
{
return this->tamanio_cola_async;
}
bool ConfiguracionLogger::getAgruparPorFecha()
{
return this->agrupar_por_fecha;
}
std::string ConfiguracionLogger::getNivelLog()
{
return this->nivel_log;
}
std::string ConfiguracionLogger::getNivelFlush()
{
return this->nivel_flush;
}
std::string ConfiguracionLogger::getPatron()
{
return this->patron;
}
std::vector<std::string> ConfiguracionLogger::getSalidas()
{
std::vector<std::string> salidas = this->salidas_logger;
if (this->getAgruparPorFecha())
{
std::string string_fecha_actual = herramientas::utiles::Fecha::getFechaActual().getStringAAAAMMDD();
for (std::vector<std::string>::iterator it = salidas.begin(); it != salidas.end(); it++)
{
*it = string_fecha_actual + "_" + *it;
}
}
return salidas;
}
// TAGS
std::string ConfiguracionLogger::tagActivado()
{
return "activado";
}
std::string ConfiguracionLogger::tagNombreLogger()
{
return "nombre";
}
std::string ConfiguracionLogger::tagTamanioColaAsync()
{
return "tamanio_cola_async";
}
std::string ConfiguracionLogger::tagAgruparPorFecha()
{
return "agrupar_por_fecha";
}
std::string ConfiguracionLogger::tagNivelLog()
{
return "nivel_log";
}
std::string ConfiguracionLogger::tagNivelFlush()
{
return "nivel_flush";
}
std::string ConfiguracionLogger::tagPatron()
{
return "patron";
}
std::string ConfiguracionLogger::tagSalidas()
{
return "salidas";
}
| 24.738255 | 114 | 0.704829 | miglesias91 |
140fac534dda0b13fb63ab566e55fc0f47ca6057 | 2,232 | cpp | C++ | OCTLib/code/phase_calibration.cpp | wjh1001/octlab | 77be6161a31d2f40af238f394ee8d486e050cf73 | [
"BSD-3-Clause-Clear"
] | 1 | 2015-05-31T11:03:55.000Z | 2015-05-31T11:03:55.000Z | OCTLib/code/phase_calibration.cpp | caoyuan0923/octlab | 77be6161a31d2f40af238f394ee8d486e050cf73 | [
"BSD-3-Clause-Clear"
] | null | null | null | OCTLib/code/phase_calibration.cpp | caoyuan0923/octlab | 77be6161a31d2f40af238f394ee8d486e050cf73 | [
"BSD-3-Clause-Clear"
] | null | null | null | /*******************************************************************************
* $Id$
* Copyright (C) 2010 Stepan A. Baranov (stepan@baranov.su)
* All rights reserved.
* web-site: www.OCTLab.org
* ***** ******* *****
* Use of this source code is governed by a Clear BSD-style license that can be
* found on the http://octlab.googlecode.com/svn/trunk/COPYRIGHT.TXT web-page or
* in the COPYRIGHT.TXT file
*******************************************************************************/
// common header
#include "./OCTLib.h"
// for DLL export
extern "C" {
DllExport I8 OL_phase_calibration(U32, U32, U32, DBL *, DBL *);
}
/* phase calibration main function
PURPOSE:
calculate corrected phase based on phase information from calibration mirror
[1].
INPUTS:
X - number of elements in each row (A-scan size)
Y - number of rows (# of A-scans)
level - the depth position of calibration mirror reflector
ref - pointer to buffer with phase B-scan after FFT from calibration mirror
(size: X * Y)
OUTPUTS:
out - pointer to buffer with phase B-scan after FFT from sample
(size: X * Y)
REMARKS:
note that for all depth indexes below level the phase correction is taken
without calibration coefficient.
REFERENCES:
[1] B. J. Vakoc, S. H. Yun, J. F. de Boer, G. J. Tearney, and B. E. Bouma,
"Phase-resolved optical frequency domain imaging", Opt. Express 13,
5483-5493 (2005)
*/
I8 OL_phase_calibration(U32 X, U32 Y, U32 level, DBL *ref, DBL *ptr) {
I32 i, j;
// simple checks
if (level < 1) return EXIT_FAILURE;
#pragma omp parallel for default(shared) private(i, j)
for (i = 0; i < static_cast<I32>(Y); i++)
for (j = 0; j < static_cast<I32>(X); j++)
if (j < static_cast<I32>(level))
ptr[i * X + j] = ptr[i * X + j] - ref[i] * j / level;
else
ptr[i * X + j] = ptr[i * X + j] - ref[i];
return EXIT_SUCCESS;
}
/*******************************************************************************
Checked by http://google-styleguide.googlecode.com/svn/trunk/cpplint/cpplint.py
*******************************************************************************/
| 36 | 80 | 0.537634 | wjh1001 |
1411ed3837576e17f0f96af7faa51ba74d33e139 | 4,537 | hpp | C++ | src/rdb_protocol/batching.hpp | sauter-hq/rethinkdb | f34541d501bcf109c2825a7a1b67cf8fd39b9133 | [
"Apache-2.0"
] | null | null | null | src/rdb_protocol/batching.hpp | sauter-hq/rethinkdb | f34541d501bcf109c2825a7a1b67cf8fd39b9133 | [
"Apache-2.0"
] | null | null | null | src/rdb_protocol/batching.hpp | sauter-hq/rethinkdb | f34541d501bcf109c2825a7a1b67cf8fd39b9133 | [
"Apache-2.0"
] | null | null | null | // Copyright 2010-2014 RethinkDB, all rights reserved.
#ifndef RDB_PROTOCOL_BATCHING_HPP_
#define RDB_PROTOCOL_BATCHING_HPP_
#include <utility>
#include "containers/archive/archive.hpp"
#include "containers/archive/versioned.hpp"
#include "rdb_protocol/datum.hpp"
#include "rpc/serialize_macros.hpp"
#include "time.hpp"
template<class T>
class counted_t;
namespace ql {
class datum_t;
class env_t;
enum class batch_type_t {
// A normal batch.
NORMAL = 0,
// The first batch in a series of normal batches. The size limit is reduced
// to help minimizing the latency until a user receives their first response.
NORMAL_FIRST = 1,
// A batch fetched for a terminal or terminal-like term, e.g. a big batched
// insert. Ignores latency caps because the latency the user encounters is
// determined by bandwidth instead.
TERMINAL = 2,
// If we're ordering by an sindex, get a batch with a constant value for
// that sindex. We sometimes need a batch with that invariant for sorting.
// (This replaces that SORTING_HINT_NEXT stuff.)
SINDEX_CONSTANT = 3
};
ARCHIVE_PRIM_MAKE_RANGED_SERIALIZABLE(
batch_type_t, int8_t, batch_type_t::NORMAL, batch_type_t::SINDEX_CONSTANT);
enum ignore_latency_t { NO, YES };
class batcher_t {
public:
bool note_el(const datum_t &t) {
seen_one_el = true;
els_left -= 1;
min_els_left -= 1;
size_left -= serialized_size<cluster_version_t::CLUSTER>(t);
return should_send_batch();
}
bool should_send_batch(
ignore_latency_t ignore_latency = ignore_latency_t::NO) const;
batcher_t(batcher_t &&other) :
batch_type(std::move(other.batch_type)),
seen_one_el(std::move(other.seen_one_el)),
min_els_left(std::move(other.min_els_left)),
els_left(std::move(other.els_left)),
size_left(std::move(other.size_left)),
end_time(std::move(other.end_time)) { }
microtime_t microtime_left() {
microtime_t cur_time = current_microtime();
return end_time > cur_time ? end_time - cur_time : 0;
}
batch_type_t get_batch_type() { return batch_type; }
private:
DISABLE_COPYING(batcher_t);
friend class batchspec_t;
batcher_t(batch_type_t batch_type, int64_t min_els, int64_t max_els,
int64_t max_size, microtime_t end_time);
const batch_type_t batch_type;
bool seen_one_el;
int64_t min_els_left, els_left, size_left;
const microtime_t end_time;
};
class batchspec_t {
public:
static batchspec_t user(batch_type_t batch_type, env_t *env);
static batchspec_t all(); // Gimme everything.
static batchspec_t empty() { return batchspec_t(); }
static batchspec_t default_for(batch_type_t batch_type);
batch_type_t get_batch_type() const { return batch_type; }
batchspec_t with_new_batch_type(batch_type_t new_batch_type) const;
batchspec_t with_min_els(int64_t new_min_els) const;
batchspec_t with_max_dur(int64_t new_max_dur) const;
batchspec_t with_at_most(uint64_t max_els) const;
// These are used to allow batchspecs to override the default ordering on a
// stream. This is only really useful when a stream is being treated as a
// set, as in the case of `include_initial` changefeeds where always using
// `ASCENDING` ordering allows the logic to be simpler.
batchspec_t with_lazy_sorting_override(sorting_t sort) const;
sorting_t lazy_sorting(sorting_t base) const {
return lazy_sorting_override ? *lazy_sorting_override : base;
}
batchspec_t scale_down(int64_t divisor) const;
batcher_t to_batcher() const;
private:
// I made this private and accessible through a static function because it
// was being accidentally default-initialized.
batchspec_t() { } // USE ONLY FOR SERIALIZATION
batchspec_t(batch_type_t batch_type, int64_t min_els, int64_t max_els,
int64_t max_size, int64_t first_scaledown,
int64_t max_dur, microtime_t start_time);
template<cluster_version_t W>
friend void serialize(write_message_t *wm, const batchspec_t &batchspec);
template<cluster_version_t W>
friend archive_result_t deserialize(read_stream_t *s, batchspec_t *batchspec);
batch_type_t batch_type;
int64_t min_els, max_els, max_size, first_scaledown_factor, max_dur;
microtime_t start_time;
boost::optional<sorting_t> lazy_sorting_override;
};
RDB_DECLARE_SERIALIZABLE(batchspec_t);
} // namespace ql
#endif // RDB_PROTOCOL_BATCHING_HPP_
| 36.886179 | 82 | 0.728675 | sauter-hq |
1413dfe7cd85c122d1f627a71f8c04d446f74a28 | 12,668 | cpp | C++ | src/casinocoin/beast/utility/src/beast_PropertyStream.cpp | MassICTBV/casinocoind | 81d6a15a0578c086c1812dd2203c0973099b0061 | [
"BSL-1.0"
] | 1 | 2020-03-17T21:31:14.000Z | 2020-03-17T21:31:14.000Z | src/casinocoin/beast/utility/src/beast_PropertyStream.cpp | MassICTBV/casinocoind | 81d6a15a0578c086c1812dd2203c0973099b0061 | [
"BSL-1.0"
] | 1 | 2018-09-29T17:35:07.000Z | 2018-09-29T17:35:07.000Z | src/casinocoin/beast/utility/src/beast_PropertyStream.cpp | MassICTBV/casinocoind | 81d6a15a0578c086c1812dd2203c0973099b0061 | [
"BSL-1.0"
] | 3 | 2018-07-12T11:34:45.000Z | 2021-09-13T18:08:25.000Z | //------------------------------------------------------------------------------
/*
This file is part of Beast: https://github.com/vinniefalco/Beast
Copyright 2013, Vinnie Falco <vinnie.falco@gmail.com>
Permission to use, copy, modify, and/or distribute this software for any
purpose with or without fee is hereby granted, provided that the above
copyright notice and this permission notice appear in all copies.
THE SOFTWARE IS PROVIDED "AS IS" AND THE AUTHOR DISCLAIMS ALL WARRANTIES
WITH REGARD TO THIS SOFTWARE INCLUDING ALL IMPLIED WARRANTIES OF
MERCHANTABILITY AND FITNESS. IN NO EVENT SHALL THE AUTHOR BE LIABLE FOR
ANY SPECIAL , DIRECT, INDIRECT, OR CONSEQUENTIAL DAMAGES OR ANY DAMAGES
WHATSOEVER RESULTING FROM LOSS OF USE, DATA OR PROFITS, WHETHER IN AN
ACTION OF CONTRACT, NEGLIGENCE OR OTHER TORTIOUS ACTION, ARISING OUT OF
OR IN CONNECTION WITH THE USE OR PERFORMANCE OF THIS SOFTWARE.
*/
//==============================================================================
#include <casinocoin/beast/utility/PropertyStream.h>
#include <algorithm>
#include <cassert>
#include <limits>
#include <iostream>
namespace beast {
//------------------------------------------------------------------------------
//
// Item
//
//------------------------------------------------------------------------------
PropertyStream::Item::Item (Source* source)
: m_source (source)
{
}
PropertyStream::Source& PropertyStream::Item::source() const
{
return *m_source;
}
PropertyStream::Source* PropertyStream::Item::operator-> () const
{
return &source();
}
PropertyStream::Source& PropertyStream::Item::operator* () const
{
return source();
}
//------------------------------------------------------------------------------
//
// Proxy
//
//------------------------------------------------------------------------------
PropertyStream::Proxy::Proxy (
Map const& map, std::string const& key)
: m_map (&map)
, m_key (key)
{
}
PropertyStream::Proxy::Proxy (Proxy const& other)
: m_map (other.m_map)
, m_key (other.m_key)
{
}
PropertyStream::Proxy::~Proxy ()
{
std::string const s (m_ostream.str());
if (! s.empty())
m_map->add (m_key, s);
}
std::ostream& PropertyStream::Proxy::operator<< (
std::ostream& manip (std::ostream&)) const
{
return m_ostream << manip;
}
//------------------------------------------------------------------------------
//
// Map
//
//------------------------------------------------------------------------------
PropertyStream::Map::Map (PropertyStream& stream)
: m_stream (stream)
{
}
PropertyStream::Map::Map (Set& parent)
: m_stream (parent.stream())
{
m_stream.map_begin ();
}
PropertyStream::Map::Map (std::string const& key, Map& map)
: m_stream (map.stream())
{
m_stream.map_begin (key);
}
PropertyStream::Map::Map (std::string const& key, PropertyStream& stream)
: m_stream (stream)
{
m_stream.map_begin (key);
}
PropertyStream::Map::~Map ()
{
m_stream.map_end ();
}
PropertyStream& PropertyStream::Map::stream()
{
return m_stream;
}
PropertyStream const& PropertyStream::Map::stream() const
{
return m_stream;
}
PropertyStream::Proxy PropertyStream::Map::operator[] (std::string const& key)
{
return Proxy (*this, key);
}
//------------------------------------------------------------------------------
//
// Set
//
//------------------------------------------------------------------------------
PropertyStream::Set::Set (std::string const& key, Map& map)
: m_stream (map.stream())
{
m_stream.array_begin (key);
}
PropertyStream::Set::Set (std::string const& key, PropertyStream& stream)
: m_stream (stream)
{
m_stream.array_begin (key);
}
PropertyStream::Set::~Set ()
{
m_stream.array_end ();
}
PropertyStream& PropertyStream::Set::stream()
{
return m_stream;
}
PropertyStream const& PropertyStream::Set::stream() const
{
return m_stream;
}
//------------------------------------------------------------------------------
//
// Source
//
//------------------------------------------------------------------------------
PropertyStream::Source::Source (std::string const& name)
: m_name (name)
, item_ (this)
, parent_ (nullptr)
{
}
PropertyStream::Source::~Source ()
{
std::lock_guard<std::recursive_mutex> _(lock_);
if (parent_ != nullptr)
parent_->remove (*this);
removeAll ();
}
std::string const& PropertyStream::Source::name () const
{
return m_name;
}
void PropertyStream::Source::add (Source& source)
{
std::lock(lock_, source.lock_);
std::lock_guard<std::recursive_mutex> lk1(lock_, std::adopt_lock);
std::lock_guard<std::recursive_mutex> lk2(source.lock_, std::adopt_lock);
assert (source.parent_ == nullptr);
children_.push_back (source.item_);
source.parent_ = this;
}
void PropertyStream::Source::remove (Source& child)
{
std::lock(lock_, child.lock_);
std::lock_guard<std::recursive_mutex> lk1(lock_, std::adopt_lock);
std::lock_guard<std::recursive_mutex> lk2(child.lock_, std::adopt_lock);
assert (child.parent_ == this);
children_.erase (
children_.iterator_to (
child.item_));
child.parent_ = nullptr;
}
void PropertyStream::Source::removeAll ()
{
std::lock_guard<std::recursive_mutex> _(lock_);
for (auto iter = children_.begin(); iter != children_.end(); )
{
std::lock_guard<std::recursive_mutex> _cl((*iter)->lock_);
remove (*(*iter));
}
}
//------------------------------------------------------------------------------
void PropertyStream::Source::write_one (PropertyStream& stream)
{
Map map (m_name, stream);
onWrite (map);
}
void PropertyStream::Source::write (PropertyStream& stream)
{
Map map (m_name, stream);
onWrite (map);
std::lock_guard<std::recursive_mutex> _(lock_);
for (auto& child : children_)
child.source().write (stream);
}
void PropertyStream::Source::write (PropertyStream& stream, std::string const& path)
{
std::pair <Source*, bool> result (find (path));
if (result.first == nullptr)
return;
if (result.second)
result.first->write (stream);
else
result.first->write_one (stream);
}
std::pair <PropertyStream::Source*, bool> PropertyStream::Source::find (std::string path)
{
bool const deep (peel_trailing_slashstar (&path));
bool const rooted (peel_leading_slash (&path));
Source* source (this);
if (! path.empty())
{
if (! rooted)
{
std::string const name (peel_name (&path));
source = find_one_deep (name);
if (source == nullptr)
return std::make_pair (nullptr, deep);
}
source = source->find_path (path);
}
return std::make_pair (source, deep);
}
bool PropertyStream::Source::peel_leading_slash (std::string* path)
{
if (! path->empty() && path->front() == '/')
{
*path = std::string (path->begin() + 1, path->end());
return true;
}
return false;
}
bool PropertyStream::Source::peel_trailing_slashstar (std::string* path)
{
bool found(false);
if (path->empty())
return false;
if (path->back() == '*')
{
found = true;
path->pop_back();
}
if(! path->empty() && path->back() == '/')
path->pop_back();
return found;
}
std::string PropertyStream::Source::peel_name (std::string* path)
{
if (path->empty())
return "";
std::string::const_iterator first = (*path).begin();
std::string::const_iterator last = (*path).end();
std::string::const_iterator pos = std::find (first, last, '/');
std::string s (first, pos);
if (pos != last)
*path = std::string (pos+1, last);
else
*path = std::string ();
return s;
}
// Recursive search through the whole tree until name is found
PropertyStream::Source* PropertyStream::Source::find_one_deep (std::string const& name)
{
Source* found = find_one (name);
if (found != nullptr)
return found;
std::lock_guard<std::recursive_mutex> _(lock_);
for (auto& s : children_)
{
found = s.source().find_one_deep (name);
if (found != nullptr)
return found;
}
return nullptr;
}
PropertyStream::Source* PropertyStream::Source::find_path (std::string path)
{
if (path.empty())
return this;
Source* source (this);
do
{
std::string const name (peel_name (&path));
if(name.empty ())
break;
source = source->find_one(name);
}
while (source != nullptr);
return source;
}
// This function only looks at immediate children
// If no immediate children match, then return nullptr
PropertyStream::Source* PropertyStream::Source::find_one (std::string const& name)
{
std::lock_guard<std::recursive_mutex> _(lock_);
for (auto& s : children_)
{
if (s.source().m_name == name)
return &s.source();
}
return nullptr;
}
void PropertyStream::Source::onWrite (Map&)
{
}
//------------------------------------------------------------------------------
//
// PropertyStream
//
//------------------------------------------------------------------------------
PropertyStream::PropertyStream ()
{
}
PropertyStream::~PropertyStream ()
{
}
void PropertyStream::add (std::string const& key, bool value)
{
if (value)
add (key, "true");
else
add (key, "false");
}
void PropertyStream::add (std::string const& key, char value)
{
lexical_add (key, value);
}
void PropertyStream::add (std::string const& key, signed char value)
{
lexical_add (key, value);
}
void PropertyStream::add (std::string const& key, unsigned char value)
{
lexical_add (key, value);
}
void PropertyStream::add (std::string const& key, wchar_t value)
{
lexical_add (key, value);
}
#if 0
void PropertyStream::add (std::string const& key, char16_t value)
{
lexical_add (key, value);
}
void PropertyStream::add (std::string const& key, char32_t value)
{
lexical_add (key, value);
}
#endif
void PropertyStream::add (std::string const& key, short value)
{
lexical_add (key, value);
}
void PropertyStream::add (std::string const& key, unsigned short value)
{
lexical_add (key, value);
}
void PropertyStream::add (std::string const& key, int value)
{
lexical_add (key, value);
}
void PropertyStream::add (std::string const& key, unsigned int value)
{
lexical_add (key, value);
}
void PropertyStream::add (std::string const& key, long value)
{
lexical_add (key, value);
}
void PropertyStream::add (std::string const& key, unsigned long value)
{
lexical_add (key, value);
}
void PropertyStream::add (std::string const& key, long long value)
{
lexical_add (key, value);
}
void PropertyStream::add (std::string const& key, unsigned long long value)
{
lexical_add (key, value);
}
void PropertyStream::add (std::string const& key, float value)
{
lexical_add (key, value);
}
void PropertyStream::add (std::string const& key, double value)
{
lexical_add (key, value);
}
void PropertyStream::add (std::string const& key, long double value)
{
lexical_add (key, value);
}
void PropertyStream::add (bool value)
{
if (value)
add ("true");
else
add ("false");
}
void PropertyStream::add (char value)
{
lexical_add (value);
}
void PropertyStream::add (signed char value)
{
lexical_add (value);
}
void PropertyStream::add (unsigned char value)
{
lexical_add (value);
}
void PropertyStream::add (wchar_t value)
{
lexical_add (value);
}
#if 0
void PropertyStream::add (char16_t value)
{
lexical_add (value);
}
void PropertyStream::add (char32_t value)
{
lexical_add (value);
}
#endif
void PropertyStream::add (short value)
{
lexical_add (value);
}
void PropertyStream::add (unsigned short value)
{
lexical_add (value);
}
void PropertyStream::add (int value)
{
lexical_add (value);
}
void PropertyStream::add (unsigned int value)
{
lexical_add (value);
}
void PropertyStream::add (long value)
{
lexical_add (value);
}
void PropertyStream::add (unsigned long value)
{
lexical_add (value);
}
void PropertyStream::add (long long value)
{
lexical_add (value);
}
void PropertyStream::add (unsigned long long value)
{
lexical_add (value);
}
void PropertyStream::add (float value)
{
lexical_add (value);
}
void PropertyStream::add (double value)
{
lexical_add (value);
}
void PropertyStream::add (long double value)
{
lexical_add (value);
}
}
| 21.916955 | 89 | 0.586517 | MassICTBV |
141442bb280965fafefcd810c2a762ad51690759 | 54,805 | cpp | C++ | core/fpdfapi/page/cpdf_streamcontentparser.cpp | guidopola/pdfium | 4117500e4809c74ec7f800f1729dcffa2ce54874 | [
"BSD-3-Clause"
] | 1 | 2019-01-12T07:08:25.000Z | 2019-01-12T07:08:25.000Z | core/fpdfapi/page/cpdf_streamcontentparser.cpp | guidopola/pdfium | 4117500e4809c74ec7f800f1729dcffa2ce54874 | [
"BSD-3-Clause"
] | null | null | null | core/fpdfapi/page/cpdf_streamcontentparser.cpp | guidopola/pdfium | 4117500e4809c74ec7f800f1729dcffa2ce54874 | [
"BSD-3-Clause"
] | 1 | 2019-09-20T07:47:55.000Z | 2019-09-20T07:47:55.000Z | // Copyright 2016 PDFium Authors. All rights reserved.
// Use of this source code is governed by a BSD-style license that can be
// found in the LICENSE file.
// Original code copyright 2014 Foxit Software Inc. http://www.foxitsoftware.com
#include "core/fpdfapi/page/cpdf_streamcontentparser.h"
#include <memory>
#include <utility>
#include <vector>
#include "core/fpdfapi/font/cpdf_font.h"
#include "core/fpdfapi/font/cpdf_type3font.h"
#include "core/fpdfapi/page/cpdf_allstates.h"
#include "core/fpdfapi/page/cpdf_docpagedata.h"
#include "core/fpdfapi/page/cpdf_form.h"
#include "core/fpdfapi/page/cpdf_formobject.h"
#include "core/fpdfapi/page/cpdf_image.h"
#include "core/fpdfapi/page/cpdf_imageobject.h"
#include "core/fpdfapi/page/cpdf_meshstream.h"
#include "core/fpdfapi/page/cpdf_pageobject.h"
#include "core/fpdfapi/page/cpdf_pathobject.h"
#include "core/fpdfapi/page/cpdf_shadingobject.h"
#include "core/fpdfapi/page/cpdf_shadingpattern.h"
#include "core/fpdfapi/page/cpdf_streamparser.h"
#include "core/fpdfapi/page/cpdf_textobject.h"
#include "core/fpdfapi/page/pageint.h"
#include "core/fpdfapi/parser/cpdf_array.h"
#include "core/fpdfapi/parser/cpdf_dictionary.h"
#include "core/fpdfapi/parser/cpdf_document.h"
#include "core/fpdfapi/parser/cpdf_name.h"
#include "core/fpdfapi/parser/cpdf_number.h"
#include "core/fpdfapi/parser/cpdf_reference.h"
#include "core/fpdfapi/parser/cpdf_stream.h"
#include "core/fpdfapi/parser/fpdf_parser_decode.h"
#include "core/fxcrt/fx_safe_types.h"
#include "core/fxge/cfx_graphstatedata.h"
#include "third_party/base/ptr_util.h"
namespace {
const int kMaxFormLevel = 30;
const int kSingleCoordinatePair = 1;
const int kTensorCoordinatePairs = 16;
const int kCoonsCoordinatePairs = 12;
const int kSingleColorPerPatch = 1;
const int kQuadColorsPerPatch = 4;
const char kPathOperatorSubpath = 'm';
const char kPathOperatorLine = 'l';
const char kPathOperatorCubicBezier1 = 'c';
const char kPathOperatorCubicBezier2 = 'v';
const char kPathOperatorCubicBezier3 = 'y';
const char kPathOperatorClosePath = 'h';
const char kPathOperatorRectangle[] = "re";
class CPDF_StreamParserAutoClearer {
public:
CPDF_StreamParserAutoClearer(CPDF_StreamParser** scoped_variable,
CPDF_StreamParser* new_parser)
: scoped_variable_(scoped_variable) {
*scoped_variable_ = new_parser;
}
~CPDF_StreamParserAutoClearer() { *scoped_variable_ = nullptr; }
private:
CPDF_StreamParser** scoped_variable_;
};
CFX_FloatRect GetShadingBBox(CPDF_ShadingPattern* pShading,
const CFX_Matrix& matrix) {
ShadingType type = pShading->GetShadingType();
CPDF_Stream* pStream = ToStream(pShading->GetShadingObject());
CPDF_ColorSpace* pCS = pShading->GetCS();
if (!pStream || !pCS)
return CFX_FloatRect(0, 0, 0, 0);
CPDF_MeshStream stream(type, pShading->GetFuncs(), pStream, pCS);
if (!stream.Load())
return CFX_FloatRect(0, 0, 0, 0);
CFX_FloatRect rect;
bool bStarted = false;
bool bGouraud = type == kFreeFormGouraudTriangleMeshShading ||
type == kLatticeFormGouraudTriangleMeshShading;
int point_count = kSingleCoordinatePair;
if (type == kTensorProductPatchMeshShading)
point_count = kTensorCoordinatePairs;
else if (type == kCoonsPatchMeshShading)
point_count = kCoonsCoordinatePairs;
int color_count = kSingleColorPerPatch;
if (type == kCoonsPatchMeshShading || type == kTensorProductPatchMeshShading)
color_count = kQuadColorsPerPatch;
while (!stream.BitStream()->IsEOF()) {
uint32_t flag = 0;
if (type != kLatticeFormGouraudTriangleMeshShading)
flag = stream.GetFlag();
if (!bGouraud && flag) {
point_count -= 4;
color_count -= 2;
}
for (int i = 0; i < point_count; i++) {
FX_FLOAT x;
FX_FLOAT y;
stream.GetCoords(x, y);
if (bStarted) {
rect.UpdateRect(x, y);
} else {
rect.InitRect(x, y);
bStarted = true;
}
}
FX_SAFE_UINT32 nBits = stream.Components();
nBits *= stream.ComponentBits();
nBits *= color_count;
if (!nBits.IsValid())
break;
stream.BitStream()->SkipBits(nBits.ValueOrDie());
if (bGouraud)
stream.BitStream()->ByteAlign();
}
rect.Transform(&matrix);
return rect;
}
struct AbbrPair {
const FX_CHAR* abbr;
const FX_CHAR* full_name;
};
const AbbrPair InlineKeyAbbr[] = {
{"BPC", "BitsPerComponent"}, {"CS", "ColorSpace"}, {"D", "Decode"},
{"DP", "DecodeParms"}, {"F", "Filter"}, {"H", "Height"},
{"IM", "ImageMask"}, {"I", "Interpolate"}, {"W", "Width"},
};
const AbbrPair InlineValueAbbr[] = {
{"G", "DeviceGray"}, {"RGB", "DeviceRGB"},
{"CMYK", "DeviceCMYK"}, {"I", "Indexed"},
{"AHx", "ASCIIHexDecode"}, {"A85", "ASCII85Decode"},
{"LZW", "LZWDecode"}, {"Fl", "FlateDecode"},
{"RL", "RunLengthDecode"}, {"CCF", "CCITTFaxDecode"},
{"DCT", "DCTDecode"},
};
struct AbbrReplacementOp {
bool is_replace_key;
CFX_ByteString key;
CFX_ByteStringC replacement;
};
CFX_ByteStringC FindFullName(const AbbrPair* table,
size_t count,
const CFX_ByteStringC& abbr) {
auto it = std::find_if(table, table + count, [abbr](const AbbrPair& pair) {
return pair.abbr == abbr;
});
return it != table + count ? CFX_ByteStringC(it->full_name)
: CFX_ByteStringC();
}
void ReplaceAbbr(CPDF_Object* pObj) {
switch (pObj->GetType()) {
case CPDF_Object::DICTIONARY: {
CPDF_Dictionary* pDict = pObj->AsDictionary();
std::vector<AbbrReplacementOp> replacements;
for (const auto& it : *pDict) {
CFX_ByteString key = it.first;
CPDF_Object* value = it.second.get();
CFX_ByteStringC fullname = FindFullName(
InlineKeyAbbr, FX_ArraySize(InlineKeyAbbr), key.AsStringC());
if (!fullname.IsEmpty()) {
AbbrReplacementOp op;
op.is_replace_key = true;
op.key = key;
op.replacement = fullname;
replacements.push_back(op);
key = fullname;
}
if (value->IsName()) {
CFX_ByteString name = value->GetString();
fullname = FindFullName(
InlineValueAbbr, FX_ArraySize(InlineValueAbbr), name.AsStringC());
if (!fullname.IsEmpty()) {
AbbrReplacementOp op;
op.is_replace_key = false;
op.key = key;
op.replacement = fullname;
replacements.push_back(op);
}
} else {
ReplaceAbbr(value);
}
}
for (const auto& op : replacements) {
if (op.is_replace_key)
pDict->ReplaceKey(op.key, CFX_ByteString(op.replacement));
else
pDict->SetNewFor<CPDF_Name>(op.key, CFX_ByteString(op.replacement));
}
break;
}
case CPDF_Object::ARRAY: {
CPDF_Array* pArray = pObj->AsArray();
for (size_t i = 0; i < pArray->GetCount(); i++) {
CPDF_Object* pElement = pArray->GetObjectAt(i);
if (pElement->IsName()) {
CFX_ByteString name = pElement->GetString();
CFX_ByteStringC fullname = FindFullName(
InlineValueAbbr, FX_ArraySize(InlineValueAbbr), name.AsStringC());
if (!fullname.IsEmpty())
pArray->SetNewAt<CPDF_Name>(i, CFX_ByteString(fullname));
} else {
ReplaceAbbr(pElement);
}
}
break;
}
default:
break;
}
}
} // namespace
CFX_ByteStringC PDF_FindKeyAbbreviationForTesting(const CFX_ByteStringC& abbr) {
return FindFullName(InlineKeyAbbr, FX_ArraySize(InlineKeyAbbr), abbr);
}
CFX_ByteStringC PDF_FindValueAbbreviationForTesting(
const CFX_ByteStringC& abbr) {
return FindFullName(InlineValueAbbr, FX_ArraySize(InlineValueAbbr), abbr);
}
CPDF_StreamContentParser::CPDF_StreamContentParser(
CPDF_Document* pDocument,
CPDF_Dictionary* pPageResources,
CPDF_Dictionary* pParentResources,
const CFX_Matrix* pmtContentToUser,
CPDF_PageObjectHolder* pObjHolder,
CPDF_Dictionary* pResources,
CFX_FloatRect* pBBox,
CPDF_AllStates* pStates,
int level)
: m_pDocument(pDocument),
m_pPageResources(pPageResources),
m_pParentResources(pParentResources),
m_pResources(pResources),
m_pObjectHolder(pObjHolder),
m_Level(level),
m_ParamStartPos(0),
m_ParamCount(0),
m_pCurStates(new CPDF_AllStates),
m_pLastTextObject(nullptr),
m_DefFontSize(0),
m_pPathPoints(nullptr),
m_PathPointCount(0),
m_PathAllocSize(0),
m_PathCurrentX(0.0f),
m_PathCurrentY(0.0f),
m_PathClipType(0),
m_pLastImage(nullptr),
m_bColored(false),
m_bResourceMissing(false) {
if (pmtContentToUser)
m_mtContentToUser = *pmtContentToUser;
if (!m_pResources)
m_pResources = m_pParentResources;
if (!m_pResources)
m_pResources = m_pPageResources;
if (pBBox)
m_BBox = *pBBox;
if (pStates) {
m_pCurStates->Copy(*pStates);
} else {
m_pCurStates->m_GeneralState.Emplace();
m_pCurStates->m_GraphState.Emplace();
m_pCurStates->m_TextState.Emplace();
m_pCurStates->m_ColorState.Emplace();
}
for (size_t i = 0; i < FX_ArraySize(m_Type3Data); ++i) {
m_Type3Data[i] = 0.0;
}
}
CPDF_StreamContentParser::~CPDF_StreamContentParser() {
ClearAllParams();
FX_Free(m_pPathPoints);
}
int CPDF_StreamContentParser::GetNextParamPos() {
if (m_ParamCount == kParamBufSize) {
m_ParamStartPos++;
if (m_ParamStartPos == kParamBufSize) {
m_ParamStartPos = 0;
}
if (m_ParamBuf[m_ParamStartPos].m_Type == ContentParam::OBJECT)
m_ParamBuf[m_ParamStartPos].m_pObject.reset();
return m_ParamStartPos;
}
int index = m_ParamStartPos + m_ParamCount;
if (index >= kParamBufSize) {
index -= kParamBufSize;
}
m_ParamCount++;
return index;
}
void CPDF_StreamContentParser::AddNameParam(const FX_CHAR* name, int len) {
CFX_ByteStringC bsName(name, len);
ContentParam& param = m_ParamBuf[GetNextParamPos()];
if (len > 32) {
param.m_Type = ContentParam::OBJECT;
param.m_pObject = pdfium::MakeUnique<CPDF_Name>(
m_pDocument->GetByteStringPool(), PDF_NameDecode(bsName));
} else {
param.m_Type = ContentParam::NAME;
if (bsName.Find('#') == -1) {
FXSYS_memcpy(param.m_Name.m_Buffer, name, len);
param.m_Name.m_Len = len;
} else {
CFX_ByteString str = PDF_NameDecode(bsName);
FXSYS_memcpy(param.m_Name.m_Buffer, str.c_str(), str.GetLength());
param.m_Name.m_Len = str.GetLength();
}
}
}
void CPDF_StreamContentParser::AddNumberParam(const FX_CHAR* str, int len) {
ContentParam& param = m_ParamBuf[GetNextParamPos()];
param.m_Type = ContentParam::NUMBER;
param.m_Number.m_bInteger =
FX_atonum(CFX_ByteStringC(str, len), ¶m.m_Number.m_Integer);
}
void CPDF_StreamContentParser::AddObjectParam(
std::unique_ptr<CPDF_Object> pObj) {
ContentParam& param = m_ParamBuf[GetNextParamPos()];
param.m_Type = ContentParam::OBJECT;
param.m_pObject = std::move(pObj);
}
void CPDF_StreamContentParser::ClearAllParams() {
uint32_t index = m_ParamStartPos;
for (uint32_t i = 0; i < m_ParamCount; i++) {
if (m_ParamBuf[index].m_Type == ContentParam::OBJECT)
m_ParamBuf[index].m_pObject.reset();
index++;
if (index == kParamBufSize)
index = 0;
}
m_ParamStartPos = 0;
m_ParamCount = 0;
}
CPDF_Object* CPDF_StreamContentParser::GetObject(uint32_t index) {
if (index >= m_ParamCount) {
return nullptr;
}
int real_index = m_ParamStartPos + m_ParamCount - index - 1;
if (real_index >= kParamBufSize) {
real_index -= kParamBufSize;
}
ContentParam& param = m_ParamBuf[real_index];
if (param.m_Type == ContentParam::NUMBER) {
param.m_Type = ContentParam::OBJECT;
param.m_pObject =
param.m_Number.m_bInteger
? pdfium::MakeUnique<CPDF_Number>(param.m_Number.m_Integer)
: pdfium::MakeUnique<CPDF_Number>(param.m_Number.m_Float);
return param.m_pObject.get();
}
if (param.m_Type == ContentParam::NAME) {
param.m_Type = ContentParam::OBJECT;
param.m_pObject = pdfium::MakeUnique<CPDF_Name>(
m_pDocument->GetByteStringPool(),
CFX_ByteString(param.m_Name.m_Buffer, param.m_Name.m_Len));
return param.m_pObject.get();
}
if (param.m_Type == ContentParam::OBJECT)
return param.m_pObject.get();
ASSERT(false);
return nullptr;
}
CFX_ByteString CPDF_StreamContentParser::GetString(uint32_t index) {
if (index >= m_ParamCount) {
return CFX_ByteString();
}
int real_index = m_ParamStartPos + m_ParamCount - index - 1;
if (real_index >= kParamBufSize) {
real_index -= kParamBufSize;
}
ContentParam& param = m_ParamBuf[real_index];
if (param.m_Type == ContentParam::NAME) {
return CFX_ByteString(param.m_Name.m_Buffer, param.m_Name.m_Len);
}
if (param.m_Type == 0 && param.m_pObject) {
return param.m_pObject->GetString();
}
return CFX_ByteString();
}
FX_FLOAT CPDF_StreamContentParser::GetNumber(uint32_t index) {
if (index >= m_ParamCount) {
return 0;
}
int real_index = m_ParamStartPos + m_ParamCount - index - 1;
if (real_index >= kParamBufSize) {
real_index -= kParamBufSize;
}
ContentParam& param = m_ParamBuf[real_index];
if (param.m_Type == ContentParam::NUMBER) {
return param.m_Number.m_bInteger ? (FX_FLOAT)param.m_Number.m_Integer
: param.m_Number.m_Float;
}
if (param.m_Type == 0 && param.m_pObject) {
return param.m_pObject->GetNumber();
}
return 0;
}
void CPDF_StreamContentParser::SetGraphicStates(CPDF_PageObject* pObj,
bool bColor,
bool bText,
bool bGraph) {
pObj->m_GeneralState = m_pCurStates->m_GeneralState;
pObj->m_ClipPath = m_pCurStates->m_ClipPath;
pObj->m_ContentMark = m_CurContentMark;
if (bColor) {
pObj->m_ColorState = m_pCurStates->m_ColorState;
}
if (bGraph) {
pObj->m_GraphState = m_pCurStates->m_GraphState;
}
if (bText) {
pObj->m_TextState = m_pCurStates->m_TextState;
}
}
// static
CPDF_StreamContentParser::OpCodes
CPDF_StreamContentParser::InitializeOpCodes() {
return OpCodes({
{FXBSTR_ID('"', 0, 0, 0),
&CPDF_StreamContentParser::Handle_NextLineShowText_Space},
{FXBSTR_ID('\'', 0, 0, 0),
&CPDF_StreamContentParser::Handle_NextLineShowText},
{FXBSTR_ID('B', 0, 0, 0),
&CPDF_StreamContentParser::Handle_FillStrokePath},
{FXBSTR_ID('B', '*', 0, 0),
&CPDF_StreamContentParser::Handle_EOFillStrokePath},
{FXBSTR_ID('B', 'D', 'C', 0),
&CPDF_StreamContentParser::Handle_BeginMarkedContent_Dictionary},
{FXBSTR_ID('B', 'I', 0, 0), &CPDF_StreamContentParser::Handle_BeginImage},
{FXBSTR_ID('B', 'M', 'C', 0),
&CPDF_StreamContentParser::Handle_BeginMarkedContent},
{FXBSTR_ID('B', 'T', 0, 0), &CPDF_StreamContentParser::Handle_BeginText},
{FXBSTR_ID('C', 'S', 0, 0),
&CPDF_StreamContentParser::Handle_SetColorSpace_Stroke},
{FXBSTR_ID('D', 'P', 0, 0),
&CPDF_StreamContentParser::Handle_MarkPlace_Dictionary},
{FXBSTR_ID('D', 'o', 0, 0),
&CPDF_StreamContentParser::Handle_ExecuteXObject},
{FXBSTR_ID('E', 'I', 0, 0), &CPDF_StreamContentParser::Handle_EndImage},
{FXBSTR_ID('E', 'M', 'C', 0),
&CPDF_StreamContentParser::Handle_EndMarkedContent},
{FXBSTR_ID('E', 'T', 0, 0), &CPDF_StreamContentParser::Handle_EndText},
{FXBSTR_ID('F', 0, 0, 0), &CPDF_StreamContentParser::Handle_FillPathOld},
{FXBSTR_ID('G', 0, 0, 0),
&CPDF_StreamContentParser::Handle_SetGray_Stroke},
{FXBSTR_ID('I', 'D', 0, 0),
&CPDF_StreamContentParser::Handle_BeginImageData},
{FXBSTR_ID('J', 0, 0, 0), &CPDF_StreamContentParser::Handle_SetLineCap},
{FXBSTR_ID('K', 0, 0, 0),
&CPDF_StreamContentParser::Handle_SetCMYKColor_Stroke},
{FXBSTR_ID('M', 0, 0, 0),
&CPDF_StreamContentParser::Handle_SetMiterLimit},
{FXBSTR_ID('M', 'P', 0, 0), &CPDF_StreamContentParser::Handle_MarkPlace},
{FXBSTR_ID('Q', 0, 0, 0),
&CPDF_StreamContentParser::Handle_RestoreGraphState},
{FXBSTR_ID('R', 'G', 0, 0),
&CPDF_StreamContentParser::Handle_SetRGBColor_Stroke},
{FXBSTR_ID('S', 0, 0, 0), &CPDF_StreamContentParser::Handle_StrokePath},
{FXBSTR_ID('S', 'C', 0, 0),
&CPDF_StreamContentParser::Handle_SetColor_Stroke},
{FXBSTR_ID('S', 'C', 'N', 0),
&CPDF_StreamContentParser::Handle_SetColorPS_Stroke},
{FXBSTR_ID('T', '*', 0, 0),
&CPDF_StreamContentParser::Handle_MoveToNextLine},
{FXBSTR_ID('T', 'D', 0, 0),
&CPDF_StreamContentParser::Handle_MoveTextPoint_SetLeading},
{FXBSTR_ID('T', 'J', 0, 0),
&CPDF_StreamContentParser::Handle_ShowText_Positioning},
{FXBSTR_ID('T', 'L', 0, 0),
&CPDF_StreamContentParser::Handle_SetTextLeading},
{FXBSTR_ID('T', 'c', 0, 0),
&CPDF_StreamContentParser::Handle_SetCharSpace},
{FXBSTR_ID('T', 'd', 0, 0),
&CPDF_StreamContentParser::Handle_MoveTextPoint},
{FXBSTR_ID('T', 'f', 0, 0), &CPDF_StreamContentParser::Handle_SetFont},
{FXBSTR_ID('T', 'j', 0, 0), &CPDF_StreamContentParser::Handle_ShowText},
{FXBSTR_ID('T', 'm', 0, 0),
&CPDF_StreamContentParser::Handle_SetTextMatrix},
{FXBSTR_ID('T', 'r', 0, 0),
&CPDF_StreamContentParser::Handle_SetTextRenderMode},
{FXBSTR_ID('T', 's', 0, 0),
&CPDF_StreamContentParser::Handle_SetTextRise},
{FXBSTR_ID('T', 'w', 0, 0),
&CPDF_StreamContentParser::Handle_SetWordSpace},
{FXBSTR_ID('T', 'z', 0, 0),
&CPDF_StreamContentParser::Handle_SetHorzScale},
{FXBSTR_ID('W', 0, 0, 0), &CPDF_StreamContentParser::Handle_Clip},
{FXBSTR_ID('W', '*', 0, 0), &CPDF_StreamContentParser::Handle_EOClip},
{FXBSTR_ID('b', 0, 0, 0),
&CPDF_StreamContentParser::Handle_CloseFillStrokePath},
{FXBSTR_ID('b', '*', 0, 0),
&CPDF_StreamContentParser::Handle_CloseEOFillStrokePath},
{FXBSTR_ID('c', 0, 0, 0), &CPDF_StreamContentParser::Handle_CurveTo_123},
{FXBSTR_ID('c', 'm', 0, 0),
&CPDF_StreamContentParser::Handle_ConcatMatrix},
{FXBSTR_ID('c', 's', 0, 0),
&CPDF_StreamContentParser::Handle_SetColorSpace_Fill},
{FXBSTR_ID('d', 0, 0, 0), &CPDF_StreamContentParser::Handle_SetDash},
{FXBSTR_ID('d', '0', 0, 0),
&CPDF_StreamContentParser::Handle_SetCharWidth},
{FXBSTR_ID('d', '1', 0, 0),
&CPDF_StreamContentParser::Handle_SetCachedDevice},
{FXBSTR_ID('f', 0, 0, 0), &CPDF_StreamContentParser::Handle_FillPath},
{FXBSTR_ID('f', '*', 0, 0), &CPDF_StreamContentParser::Handle_EOFillPath},
{FXBSTR_ID('g', 0, 0, 0), &CPDF_StreamContentParser::Handle_SetGray_Fill},
{FXBSTR_ID('g', 's', 0, 0),
&CPDF_StreamContentParser::Handle_SetExtendGraphState},
{FXBSTR_ID('h', 0, 0, 0), &CPDF_StreamContentParser::Handle_ClosePath},
{FXBSTR_ID('i', 0, 0, 0), &CPDF_StreamContentParser::Handle_SetFlat},
{FXBSTR_ID('j', 0, 0, 0), &CPDF_StreamContentParser::Handle_SetLineJoin},
{FXBSTR_ID('k', 0, 0, 0),
&CPDF_StreamContentParser::Handle_SetCMYKColor_Fill},
{FXBSTR_ID('l', 0, 0, 0), &CPDF_StreamContentParser::Handle_LineTo},
{FXBSTR_ID('m', 0, 0, 0), &CPDF_StreamContentParser::Handle_MoveTo},
{FXBSTR_ID('n', 0, 0, 0), &CPDF_StreamContentParser::Handle_EndPath},
{FXBSTR_ID('q', 0, 0, 0),
&CPDF_StreamContentParser::Handle_SaveGraphState},
{FXBSTR_ID('r', 'e', 0, 0), &CPDF_StreamContentParser::Handle_Rectangle},
{FXBSTR_ID('r', 'g', 0, 0),
&CPDF_StreamContentParser::Handle_SetRGBColor_Fill},
{FXBSTR_ID('r', 'i', 0, 0),
&CPDF_StreamContentParser::Handle_SetRenderIntent},
{FXBSTR_ID('s', 0, 0, 0),
&CPDF_StreamContentParser::Handle_CloseStrokePath},
{FXBSTR_ID('s', 'c', 0, 0),
&CPDF_StreamContentParser::Handle_SetColor_Fill},
{FXBSTR_ID('s', 'c', 'n', 0),
&CPDF_StreamContentParser::Handle_SetColorPS_Fill},
{FXBSTR_ID('s', 'h', 0, 0), &CPDF_StreamContentParser::Handle_ShadeFill},
{FXBSTR_ID('v', 0, 0, 0), &CPDF_StreamContentParser::Handle_CurveTo_23},
{FXBSTR_ID('w', 0, 0, 0), &CPDF_StreamContentParser::Handle_SetLineWidth},
{FXBSTR_ID('y', 0, 0, 0), &CPDF_StreamContentParser::Handle_CurveTo_13},
});
}
void CPDF_StreamContentParser::OnOperator(const FX_CHAR* op) {
int i = 0;
uint32_t opid = 0;
while (i < 4 && op[i]) {
opid = (opid << 8) + op[i];
i++;
}
while (i < 4) {
opid <<= 8;
i++;
}
static const OpCodes s_OpCodes = InitializeOpCodes();
auto it = s_OpCodes.find(opid);
if (it != s_OpCodes.end())
(this->*it->second)();
}
void CPDF_StreamContentParser::Handle_CloseFillStrokePath() {
Handle_ClosePath();
AddPathObject(FXFILL_WINDING, true);
}
void CPDF_StreamContentParser::Handle_FillStrokePath() {
AddPathObject(FXFILL_WINDING, true);
}
void CPDF_StreamContentParser::Handle_CloseEOFillStrokePath() {
AddPathPoint(m_PathStartX, m_PathStartY, FXPT_LINETO | FXPT_CLOSEFIGURE);
AddPathObject(FXFILL_ALTERNATE, true);
}
void CPDF_StreamContentParser::Handle_EOFillStrokePath() {
AddPathObject(FXFILL_ALTERNATE, true);
}
void CPDF_StreamContentParser::Handle_BeginMarkedContent_Dictionary() {
CFX_ByteString tag = GetString(1);
CPDF_Object* pProperty = GetObject(0);
if (!pProperty) {
return;
}
bool bDirect = true;
if (pProperty->IsName()) {
pProperty = FindResourceObj("Properties", pProperty->GetString());
if (!pProperty)
return;
bDirect = false;
}
if (CPDF_Dictionary* pDict = pProperty->AsDictionary()) {
m_CurContentMark.AddMark(tag, pDict, bDirect);
}
}
void CPDF_StreamContentParser::Handle_BeginImage() {
FX_FILESIZE savePos = m_pSyntax->GetPos();
auto pDict =
pdfium::MakeUnique<CPDF_Dictionary>(m_pDocument->GetByteStringPool());
while (1) {
CPDF_StreamParser::SyntaxType type = m_pSyntax->ParseNextElement();
if (type == CPDF_StreamParser::Keyword) {
CFX_ByteString bsKeyword(m_pSyntax->GetWordBuf(),
m_pSyntax->GetWordSize());
if (bsKeyword != "ID") {
m_pSyntax->SetPos(savePos);
return;
}
}
if (type != CPDF_StreamParser::Name) {
break;
}
CFX_ByteString key((const FX_CHAR*)m_pSyntax->GetWordBuf() + 1,
m_pSyntax->GetWordSize() - 1);
auto pObj = m_pSyntax->ReadNextObject(false, 0);
if (!key.IsEmpty()) {
uint32_t dwObjNum = pObj ? pObj->GetObjNum() : 0;
if (dwObjNum)
pDict->SetNewFor<CPDF_Reference>(key, m_pDocument, dwObjNum);
else
pDict->SetFor(key, std::move(pObj));
}
}
ReplaceAbbr(pDict.get());
CPDF_Object* pCSObj = nullptr;
if (pDict->KeyExist("ColorSpace")) {
pCSObj = pDict->GetDirectObjectFor("ColorSpace");
if (pCSObj->IsName()) {
CFX_ByteString name = pCSObj->GetString();
if (name != "DeviceRGB" && name != "DeviceGray" && name != "DeviceCMYK") {
pCSObj = FindResourceObj("ColorSpace", name);
if (pCSObj && pCSObj->IsInline())
pDict->SetFor("ColorSpace", pCSObj->Clone());
}
}
}
pDict->SetNewFor<CPDF_Name>("Subtype", "Image");
std::unique_ptr<CPDF_Stream> pStream =
m_pSyntax->ReadInlineStream(m_pDocument, std::move(pDict), pCSObj);
while (1) {
CPDF_StreamParser::SyntaxType type = m_pSyntax->ParseNextElement();
if (type == CPDF_StreamParser::EndOfData) {
break;
}
if (type != CPDF_StreamParser::Keyword) {
continue;
}
if (m_pSyntax->GetWordSize() == 2 && m_pSyntax->GetWordBuf()[0] == 'E' &&
m_pSyntax->GetWordBuf()[1] == 'I') {
break;
}
}
AddImage(std::move(pStream));
}
void CPDF_StreamContentParser::Handle_BeginMarkedContent() {
m_CurContentMark.AddMark(GetString(0), nullptr, false);
}
void CPDF_StreamContentParser::Handle_BeginText() {
m_pCurStates->m_TextMatrix.Set(1.0f, 0, 0, 1.0f, 0, 0);
OnChangeTextMatrix();
m_pCurStates->m_TextX = 0;
m_pCurStates->m_TextY = 0;
m_pCurStates->m_TextLineX = 0;
m_pCurStates->m_TextLineY = 0;
}
void CPDF_StreamContentParser::Handle_CurveTo_123() {
AddPathPoint(GetNumber(5), GetNumber(4), FXPT_BEZIERTO);
AddPathPoint(GetNumber(3), GetNumber(2), FXPT_BEZIERTO);
AddPathPoint(GetNumber(1), GetNumber(0), FXPT_BEZIERTO);
}
void CPDF_StreamContentParser::Handle_ConcatMatrix() {
CFX_Matrix new_matrix(GetNumber(5), GetNumber(4), GetNumber(3), GetNumber(2),
GetNumber(1), GetNumber(0));
new_matrix.Concat(m_pCurStates->m_CTM);
m_pCurStates->m_CTM = new_matrix;
OnChangeTextMatrix();
}
void CPDF_StreamContentParser::Handle_SetColorSpace_Fill() {
CPDF_ColorSpace* pCS = FindColorSpace(GetString(0));
if (!pCS)
return;
m_pCurStates->m_ColorState.GetMutableFillColor()->SetColorSpace(pCS);
}
void CPDF_StreamContentParser::Handle_SetColorSpace_Stroke() {
CPDF_ColorSpace* pCS = FindColorSpace(GetString(0));
if (!pCS)
return;
m_pCurStates->m_ColorState.GetMutableStrokeColor()->SetColorSpace(pCS);
}
void CPDF_StreamContentParser::Handle_SetDash() {
CPDF_Array* pArray = ToArray(GetObject(1));
if (!pArray)
return;
m_pCurStates->SetLineDash(pArray, GetNumber(0), 1.0f);
}
void CPDF_StreamContentParser::Handle_SetCharWidth() {
m_Type3Data[0] = GetNumber(1);
m_Type3Data[1] = GetNumber(0);
m_bColored = true;
}
void CPDF_StreamContentParser::Handle_SetCachedDevice() {
for (int i = 0; i < 6; i++) {
m_Type3Data[i] = GetNumber(5 - i);
}
m_bColored = false;
}
void CPDF_StreamContentParser::Handle_ExecuteXObject() {
CFX_ByteString name = GetString(0);
if (name == m_LastImageName && m_pLastImage && m_pLastImage->GetStream() &&
m_pLastImage->GetStream()->GetObjNum()) {
AddImage(m_pLastImage);
return;
}
CPDF_Stream* pXObject = ToStream(FindResourceObj("XObject", name));
if (!pXObject) {
m_bResourceMissing = true;
return;
}
CFX_ByteString type;
if (pXObject->GetDict())
type = pXObject->GetDict()->GetStringFor("Subtype");
if (type == "Image") {
CPDF_ImageObject* pObj = pXObject->IsInline()
? AddImage(std::unique_ptr<CPDF_Stream>(
ToStream(pXObject->Clone())))
: AddImage(pXObject->GetObjNum());
m_LastImageName = name;
m_pLastImage = pObj->GetImage();
if (!m_pObjectHolder->HasImageMask())
m_pObjectHolder->SetHasImageMask(m_pLastImage->IsMask());
} else if (type == "Form") {
AddForm(pXObject);
}
}
void CPDF_StreamContentParser::AddForm(CPDF_Stream* pStream) {
std::unique_ptr<CPDF_FormObject> pFormObj(new CPDF_FormObject);
pFormObj->m_pForm.reset(
new CPDF_Form(m_pDocument, m_pPageResources, pStream, m_pResources));
pFormObj->m_FormMatrix = m_pCurStates->m_CTM;
pFormObj->m_FormMatrix.Concat(m_mtContentToUser);
CPDF_AllStates status;
status.m_GeneralState = m_pCurStates->m_GeneralState;
status.m_GraphState = m_pCurStates->m_GraphState;
status.m_ColorState = m_pCurStates->m_ColorState;
status.m_TextState = m_pCurStates->m_TextState;
pFormObj->m_pForm->ParseContent(&status, nullptr, nullptr, m_Level + 1);
if (!m_pObjectHolder->BackgroundAlphaNeeded() &&
pFormObj->m_pForm->BackgroundAlphaNeeded()) {
m_pObjectHolder->SetBackgroundAlphaNeeded(true);
}
pFormObj->CalcBoundingBox();
SetGraphicStates(pFormObj.get(), true, true, true);
m_pObjectHolder->GetPageObjectList()->push_back(std::move(pFormObj));
}
CPDF_ImageObject* CPDF_StreamContentParser::AddImage(
std::unique_ptr<CPDF_Stream> pStream) {
if (!pStream)
return nullptr;
auto pImageObj = pdfium::MakeUnique<CPDF_ImageObject>();
pImageObj->SetOwnedImage(
pdfium::MakeUnique<CPDF_Image>(m_pDocument, std::move(pStream)));
return AddImageObject(std::move(pImageObj));
}
CPDF_ImageObject* CPDF_StreamContentParser::AddImage(uint32_t streamObjNum) {
auto pImageObj = pdfium::MakeUnique<CPDF_ImageObject>();
pImageObj->SetUnownedImage(m_pDocument->LoadImageFromPageData(streamObjNum));
return AddImageObject(std::move(pImageObj));
}
CPDF_ImageObject* CPDF_StreamContentParser::AddImage(CPDF_Image* pImage) {
if (!pImage)
return nullptr;
auto pImageObj = pdfium::MakeUnique<CPDF_ImageObject>();
pImageObj->SetUnownedImage(
m_pDocument->GetPageData()->GetImage(pImage->GetStream()->GetObjNum()));
return AddImageObject(std::move(pImageObj));
}
CPDF_ImageObject* CPDF_StreamContentParser::AddImageObject(
std::unique_ptr<CPDF_ImageObject> pImageObj) {
SetGraphicStates(pImageObj.get(), pImageObj->GetImage()->IsMask(), false,
false);
CFX_Matrix ImageMatrix = m_pCurStates->m_CTM;
ImageMatrix.Concat(m_mtContentToUser);
pImageObj->set_matrix(ImageMatrix);
pImageObj->CalcBoundingBox();
CPDF_ImageObject* pRet = pImageObj.get();
m_pObjectHolder->GetPageObjectList()->push_back(std::move(pImageObj));
return pRet;
}
void CPDF_StreamContentParser::Handle_MarkPlace_Dictionary() {}
void CPDF_StreamContentParser::Handle_EndImage() {}
void CPDF_StreamContentParser::Handle_EndMarkedContent() {
if (m_CurContentMark)
m_CurContentMark.DeleteLastMark();
}
void CPDF_StreamContentParser::Handle_EndText() {
if (m_ClipTextList.empty())
return;
if (TextRenderingModeIsClipMode(m_pCurStates->m_TextState.GetTextMode()))
m_pCurStates->m_ClipPath.AppendTexts(&m_ClipTextList);
m_ClipTextList.clear();
}
void CPDF_StreamContentParser::Handle_FillPath() {
AddPathObject(FXFILL_WINDING, false);
}
void CPDF_StreamContentParser::Handle_FillPathOld() {
AddPathObject(FXFILL_WINDING, false);
}
void CPDF_StreamContentParser::Handle_EOFillPath() {
AddPathObject(FXFILL_ALTERNATE, false);
}
void CPDF_StreamContentParser::Handle_SetGray_Fill() {
FX_FLOAT value = GetNumber(0);
CPDF_ColorSpace* pCS = CPDF_ColorSpace::GetStockCS(PDFCS_DEVICEGRAY);
m_pCurStates->m_ColorState.SetFillColor(pCS, &value, 1);
}
void CPDF_StreamContentParser::Handle_SetGray_Stroke() {
FX_FLOAT value = GetNumber(0);
CPDF_ColorSpace* pCS = CPDF_ColorSpace::GetStockCS(PDFCS_DEVICEGRAY);
m_pCurStates->m_ColorState.SetStrokeColor(pCS, &value, 1);
}
void CPDF_StreamContentParser::Handle_SetExtendGraphState() {
CFX_ByteString name = GetString(0);
CPDF_Dictionary* pGS = ToDictionary(FindResourceObj("ExtGState", name));
if (!pGS) {
m_bResourceMissing = true;
return;
}
m_pCurStates->ProcessExtGS(pGS, this);
}
void CPDF_StreamContentParser::Handle_ClosePath() {
if (m_PathPointCount == 0) {
return;
}
if (m_PathStartX != m_PathCurrentX || m_PathStartY != m_PathCurrentY) {
AddPathPoint(m_PathStartX, m_PathStartY, FXPT_LINETO | FXPT_CLOSEFIGURE);
} else if (m_pPathPoints[m_PathPointCount - 1].m_Flag != FXPT_MOVETO) {
m_pPathPoints[m_PathPointCount - 1].m_Flag |= FXPT_CLOSEFIGURE;
}
}
void CPDF_StreamContentParser::Handle_SetFlat() {
m_pCurStates->m_GeneralState.SetFlatness(GetNumber(0));
}
void CPDF_StreamContentParser::Handle_BeginImageData() {}
void CPDF_StreamContentParser::Handle_SetLineJoin() {
m_pCurStates->m_GraphState.SetLineJoin(
static_cast<CFX_GraphStateData::LineJoin>(GetInteger(0)));
}
void CPDF_StreamContentParser::Handle_SetLineCap() {
m_pCurStates->m_GraphState.SetLineCap(
static_cast<CFX_GraphStateData::LineCap>(GetInteger(0)));
}
void CPDF_StreamContentParser::Handle_SetCMYKColor_Fill() {
if (m_ParamCount != 4)
return;
FX_FLOAT values[4];
for (int i = 0; i < 4; i++) {
values[i] = GetNumber(3 - i);
}
CPDF_ColorSpace* pCS = CPDF_ColorSpace::GetStockCS(PDFCS_DEVICECMYK);
m_pCurStates->m_ColorState.SetFillColor(pCS, values, 4);
}
void CPDF_StreamContentParser::Handle_SetCMYKColor_Stroke() {
if (m_ParamCount != 4)
return;
FX_FLOAT values[4];
for (int i = 0; i < 4; i++) {
values[i] = GetNumber(3 - i);
}
CPDF_ColorSpace* pCS = CPDF_ColorSpace::GetStockCS(PDFCS_DEVICECMYK);
m_pCurStates->m_ColorState.SetStrokeColor(pCS, values, 4);
}
void CPDF_StreamContentParser::Handle_LineTo() {
if (m_ParamCount != 2)
return;
AddPathPoint(GetNumber(1), GetNumber(0), FXPT_LINETO);
}
void CPDF_StreamContentParser::Handle_MoveTo() {
if (m_ParamCount != 2)
return;
AddPathPoint(GetNumber(1), GetNumber(0), FXPT_MOVETO);
ParsePathObject();
}
void CPDF_StreamContentParser::Handle_SetMiterLimit() {
m_pCurStates->m_GraphState.SetMiterLimit(GetNumber(0));
}
void CPDF_StreamContentParser::Handle_MarkPlace() {}
void CPDF_StreamContentParser::Handle_EndPath() {
AddPathObject(0, false);
}
void CPDF_StreamContentParser::Handle_SaveGraphState() {
std::unique_ptr<CPDF_AllStates> pStates(new CPDF_AllStates);
pStates->Copy(*m_pCurStates);
m_StateStack.push_back(std::move(pStates));
}
void CPDF_StreamContentParser::Handle_RestoreGraphState() {
if (m_StateStack.empty())
return;
std::unique_ptr<CPDF_AllStates> pStates = std::move(m_StateStack.back());
m_StateStack.pop_back();
m_pCurStates->Copy(*pStates);
}
void CPDF_StreamContentParser::Handle_Rectangle() {
FX_FLOAT x = GetNumber(3), y = GetNumber(2);
FX_FLOAT w = GetNumber(1), h = GetNumber(0);
AddPathRect(x, y, w, h);
}
void CPDF_StreamContentParser::AddPathRect(FX_FLOAT x,
FX_FLOAT y,
FX_FLOAT w,
FX_FLOAT h) {
AddPathPoint(x, y, FXPT_MOVETO);
AddPathPoint(x + w, y, FXPT_LINETO);
AddPathPoint(x + w, y + h, FXPT_LINETO);
AddPathPoint(x, y + h, FXPT_LINETO);
AddPathPoint(x, y, FXPT_LINETO | FXPT_CLOSEFIGURE);
}
void CPDF_StreamContentParser::Handle_SetRGBColor_Fill() {
if (m_ParamCount != 3)
return;
FX_FLOAT values[3];
for (int i = 0; i < 3; i++) {
values[i] = GetNumber(2 - i);
}
CPDF_ColorSpace* pCS = CPDF_ColorSpace::GetStockCS(PDFCS_DEVICERGB);
m_pCurStates->m_ColorState.SetFillColor(pCS, values, 3);
}
void CPDF_StreamContentParser::Handle_SetRGBColor_Stroke() {
if (m_ParamCount != 3)
return;
FX_FLOAT values[3];
for (int i = 0; i < 3; i++) {
values[i] = GetNumber(2 - i);
}
CPDF_ColorSpace* pCS = CPDF_ColorSpace::GetStockCS(PDFCS_DEVICERGB);
m_pCurStates->m_ColorState.SetStrokeColor(pCS, values, 3);
}
void CPDF_StreamContentParser::Handle_SetRenderIntent() {}
void CPDF_StreamContentParser::Handle_CloseStrokePath() {
Handle_ClosePath();
AddPathObject(0, true);
}
void CPDF_StreamContentParser::Handle_StrokePath() {
AddPathObject(0, true);
}
void CPDF_StreamContentParser::Handle_SetColor_Fill() {
FX_FLOAT values[4];
int nargs = m_ParamCount;
if (nargs > 4) {
nargs = 4;
}
for (int i = 0; i < nargs; i++) {
values[i] = GetNumber(nargs - i - 1);
}
m_pCurStates->m_ColorState.SetFillColor(nullptr, values, nargs);
}
void CPDF_StreamContentParser::Handle_SetColor_Stroke() {
FX_FLOAT values[4];
int nargs = m_ParamCount;
if (nargs > 4) {
nargs = 4;
}
for (int i = 0; i < nargs; i++) {
values[i] = GetNumber(nargs - i - 1);
}
m_pCurStates->m_ColorState.SetStrokeColor(nullptr, values, nargs);
}
void CPDF_StreamContentParser::Handle_SetColorPS_Fill() {
CPDF_Object* pLastParam = GetObject(0);
if (!pLastParam) {
return;
}
uint32_t nargs = m_ParamCount;
uint32_t nvalues = nargs;
if (pLastParam->IsName())
nvalues--;
FX_FLOAT* values = nullptr;
if (nvalues) {
values = FX_Alloc(FX_FLOAT, nvalues);
for (uint32_t i = 0; i < nvalues; i++) {
values[i] = GetNumber(nargs - i - 1);
}
}
if (nvalues != nargs) {
CPDF_Pattern* pPattern = FindPattern(GetString(0), false);
if (pPattern) {
m_pCurStates->m_ColorState.SetFillPattern(pPattern, values, nvalues);
}
} else {
m_pCurStates->m_ColorState.SetFillColor(nullptr, values, nvalues);
}
FX_Free(values);
}
void CPDF_StreamContentParser::Handle_SetColorPS_Stroke() {
CPDF_Object* pLastParam = GetObject(0);
if (!pLastParam) {
return;
}
int nargs = m_ParamCount;
int nvalues = nargs;
if (pLastParam->IsName())
nvalues--;
FX_FLOAT* values = nullptr;
if (nvalues) {
values = FX_Alloc(FX_FLOAT, nvalues);
for (int i = 0; i < nvalues; i++) {
values[i] = GetNumber(nargs - i - 1);
}
}
if (nvalues != nargs) {
CPDF_Pattern* pPattern = FindPattern(GetString(0), false);
if (pPattern) {
m_pCurStates->m_ColorState.SetStrokePattern(pPattern, values, nvalues);
}
} else {
m_pCurStates->m_ColorState.SetStrokeColor(nullptr, values, nvalues);
}
FX_Free(values);
}
void CPDF_StreamContentParser::Handle_ShadeFill() {
CPDF_Pattern* pPattern = FindPattern(GetString(0), true);
if (!pPattern)
return;
CPDF_ShadingPattern* pShading = pPattern->AsShadingPattern();
if (!pShading)
return;
if (!pShading->IsShadingObject() || !pShading->Load())
return;
std::unique_ptr<CPDF_ShadingObject> pObj(new CPDF_ShadingObject);
pObj->m_pShading = pShading;
SetGraphicStates(pObj.get(), false, false, false);
pObj->m_Matrix = m_pCurStates->m_CTM;
pObj->m_Matrix.Concat(m_mtContentToUser);
CFX_FloatRect bbox =
pObj->m_ClipPath ? pObj->m_ClipPath.GetClipBox() : m_BBox;
if (pShading->IsMeshShading())
bbox.Intersect(GetShadingBBox(pShading, pObj->m_Matrix));
pObj->m_Left = bbox.left;
pObj->m_Right = bbox.right;
pObj->m_Top = bbox.top;
pObj->m_Bottom = bbox.bottom;
m_pObjectHolder->GetPageObjectList()->push_back(std::move(pObj));
}
void CPDF_StreamContentParser::Handle_SetCharSpace() {
m_pCurStates->m_TextState.SetCharSpace(GetNumber(0));
}
void CPDF_StreamContentParser::Handle_MoveTextPoint() {
m_pCurStates->m_TextLineX += GetNumber(1);
m_pCurStates->m_TextLineY += GetNumber(0);
m_pCurStates->m_TextX = m_pCurStates->m_TextLineX;
m_pCurStates->m_TextY = m_pCurStates->m_TextLineY;
}
void CPDF_StreamContentParser::Handle_MoveTextPoint_SetLeading() {
Handle_MoveTextPoint();
m_pCurStates->m_TextLeading = -GetNumber(0);
}
void CPDF_StreamContentParser::Handle_SetFont() {
FX_FLOAT fs = GetNumber(0);
if (fs == 0) {
fs = m_DefFontSize;
}
m_pCurStates->m_TextState.SetFontSize(fs);
CPDF_Font* pFont = FindFont(GetString(1));
if (pFont) {
m_pCurStates->m_TextState.SetFont(pFont);
}
}
CPDF_Object* CPDF_StreamContentParser::FindResourceObj(
const CFX_ByteString& type,
const CFX_ByteString& name) {
if (!m_pResources)
return nullptr;
CPDF_Dictionary* pDict = m_pResources->GetDictFor(type);
if (pDict)
return pDict->GetDirectObjectFor(name);
if (m_pResources == m_pPageResources || !m_pPageResources)
return nullptr;
CPDF_Dictionary* pPageDict = m_pPageResources->GetDictFor(type);
return pPageDict ? pPageDict->GetDirectObjectFor(name) : nullptr;
}
CPDF_Font* CPDF_StreamContentParser::FindFont(const CFX_ByteString& name) {
CPDF_Dictionary* pFontDict = ToDictionary(FindResourceObj("Font", name));
if (!pFontDict) {
m_bResourceMissing = true;
return CPDF_Font::GetStockFont(m_pDocument, "Helvetica");
}
CPDF_Font* pFont = m_pDocument->LoadFont(pFontDict);
if (pFont && pFont->IsType3Font()) {
pFont->AsType3Font()->SetPageResources(m_pResources);
pFont->AsType3Font()->CheckType3FontMetrics();
}
return pFont;
}
CPDF_ColorSpace* CPDF_StreamContentParser::FindColorSpace(
const CFX_ByteString& name) {
if (name == "Pattern") {
return CPDF_ColorSpace::GetStockCS(PDFCS_PATTERN);
}
if (name == "DeviceGray" || name == "DeviceCMYK" || name == "DeviceRGB") {
CFX_ByteString defname = "Default";
defname += name.Mid(7);
CPDF_Object* pDefObj = FindResourceObj("ColorSpace", defname);
if (!pDefObj) {
if (name == "DeviceGray") {
return CPDF_ColorSpace::GetStockCS(PDFCS_DEVICEGRAY);
}
if (name == "DeviceRGB") {
return CPDF_ColorSpace::GetStockCS(PDFCS_DEVICERGB);
}
return CPDF_ColorSpace::GetStockCS(PDFCS_DEVICECMYK);
}
return m_pDocument->LoadColorSpace(pDefObj);
}
CPDF_Object* pCSObj = FindResourceObj("ColorSpace", name);
if (!pCSObj) {
m_bResourceMissing = true;
return nullptr;
}
return m_pDocument->LoadColorSpace(pCSObj);
}
CPDF_Pattern* CPDF_StreamContentParser::FindPattern(const CFX_ByteString& name,
bool bShading) {
CPDF_Object* pPattern =
FindResourceObj(bShading ? "Shading" : "Pattern", name);
if (!pPattern || (!pPattern->IsDictionary() && !pPattern->IsStream())) {
m_bResourceMissing = true;
return nullptr;
}
return m_pDocument->LoadPattern(pPattern, bShading,
m_pCurStates->m_ParentMatrix);
}
void CPDF_StreamContentParser::ConvertTextSpace(FX_FLOAT& x, FX_FLOAT& y) {
m_pCurStates->m_TextMatrix.Transform(x, y, x, y);
ConvertUserSpace(x, y);
}
void CPDF_StreamContentParser::ConvertUserSpace(FX_FLOAT& x, FX_FLOAT& y) {
m_pCurStates->m_CTM.Transform(x, y, x, y);
m_mtContentToUser.Transform(x, y, x, y);
}
void CPDF_StreamContentParser::AddTextObject(CFX_ByteString* pStrs,
FX_FLOAT fInitKerning,
FX_FLOAT* pKerning,
int nsegs) {
CPDF_Font* pFont = m_pCurStates->m_TextState.GetFont();
if (!pFont) {
return;
}
if (fInitKerning != 0) {
if (!pFont->IsVertWriting()) {
m_pCurStates->m_TextX -=
(fInitKerning * m_pCurStates->m_TextState.GetFontSize() *
m_pCurStates->m_TextHorzScale) /
1000;
} else {
m_pCurStates->m_TextY -=
(fInitKerning * m_pCurStates->m_TextState.GetFontSize()) / 1000;
}
}
if (nsegs == 0) {
return;
}
const TextRenderingMode text_mode =
pFont->IsType3Font() ? TextRenderingMode::MODE_FILL
: m_pCurStates->m_TextState.GetTextMode();
{
std::unique_ptr<CPDF_TextObject> pText(new CPDF_TextObject);
m_pLastTextObject = pText.get();
SetGraphicStates(m_pLastTextObject, true, true, true);
if (TextRenderingModeIsStrokeMode(text_mode)) {
FX_FLOAT* pCTM = pText->m_TextState.GetMutableCTM();
pCTM[0] = m_pCurStates->m_CTM.a;
pCTM[1] = m_pCurStates->m_CTM.c;
pCTM[2] = m_pCurStates->m_CTM.b;
pCTM[3] = m_pCurStates->m_CTM.d;
}
pText->SetSegments(pStrs, pKerning, nsegs);
pText->m_PosX = m_pCurStates->m_TextX;
pText->m_PosY = m_pCurStates->m_TextY + m_pCurStates->m_TextRise;
ConvertTextSpace(pText->m_PosX, pText->m_PosY);
FX_FLOAT x_advance;
FX_FLOAT y_advance;
pText->CalcPositionData(&x_advance, &y_advance,
m_pCurStates->m_TextHorzScale);
m_pCurStates->m_TextX += x_advance;
m_pCurStates->m_TextY += y_advance;
if (TextRenderingModeIsClipMode(text_mode)) {
m_ClipTextList.push_back(
std::unique_ptr<CPDF_TextObject>(pText->Clone()));
}
m_pObjectHolder->GetPageObjectList()->push_back(std::move(pText));
}
if (pKerning && pKerning[nsegs - 1] != 0) {
if (!pFont->IsVertWriting()) {
m_pCurStates->m_TextX -=
(pKerning[nsegs - 1] * m_pCurStates->m_TextState.GetFontSize() *
m_pCurStates->m_TextHorzScale) /
1000;
} else {
m_pCurStates->m_TextY -=
(pKerning[nsegs - 1] * m_pCurStates->m_TextState.GetFontSize()) /
1000;
}
}
}
void CPDF_StreamContentParser::Handle_ShowText() {
CFX_ByteString str = GetString(0);
if (str.IsEmpty()) {
return;
}
AddTextObject(&str, 0, nullptr, 1);
}
void CPDF_StreamContentParser::Handle_ShowText_Positioning() {
CPDF_Array* pArray = ToArray(GetObject(0));
if (!pArray)
return;
size_t n = pArray->GetCount();
size_t nsegs = 0;
for (size_t i = 0; i < n; i++) {
if (pArray->GetDirectObjectAt(i)->IsString())
nsegs++;
}
if (nsegs == 0) {
for (size_t i = 0; i < n; i++) {
m_pCurStates->m_TextX -=
(pArray->GetNumberAt(i) * m_pCurStates->m_TextState.GetFontSize() *
m_pCurStates->m_TextHorzScale) /
1000;
}
return;
}
CFX_ByteString* pStrs = new CFX_ByteString[nsegs];
FX_FLOAT* pKerning = FX_Alloc(FX_FLOAT, nsegs);
size_t iSegment = 0;
FX_FLOAT fInitKerning = 0;
for (size_t i = 0; i < n; i++) {
CPDF_Object* pObj = pArray->GetDirectObjectAt(i);
if (pObj->IsString()) {
CFX_ByteString str = pObj->GetString();
if (str.IsEmpty()) {
continue;
}
pStrs[iSegment] = str;
pKerning[iSegment++] = 0;
} else {
FX_FLOAT num = pObj ? pObj->GetNumber() : 0;
if (iSegment == 0) {
fInitKerning += num;
} else {
pKerning[iSegment - 1] += num;
}
}
}
AddTextObject(pStrs, fInitKerning, pKerning, iSegment);
delete[] pStrs;
FX_Free(pKerning);
}
void CPDF_StreamContentParser::Handle_SetTextLeading() {
m_pCurStates->m_TextLeading = GetNumber(0);
}
void CPDF_StreamContentParser::Handle_SetTextMatrix() {
m_pCurStates->m_TextMatrix.Set(GetNumber(5), GetNumber(4), GetNumber(3),
GetNumber(2), GetNumber(1), GetNumber(0));
OnChangeTextMatrix();
m_pCurStates->m_TextX = 0;
m_pCurStates->m_TextY = 0;
m_pCurStates->m_TextLineX = 0;
m_pCurStates->m_TextLineY = 0;
}
void CPDF_StreamContentParser::OnChangeTextMatrix() {
CFX_Matrix text_matrix(m_pCurStates->m_TextHorzScale, 0.0f, 0.0f, 1.0f, 0.0f,
0.0f);
text_matrix.Concat(m_pCurStates->m_TextMatrix);
text_matrix.Concat(m_pCurStates->m_CTM);
text_matrix.Concat(m_mtContentToUser);
FX_FLOAT* pTextMatrix = m_pCurStates->m_TextState.GetMutableMatrix();
pTextMatrix[0] = text_matrix.a;
pTextMatrix[1] = text_matrix.c;
pTextMatrix[2] = text_matrix.b;
pTextMatrix[3] = text_matrix.d;
}
void CPDF_StreamContentParser::Handle_SetTextRenderMode() {
TextRenderingMode mode;
if (SetTextRenderingModeFromInt(GetInteger(0), &mode))
m_pCurStates->m_TextState.SetTextMode(mode);
}
void CPDF_StreamContentParser::Handle_SetTextRise() {
m_pCurStates->m_TextRise = GetNumber(0);
}
void CPDF_StreamContentParser::Handle_SetWordSpace() {
m_pCurStates->m_TextState.SetWordSpace(GetNumber(0));
}
void CPDF_StreamContentParser::Handle_SetHorzScale() {
if (m_ParamCount != 1) {
return;
}
m_pCurStates->m_TextHorzScale = GetNumber(0) / 100;
OnChangeTextMatrix();
}
void CPDF_StreamContentParser::Handle_MoveToNextLine() {
m_pCurStates->m_TextLineY -= m_pCurStates->m_TextLeading;
m_pCurStates->m_TextX = m_pCurStates->m_TextLineX;
m_pCurStates->m_TextY = m_pCurStates->m_TextLineY;
}
void CPDF_StreamContentParser::Handle_CurveTo_23() {
AddPathPoint(m_PathCurrentX, m_PathCurrentY, FXPT_BEZIERTO);
AddPathPoint(GetNumber(3), GetNumber(2), FXPT_BEZIERTO);
AddPathPoint(GetNumber(1), GetNumber(0), FXPT_BEZIERTO);
}
void CPDF_StreamContentParser::Handle_SetLineWidth() {
m_pCurStates->m_GraphState.SetLineWidth(GetNumber(0));
}
void CPDF_StreamContentParser::Handle_Clip() {
m_PathClipType = FXFILL_WINDING;
}
void CPDF_StreamContentParser::Handle_EOClip() {
m_PathClipType = FXFILL_ALTERNATE;
}
void CPDF_StreamContentParser::Handle_CurveTo_13() {
AddPathPoint(GetNumber(3), GetNumber(2), FXPT_BEZIERTO);
AddPathPoint(GetNumber(1), GetNumber(0), FXPT_BEZIERTO);
AddPathPoint(GetNumber(1), GetNumber(0), FXPT_BEZIERTO);
}
void CPDF_StreamContentParser::Handle_NextLineShowText() {
Handle_MoveToNextLine();
Handle_ShowText();
}
void CPDF_StreamContentParser::Handle_NextLineShowText_Space() {
m_pCurStates->m_TextState.SetWordSpace(GetNumber(2));
m_pCurStates->m_TextState.SetCharSpace(GetNumber(1));
Handle_NextLineShowText();
}
void CPDF_StreamContentParser::Handle_Invalid() {}
void CPDF_StreamContentParser::AddPathPoint(FX_FLOAT x, FX_FLOAT y, int flag) {
m_PathCurrentX = x;
m_PathCurrentY = y;
if (flag == FXPT_MOVETO) {
m_PathStartX = x;
m_PathStartY = y;
if (m_PathPointCount &&
m_pPathPoints[m_PathPointCount - 1].m_Flag == FXPT_MOVETO) {
m_pPathPoints[m_PathPointCount - 1].m_PointX = x;
m_pPathPoints[m_PathPointCount - 1].m_PointY = y;
return;
}
} else if (m_PathPointCount == 0) {
return;
}
m_PathPointCount++;
if (m_PathPointCount > m_PathAllocSize) {
int newsize = m_PathPointCount + 256;
FX_PATHPOINT* pNewPoints = FX_Alloc(FX_PATHPOINT, newsize);
if (m_PathAllocSize) {
FXSYS_memcpy(pNewPoints, m_pPathPoints,
m_PathAllocSize * sizeof(FX_PATHPOINT));
FX_Free(m_pPathPoints);
}
m_pPathPoints = pNewPoints;
m_PathAllocSize = newsize;
}
m_pPathPoints[m_PathPointCount - 1].m_Flag = flag;
m_pPathPoints[m_PathPointCount - 1].m_PointX = x;
m_pPathPoints[m_PathPointCount - 1].m_PointY = y;
}
void CPDF_StreamContentParser::AddPathObject(int FillType, bool bStroke) {
int PathPointCount = m_PathPointCount;
uint8_t PathClipType = m_PathClipType;
m_PathPointCount = 0;
m_PathClipType = 0;
if (PathPointCount <= 1) {
if (PathPointCount && PathClipType) {
CPDF_Path path;
path.AppendRect(0, 0, 0, 0);
m_pCurStates->m_ClipPath.AppendPath(path, FXFILL_WINDING, true);
}
return;
}
if (PathPointCount &&
m_pPathPoints[PathPointCount - 1].m_Flag == FXPT_MOVETO) {
PathPointCount--;
}
CPDF_Path Path;
Path.SetPointCount(PathPointCount);
FXSYS_memcpy(Path.GetMutablePoints(), m_pPathPoints,
sizeof(FX_PATHPOINT) * PathPointCount);
CFX_Matrix matrix = m_pCurStates->m_CTM;
matrix.Concat(m_mtContentToUser);
if (bStroke || FillType) {
std::unique_ptr<CPDF_PathObject> pPathObj(new CPDF_PathObject);
pPathObj->m_bStroke = bStroke;
pPathObj->m_FillType = FillType;
pPathObj->m_Path = Path;
pPathObj->m_Matrix = matrix;
SetGraphicStates(pPathObj.get(), true, false, true);
pPathObj->CalcBoundingBox();
m_pObjectHolder->GetPageObjectList()->push_back(std::move(pPathObj));
}
if (PathClipType) {
if (!matrix.IsIdentity()) {
Path.Transform(&matrix);
matrix.SetIdentity();
}
m_pCurStates->m_ClipPath.AppendPath(Path, PathClipType, true);
}
}
uint32_t CPDF_StreamContentParser::Parse(const uint8_t* pData,
uint32_t dwSize,
uint32_t max_cost) {
if (m_Level > kMaxFormLevel)
return dwSize;
uint32_t InitObjCount = m_pObjectHolder->GetPageObjectList()->size();
CPDF_StreamParser syntax(pData, dwSize, m_pDocument->GetByteStringPool());
CPDF_StreamParserAutoClearer auto_clearer(&m_pSyntax, &syntax);
while (1) {
uint32_t cost = m_pObjectHolder->GetPageObjectList()->size() - InitObjCount;
if (max_cost && cost >= max_cost) {
break;
}
switch (syntax.ParseNextElement()) {
case CPDF_StreamParser::EndOfData:
return m_pSyntax->GetPos();
case CPDF_StreamParser::Keyword:
OnOperator((char*)syntax.GetWordBuf());
ClearAllParams();
break;
case CPDF_StreamParser::Number:
AddNumberParam((char*)syntax.GetWordBuf(), syntax.GetWordSize());
break;
case CPDF_StreamParser::Name:
AddNameParam((const FX_CHAR*)syntax.GetWordBuf() + 1,
syntax.GetWordSize() - 1);
break;
default:
AddObjectParam(syntax.GetObject());
}
}
return m_pSyntax->GetPos();
}
void CPDF_StreamContentParser::ParsePathObject() {
FX_FLOAT params[6] = {};
int nParams = 0;
int last_pos = m_pSyntax->GetPos();
while (1) {
CPDF_StreamParser::SyntaxType type = m_pSyntax->ParseNextElement();
bool bProcessed = true;
switch (type) {
case CPDF_StreamParser::EndOfData:
return;
case CPDF_StreamParser::Keyword: {
int len = m_pSyntax->GetWordSize();
if (len == 1) {
switch (m_pSyntax->GetWordBuf()[0]) {
case kPathOperatorSubpath:
AddPathPoint(params[0], params[1], FXPT_MOVETO);
nParams = 0;
break;
case kPathOperatorLine:
AddPathPoint(params[0], params[1], FXPT_LINETO);
nParams = 0;
break;
case kPathOperatorCubicBezier1:
AddPathPoint(params[0], params[1], FXPT_BEZIERTO);
AddPathPoint(params[2], params[3], FXPT_BEZIERTO);
AddPathPoint(params[4], params[5], FXPT_BEZIERTO);
nParams = 0;
break;
case kPathOperatorCubicBezier2:
AddPathPoint(m_PathCurrentX, m_PathCurrentY, FXPT_BEZIERTO);
AddPathPoint(params[0], params[1], FXPT_BEZIERTO);
AddPathPoint(params[2], params[3], FXPT_BEZIERTO);
nParams = 0;
break;
case kPathOperatorCubicBezier3:
AddPathPoint(params[0], params[1], FXPT_BEZIERTO);
AddPathPoint(params[2], params[3], FXPT_BEZIERTO);
AddPathPoint(params[2], params[3], FXPT_BEZIERTO);
nParams = 0;
break;
case kPathOperatorClosePath:
Handle_ClosePath();
nParams = 0;
break;
default:
bProcessed = false;
break;
}
} else if (len == 2) {
if (m_pSyntax->GetWordBuf()[0] == kPathOperatorRectangle[0] &&
m_pSyntax->GetWordBuf()[1] == kPathOperatorRectangle[1]) {
AddPathRect(params[0], params[1], params[2], params[3]);
nParams = 0;
} else {
bProcessed = false;
}
} else {
bProcessed = false;
}
if (bProcessed) {
last_pos = m_pSyntax->GetPos();
}
break;
}
case CPDF_StreamParser::Number: {
if (nParams == 6)
break;
int value;
bool bInteger = FX_atonum(
CFX_ByteStringC(m_pSyntax->GetWordBuf(), m_pSyntax->GetWordSize()),
&value);
params[nParams++] = bInteger ? (FX_FLOAT)value : *(FX_FLOAT*)&value;
break;
}
default:
bProcessed = false;
}
if (!bProcessed) {
m_pSyntax->SetPos(last_pos);
return;
}
}
}
CPDF_StreamContentParser::ContentParam::ContentParam() {}
CPDF_StreamContentParser::ContentParam::~ContentParam() {}
| 32.837028 | 80 | 0.671417 | guidopola |
141461ffd27400fdd523d30aaa154a19f21ce3e7 | 1,465 | cpp | C++ | src/examples/cpp/info_reg.cpp | o2e/Triton | 0753a0c097fe637beb25b428ff2f0983f14f96d9 | [
"Apache-2.0"
] | 2,337 | 2015-06-03T10:26:30.000Z | 2022-03-30T02:42:26.000Z | src/examples/cpp/info_reg.cpp | o2e/Triton | 0753a0c097fe637beb25b428ff2f0983f14f96d9 | [
"Apache-2.0"
] | 914 | 2015-06-03T10:56:48.000Z | 2022-03-30T11:11:40.000Z | src/examples/cpp/info_reg.cpp | o2e/Triton | 0753a0c097fe637beb25b428ff2f0983f14f96d9 | [
"Apache-2.0"
] | 521 | 2015-06-03T10:41:15.000Z | 2022-03-26T15:45:08.000Z | /*
** Output:
**
** $ ./info_reg.bin
** Name : ah
** Size byte : 1
** Size bit : 8
** Highed bit : 15
** Lower bit : 8
** Parent : rax
** operator<< : ah:8 bitsvector[15..8]
** Object : ah:8 bitsvector[15..8]
** Object : ah:8 bitsvector[15..8]
*/
#include <iostream>
#include <triton/x86Specifications.hpp>
#include <triton/api.hpp>
using namespace triton;
using namespace triton::arch;
using namespace triton::arch::x86;
int main(int ac, const char **av) {
triton::API api;
/* Set the arch */
api.setArchitecture(ARCH_X86_64);
std::cout << "Name : " << api.registers.x86_ah.getName() << std::endl;
std::cout << "Size byte : " << api.registers.x86_ah.getSize() << std::endl;
std::cout << "Size bit : " << api.registers.x86_ah.getBitSize() << std::endl;
std::cout << "Higher bit : " << api.registers.x86_ah.getHigh() << std::endl;
std::cout << "Lower bit : " << api.registers.x86_ah.getLow() << std::endl;
std::cout << "Parent : " << api.getParentRegister(ID_REG_X86_AH).getName() << std::endl;
std::cout << "operator<< : " << api.getRegister(ID_REG_X86_AH) << std::endl;
std::cout << "Object : " << api.getRegister("ah") << std::endl;
std::cout << "Object : " << api.getRegister("AH") << std::endl;
std::cout << "----------------------------" << std::endl;
for(const auto& kv: api.getAllRegisters())
std::cout << kv.second << std::endl;
return 0;
}
| 29.897959 | 95 | 0.572014 | o2e |
14146dfbc9bec580cf9fb46ba61bc929de305f6f | 6,648 | hpp | C++ | unit_test/include/extra_features_test.hpp | wh5a/intel-qs | b625e1fb09c5aa3c146cb7129a2a29cdb6ff186a | [
"Apache-2.0"
] | 1 | 2021-04-15T11:41:57.000Z | 2021-04-15T11:41:57.000Z | unit_test/include/extra_features_test.hpp | wh5a/intel-qs | b625e1fb09c5aa3c146cb7129a2a29cdb6ff186a | [
"Apache-2.0"
] | null | null | null | unit_test/include/extra_features_test.hpp | wh5a/intel-qs | b625e1fb09c5aa3c146cb7129a2a29cdb6ff186a | [
"Apache-2.0"
] | null | null | null | #ifndef EXTRA_FEATURES_TEST_HPP
#define EXTRA_FEATURES_TEST_HPP
#include "../../include/qureg.hpp"
#include "../../include/qaoa_features.hpp"
//////////////////////////////////////////////////////////////////////////////
// Test fixture class.
class ExtraFeaturesTest : public ::testing::Test
{
protected:
ExtraFeaturesTest()
{ }
// just after the 'constructor'
void SetUp() override
{
// All tests are skipped if the rank is dummy.
if (qhipster::mpi::Environment::IsUsefulRank() == false)
GTEST_SKIP();
// All tests are skipped if the 6-qubit state is distributed in more than 2^5 ranks.
// In fact the MPI version needs to allocate half-the-local-storage for communication.
// If the local storage is a single amplitude, this cannot be further divided.
if (qhipster::mpi::Environment::GetStateSize() > 32)
GTEST_SKIP();
}
const std::size_t num_qubits_ = 6;
double accepted_error_ = 1e-15;
};
//////////////////////////////////////////////////////////////////////////////
// Functions developed to facilitate the simulation of QAOA circuits.
//////////////////////////////////////////////////////////////////////////////
TEST_F(ExtraFeaturesTest, qaoa_maxcut)
{
// Instance of the max-cut problem provided as adjacency matrix.
// It is a ring of 6 vertices:
//
// 0--1--2
// | |
// 5--4--3
//
std::vector<int> adjacency = {0, 1, 0, 0, 0, 1,
1, 0, 1, 0, 0, 0,
0, 1, 0, 1, 0, 0,
0, 0, 1, 0, 1, 0,
0, 0, 0, 1, 0, 1,
1, 0, 0, 0, 1, 0};
QubitRegister<ComplexDP> diag (num_qubits_,"base",0);
int max_cut_value;
max_cut_value = qaoa::InitializeVectorAsMaxCutCostFunction(diag,adjacency);
// Among other properties, only two bipartition has cut=0.
ComplexDP amplitude;
amplitude = { 0, 0 };
ASSERT_COMPLEX_NEAR(diag.GetGlobalAmplitude(0), amplitude, accepted_error_);
ASSERT_COMPLEX_NEAR(diag.GetGlobalAmplitude(diag.GlobalSize()-1), amplitude,
accepted_error_);
// No bipartition can cut a single edge.
for (size_t j=0; j<diag.LocalSize(); ++j)
ASSERT_GT( std::abs(diag[j].real()-1.), accepted_error_);
// Perform QAOA simulation (p=1).
QubitRegister<ComplexDP> psi (num_qubits_,"++++",0);
double gamma = 0.4;
double beta = 0.3;
// Emulation of the layer based on the cost function:
qaoa::ImplementQaoaLayerBasedOnCostFunction(psi, diag, gamma);
// Simulation of the layer based on the local transverse field:
for (int qubit=0; qubit<num_qubits_; ++qubit)
psi.ApplyRotationX(qubit, beta);
// Get average of cut value:
double expectation = qaoa::GetExpectationValueFromCostFunction( psi, diag);
// Get histogram of the cut values:
std::vector<double> histo = qaoa::GetHistogramFromCostFunction(psi, diag, max_cut_value);
ASSERT_EQ(histo.size(), max_cut_value+1);
double average=0;
for (int j=0; j<histo.size(); ++j)
average += double(j)*histo[j];
ASSERT_DOUBLE_EQ(expectation, average);
}
//////////////////////////////////////////////////////////////////////////////
TEST_F(ExtraFeaturesTest, qaoa_weighted_maxcut)
{
// Instance of the max-cut problem provided as adjacency matrix.
// It is a ring of 6 vertices:
//
// 0--1--2
// | |
// 5--4--3
//
// where the verical edges have weight 1.4
std::vector<double> adjacency = {0 , 1 , 0 , 0 , 0 , 1.4,
1 , 0 , 1 , 0 , 0 , 0 ,
0 , 1 , 0 , 1.4, 0 , 0 ,
0 , 0 , 1.4, 0 , 1 , 0 ,
0 , 0 , 0 , 1 , 0 , 1 ,
1.4, 0 , 0 , 0 , 1 , 0 };
QubitRegister<ComplexDP> diag (num_qubits_,"base",0);
double max_cut_value;
max_cut_value = qaoa::InitializeVectorAsWeightedMaxCutCostFunction(diag,adjacency);
// Among other properties, only two bipartition has cut=0.
ComplexDP amplitude;
amplitude = { 0, 0 };
ASSERT_COMPLEX_NEAR(diag.GetGlobalAmplitude(0), amplitude, accepted_error_);
ASSERT_COMPLEX_NEAR(diag.GetGlobalAmplitude(diag.GlobalSize()-1), amplitude,
accepted_error_);
// Case in which only 2 is dis-aligned:
// 001000 = 1*2^2
amplitude = { 1+1.4, 0 };
size_t index = 2*2;
ASSERT_COMPLEX_NEAR(diag.GetGlobalAmplitude(index), amplitude, accepted_error_);
// Case in which only 2 and 5 are dis-aligned:
// 001001 = 1*2^2 + 1*2^5
amplitude = { 1+1.4+1+1.4, 0 };
index = 4+32;
ASSERT_COMPLEX_NEAR(diag.GetGlobalAmplitude(index), amplitude, accepted_error_);
// No bipartition can cut a single edge.
for (size_t j=0; j<diag.LocalSize(); ++j)
ASSERT_GT( std::abs(diag[j].real()-1.), accepted_error_);
// Perform QAOA simulation (p=1).
QubitRegister<ComplexDP> psi (num_qubits_,"++++",0);
double gamma = 0.4;
double beta = 0.3;
// Emulation of the layer based on the cost function:
qaoa::ImplementQaoaLayerBasedOnCostFunction(psi, diag, gamma);
// Simulation of the layer based on the local transverse field:
for (int qubit=0; qubit<num_qubits_; ++qubit)
psi.ApplyRotationX(qubit, beta);
// Get average of cut value:
double expectation = qaoa::GetExpectationValueFromCostFunction(psi, diag);
// Histogram for rounded cutvals and check if it matches expval to the tolerance.
std::vector<double> histo = qaoa::GetHistogramFromCostFunctionWithWeightsRounded(psi, diag, max_cut_value);
ASSERT_EQ(histo.size(), (int)(floor(max_cut_value))+1);
double average=0;
for (int j=0; j<histo.size(); ++j)
average += double(j)*histo[j];
// The expval will be within less than 1.0 of the actual since the cutvals are rounded down to nearest 1.0.
ASSERT_TRUE( (abs(expectation - average) )<=1.0+1e-7);
// Histogram for rounded cutvals and check if it matches expval to the tolerance.
double bin_width = 0.1;
std::vector<double> histo2 = qaoa::GetHistogramFromCostFunctionWithWeightsBinned(psi, diag, max_cut_value, bin_width);
ASSERT_EQ(histo2.size(), (int)(ceil(max_cut_value / bin_width)) + 1);
average = 0.0;
for (int j=0; j<histo2.size(); ++j)
average += double(j)*bin_width*histo2[j];
// The expval will be within less than bin_width of the actual since the cutvals are rounded down to the bin_width.
ASSERT_TRUE( (abs(expectation - average) )<=bin_width+1e-7);
}
//////////////////////////////////////////////////////////////////////////////
#endif // header guard EXTRA_FEATURES_TEST_HPP
| 39.337278 | 120 | 0.602136 | wh5a |
14149a39491f7d7fde5c6c4282ddd14371a352f0 | 8,667 | cpp | C++ | lib/string.cpp | bilyanhadzhi/susi | 92ae0e30fe67b544f75fc3581b292ea87f4f078c | [
"MIT"
] | 1 | 2021-03-01T14:14:56.000Z | 2021-03-01T14:14:56.000Z | lib/string.cpp | bilyanhadzhi/susi | 92ae0e30fe67b544f75fc3581b292ea87f4f078c | [
"MIT"
] | null | null | null | lib/string.cpp | bilyanhadzhi/susi | 92ae0e30fe67b544f75fc3581b292ea87f4f078c | [
"MIT"
] | null | null | null | #include <fstream>
#include <cstring>
#include <cassert>
#include "string.hpp"
#include "../constants.hpp"
void String::copy_from(const String& other)
{
this->capacity = this->get_needed_capacity(other.value);
this->set_value(other.value);
this->len = other.len;
}
void String::free_memory()
{
if (this->value != nullptr)
{
delete[] this->value;
this->value = nullptr;
}
}
String::String()
{
this->capacity = BUFFER_SIZE;
this->value = new char[this->capacity]();
this->len = 0;
}
String::String(const char* str)
{
assert(str != nullptr);
this->capacity = this->get_needed_capacity(str);
this->value = new char[this->capacity]();
strcpy(this->value, str);
this->len = strlen(this->value);
}
String::String(const String& other)
{
this->capacity = other.capacity;
this->value = nullptr;
this->set_value(other.value);
this->len = other.len;
}
String& String::operator=(const String& other)
{
if (this == &other)
{
return *this;
}
this->free_memory();
this->copy_from(other);
return *this;
}
String& String::operator=(const char* str)
{
assert(str != nullptr);
this->set_value(str);
return *this;
}
String::~String()
{
this->free_memory();
}
void String::set_value(const char* value)
{
assert(value != nullptr);
const int value_len = strlen(value);
this->capacity = this->get_needed_capacity(value);
this->len = value_len;
char* new_value = new char[this->capacity]();
strcpy(new_value, value);
if (this->value != nullptr)
{
delete[] this->value;
}
this->value = new_value;
this->len = strlen(this->value);
}
void String::increase_capacity()
{
this->capacity *= 2;
char* value_new_capacity = new char[this->capacity]();
strcpy(value_new_capacity, this->value);
delete[] this->value;
this->value = value_new_capacity;
}
int String::get_needed_capacity(const char* string) const
{
int temp_capacity = BUFFER_SIZE;
int str_len = strlen(string);
if (str_len == 0)
{
return temp_capacity;
}
while (temp_capacity < str_len)
{
temp_capacity *= 2;
}
return temp_capacity;
}
std::ostream& operator<<(std::ostream& o_stream, const String& string)
{
o_stream << string.value;
return o_stream;
}
char String::operator[](int i) const
{
assert(i >= 0);
if (i >= this->len)
{
return '\0';
}
return this->value[i];
}
void String::input(std::istream& i_stream, bool whole_line)
{
char curr_char;
int string_len = 0;
int string_capacity = BUFFER_SIZE;
char* new_string_value = new char[string_capacity]();
if (i_stream.peek() == EOF || i_stream.peek() == '\n')
{
delete[] new_string_value;
this->set_value("");
if (std::cin.peek() == '\n')
{
std::cin.get();
}
return;
}
// skip whitespace
while (i_stream.peek() == ' ')
{
i_stream.get();
}
do
{
curr_char = i_stream.get();
if (!whole_line && curr_char == ' ')
{
break;
}
if (curr_char == '\n' || curr_char == EOF)
{
break;
}
if (string_len + 1 >= string_capacity)
{
char* bigger = new char[string_capacity *= 2]();
strcpy(bigger, new_string_value);
delete[] new_string_value;
new_string_value = bigger;
}
new_string_value[string_len++] = curr_char;
} while (i_stream.peek() != '\n');
new_string_value[string_len] = '\0';
this->set_value(new_string_value);
delete[] new_string_value;
}
std::istream& operator>>(std::istream& i_stream, String& string)
{
string.input(i_stream);
return i_stream;
}
bool operator==(const String& left_string, const String& right_string)
{
return strcmp(left_string.value, right_string.value) == 0;
}
bool operator==(const String& string, const char* c_string)
{
return strcmp(string.value, c_string) == 0;
}
bool operator==(const char* c_string, const String& string)
{
return strcmp(c_string, string.value) == 0;
}
bool operator!=(const String& left_string, const String& right_string)
{
return !(left_string == right_string);
}
bool operator!=(const String& string, const char* c_string)
{
return !(string == c_string);
}
bool operator!=(const char* c_string, const String& string)
{
return !(c_string == string);
}
String& String::operator+=(const char new_char)
{
if (this->len + 1 >= this->capacity)
{
this->increase_capacity();
}
this->value[len] = new_char;
if (new_char != '\0')
{
++len;
}
return *this;
}
String& String::operator+=(const char* to_append)
{
assert(to_append != nullptr);
const int to_append_len = strlen(to_append);
if (to_append_len < 1)
{
return *this;
}
for (int i = 0; i < to_append_len; ++i)
{
*this += to_append[i];
}
return *this;
}
String& String::operator+=(const String to_append)
{
const int to_append_len = to_append.get_len();
if (to_append_len < 1)
{
return *this;
}
for (int i = 0; i < to_append_len; ++i)
{
*this += to_append[i];
}
return *this;
}
int String::get_len() const
{
return this->len;
}
bool String::is_valid_number(bool check_for_int_only) const
{
const int len = this->get_len();
bool found_dot = this->value[0] == '.';
bool is_valid = true;
if (len < 1)
{
is_valid = false;
}
if (this->value[0] != '-' && this->value[0] != '+' && !isdigit(this->value[0]))
{
is_valid = false;
}
int beg_index = this->value[0] == '-' || this->value[0] == '+';
for (int i = beg_index; i < len && is_valid; ++i)
{
if (!isdigit(this->value[i]))
{
if (this->value[i] == '.')
{
// Found 2nd dot -> invalid
if (found_dot)
{
is_valid = false;
}
else
{
found_dot = true;
}
}
else
{
is_valid = false;
}
}
}
if (check_for_int_only && found_dot)
{
is_valid = false;
}
return is_valid;
}
double String::to_double() const
{
if (!this->is_valid_number())
{
return -__DBL_MAX__;
}
double result = 0.0;
int len = this->get_len();
bool has_sign = this->value[0] == '+' || this->value[0] == '-';
bool is_int = true;
int begin_index = has_sign ? 1 : 0;
int i = begin_index;
// skip beginning zeros
while (this->value[i] == '0')
{
++i;
}
// get integer part
while (i < len)
{
if (this->value[i] == '.')
{
is_int = false;
++i;
break;
}
result *= 10;
result += (int)(this->value[i] - '0');
++i;
}
// get fractional part
double divide_by = 10;
// know decimal places so to round number
int dec_places = 0;
if (!is_int)
{
while (i < len && dec_places < 2)
{
result += (double)(this->value[i] - '0') / divide_by;
divide_by *= 10;
++dec_places;
++i;
}
}
if (dec_places >= 2 && (int)(this->value[i] - '0') >= 5)
{
result += 10 / divide_by;
}
bool is_negative = has_sign && this->value[0] == '-';
return is_negative ? -result : result;
}
int String::to_int() const
{
return (int)this->to_double();
}
bool String::read_from_bin(std::ifstream& if_stream)
{
if (if_stream.eof())
{
return false;
}
int value_len;
if (!if_stream.read((char*)&value_len, sizeof(int)))
{
return false;
}
char* new_value = new char[value_len + 1];
if (!if_stream.read(new_value, value_len))
{
delete[] new_value;
return false;
}
new_value[value_len] = '\0';
this->set_value(new_value);
delete[] new_value;
return true;
}
bool String::write_to_bin(std::ofstream& of_stream) const
{
if (this->len < 1)
{
return false;
}
if (!of_stream.write((char*)&this->len, sizeof(int)))
{
return false;
}
if (!of_stream.write(this->value, this->len))
{
return false;
}
return true;
}
const char* String::to_c_string() const
{
return this->value;
}
| 18.440426 | 83 | 0.543671 | bilyanhadzhi |
1416b0991154bafad89626ae8e9641383bab2bd8 | 6,244 | hpp | C++ | include/UnityEngine/TextCore/LowLevel/GlyphPairAdjustmentRecord.hpp | RedBrumbler/virtuoso-codegen | e83f6f0f9b47bec4b6dd976b21edc1d46bf3cfe3 | [
"Unlicense"
] | null | null | null | include/UnityEngine/TextCore/LowLevel/GlyphPairAdjustmentRecord.hpp | RedBrumbler/virtuoso-codegen | e83f6f0f9b47bec4b6dd976b21edc1d46bf3cfe3 | [
"Unlicense"
] | null | null | null | include/UnityEngine/TextCore/LowLevel/GlyphPairAdjustmentRecord.hpp | RedBrumbler/virtuoso-codegen | e83f6f0f9b47bec4b6dd976b21edc1d46bf3cfe3 | [
"Unlicense"
] | null | null | null | // Autogenerated from CppHeaderCreator
// Created by Sc2ad
// =========================================================================
#pragma once
// Begin includes
#include "beatsaber-hook/shared/utils/typedefs.h"
#include "beatsaber-hook/shared/utils/byref.hpp"
// Including type: System.ValueType
#include "System/ValueType.hpp"
// Including type: UnityEngine.TextCore.LowLevel.GlyphAdjustmentRecord
#include "UnityEngine/TextCore/LowLevel/GlyphAdjustmentRecord.hpp"
// Including type: UnityEngine.TextCore.LowLevel.FontFeatureLookupFlags
#include "UnityEngine/TextCore/LowLevel/FontFeatureLookupFlags.hpp"
// Completed includes
// Type namespace: UnityEngine.TextCore.LowLevel
namespace UnityEngine::TextCore::LowLevel {
// Forward declaring type: GlyphPairAdjustmentRecord
struct GlyphPairAdjustmentRecord;
}
#include "beatsaber-hook/shared/utils/il2cpp-type-check.hpp"
DEFINE_IL2CPP_ARG_TYPE(::UnityEngine::TextCore::LowLevel::GlyphPairAdjustmentRecord, "UnityEngine.TextCore.LowLevel", "GlyphPairAdjustmentRecord");
// Type namespace: UnityEngine.TextCore.LowLevel
namespace UnityEngine::TextCore::LowLevel {
// Size: 0x2C
#pragma pack(push, 1)
// WARNING Layout: Sequential may not be correctly taken into account!
// Autogenerated type: UnityEngine.TextCore.LowLevel.GlyphPairAdjustmentRecord
// [TokenAttribute] Offset: FFFFFFFF
// [UsedByNativeCodeAttribute] Offset: 5BC52C
// [DebuggerDisplayAttribute] Offset: 5BC52C
struct GlyphPairAdjustmentRecord/*, public ::System::ValueType*/ {
public:
public:
// [NativeNameAttribute] Offset: 0x5BD1F8
// private UnityEngine.TextCore.LowLevel.GlyphAdjustmentRecord m_FirstAdjustmentRecord
// Size: 0x14
// Offset: 0x0
::UnityEngine::TextCore::LowLevel::GlyphAdjustmentRecord m_FirstAdjustmentRecord;
// Field size check
static_assert(sizeof(::UnityEngine::TextCore::LowLevel::GlyphAdjustmentRecord) == 0x14);
// [NativeNameAttribute] Offset: 0x5BD244
// private UnityEngine.TextCore.LowLevel.GlyphAdjustmentRecord m_SecondAdjustmentRecord
// Size: 0x14
// Offset: 0x14
::UnityEngine::TextCore::LowLevel::GlyphAdjustmentRecord m_SecondAdjustmentRecord;
// Field size check
static_assert(sizeof(::UnityEngine::TextCore::LowLevel::GlyphAdjustmentRecord) == 0x14);
// private UnityEngine.TextCore.LowLevel.FontFeatureLookupFlags m_FeatureLookupFlags
// Size: 0x4
// Offset: 0x28
::UnityEngine::TextCore::LowLevel::FontFeatureLookupFlags m_FeatureLookupFlags;
// Field size check
static_assert(sizeof(::UnityEngine::TextCore::LowLevel::FontFeatureLookupFlags) == 0x4);
public:
// Creating value type constructor for type: GlyphPairAdjustmentRecord
constexpr GlyphPairAdjustmentRecord(::UnityEngine::TextCore::LowLevel::GlyphAdjustmentRecord m_FirstAdjustmentRecord_ = {}, ::UnityEngine::TextCore::LowLevel::GlyphAdjustmentRecord m_SecondAdjustmentRecord_ = {}, ::UnityEngine::TextCore::LowLevel::FontFeatureLookupFlags m_FeatureLookupFlags_ = {}) noexcept : m_FirstAdjustmentRecord{m_FirstAdjustmentRecord_}, m_SecondAdjustmentRecord{m_SecondAdjustmentRecord_}, m_FeatureLookupFlags{m_FeatureLookupFlags_} {}
// Creating interface conversion operator: operator ::System::ValueType
operator ::System::ValueType() noexcept {
return *reinterpret_cast<::System::ValueType*>(this);
}
// Get instance field reference: private UnityEngine.TextCore.LowLevel.GlyphAdjustmentRecord m_FirstAdjustmentRecord
::UnityEngine::TextCore::LowLevel::GlyphAdjustmentRecord& dyn_m_FirstAdjustmentRecord();
// Get instance field reference: private UnityEngine.TextCore.LowLevel.GlyphAdjustmentRecord m_SecondAdjustmentRecord
::UnityEngine::TextCore::LowLevel::GlyphAdjustmentRecord& dyn_m_SecondAdjustmentRecord();
// Get instance field reference: private UnityEngine.TextCore.LowLevel.FontFeatureLookupFlags m_FeatureLookupFlags
::UnityEngine::TextCore::LowLevel::FontFeatureLookupFlags& dyn_m_FeatureLookupFlags();
// public UnityEngine.TextCore.LowLevel.GlyphAdjustmentRecord get_firstAdjustmentRecord()
// Offset: 0x12E96BC
::UnityEngine::TextCore::LowLevel::GlyphAdjustmentRecord get_firstAdjustmentRecord();
// public UnityEngine.TextCore.LowLevel.GlyphAdjustmentRecord get_secondAdjustmentRecord()
// Offset: 0x12E96D0
::UnityEngine::TextCore::LowLevel::GlyphAdjustmentRecord get_secondAdjustmentRecord();
}; // UnityEngine.TextCore.LowLevel.GlyphPairAdjustmentRecord
#pragma pack(pop)
static check_size<sizeof(GlyphPairAdjustmentRecord), 40 + sizeof(::UnityEngine::TextCore::LowLevel::FontFeatureLookupFlags)> __UnityEngine_TextCore_LowLevel_GlyphPairAdjustmentRecordSizeCheck;
static_assert(sizeof(GlyphPairAdjustmentRecord) == 0x2C);
}
#include "beatsaber-hook/shared/utils/il2cpp-utils-methods.hpp"
// Writing MetadataGetter for method: UnityEngine::TextCore::LowLevel::GlyphPairAdjustmentRecord::get_firstAdjustmentRecord
// Il2CppName: get_firstAdjustmentRecord
template<>
struct ::il2cpp_utils::il2cpp_type_check::MetadataGetter<static_cast<::UnityEngine::TextCore::LowLevel::GlyphAdjustmentRecord (UnityEngine::TextCore::LowLevel::GlyphPairAdjustmentRecord::*)()>(&UnityEngine::TextCore::LowLevel::GlyphPairAdjustmentRecord::get_firstAdjustmentRecord)> {
static const MethodInfo* get() {
return ::il2cpp_utils::FindMethod(classof(UnityEngine::TextCore::LowLevel::GlyphPairAdjustmentRecord), "get_firstAdjustmentRecord", std::vector<Il2CppClass*>(), ::std::vector<const Il2CppType*>{});
}
};
// Writing MetadataGetter for method: UnityEngine::TextCore::LowLevel::GlyphPairAdjustmentRecord::get_secondAdjustmentRecord
// Il2CppName: get_secondAdjustmentRecord
template<>
struct ::il2cpp_utils::il2cpp_type_check::MetadataGetter<static_cast<::UnityEngine::TextCore::LowLevel::GlyphAdjustmentRecord (UnityEngine::TextCore::LowLevel::GlyphPairAdjustmentRecord::*)()>(&UnityEngine::TextCore::LowLevel::GlyphPairAdjustmentRecord::get_secondAdjustmentRecord)> {
static const MethodInfo* get() {
return ::il2cpp_utils::FindMethod(classof(UnityEngine::TextCore::LowLevel::GlyphPairAdjustmentRecord), "get_secondAdjustmentRecord", std::vector<Il2CppClass*>(), ::std::vector<const Il2CppType*>{});
}
};
| 65.726316 | 464 | 0.788597 | RedBrumbler |
1417207abb02a99c22957e6bf67017ba855f6d3e | 2,370 | cc | C++ | shell/browser/ui/win/atom_desktop_native_widget_aura.cc | CezaryKulakowski/electron | eb6660f5341d6d7e2143be31eefec558fd866c84 | [
"MIT"
] | 4 | 2019-07-05T20:42:42.000Z | 2020-01-02T07:26:56.000Z | shell/browser/ui/win/atom_desktop_native_widget_aura.cc | CezaryKulakowski/electron | eb6660f5341d6d7e2143be31eefec558fd866c84 | [
"MIT"
] | 4 | 2021-03-11T05:19:38.000Z | 2022-03-28T01:24:48.000Z | shell/browser/ui/win/atom_desktop_native_widget_aura.cc | CezaryKulakowski/electron | eb6660f5341d6d7e2143be31eefec558fd866c84 | [
"MIT"
] | null | null | null | // Copyright (c) 2017 GitHub, Inc.
// Use of this source code is governed by the MIT license that can be
// found in the LICENSE file.
#include "shell/browser/ui/win/atom_desktop_native_widget_aura.h"
#include "shell/browser/ui/win/atom_desktop_window_tree_host_win.h"
#include "ui/views/corewm/tooltip_controller.h"
#include "ui/wm/public/tooltip_client.h"
namespace electron {
AtomDesktopNativeWidgetAura::AtomDesktopNativeWidgetAura(
NativeWindowViews* native_window_view)
: views::DesktopNativeWidgetAura(native_window_view->widget()),
native_window_view_(native_window_view) {
GetNativeWindow()->SetName("AtomDesktopNativeWidgetAura");
// This is to enable the override of OnWindowActivated
wm::SetActivationChangeObserver(GetNativeWindow(), this);
}
void AtomDesktopNativeWidgetAura::InitNativeWidget(
const views::Widget::InitParams& params) {
views::Widget::InitParams modified_params = params;
desktop_window_tree_host_ = new AtomDesktopWindowTreeHostWin(
native_window_view_,
static_cast<views::DesktopNativeWidgetAura*>(params.native_widget));
modified_params.desktop_window_tree_host = desktop_window_tree_host_;
views::DesktopNativeWidgetAura::InitNativeWidget(modified_params);
}
void AtomDesktopNativeWidgetAura::Activate() {
// Activate can cause the focused window to be blurred so only
// call when the window being activated is visible. This prevents
// hidden windows from blurring the focused window when created.
if (IsVisible())
views::DesktopNativeWidgetAura::Activate();
}
void AtomDesktopNativeWidgetAura::OnWindowActivated(
wm::ActivationChangeObserver::ActivationReason reason,
aura::Window* gained_active,
aura::Window* lost_active) {
views::DesktopNativeWidgetAura::OnWindowActivated(reason, gained_active,
lost_active);
if (lost_active != nullptr) {
auto* tooltip_controller = static_cast<views::corewm::TooltipController*>(
wm::GetTooltipClient(lost_active->GetRootWindow()));
// This will cause the tooltip to be hidden when a window is deactivated,
// as it should be.
// TODO(brenca): Remove this fix when the chromium issue is fixed.
// crbug.com/724538
if (tooltip_controller != nullptr)
tooltip_controller->OnCancelMode(nullptr);
}
}
} // namespace electron
| 39.5 | 78 | 0.753586 | CezaryKulakowski |
1419a26dccf467f4d83a38faecc92571c622b84f | 4,268 | hpp | C++ | include/okapi/api.hpp | seendsouza/PROS_CPP_6M_Template | d93b32911d6cf9432718fad41ee3a8ec55c89184 | [
"MIT"
] | 7 | 2019-05-15T00:44:20.000Z | 2020-08-31T14:17:37.000Z | include/okapi/api.hpp | seendsouza/PROS_CPP_6M_Template | d93b32911d6cf9432718fad41ee3a8ec55c89184 | [
"MIT"
] | 3 | 2019-07-26T15:56:19.000Z | 2019-07-29T02:55:32.000Z | include/okapi/api.hpp | 1069B/Tower_Takeover | 331a323216cd006a8cc3bc7a326ebe3a463e429f | [
"MIT"
] | 3 | 2019-05-31T18:08:54.000Z | 2019-08-29T22:53:53.000Z | /**
* @author Ryan Benasutti, WPI
*
* 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/.
*/
#pragma once
#include "okapi/api/chassis/controller/chassisControllerIntegrated.hpp"
#include "okapi/api/chassis/controller/chassisControllerPid.hpp"
#include "okapi/api/chassis/controller/chassisScales.hpp"
#include "okapi/api/chassis/model/readOnlyChassisModel.hpp"
#include "okapi/api/chassis/model/skidSteerModel.hpp"
#include "okapi/api/chassis/model/threeEncoderSkidSteerModel.hpp"
#include "okapi/api/chassis/model/xDriveModel.hpp"
#include "okapi/impl/chassis/controller/chassisControllerFactory.hpp"
#include "okapi/impl/chassis/model/chassisModelFactory.hpp"
#include "okapi/api/control/async/asyncLinearMotionProfileController.hpp"
#include "okapi/api/control/async/asyncMotionProfileController.hpp"
#include "okapi/api/control/async/asyncPosIntegratedController.hpp"
#include "okapi/api/control/async/asyncPosPidController.hpp"
#include "okapi/api/control/async/asyncVelIntegratedController.hpp"
#include "okapi/api/control/async/asyncVelPidController.hpp"
#include "okapi/api/control/async/asyncWrapper.hpp"
#include "okapi/api/control/controllerInput.hpp"
#include "okapi/api/control/controllerOutput.hpp"
#include "okapi/api/control/iterative/iterativeMotorVelocityController.hpp"
#include "okapi/api/control/iterative/iterativePosPidController.hpp"
#include "okapi/api/control/iterative/iterativeVelPidController.hpp"
#include "okapi/api/control/util/controllerRunner.hpp"
#include "okapi/api/control/util/flywheelSimulator.hpp"
#include "okapi/api/control/util/pidTuner.hpp"
#include "okapi/api/control/util/settledUtil.hpp"
#include "okapi/impl/control/async/asyncControllerFactory.hpp"
#include "okapi/impl/control/iterative/iterativeControllerFactory.hpp"
#include "okapi/impl/control/util/controllerRunnerFactory.hpp"
#include "okapi/impl/control/util/pidTunerFactory.hpp"
#include "okapi/impl/control/util/settledUtilFactory.hpp"
#include "okapi/api/device/rotarysensor/continuousRotarySensor.hpp"
#include "okapi/api/device/rotarysensor/rotarySensor.hpp"
#include "okapi/impl/device/adiUltrasonic.hpp"
#include "okapi/impl/device/button/adiButton.hpp"
#include "okapi/impl/device/button/controllerButton.hpp"
#include "okapi/impl/device/controller.hpp"
#include "okapi/impl/device/motor/motor.hpp"
#include "okapi/impl/device/motor/motorGroup.hpp"
#include "okapi/impl/device/rotarysensor/adiEncoder.hpp"
#include "okapi/impl/device/rotarysensor/adiGyro.hpp"
#include "okapi/impl/device/rotarysensor/integratedEncoder.hpp"
#include "okapi/impl/device/rotarysensor/potentiometer.hpp"
#include "okapi/impl/device/vision.hpp"
#include "okapi/api/filter/averageFilter.hpp"
#include "okapi/api/filter/composableFilter.hpp"
#include "okapi/api/filter/demaFilter.hpp"
#include "okapi/api/filter/ekfFilter.hpp"
#include "okapi/api/filter/emaFilter.hpp"
#include "okapi/api/filter/filter.hpp"
#include "okapi/api/filter/filteredControllerInput.hpp"
#include "okapi/api/filter/medianFilter.hpp"
#include "okapi/api/filter/passthroughFilter.hpp"
#include "okapi/api/filter/velMath.hpp"
#include "okapi/impl/filter/velMathFactory.hpp"
#include "okapi/api/units/QAcceleration.hpp"
#include "okapi/api/units/QAngle.hpp"
#include "okapi/api/units/QAngularAcceleration.hpp"
#include "okapi/api/units/QAngularJerk.hpp"
#include "okapi/api/units/QAngularSpeed.hpp"
#include "okapi/api/units/QArea.hpp"
#include "okapi/api/units/QForce.hpp"
#include "okapi/api/units/QFrequency.hpp"
#include "okapi/api/units/QJerk.hpp"
#include "okapi/api/units/QLength.hpp"
#include "okapi/api/units/QMass.hpp"
#include "okapi/api/units/QPressure.hpp"
#include "okapi/api/units/QSpeed.hpp"
#include "okapi/api/units/QTime.hpp"
#include "okapi/api/units/QTorque.hpp"
#include "okapi/api/units/QVolume.hpp"
#include "okapi/api/util/abstractRate.hpp"
#include "okapi/api/util/abstractTimer.hpp"
#include "okapi/api/util/mathUtil.hpp"
#include "okapi/api/util/supplier.hpp"
#include "okapi/api/util/timeUtil.hpp"
#include "okapi/impl/util/rate.hpp"
#include "okapi/impl/util/timeUtilFactory.hpp"
#include "okapi/impl/util/timer.hpp"
| 45.892473 | 75 | 0.806467 | seendsouza |
141b7965c07f0f45e8fd46372b9f0a7378e9b13c | 3,130 | cc | C++ | B2G/gecko/media/webrtc/trunk/src/common_audio/vad/vad_core_unittest.cc | wilebeast/FireFox-OS | 43067f28711d78c429a1d6d58c77130f6899135f | [
"Apache-2.0"
] | 3 | 2015-08-31T15:24:31.000Z | 2020-04-24T20:31:29.000Z | hookflash-core/webRTC/webRTC_ios/src/common_audio/vad/vad_core_unittest.cc | ilin-in/OP | bf3e87d90008e2a4106ee70360fbe15b0d694e77 | [
"Unlicense"
] | null | null | null | hookflash-core/webRTC/webRTC_ios/src/common_audio/vad/vad_core_unittest.cc | ilin-in/OP | bf3e87d90008e2a4106ee70360fbe15b0d694e77 | [
"Unlicense"
] | 3 | 2015-07-29T07:17:15.000Z | 2020-11-04T06:55:37.000Z | /*
* Copyright (c) 2012 The WebRTC project authors. All Rights Reserved.
*
* Use of this source code is governed by a BSD-style license
* that can be found in the LICENSE file in the root of the source
* tree. An additional intellectual property rights grant can be found
* in the file PATENTS. All contributing project authors may
* be found in the AUTHORS file in the root of the source tree.
*/
#include <stdlib.h>
#include "gtest/gtest.h"
#include "typedefs.h"
#include "vad_unittest.h"
extern "C" {
#include "vad_core.h"
}
namespace {
TEST_F(VadTest, InitCore) {
// Test WebRtcVad_InitCore().
VadInstT* self = reinterpret_cast<VadInstT*>(malloc(sizeof(VadInstT)));
// NULL pointer test.
EXPECT_EQ(-1, WebRtcVad_InitCore(NULL));
// Verify return = 0 for non-NULL pointer.
EXPECT_EQ(0, WebRtcVad_InitCore(self));
// Verify init_flag is set.
EXPECT_EQ(42, self->init_flag);
free(self);
}
TEST_F(VadTest, set_mode_core) {
VadInstT* self = reinterpret_cast<VadInstT*>(malloc(sizeof(VadInstT)));
// TODO(bjornv): Add NULL pointer check if we take care of it in
// vad_core.c
ASSERT_EQ(0, WebRtcVad_InitCore(self));
// Test WebRtcVad_set_mode_core().
// Invalid modes should return -1.
EXPECT_EQ(-1, WebRtcVad_set_mode_core(self, -1));
EXPECT_EQ(-1, WebRtcVad_set_mode_core(self, 1000));
// Valid modes should return 0.
for (size_t j = 0; j < kModesSize; ++j) {
EXPECT_EQ(0, WebRtcVad_set_mode_core(self, kModes[j]));
}
free(self);
}
TEST_F(VadTest, CalcVad) {
VadInstT* self = reinterpret_cast<VadInstT*>(malloc(sizeof(VadInstT)));
int16_t speech[kMaxFrameLength];
// TODO(bjornv): Add NULL pointer check if we take care of it in
// vad_core.c
// Test WebRtcVad_CalcVadXXkhz()
// Verify that all zeros in gives VAD = 0 out.
memset(speech, 0, sizeof(speech));
ASSERT_EQ(0, WebRtcVad_InitCore(self));
for (size_t j = 0; j < kFrameLengthsSize; ++j) {
if (ValidRatesAndFrameLengths(8000, kFrameLengths[j])) {
EXPECT_EQ(0, WebRtcVad_CalcVad8khz(self, speech, kFrameLengths[j]));
}
if (ValidRatesAndFrameLengths(16000, kFrameLengths[j])) {
EXPECT_EQ(0, WebRtcVad_CalcVad16khz(self, speech, kFrameLengths[j]));
}
if (ValidRatesAndFrameLengths(32000, kFrameLengths[j])) {
EXPECT_EQ(0, WebRtcVad_CalcVad32khz(self, speech, kFrameLengths[j]));
}
}
// Construct a speech signal that will trigger the VAD in all modes. It is
// known that (i * i) will wrap around, but that doesn't matter in this case.
for (int16_t i = 0; i < kMaxFrameLength; ++i) {
speech[i] = (i * i);
}
for (size_t j = 0; j < kFrameLengthsSize; ++j) {
if (ValidRatesAndFrameLengths(8000, kFrameLengths[j])) {
EXPECT_EQ(1, WebRtcVad_CalcVad8khz(self, speech, kFrameLengths[j]));
}
if (ValidRatesAndFrameLengths(16000, kFrameLengths[j])) {
EXPECT_EQ(1, WebRtcVad_CalcVad16khz(self, speech, kFrameLengths[j]));
}
if (ValidRatesAndFrameLengths(32000, kFrameLengths[j])) {
EXPECT_EQ(1, WebRtcVad_CalcVad32khz(self, speech, kFrameLengths[j]));
}
}
free(self);
}
} // namespace
| 31.3 | 79 | 0.69361 | wilebeast |
141bb1ef6637cb707642cb2d692ff6b0307652cf | 1,868 | cpp | C++ | main.cpp | chenhongqiao/FCWT | 16034c4422db0119d680ff1af0ad68dc149b0b47 | [
"MIT"
] | null | null | null | main.cpp | chenhongqiao/FCWT | 16034c4422db0119d680ff1af0ad68dc149b0b47 | [
"MIT"
] | null | null | null | main.cpp | chenhongqiao/FCWT | 16034c4422db0119d680ff1af0ad68dc149b0b47 | [
"MIT"
] | null | null | null | #include <iostream>
#include <vector>
#include <map>
#include <fstream>
#include "input.h"
#include <iomanip>
std::map<std::string, short int> vocab_tree(const std::vector<std::string> &v) {
std::map<std::string, short int> m;
for (auto &i : v) {
for (int j = 1; j < i.size(); ++j) {
if (m[i.substr(0, j)] != 2) {
m[i.substr(0, j)] = 1;
}
}
m[i] = 2;
}
return m;
}
int main() {
std::ifstream vs;
std::ifstream ps;
vs.open("vocab.in");
ps.open("para.in");
if (!vs) {
vs.close();
std::string vfn;
std::cout << "Vocabulary file path: ";
std::cin >> vfn;
vs.open(vfn);
}
if (!ps) {
ps.close();
std::string pfn;
std::cout << "Paragraph file path: ";
std::cin >> pfn;
ps.open(pfn);
}
std::vector<std::string> v = read_vocab(vs);
std::map<std::string, short int> vt = vocab_tree(v);
std::string p = read_para(ps);
std::map<std::string, int> cnt;
for (int i = 0; i < p.size(); ++i) {
std::string can;
int j;
for (j = 1; j <= p.size() - i; ++j) {
if (vt[p.substr(i, j)] == 2) {
can = p.substr(i, j);
} else if (vt[p.substr(i, j)] != 1) {
break;
}
}
if (!can.empty()) {
i += j - 3;
cnt[can]++;
}
}
int cvd = 0;
for (auto &i : v) {
if (cnt[i] > 0) {
cvd++;
std::cout << "(" << cnt[i] << ") " << i << std::endl;
} else {
std::cout << "(X)" << " " << i << std::endl;
}
}
std::cout << cvd << "/" << v.size();
std::cout << " " << std::fixed << std::setprecision(1) << 1.0 * cvd / v.size() * 100 + 0.05 << "% " << std::endl;
return 0;
}
| 24.25974 | 117 | 0.41167 | chenhongqiao |
141c4d7a5d6cf1a31b3fe05d2cbb6bf3557c189a | 1,138 | cc | C++ | native_client_sdk/src/libraries/nacl_io/nacl_io.cc | zealoussnow/chromium | fd8a8914ca0183f0add65ae55f04e287543c7d4a | [
"BSD-3-Clause-No-Nuclear-License-2014",
"BSD-3-Clause"
] | 14,668 | 2015-01-01T01:57:10.000Z | 2022-03-31T23:33:32.000Z | native_client_sdk/src/libraries/nacl_io/nacl_io.cc | zealoussnow/chromium | fd8a8914ca0183f0add65ae55f04e287543c7d4a | [
"BSD-3-Clause-No-Nuclear-License-2014",
"BSD-3-Clause"
] | 395 | 2020-04-18T08:22:18.000Z | 2021-12-08T13:04:49.000Z | native_client_sdk/src/libraries/nacl_io/nacl_io.cc | zealoussnow/chromium | fd8a8914ca0183f0add65ae55f04e287543c7d4a | [
"BSD-3-Clause-No-Nuclear-License-2014",
"BSD-3-Clause"
] | 5,941 | 2015-01-02T11:32:21.000Z | 2022-03-31T16:35:46.000Z | // Copyright (c) 2012 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 "nacl_io/nacl_io.h"
#include <stdlib.h>
#include "nacl_io/kernel_intercept.h"
#include "nacl_io/kernel_proxy.h"
int nacl_io_init() {
return ki_init(NULL);
}
int nacl_io_uninit() {
return ki_uninit();
}
int nacl_io_init_ppapi(PP_Instance instance, PPB_GetInterface get_interface) {
return ki_init_ppapi(NULL, instance, get_interface);
}
int nacl_io_register_fs_type(const char* fs_type, fuse_operations* fuse_ops) {
return ki_get_proxy()->RegisterFsType(fs_type, fuse_ops);
}
int nacl_io_unregister_fs_type(const char* fs_type) {
return ki_get_proxy()->UnregisterFsType(fs_type);
}
void nacl_io_set_exit_callback(nacl_io_exit_callback_t exit_callback,
void* user_data) {
ki_get_proxy()->SetExitCallback(exit_callback, user_data);
}
void nacl_io_set_mount_callback(nacl_io_mount_callback_t callback,
void* user_data) {
ki_get_proxy()->SetMountCallback(callback, user_data);
}
| 28.45 | 78 | 0.740773 | zealoussnow |
141c99031047705bb33532ba1eba1efd77d93b26 | 2,956 | cpp | C++ | src/settings.cpp | adrien1018/tioj-judge | a308d42603caaad71e370fa5d34d4d2cb69936ba | [
"Apache-2.0"
] | 3 | 2017-12-17T02:13:21.000Z | 2018-02-22T13:21:09.000Z | src/settings.cpp | adrien1018/tioj-judge | a308d42603caaad71e370fa5d34d4d2cb69936ba | [
"Apache-2.0"
] | null | null | null | src/settings.cpp | adrien1018/tioj-judge | a308d42603caaad71e370fa5d34d4d2cb69936ba | [
"Apache-2.0"
] | null | null | null | #include "settings.h"
// class ScoreInt
const int ScoreInt::kBase = 1000000;
ScoreInt::ScoreInt() : val_(0) {}
ScoreInt::ScoreInt(double a) : val_(llround(a * kBase)) {}
ScoreInt::ScoreInt(long double a) : val_(llroundl(a * kBase)) {}
ScoreInt::ScoreInt(int64_t a) : val_(a) {}
ScoreInt& ScoreInt::operator=(double a) {
val_ = llround(a * kBase);
return *this;
}
ScoreInt& ScoreInt::operator=(long double a) {
val_ = llroundl(a * kBase);
return *this;
}
ScoreInt& ScoreInt::operator=(int64_t a) {
val_ = a;
return *this;
}
ScoreInt& ScoreInt::operator+=(const ScoreInt& a) {
val_ += a.val_;
return *this;
}
ScoreInt& ScoreInt::operator*=(const ScoreInt& a) {
val_ = static_cast<long double>(val_) / kBase * a.val_;
return *this;
}
ScoreInt::operator long double() const {
return static_cast<long double>(val_) / kBase;
}
ScoreInt::operator int64_t() const {
return static_cast<int64_t>(val_);
}
ScoreInt operator+(ScoreInt a, const ScoreInt& b) {
a += b;
return a;
}
ScoreInt operator*(ScoreInt a, const ScoreInt& b) {
a += b;
return a;
}
// Some default constuctors
ProblemSettings::CompileSettings::CompileSettings() :
lang(kLangNull), args() {}
ProblemSettings::CustomLanguage::CustomLanguage() :
compile(), as_interpreter(false), tl_a(1.), tl_b(0.), ml_a(1.), ml_b(0.),
syscall_adj() {}
ProblemSettings::ResultColumn::ResultColumn() :
type(ProblemSettings::ResultColumn::kScoreFloat), visible(true) {}
ProblemSettings::TestdataFile::TestdataFile() :
id(0), path() {}
ProblemSettings::CommonFile::CommonFile() :
usage(ProblemSettings::CommonFile::kLib), lib_lang(kLangNull), id(0),
stages{0, 0, 0, 0}, file_id(0), path() {}
ProblemSettings::Testdata::Testdata() :
time_lim(1000000), memory_lim(262144), file_id(), args() {}
ProblemSettings::ScoreRange::ScoreRange() :
score(), testdata() {}
// Default problem settings
ProblemSettings::ProblemSettings() :
problem_id(0),
is_one_stage(false), // 4-stage mode
code_check_compile(), // no code checking
custom_lang(), // not used
execution_type(ProblemSettings::kExecNormal), // batch judge
execution_times(1), // not used
lib_compile(), // not used
pipe_in(false), pipe_out(false), // read from file
partial_judge(false), // judge whole problem
evaluation_type(ProblemSettings::kEvalNormal), // normal judge
evaluation_format(ProblemSettings::kEvalFormatZero), // not used
password(0), // not used
evaluation_compile(), // not used
evaluation_columns(), // no additional columns
evaluate_nonnormal(false),
scoring_type(ProblemSettings::kScoringNormal), // normal scoring
scoring_compile(), // not used
scoring_columns(), // no additional columns
file_per_testdata(2), // no additional files
testdata_files(), common_files(), // not used
kill_old(false), // not used
custom_stage(), // not used
testdata(), ranges(), timestamp(0) {}
| 30.474227 | 77 | 0.686062 | adrien1018 |
1420989cb651a7286778c934ce2e6c1e8a93b673 | 10,608 | hh | C++ | gazebo/physics/Inertial.hh | traversaro/gazebo | 6fd426b3949c4ca73fa126cde68f5cc4a59522eb | [
"ECL-2.0",
"Apache-2.0"
] | 887 | 2020-04-18T08:43:06.000Z | 2022-03-31T11:58:50.000Z | gazebo/physics/Inertial.hh | traversaro/gazebo | 6fd426b3949c4ca73fa126cde68f5cc4a59522eb | [
"ECL-2.0",
"Apache-2.0"
] | 462 | 2020-04-21T21:59:19.000Z | 2022-03-31T23:23:21.000Z | gazebo/physics/Inertial.hh | traversaro/gazebo | 6fd426b3949c4ca73fa126cde68f5cc4a59522eb | [
"ECL-2.0",
"Apache-2.0"
] | 421 | 2020-04-21T09:13:03.000Z | 2022-03-30T02:22:01.000Z | /*
* Copyright (C) 2012 Open Source Robotics Foundation
*
* 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 GAZEBO_PHYSICS_INERTIAL_HH_
#define GAZEBO_PHYSICS_INERTIAL_HH_
#include <string>
#include <memory>
#include <ignition/math/Inertial.hh>
#include <sdf/sdf.hh>
#include <ignition/math/Vector3.hh>
#include <ignition/math/Quaternion.hh>
#include <ignition/math/Matrix3.hh>
#include "gazebo/msgs/msgs.hh"
#include "gazebo/util/system.hh"
namespace gazebo
{
namespace physics
{
// Forward declare private data
class InertialPrivate;
/// \addtogroup gazebo_physics
/// \{
/// \class Inertial Inertial.hh physics/physics.hh
/// \brief A class for inertial information about a link
class GZ_PHYSICS_VISIBLE Inertial
{
/// \brief Default Constructor
public: Inertial();
/// \brief Constructor.
/// \param[in] _mass Mass value in kg if using metric.
public: explicit Inertial(const double _mass);
/// \brief Constructor from ignition::math::Inertial.
/// \param[in] _inertial Ignition inertial object to copy.
// cppcheck-suppress noExplicitConstructor
public: Inertial(const ignition::math::Inertiald &_inertial);
/// \brief Copy constructor.
/// \param[in] _inertial Inertial element to copy
public: Inertial(const Inertial &_inertial);
/// \brief Destructor.
public: virtual ~Inertial();
/// \brief Load from SDF values.
/// \param[in] _sdf SDF value to load from.
public: void Load(sdf::ElementPtr _sdf);
/// \brief update the parameters using new sdf values.
/// \param[in] _sdf Update values from.
public: void UpdateParameters(sdf::ElementPtr _sdf);
/// \brief Reset all the mass properties.
public: void Reset();
/// \brief Return copy of Inertial in ignition format.
public: ignition::math::Inertiald Ign() const;
/// \brief Set the mass.
/// \param[in] _m Mass value in kilograms.
public: void SetMass(const double _m);
/// \brief Get the mass
/// \return The mass in kilograms
public: double Mass() const;
/// \brief Set the mass matrix.
/// \param[in] _ixx X second moment of inertia (MOI) about x axis.
/// \param[in] _iyy Y second moment of inertia about y axis.
/// \param[in] _izz Z second moment of inertia about z axis.
/// \param[in] _ixy XY inertia.
/// \param[in] _ixz XZ inertia.
/// \param[in] _iyz YZ inertia.
public: void SetInertiaMatrix(
const double _ixx, const double _iyy, const double _izz,
const double _ixy, const double _ixz, const double iyz);
/// \brief Set the center of gravity.
/// \param[in] _cx X position.
/// \param[in] _cy Y position.
/// \param[in] _cz Z position.
public: void SetCoG(const double _cx, const double _cy, const double _cz);
/// \brief Set the center of gravity.
/// \param[in] _center Center of the gravity.
public: void SetCoG(const ignition::math::Vector3d &_center);
/// \brief Set the center of gravity and rotation offset of inertial
/// coordinate frame relative to Link frame.
/// \param[in] _cx Center offset in x-direction in Link frame
/// \param[in] _cy Center offset in y-direction in Link frame
/// \param[in] _cz Center offset in z-direction in Link frame
/// \param[in] _rx Roll angle offset of inertial coordinate frame.
/// \param[in] _ry Pitch angle offset of inertial coordinate frame.
/// \param[in] _rz Yaw angle offset of inertial coordinate frame.
public: void SetCoG(const double _cx, const double _cy, const double _cz,
const double _rx, const double _ry, const double _rz);
/// \brief Set the center of gravity.
/// \param[in] _c Transform to center of gravity.
public: void SetCoG(const ignition::math::Pose3d &_c);
/// \brief Get the center of gravity.
/// \return The center of gravity.
public: const ignition::math::Vector3d &CoG() const;
/// \brief Get the pose about which the mass and inertia matrix is
/// specified in the Link frame.
/// \return The inertial pose.
public: ignition::math::Pose3d Pose() const;
/// \brief Get the principal moments of inertia (Ixx, Iyy, Izz).
/// \return The principal moments.
public: const ignition::math::Vector3d &PrincipalMoments() const;
/// \brief Get the products of inertia (Ixy, Ixz, Iyz).
/// \return The products of inertia.
public: const ignition::math::Vector3d &ProductsOfInertia() const;
/// \brief Get IXX
/// \return IXX value
public: double IXX() const;
/// \brief Get IYY
/// \return IYY value
public: double IYY() const;
/// \brief Get IZZ
/// \return IZZ value
public: double IZZ() const;
/// \brief Get IXY
/// \return IXY value
public: double IXY() const;
/// \brief Get IXZ
/// \return IXZ value
public: double IXZ() const;
/// \brief Get IYZ
/// \return IYZ value
public: double IYZ() const;
/// \brief Set IXX
/// \param[in] _v IXX value
public: void SetIXX(const double _v);
/// \brief Set IYY
/// \param[in] _v IYY value
public: void SetIYY(const double _v);
/// \brief Set IZZ
/// \param[in] _v IZZ value
public: void SetIZZ(const double _v);
/// \brief Set IXY
/// \param[in] _v IXY value
public: void SetIXY(const double _v);
/// \brief Set IXZ
/// \param[in] _v IXZ value
public: void SetIXZ(const double _v);
/// \brief Set IYZ
/// \param[in] _v IYZ value
public: void SetIYZ(const double _v);
/// \brief Rotate this mass.
/// \param[in] _rot Rotation amount.
public: void Rotate(const ignition::math::Quaterniond &_rot);
/// \brief Equal operator.
/// \param[in] _inertial Inertial to copy.
/// \return Reference to this object.
public: Inertial &operator=(const Inertial &_inertial);
/// \brief Equal operator.
/// \param[in] _inertial Ignition inertial to copy.
/// \return Reference to this object.
public: Inertial &operator=(const ignition::math::Inertiald &_inertial);
/// \brief Addition operator.
/// Assuming both CG and Moment of Inertia (MOI) are defined
/// in the same reference Link frame.
/// New CG is computed from masses and perspective offsets,
/// and both MOI contributions relocated to the new cog.
/// \param[in] _inertial Inertial to add.
/// \return The result of the addition.
public: Inertial operator+(const Inertial &_inertial) const;
/// \brief Addition equal operator.
/// \param[in] _inertial Inertial to add.
/// \return Reference to this object.
public: const Inertial &operator+=(const Inertial &_inertial);
/// \brief Update parameters from a message
/// \param[in] _msg Message to read
public: void ProcessMsg(const msgs::Inertial &_msg);
/// \brief Get the equivalent inertia from a point in local Link frame
/// If you specify MOI(this->GetPose()), you should get
/// back the Moment of Inertia (MOI) exactly as specified in the SDF.
/// If _pose is different from pose of the Inertial block, then
/// the MOI is rotated accordingly, and contributions from changes
/// in MOI location due to point mass is added to the final MOI.
/// \param[in] _pose location in Link local frame
/// \return equivalent inertia at _pose
public: ignition::math::Matrix3d MOI(
const ignition::math::Pose3d &_pose) const;
/// \brief Get equivalent Inertia values with the Link frame offset,
/// while holding the Pose of CoG constant in the world frame.
/// \param[in] _frameOffset amount to offset the Link frame by, this
/// is a transform defined in the Link frame.
/// \return Inertial parameters with the shifted frame.
public: Inertial operator()(
const ignition::math::Pose3d &_frameOffset) const;
/// \brief Get equivalent Inertia values with the Link frame offset,
/// while holding the Pose of CoG constant in the world frame.
/// \param[in] _frameOffset amount to offset the Link frame by, this
/// is a transform defined in the Link frame.
/// \return Inertial parameters with the shifted frame.
public: Inertial operator()(
const ignition::math::Vector3d &_frameOffset) const;
/// \brief Output operator.
/// \param[in] _out Output stream.
/// \param[in] _inertial Inertial object to output.
public: friend std::ostream &operator<<(std::ostream &_out,
const gazebo::physics::Inertial &_inertial)
{
_out << "Mass[" << _inertial.Mass() << "] CoG["
<< _inertial.CoG() << "]\n";
_out << "IXX[" << _inertial.PrincipalMoments().X() << "] "
<< "IYY[" << _inertial.PrincipalMoments().Y() << "] "
<< "IZZ[" << _inertial.PrincipalMoments().Z() << "]\n";
_out << "IXY[" << _inertial.ProductsOfInertia().X() << "] "
<< "IXZ[" << _inertial.ProductsOfInertia().Y() << "] "
<< "IYZ[" << _inertial.ProductsOfInertia().Z() << "]\n";
return _out;
}
/// \brief returns Moments of Inertia as a Matrix3
/// \return Moments of Inertia as a Matrix3
public: ignition::math::Matrix3d MOI() const;
/// \brief Sets Moments of Inertia (MOI) from a Matrix3
/// \param[in] _moi Moments of Inertia as a Matrix3
public: void SetMOI(const ignition::math::Matrix3d &_moi);
/// \internal
/// \brief Private data pointer.
private: std::unique_ptr<InertialPrivate> dataPtr;
};
/// \}
}
}
#endif
| 37.75089 | 80 | 0.621889 | traversaro |
14267d93874b2e1a844267e7ceff6f4bc9457a74 | 7,416 | cpp | C++ | engine/test/gtest/SparseLib/test_spmm_amx_bf16_x16_kernel.cpp | intel/neural-compressor | 16a4a12045fcb468da4d33769aff2c1a5e2ba6ba | [
"Apache-2.0"
] | 172 | 2021-09-14T18:34:17.000Z | 2022-03-30T06:49:53.000Z | engine/test/gtest/SparseLib/test_spmm_amx_bf16_x16_kernel.cpp | intel/neural-compressor | 16a4a12045fcb468da4d33769aff2c1a5e2ba6ba | [
"Apache-2.0"
] | 40 | 2021-09-14T02:26:12.000Z | 2022-03-29T08:34:04.000Z | engine/test/gtest/SparseLib/test_spmm_amx_bf16_x16_kernel.cpp | intel/neural-compressor | 16a4a12045fcb468da4d33769aff2c1a5e2ba6ba | [
"Apache-2.0"
] | 33 | 2021-09-15T07:27:25.000Z | 2022-03-25T08:30:57.000Z | // Copyright (c) 2021 Intel Corporation
//
// 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 <omp.h>
#include <exception>
#include <numeric>
#include <string>
#include <unordered_map>
#include <unordered_set>
#include <vector>
#include "gtest/gtest.h"
#include "interface.hpp"
namespace jd {
using dt = jd::data_type;
using ft = jd::format_type;
struct op_args_t {
operator_desc op_desc;
std::vector<const void*> rt_data;
};
struct test_params_t {
std::pair<op_args_t, op_args_t> args;
bool expect_to_fail;
};
void get_true_data(const operator_desc& op_desc, const std::vector<const void*>& rt_data) {
// shape configure alias
const auto& ts_descs = op_desc.tensor_descs();
const auto& wei_desc = ts_descs[0];
const auto& src_desc = ts_descs[1];
const auto& dst_desc = ts_descs[3];
int dims = wei_desc.shape().size();
int N = wei_desc.shape()[0];
int K = wei_desc.shape()[1];
int M = src_desc.shape()[1];
const auto& dst_dt = dst_desc.dtype();
auto attrs_map = op_desc.attrs();
// runtime data alias
const auto wei_data = static_cast<const bfloat16_t*>(rt_data[0]);
const auto src_data = static_cast<const bfloat16_t*>(rt_data[1]);
auto dst_data = const_cast<void*>(rt_data[3]);
auto fp_dst_data = static_cast<float*>(dst_data);
// Computing the kernel
if (dims == 2) {
for (int n = 0; n < N; ++n) {
#pragma omp parallel for
for (int m = 0; m < M; ++m) {
#pragma omp parallel for
for (int k = 0; k < K; ++k) {
fp_dst_data[n * M + m] += make_fp32(wei_data[n * K + k]) * make_fp32(src_data[k * M + m]);
}
}
}
}
}
bool check_result(const test_params_t& t) {
const auto& p = t.args.first;
const auto& q = t.args.second;
try {
const auto& op_desc = p.op_desc;
sparse_matmul_desc spmm_desc(op_desc);
sparse_matmul spmm_kern(spmm_desc);
spmm_kern.execute(p.rt_data);
} catch (const std::exception& e) {
if (t.expect_to_fail) {
return true;
} else {
return false;
}
}
if (!t.expect_to_fail) {
get_true_data(q.op_desc, q.rt_data);
auto buf1 = p.rt_data[3];
auto size1 = p.op_desc.tensor_descs()[3].size();
auto buf2 = q.rt_data[3];
auto size2 = q.op_desc.tensor_descs()[3].size();
// Should compare buffer with different addresses
EXPECT_NE(buf1, buf2);
const auto& dst_type = p.op_desc.tensor_descs()[3].dtype();
return compare_data<float>(buf1, size1, buf2, size2, 5e-3);
}
return false;
}
class SpmmAMXX16KernelTest : public testing::TestWithParam<test_params_t> {
protected:
SpmmAMXX16KernelTest() {}
virtual ~SpmmAMXX16KernelTest() {}
void SetUp() override {}
void TearDown() override {}
};
TEST_P(SpmmAMXX16KernelTest, TestPostfix) {
test_params_t t = testing::TestWithParam<test_params_t>::GetParam();
EXPECT_TRUE(check_result(t));
}
template <typename T>
void prepare_sparse_data(T* weight, dim_t N, dim_t K, dim_t n_blksize, dim_t k_blksize, float ratio) {
uint32_t seed = 9527;
for (int n = 0; n < N; ++n) {
for (int k = 0; k < K; ++k) {
weight[n * K + k] = make_bf16(rand_r(&seed) % 10 + 1);
}
}
// sparsify a_mat
for (int nb = 0; nb < N / n_blksize; ++nb) {
for (int kb = 0; kb < K / k_blksize; ++kb) {
bool fill_zero = rand_r(&seed) % 100 <= (dim_t)(ratio * 100);
if (fill_zero) {
for (int n = 0; n < n_blksize; ++n) {
for (int k = 0; k < k_blksize; ++k) {
weight[(nb * n_blksize + n) * K + kb * k_blksize + k] = make_bf16(0);
}
}
}
}
}
}
std::pair<const void*, const void*> make_data_obj(const dt& tensor_dt, dim_t rows, dim_t cols, bool is_clear = false,
bool is_sparse = false,
const std::vector<float>& ranges = {-10, 10}) {
dim_t elem_num = rows * cols;
dim_t bytes_size = elem_num * type_size[tensor_dt];
void* data_ptr = nullptr;
if (is_clear) {
// prepare dst
data_ptr = new float[elem_num];
memset(data_ptr, 0, bytes_size);
} else {
if (is_sparse) {
// prepare sparse weight
float ratio = 0.9;
data_ptr = new bfloat16_t[elem_num];
bfloat16_t* bf16_ptr = static_cast<bfloat16_t*>(data_ptr);
prepare_sparse_data<bfloat16_t>(bf16_ptr, rows, cols, 16, 1, ratio);
} else {
// prepare dense activation
data_ptr = new bfloat16_t[elem_num];
bfloat16_t* bf16_ptr = static_cast<bfloat16_t*>(data_ptr);
init_vector(bf16_ptr, elem_num, ranges[0], ranges[1]);
}
}
void* data_ptr_copy = new uint8_t[bytes_size];
memcpy(data_ptr_copy, data_ptr, bytes_size);
return std::pair<const void*, const void*>{data_ptr, data_ptr_copy};
}
std::pair<op_args_t, op_args_t> gen_case(const jd::kernel_kind ker_kind, const jd::kernel_prop ker_prop,
const jd::engine_kind eng_kind, const std::vector<tensor_desc>& ts_descs) {
std::unordered_map<std::string, std::string> op_attrs;
// Step 1: Construct runtime data
std::vector<const void*> rt_data1;
std::vector<const void*> rt_data2;
dim_t N = ts_descs[0].shape()[0];
dim_t K = ts_descs[0].shape()[1];
int tensor_num = ts_descs.size();
for (int index = 0; index < tensor_num; ++index) {
bool is_clear = (index == 2 | index == 3) ? true : false;
bool is_sparse = (index == 0) ? true : false;
dim_t rows = ts_descs[index].shape()[0];
dim_t cols = ts_descs[index].shape()[1];
auto data_pair = make_data_obj(ts_descs[index].dtype(), rows, cols, is_clear, is_sparse);
rt_data1.emplace_back(data_pair.first);
rt_data2.emplace_back(data_pair.second);
}
// Step 2: sparse data encoding
volatile bsr_data_t<bfloat16_t>* sparse_ptr = spns::reorder_to_bsr_amx<bfloat16_t, 32>(N, K, rt_data1[0]);
op_attrs["sparse_ptr"] = std::to_string(reinterpret_cast<uint64_t>(sparse_ptr));
operator_desc an_op_desc(ker_kind, ker_prop, eng_kind, ts_descs, op_attrs);
// Step 3: op_args_t testcase pair
op_args_t op_args = {an_op_desc, rt_data1};
op_args_t op_args_copy = {an_op_desc, rt_data2};
return {op_args, op_args_copy};
}
static auto case_func = []() {
std::vector<test_params_t> cases;
// Config
tensor_desc wei_desc;
tensor_desc src_desc;
tensor_desc bia_desc;
tensor_desc dst_desc;
// case: sparse: bf16xbf16=f32, weight(N, K) * activation(K, M)
// = dst(N, M)
wei_desc = {{64, 64}, dt::bf16, ft::bsr};
src_desc = {{64, 64}, dt::bf16, ft::ab};
bia_desc = {{64, 1}, dt::fp32, ft::ab};
dst_desc = {{64, 64}, dt::fp32, ft::ab};
cases.push_back({gen_case(kernel_kind::sparse_matmul, kernel_prop::forward_inference, engine_kind::cpu,
{wei_desc, src_desc, bia_desc, dst_desc})});
return ::testing::ValuesIn(cases);
};
INSTANTIATE_TEST_SUITE_P(Prefix, SpmmAMXX16KernelTest, case_func());
} // namespace jd
| 33.255605 | 117 | 0.649272 | intel |
142a715eb42fa83babbd86b50d9936cb60b046da | 70 | cpp | C++ | Autoplay/Source/Autoplay/Private/Autoplay.cpp | realityreflection/Autoplay | e81555444f821d44ce986c4e5e450dabb0930af0 | [
"MIT"
] | 6 | 2017-05-22T02:24:50.000Z | 2021-11-08T07:22:52.000Z | Example/Plugins/Autoplay/Source/Autoplay/Private/Autoplay.cpp | realityreflection/Autoplay | e81555444f821d44ce986c4e5e450dabb0930af0 | [
"MIT"
] | null | null | null | Example/Plugins/Autoplay/Source/Autoplay/Private/Autoplay.cpp | realityreflection/Autoplay | e81555444f821d44ce986c4e5e450dabb0930af0 | [
"MIT"
] | 4 | 2018-04-10T11:06:59.000Z | 2020-07-05T14:21:56.000Z | #include "Autoplay.h"
IMPLEMENT_MODULE(AutoplayModuleImpl, Autoplay); | 23.333333 | 47 | 0.828571 | realityreflection |
289fd07dc3fd76909857223799c82d140ec15d31 | 5,667 | cc | C++ | modules/canbus/vehicle/lexus/protocol/lat_lon_heading_rpt_40e.cc | seeclong/apollo | 99c8afb5ebcae2a3c9359a156a957ff03944b27b | [
"Apache-2.0"
] | 22,688 | 2017-07-04T23:17:19.000Z | 2022-03-31T18:56:48.000Z | modules/canbus/vehicle/lexus/protocol/lat_lon_heading_rpt_40e.cc | Songjiarui3313/apollo | df9113ae656e28e5374db32529d68e59455058a0 | [
"Apache-2.0"
] | 4,804 | 2017-07-04T22:30:12.000Z | 2022-03-31T12:58:21.000Z | modules/canbus/vehicle/lexus/protocol/lat_lon_heading_rpt_40e.cc | Songjiarui3313/apollo | df9113ae656e28e5374db32529d68e59455058a0 | [
"Apache-2.0"
] | 9,985 | 2017-07-04T22:01:17.000Z | 2022-03-31T14:18:16.000Z | /******************************************************************************
* Copyright 2018 The Apollo 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 "modules/canbus/vehicle/lexus/protocol/lat_lon_heading_rpt_40e.h"
#include "glog/logging.h"
#include "modules/drivers/canbus/common/byte.h"
#include "modules/drivers/canbus/common/canbus_consts.h"
namespace apollo {
namespace canbus {
namespace lexus {
using ::apollo::drivers::canbus::Byte;
Latlonheadingrpt40e::Latlonheadingrpt40e() {}
const int32_t Latlonheadingrpt40e::ID = 0x40E;
void Latlonheadingrpt40e::Parse(const std::uint8_t* bytes, int32_t length,
ChassisDetail* chassis) const {
chassis->mutable_lexus()->mutable_lat_lon_heading_rpt_40e()->set_heading(
heading(bytes, length));
chassis->mutable_lexus()
->mutable_lat_lon_heading_rpt_40e()
->set_longitude_seconds(longitude_seconds(bytes, length));
chassis->mutable_lexus()
->mutable_lat_lon_heading_rpt_40e()
->set_longitude_minutes(longitude_minutes(bytes, length));
chassis->mutable_lexus()
->mutable_lat_lon_heading_rpt_40e()
->set_longitude_degrees(longitude_degrees(bytes, length));
chassis->mutable_lexus()
->mutable_lat_lon_heading_rpt_40e()
->set_latitude_seconds(latitude_seconds(bytes, length));
chassis->mutable_lexus()
->mutable_lat_lon_heading_rpt_40e()
->set_latitude_minutes(latitude_minutes(bytes, length));
chassis->mutable_lexus()
->mutable_lat_lon_heading_rpt_40e()
->set_latitude_degrees(latitude_degrees(bytes, length));
}
// config detail: {'name': 'heading', 'offset': 0.0, 'precision': 0.01, 'len':
// 16, 'is_signed_var': True, 'physical_range': '[-327.68|327.67]', 'bit': 55,
// 'type': 'double', 'order': 'motorola', 'physical_unit': 'deg'}
double Latlonheadingrpt40e::heading(const std::uint8_t* bytes,
int32_t length) const {
Byte t0(bytes + 6);
int32_t x = t0.get_byte(0, 8);
Byte t1(bytes + 7);
int32_t t = t1.get_byte(0, 8);
x <<= 8;
x |= t;
x <<= 16;
x >>= 16;
double ret = x * 0.010000;
return ret;
}
// config detail: {'name': 'longitude_seconds', 'offset': 0.0, 'precision': 1.0,
// 'len': 8, 'is_signed_var': True, 'physical_range': '[-128|127]', 'bit': 47,
// 'type': 'int', 'order': 'motorola', 'physical_unit': 'sec'}
int Latlonheadingrpt40e::longitude_seconds(const std::uint8_t* bytes,
int32_t length) const {
Byte t0(bytes + 5);
int32_t x = t0.get_byte(0, 8);
x <<= 24;
x >>= 24;
int ret = x;
return ret;
}
// config detail: {'name': 'longitude_minutes', 'offset': 0.0, 'precision': 1.0,
// 'len': 8, 'is_signed_var': True, 'physical_range': '[-128|127]', 'bit': 39,
// 'type': 'int', 'order': 'motorola', 'physical_unit': 'min'}
int Latlonheadingrpt40e::longitude_minutes(const std::uint8_t* bytes,
int32_t length) const {
Byte t0(bytes + 4);
int32_t x = t0.get_byte(0, 8);
x <<= 24;
x >>= 24;
int ret = x;
return ret;
}
// config detail: {'name': 'longitude_degrees', 'offset': 0.0, 'precision': 1.0,
// 'len': 8, 'is_signed_var': True, 'physical_range': '[-128|127]', 'bit': 31,
// 'type': 'int', 'order': 'motorola', 'physical_unit': 'deg'}
int Latlonheadingrpt40e::longitude_degrees(const std::uint8_t* bytes,
int32_t length) const {
Byte t0(bytes + 3);
int32_t x = t0.get_byte(0, 8);
x <<= 24;
x >>= 24;
int ret = x;
return ret;
}
// config detail: {'name': 'latitude_seconds', 'offset': 0.0, 'precision': 1.0,
// 'len': 8, 'is_signed_var': True, 'physical_range': '[-128|127]', 'bit': 23,
// 'type': 'int', 'order': 'motorola', 'physical_unit': 'sec'}
int Latlonheadingrpt40e::latitude_seconds(const std::uint8_t* bytes,
int32_t length) const {
Byte t0(bytes + 2);
int32_t x = t0.get_byte(0, 8);
x <<= 24;
x >>= 24;
int ret = x;
return ret;
}
// config detail: {'name': 'latitude_minutes', 'offset': 0.0, 'precision': 1.0,
// 'len': 8, 'is_signed_var': True, 'physical_range': '[-128|127]', 'bit': 15,
// 'type': 'int', 'order': 'motorola', 'physical_unit': 'min'}
int Latlonheadingrpt40e::latitude_minutes(const std::uint8_t* bytes,
int32_t length) const {
Byte t0(bytes + 1);
int32_t x = t0.get_byte(0, 8);
x <<= 24;
x >>= 24;
int ret = x;
return ret;
}
// config detail: {'name': 'latitude_degrees', 'offset': 0.0, 'precision': 1.0,
// 'len': 8, 'is_signed_var': True, 'physical_range': '[-128|127]', 'bit': 7,
// 'type': 'int', 'order': 'motorola', 'physical_unit': 'deg'}
int Latlonheadingrpt40e::latitude_degrees(const std::uint8_t* bytes,
int32_t length) const {
Byte t0(bytes + 0);
int32_t x = t0.get_byte(0, 8);
x <<= 24;
x >>= 24;
int ret = x;
return ret;
}
} // namespace lexus
} // namespace canbus
} // namespace apollo
| 33.532544 | 80 | 0.611964 | seeclong |
28a2f38bd00c1ccd4103718bfd98e16013240a4c | 3,812 | cpp | C++ | src/nnfusion/core/kernels/cuda_gpu/kernels/layer_norm.cpp | nox-410/nnfusion | 0777e297299c4e7a5071dc2ee97b87adcd22840e | [
"MIT"
] | 639 | 2020-09-05T10:00:59.000Z | 2022-03-30T08:42:39.000Z | src/nnfusion/core/kernels/cuda_gpu/kernels/layer_norm.cpp | QPC-database/nnfusion | 99ada47c50f355ca278001f11bc752d1c7abcee2 | [
"MIT"
] | 252 | 2020-09-09T05:35:36.000Z | 2022-03-29T04:58:41.000Z | src/nnfusion/core/kernels/cuda_gpu/kernels/layer_norm.cpp | QPC-database/nnfusion | 99ada47c50f355ca278001f11bc752d1c7abcee2 | [
"MIT"
] | 104 | 2020-09-05T10:01:08.000Z | 2022-03-23T10:59:13.000Z | // Copyright (c) Microsoft Corporation.
// Licensed under the MIT License.
// #include "../cuda_cudnn.hpp"
#include "../cuda_cudnn.hpp"
#include "../cuda_emitter.hpp"
#include "../cuda_langunit.hpp"
#include "nnfusion/core/operators/generic_op/generic_op.hpp"
namespace nnfusion
{
namespace kernels
{
namespace cuda
{
class LayerNorm : public CudaLibEmitter
{
shared_ptr<nnfusion::op::GenericOp> generic_op;
public:
LayerNorm(shared_ptr<KernelContext> ctx)
: CudaLibEmitter(ctx)
, generic_op(
static_pointer_cast<nnfusion::op::GenericOp>(ctx->gnode->get_op_ptr()))
{
GENERIC_OP_LOGGING();
}
LanguageUnit_p emit_function_body() override
{
GENERIC_OP_LOGGING();
const nnfusion::Shape& input_shape = m_context->inputs[0]->get_shape();
auto& cfg = generic_op->localOpConfig.getRoot();
float eps = cfg["epsilon"];
int axis = cfg["axis"];
axis += axis < 0 ? input_shape.size() : 0;
size_t n1 = 1, n2 = 1;
for (auto i = 0; i < axis; i++)
{
n1 *= input_shape[i];
}
for (auto i = axis; i < input_shape.size(); i++)
{
n2 *= input_shape[i];
}
nnfusion::element::Type dtype = m_context->inputs[0]->get_element_type();
LanguageUnit_p _lu(new LanguageUnit(get_function_name()));
auto& lu = *_lu;
// lu << "HostApplyLayerNorm(output0,"
// << " output1,"
// << " output2,"
// << " input0," << n1 << "," << n2 << "," << eps << ","
// << " input1,"
// << " input2);\n";
auto code = nnfusion::op::create_code_from_template(
R"(
HostApplyLayerNorm<@dtype@>(
output0, output1, output2, input0, @n1@, @n2@, @expression1@@eps@@expression2@, input1, input2);
)",
{{"n1", n1},
{"n2", n2},
{"dtype", (dtype == element::f16) ? "half" : "float"},
{"expression1", (dtype == element::f16) ? "__float2half_rn(" : ""},
{"expression2", (dtype == element::f16) ? ")" : ""},
{"eps", eps}});
lu << code << "\n";
return _lu;
}
LanguageUnit_p emit_dependency() override
{
GENERIC_OP_LOGGING();
LanguageUnit_p _lu(new LanguageUnit(get_function_name() + "_dep"));
_lu->require(header::cuda);
_lu->require(declaration::cuda_layer_norm);
declaration::cuda_layer_norm->require(declaration::math_Rsqrt);
declaration::cuda_layer_norm->require(declaration::warp);
return _lu;
}
};
} // namespace cuda
} // namespace kernels
} // namespace nnfusion
// Register kernel emitter
using namespace nnfusion;
using namespace nnfusion::kernels;
REGISTER_KERNEL_EMITTER("LayerNorm", // op_name
Device(CUDA_GPU).TypeConstraint(element::f32).Tag("cudalib"), // attrs
cuda::LayerNorm) // constructor
| 38.12 | 100 | 0.444386 | nox-410 |
28a4931a93ce452e7bccfa0b8200fc8589aae136 | 3,016 | cpp | C++ | src/GTKClient.cpp | Ladislus/svg-project-l3 | e1932dd175b59c81af39b8f49c4fb28f963e9c4f | [
"MIT"
] | null | null | null | src/GTKClient.cpp | Ladislus/svg-project-l3 | e1932dd175b59c81af39b8f49c4fb28f963e9c4f | [
"MIT"
] | null | null | null | src/GTKClient.cpp | Ladislus/svg-project-l3 | e1932dd175b59c81af39b8f49c4fb28f963e9c4f | [
"MIT"
] | null | null | null | //
// Created by o2173194 on 04/03/20.
//
#include <gtk/gtk.h>
#include <cctype>
static void enter_callback( GtkWidget *widget, GtkWidget *entry )
{
const gchar *entry_text;
entry_text = gtk_entry_get_text (GTK_ENTRY (entry));
printf ("Entry contents: %s\n", entry_text);
}
void insert_text_event(GtkEditable *editable, const gchar *text, gint length, gint *position, gpointer data)
{
int i;
for (i = 0; i < length; i++) {
if (!isdigit(text[i])) {
g_signal_stop_emission_by_name(G_OBJECT(editable), "insert-text");
return;
}
}
}
/*
* Initialize GTK Window and all widgets
* */
int main(int argc, char *argv[])
{
/*Initialization of widgets*/
GtkWidget *window, *button, *input1, *input2, *vbox, *hbox;
/*Init*/
gtk_init(&argc, &argv);
/* Creation of a new window */
window = gtk_window_new(GTK_WINDOW_TOPLEVEL);
vbox = gtk_vbox_new(FALSE, 0);
gtk_container_add (GTK_CONTAINER (window), vbox);
gtk_widget_show (vbox);
input1 = gtk_entry_new();
gtk_entry_set_max_length (GTK_ENTRY (input1), 3);
g_signal_connect (input1, "activate",
G_CALLBACK (enter_callback),
input1);
g_signal_connect(G_OBJECT(input1), "insert_text",
G_CALLBACK(insert_text_event),
NULL);
gtk_box_pack_start (GTK_BOX (vbox), input1, TRUE, TRUE, 0);
gtk_widget_show (input1);
input2 = gtk_entry_new();
gtk_entry_set_max_length (GTK_ENTRY (input2), 3);
g_signal_connect (input2, "activate",
G_CALLBACK (enter_callback),
input2);
g_signal_connect(G_OBJECT(input2), "insert_text",
G_CALLBACK(insert_text_event),
NULL);
gtk_box_pack_start (GTK_BOX (vbox), input2, TRUE, TRUE, 0);
gtk_widget_show (input2);
hbox = gtk_hbox_new(FALSE, 0);
gtk_container_add (GTK_CONTAINER (vbox), hbox);
gtk_widget_show (hbox);
button = gtk_button_new_with_label ("Submit to server");
g_signal_connect(button, "clicked",
G_CALLBACK (enter_callback),
window);
gtk_box_pack_start (GTK_BOX (vbox), button, TRUE, TRUE, 0);
gtk_widget_show (button);
// /* This function will WRITE all the modifications of the SVG in the XMLFile*/
// svg_data.SaveFile("../Resources/Image Samples/atom.svg");
/*
* Connecting all the events to the GTK window
* */
g_signal_connect(window, "destroy",
G_CALLBACK(gtk_main_quit), NULL);
/* Configuration of the window */
gtk_container_set_border_width (GTK_CONTAINER (window), 10);
gtk_window_set_position(GTK_WINDOW(window), GTK_WIN_POS_CENTER);
gtk_window_set_default_size(GTK_WINDOW(window), 275, 275);
gtk_window_set_title(GTK_WINDOW(window), "Client SVG");
/*
* This will show all the widgets in the window
* */
gtk_widget_show_all(window);
gtk_main();
return 0;
}
| 30.464646 | 108 | 0.634947 | Ladislus |
28a73e8d0c6a8676d78e0aff4af2e7f5a6281d84 | 53,394 | cpp | C++ | wxWidgets-2.9.1/src/richtext/richtextliststylepage.cpp | gamekit-developers/gamekit | 74c896af5826ebe8fb72f2911015738f38ab7bb2 | [
"Zlib",
"MIT"
] | 241 | 2015-01-04T00:36:58.000Z | 2022-01-06T19:19:23.000Z | wxWidgets-2.9.1/src/richtext/richtextliststylepage.cpp | gamekit-developers/gamekit | 74c896af5826ebe8fb72f2911015738f38ab7bb2 | [
"Zlib",
"MIT"
] | 10 | 2015-07-10T18:27:17.000Z | 2019-06-26T20:59:59.000Z | wxWidgets-2.9.1/src/richtext/richtextliststylepage.cpp | gamekit-developers/gamekit | 74c896af5826ebe8fb72f2911015738f38ab7bb2 | [
"Zlib",
"MIT"
] | 82 | 2015-01-25T18:02:35.000Z | 2022-03-05T12:28:17.000Z | /////////////////////////////////////////////////////////////////////////////
// Name: src/richtext/richtextliststylepage.cpp
// Purpose:
// Author: Julian Smart
// Modified by:
// Created: 10/18/2006 11:36:37 AM
// RCS-ID: $Id$
// Copyright: (c) Julian Smart
// Licence: wxWindows licence
/////////////////////////////////////////////////////////////////////////////
#include "wx/richtext/richtextliststylepage.h"
////@begin XPM images
////@end XPM images
/*!
* wxRichTextListStylePage type definition
*/
IMPLEMENT_DYNAMIC_CLASS( wxRichTextListStylePage, wxPanel )
/*!
* wxRichTextListStylePage event table definition
*/
BEGIN_EVENT_TABLE( wxRichTextListStylePage, wxPanel )
////@begin wxRichTextListStylePage event table entries
EVT_SPINCTRL( ID_RICHTEXTLISTSTYLEPAGE_LEVEL, wxRichTextListStylePage::OnLevelUpdated )
EVT_SPIN_UP( ID_RICHTEXTLISTSTYLEPAGE_LEVEL, wxRichTextListStylePage::OnLevelUp )
EVT_SPIN_DOWN( ID_RICHTEXTLISTSTYLEPAGE_LEVEL, wxRichTextListStylePage::OnLevelDown )
EVT_TEXT( ID_RICHTEXTLISTSTYLEPAGE_LEVEL, wxRichTextListStylePage::OnLevelTextUpdated )
EVT_UPDATE_UI( ID_RICHTEXTLISTSTYLEPAGE_LEVEL, wxRichTextListStylePage::OnLevelUIUpdate )
EVT_BUTTON( ID_RICHTEXTLISTSTYLEPAGE_CHOOSE_FONT, wxRichTextListStylePage::OnChooseFontClick )
EVT_LISTBOX( ID_RICHTEXTLISTSTYLEPAGE_STYLELISTBOX, wxRichTextListStylePage::OnStylelistboxSelected )
EVT_CHECKBOX( ID_RICHTEXTLISTSTYLEPAGE_PERIODCTRL, wxRichTextListStylePage::OnPeriodctrlClick )
EVT_UPDATE_UI( ID_RICHTEXTLISTSTYLEPAGE_PERIODCTRL, wxRichTextListStylePage::OnPeriodctrlUpdate )
EVT_CHECKBOX( ID_RICHTEXTLISTSTYLEPAGE_PARENTHESESCTRL, wxRichTextListStylePage::OnParenthesesctrlClick )
EVT_UPDATE_UI( ID_RICHTEXTLISTSTYLEPAGE_PARENTHESESCTRL, wxRichTextListStylePage::OnParenthesesctrlUpdate )
EVT_CHECKBOX( ID_RICHTEXTLISTSTYLEPAGE_RIGHTPARENTHESISCTRL, wxRichTextListStylePage::OnRightParenthesisCtrlClick )
EVT_UPDATE_UI( ID_RICHTEXTLISTSTYLEPAGE_RIGHTPARENTHESISCTRL, wxRichTextListStylePage::OnRightParenthesisCtrlUpdate )
EVT_COMBOBOX( ID_RICHTEXTLISTSTYLEPAGE_BULLETALIGNMENTCTRL, wxRichTextListStylePage::OnBulletAlignmentCtrlSelected )
EVT_UPDATE_UI( ID_RICHTEXTLISTSTYLEPAGE_SYMBOLSTATIC, wxRichTextListStylePage::OnSymbolstaticUpdate )
EVT_COMBOBOX( ID_RICHTEXTLISTSTYLEPAGE_SYMBOLCTRL, wxRichTextListStylePage::OnSymbolctrlSelected )
EVT_TEXT( ID_RICHTEXTLISTSTYLEPAGE_SYMBOLCTRL, wxRichTextListStylePage::OnSymbolctrlUpdated )
EVT_UPDATE_UI( ID_RICHTEXTLISTSTYLEPAGE_SYMBOLCTRL, wxRichTextListStylePage::OnSymbolctrlUIUpdate )
EVT_BUTTON( ID_RICHTEXTLISTSTYLEPAGE_CHOOSE_SYMBOL, wxRichTextListStylePage::OnChooseSymbolClick )
EVT_UPDATE_UI( ID_RICHTEXTLISTSTYLEPAGE_CHOOSE_SYMBOL, wxRichTextListStylePage::OnChooseSymbolUpdate )
EVT_COMBOBOX( ID_RICHTEXTLISTSTYLEPAGE_SYMBOLFONTCTRL, wxRichTextListStylePage::OnSymbolfontctrlSelected )
EVT_TEXT( ID_RICHTEXTLISTSTYLEPAGE_SYMBOLFONTCTRL, wxRichTextListStylePage::OnSymbolfontctrlUpdated )
EVT_UPDATE_UI( ID_RICHTEXTLISTSTYLEPAGE_SYMBOLFONTCTRL, wxRichTextListStylePage::OnSymbolfontctrlUIUpdate )
EVT_UPDATE_UI( ID_RICHTEXTLISTSTYLEPAGE_NAMESTATIC, wxRichTextListStylePage::OnNamestaticUpdate )
EVT_COMBOBOX( ID_RICHTEXTLISTSTYLEPAGE_NAMECTRL, wxRichTextListStylePage::OnNamectrlSelected )
EVT_TEXT( ID_RICHTEXTLISTSTYLEPAGE_NAMECTRL, wxRichTextListStylePage::OnNamectrlUpdated )
EVT_UPDATE_UI( ID_RICHTEXTLISTSTYLEPAGE_NAMECTRL, wxRichTextListStylePage::OnNamectrlUIUpdate )
EVT_RADIOBUTTON( ID_RICHTEXTLISTSTYLEPAGE_ALIGNLEFT, wxRichTextListStylePage::OnRichtextliststylepageAlignleftSelected )
EVT_RADIOBUTTON( ID_RICHTEXTLISTSTYLEPAGE_ALIGNRIGHT, wxRichTextListStylePage::OnRichtextliststylepageAlignrightSelected )
EVT_RADIOBUTTON( ID_RICHTEXTLISTSTYLEPAGE_JUSTIFIED, wxRichTextListStylePage::OnRichtextliststylepageJustifiedSelected )
EVT_RADIOBUTTON( ID_RICHTEXTLISTSTYLEPAGE_CENTERED, wxRichTextListStylePage::OnRichtextliststylepageCenteredSelected )
EVT_RADIOBUTTON( ID_RICHTEXTLISTSTYLEPAGE_ALIGNINDETERMINATE, wxRichTextListStylePage::OnRichtextliststylepageAlignindeterminateSelected )
EVT_TEXT( ID_RICHTEXTLISTSTYLEPAGE_INDENTLEFT, wxRichTextListStylePage::OnIndentLeftUpdated )
EVT_TEXT( ID_RICHTEXTLISTSTYLEPAGE_INDENTFIRSTLINE, wxRichTextListStylePage::OnIndentFirstLineUpdated )
EVT_TEXT( ID_RICHTEXTLISTSTYLEPAGE_INDENTRIGHT, wxRichTextListStylePage::OnIndentRightUpdated )
EVT_TEXT( ID_RICHTEXTLISTSTYLEPAGE_SPACINGBEFORE, wxRichTextListStylePage::OnSpacingBeforeUpdated )
EVT_TEXT( ID_RICHTEXTLISTSTYLEPAGE_SPACINGAFTER, wxRichTextListStylePage::OnSpacingAfterUpdated )
EVT_COMBOBOX( ID_RICHTEXTLISTSTYLEPAGE_LINESPACING, wxRichTextListStylePage::OnLineSpacingSelected )
////@end wxRichTextListStylePage event table entries
END_EVENT_TABLE()
/*!
* wxRichTextListStylePage constructors
*/
wxRichTextListStylePage::wxRichTextListStylePage( )
{
Init();
}
wxRichTextListStylePage::wxRichTextListStylePage( wxWindow* parent, wxWindowID id, const wxPoint& pos, const wxSize& size, long style )
{
Init();
Create(parent, id, pos, size, style);
}
/*!
* wxRichTextListStylePage creator
*/
bool wxRichTextListStylePage::Create( wxWindow* parent, wxWindowID id, const wxPoint& pos, const wxSize& size, long style )
{
////@begin wxRichTextListStylePage creation
wxPanel::Create( parent, id, pos, size, style );
CreateControls();
if (GetSizer())
{
GetSizer()->SetSizeHints(this);
}
Centre();
////@end wxRichTextListStylePage creation
return true;
}
/*!
* Member initialisation
*/
void wxRichTextListStylePage::Init()
{
m_dontUpdate = false;
m_currentLevel = 1;
////@begin wxRichTextListStylePage member initialisation
m_levelCtrl = NULL;
m_styleListBox = NULL;
m_periodCtrl = NULL;
m_parenthesesCtrl = NULL;
m_rightParenthesisCtrl = NULL;
m_bulletAlignmentCtrl = NULL;
m_symbolCtrl = NULL;
m_symbolFontCtrl = NULL;
m_bulletNameCtrl = NULL;
m_alignmentLeft = NULL;
m_alignmentRight = NULL;
m_alignmentJustified = NULL;
m_alignmentCentred = NULL;
m_alignmentIndeterminate = NULL;
m_indentLeft = NULL;
m_indentLeftFirst = NULL;
m_indentRight = NULL;
m_spacingBefore = NULL;
m_spacingAfter = NULL;
m_spacingLine = NULL;
m_previewCtrl = NULL;
////@end wxRichTextListStylePage member initialisation
}
/*!
* Control creation for wxRichTextListStylePage
*/
void wxRichTextListStylePage::CreateControls()
{
////@begin wxRichTextListStylePage content construction
wxRichTextListStylePage* itemPanel1 = this;
wxBoxSizer* itemBoxSizer2 = new wxBoxSizer(wxVERTICAL);
itemPanel1->SetSizer(itemBoxSizer2);
wxBoxSizer* itemBoxSizer3 = new wxBoxSizer(wxVERTICAL);
itemBoxSizer2->Add(itemBoxSizer3, 1, wxGROW|wxALL, 5);
wxBoxSizer* itemBoxSizer4 = new wxBoxSizer(wxHORIZONTAL);
itemBoxSizer3->Add(itemBoxSizer4, 0, wxALIGN_CENTER_HORIZONTAL, 5);
wxStaticText* itemStaticText5 = new wxStaticText( itemPanel1, wxID_STATIC, _("&List level:"), wxDefaultPosition, wxDefaultSize, 0 );
itemBoxSizer4->Add(itemStaticText5, 0, wxALIGN_CENTER_VERTICAL|wxALL, 5);
m_levelCtrl = new wxSpinCtrl( itemPanel1, ID_RICHTEXTLISTSTYLEPAGE_LEVEL, wxT("1"), wxDefaultPosition, wxSize(60, -1), wxSP_ARROW_KEYS, 1, 10, 1 );
m_levelCtrl->SetHelpText(_("Selects the list level to edit."));
if (wxRichTextListStylePage::ShowToolTips())
m_levelCtrl->SetToolTip(_("Selects the list level to edit."));
itemBoxSizer4->Add(m_levelCtrl, 0, wxALIGN_CENTER_VERTICAL|wxALL, 5);
itemBoxSizer4->Add(5, 5, 0, wxALIGN_CENTER_VERTICAL|wxALL, 5);
wxButton* itemButton8 = new wxButton( itemPanel1, ID_RICHTEXTLISTSTYLEPAGE_CHOOSE_FONT, _("&Font for Level..."), wxDefaultPosition, wxDefaultSize, 0 );
itemButton8->SetHelpText(_("Click to choose the font for this level."));
if (wxRichTextListStylePage::ShowToolTips())
itemButton8->SetToolTip(_("Click to choose the font for this level."));
itemBoxSizer4->Add(itemButton8, 0, wxALIGN_CENTER_VERTICAL|wxALL, 5);
wxNotebook* itemNotebook9 = new wxNotebook( itemPanel1, ID_RICHTEXTLISTSTYLEPAGE_NOTEBOOK, wxDefaultPosition, wxDefaultSize, wxNB_DEFAULT|wxNB_TOP );
wxPanel* itemPanel10 = new wxPanel( itemNotebook9, ID_RICHTEXTLISTSTYLEPAGE_BULLETS, wxDefaultPosition, wxDefaultSize, wxNO_BORDER|wxTAB_TRAVERSAL );
wxBoxSizer* itemBoxSizer11 = new wxBoxSizer(wxVERTICAL);
itemPanel10->SetSizer(itemBoxSizer11);
wxBoxSizer* itemBoxSizer12 = new wxBoxSizer(wxHORIZONTAL);
itemBoxSizer11->Add(itemBoxSizer12, 1, wxGROW, 5);
wxBoxSizer* itemBoxSizer13 = new wxBoxSizer(wxVERTICAL);
itemBoxSizer12->Add(itemBoxSizer13, 0, wxGROW, 5);
wxStaticText* itemStaticText14 = new wxStaticText( itemPanel10, wxID_STATIC, _("&Bullet style:"), wxDefaultPosition, wxDefaultSize, 0 );
itemBoxSizer13->Add(itemStaticText14, 0, wxALIGN_LEFT|wxLEFT|wxRIGHT|wxTOP, 5);
wxArrayString m_styleListBoxStrings;
m_styleListBox = new wxListBox( itemPanel10, ID_RICHTEXTLISTSTYLEPAGE_STYLELISTBOX, wxDefaultPosition, wxSize(-1, 140), m_styleListBoxStrings, wxLB_SINGLE );
m_styleListBox->SetHelpText(_("The available bullet styles."));
if (wxRichTextListStylePage::ShowToolTips())
m_styleListBox->SetToolTip(_("The available bullet styles."));
itemBoxSizer13->Add(m_styleListBox, 1, wxGROW|wxALL, 5);
wxBoxSizer* itemBoxSizer16 = new wxBoxSizer(wxHORIZONTAL);
itemBoxSizer13->Add(itemBoxSizer16, 0, wxGROW, 5);
m_periodCtrl = new wxCheckBox( itemPanel10, ID_RICHTEXTLISTSTYLEPAGE_PERIODCTRL, _("Peri&od"), wxDefaultPosition, wxDefaultSize, 0 );
m_periodCtrl->SetValue(false);
m_periodCtrl->SetHelpText(_("Check to add a period after the bullet."));
if (wxRichTextListStylePage::ShowToolTips())
m_periodCtrl->SetToolTip(_("Check to add a period after the bullet."));
itemBoxSizer16->Add(m_periodCtrl, 0, wxALIGN_CENTER_VERTICAL|wxALL, 5);
m_parenthesesCtrl = new wxCheckBox( itemPanel10, ID_RICHTEXTLISTSTYLEPAGE_PARENTHESESCTRL, _("(*)"), wxDefaultPosition, wxDefaultSize, 0 );
m_parenthesesCtrl->SetValue(false);
m_parenthesesCtrl->SetHelpText(_("Check to enclose the bullet in parentheses."));
if (wxRichTextListStylePage::ShowToolTips())
m_parenthesesCtrl->SetToolTip(_("Check to enclose the bullet in parentheses."));
itemBoxSizer16->Add(m_parenthesesCtrl, 0, wxALIGN_CENTER_VERTICAL|wxALL, 5);
m_rightParenthesisCtrl = new wxCheckBox( itemPanel10, ID_RICHTEXTLISTSTYLEPAGE_RIGHTPARENTHESISCTRL, _("*)"), wxDefaultPosition, wxDefaultSize, 0 );
m_rightParenthesisCtrl->SetValue(false);
m_rightParenthesisCtrl->SetHelpText(_("Check to add a right parenthesis."));
if (wxRichTextListStylePage::ShowToolTips())
m_rightParenthesisCtrl->SetToolTip(_("Check to add a right parenthesis."));
itemBoxSizer16->Add(m_rightParenthesisCtrl, 0, wxALIGN_CENTER_VERTICAL|wxALL, 5);
itemBoxSizer13->Add(2, 1, 0, wxALIGN_CENTER_HORIZONTAL, 5);
wxStaticText* itemStaticText21 = new wxStaticText( itemPanel10, wxID_STATIC, _("Bullet &Alignment:"), wxDefaultPosition, wxDefaultSize, 0 );
itemBoxSizer13->Add(itemStaticText21, 0, wxALIGN_LEFT|wxLEFT|wxRIGHT|wxTOP, 5);
wxArrayString m_bulletAlignmentCtrlStrings;
m_bulletAlignmentCtrlStrings.Add(_("Left"));
m_bulletAlignmentCtrlStrings.Add(_("Centre"));
m_bulletAlignmentCtrlStrings.Add(_("Right"));
m_bulletAlignmentCtrl = new wxComboBox( itemPanel10, ID_RICHTEXTLISTSTYLEPAGE_BULLETALIGNMENTCTRL, _("Left"), wxDefaultPosition, wxSize(60, -1), m_bulletAlignmentCtrlStrings, wxCB_READONLY );
m_bulletAlignmentCtrl->SetStringSelection(_("Left"));
m_bulletAlignmentCtrl->SetHelpText(_("The bullet character."));
if (wxRichTextListStylePage::ShowToolTips())
m_bulletAlignmentCtrl->SetToolTip(_("The bullet character."));
itemBoxSizer13->Add(m_bulletAlignmentCtrl, 0, wxGROW|wxALL|wxFIXED_MINSIZE, 5);
itemBoxSizer12->Add(2, 1, 1, wxALIGN_CENTER_VERTICAL|wxTOP|wxBOTTOM, 5);
wxStaticLine* itemStaticLine24 = new wxStaticLine( itemPanel10, wxID_STATIC, wxDefaultPosition, wxDefaultSize, wxLI_VERTICAL );
itemBoxSizer12->Add(itemStaticLine24, 0, wxGROW|wxALL, 5);
itemBoxSizer12->Add(2, 1, 1, wxALIGN_CENTER_VERTICAL|wxTOP|wxBOTTOM, 5);
wxBoxSizer* itemBoxSizer26 = new wxBoxSizer(wxVERTICAL);
itemBoxSizer12->Add(itemBoxSizer26, 0, wxGROW, 5);
wxStaticText* itemStaticText27 = new wxStaticText( itemPanel10, ID_RICHTEXTLISTSTYLEPAGE_SYMBOLSTATIC, _("&Symbol:"), wxDefaultPosition, wxDefaultSize, 0 );
itemBoxSizer26->Add(itemStaticText27, 0, wxALIGN_LEFT|wxLEFT|wxRIGHT|wxTOP, 5);
wxBoxSizer* itemBoxSizer28 = new wxBoxSizer(wxHORIZONTAL);
itemBoxSizer26->Add(itemBoxSizer28, 0, wxGROW, 5);
wxArrayString m_symbolCtrlStrings;
m_symbolCtrl = new wxComboBox( itemPanel10, ID_RICHTEXTLISTSTYLEPAGE_SYMBOLCTRL, wxT(""), wxDefaultPosition, wxSize(60, -1), m_symbolCtrlStrings, wxCB_DROPDOWN );
m_symbolCtrl->SetHelpText(_("The bullet character."));
if (wxRichTextListStylePage::ShowToolTips())
m_symbolCtrl->SetToolTip(_("The bullet character."));
itemBoxSizer28->Add(m_symbolCtrl, 0, wxALIGN_CENTER_VERTICAL|wxALL|wxFIXED_MINSIZE, 5);
wxButton* itemButton30 = new wxButton( itemPanel10, ID_RICHTEXTLISTSTYLEPAGE_CHOOSE_SYMBOL, _("Ch&oose..."), wxDefaultPosition, wxDefaultSize, 0 );
itemButton30->SetHelpText(_("Click to browse for a symbol."));
if (wxRichTextListStylePage::ShowToolTips())
itemButton30->SetToolTip(_("Click to browse for a symbol."));
itemBoxSizer28->Add(itemButton30, 0, wxALIGN_CENTER_VERTICAL|wxALL, 5);
itemBoxSizer26->Add(5, 5, 0, wxALIGN_CENTER_HORIZONTAL, 5);
wxStaticText* itemStaticText32 = new wxStaticText( itemPanel10, ID_RICHTEXTLISTSTYLEPAGE_SYMBOLSTATIC, _("Symbol &font:"), wxDefaultPosition, wxDefaultSize, 0 );
itemBoxSizer26->Add(itemStaticText32, 0, wxALIGN_LEFT|wxLEFT|wxRIGHT|wxTOP, 5);
wxArrayString m_symbolFontCtrlStrings;
m_symbolFontCtrl = new wxComboBox( itemPanel10, ID_RICHTEXTLISTSTYLEPAGE_SYMBOLFONTCTRL, wxT(""), wxDefaultPosition, wxDefaultSize, m_symbolFontCtrlStrings, wxCB_DROPDOWN );
if (wxRichTextListStylePage::ShowToolTips())
m_symbolFontCtrl->SetToolTip(_("Available fonts."));
itemBoxSizer26->Add(m_symbolFontCtrl, 0, wxGROW|wxALL, 5);
itemBoxSizer26->Add(5, 5, 1, wxALIGN_CENTER_HORIZONTAL, 5);
wxStaticText* itemStaticText35 = new wxStaticText( itemPanel10, ID_RICHTEXTLISTSTYLEPAGE_NAMESTATIC, _("S&tandard bullet name:"), wxDefaultPosition, wxDefaultSize, 0 );
itemBoxSizer26->Add(itemStaticText35, 0, wxALIGN_LEFT|wxLEFT|wxRIGHT|wxTOP, 5);
wxArrayString m_bulletNameCtrlStrings;
m_bulletNameCtrl = new wxComboBox( itemPanel10, ID_RICHTEXTLISTSTYLEPAGE_NAMECTRL, wxT(""), wxDefaultPosition, wxDefaultSize, m_bulletNameCtrlStrings, wxCB_DROPDOWN );
m_bulletNameCtrl->SetHelpText(_("A standard bullet name."));
if (wxRichTextListStylePage::ShowToolTips())
m_bulletNameCtrl->SetToolTip(_("A standard bullet name."));
itemBoxSizer26->Add(m_bulletNameCtrl, 0, wxGROW|wxALL, 5);
itemNotebook9->AddPage(itemPanel10, _("Bullet style"));
wxPanel* itemPanel37 = new wxPanel( itemNotebook9, ID_RICHTEXTLISTSTYLEPAGE_SPACING, wxDefaultPosition, wxDefaultSize, wxNO_BORDER|wxTAB_TRAVERSAL );
wxBoxSizer* itemBoxSizer38 = new wxBoxSizer(wxVERTICAL);
itemPanel37->SetSizer(itemBoxSizer38);
wxBoxSizer* itemBoxSizer39 = new wxBoxSizer(wxHORIZONTAL);
itemBoxSizer38->Add(itemBoxSizer39, 0, wxGROW, 5);
wxBoxSizer* itemBoxSizer40 = new wxBoxSizer(wxVERTICAL);
itemBoxSizer39->Add(itemBoxSizer40, 0, wxGROW, 5);
wxStaticText* itemStaticText41 = new wxStaticText( itemPanel37, wxID_STATIC, _("&Alignment"), wxDefaultPosition, wxDefaultSize, 0 );
itemBoxSizer40->Add(itemStaticText41, 0, wxALIGN_LEFT|wxLEFT|wxRIGHT|wxTOP, 5);
wxBoxSizer* itemBoxSizer42 = new wxBoxSizer(wxHORIZONTAL);
itemBoxSizer40->Add(itemBoxSizer42, 0, wxALIGN_CENTER_HORIZONTAL|wxALL, 5);
itemBoxSizer42->Add(5, 5, 0, wxALIGN_CENTER_VERTICAL, 5);
wxBoxSizer* itemBoxSizer44 = new wxBoxSizer(wxVERTICAL);
itemBoxSizer42->Add(itemBoxSizer44, 0, wxALIGN_CENTER_VERTICAL|wxTOP, 5);
m_alignmentLeft = new wxRadioButton( itemPanel37, ID_RICHTEXTLISTSTYLEPAGE_ALIGNLEFT, _("&Left"), wxDefaultPosition, wxDefaultSize, wxRB_GROUP );
m_alignmentLeft->SetValue(false);
m_alignmentLeft->SetHelpText(_("Left-align text."));
if (wxRichTextListStylePage::ShowToolTips())
m_alignmentLeft->SetToolTip(_("Left-align text."));
itemBoxSizer44->Add(m_alignmentLeft, 0, wxALIGN_LEFT|wxALL, 5);
m_alignmentRight = new wxRadioButton( itemPanel37, ID_RICHTEXTLISTSTYLEPAGE_ALIGNRIGHT, _("&Right"), wxDefaultPosition, wxDefaultSize, 0 );
m_alignmentRight->SetValue(false);
m_alignmentRight->SetHelpText(_("Right-align text."));
if (wxRichTextListStylePage::ShowToolTips())
m_alignmentRight->SetToolTip(_("Right-align text."));
itemBoxSizer44->Add(m_alignmentRight, 0, wxALIGN_LEFT|wxALL, 5);
m_alignmentJustified = new wxRadioButton( itemPanel37, ID_RICHTEXTLISTSTYLEPAGE_JUSTIFIED, _("&Justified"), wxDefaultPosition, wxDefaultSize, 0 );
m_alignmentJustified->SetValue(false);
m_alignmentJustified->SetHelpText(_("Justify text left and right."));
if (wxRichTextListStylePage::ShowToolTips())
m_alignmentJustified->SetToolTip(_("Justify text left and right."));
itemBoxSizer44->Add(m_alignmentJustified, 0, wxALIGN_LEFT|wxALL, 5);
m_alignmentCentred = new wxRadioButton( itemPanel37, ID_RICHTEXTLISTSTYLEPAGE_CENTERED, _("Cen&tred"), wxDefaultPosition, wxDefaultSize, 0 );
m_alignmentCentred->SetValue(false);
m_alignmentCentred->SetHelpText(_("Centre text."));
if (wxRichTextListStylePage::ShowToolTips())
m_alignmentCentred->SetToolTip(_("Centre text."));
itemBoxSizer44->Add(m_alignmentCentred, 0, wxALIGN_LEFT|wxALL, 5);
m_alignmentIndeterminate = new wxRadioButton( itemPanel37, ID_RICHTEXTLISTSTYLEPAGE_ALIGNINDETERMINATE, _("&Indeterminate"), wxDefaultPosition, wxDefaultSize, 0 );
m_alignmentIndeterminate->SetValue(false);
m_alignmentIndeterminate->SetHelpText(_("Use the current alignment setting."));
if (wxRichTextListStylePage::ShowToolTips())
m_alignmentIndeterminate->SetToolTip(_("Use the current alignment setting."));
itemBoxSizer44->Add(m_alignmentIndeterminate, 0, wxALIGN_LEFT|wxALL, 5);
itemBoxSizer39->Add(2, 1, 1, wxALIGN_CENTER_VERTICAL|wxTOP|wxBOTTOM, 5);
wxStaticLine* itemStaticLine51 = new wxStaticLine( itemPanel37, wxID_STATIC, wxDefaultPosition, wxDefaultSize, wxLI_VERTICAL );
itemBoxSizer39->Add(itemStaticLine51, 0, wxGROW|wxLEFT|wxBOTTOM, 5);
itemBoxSizer39->Add(2, 1, 1, wxALIGN_CENTER_VERTICAL|wxTOP|wxBOTTOM, 5);
wxBoxSizer* itemBoxSizer53 = new wxBoxSizer(wxVERTICAL);
itemBoxSizer39->Add(itemBoxSizer53, 0, wxGROW, 5);
wxStaticText* itemStaticText54 = new wxStaticText( itemPanel37, wxID_STATIC, _("&Indentation (tenths of a mm)"), wxDefaultPosition, wxDefaultSize, 0 );
itemBoxSizer53->Add(itemStaticText54, 0, wxALIGN_LEFT|wxLEFT|wxRIGHT|wxTOP, 5);
wxBoxSizer* itemBoxSizer55 = new wxBoxSizer(wxHORIZONTAL);
itemBoxSizer53->Add(itemBoxSizer55, 0, wxALIGN_LEFT|wxALL, 5);
itemBoxSizer55->Add(5, 5, 0, wxALIGN_CENTER_VERTICAL, 5);
wxFlexGridSizer* itemFlexGridSizer57 = new wxFlexGridSizer(2, 2, 0, 0);
itemBoxSizer55->Add(itemFlexGridSizer57, 0, wxALIGN_CENTER_VERTICAL, 5);
wxStaticText* itemStaticText58 = new wxStaticText( itemPanel37, wxID_STATIC, _("&Left:"), wxDefaultPosition, wxDefaultSize, 0 );
itemFlexGridSizer57->Add(itemStaticText58, 0, wxALIGN_RIGHT|wxALIGN_CENTER_VERTICAL|wxALL, 5);
wxBoxSizer* itemBoxSizer59 = new wxBoxSizer(wxHORIZONTAL);
itemFlexGridSizer57->Add(itemBoxSizer59, 0, wxALIGN_CENTER_HORIZONTAL|wxALIGN_CENTER_VERTICAL, 5);
m_indentLeft = new wxTextCtrl( itemPanel37, ID_RICHTEXTLISTSTYLEPAGE_INDENTLEFT, wxT(""), wxDefaultPosition, wxSize(50, -1), 0 );
m_indentLeft->SetHelpText(_("The left indent."));
if (wxRichTextListStylePage::ShowToolTips())
m_indentLeft->SetToolTip(_("The left indent."));
itemBoxSizer59->Add(m_indentLeft, 0, wxALIGN_CENTER_VERTICAL|wxALL, 5);
wxStaticText* itemStaticText61 = new wxStaticText( itemPanel37, wxID_STATIC, _("Left (&first line):"), wxDefaultPosition, wxDefaultSize, 0 );
itemFlexGridSizer57->Add(itemStaticText61, 0, wxALIGN_RIGHT|wxALIGN_CENTER_VERTICAL|wxALL, 5);
wxBoxSizer* itemBoxSizer62 = new wxBoxSizer(wxHORIZONTAL);
itemFlexGridSizer57->Add(itemBoxSizer62, 0, wxALIGN_CENTER_HORIZONTAL|wxALIGN_CENTER_VERTICAL, 5);
m_indentLeftFirst = new wxTextCtrl( itemPanel37, ID_RICHTEXTLISTSTYLEPAGE_INDENTFIRSTLINE, wxT(""), wxDefaultPosition, wxSize(50, -1), 0 );
m_indentLeftFirst->SetHelpText(_("The first line indent."));
if (wxRichTextListStylePage::ShowToolTips())
m_indentLeftFirst->SetToolTip(_("The first line indent."));
itemBoxSizer62->Add(m_indentLeftFirst, 0, wxALIGN_CENTER_VERTICAL|wxALL, 5);
wxStaticText* itemStaticText64 = new wxStaticText( itemPanel37, wxID_STATIC, _("&Right:"), wxDefaultPosition, wxDefaultSize, 0 );
itemFlexGridSizer57->Add(itemStaticText64, 0, wxALIGN_RIGHT|wxALIGN_CENTER_VERTICAL|wxALL, 5);
wxBoxSizer* itemBoxSizer65 = new wxBoxSizer(wxHORIZONTAL);
itemFlexGridSizer57->Add(itemBoxSizer65, 0, wxALIGN_CENTER_HORIZONTAL|wxALIGN_CENTER_VERTICAL, 5);
m_indentRight = new wxTextCtrl( itemPanel37, ID_RICHTEXTLISTSTYLEPAGE_INDENTRIGHT, wxT(""), wxDefaultPosition, wxSize(50, -1), 0 );
m_indentRight->SetHelpText(_("The right indent."));
if (wxRichTextListStylePage::ShowToolTips())
m_indentRight->SetToolTip(_("The right indent."));
itemBoxSizer65->Add(m_indentRight, 0, wxALIGN_CENTER_VERTICAL|wxALL, 5);
itemBoxSizer39->Add(2, 1, 1, wxALIGN_CENTER_VERTICAL|wxTOP|wxBOTTOM, 5);
wxStaticLine* itemStaticLine68 = new wxStaticLine( itemPanel37, wxID_STATIC, wxDefaultPosition, wxDefaultSize, wxLI_VERTICAL );
itemBoxSizer39->Add(itemStaticLine68, 0, wxGROW|wxTOP|wxBOTTOM, 5);
itemBoxSizer39->Add(2, 1, 1, wxALIGN_CENTER_VERTICAL|wxTOP|wxBOTTOM, 5);
wxBoxSizer* itemBoxSizer70 = new wxBoxSizer(wxVERTICAL);
itemBoxSizer39->Add(itemBoxSizer70, 0, wxGROW, 5);
wxStaticText* itemStaticText71 = new wxStaticText( itemPanel37, wxID_STATIC, _("&Spacing (tenths of a mm)"), wxDefaultPosition, wxDefaultSize, 0 );
itemBoxSizer70->Add(itemStaticText71, 0, wxALIGN_LEFT|wxLEFT|wxRIGHT|wxTOP, 5);
wxBoxSizer* itemBoxSizer72 = new wxBoxSizer(wxHORIZONTAL);
itemBoxSizer70->Add(itemBoxSizer72, 0, wxALIGN_LEFT|wxALL, 5);
itemBoxSizer72->Add(5, 5, 0, wxALIGN_CENTER_VERTICAL, 5);
wxFlexGridSizer* itemFlexGridSizer74 = new wxFlexGridSizer(2, 2, 0, 0);
itemBoxSizer72->Add(itemFlexGridSizer74, 0, wxALIGN_CENTER_VERTICAL, 5);
wxStaticText* itemStaticText75 = new wxStaticText( itemPanel37, wxID_STATIC, _("Before a paragraph:"), wxDefaultPosition, wxDefaultSize, 0 );
itemFlexGridSizer74->Add(itemStaticText75, 0, wxALIGN_RIGHT|wxALIGN_CENTER_VERTICAL|wxALL, 5);
wxBoxSizer* itemBoxSizer76 = new wxBoxSizer(wxHORIZONTAL);
itemFlexGridSizer74->Add(itemBoxSizer76, 0, wxALIGN_CENTER_HORIZONTAL|wxALIGN_CENTER_VERTICAL, 5);
m_spacingBefore = new wxTextCtrl( itemPanel37, ID_RICHTEXTLISTSTYLEPAGE_SPACINGBEFORE, wxT(""), wxDefaultPosition, wxSize(50, -1), 0 );
m_spacingBefore->SetHelpText(_("The spacing before the paragraph."));
if (wxRichTextListStylePage::ShowToolTips())
m_spacingBefore->SetToolTip(_("The spacing before the paragraph."));
itemBoxSizer76->Add(m_spacingBefore, 0, wxALIGN_CENTER_VERTICAL|wxALL, 5);
wxStaticText* itemStaticText78 = new wxStaticText( itemPanel37, wxID_STATIC, _("After a paragraph:"), wxDefaultPosition, wxDefaultSize, 0 );
itemFlexGridSizer74->Add(itemStaticText78, 0, wxALIGN_RIGHT|wxALIGN_CENTER_VERTICAL|wxALL, 5);
wxBoxSizer* itemBoxSizer79 = new wxBoxSizer(wxHORIZONTAL);
itemFlexGridSizer74->Add(itemBoxSizer79, 0, wxALIGN_CENTER_HORIZONTAL|wxALIGN_CENTER_VERTICAL, 5);
m_spacingAfter = new wxTextCtrl( itemPanel37, ID_RICHTEXTLISTSTYLEPAGE_SPACINGAFTER, wxT(""), wxDefaultPosition, wxSize(50, -1), 0 );
m_spacingAfter->SetHelpText(_("The spacing after the paragraph."));
if (wxRichTextListStylePage::ShowToolTips())
m_spacingAfter->SetToolTip(_("The spacing after the paragraph."));
itemBoxSizer79->Add(m_spacingAfter, 0, wxALIGN_CENTER_VERTICAL|wxALL, 5);
wxStaticText* itemStaticText81 = new wxStaticText( itemPanel37, wxID_STATIC, _("Line spacing:"), wxDefaultPosition, wxDefaultSize, 0 );
itemFlexGridSizer74->Add(itemStaticText81, 0, wxALIGN_RIGHT|wxALIGN_CENTER_VERTICAL|wxALL, 5);
wxBoxSizer* itemBoxSizer82 = new wxBoxSizer(wxHORIZONTAL);
itemFlexGridSizer74->Add(itemBoxSizer82, 0, wxALIGN_CENTER_HORIZONTAL|wxALIGN_CENTER_VERTICAL, 5);
wxArrayString m_spacingLineStrings;
m_spacingLineStrings.Add(_("Single"));
m_spacingLineStrings.Add(_("1.5"));
m_spacingLineStrings.Add(_("2"));
m_spacingLine = new wxComboBox( itemPanel37, ID_RICHTEXTLISTSTYLEPAGE_LINESPACING, _("Single"), wxDefaultPosition, wxDefaultSize, m_spacingLineStrings, wxCB_READONLY );
m_spacingLine->SetStringSelection(_("Single"));
m_spacingLine->SetHelpText(_("The line spacing."));
if (wxRichTextListStylePage::ShowToolTips())
m_spacingLine->SetToolTip(_("The line spacing."));
itemBoxSizer82->Add(m_spacingLine, 0, wxALIGN_CENTER_VERTICAL|wxALL, 5);
itemNotebook9->AddPage(itemPanel37, _("Spacing"));
itemBoxSizer3->Add(itemNotebook9, 0, wxGROW|wxALL, 5);
m_previewCtrl = new wxRichTextCtrl( itemPanel1, ID_RICHTEXTLISTSTYLEPAGE_RICHTEXTCTRL, wxEmptyString, wxDefaultPosition, wxSize(350, 180), wxSUNKEN_BORDER|wxVSCROLL|wxTE_READONLY );
m_previewCtrl->SetHelpText(_("Shows a preview of the bullet settings."));
if (wxRichTextListStylePage::ShowToolTips())
m_previewCtrl->SetToolTip(_("Shows a preview of the bullet settings."));
itemBoxSizer3->Add(m_previewCtrl, 0, wxGROW|wxALL, 5);
////@end wxRichTextListStylePage content construction
m_dontUpdate = true;
m_styleListBox->Append(_("(None)"));
m_styleListBox->Append(_("Arabic"));
m_styleListBox->Append(_("Upper case letters"));
m_styleListBox->Append(_("Lower case letters"));
m_styleListBox->Append(_("Upper case roman numerals"));
m_styleListBox->Append(_("Lower case roman numerals"));
m_styleListBox->Append(_("Numbered outline"));
m_styleListBox->Append(_("Symbol"));
m_styleListBox->Append(_("Bitmap"));
m_styleListBox->Append(_("Standard"));
m_symbolCtrl->Append(_("*"));
m_symbolCtrl->Append(_("-"));
m_symbolCtrl->Append(_(">"));
m_symbolCtrl->Append(_("+"));
m_symbolCtrl->Append(_("~"));
wxArrayString standardBulletNames;
if (wxRichTextBuffer::GetRenderer())
wxRichTextBuffer::GetRenderer()->EnumerateStandardBulletNames(standardBulletNames);
m_bulletNameCtrl->Append(standardBulletNames);
wxArrayString facenames = wxRichTextCtrl::GetAvailableFontNames();
facenames.Sort();
m_symbolFontCtrl->Append(facenames);
m_levelCtrl->SetValue(m_currentLevel);
m_dontUpdate = false;
}
/// Updates the font preview
void wxRichTextListStylePage::UpdatePreview()
{
static const wxChar* s_para1 = wxT("Lorem ipsum dolor sit amet, consectetuer adipiscing elit. \
Nullam ante sapien, vestibulum nonummy, pulvinar sed, luctus ut, lacus.\n");
static const wxChar* s_para2 = wxT("Duis pharetra consequat dui. Nullam vitae justo id mauris lobortis interdum.\n");
static const wxChar* s_para3 = wxT("Integer convallis dolor at augue \
iaculis malesuada. Donec bibendum ipsum ut ante porta fringilla.\n");
wxRichTextListStyleDefinition* def = wxDynamicCast(wxRichTextFormattingDialog::GetDialogStyleDefinition(this),
wxRichTextListStyleDefinition);
wxRichTextStyleSheet* styleSheet = wxRichTextFormattingDialog::GetDialog(this)->GetStyleSheet();
wxTextAttr attr((const wxTextAttr &)(styleSheet ? def->GetStyle() : def->GetStyleMergedWithBase(styleSheet)));
attr.SetFlags(attr.GetFlags() &
(wxTEXT_ATTR_ALIGNMENT|wxTEXT_ATTR_LEFT_INDENT|wxTEXT_ATTR_RIGHT_INDENT|wxTEXT_ATTR_PARA_SPACING_BEFORE|wxTEXT_ATTR_PARA_SPACING_AFTER|
wxTEXT_ATTR_LINE_SPACING|
wxTEXT_ATTR_BULLET_STYLE|wxTEXT_ATTR_BULLET_NUMBER|wxTEXT_ATTR_BULLET_TEXT));
wxFont font(m_previewCtrl->GetFont());
font.SetPointSize(9);
m_previewCtrl->SetFont(font);
wxTextAttr normalParaAttr;
normalParaAttr.SetFont(font);
normalParaAttr.SetTextColour(wxColour(wxT("LIGHT GREY")));
m_previewCtrl->Freeze();
m_previewCtrl->Clear();
m_previewCtrl->BeginStyle(normalParaAttr);
m_previewCtrl->WriteText(s_para1);
m_previewCtrl->EndStyle();
m_previewCtrl->BeginStyle(attr);
long listStart = m_previewCtrl->GetInsertionPoint() + 1;
int i;
for (i = 0; i < 10; i++)
{
wxTextAttr levelAttr = * def->GetLevelAttributes(i);
levelAttr.SetBulletNumber(1);
m_previewCtrl->BeginStyle(levelAttr);
m_previewCtrl->WriteText(wxString::Format(wxT("List level %d. "), i+1) + s_para2);
m_previewCtrl->EndStyle();
}
m_previewCtrl->EndStyle();
long listEnd = m_previewCtrl->GetInsertionPoint();
m_previewCtrl->BeginStyle(normalParaAttr);
m_previewCtrl->WriteText(s_para3);
m_previewCtrl->EndStyle();
m_previewCtrl->NumberList(wxRichTextRange(listStart, listEnd), def);
m_previewCtrl->Thaw();
}
/// Transfer data from/to window
bool wxRichTextListStylePage::TransferDataFromWindow()
{
wxPanel::TransferDataFromWindow();
m_currentLevel = m_levelCtrl->GetValue();
wxTextAttr* attr = GetAttributesForSelection();
if (m_alignmentLeft->GetValue())
attr->SetAlignment(wxTEXT_ALIGNMENT_LEFT);
else if (m_alignmentCentred->GetValue())
attr->SetAlignment(wxTEXT_ALIGNMENT_CENTRE);
else if (m_alignmentRight->GetValue())
attr->SetAlignment(wxTEXT_ALIGNMENT_RIGHT);
else if (m_alignmentJustified->GetValue())
attr->SetAlignment(wxTEXT_ALIGNMENT_JUSTIFIED);
else
{
attr->SetAlignment(wxTEXT_ALIGNMENT_DEFAULT);
attr->SetFlags(attr->GetFlags() & (~wxTEXT_ATTR_ALIGNMENT));
}
wxString leftIndent(m_indentLeft->GetValue());
wxString leftFirstIndent(m_indentLeftFirst->GetValue());
if (!leftIndent.empty())
{
int visualLeftIndent = wxAtoi(leftIndent);
int visualLeftFirstIndent = wxAtoi(leftFirstIndent);
int actualLeftIndent = visualLeftFirstIndent;
int actualLeftSubIndent = visualLeftIndent - visualLeftFirstIndent;
attr->SetLeftIndent(actualLeftIndent, actualLeftSubIndent);
}
else
attr->SetFlags(attr->GetFlags() & (~wxTEXT_ATTR_LEFT_INDENT));
wxString rightIndent(m_indentRight->GetValue());
if (!rightIndent.empty())
attr->SetRightIndent(wxAtoi(rightIndent));
else
attr->SetFlags(attr->GetFlags() & (~wxTEXT_ATTR_RIGHT_INDENT));
wxString spacingAfter(m_spacingAfter->GetValue());
if (!spacingAfter.empty())
attr->SetParagraphSpacingAfter(wxAtoi(spacingAfter));
else
attr->SetFlags(attr->GetFlags() & (~wxTEXT_ATTR_PARA_SPACING_AFTER));
wxString spacingBefore(m_spacingBefore->GetValue());
if (!spacingBefore.empty())
attr->SetParagraphSpacingBefore(wxAtoi(spacingBefore));
else
attr->SetFlags(attr->GetFlags() & (~wxTEXT_ATTR_PARA_SPACING_BEFORE));
int spacingIndex = m_spacingLine->GetSelection();
int lineSpacing = 0;
if (spacingIndex == 0)
lineSpacing = 10;
else if (spacingIndex == 1)
lineSpacing = 15;
else if (spacingIndex == 2)
lineSpacing = 20;
if (lineSpacing == 0)
attr->SetFlags(attr->GetFlags() & (~wxTEXT_ATTR_LINE_SPACING));
else
attr->SetLineSpacing(lineSpacing);
/// BULLETS
// if (m_hasBulletStyle)
{
long bulletStyle = 0;
int index = m_styleListBox->GetSelection();
if (index == wxRICHTEXT_BULLETINDEX_ARABIC)
bulletStyle |= wxTEXT_ATTR_BULLET_STYLE_ARABIC;
else if (index == wxRICHTEXT_BULLETINDEX_UPPER_CASE)
bulletStyle |= wxTEXT_ATTR_BULLET_STYLE_LETTERS_UPPER;
else if (index == wxRICHTEXT_BULLETINDEX_LOWER_CASE)
bulletStyle |= wxTEXT_ATTR_BULLET_STYLE_LETTERS_LOWER;
else if (index == wxRICHTEXT_BULLETINDEX_UPPER_CASE_ROMAN)
bulletStyle |= wxTEXT_ATTR_BULLET_STYLE_ROMAN_UPPER;
else if (index == wxRICHTEXT_BULLETINDEX_LOWER_CASE_ROMAN)
bulletStyle |= wxTEXT_ATTR_BULLET_STYLE_ROMAN_LOWER;
else if (index == wxRICHTEXT_BULLETINDEX_OUTLINE)
bulletStyle |= wxTEXT_ATTR_BULLET_STYLE_OUTLINE;
else if (index == wxRICHTEXT_BULLETINDEX_SYMBOL)
bulletStyle |= wxTEXT_ATTR_BULLET_STYLE_SYMBOL;
else if (index == wxRICHTEXT_BULLETINDEX_BITMAP)
bulletStyle |= wxTEXT_ATTR_BULLET_STYLE_BITMAP;
else if (index == wxRICHTEXT_BULLETINDEX_STANDARD)
{
bulletStyle |= wxTEXT_ATTR_BULLET_STYLE_STANDARD;
attr->SetBulletName(m_bulletNameCtrl->GetValue());
}
if (m_parenthesesCtrl->GetValue())
bulletStyle |= wxTEXT_ATTR_BULLET_STYLE_PARENTHESES;
if (m_rightParenthesisCtrl->GetValue())
bulletStyle |= wxTEXT_ATTR_BULLET_STYLE_RIGHT_PARENTHESIS;
if (m_periodCtrl->GetValue())
bulletStyle |= wxTEXT_ATTR_BULLET_STYLE_PERIOD;
if (m_bulletAlignmentCtrl->GetSelection() == 1)
bulletStyle |= wxTEXT_ATTR_BULLET_STYLE_ALIGN_CENTRE;
else if (m_bulletAlignmentCtrl->GetSelection() == 2)
bulletStyle |= wxTEXT_ATTR_BULLET_STYLE_ALIGN_RIGHT;
// Left is implied
attr->SetBulletStyle(bulletStyle);
}
// if (m_hasBulletSymbol)
{
attr->SetBulletText(m_symbolCtrl->GetValue());
attr->SetBulletFont(m_symbolFontCtrl->GetValue());
}
return true;
}
bool wxRichTextListStylePage::TransferDataToWindow()
{
DoTransferDataToWindow();
UpdatePreview();
return true;
}
/// Just transfer to the window
void wxRichTextListStylePage::DoTransferDataToWindow()
{
m_dontUpdate = true;
wxPanel::TransferDataToWindow();
wxTextAttr* attr = GetAttributesForSelection();
if (attr->HasAlignment())
{
if (attr->GetAlignment() == wxTEXT_ALIGNMENT_LEFT)
m_alignmentLeft->SetValue(true);
else if (attr->GetAlignment() == wxTEXT_ALIGNMENT_RIGHT)
m_alignmentRight->SetValue(true);
else if (attr->GetAlignment() == wxTEXT_ALIGNMENT_CENTRE)
m_alignmentCentred->SetValue(true);
else if (attr->GetAlignment() == wxTEXT_ALIGNMENT_JUSTIFIED)
m_alignmentJustified->SetValue(true);
else
m_alignmentIndeterminate->SetValue(true);
}
else
m_alignmentIndeterminate->SetValue(true);
if (attr->HasLeftIndent())
{
wxString leftIndent(wxString::Format(wxT("%ld"), attr->GetLeftIndent() + attr->GetLeftSubIndent()));
wxString leftFirstIndent(wxString::Format(wxT("%ld"), attr->GetLeftIndent()));
m_indentLeft->SetValue(leftIndent);
m_indentLeftFirst->SetValue(leftFirstIndent);
}
else
{
m_indentLeft->SetValue(wxEmptyString);
m_indentLeftFirst->SetValue(wxEmptyString);
}
if (attr->HasRightIndent())
{
wxString rightIndent(wxString::Format(wxT("%ld"), attr->GetRightIndent()));
m_indentRight->SetValue(rightIndent);
}
else
m_indentRight->SetValue(wxEmptyString);
if (attr->HasParagraphSpacingAfter())
{
wxString spacingAfter(wxString::Format(wxT("%d"), attr->GetParagraphSpacingAfter()));
m_spacingAfter->SetValue(spacingAfter);
}
else
m_spacingAfter->SetValue(wxEmptyString);
if (attr->HasParagraphSpacingBefore())
{
wxString spacingBefore(wxString::Format(wxT("%d"), attr->GetParagraphSpacingBefore()));
m_spacingBefore->SetValue(spacingBefore);
}
else
m_spacingBefore->SetValue(wxEmptyString);
if (attr->HasLineSpacing())
{
int index = 0;
int lineSpacing = attr->GetLineSpacing();
if (lineSpacing == 10)
index = 0;
else if (lineSpacing == 15)
index = 1;
else if (lineSpacing == 20)
index = 2;
else
index = -1;
m_spacingLine->SetSelection(index);
}
else
m_spacingLine->SetSelection(-1);
/// BULLETS
if (attr->HasBulletStyle())
{
int index = 0;
if (attr->GetBulletStyle() & wxTEXT_ATTR_BULLET_STYLE_ARABIC)
index = wxRICHTEXT_BULLETINDEX_ARABIC;
else if (attr->GetBulletStyle() & wxTEXT_ATTR_BULLET_STYLE_LETTERS_UPPER)
index = wxRICHTEXT_BULLETINDEX_UPPER_CASE;
else if (attr->GetBulletStyle() & wxTEXT_ATTR_BULLET_STYLE_LETTERS_LOWER)
index = wxRICHTEXT_BULLETINDEX_LOWER_CASE;
else if (attr->GetBulletStyle() & wxTEXT_ATTR_BULLET_STYLE_ROMAN_UPPER)
index = wxRICHTEXT_BULLETINDEX_UPPER_CASE_ROMAN;
else if (attr->GetBulletStyle() & wxTEXT_ATTR_BULLET_STYLE_ROMAN_LOWER)
index = wxRICHTEXT_BULLETINDEX_LOWER_CASE_ROMAN;
else if (attr->GetBulletStyle() & wxTEXT_ATTR_BULLET_STYLE_OUTLINE)
index = wxRICHTEXT_BULLETINDEX_OUTLINE;
else if (attr->GetBulletStyle() & wxTEXT_ATTR_BULLET_STYLE_SYMBOL)
index = wxRICHTEXT_BULLETINDEX_SYMBOL;
else if (attr->GetBulletStyle() & wxTEXT_ATTR_BULLET_STYLE_BITMAP)
index = wxRICHTEXT_BULLETINDEX_BITMAP;
else if (attr->GetBulletStyle() & wxTEXT_ATTR_BULLET_STYLE_STANDARD)
index = wxRICHTEXT_BULLETINDEX_STANDARD;
m_styleListBox->SetSelection(index);
if (attr->GetBulletStyle() & wxTEXT_ATTR_BULLET_STYLE_PARENTHESES)
m_parenthesesCtrl->SetValue(true);
else
m_parenthesesCtrl->SetValue(false);
if (attr->GetBulletStyle() & wxTEXT_ATTR_BULLET_STYLE_RIGHT_PARENTHESIS)
m_rightParenthesisCtrl->SetValue(true);
else
m_rightParenthesisCtrl->SetValue(false);
if (attr->GetBulletStyle() & wxTEXT_ATTR_BULLET_STYLE_PERIOD)
m_periodCtrl->SetValue(true);
else
m_periodCtrl->SetValue(false);
if (attr->GetBulletStyle() & wxTEXT_ATTR_BULLET_STYLE_ALIGN_CENTRE)
m_bulletAlignmentCtrl->SetSelection(1);
else if (attr->GetBulletStyle() & wxTEXT_ATTR_BULLET_STYLE_ALIGN_RIGHT)
m_bulletAlignmentCtrl->SetSelection(2);
else
m_bulletAlignmentCtrl->SetSelection(0);
}
else
{
m_styleListBox->SetSelection(-1);
m_bulletAlignmentCtrl->SetSelection(-1);
}
if (attr->HasBulletText())
{
m_symbolCtrl->SetValue(attr->GetBulletText());
m_symbolFontCtrl->SetValue(attr->GetBulletFont());
}
else
m_symbolCtrl->SetValue(wxEmptyString);
if (attr->HasBulletName())
m_bulletNameCtrl->SetValue(attr->GetBulletName());
else
m_bulletNameCtrl->SetValue(wxEmptyString);
m_dontUpdate = false;
}
/// Get attributes for selected level
wxTextAttr* wxRichTextListStylePage::GetAttributesForSelection()
{
wxRichTextListStyleDefinition* def = wxDynamicCast(wxRichTextFormattingDialog::GetDialogStyleDefinition(this),
wxRichTextListStyleDefinition);
int value = m_levelCtrl->GetValue();
if (def)
return def->GetLevelAttributes(value-1);
else
return NULL;
}
/// Just transfer from the window and update the preview
void wxRichTextListStylePage::TransferAndPreview()
{
if (!m_dontUpdate)
{
TransferDataFromWindow();
UpdatePreview();
}
}
/*!
* wxEVT_COMMAND_SPINCTRL_UPDATED event handler for ID_RICHTEXTLISTSTYLEPAGE_LEVEL
*/
void wxRichTextListStylePage::OnLevelUpdated( wxSpinEvent& WXUNUSED(event) )
{
if (!m_dontUpdate)
{
m_currentLevel = m_levelCtrl->GetValue();
TransferDataToWindow();
}
}
/*!
* wxEVT_SCROLL_LINEUP event handler for ID_RICHTEXTLISTSTYLEPAGE_LEVEL
*/
void wxRichTextListStylePage::OnLevelUp( wxSpinEvent& event )
{
if (!m_dontUpdate)
{
m_currentLevel = event.GetPosition();
TransferDataToWindow();
}
}
/*!
* wxEVT_SCROLL_LINEDOWN event handler for ID_RICHTEXTLISTSTYLEPAGE_LEVEL
*/
void wxRichTextListStylePage::OnLevelDown( wxSpinEvent& event )
{
if (!m_dontUpdate)
{
m_currentLevel = event.GetPosition();
TransferDataToWindow();
}
}
/*!
* wxEVT_COMMAND_TEXT_UPDATED event handler for ID_RICHTEXTLISTSTYLEPAGE_LEVEL
*/
void wxRichTextListStylePage::OnLevelTextUpdated( wxCommandEvent& WXUNUSED(event) )
{
// Can cause problems
#if 0
if (!m_dontUpdate)
{
m_currentLevel = event.GetInt();
TransferDataToWindow();
}
#endif
}
/*!
* wxEVT_UPDATE_UI event handler for ID_RICHTEXTLISTSTYLEPAGE_LEVEL
*/
void wxRichTextListStylePage::OnLevelUIUpdate( wxUpdateUIEvent& event )
{
////@begin wxEVT_UPDATE_UI event handler for ID_RICHTEXTLISTSTYLEPAGE_LEVEL in wxRichTextListStylePage.
// Before editing this code, remove the block markers.
event.Skip();
////@end wxEVT_UPDATE_UI event handler for ID_RICHTEXTLISTSTYLEPAGE_LEVEL in wxRichTextListStylePage.
}
/*!
* wxEVT_COMMAND_LISTBOX_SELECTED event handler for ID_RICHTEXTLISTSTYLEPAGE_STYLELISTBOX
*/
void wxRichTextListStylePage::OnStylelistboxSelected( wxCommandEvent& WXUNUSED(event) )
{
TransferAndPreview();
}
/*!
* wxEVT_UPDATE_UI event handler for ID_RICHTEXTLISTSTYLEPAGE_SYMBOLSTATIC
*/
void wxRichTextListStylePage::OnSymbolstaticUpdate( wxUpdateUIEvent& event )
{
OnSymbolUpdate(event);
}
/*!
* wxEVT_COMMAND_COMBOBOX_SELECTED event handler for ID_RICHTEXTBULLETSPAGE_SYMBOLCTRL
*/
void wxRichTextListStylePage::OnSymbolctrlSelected( wxCommandEvent& WXUNUSED(event) )
{
TransferAndPreview();
}
/*!
* wxEVT_COMMAND_TEXT_UPDATED event handler for ID_RICHTEXTBULLETSPAGE_SYMBOLCTRL
*/
void wxRichTextListStylePage::OnSymbolctrlUpdated( wxCommandEvent& WXUNUSED(event) )
{
TransferAndPreview();
}
/*!
* wxEVT_UPDATE_UI event handler for ID_RICHTEXTBULLETSPAGE_SYMBOLCTRL
*/
void wxRichTextListStylePage::OnSymbolctrlUIUpdate( wxUpdateUIEvent& event )
{
OnSymbolUpdate(event);
}
/*!
* wxEVT_COMMAND_BUTTON_CLICKED event handler for ID_RICHTEXTBULLETSPAGE_CHOOSE_SYMBOL
*/
void wxRichTextListStylePage::OnChooseSymbolClick( wxCommandEvent& WXUNUSED(event) )
{
int sel = m_styleListBox->GetSelection();
if (sel == wxRICHTEXT_BULLETINDEX_SYMBOL)
{
wxString symbol = m_symbolCtrl->GetValue();
wxString fontName = m_symbolFontCtrl->GetValue();
wxSymbolPickerDialog dlg(symbol, fontName, fontName, this);
if (dlg.ShowModal() == wxID_OK)
{
m_dontUpdate = true;
m_symbolCtrl->SetValue(dlg.GetSymbol());
m_symbolFontCtrl->SetValue(dlg.GetFontName());
TransferAndPreview();
m_dontUpdate = false;
}
}
}
/*!
* wxEVT_UPDATE_UI event handler for ID_RICHTEXTBULLETSPAGE_CHOOSE_SYMBOL
*/
void wxRichTextListStylePage::OnChooseSymbolUpdate( wxUpdateUIEvent& event )
{
OnSymbolUpdate(event);
}
/*!
* wxEVT_COMMAND_COMBOBOX_SELECTED event handler for ID_RICHTEXTLISTSTYLEPAGE_SYMBOLFONTCTRL
*/
void wxRichTextListStylePage::OnSymbolfontctrlSelected( wxCommandEvent& WXUNUSED(event) )
{
TransferAndPreview();
}
/*!
* wxEVT_COMMAND_TEXT_UPDATED event handler for ID_RICHTEXTLISTSTYLEPAGE_SYMBOLFONTCTRL
*/
void wxRichTextListStylePage::OnSymbolfontctrlUpdated( wxCommandEvent& WXUNUSED(event) )
{
TransferAndPreview();
}
/*!
* wxEVT_UPDATE_UI event handler for ID_RICHTEXTLISTSTYLEPAGE_SYMBOLFONTCTRL
*/
void wxRichTextListStylePage::OnSymbolfontctrlUIUpdate( wxUpdateUIEvent& event )
{
OnSymbolUpdate(event);
}
/*!
* wxEVT_COMMAND_CHECKBOX_CLICKED event handler for ID_RICHTEXTLISTSTYLEPAGE__PARENTHESESCTRL
*/
void wxRichTextListStylePage::OnParenthesesctrlClick( wxCommandEvent& WXUNUSED(event) )
{
TransferAndPreview();
}
/*!
* wxEVT_UPDATE_UI event handler for ID_RICHTEXTLISTSTYLEPAGE__PARENTHESESCTRL
*/
void wxRichTextListStylePage::OnParenthesesctrlUpdate( wxUpdateUIEvent& event )
{
int sel = m_styleListBox->GetSelection();
event.Enable((sel != wxRICHTEXT_BULLETINDEX_SYMBOL &&
sel != wxRICHTEXT_BULLETINDEX_BITMAP &&
sel != wxRICHTEXT_BULLETINDEX_NONE));
}
/*!
* wxEVT_COMMAND_CHECKBOX_CLICKED event handler for ID_RICHTEXTLISTSTYLEPAGE_PERIODCTRL
*/
void wxRichTextListStylePage::OnPeriodctrlClick( wxCommandEvent& WXUNUSED(event) )
{
TransferAndPreview();
}
/*!
* wxEVT_UPDATE_UI event handler for ID_RICHTEXTLISTSTYLEPAGE_PERIODCTRL
*/
void wxRichTextListStylePage::OnPeriodctrlUpdate( wxUpdateUIEvent& event )
{
int sel = m_styleListBox->GetSelection();
event.Enable((sel != wxRICHTEXT_BULLETINDEX_SYMBOL &&
sel != wxRICHTEXT_BULLETINDEX_BITMAP &&
sel != wxRICHTEXT_BULLETINDEX_NONE));
}
/*!
* wxEVT_COMMAND_RADIOBUTTON_SELECTED event handler for ID_RICHTEXTLISTSTYLEPAGE_ALIGNLEFT
*/
void wxRichTextListStylePage::OnRichtextliststylepageAlignleftSelected( wxCommandEvent& WXUNUSED(event) )
{
TransferAndPreview();
}
/*!
* wxEVT_COMMAND_RADIOBUTTON_SELECTED event handler for ID_RICHTEXTLISTSTYLEPAGE_ALIGNRIGHT
*/
void wxRichTextListStylePage::OnRichtextliststylepageAlignrightSelected( wxCommandEvent& WXUNUSED(event) )
{
TransferAndPreview();
}
/*!
* wxEVT_COMMAND_RADIOBUTTON_SELECTED event handler for ID_RICHTEXTLISTSTYLEPAGE_JUSTIFIED
*/
void wxRichTextListStylePage::OnRichtextliststylepageJustifiedSelected( wxCommandEvent& WXUNUSED(event) )
{
TransferAndPreview();
}
/*!
* wxEVT_COMMAND_RADIOBUTTON_SELECTED event handler for ID_RICHTEXTLISTSTYLEPAGE_CENTERED
*/
void wxRichTextListStylePage::OnRichtextliststylepageCenteredSelected( wxCommandEvent& WXUNUSED(event) )
{
TransferAndPreview();
}
/*!
* wxEVT_COMMAND_RADIOBUTTON_SELECTED event handler for ID_RICHTEXTLISTSTYLEPAGE_ALIGNINDETERMINATE
*/
void wxRichTextListStylePage::OnRichtextliststylepageAlignindeterminateSelected( wxCommandEvent& WXUNUSED(event) )
{
TransferAndPreview();
}
/*!
* wxEVT_COMMAND_TEXT_UPDATED event handler for ID_RICHTEXTLISTSTYLEPAGE_INDENTLEFT
*/
void wxRichTextListStylePage::OnIndentLeftUpdated( wxCommandEvent& WXUNUSED(event) )
{
TransferAndPreview();
}
/*!
* wxEVT_COMMAND_TEXT_UPDATED event handler for ID_RICHTEXTLISTSTYLEPAGE_INDENTFIRSTLINE
*/
void wxRichTextListStylePage::OnIndentFirstLineUpdated( wxCommandEvent& WXUNUSED(event) )
{
TransferAndPreview();
}
/*!
* wxEVT_COMMAND_TEXT_UPDATED event handler for ID_RICHTEXTLISTSTYLEPAGE_INDENTRIGHT
*/
void wxRichTextListStylePage::OnIndentRightUpdated( wxCommandEvent& WXUNUSED(event) )
{
TransferAndPreview();
}
/*!
* wxEVT_COMMAND_TEXT_UPDATED event handler for ID_RICHTEXTLISTSTYLEPAGE_SPACINGBEFORE
*/
void wxRichTextListStylePage::OnSpacingBeforeUpdated( wxCommandEvent& WXUNUSED(event) )
{
TransferAndPreview();
}
/*!
* wxEVT_COMMAND_TEXT_UPDATED event handler for ID_RICHTEXTLISTSTYLEPAGE_SPACINGAFTER
*/
void wxRichTextListStylePage::OnSpacingAfterUpdated( wxCommandEvent& WXUNUSED(event) )
{
TransferAndPreview();
}
/*!
* wxEVT_COMMAND_COMBOBOX_SELECTED event handler for ID_RICHTEXTLISTSTYLEPAGE_LINESPACING
*/
void wxRichTextListStylePage::OnLineSpacingSelected( wxCommandEvent& WXUNUSED(event) )
{
TransferAndPreview();
}
/*!
* Should we show tooltips?
*/
bool wxRichTextListStylePage::ShowToolTips()
{
return wxRichTextFormattingDialog::ShowToolTips();
}
/*!
* Get bitmap resources
*/
wxBitmap wxRichTextListStylePage::GetBitmapResource( const wxString& name )
{
// Bitmap retrieval
////@begin wxRichTextListStylePage bitmap retrieval
wxUnusedVar(name);
return wxNullBitmap;
////@end wxRichTextListStylePage bitmap retrieval
}
/*!
* Get icon resources
*/
wxIcon wxRichTextListStylePage::GetIconResource( const wxString& name )
{
// Icon retrieval
////@begin wxRichTextListStylePage icon retrieval
wxUnusedVar(name);
return wxNullIcon;
////@end wxRichTextListStylePage icon retrieval
}
/// Update for symbol-related controls
void wxRichTextListStylePage::OnSymbolUpdate( wxUpdateUIEvent& event )
{
int sel = m_styleListBox->GetSelection();
event.Enable(sel == wxRICHTEXT_BULLETINDEX_SYMBOL);
}
/// Update for number-related controls
void wxRichTextListStylePage::OnNumberUpdate( wxUpdateUIEvent& event )
{
int sel = m_styleListBox->GetSelection();
event.Enable((sel != wxRICHTEXT_BULLETINDEX_SYMBOL &&
sel != wxRICHTEXT_BULLETINDEX_BITMAP &&
sel != wxRICHTEXT_BULLETINDEX_STANDARD &&
sel != wxRICHTEXT_BULLETINDEX_NONE));
}
/// Update for standard bullet-related controls
void wxRichTextListStylePage::OnStandardBulletUpdate( wxUpdateUIEvent& event )
{
int sel = m_styleListBox->GetSelection();
event.Enable( sel == wxRICHTEXT_BULLETINDEX_STANDARD );
}
/*!
* wxEVT_COMMAND_BUTTON_CLICKED event handler for ID_RICHTEXTLISTSTYLEPAGE_CHOOSE_FONT
*/
void wxRichTextListStylePage::OnChooseFontClick( wxCommandEvent& WXUNUSED(event) )
{
wxTextAttr* attr = GetAttributesForSelection();
int pages = wxRICHTEXT_FORMAT_FONT;
wxRichTextFormattingDialog formatDlg;
formatDlg.SetStyle(*attr, false);
formatDlg.Create(pages, this);
if (formatDlg.ShowModal() == wxID_OK)
{
(*attr) = formatDlg.GetAttributes();
TransferAndPreview();
}
}
/*!
* wxEVT_UPDATE_UI event handler for ID_RICHTEXTLISTSTYLEPAGE_NAMESTATIC
*/
void wxRichTextListStylePage::OnNamestaticUpdate( wxUpdateUIEvent& event )
{
OnStandardBulletUpdate(event);
}
/*!
* wxEVT_COMMAND_COMBOBOX_SELECTED event handler for ID_RICHTEXTLISTSTYLEPAGE_NAMECTRL
*/
void wxRichTextListStylePage::OnNamectrlSelected( wxCommandEvent& WXUNUSED(event) )
{
TransferAndPreview();
}
/*!
* wxEVT_COMMAND_TEXT_UPDATED event handler for ID_RICHTEXTLISTSTYLEPAGE_NAMECTRL
*/
void wxRichTextListStylePage::OnNamectrlUpdated( wxCommandEvent& WXUNUSED(event) )
{
TransferAndPreview();
}
/*!
* wxEVT_UPDATE_UI event handler for ID_RICHTEXTLISTSTYLEPAGE_NAMECTRL
*/
void wxRichTextListStylePage::OnNamectrlUIUpdate( wxUpdateUIEvent& event )
{
OnStandardBulletUpdate(event);
}
/*!
* wxEVT_COMMAND_CHECKBOX_CLICKED event handler for ID_RICHTEXTLISTSTYLEPAGE_RIGHTPARENTHESISCTRL
*/
void wxRichTextListStylePage::OnRightParenthesisCtrlClick( wxCommandEvent& WXUNUSED(event) )
{
TransferAndPreview();
}
/*!
* wxEVT_UPDATE_UI event handler for ID_RICHTEXTLISTSTYLEPAGE_RIGHTPARENTHESISCTRL
*/
void wxRichTextListStylePage::OnRightParenthesisCtrlUpdate( wxUpdateUIEvent& event )
{
int sel = m_styleListBox->GetSelection();
event.Enable((sel != wxRICHTEXT_BULLETINDEX_SYMBOL &&
sel != wxRICHTEXT_BULLETINDEX_BITMAP &&
sel != wxRICHTEXT_BULLETINDEX_NONE));
}
/*!
* wxEVT_COMMAND_COMBOBOX_SELECTED event handler for ID_RICHTEXTLISTSTYLEPAGE_BULLETALIGNMENTCTRL
*/
void wxRichTextListStylePage::OnBulletAlignmentCtrlSelected( wxCommandEvent& WXUNUSED(event) )
{
TransferAndPreview();
}
| 39.202643 | 196 | 0.725625 | gamekit-developers |
28a8244d55fdf91d8eb3dc77167e6b9cb62f5c81 | 5,684 | cc | C++ | ge/graph/passes/replace_transshape_pass.cc | tomzhang/graphengine | 49aa7bb17b371caf58a871172fc53afc31b8022c | [
"Apache-2.0"
] | null | null | null | ge/graph/passes/replace_transshape_pass.cc | tomzhang/graphengine | 49aa7bb17b371caf58a871172fc53afc31b8022c | [
"Apache-2.0"
] | null | null | null | ge/graph/passes/replace_transshape_pass.cc | tomzhang/graphengine | 49aa7bb17b371caf58a871172fc53afc31b8022c | [
"Apache-2.0"
] | null | null | null | /**
* Copyright 2019-2020 Huawei Technologies Co., Ltd
*
* 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 "graph/passes/replace_transshape_pass.h"
#include <string>
#include "common/ge/ge_util.h"
#include "common/ge_inner_error_codes.h"
#include "framework/common/debug/ge_log.h"
#include "graph/common/omg_util.h"
#include "graph/utils/graph_utils.h"
namespace ge {
Status ReplaceTransShapePass::Run(ge::ComputeGraphPtr graph) {
GE_CHECK_NOTNULL(graph);
for (auto &node : graph->GetDirectNode()) {
if (node->GetType() == TRANSSHAPE) {
auto ret = ReplaceTransShapeNode(graph, node);
if (ret != SUCCESS) {
GELOGE(FAILED, "Trans shape node %s failed", node->GetName().c_str());
return FAILED;
}
}
}
return SUCCESS;
}
Status ReplaceTransShapePass::ReplaceTransShapeNode(ComputeGraphPtr &graph, NodePtr &trans_shape_node) {
std::string op_type;
auto ret = GetOriginalType(trans_shape_node, op_type);
if (ret != SUCCESS) {
GELOGE(FAILED, "Get node %s original type failede", trans_shape_node->GetName().c_str());
return FAILED;
}
auto src_op_desc = trans_shape_node->GetOpDesc();
GE_CHECK_NOTNULL(src_op_desc);
std::string node_name = trans_shape_node->GetName() + "ToMemcpy";
auto dst_op_desc = MakeShared<OpDesc>(node_name, MEMCPYASYNC);
if (dst_op_desc == nullptr) {
GELOGE(FAILED, "Make node %s opdesc failed", node_name.c_str());
return FAILED;
}
GELOGI("Create memcpy Op, name=%s.", node_name.c_str());
for (InDataAnchorPtr &in_anchor : trans_shape_node->GetAllInDataAnchors()) {
auto ret = dst_op_desc->AddInputDesc(src_op_desc->GetInputDesc(in_anchor->GetIdx()));
if (ret != GRAPH_SUCCESS) {
GELOGE(FAILED, "Add input desc failed");
return FAILED;
}
}
for (OutDataAnchorPtr &out_anchor : trans_shape_node->GetAllOutDataAnchors()) {
auto ret = dst_op_desc->AddOutputDesc(src_op_desc->GetOutputDesc(out_anchor->GetIdx()));
if (ret != GRAPH_SUCCESS) {
GELOGE(FAILED, "Add output desc failed");
return FAILED;
}
}
NodePtr memcpy_node = graph->AddNode(dst_op_desc);
GE_CHECK_NOTNULL(memcpy_node);
for (InDataAnchorPtr &in_data_anchor : trans_shape_node->GetAllInDataAnchors()) {
OutDataAnchorPtr peer_out_anchor = in_data_anchor->GetPeerOutAnchor();
GE_IF_BOOL_EXEC(peer_out_anchor == nullptr, continue);
GE_CHK_STATUS(GraphUtils::RemoveEdge(peer_out_anchor, in_data_anchor), "Remove Memcpy data input fail.");
GE_CHK_STATUS(GraphUtils::AddEdge(peer_out_anchor, memcpy_node->GetInDataAnchor(in_data_anchor->GetIdx())),
"Memcpy node add edge fail.");
}
for (OutDataAnchorPtr &out_data_anchor : trans_shape_node->GetAllOutDataAnchors()) {
for (InDataAnchorPtr &peer_in_anchor : out_data_anchor->GetPeerInDataAnchors()) {
GE_CHK_STATUS(GraphUtils::RemoveEdge(out_data_anchor, peer_in_anchor), "Remove Memcpy data output fail.");
GE_CHK_STATUS(GraphUtils::AddEdge(memcpy_node->GetOutDataAnchor(out_data_anchor->GetIdx()), peer_in_anchor),
"Memcpy node add edge fail.");
}
}
ReplaceControlEdges(trans_shape_node, memcpy_node);
return SUCCESS;
}
void ReplaceTransShapePass::CopyControlEdges(NodePtr &old_node, NodePtr &new_node, bool input_check_flag) {
GE_CHECK_NOTNULL_JUST_RETURN(old_node);
GE_CHECK_NOTNULL_JUST_RETURN(new_node);
GE_IF_BOOL_EXEC(old_node == new_node, return );
for (NodePtr &node : old_node->GetInControlNodes()) {
auto out_control_anchor = node->GetOutControlAnchor();
GE_IF_BOOL_EXEC(!out_control_anchor->IsLinkedWith(new_node->GetInControlAnchor()), {
GE_CHK_STATUS(GraphUtils::AddEdge(out_control_anchor, new_node->GetInControlAnchor()), "Add in ctl edge fail.");
});
}
for (NodePtr &node : old_node->GetOutControlNodes()) {
GE_IF_BOOL_EXEC(!new_node->GetOutControlAnchor()->IsLinkedWith(node->GetInControlAnchor()), {
GE_CHK_STATUS(GraphUtils::AddEdge(new_node->GetOutControlAnchor(), node->GetInControlAnchor()),
"Add out ctl edge fail.");
});
}
}
void ReplaceTransShapePass::RemoveControlEdges(NodePtr &node) {
GE_CHECK_NOTNULL_JUST_RETURN(node);
for (NodePtr &in_node : node->GetInControlNodes()) {
GE_CHK_STATUS(GraphUtils::RemoveEdge(in_node->GetOutControlAnchor(), node->GetInControlAnchor()),
"Remove in ctl edge fail.");
}
for (auto &out_data_anchor : node->GetAllOutDataAnchors()) {
for (auto &in_ctrl_anchor : out_data_anchor->GetPeerInControlAnchors()) {
GE_CHK_STATUS(GraphUtils::RemoveEdge(out_data_anchor, in_ctrl_anchor), "Remove in ctl edge fail.");
}
}
auto out_control_anchor = node->GetOutControlAnchor();
GE_CHECK_NOTNULL_JUST_RETURN(out_control_anchor);
for (auto &peer_anchor : out_control_anchor->GetPeerAnchors()) {
GE_CHK_STATUS(GraphUtils::RemoveEdge(out_control_anchor, peer_anchor), "Remove out ctl edge fail.");
}
}
void ReplaceTransShapePass::ReplaceControlEdges(NodePtr &old_node, NodePtr &new_node) {
GE_IF_BOOL_EXEC(old_node == new_node, return );
CopyControlEdges(old_node, new_node);
RemoveControlEdges(old_node);
}
} // namespace ge
| 40.312057 | 118 | 0.728184 | tomzhang |
28a89cc05ba03d2d9c9aee54301e3f00a7fdc05f | 5,259 | hpp | C++ | src/include/duckdb/main/query_result.hpp | AldoMyrtaj/duckdb | 3aa4978a2ceab8df25e4b20c388bcd7629de73ed | [
"MIT"
] | 2,816 | 2018-06-26T18:52:52.000Z | 2021-04-06T10:39:15.000Z | src/include/duckdb/main/query_result.hpp | AldoMyrtaj/duckdb | 3aa4978a2ceab8df25e4b20c388bcd7629de73ed | [
"MIT"
] | 1,310 | 2021-04-06T16:04:52.000Z | 2022-03-31T13:52:53.000Z | src/include/duckdb/main/query_result.hpp | AldoMyrtaj/duckdb | 3aa4978a2ceab8df25e4b20c388bcd7629de73ed | [
"MIT"
] | 270 | 2021-04-09T06:18:28.000Z | 2022-03-31T11:55:37.000Z | //===----------------------------------------------------------------------===//
// DuckDB
//
// duckdb/main/query_result.hpp
//
//
//===----------------------------------------------------------------------===//
#pragma once
#include "duckdb/common/enums/statement_type.hpp"
#include "duckdb/common/types/data_chunk.hpp"
#include "duckdb/common/winapi.hpp"
struct ArrowSchema;
namespace duckdb {
enum class QueryResultType : uint8_t { MATERIALIZED_RESULT, STREAM_RESULT, PENDING_RESULT };
class BaseQueryResult {
public:
//! Creates a successful empty query result
DUCKDB_API BaseQueryResult(QueryResultType type, StatementType statement_type);
//! Creates a successful query result with the specified names and types
DUCKDB_API BaseQueryResult(QueryResultType type, StatementType statement_type, vector<LogicalType> types,
vector<string> names);
//! Creates an unsuccessful query result with error condition
DUCKDB_API BaseQueryResult(QueryResultType type, string error);
DUCKDB_API virtual ~BaseQueryResult();
//! The type of the result (MATERIALIZED or STREAMING)
QueryResultType type;
//! The type of the statement that created this result
StatementType statement_type;
//! The SQL types of the result
vector<LogicalType> types;
//! The names of the result
vector<string> names;
//! Whether or not execution was successful
bool success;
//! The error string (in case execution was not successful)
string error;
public:
DUCKDB_API bool HasError();
DUCKDB_API const string &GetError();
DUCKDB_API idx_t ColumnCount();
};
//! The QueryResult object holds the result of a query. It can either be a MaterializedQueryResult, in which case the
//! result contains the entire result set, or a StreamQueryResult in which case the Fetch method can be called to
//! incrementally fetch data from the database.
class QueryResult : public BaseQueryResult {
public:
//! Creates a successful empty query result
DUCKDB_API QueryResult(QueryResultType type, StatementType statement_type);
//! Creates a successful query result with the specified names and types
DUCKDB_API QueryResult(QueryResultType type, StatementType statement_type, vector<LogicalType> types,
vector<string> names);
//! Creates an unsuccessful query result with error condition
DUCKDB_API QueryResult(QueryResultType type, string error);
DUCKDB_API virtual ~QueryResult() override;
//! The next result (if any)
unique_ptr<QueryResult> next;
public:
//! Fetches a DataChunk of normalized (flat) vectors from the query result.
//! Returns nullptr if there are no more results to fetch.
DUCKDB_API virtual unique_ptr<DataChunk> Fetch();
//! Fetches a DataChunk from the query result. The vectors are not normalized and hence any vector types can be
//! returned.
DUCKDB_API virtual unique_ptr<DataChunk> FetchRaw() = 0;
//! Converts the QueryResult to a string
DUCKDB_API virtual string ToString() = 0;
//! Prints the QueryResult to the console
DUCKDB_API void Print();
//! Returns true if the two results are identical; false otherwise. Note that this method is destructive; it calls
//! Fetch() until both results are exhausted. The data in the results will be lost.
DUCKDB_API bool Equals(QueryResult &other);
DUCKDB_API bool TryFetch(unique_ptr<DataChunk> &result, string &error) {
try {
result = Fetch();
return success;
} catch (std::exception &ex) {
error = ex.what();
return false;
} catch (...) {
error = "Unknown error in Fetch";
return false;
}
}
DUCKDB_API void ToArrowSchema(ArrowSchema *out_array);
private:
//! The current chunk used by the iterator
unique_ptr<DataChunk> iterator_chunk;
private:
class QueryResultIterator;
class QueryResultRow {
public:
explicit QueryResultRow(QueryResultIterator &iterator) : iterator(iterator), row(0) {
}
QueryResultIterator &iterator;
idx_t row;
template <class T>
T GetValue(idx_t col_idx) const {
return iterator.result->iterator_chunk->GetValue(col_idx, iterator.row_idx).GetValue<T>();
}
};
//! The row-based query result iterator. Invoking the
class QueryResultIterator {
public:
explicit QueryResultIterator(QueryResult *result) : current_row(*this), result(result), row_idx(0) {
if (result) {
result->iterator_chunk = result->Fetch();
}
}
QueryResultRow current_row;
QueryResult *result;
idx_t row_idx;
public:
void Next() {
if (!result->iterator_chunk) {
return;
}
current_row.row++;
row_idx++;
if (row_idx >= result->iterator_chunk->size()) {
result->iterator_chunk = result->Fetch();
row_idx = 0;
}
}
QueryResultIterator &operator++() {
Next();
return *this;
}
bool operator!=(const QueryResultIterator &other) const {
return result->iterator_chunk && result->iterator_chunk->ColumnCount() > 0;
}
const QueryResultRow &operator*() const {
return current_row;
}
};
public:
DUCKDB_API QueryResultIterator begin() {
return QueryResultIterator(this);
}
DUCKDB_API QueryResultIterator end() {
return QueryResultIterator(nullptr);
}
protected:
DUCKDB_API string HeaderToString();
private:
QueryResult(const QueryResult &) = delete;
};
} // namespace duckdb | 30.935294 | 117 | 0.711542 | AldoMyrtaj |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.