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 109 | max_stars_repo_head_hexsha stringlengths 40 40 | max_stars_repo_licenses listlengths 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 listlengths 1 9 | max_issues_count int64 1 48.5k ⌀ | 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 listlengths 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 |
|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|
c450fac68fa8df9625a6f1af5e900b7cee05546e | 424 | cpp | C++ | tests/src/string_ifind.cpp | scaryrawr/mtl | eea8e9c6662b613dc5098a2cb442a7b1522bf8f0 | [
"MIT"
] | null | null | null | tests/src/string_ifind.cpp | scaryrawr/mtl | eea8e9c6662b613dc5098a2cb442a7b1522bf8f0 | [
"MIT"
] | null | null | null | tests/src/string_ifind.cpp | scaryrawr/mtl | eea8e9c6662b613dc5098a2cb442a7b1522bf8f0 | [
"MIT"
] | null | null | null | #include <mtl/string.hpp>
#include <gtest/gtest.h>
TEST(StringIFind, RawString)
{
const char *str{"Hello World"};
ASSERT_EQ(mtl::string::ifind(str, "world"), 6);
}
TEST(StringIFind, BasicString)
{
std::string str{"Hello World"};
ASSERT_EQ(mtl::string::ifind(str, "world"), 6);
}
TEST(StringIFind, StringView)
{
std::string_view str{"Hello World"};
ASSERT_EQ(mtl::string::ifind(str, "world"), 6);
} | 21.2 | 51 | 0.658019 | scaryrawr |
c452f423deb6313cd02bcba1fc8e104f0091c11e | 30 | hpp | C++ | src/boost_mpl_next.hpp | miathedev/BoostForArduino | 919621dcd0c157094bed4df752b583ba6ea6409e | [
"BSL-1.0"
] | 10 | 2018-03-17T00:58:42.000Z | 2021-07-06T02:48:49.000Z | src/boost_mpl_next.hpp | miathedev/BoostForArduino | 919621dcd0c157094bed4df752b583ba6ea6409e | [
"BSL-1.0"
] | 2 | 2021-03-26T15:17:35.000Z | 2021-05-20T23:55:08.000Z | src/boost_mpl_next.hpp | miathedev/BoostForArduino | 919621dcd0c157094bed4df752b583ba6ea6409e | [
"BSL-1.0"
] | 4 | 2019-05-28T21:06:37.000Z | 2021-07-06T03:06:52.000Z | #include <boost/mpl/next.hpp>
| 15 | 29 | 0.733333 | miathedev |
c4545d26f42e20282c276664e20c31c163072b06 | 10,794 | cc | C++ | lite/kernels/apu/bridges/elementwise_ops.cc | wanglei91/Paddle-Lite | 8b2479f4cdd6970be507203d791bede5a453c09d | [
"Apache-2.0"
] | 1,799 | 2019-08-19T03:29:38.000Z | 2022-03-31T14:30:50.000Z | lite/kernels/apu/bridges/elementwise_ops.cc | wanglei91/Paddle-Lite | 8b2479f4cdd6970be507203d791bede5a453c09d | [
"Apache-2.0"
] | 3,767 | 2019-08-19T03:36:04.000Z | 2022-03-31T14:37:26.000Z | lite/kernels/apu/bridges/elementwise_ops.cc | wanglei91/Paddle-Lite | 8b2479f4cdd6970be507203d791bede5a453c09d | [
"Apache-2.0"
] | 798 | 2019-08-19T02:28:23.000Z | 2022-03-31T08:31:54.000Z | // Copyright (c) 2019 PaddlePaddle Authors. All Rights Reserved.
//
// Licensed under the Apache License, Version 2.0 (the "License");
// you may not use this file except in compliance with the License.
// 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 "lite/core/subgraph/subgraph_bridge_registry.h"
#include "lite/kernels/apu/bridges/graph.h"
#include "lite/kernels/apu/bridges/utility.h"
namespace paddle {
namespace lite {
namespace subgraph {
namespace apu {
int ElementwiseConverter(void* ctx, OpLite* op, KernelBase* kernel) {
CHECK(ctx != nullptr);
CHECK(op != nullptr);
auto graph = static_cast<Graph*>(ctx);
auto model = graph->model();
auto op_info = op->op_info();
auto op_type = op_info->Type();
auto scope = op->scope();
int neuron_errCode;
VLOG(3) << "[APU] Converting [" + op_type + "]";
// Get input and output vars and op attributes
auto x_name = op_info->Input("X").front();
auto x_scale_name = "X0_scale";
auto x = scope->FindTensor(x_name);
auto x_dims = x->dims();
auto y_name = op_info->Input("Y").front();
auto y_scale_name = "Y0_scale";
auto y = scope->FindTensor(y_name);
auto y_dims = y->dims();
auto out_name = op_info->Output("Out").front();
auto out_scale_name = "Out0_scale";
auto out = scope->FindTensor(out_name);
auto out_dims = out->dims();
auto axis = op_info->GetAttr<int>("axis");
if (axis < 0) {
axis = x_dims.size() - y_dims.size();
}
auto x_shape = x_dims.Vectorize();
auto y_shape = y_dims.Vectorize();
// Two dimensions are compatible when:
// 1. they are equal, or
// 2. one of them is 1
for (int i = axis; i < x_shape.size(); i++) {
if (x_dims[i] != y_dims[i - axis]) {
// Input 1 compatible dimensions as input0
if (y_dims[i - axis] != 1) {
LOG(WARNING) << i << ":" << axis << ":" << y_dims[i - axis];
return FAILED;
}
}
} // End of for
int32_t fuse_val[1] = {NEURON_FUSED_NONE};
// Act node
if (op_type == "fusion_elementwise_add_activation" ||
op_type == "fusion_elementwise_sub_activation" ||
op_type == "fusion_elementwise_mul_activation" ||
op_type == "fusion_elementwise_div_activation") {
auto act_type = op_info->GetAttr<std::string>("act_type");
if (act_type == "relu") {
fuse_val[0] = NEURON_FUSED_RELU;
} else if (act_type == "relu1") {
fuse_val[0] = NEURON_FUSED_RELU1;
} else if (act_type == "relu6") {
fuse_val[0] = NEURON_FUSED_RELU6;
} else if (!act_type.empty()) {
fuse_val[0] = NEURON_FUSED_NONE;
LOG(WARNING) << "Support act_type: " << act_type;
return FAILED;
}
} // End of if
VLOG(3) << "x_name" << x_name;
CHECK(op_info->HasInputScale(x_scale_name, true));
auto x_scale = op_info->GetInputScale(x_scale_name, true)[0];
CHECK(op_info->HasInputScale(y_scale_name, true));
auto y_scale = op_info->GetInputScale(y_scale_name, true)[0];
CHECK(op_info->HasOutputScale(out_scale_name, true));
auto out_scale = op_info->GetOutputScale(out_scale_name, true)[0];
// Add x tensor type
NeuronOperandType xType;
xType.type = NEURON_TENSOR_QUANT8_ASYMM;
xType.scale = x_scale;
xType.zeroPoint = 128;
xType.dimensionCount = x_dims.size();
std::vector<uint32_t> dims_x = {(uint32_t)x_dims[0],
(uint32_t)x_dims[2],
(uint32_t)x_dims[3],
(uint32_t)x_dims[1]};
xType.dimensions = &dims_x[0];
std::shared_ptr<Node> x_node = nullptr;
if (graph->Has(x_name)) {
VLOG(3) << "Graph has " << x_name;
if (graph->IsInput(x_name)) {
VLOG(3) << x_name << "is input and already exist";
x_name = "transpose_" + x_name;
}
if (graph->IsOutput(x_name)) {
VLOG(3) << x_name << "is input and output node";
x_name = "transpose_" + x_name;
}
x_node = graph->Get(x_name);
} else {
if (graph->IsInput(x_name)) {
insert_transpose_node(ctx,
x_name,
"transpose_" + x_name,
{(uint32_t)x_dims[0],
(uint32_t)x_dims[1],
(uint32_t)x_dims[2],
(uint32_t)x_dims[3]},
dims_x,
{0, 2, 3, 1},
xType.scale,
xType.zeroPoint);
// Change x name after insert transpose op for x data relayout
x_name = "transpose_" + x_name;
x_node = graph->Get(x_name);
} else {
NeuronModel_addOperand(model, &xType);
x_node = graph->Add(x_name, dims_x);
}
} // End of else
VLOG(3) << "x node idx: " << x_node->index() << "x_dims: " << x_dims
<< ": x_scale: " << x_scale << ", xType: " << xType.dimensions[0]
<< ":" << xType.dimensions[1] << ":" << xType.dimensions[2] << ":"
<< xType.dimensions[3];
// Add y tensor type
NeuronOperandType yType;
yType.type = NEURON_TENSOR_QUANT8_ASYMM;
yType.scale = y_scale;
yType.zeroPoint = 128;
yType.dimensionCount = y_dims.size();
std::vector<uint32_t> dims_y = {(uint32_t)y_dims[0],
(uint32_t)y_dims[2],
(uint32_t)y_dims[3],
(uint32_t)y_dims[1]};
yType.dimensions = &dims_y[0];
std::shared_ptr<Node> y_node = nullptr;
if (graph->Has(y_name)) {
VLOG(3) << "Graph has " << y_name;
y_node = graph->Get(y_name);
} else {
if (graph->IsInput(y_name)) {
insert_transpose_node(ctx,
y_name,
"transpose_" + y_name,
{(uint32_t)y_dims[0],
(uint32_t)y_dims[1],
(uint32_t)y_dims[2],
(uint32_t)y_dims[3]},
dims_y,
{0, 2, 3, 1},
yType.scale,
yType.zeroPoint);
y_name = "transpose_" + y_name;
y_node = graph->Get(y_name);
} else {
NeuronModel_addOperand(model, &yType);
y_node = graph->Add(y_name, dims_y);
}
}
VLOG(3) << "y node idx: " << y_node->index() << "y_dims: " << y_dims
<< ": y_scale: " << y_scale << ", yType: " << yType.dimensions[0]
<< ":" << yType.dimensions[1] << ":" << yType.dimensions[2] << ":"
<< yType.dimensions[3];
// Add fuse operand type
NeuronOperandType int32Type;
int32Type.type = NEURON_INT32;
int32Type.dimensionCount = 0;
std::vector<uint32_t> dims_int32 = {1};
// Add fuse operand
std::shared_ptr<Node> fuse_node = nullptr;
NeuronModel_addOperand(model, &int32Type); // Operand 2: fuse
fuse_node = graph->Add(out_name + "_fuse", dims_int32);
// Add out tensor type
NeuronOperandType outType;
outType.type = NEURON_TENSOR_QUANT8_ASYMM;
outType.scale = out_scale;
outType.zeroPoint = 128;
outType.dimensionCount = out_dims.size();
std::vector<uint32_t> dims_out = {(uint32_t)out_dims[0],
(uint32_t)out_dims[2],
(uint32_t)out_dims[3],
(uint32_t)out_dims[1]};
outType.dimensions = &dims_out[0];
std::shared_ptr<Node> out_node = nullptr;
if (graph->Has(out_name)) {
VLOG(3) << "Graph has " << out_name;
out_node = graph->Get(out_name);
} else {
if (graph->IsOutput(out_name)) {
NeuronModel_addOperand(model, &outType);
out_node = graph->Add("transpose_" + out_name, dims_out);
} else {
NeuronModel_addOperand(model, &outType);
out_node = graph->Add(out_name, dims_out);
}
}
VLOG(3) << "out node idx: " << out_node->index() << "out_dims: " << out_dims
<< ": out_scale: " << out_scale
<< ", outType: " << outType.dimensions[0] << ":"
<< outType.dimensions[1] << ":" << outType.dimensions[2] << ":"
<< outType.dimensions[3];
// Set fuse value
NeuronModel_setOperandValue(
model, fuse_node->index(), fuse_val, sizeof(int32_t) * 1);
std::vector<uint32_t> addInIndex = {
x_node->index(), // 0: A tensor
y_node->index(), // 1: A tensor of the same OperandCode,
// and compatible dimensions as input 0
fuse_node->index()}; // 2: fuse
std::vector<uint32_t> addOutIndex = {out_node->index()};
if (op_type == "elementwise_add" ||
op_type == "fusion_elementwise_add_activation") {
neuron_errCode = NeuronModel_addOperation(model,
NEURON_ADD,
addInIndex.size(),
&addInIndex[0],
addOutIndex.size(),
&addOutIndex[0]);
} else {
LOG(WARNING) << "[APU] Unsupported op type: " << op_type;
return FAILED;
}
if (NEURON_NO_ERROR != neuron_errCode) {
LOG(WARNING) << "ADD op fail:" << op_type;
return FAILED;
}
if (graph->IsOutput(out_name)) {
// Insert transpose for NHWC -> NCHW
insert_transpose_node(ctx,
"transpose_" + out_name,
out_name,
dims_out,
{(uint32_t)out_dims[0],
(uint32_t)out_dims[1],
(uint32_t)out_dims[2],
(uint32_t)out_dims[3]},
{0, 3, 1, 2},
outType.scale,
outType.zeroPoint);
out_node = graph->Get(out_name);
if (out_node == nullptr) return FAILED;
}
return REBUILD_WHEN_SHAPE_CHANGED;
}
} // namespace apu
} // namespace subgraph
} // namespace lite
} // namespace paddle
REGISTER_SUBGRAPH_BRIDGE(elementwise_add,
kAPU,
paddle::lite::subgraph::apu::ElementwiseConverter);
REGISTER_SUBGRAPH_BRIDGE(elementwise_mul,
kAPU,
paddle::lite::subgraph::apu::ElementwiseConverter);
REGISTER_SUBGRAPH_BRIDGE(fusion_elementwise_add_activation,
kAPU,
paddle::lite::subgraph::apu::ElementwiseConverter);
| 35.98 | 78 | 0.55642 | wanglei91 |
c459882e7b80214d0930a4a7dea9843803f5011d | 6,872 | hpp | C++ | examples/select/select.hpp | stevenybw/thrill | a2dc05035f4e24f64af0a22b60155e80843a5ba9 | [
"BSD-2-Clause"
] | 609 | 2015-08-27T11:09:24.000Z | 2022-03-28T21:34:05.000Z | examples/select/select.hpp | tim3z/thrill | f0e5aa2326a55af3c9a92fc418f8eb8e3cf8c5fa | [
"BSD-2-Clause"
] | 109 | 2015-09-10T21:34:42.000Z | 2022-02-15T14:46:26.000Z | examples/select/select.hpp | tim3z/thrill | f0e5aa2326a55af3c9a92fc418f8eb8e3cf8c5fa | [
"BSD-2-Clause"
] | 114 | 2015-08-27T14:54:13.000Z | 2021-12-08T07:28:35.000Z | /*******************************************************************************
* examples/select/select.hpp
*
* Part of Project Thrill - http://project-thrill.org
*
* Copyright (C) 2016 Lorenz Hübschle-Schneider <[email protected]>
*
* All rights reserved. Published under the BSD-2 license in the LICENSE file.
******************************************************************************/
#pragma once
#ifndef THRILL_EXAMPLES_SELECT_SELECT_HEADER
#define THRILL_EXAMPLES_SELECT_SELECT_HEADER
#include <thrill/api/bernoulli_sample.hpp>
#include <thrill/api/collapse.hpp>
#include <thrill/api/dia.hpp>
#include <thrill/api/gather.hpp>
#include <thrill/api/size.hpp>
#include <thrill/api/sum.hpp>
#include <thrill/common/logger.hpp>
#include <algorithm>
#include <cmath>
#include <functional>
#include <utility>
namespace examples {
namespace select {
using namespace thrill; // NOLINT
static constexpr bool debug = false;
static constexpr double delta = 0.1; // 0 < delta < 0.25
static constexpr size_t base_case_size = 1024;
#define LOGM LOGC(debug && ctx.my_rank() == 0)
template <typename ValueType, typename InStack,
typename Compare = std::less<ValueType> >
std::pair<ValueType, ValueType>
PickPivots(const DIA<ValueType, InStack>& data, size_t size, size_t rank,
const Compare& compare = Compare()) {
api::Context& ctx = data.context();
const size_t num_workers(ctx.num_workers());
const double size_d = static_cast<double>(size);
const double p = 20 * sqrt(static_cast<double>(num_workers)) / size_d;
// materialized at worker 0
auto sample = data.Keep().BernoulliSample(p).Gather();
std::pair<ValueType, ValueType> pivots;
if (ctx.my_rank() == 0) {
LOG << "got " << sample.size() << " samples (p = " << p << ")";
// Sort the samples
std::sort(sample.begin(), sample.end(), compare);
const double base_pos =
static_cast<double>(rank * sample.size()) / size_d;
const double offset = pow(size_d, 0.25 + delta);
long lower_pos = static_cast<long>(floor(base_pos - offset));
long upper_pos = static_cast<long>(floor(base_pos + offset));
size_t lower = static_cast<size_t>(std::max(0L, lower_pos));
size_t upper = static_cast<size_t>(
std::min(upper_pos, static_cast<long>(sample.size() - 1)));
assert(0 <= lower && lower < sample.size());
assert(0 <= upper && upper < sample.size());
LOG << "Selected pivots at positions " << lower << " and " << upper
<< ": " << sample[lower] << " and " << sample[upper];
pivots = std::make_pair(sample[lower], sample[upper]);
}
pivots = ctx.net.Broadcast(pivots);
LOGM << "pivots: " << pivots.first << " and " << pivots.second;
return pivots;
}
template <typename ValueType, typename InStack,
typename Compare = std::less<ValueType> >
ValueType Select(const DIA<ValueType, InStack>& data, size_t rank,
const Compare& compare = Compare()) {
api::Context& ctx = data.context();
const size_t size = data.Keep().Size();
assert(0 <= rank && rank < size);
if (size <= base_case_size) {
// base case, gather all data at worker with rank 0
ValueType result = ValueType();
auto elements = data.Gather();
if (ctx.my_rank() == 0) {
assert(rank < elements.size());
std::nth_element(elements.begin(), elements.begin() + rank,
elements.end(), compare);
result = elements[rank];
LOG << "base case: " << size << " elements remaining, result is "
<< result;
}
result = ctx.net.Broadcast(result);
return result;
}
ValueType left_pivot, right_pivot;
std::tie(left_pivot, right_pivot) = PickPivots(data, size, rank, compare);
size_t left_size, middle_size, right_size;
using PartSizes = std::pair<size_t, size_t>;
std::tie(left_size, middle_size) =
data.Keep().Map(
[&](const ValueType& elem) -> PartSizes {
if (compare(elem, left_pivot))
return PartSizes { 1, 0 };
else if (!compare(right_pivot, elem))
return PartSizes { 0, 1 };
else
return PartSizes { 0, 0 };
})
.Sum(
[](const PartSizes& a, const PartSizes& b) -> PartSizes {
return PartSizes { a.first + b.first, a.second + b.second };
},
PartSizes { 0, 0 });
right_size = size - left_size - middle_size;
LOGM << "left_size = " << left_size << ", middle_size = " << middle_size
<< ", right_size = " << right_size << ", rank = " << rank;
if (rank == left_size) {
// all the elements strictly smaller than the left pivot are on the left
// side -> left_size-th element is the left pivot
LOGM << "result is left pivot: " << left_pivot;
return left_pivot;
}
else if (rank == left_size + middle_size - 1) {
// only the elements strictly greater than the right pivot are on the
// right side, so the result is the right pivot in this case
LOGM << "result is right pivot: " << right_pivot;
return right_pivot;
}
else if (rank < left_size) {
// recurse on the left partition
LOGM << "Recursing left, " << left_size
<< " elements remaining (rank = " << rank << ")\n";
auto left = data.Filter(
[&](const ValueType& elem) -> bool {
return compare(elem, left_pivot);
}).Collapse();
return Select(left, rank, compare);
}
else if (left_size + middle_size <= rank) {
// recurse on the right partition
LOGM << "Recursing right, " << right_size
<< " elements remaining (rank = " << rank - left_size - middle_size
<< ")\n";
auto right = data.Filter(
[&](const ValueType& elem) -> bool {
return compare(right_pivot, elem);
}).Collapse();
return Select(right, rank - left_size - middle_size, compare);
}
else {
// recurse on the middle partition
LOGM << "Recursing middle, " << middle_size
<< " elements remaining (rank = " << rank - left_size << ")\n";
auto middle = data.Filter(
[&](const ValueType& elem) -> bool {
return !compare(elem, left_pivot) &&
!compare(right_pivot, elem);
}).Collapse();
return Select(middle, rank - left_size, compare);
}
}
} // namespace select
} // namespace examples
#endif // !THRILL_EXAMPLES_SELECT_SELECT_HEADER
/******************************************************************************/
| 34.532663 | 80 | 0.565192 | stevenybw |
c46636ba7931107aa21b40388ac3342be1672f56 | 5,064 | cpp | C++ | src/RageSurface_Load.cpp | graemephi/etterna | b984fe493d9f7ac84a35af3e6f80f16607aceb09 | [
"MIT"
] | null | null | null | src/RageSurface_Load.cpp | graemephi/etterna | b984fe493d9f7ac84a35af3e6f80f16607aceb09 | [
"MIT"
] | null | null | null | src/RageSurface_Load.cpp | graemephi/etterna | b984fe493d9f7ac84a35af3e6f80f16607aceb09 | [
"MIT"
] | null | null | null | #include "global.h"
#include "ActorUtil.h"
#include "RageFile.h"
#include "RageLog.h"
#include "RageSurface_Load.h"
#include "RageSurface_Load_BMP.h"
#include "RageSurface_Load_GIF.h"
#include "RageSurface_Load_JPEG.h"
#include "RageSurface_Load_PNG.h"
#include "RageUtil.h"
#include <set>
static RageSurface*
TryOpenFile(RString sPath,
bool bHeaderOnly,
RString& error,
RString format,
bool& bKeepTrying)
{
RageSurface* ret = nullptr;
RageSurfaceUtils::OpenResult result;
if (!format.CompareNoCase("png"))
result = RageSurface_Load_PNG(sPath, ret, bHeaderOnly, error);
else if (!format.CompareNoCase("gif"))
result = RageSurface_Load_GIF(sPath, ret, bHeaderOnly, error);
else if (!format.CompareNoCase("jpg") || !format.CompareNoCase("jpeg"))
result = RageSurface_Load_JPEG(sPath, ret, bHeaderOnly, error);
else if (!format.CompareNoCase("bmp"))
result = RageSurface_Load_BMP(sPath, ret, bHeaderOnly, error);
else {
error = "Unsupported format";
bKeepTrying = true;
return nullptr;
}
if (result == RageSurfaceUtils::OPEN_OK) {
ASSERT(ret != nullptr);
return ret;
}
LOG->Trace("Format %s failed: %s", format.c_str(), error.c_str());
/*
* The file failed to open, or failed to read. This indicates a problem
* that will affect all readers, so don't waste time trying more readers.
* (OPEN_IO_ERROR)
*
* Errors fall in two categories:
* OPEN_UNKNOWN_FILE_FORMAT: Data was successfully read from the file, but
* it's the wrong file format. The error message always looks like "unknown
* file format" or "Not Vorbis data"; ignore it so we always give a
* consistent error message, and continue trying other file formats.
*
* OPEN_FATAL_ERROR: Either the file was opened successfully and appears to
* be the correct format, but a fatal format-specific error was encountered
* that will probably not be fixed by using a different reader (for example,
* an Ogg file that doesn't actually contain any audio streams); or the file
* failed to open or read ("I/O error", "permission denied"), in which case
* all other readers will probably fail, too. The returned error is used,
* and no other formats will be tried.
*/
bKeepTrying = (result != RageSurfaceUtils::OPEN_FATAL_ERROR);
switch (result) {
case RageSurfaceUtils::OPEN_UNKNOWN_FILE_FORMAT:
bKeepTrying = true;
error = "Unknown file format";
break;
case RageSurfaceUtils::OPEN_FATAL_ERROR:
/* The file matched, but failed to load. We know it's this type of
* data; don't bother trying the other file types. */
bKeepTrying = false;
break;
default:
break;
}
return nullptr;
}
RageSurface*
RageSurfaceUtils::LoadFile(const RString& sPath,
RString& error,
bool bHeaderOnly)
{
{
RageFile TestOpen;
if (!TestOpen.Open(sPath)) {
error = TestOpen.GetError();
return nullptr;
}
}
set<RString> FileTypes;
vector<RString> const& exts = ActorUtil::GetTypeExtensionList(FT_Bitmap);
for (vector<RString>::const_iterator curr = exts.begin();
curr != exts.end();
++curr) {
FileTypes.insert(*curr);
}
RString format = GetExtension(sPath);
format.MakeLower();
bool bKeepTrying = true;
/* If the extension matches a format, try that first. */
if (FileTypes.find(format) != FileTypes.end()) {
RageSurface* ret =
TryOpenFile(sPath, bHeaderOnly, error, format, bKeepTrying);
if (ret)
return ret;
FileTypes.erase(format);
}
for (set<RString>::iterator it = FileTypes.begin();
bKeepTrying && it != FileTypes.end();
++it) {
RageSurface* ret =
TryOpenFile(sPath, bHeaderOnly, error, *it, bKeepTrying);
if (ret) {
LOG->UserLog("Graphic file", sPath, "is really %s", it->c_str());
return ret;
}
}
return nullptr;
}
/*
* (c) 2004 Glenn Maynard
* All rights reserved.
*
* Permission is hereby granted, free of charge, to any person obtaining a
* copy of this software and associated documentation files (the
* "Software"), to deal in the Software without restriction, including
* without limitation the rights to use, copy, modify, merge, publish,
* distribute, and/or sell copies of the Software, and to permit persons to
* whom the Software is furnished to do so, provided that the above
* copyright notice(s) and this permission notice appear in all copies of
* the Software and that both the above copyright notice(s) and this
* permission notice appear in supporting documentation.
*
* THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS
* OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF
* MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT OF
* THIRD PARTY RIGHTS. IN NO EVENT SHALL THE COPYRIGHT HOLDER OR HOLDERS
* INCLUDED IN THIS NOTICE BE LIABLE FOR ANY CLAIM, OR ANY SPECIAL 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.
*/
| 32.883117 | 77 | 0.720577 | graemephi |
c47621d6b4f0c61a6c33fc2c834f9f42419536c9 | 5,217 | cpp | C++ | OGDF/src/ogdf/fileformats/xml/Lexer.cpp | shahnidhi/MetaCarvel | f3bea5fdbbecec4c9becc6bbdc9585a939eb5481 | [
"MIT"
] | 13 | 2017-12-21T03:35:41.000Z | 2022-01-31T13:45:25.000Z | OGDF/src/ogdf/fileformats/xml/Lexer.cpp | shahnidhi/MetaCarvel | f3bea5fdbbecec4c9becc6bbdc9585a939eb5481 | [
"MIT"
] | 7 | 2017-09-13T01:31:24.000Z | 2021-12-14T00:31:50.000Z | OGDF/src/ogdf/fileformats/xml/Lexer.cpp | shahnidhi/MetaCarvel | f3bea5fdbbecec4c9becc6bbdc9585a939eb5481 | [
"MIT"
] | 15 | 2017-09-07T18:28:55.000Z | 2022-01-18T14:17:43.000Z | /** \file
* \brief Implementation of simple XML lexer.
*
* \author Łukasz Hanuszczak
*
* \par License:
* This file is part of the Open Graph Drawing Framework (OGDF).
*
* \par
* Copyright (C)<br>
* See README.txt in the root directory of the OGDF installation for details.
*
* \par
* This program is free software; you can redistribute it and/or
* modify it under the terms of the GNU General Public License
* Version 2 or 3 as published by the Free Software Foundation;
* see the file LICENSE.txt included in the packaging of this file
* for details.
*
* \par
* 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.
*
* \par
* 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.
*
* \see http://www.gnu.org/copyleft/gpl.html
***************************************************************/
#include <ogdf/fileformats/xml/Lexer.h>
namespace ogdf {
namespace xml {
Lexer::Lexer()
: m_input(nullptr)
{
}
Lexer::Lexer(std::istream &is)
{
setInput(is);
}
void Lexer::setInput(std::istream &is)
{
m_input = &is;
// Input changes, so we need to reset our position...
m_row = 1;
m_column = 0;
// ... and reset the buffer.
m_buffer_begin = 0;
m_buffer_size = 0;
}
xml::token Lexer::nextToken()
{
while (skipWhitespace() || skipComments()) {
}
if (buffer_empty()) {
buffer_put(m_input->get());
}
switch (buffer_peek()) {
case '<':
m_token = token::chevron_left;
buffer_pop();
break;
case '>':
m_token = token::chevron_right;
buffer_pop();
break;
case '?':
m_token = token::questionMark;
buffer_pop();
break;
case '=':
m_token = token::assignment;
buffer_pop();
break;
case '/':
m_token = token::slash;
buffer_pop();
break;
case '"': case '\'':
consumeString();
break;
case EOF:
/*
* TODO: Replace EOF with std::char_traits<char>::eof() once VS
* will learn what "constexpr" is.
*/
m_token = token::eof;
buffer_pop();
break;
default:
consumeIdentifier();
break;
}
return m_token;
}
bool Lexer::skipWhitespace()
{
bool consumed = false;
for (;;) {
if (buffer_empty()) {
buffer_put(m_input->get());
}
char current = buffer_peek();
// TODO: Replace it with std::isspace in the future.
if (!isspace(current)) {
break;
}
buffer_pop();
consumed = true;
}
return consumed;
}
bool Lexer::skipComments()
{
// We need to ensure that we have enough characters in the buffer.
switch (buffer_size()) {
case 0:
buffer_put(m_input->get());
case 1:
buffer_put(m_input->get());
case 2:
buffer_put(m_input->get());
case 3:
buffer_put(m_input->get());
}
// We have a comment iff it begins with '<!--' sequence.
if (!(buffer_at(0) == '<' &&
buffer_at(1) == '!' &&
buffer_at(2) == '-' &&
buffer_at(3) == '-'))
{
return false;
}
buffer_pop();
buffer_pop();
buffer_pop();
buffer_pop();
for (;;) {
// TODO: Handle unclosed comments.
// As above, we enusre that we have enough characters available.
switch (buffer_size()) {
case 0:
buffer_put(m_input->get());
case 1:
buffer_put(m_input->get());
case 2:
buffer_put(m_input->get());
}
// The comment ends only with the '-->' sequence.
if (buffer_at(0) == '-' &&
buffer_at(1) == '-' &&
buffer_at(2) == '>')
{
buffer_pop();
buffer_pop();
buffer_pop();
break;
}
buffer_pop();
}
return true;
}
void Lexer::consumeText()
{
m_value = "";
for (;;) {
while (skipComments()) {
}
if (buffer_empty()) {
buffer_put(m_input->get());
}
char current = buffer_peek();
// TODO: Escape '<' and '>' as '<' and '>';
if (current == '<' || current == '>' ||
current == std::char_traits<char>::eof())
{
break;
}
m_value.push_back(buffer_pop());
}
}
void Lexer::consumeString()
{
m_value = "";
char delim = buffer_pop();
for (;;) {
if (buffer_empty()) {
buffer_put(m_input->get());
}
char current = buffer_peek();
if (current == delim) {
buffer_pop();
break;
}
if (current == std::char_traits<char>::eof()) {
break;
}
m_value.push_back(buffer_pop());
}
m_token = token::string;
}
void Lexer::consumeIdentifier()
{
m_value = "";
for (;;) {
if (buffer_empty()) {
buffer_put(m_input->get());
}
char current = buffer_peek();
/*
* The XML spec allows much narrower set of valid identifiers, but
* I see not charm in accepting some of the malformed identifiers
* since the parser is not very strict about standard too.
*/
// TODO: Replace it with std::isspace in the future.
if (isspace(current) ||
current == '<' || current == '>' ||
current == '=' || current == '/' || current == '?' ||
current == '"' || current == '\'' ||
current == std::char_traits<char>::eof())
{
break;
}
m_value.push_back(buffer_pop());
}
m_token = token::identifier;
}
}
}
| 17.989655 | 77 | 0.608396 | shahnidhi |
c476b9e173ab8d68f2fbd673567f74289990e62d | 10,017 | cc | C++ | src/ir/auth_logic/souffle_emitter_test.cc | Cypher1/raksha | 0f52f108ceb8bc7b8be36a7bf8e9662188c57551 | [
"Apache-2.0"
] | null | null | null | src/ir/auth_logic/souffle_emitter_test.cc | Cypher1/raksha | 0f52f108ceb8bc7b8be36a7bf8e9662188c57551 | [
"Apache-2.0"
] | null | null | null | src/ir/auth_logic/souffle_emitter_test.cc | Cypher1/raksha | 0f52f108ceb8bc7b8be36a7bf8e9662188c57551 | [
"Apache-2.0"
] | null | null | null | /*
* Copyright 2022 Google LLC.
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
#include "src/ir/auth_logic/souffle_emitter.h"
#include "src/common/testing/gtest.h"
#include "src/ir/auth_logic/ast.h"
#include "src/ir/datalog/program.h"
#include "src/ir/auth_logic/lowering_ast_datalog.h"
#include "src/utils/move_append.h"
namespace raksha::ir::auth_logic {
Program BuildSingleAssertionProgram(SaysAssertion assertion) {
std::vector<SaysAssertion> assertion_list = {};
assertion_list.push_back(std::move(assertion));
return Program(std::move(assertion_list), {});
}
SaysAssertion BuildSingleSaysAssertion(Principal speaker, Assertion assertion) {
std::vector<Assertion> assertion_list = {};
assertion_list.push_back(std::move(assertion));
return SaysAssertion(std::move(speaker), std::move(assertion_list));
}
Program BuildPredicateTestProgram() {
return BuildSingleAssertionProgram(BuildSingleSaysAssertion(
Principal("TestPrincipal"),
Assertion(Fact(BaseFact(datalog::Predicate("foo", {"bar", "baz"}, datalog::kPositive))))));
}
TEST(EmitterTestSuite, SimpleTest) {
std::string expected =
R"(says_foo(TestPrincipal, bar, baz).
grounded_dummy(dummy_var).
.decl grounded_dummy(x0: symbol)
.decl says_foo(x0: symbol, x1: symbol, x2: symbol)
)";
std::string actual = SouffleEmitter::EmitProgram(
LoweringToDatalogPass::Lower(BuildPredicateTestProgram()));
EXPECT_EQ(actual, expected);
}
Program BuildAttributeTestProgram() {
return BuildSingleAssertionProgram(BuildSingleSaysAssertion(
Principal("TestSpeaker"),
Assertion(Fact(BaseFact(
Attribute(Principal("OtherTestPrincipal"),
datalog::Predicate("hasProperty", {"wellTested"}, datalog::kPositive)))))));
}
TEST(EmitterTestSuite, AttributeTest) {
std::string expected =
R"(says_hasProperty(TestSpeaker, x__1, wellTested) :- says_canActAs(TestSpeaker, x__1, OtherTestPrincipal), says_hasProperty(TestSpeaker, OtherTestPrincipal, wellTested).
says_hasProperty(TestSpeaker, OtherTestPrincipal, wellTested).
grounded_dummy(dummy_var).
.decl grounded_dummy(x0: symbol)
.decl says_canActAs(x0: symbol, x1: symbol, x2: symbol)
.decl says_hasProperty(x0: symbol, x1: symbol, x2: symbol)
)";
std::string actual = SouffleEmitter::EmitProgram(
LoweringToDatalogPass::Lower(BuildAttributeTestProgram()));
EXPECT_EQ(actual, expected);
}
Program BuildCanActAsProgram() {
return BuildSingleAssertionProgram(BuildSingleSaysAssertion(
Principal("TestSpeaker"),
Assertion(Fact(BaseFact(
CanActAs(Principal("PrincipalA"), Principal("PrincipalB")))))));
}
TEST(EmitterTestSuite, CanActAsTest) {
std::string expected =
R"(says_canActAs(TestSpeaker, x__1, PrincipalB) :- says_canActAs(TestSpeaker, x__1, PrincipalA), says_canActAs(TestSpeaker, PrincipalA, PrincipalB).
says_canActAs(TestSpeaker, PrincipalA, PrincipalB).
grounded_dummy(dummy_var).
.decl grounded_dummy(x0: symbol)
.decl says_canActAs(x0: symbol, x1: symbol, x2: symbol)
)";
std::string actual = SouffleEmitter::EmitProgram(
LoweringToDatalogPass::Lower(BuildCanActAsProgram()));
EXPECT_EQ(actual, expected);
}
Program BuildCanSayProgram() {
std::unique_ptr<Fact> inner_fact = std::unique_ptr<Fact>(
new Fact(BaseFact(datalog::Predicate("grantAccess", {"secretFile"}, datalog::kPositive))));
Fact::FactVariantType cansay_fact =
std::unique_ptr<CanSay>(new CanSay(Principal("PrincipalA"), inner_fact));
return BuildSingleAssertionProgram(BuildSingleSaysAssertion(
Principal("TestSpeaker"), Assertion(Fact(std::move(cansay_fact)))));
}
TEST(EmitterTestSuite, CanSayTest) {
std::string expected =
R"(says_grantAccess(TestSpeaker, secretFile) :- says_grantAccess(x__1, secretFile), says_canSay_grantAccess(TestSpeaker, x__1, secretFile).
says_canSay_grantAccess(TestSpeaker, PrincipalA, secretFile).
grounded_dummy(dummy_var).
.decl grounded_dummy(x0: symbol)
.decl says_canSay_grantAccess(x0: symbol, x1: symbol, x2: symbol)
.decl says_grantAccess(x0: symbol, x1: symbol)
)";
std::string actual = SouffleEmitter::EmitProgram(
LoweringToDatalogPass::Lower(BuildCanSayProgram()));
EXPECT_EQ(actual, expected);
}
Program BuildDoubleCanSayProgram() {
// So much fun with unique pointers!
std::unique_ptr<Fact> inner_fact = std::unique_ptr<Fact>(
new Fact(BaseFact(datalog::Predicate("grantAccess", {"secretFile"}, datalog::kPositive))));
Fact::FactVariantType inner_cansay =
std::unique_ptr<CanSay>(new CanSay(Principal("PrincipalA"), inner_fact));
std::unique_ptr<Fact> inner_cansay_fact =
std::unique_ptr<Fact>(new Fact(std::move(inner_cansay)));
Fact::FactVariantType cansay_fact = std::unique_ptr<CanSay>(
new CanSay(Principal("PrincipalB"), inner_cansay_fact));
return BuildSingleAssertionProgram(BuildSingleSaysAssertion(
Principal("TestSpeaker"), Assertion(Fact(std::move(cansay_fact)))));
}
TEST(EmitterTestSuite, DoubleCanSayTest) {
std::string expected =
R"(says_grantAccess(TestSpeaker, secretFile) :- says_grantAccess(x__1, secretFile), says_canSay_grantAccess(TestSpeaker, x__1, secretFile).
says_canSay_grantAccess(TestSpeaker, PrincipalA, secretFile) :- says_canSay_grantAccess(x__2, PrincipalA, secretFile), says_canSay_canSay_grantAccess(TestSpeaker, x__2, PrincipalA, secretFile).
says_canSay_canSay_grantAccess(TestSpeaker, PrincipalB, PrincipalA, secretFile).
grounded_dummy(dummy_var).
.decl grounded_dummy(x0: symbol)
.decl says_canSay_canSay_grantAccess(x0: symbol, x1: symbol, x2: symbol, x3: symbol)
.decl says_canSay_grantAccess(x0: symbol, x1: symbol, x2: symbol)
.decl says_grantAccess(x0: symbol, x1: symbol)
)";
std::string actual = SouffleEmitter::EmitProgram(
LoweringToDatalogPass::Lower(BuildDoubleCanSayProgram()));
EXPECT_EQ(actual, expected);
}
Program BuildConditionalProgram() {
std::vector<BaseFact> rhs = {
BaseFact(datalog::Predicate("isEmployee", {"somePerson"}, datalog::kPositive))};
Fact lhs(
BaseFact(datalog::Predicate("canAccess", {"somePerson", "someFile"}, datalog::kPositive)));
return BuildSingleAssertionProgram(BuildSingleSaysAssertion(
Principal("TestSpeaker"),
Assertion(ConditionalAssertion(std::move(lhs), std::move(rhs)))));
}
TEST(EmitterTestSuite, ConditionalProgramTest) {
std::string expected =
R"(says_canAccess(TestSpeaker, somePerson, someFile) :- says_isEmployee(TestSpeaker, somePerson).
grounded_dummy(dummy_var).
.decl grounded_dummy(x0: symbol)
.decl says_canAccess(x0: symbol, x1: symbol, x2: symbol)
.decl says_isEmployee(x0: symbol, x1: symbol)
)";
std::string actual = SouffleEmitter::EmitProgram(
LoweringToDatalogPass::Lower(BuildConditionalProgram()));
EXPECT_EQ(actual, expected);
}
Program BuildMultiAssertionProgram() {
// Conditional Assertion
std::vector<BaseFact> rhs = {
BaseFact(datalog::Predicate("isEmployee", {"somePerson"}, datalog::kPositive))};
Fact lhs(
BaseFact(datalog::Predicate("canAccess", {"somePerson", "someFile"}, datalog::kPositive)));
SaysAssertion condAssertion = BuildSingleSaysAssertion(
Principal("TestPrincipal"),
Assertion(ConditionalAssertion(std::move(lhs), std::move(rhs))));
// Assertion stating the condition
SaysAssertion predicateAssertion = BuildSingleSaysAssertion(
Principal("TestPrincipal"),
Assertion(
Fact(BaseFact(datalog::Predicate("isEmployee", {"somePerson"}, datalog::kPositive)))));
// I would love to just write this:
// return Program({std::move(condAssertion),
// std::move(predicateAssertion)}, {});
std::vector<SaysAssertion> assertion_list = {};
assertion_list.push_back(std::move(condAssertion));
assertion_list.push_back(std::move(predicateAssertion));
return Program(std::move(assertion_list), {});
}
TEST(EmitterTestSuite, MultiAssertionProgramTest) {
std::string expected =
R"(says_canAccess(TestPrincipal, somePerson, someFile) :- says_isEmployee(TestPrincipal, somePerson).
says_isEmployee(TestPrincipal, somePerson).
grounded_dummy(dummy_var).
.decl grounded_dummy(x0: symbol)
.decl says_canAccess(x0: symbol, x1: symbol, x2: symbol)
.decl says_isEmployee(x0: symbol, x1: symbol)
)";
std::string actual = SouffleEmitter::EmitProgram(
LoweringToDatalogPass::Lower(BuildMultiAssertionProgram()));
EXPECT_EQ(actual, expected);
}
Program BuildQueryProgram() {
Query testQuery("theTestQuery", Principal("TestSpeaker"),
Fact(BaseFact(datalog::Predicate("anything", {"atAll"}, datalog::kPositive))));
std::vector<Query> query_list = {};
query_list.push_back(std::move(testQuery));
return Program({}, std::move(query_list));
}
TEST(EmitterTestSuite, QueryTestProgram) {
std::string expected =
R"(theTestQuery(dummy_var) :- says_anything(TestSpeaker, atAll), grounded_dummy(dummy_var).
grounded_dummy(dummy_var).
.output theTestQuery
.decl grounded_dummy(x0: symbol)
.decl says_anything(x0: symbol, x1: symbol)
.decl theTestQuery(x0: symbol)
)";
// R"(theTestQuery(dummy_var) :- says_anything(TestSpeaker, atAll),
// grounded_dummy(dummy_var). grounded_dummy(dummy_var). .output theTestQuery
//
// .decl theTestQuery(x0: symbol)
// .decl says_anything(x0: symbol, x1: symbol)
// .decl grounded_dummy(x0: symbol))";
std::string actual = SouffleEmitter::EmitProgram(
LoweringToDatalogPass::Lower(BuildQueryProgram()));
EXPECT_EQ(actual, expected);
}
} // namespace raksha::ir::auth_logic
| 37.943182 | 193 | 0.745932 | Cypher1 |
c47eff3d038eac49c6ebcbd7d03ce34182bdc98b | 296 | cpp | C++ | test/suits/nav/test_atcproceduresid.cpp | ignmiz/ATC_Console | 549dd67a007cf54b976e33fed1581f30beb08b06 | [
"Intel",
"MIT"
] | 5 | 2018-01-08T22:20:07.000Z | 2021-06-19T17:42:29.000Z | test/suits/nav/test_atcproceduresid.cpp | ignmiz/ATC_Console | 549dd67a007cf54b976e33fed1581f30beb08b06 | [
"Intel",
"MIT"
] | null | null | null | test/suits/nav/test_atcproceduresid.cpp | ignmiz/ATC_Console | 549dd67a007cf54b976e33fed1581f30beb08b06 | [
"Intel",
"MIT"
] | 2 | 2017-08-07T23:07:42.000Z | 2021-05-09T13:02:39.000Z |
#include "test_atcproceduresid.h"
void Test_ATCProcedureSID::test_constructObject()
{
ATCProcedureSID foo("NAME", "CODE", "01");
QVERIFY(foo.getName() == "NAME");
QVERIFY(foo.getAirport() == "CODE");
QVERIFY(foo.getRunwayID() == "01");
QVERIFY(foo.getFixListSize() == 0);
}
| 24.666667 | 49 | 0.652027 | ignmiz |
c47f8acd78f5f6aeff4c10ffae4bba33d5089c6f | 2,623 | cpp | C++ | qt/qt_common/qtoglcontext.cpp | keksikex/omim | cf75e55bc6d96f3488af9d5977c4bee422a366c3 | [
"Apache-2.0"
] | null | null | null | qt/qt_common/qtoglcontext.cpp | keksikex/omim | cf75e55bc6d96f3488af9d5977c4bee422a366c3 | [
"Apache-2.0"
] | null | null | null | qt/qt_common/qtoglcontext.cpp | keksikex/omim | cf75e55bc6d96f3488af9d5977c4bee422a366c3 | [
"Apache-2.0"
] | null | null | null | #include "qt/qt_common/qtoglcontext.hpp"
#include "base/assert.hpp"
#include "base/logging.hpp"
#include "base/macros.hpp"
#include "base/math.hpp"
#include "base/stl_add.hpp"
#include "drape/glfunctions.hpp"
namespace qt
{
namespace common
{
// QtRenderOGLContext ------------------------------------------------------------------------------
QtRenderOGLContext::QtRenderOGLContext(QOpenGLContext * rootContext, QOffscreenSurface * surface)
: m_surface(surface)
, m_ctx(my::make_unique<QOpenGLContext>())
{
m_ctx->setFormat(rootContext->format());
m_ctx->setShareContext(rootContext);
m_ctx->create();
ASSERT(m_ctx->isValid(), ());
}
void QtRenderOGLContext::Present()
{
if (!m_resizeLock)
LockFrame();
m_resizeLock = false;
GLFunctions::glFinish();
std::swap(m_frontFrame, m_backFrame);
UnlockFrame();
}
void QtRenderOGLContext::MakeCurrent()
{
VERIFY(m_ctx->makeCurrent(m_surface), ());
}
void QtRenderOGLContext::DoneCurrent()
{
m_ctx->doneCurrent();
}
void QtRenderOGLContext::SetDefaultFramebuffer()
{
if (m_backFrame == nullptr)
return;
m_backFrame->bind();
}
void QtRenderOGLContext::Resize(int w, int h)
{
LockFrame();
m_resizeLock = true;
QSize size(my::NextPowOf2(w), my::NextPowOf2(h));
m_texRect =
QRectF(0.0, 0.0, w / static_cast<float>(size.width()), h / static_cast<float>(size.height()));
m_frontFrame = my::make_unique<QOpenGLFramebufferObject>(size, QOpenGLFramebufferObject::Depth);
m_backFrame = my::make_unique<QOpenGLFramebufferObject>(size, QOpenGLFramebufferObject::Depth);
}
void QtRenderOGLContext::LockFrame()
{
m_lock.lock();
}
QRectF const & QtRenderOGLContext::GetTexRect() const
{
return m_texRect;
}
GLuint QtRenderOGLContext::GetTextureHandle() const
{
if (!m_frontFrame)
return 0;
return m_frontFrame->texture();
}
void QtRenderOGLContext::UnlockFrame()
{
m_lock.unlock();
}
// QtUploadOGLContext ------------------------------------------------------------------------------
QtUploadOGLContext::QtUploadOGLContext(QOpenGLContext * rootContext, QOffscreenSurface * surface)
: m_surface(surface), m_ctx(my::make_unique<QOpenGLContext>())
{
m_ctx->setFormat(rootContext->format());
m_ctx->setShareContext(rootContext);
m_ctx->create();
ASSERT(m_ctx->isValid(), ());
}
void QtUploadOGLContext::MakeCurrent()
{
m_ctx->makeCurrent(m_surface);
}
void QtUploadOGLContext::DoneCurrent()
{
m_ctx->doneCurrent();
}
void QtUploadOGLContext::Present()
{
ASSERT(false, ());
}
void QtUploadOGLContext::SetDefaultFramebuffer()
{
ASSERT(false, ());
}
} // namespace common
} // namespace qt
| 21.325203 | 100 | 0.682043 | keksikex |
c48275d7bd69f5f138c89b4a20251267a824a99d | 290 | cpp | C++ | sand_box_6.cpp | gwamoniak/Cpp | b1815464412f8d282f578cbf3ecc4b07a480b7d3 | [
"MIT"
] | null | null | null | sand_box_6.cpp | gwamoniak/Cpp | b1815464412f8d282f578cbf3ecc4b07a480b7d3 | [
"MIT"
] | null | null | null | sand_box_6.cpp | gwamoniak/Cpp | b1815464412f8d282f578cbf3ecc4b07a480b7d3 | [
"MIT"
] | 1 | 2022-01-16T16:29:05.000Z | 2022-01-16T16:29:05.000Z | #include <utility>
#include <iostream>
#include <algorithm>
#include <vector>
#include <memory_resource>
constexpr double pow(const double x, std::size_t y)
{
return y!= 1 ? x*pow(x,y-1) :x;
}
int main()
{
auto out = pow(3.0,6);
std::cout << out << '\n';
return 0;
} | 13.181818 | 52 | 0.6 | gwamoniak |
c48b98599f5edb14b0f9b2711498878829315744 | 167,604 | cpp | C++ | src/parser.cpp | giag3/peng-utils | f0883ffbf3b422de2e0ea326861114b1f5809037 | [
"MIT"
] | 1 | 2022-03-28T11:20:50.000Z | 2022-03-28T11:20:50.000Z | src/parser.cpp | giag3/peng-utils | f0883ffbf3b422de2e0ea326861114b1f5809037 | [
"MIT"
] | null | null | null | src/parser.cpp | giag3/peng-utils | f0883ffbf3b422de2e0ea326861114b1f5809037 | [
"MIT"
] | null | null | null | #include "parser/parser.hpp"
#include "error_handler/error_handler.hpp"
#include "assembler/assembler.hpp"
#include "error_handler/console.hpp"
#include "compiler/assembly_shortcuts.hpp"
#if (UTILITY == COMPILER)
#include "compiler/assembly_shortcuts.hpp"
#include "compiler/variable.hpp"
#endif
// Use assembler namespace
using namespace assembler;
// Get the number system
/**
* @brief is_number Checks whether the string is a number
* @param token the token to check
* @return the number system
*/
extern num_sys is_number(const std::string& token);
// Parses a string and returns it
std::string parser::parse_string(source_file& file) {
// First character (whatever it is should already be removed)
// Parse a string ending with a \"
return parse_string(file, '"');
}
// Returns the espace sequence
char get_escape_sequence(char c) {
// Check the character after '\'
switch (c) {
// Newline
case 'n': return '\n';
// Horizontal tab
case 't': return '\t';
// Single quotation mark
case '\'': return '\'';
// Double quotation mark
case '"': return '"';
// Backslash
case '\\': return '\\';
// Return
case 'r': return '\r';
// Vertical tab
case 'v': return '\v';
// Question mark
case '?': return '\?';
// Null Character
case '0': return '\0';
// Backspace
case 'b': return '\b';
// Form feed
case 'f': return '\f';
}
}
// Parses a char and returns it
char parser::parse_char(source_file& file) {
// The returning character
char c;
// Check for '\'
if (file.is_char('\\'))
c = get_escape_sequence(file.get_char());
// Else return the next character
else
c = file.get_char();
// Remove ' character
while (!file.is_char('\'') && !file.eof()) {
error_handler::compilation_error("multiple characters found; unknown '" + C_BLUE + std::string(1, file.get_char()) + C_CLR + "'");
}
// Return the character
return c;
}
// Parses a string and returns it
std::string parser::parse_string(source_file& file, char ending_char) {
// Parse string until ending_char has been reached
// EXCEPT: \", ...
// Character, String variable
char c;
std::string text;
// Get the next char in sequence
// And quit if the character is a quote
while (((c = file.get_char()) != ending_char)) {
// If eof => return text
if (file.get_current_line() >= file.get_source_lines().size())
return text;
// Escape sequence check
if (c == '\\')
text += get_escape_sequence(file.get_char());
else
text += c;
}
// Return the text
return text;
}
// Get library paths
extern std::string std_library_path;
// Externed methods -> do not add them again to externals
extern std::vector<std::string> externed_methods;
// Check if externed already
extern bool externed(const std::string& mname);
// True - success, False - error
bool get_file_name(source_file* file, std::string& file_name) {
// Whether to parse a string not in lib
if (file->is_token("\"")) {
// Parse path
file_name = parser::parse_string(*file);
// Convert to absolute path
if (std::experimental::filesystem::path(file_name).is_relative())
file_name = std::experimental::filesystem::absolute(file_name).string();
}
#if UTILITY == COMPILER
// File is in library path (or elsewhere)
else if (file->is_token("<")) {
// Parse path
file_name = parser::parse_string(*file, '>');
// Check if absolute path
if (std::experimental::filesystem::path(file_name).is_relative()) {
// Add the library path
file_name = std_library_path + file_name;
}
}
#endif
// Throw error since no viable way to get the path exists
else {
error_handler::utility_error("file needs to be a string path");
return false;
}
// Give heads up about infinite inclusion
if (file_name == file->get_source_file_path())
error_handler::warning("shouldn't include the same file; results in an infinite inclusion");
return true;
}
// *****************
// STACK VARIABLES
// *****************
#if UTILITY == COMPILER
// Type bool
TYPE BOOL = {DATA_TYPE::BOOL};
extern bool is_signed(TYPE& type);
extern ulong size(TYPE& type, bool capped = false);
extern bool get_variable(variable& var, std::string& name);
extern bool get_method(method& met, std::string& name, std::vector<variable>& arguments, nclass*& obj_nclass);
// Whether we want to terminate the loop
bool parser::terminate() {
// If end of file terminate
if (file->eof()) {
error_handler::compilation_error("end of file reached while parsing", true);
return true;
}
// Get next character from file
std::string check_char = file->check_token();
// Check if current token is an ending character
for (char& c : *terminate_characters)
if (check_char == std::string(1, c) && c != ')') {
// Remove the token before returning
file->get_token();
this->terminate_character = c;
return true;
}
// If this bracket is found, return only if it matches the other ones
else if (check_char == std::string(1, c) && c == ')' && bracket_count - 1 < 0) {
// Remove the token before returning
file->get_token();
this->terminate_character = c;
return true;
}
// Else continue
return false;
}
// Get namespaces
extern std::vector<NAMESPACE*> namespaces;
extern std::vector<ENUM*> enums;
// Get namespace name
extern std::string get_namespace_name(NAMESPACE*& nc);
// Check if types are equal
extern bool type_equal(TYPE& t1, TYPE& t2, bool* b = nullptr, bool allow_pointers = true);
// Gets type info
extern std::string get_type_info(TYPE& type);
// Checks whether the type is equal
void check_type(TYPE& correct_type, TYPE& check_type) {
// Check if correct type found
if (!type_equal(check_type, correct_type)) {
// Do not throw ambiguous errors
if (check_type.data_type <= (DATA_TYPE) DATA_TYPE_SIZE && correct_type.data_type <= (DATA_TYPE) DATA_TYPE_SIZE)
error_handler::compilation_error("incorrect type found; found '" + C_GREEN + get_type_info(check_type) + C_CLR + "' instead of '" + C_GREEN + get_type_info(correct_type) + C_CLR + "'");
return;
}
}
// Moves a variable to an effective address
void move_variable(uint size, effective_address<reg64> eff_address) {
// If size is 8 bytes
if (size == 8) {
assembler::write_inst(assembler::POP(eff_address, PTR_SIZE::QWORD));
return;
}
// Get variable to rax
write_inst(POP(reg64::R12));
// Move to the variable
if (size == 8)
write_inst(MOV(eff_address, reg64::R12));
else if (size == 4)
write_inst(MOV(eff_address, reg32::R12D));
else if (size == 2)
write_inst(MOV(eff_address, reg16::R12W));
else
write_inst(MOV(eff_address, reg8::R12B));
}
// Function for eff + reg
template <typename REG>
std::vector<assembler::byte> (*func_eff_reg)(effective_address<reg64>, REG);
// Function for extended insts
template <typename REG>
std::vector<assembler::byte> (*func_ext)(REG reg);
// Function for mul
template <typename REG>
std::vector<assembler::byte> (*func_mul)(effective_address<reg64>, PTR_SIZE);
// Nor for variable, variable
void do_nor(variable& var, variable& type) {
// CHANGED FROM R12 to RAX
// The size of the variable to mov to
uint size = var.size(true);
// Conversion
if (size > type.size(true)) {
// Move variable to rax
conv::convert_eff(int(reg64::RAX), var.size(), type.size(), type);
} else {
// Move variable to rax
type.move_to_reg((int) reg64::RAX);
}
// Move to variable
switch (var.size(true)) {
case 8: write_inst(func_eff_reg<reg64>(var.get_eff(false), reg64::RAX)); break;
case 4: write_inst(func_eff_reg<reg32>(var.get_eff(false), reg32::EAX)); break;
case 2: write_inst(func_eff_reg<reg16>(var.get_eff(false), reg16::AX)); break;
case 1: write_inst(func_eff_reg<reg8>(var.get_eff(false), reg8::AL)); break;
}
}
// Ext for variable, variable
void do_ext(VARIABLE_OPERATION& var_op, variable& var, variable& type) {
// CHANGED FROM R12 to RAX
// The size of the variable to mov to
uint size = var.size(true);
// Conversion
if (size > type.size(true)) {
// Move type variable to rbx
conv::convert_eff(int(reg64::RCX), var.size(), type.size(), type);
} else {
// Check for multiplication
if (var_op == VARIABLE_OPERATION::MULTIPLY && !var.on_stack) {
// Move variable to RAX
var.move_to_reg(int(reg64::RAX), false);
// Mul variable
switch (var.size(true)) {
case 8: write_inst(func_mul<reg64>(type.get_eff(), PTR_SIZE::QWORD)); _WI(MOV(var.get_eff(false), reg64::RAX)); return;
case 4: write_inst(func_mul<reg32>(type.get_eff(), PTR_SIZE::DWORD)); _WI(MOV(var.get_eff(false), reg32::EAX)); return;
case 2: write_inst(func_mul<reg16>(type.get_eff(), PTR_SIZE::WORD)); _WI(MOV(var.get_eff(false), reg16::AX)); return;
case 1: write_inst(func_mul<reg8>(type.get_eff(), PTR_SIZE::BYTE)); _WI(MOV(var.get_eff(false), reg8::AL)); return;
}
} else {
// Move type variable to rbx
type.move_to_reg((int) reg64::RCX);
}
}
// Left shift
if (var_op == VARIABLE_OPERATION::SHL) {
// Do to variable
switch (var.size(true)) {
case 8: _WI(SHL_CL(var.get_eff(false), PTR_SIZE::QWORD)); return;
case 4: _WI(SHL_CL(var.get_eff(false), PTR_SIZE::DWORD)); return;
case 2: _WI(SHL_CL(var.get_eff(false), PTR_SIZE::WORD)); return;
case 1: _WI(SHL_CL(var.get_eff(false), PTR_SIZE::BYTE)); return;
}
}
// Right shift
else if (var_op == VARIABLE_OPERATION::SHR) {
// Do to variable
switch (var.size(true)) {
case 8: _WI(SHR_CL(var.get_eff(false), PTR_SIZE::QWORD)); return;
case 4: _WI(SHR_CL(var.get_eff(false), PTR_SIZE::DWORD)); return;
case 2: _WI(SHR_CL(var.get_eff(false), PTR_SIZE::WORD)); return;
case 1: _WI(SHR_CL(var.get_eff(false), PTR_SIZE::BYTE)); return;
}
}
// Move variable to RAX
var.move_to_reg(int(reg64::RAX), false);
// Check for mod
bool mod = var_op == VARIABLE_OPERATION::MODULO;
// Do to variable
switch (var.size(true)) {
case 8: write_inst(func_ext<reg64>(reg64::RCX)); _WI(MOV(var.get_eff(false), mod ? reg64::RDX : reg64::RAX)); return;
case 4: write_inst(func_ext<reg32>(reg32::ECX)); _WI(MOV(var.get_eff(false), mod ? reg32::EDX : reg32::EAX)); return;
case 2: write_inst(func_ext<reg16>(reg16::CX)); _WI(MOV(var.get_eff(false), mod ? reg16::DX : reg16::AX)); return;
case 1: write_inst(func_ext<reg8>(reg8::CL)); _WI(MOV(var.get_eff(false), mod ? reg8::AH : reg8::DL)); return;
}
}
// Nor for variable, type
void do_nor(VARIABLE_OPERATION& var_op, variable& var, TYPE& type) {
// Move variable to eff from stack
int size = var.size(true);
// Pop type to RAX
_WI(POP(reg64::RAX));
// Conversion
if (size > ::size(type, true)) {
// Convert type to var
conv::convert_reg(int(reg64::RAX), size, ::size(type), var.is_signed());
}
// Check with size
switch (size) {
case 8: _WI(func_eff_reg<reg64>(var.get_eff(false), reg64::RAX)); break;
case 4: _WI(func_eff_reg<reg32>(var.get_eff(false), reg32::EAX)); break;
case 2: _WI(func_eff_reg<reg16>(var.get_eff(false), reg16::AX)); break;
case 1: _WI(func_eff_reg<reg8>(var.get_eff(false), reg8::AL)); break;
}
}
// Ext for variable, type
void do_ext(VARIABLE_OPERATION& var_op, variable& var, TYPE& type) {
// The size of the variable to mov to
uint size = var.size(true);
// Conversion
if (size > ::size(type, true)) {
// Move type variable to rbx
conv::convert_reg(int(reg64::RCX), var.size(), ::size(type, true), var.is_signed());
} else {
// Check for multiplication
if (var_op == VARIABLE_OPERATION::MULTIPLY && !var.on_stack) {
// Move variable to RAX
var.move_to_reg(int(reg64::RAX), false);
// Mul variable
switch (var.size(true)) {
case 8: write_inst(func_mul<reg64>(effective_address<reg64>(reg64::RSP), PTR_SIZE::QWORD)); _WI(MOV(var.get_eff(false), reg64::RAX)); break;
case 4: write_inst(func_mul<reg32>(effective_address<reg64>(reg64::RSP), PTR_SIZE::DWORD)); _WI(MOV(var.get_eff(false), reg32::EAX)); break;
case 2: write_inst(func_mul<reg16>(effective_address<reg64>(reg64::RSP), PTR_SIZE::WORD)); _WI(MOV(var.get_eff(false), reg16::AX)); break;
case 1: write_inst(func_mul<reg8>(effective_address<reg64>(reg64::RSP), PTR_SIZE::BYTE)); _WI(MOV(var.get_eff(false), reg8::AL)); break;
}
// Pop type to RAX
_WI(POP(reg64::RAX));
return;
} else {
// Pop type to RBX
_WI(POP(reg64::RCX));
}
}
// Left shift
if (var_op == VARIABLE_OPERATION::SHL) {
// Do to variable
switch (var.size(true)) {
case 8: _WI(SHL_CL(var.get_eff(false), PTR_SIZE::QWORD)); return;
case 4: _WI(SHL_CL(var.get_eff(false), PTR_SIZE::DWORD)); return;
case 2: _WI(SHL_CL(var.get_eff(false), PTR_SIZE::WORD)); return;
case 1: _WI(SHL_CL(var.get_eff(false), PTR_SIZE::BYTE)); return;
}
}
// Right shift
else if (var_op == VARIABLE_OPERATION::SHR) {
// Do to variable
switch (var.size(true)) {
case 8: _WI(SHR_CL(var.get_eff(false), PTR_SIZE::QWORD)); return;
case 4: _WI(SHR_CL(var.get_eff(false), PTR_SIZE::DWORD)); return;
case 2: _WI(SHR_CL(var.get_eff(false), PTR_SIZE::WORD)); return;
case 1: _WI(SHR_CL(var.get_eff(false), PTR_SIZE::BYTE)); return;
}
}
// Move variable to RAX
var.move_to_reg(int(reg64::RAX), false);
// Check for mod
bool mod = var_op == VARIABLE_OPERATION::MODULO;
// Do to variable
switch (var.size(true)) {
case 8: write_inst(func_ext<reg64>(reg64::RBX)); _WI(MOV(var.get_eff(false), mod ? reg64::RDX : reg64::RAX)); break;
case 4: write_inst(func_ext<reg32>(reg32::EBX)); _WI(MOV(var.get_eff(false), mod ? reg32::EDX : reg32::EAX)); break;
case 2: write_inst(func_ext<reg16>(reg16::BX)); _WI(MOV(var.get_eff(false), mod ? reg16::DX : reg16::AX)); break;
case 1: write_inst(func_ext<reg8>(reg8::BL)); _WI(MOV(var.get_eff(false), mod ? reg8::AH : reg8::DL)); break;
}
}
// Function pointers for variable operations
std::vector<assembler::byte> (*func_eff_num)(effective_address<reg64>, int, PTR_SIZE);
// Variable operations
void parser::do_to_variable(VARIABLE_OPERATION var_op, variable& var) {
// DEBUG:
#ifdef DEBUG
var.print_info();
#endif
// Mul/div/mod inst assignment
bool ext_insts = false;
// Set functions
switch (var_op) {
case VARIABLE_OPERATION::ASSIGN:
func_eff_reg<reg64> = MOV, func_eff_reg<reg32> = MOV, func_eff_reg<reg16> = MOV, func_eff_reg<reg8> = MOV; break;
case VARIABLE_OPERATION::ADD:
func_eff_num = ADD;
func_eff_reg<reg64> = ADD, func_eff_reg<reg32> = ADD, func_eff_reg<reg16> = ADD, func_eff_reg<reg8> = ADD; break;
case VARIABLE_OPERATION::AND:
func_eff_num = AND;
func_eff_reg<reg64> = AND, func_eff_reg<reg32> = AND, func_eff_reg<reg16> = AND, func_eff_reg<reg8> = AND; break;
case VARIABLE_OPERATION::OR:
func_eff_num = OR;
func_eff_reg<reg64> = OR, func_eff_reg<reg32> = OR, func_eff_reg<reg16> = OR, func_eff_reg<reg8> = OR; break;
case VARIABLE_OPERATION::XOR:
func_eff_num = XOR;
func_eff_reg<reg64> = XOR, func_eff_reg<reg32> = XOR, func_eff_reg<reg16> = XOR, func_eff_reg<reg8> = XOR; break;
case VARIABLE_OPERATION::SUBTRACT:
func_eff_num = SUB;
func_eff_reg<reg64> = SUB, func_eff_reg<reg32> = SUB, func_eff_reg<reg16> = SUB, func_eff_reg<reg8> = SUB; break;
case VARIABLE_OPERATION::DIVIDE:
if (var.is_signed()) {
func_ext<reg64> = IDIV; func_ext<reg32> = IDIV; func_ext<reg16> = IDIV; func_ext<reg8> = IDIV; ext_insts = true; break;
}
func_ext<reg64> = DIV; func_ext<reg32> = DIV; func_ext<reg16> = DIV; func_ext<reg8> = DIV; ext_insts = true; break;
case VARIABLE_OPERATION::SHL: ext_insts = true; break;
case VARIABLE_OPERATION::SHR: ext_insts = true; break;
case VARIABLE_OPERATION::MULTIPLY:
if (var.is_signed()) {
func_mul<reg64> = IMUL; func_mul<reg32> = IMUL; func_mul<reg16> = IMUL; func_mul<reg8> = IMUL;
func_ext<reg64> = IMUL; func_ext<reg32> = IMUL; func_ext<reg16> = IMUL; func_ext<reg8> = IMUL; ext_insts = true; break;
}
func_mul<reg64> = MUL; func_mul<reg32> = MUL; func_mul<reg16> = MUL; func_mul<reg8> = MUL;
func_ext<reg64> = MUL; func_ext<reg32> = MUL; func_ext<reg16> = MUL; func_ext<reg8> = MUL; ext_insts = true; break;
case VARIABLE_OPERATION::MODULO:
if (var.is_signed()) {
func_ext<reg64> = IDIV; func_ext<reg32> = IDIV; func_ext<reg16> = IDIV; func_ext<reg8> = IDIV; ext_insts = true; break;
}
func_ext<reg64> = DIV; func_ext<reg32> = DIV; func_ext<reg16> = DIV; func_ext<reg8> = DIV; ext_insts = true; break;
default: error_handler::compilation_error("missing variable operation; internal");
}
// If top of stack is a number -> move to the variable,
// as this value has not been pushed to program stack
if (postfix_buffer.back().is_number()) {
// Mul/Div/Mod
if (ext_insts) {
// Move number to RBX
_WI(MOV_opt(reg64::RCX, postfix_buffer.back().number));
// Left shift
if (var_op == VARIABLE_OPERATION::SHL) {
// Do to variable
switch (var.size(true)) {
case 8: _WI(SHL_CL(var.get_eff(false), PTR_SIZE::QWORD)); return;
case 4: _WI(SHL_CL(var.get_eff(false), PTR_SIZE::DWORD)); return;
case 2: _WI(SHL_CL(var.get_eff(false), PTR_SIZE::WORD)); return;
case 1: _WI(SHL_CL(var.get_eff(false), PTR_SIZE::BYTE)); return;
}
}
// Right shift
else if (var_op == VARIABLE_OPERATION::SHR) {
// Do to variable
switch (var.size(true)) {
case 8: _WI(SHR_CL(var.get_eff(false), PTR_SIZE::QWORD)); return;
case 4: _WI(SHR_CL(var.get_eff(false), PTR_SIZE::DWORD)); return;
case 2: _WI(SHR_CL(var.get_eff(false), PTR_SIZE::WORD)); return;
case 1: _WI(SHR_CL(var.get_eff(false), PTR_SIZE::BYTE)); return;
}
}
// Move variable to RAX
var.move_to_reg((int) reg64::RAX);
// Check for mod
bool mod = var_op == VARIABLE_OPERATION::MODULO;
// Do to variable
switch (var.size(true)) {
case 8: if (var_op == VARIABLE_OPERATION::DIVIDE || mod) var.is_signed() ? _WI(CQO()) : _XOR_REG(RDX, RDX); write_inst(func_ext<reg64>(reg64::RCX)); write_inst(MOV(var.get_eff(false), mod ? reg64::RDX : reg64::RAX)); break;
case 4: if (var_op == VARIABLE_OPERATION::DIVIDE || mod) var.is_signed() ? _WI(CDQ()) : _XOR_REG32(EDX, EDX); write_inst(func_ext<reg32>(reg32::ECX)); write_inst(MOV(var.get_eff(false), mod ? reg32::EDX : reg32::EAX)); break;
case 2: if (var_op == VARIABLE_OPERATION::DIVIDE || mod) var.is_signed() ? _WI(CWD()) : _XOR_REG16(DX, DX); write_inst(func_ext<reg16>(reg16::CX)); write_inst(MOV(var.get_eff(false), mod ? reg16::DX : reg16::AX)); break;
case 1: write_inst(func_ext<reg8>(reg8::CL)); write_inst(MOV(var.get_eff(false), mod ? reg8::AH : reg8::DL)); break;
}
}
// Add/Sub/Assign
else {
// Assign
if (var_op == VARIABLE_OPERATION::ASSIGN) {
// Assign
switch (var.size(true)) {
case 8: _WI(MOV_opt(reg64::RAX, postfix_buffer.back().number)); write_inst(MOV(var.get_eff(false), reg64::RAX)); return;
case 4: write_inst(MOV(var.get_eff(false), postfix_buffer.back().number, PTR_SIZE::DWORD)); return;
case 2: write_inst(MOV(var.get_eff(false), postfix_buffer.back().number, PTR_SIZE::WORD)); return;
case 1: write_inst(MOV(var.get_eff(false), postfix_buffer.back().number, PTR_SIZE::BYTE)); return;
}
} else {
// Do to variable
switch (var.size(true)) {
case 8: write_inst(func_eff_num(var.get_eff(false), postfix_buffer.back().number, PTR_SIZE::QWORD)); return;
case 4: write_inst(func_eff_num(var.get_eff(false), postfix_buffer.back().number, PTR_SIZE::DWORD)); return;
case 2: write_inst(func_eff_num(var.get_eff(false), postfix_buffer.back().number, PTR_SIZE::WORD)); return;
case 1: write_inst(func_eff_num(var.get_eff(false), postfix_buffer.back().number, PTR_SIZE::BYTE)); return;
}
}
}
}
// Variable is on top of stack
else if (postfix_buffer.back().is_variable()) {
// Copy the nclass
if (var.is_nclass_type()) {
// Prepare for call
var.move_pointer_to_reg(reg64::RDI);
// Move the variable to rsi for copying
postfix_buffer.back().var.move_pointer_to_reg(reg64::RSI);
// Push RDI to stack
_WI(PUSH(reg64::RDI));
// The name of the constructor
std::string mname = "c#" + get_namespace_name(var.get_type().obj_nclass->get_namespace()) + var.get_type().obj_nclass->get_name() + "#n_"+var.get_type().obj_nclass->get_name()+"p";
// If already compiled => get from another object file
if ((var.get_type().obj_nclass->get_copy_constructor()->is_compiled() || !var.get_type().obj_nclass->get_copy_constructor()->is_defined()) && !externed(mname)) {
// Method full name -> no namespace
_EXTERN(mname);
// Add to list (so we do not add it again)
externed_methods.push_back(mname);
}
// Call copy constructor
_WI(assembler::CALL(mname));
} else {
// Mul/Div/Mod
if (ext_insts) {
do_ext(var_op, var, postfix_buffer.back().var);
}
// Add/Sub/Assign
else {
do_nor(var, postfix_buffer.back().var);
}
}
}
// Stack variable is on top of stack
else {
// Move from stack to variable
if (var.is_nclass_type()) {
// Move variable to eff from stack
// If size is 8 bytes
if (var_op == VARIABLE_OPERATION::ASSIGN) {
_WI(MOV(reg64::R12, effective_address<reg64>(reg64::RSP)));
_WI(MOV(var.get_eff(false), reg64::R12));
} else
error_handler::compilation_error("cannot add to nclass variable");
} else {
// Mul/Div/Mod
if (ext_insts) {
do_ext(var_op, var, postfix_buffer.back().var.get_type());
}
// Add/Sub/Assign
else {
do_nor(var_op, var, postfix_buffer.back().var.get_type());
}
}
}
}
// Pop to output buffer until left bracket
void parser::pop_until_left_bracket() {
// Check not empty
if (pe_stack.empty())
return;
// While the stack top is not pe_op -> pop
while (!(pe_stack.top().pe_id == parser_expression_id::BRACKET && pe_stack.top()._operator == pe_operator::LEFT_BRACKET)) {
// If it is an operator => evaluate
if (pe_stack.top().is_operator()) {
// Evaluate the values with the operator
evaluate_operator();
} else {
// Add to the output buffer
postfix_buffer.push_back(pe_stack.top());
}
// And remove the parser expr from the stack
pe_stack.pop();
// Check not empty
if (pe_stack.empty())
break;
}
}
// Gets precedence from character
unsigned char get_precedence(pe_operator pe_op) {
if (pe_op == pe_operator::EQUAL || pe_op == pe_operator::NOT_EQUAL
|| pe_op == pe_operator::LESSER || pe_op == pe_operator::LESSER_OR_EQUAL
|| pe_op == pe_operator::GREATER || pe_op == pe_operator::GREATER_OR_EQUAL
|| pe_op == pe_operator::TERNARY_COLON)
return 1;
else if (pe_op == pe_operator::PLUS || pe_op == pe_operator::MINUS)
return 3;
else if (pe_op == pe_operator::STAR || pe_op == pe_operator::FORWARD_SLASH
|| pe_op == pe_operator::MODULO || pe_op == pe_operator::NEGATE_VALUE
|| pe_op == pe_operator::CAST)
return 5;
else if (pe_op == pe_operator::AMPERSAND || pe_op == pe_operator::DOUBLE_AMPERSAND ||
pe_op == pe_operator::VERTICAL_BAR || pe_op == pe_operator::DOUBLE_VERTICAL_BAR ||
pe_op == pe_operator::NEGATE || pe_op == pe_operator::XOR || pe_op == pe_operator::TERNARY_QUESTION_MARK)
return 0;
return 10;
}
// Pop to output buffer until lower precedence or end
void parser::pop_until_precedence(unsigned char precedence) {
// Check not empty
if (pe_stack.empty())
return;
// While the stack top is not c -> pop
while (pe_stack.top().pe_id == parser_expression_id::OPERATOR && precedence <= get_precedence(pe_stack.top()._operator)) {
// If it is an operator => evaluate
if (pe_stack.top().is_operator()) {
// Evaluate the values with the operator
evaluate_operator();
} else {
// Add to the output buffer
postfix_buffer.push_back(pe_stack.top());
}
// And remove the parser expr from the stack
pe_stack.pop();
// Check not empty
if (pe_stack.empty())
return;
}
}
// Get the type from a pe expression
TYPE get_type(parser_expression& pe) {
if (pe.is_variable() || pe.is_number() || pe.is_stack_val())
return pe.var.get_type();
else if (pe.is_method())
return pe.m.get_type();
}
#define CHAR_PTR {DATA_TYPE::CHAR, META_DATA_TYPE::POINTER, 1}
// Vector of variable strings
std::vector<std::pair<variable*, std::string>> strings;
// String ID
uint str_id = 0;
// Creates/Gets a new string variable
variable* create_string(std::string str) {
// If string already exists, return it
for (auto& p : strings)
if (p.second == str)
return p.first;
// The variable name
std::string var_name = "s#" + std::to_string(str_id++);
// Else create a new pointer and save it
variable* vstr = new variable(var_name, CHAR_PTR);
// Set data pointer
vstr->is_data_pointer = true;
vstr->is_in_data() = true;
vstr->lvalue = false;
// Allocate the string with zero termination
assembler::DEFINE_STRING("v#" + var_name + "#", str, true);
// Save variable
strings.push_back({vstr, str});
// Return the pointer
return vstr;
}
// Get argument info
std::string get_arg_info(std::vector<variable>& args) {
// Argument string
std::string s_args;
// For all arguments -> get info
for (int i = 0; i < args.size(); i++) {
s_args += C_GREEN + get_type_info(args[i].get_type()) + C_CLR + (i != args.size() - 1 ? ", " : "");
}
return s_args;
}
// Get operator from token
pe_operator parser::operator_and_precedence_from_token(unsigned char& precedence, std::string& token) {
// Check if token is within range
// The parser expression operator
pe_operator pe = pe_operator::NULL_OPERATOR;
// Set parser expression
if (token == "+") {
if (file->is_token("="))
pe = pe_operator::ASSIGN_ADD;
else if (file->is_token("+"))
pe = pe_operator::RIGHT_INC_ONE;
else pe = pe_operator::PLUS;
} else if (token == "-") {
if (file->is_token("="))
pe = pe_operator::ASSIGN_SUBTRACT;
else if (file->is_token("-"))
pe = pe_operator::RIGHT_DEC_ONE;
else pe = pe_operator::MINUS;
} else if (token == "*") {
if (file->is_token("="))
pe = pe_operator::ASSIGN_MULTIPLY;
else pe = pe_operator::STAR;
} else if (token == "/") {
if (file->is_token("="))
pe = pe_operator::ASSIGN_DIVIDE;
else pe = pe_operator::FORWARD_SLASH;
} else if (token == "%") {
if (file->is_token("="))
pe = pe_operator::ASSIGN_MODULO;
else pe = pe_operator::MODULO;
} else if (token == "=") {
if (file->is_token("="))
pe = pe_operator::EQUAL;
else pe = pe_operator::ASSIGN;
} else if (token == "&") {
if (file->is_token("&")) {
pe = pe_operator::DOUBLE_AMPERSAND;
} else if (file->is_token("="))
pe = pe_operator::ASSIGN_AMPERSAND;
else pe = pe_operator::AMPERSAND;
} else if (token == "|") {
if (file->is_token("|")) {
pe = pe_operator::DOUBLE_VERTICAL_BAR;
} else if (file->is_token("="))
pe = pe_operator::ASSIGN_VERTICAL_BAR;
else pe = pe_operator::VERTICAL_BAR;
} else if (token == ">") {
if (file->is_token("="))
pe = pe_operator::GREATER_OR_EQUAL;
else if (file->is_token(">")) {
if (file->is_token("="))
pe = pe_operator::ASSIGN_RIGHT_SHIFT;
else pe = pe_operator::RIGHT_SHIFT;
} else pe = pe_operator::GREATER;
} else if (token == "<") {
if (file->is_token("="))
pe = pe_operator::LESSER_OR_EQUAL;
else if (file->is_token("<")) {
if (file->is_token("="))
pe = pe_operator::ASSIGN_LEFT_SHIFT;
else pe = pe_operator::LEFT_SHIFT;
} else pe = pe_operator::LESSER;
} else if (token == "!") {
if (file->is_token("="))
pe = pe_operator::NOT_EQUAL;
else error_handler::compilation_error("hanging '" + C_GREEN + "!" + C_CLR + "'");
} else if (token == "^") {
if (file->is_token("="))
pe = pe_operator::ASSIGN_XOR;
else pe = pe_operator::XOR;
} else if (token == "?") {
pe = pe_operator::TERNARY_QUESTION_MARK;
} else if (token == ":" && file->check_token() != ":") {
pe = pe_operator::TERNARY_COLON;
}
// Get precedence from pe_operator
precedence = get_precedence(pe);
return pe;
}
// Use path info
extern nclass* compiling_nclass;
extern method* compiling_method;
extern NAMESPACE* compiling_namespace;
extern NAMESPACE* get_namespace(std::vector<NAMESPACE*>& namespaces, std::string& name);
// Checks the left operator
void parser::check_left_operator() {
// If next token is a minus, negate
if (file->is_token("-")) {
if (file->is_token("-"))
pe_stack.push(pe_operator::LEFT_DEC_ONE);
else if (file->check_token() == "(")
pe_stack.push(pe_operator::NEGATE);
else
pe_stack.push(pe_operator::NEGATE_VALUE);
} else if (file->is_token("+")) {
if (file->is_token("+"))
pe_stack.push(pe_operator::LEFT_INC_ONE);
else error_handler::compilation_error("secluded plus operator");
} else if (file->is_token("&"))
pe_stack.push(pe_operator::REFERENCE);
else if (file->is_token("*"))
pe_stack.push(pe_operator::POINTER);
else if (file->is_token("!"))
pe_stack.push(pe_operator::BOOL_NEGATE);
}
// Get data type size
uint get_size(TYPE& type) {
// If pointer and size > 1
if (type.mdata_type == META_DATA_TYPE::POINTER && type.mdata_size > 1)
return 8;
// Return type depending on data type
switch (type.data_type) {
case DATA_TYPE::CHAR:
case DATA_TYPE::UCHAR: return 1;
case DATA_TYPE::SHORT:
case DATA_TYPE::USHORT: return 2;
case DATA_TYPE::INT:
case DATA_TYPE::UINT: return 4;
case DATA_TYPE::LONG:
case DATA_TYPE::ULONG: return 8;
}
}
// Pops values till the end
void parser::pop_till_end() {
while (!pe_stack.empty()) {
// If it is an operator => evaluate
if (pe_stack.top().is_operator()) {
// Evaluate the values with the operator
evaluate_operator();
} else {
// Add to the output buffer
postfix_buffer.push_back(pe_stack.top());
}
// Remove parser expr from pe_stack
pe_stack.pop();
}
}
// Get check for namespace
extern void check_for_namespace(std::string& token, source_file* file, method_list** methods = nullptr);
// Get non method flags
extern std::string get_all_namespaces(NAMESPACE*& nc);
extern TYPE get_type_from_array(TYPE& t);
// Method rbp offset
// Keeps track of rbp
extern uint rbp_offset, begin_rbp_offset;
// Alignment method
extern long align8(long val);
// The value to subtract before calling a method
// that returns an nclass -> needs to be the highest val
std::vector<assembler::byte>* obj_rbp_sub = nullptr;
// First var keeps track of the whole value to subtract
// Second var keeps track of the value for the current sub expression
uint obj_rbp_sub_val = 0, sub_obj_rbp_sub_val = 0;
// saved_obj_rbp_sub_val = 0, saved_sub_obj_rbp_sub_val = 0, saved_begin_rbp_offset = 0;
// Checks an array
void check_array(variable& var, nclass*& save_cn, method*& save_cm, NAMESPACE* save_ns, source_file* file, bool& in_rax, uint& voffset, path& var_path) {
// Create a parser and get the offset
// ***********************************
// CHECK FOR SINGLE POINTER / ARRAY
// ***********************************
// Check if pointer or array found
if (var.get_type().mdata_type != META_DATA_TYPE::POINTER && var.get_type().mdata_type != META_DATA_TYPE::ARRAY) {
// Throw error -> storage variable found
error_handler::compilation_error("variable needs to be " + C_BLUE + "pointer" + C_CLR + " or " + C_BLUE + "array " + C_CLR + "type");
}
// Set in rax
var.in_rax = in_rax;
// Push to stack
var.move_to_reg((int) reg64::RAX);
_PUSH_REG(RAX);
// Number type
TYPE num = {DATA_TYPE::ULONG, META_DATA_TYPE::STORAGE};
// Resave
nclass* rsave_cn = compiling_nclass;
method* rsave_cm = compiling_method;
NAMESPACE* rsave_ns = compiling_namespace;
// Reset compiling nclass
compiling_nclass = save_cn;
compiling_method = save_cm;
compiling_namespace = save_ns;
// Save obj_sub_rbp
auto& obj_save = obj_rbp_sub;
auto& obj_save_val = obj_rbp_sub_val;
// Parse num value
parser p;
p.parse_value(*file, {']'}, &num, true, false);
// Set compiling nclass
compiling_nclass = rsave_cn;
compiling_method = rsave_cm;
compiling_namespace = rsave_ns;
// ***********************************
// CHECK FOR MULTIPLE ARRAYS
// ***********************************
// Save dimension count
uint dim_count = 1;
// Get the correct offset
while (file->is_token("[")) {
// Resave
nclass* rsave_cn = compiling_nclass;
method* rsave_cm = compiling_method;
NAMESPACE* rsave_ns = compiling_namespace;
// Reset compiling nclass
compiling_nclass = save_cn;
compiling_method = save_cm;
compiling_namespace = save_ns;
// Create a parser and get the offset
parser p;
p.parse_value(*file, {']'}, &num, true, false);
// Set compiling nclass
compiling_nclass = rsave_cn;
compiling_method = rsave_cm;
compiling_namespace = rsave_ns;
// Add to dim count
++dim_count;
// Check if checking array in a wrong dim
if (dim_count > var.get_type().asize.size()) {
error_handler::compilation_error("cannot assign to dimension number '" + C_CYAN + std::to_string(dim_count) + C_CLR + "', for there's only '" + C_CYAN + std::to_string(var.get_type().asize.size()) + C_CLR + "' dimensions");
return;
}
// Pop to rbx
_WI(POP(reg64::RBX));
// Move size of dim-1 to rcx
_WI(MOV(reg32::ECX, var.get_type().asize[dim_count-2]));
// [x][y][z] => sizeof(type) * (x + y * (size_dim_x) + z * (size_of_dim_y))
_WI(MUL(reg32::EBX, reg32::ECX));
}
// Pop value to rax
_WI(POP(reg64::RAX));
// Check if dim count is not equal to 1
if (dim_count != 1)
_WI(ADD(reg32::EAX, reg32::EBX));
// Set path static variable
// var.get_path() = static_var.get_path();
// Move variable to rbx
_WI(POP(reg64::RBX));
// Get the array type
TYPE array_type = get_type_from_array(var.get_type());
// NClass offset value
if (array_type.data_type == DATA_TYPE::NCLASS && array_type.mdata_type == META_DATA_TYPE::STORAGE) {
_WI(MOV(reg64::RCX, (int) var.get_type().obj_nclass->size()));
_WI(MUL(reg64::RCX));
_WI(ADD(reg64::RAX, reg64::RBX));
}
// Go to offset normal value
else {
_WI(LEA(reg64::RAX, effective_address<reg64>(reg64::RBX, reg64::RAX, (scaling_index) get_size(var.get_type()))));
}
// ***********************************
// SET UP VARIABLE
// ***********************************
// Set in rax to true
in_rax = true;
var.lvalue = true;
// Set var offset
var.get_var_offset() = 0;
voffset = 0;
// Push itself
// static_var.get_path().get_instances().push_back(var);
var_path.get_instances().push_back(var);
// Some compilers will try to optimize IFs by jumping out of the loop after an AND is false
// that means if the meta data type is not of pointer type, it will not decrement from mdata size
if (var.get_type().mdata_type == META_DATA_TYPE::POINTER && --var.get_type().mdata_size == 0)
// Set to storage type
var.get_type().mdata_type = META_DATA_TYPE::STORAGE, var.get_type().asize.clear();
// If array found
else if (var.get_type().mdata_type == META_DATA_TYPE::ARRAY) {
// Remove first dimension
for (uint i = 0; i < dim_count; ++i)
if (!var.get_type().asize.empty())
var.get_type().asize.erase(var.get_type().asize.begin());
// If at the default element -> change type to the default type
if (var.get_type().asize.empty())
var.get_type() = get_type_from_array(var.get_type());
// If the array is of size 1, it's pretty much just a pointer
else if (var.get_type().asize.size() == 1) {
// Set mdata type to pointer
var.get_type().mdata_type = META_DATA_TYPE::POINTER;
}
}
}
// Type keywords
extern std::vector<std::pair<std::string, DATA_TYPE>> type_keywords;
extern TYPE get_expression(std::string& name, std::string& iden, source_file* file, DATA_TYPE dtype, nclass* obj_nclass = nullptr);
extern nclass* get_nclass(std::string& name);
// Pushes a cast type symbol to stack
void parser::push_cast_type_symbol(const TYPE& type) {
// Push symbol
// Create casting operator
parser_expression cast(pe_operator::CAST);
// Set casting type
cast.var.get_type() = type;
// Push to parser expr stack
pe_stack.push(cast);
}
// Parses a static type
inline TYPE parse_type(source_file* file, const DATA_TYPE& dtype, nclass* obj_nclass = nullptr, ENUM* en = nullptr) {
// **********************************
// PARSE TYPE
// **********************************
// Info about the type (meta data)
TYPE type = {dtype, META_DATA_TYPE::STORAGE};
// Set obj nclass
type.obj_nclass = obj_nclass;
type.en = en;
// Parse secondary meta_data_type
if (file->check_token() == "*")
type.mdata_type = META_DATA_TYPE::POINTER;
// Pointer found
while (file->is_token("*"))
// Increase it's size
type.mdata_size++;
// Return type
return type;
}
// Get save_ns
extern NAMESPACE* save_ns;
extern std::vector<nclass*> nclasses;
extern void check_for_namespace(std::string& token, source_file* file, ENUM*& en, bool error = true);
extern ENUM* get_enum(std::string& name);
extern std::string get_name_from_type(TYPE& type);
extern TYPE CONDITION_TYPE;
ulong ternary_id = 0;
// Get ternary end id
std::string get_ternary_end(ulong ternary_id) {
return "t" + std::to_string(ternary_id);
}
// Get ternary second id
std::string get_ternary_second(ulong ternary_id) {
return "k" + std::to_string(ternary_id);
}
// Throws error
inline void method_error(bool first_var, std::string& token, std::vector<variable>& args) {
// Method inside nclass not found
if (!first_var && compiling_nclass != nullptr)
error_handler::compilation_error("class method '" + C_GREEN + get_all_namespaces(compiling_nclass->get_namespace()) + C_RED + "::" + C_CYAN + compiling_nclass->get_name() + C_RED + "::" + C_BLUE + token + C_CLR + "' with arguments (" + get_arg_info(args) + C_CLR + ") not found");
else
error_handler::compilation_error("method '" + C_GREEN + get_all_namespaces(compiling_namespace) + C_RED + "::" + C_BLUE + token + C_CLR + "' with arguments (" + get_arg_info(args) + C_CLR + ") not found");
}
// Convert to a postfix notation
void parser::to_postfix_notation() {
// Check for left operand
check_left_operator();
// Go through the whole code
main: while (!terminate()) {
// Get next token
std::string token = file->get_token();
// *************************************
// Brackets
// *************************************
// If left bracket found -> push to stack
if (token == "(") {
// ******************************
// CASTING
// ******************************
// Save line, offset
uint line = file->get_current_line(), offset = file->get_current_offset();
// Check for casting
std::string ctoken = file->get_token();
// Check for a data type
for (auto& p : type_keywords) {
if (p.first == ctoken) {
// Get type
TYPE type = parse_type(file, p.second, nullptr);
// If not closing bracket => not casting
if (file->is_token(")")) {
// Push casted type symbol
push_cast_type_symbol(type);
// Check for left operand
check_left_operator();
goto main;
}
}
}
// Object type
// Enum pointer
ENUM* en;
// Check for a namespace
check_for_namespace(ctoken, file, en, false);
// If the object name exists => parse
if ((en = get_enum(ctoken)) != nullptr) {
// Get type
TYPE type = parse_type(file, DATA_TYPE::ENUM, nullptr, en);
// If not closing bracket => not casting
if (file->is_token(")")) {
// Push casted type symbol
push_cast_type_symbol(type);
// Check for left operand
check_left_operator();
goto main;
}
}
// Gets a reference to the nclass with the name
nclass* obj_nclass = get_nclass(ctoken);
// If the object name exists => parse
if (obj_nclass != nullptr) {
// Get type
TYPE type = parse_type(file, DATA_TYPE::NCLASS, obj_nclass);
// If not closing bracket => not casting
if (file->is_token(")")) {
// Push casted type symbol
push_cast_type_symbol(type);
// Check for left operand
check_left_operator();
goto main;
}
}
// Casting object not found -> return code pos
// Load back line, offset
file->get_current_line() = line, file->get_current_offset() = offset;
// ******************************
// BRACKET PUSH
// ******************************
// Push bracket to stack
pe_stack.push(pe_operator::LEFT_BRACKET);
// Add to bracket count
bracket_count++;
// Check for left operand
check_left_operator();
}
// If right bracket found -> pop till a left bracket is found
else if (token == ")") {
// Pop until a left parenthesis is found
pop_until_left_bracket();
// Check if stack is empty
if (!pe_stack.empty()) {
// And remove the left parenthesis
pe_stack.pop();
} else {
// Move one to be precisely at the bracket
error_handler::move_prev_offset(1);
error_handler::compilation_error("parenthesis mismatch; hanging '" + C_GREEN + ")" + C_CLR + "'");
}
// Sub from bracket count
bracket_count--;
}
// Operators
else {
// *************************************
// Operators
// *************************************
// The precedence of the operators
unsigned char precedence;
// Get operator
pe_operator pe_op = operator_and_precedence_from_token(precedence, token);
// If the equal sign operator is found
if (pe_op == pe_operator::ASSIGN
|| pe_op == pe_operator::ASSIGN_ADD || pe_op == pe_operator::ASSIGN_SUBTRACT
|| pe_op == pe_operator::ASSIGN_DIVIDE || pe_op == pe_operator::ASSIGN_MODULO
|| pe_op == pe_operator::ASSIGN_MULTIPLY || pe_op == pe_operator::ASSIGN_AMPERSAND
|| pe_op == pe_operator::ASSIGN_VERTICAL_BAR || pe_op == pe_operator::ASSIGN_XOR
|| pe_op == pe_operator::ASSIGN_LEFT_SHIFT || pe_op == pe_operator::ASSIGN_RIGHT_SHIFT
|| pe_op == pe_operator::RIGHT_INC_ONE || pe_op == pe_operator::RIGHT_DEC_ONE) {
// Pop until precedence
pop_until_precedence(precedence);
// Check if postfix_buffer is empty or the back of the list is not a variable
if (postfix_buffer.empty()) {
// Throw assignment error
error_handler::compilation_error("secluded assignment operator");
return;
}
// If parser expr is not a variable -> error
else if (!postfix_buffer.back().is_variable()) {
// Throw assignment error
error_handler::compilation_error("cannot assign to a non-variable token");
return;
}
// If variable is not an lvalue -> error
else if (!postfix_buffer.back().var.is_lvalue()) {
error_handler::compilation_error("cannot assign value to an '" + C_GREEN + "rvalue" + C_CLR + "' token");
}
// Check increment, decrement
if (pe_op == pe_operator::RIGHT_INC_ONE) {
// Push the value to stack
postfix_buffer.back().var.push_to_stack();
// Cannot be an nclass variable
if (postfix_buffer.back().var.is_nclass_type()) {
error_handler::compilation_error("cannot increment value of an '" + C_GREEN + "nclass" + C_CLR + "' variable");
return;
}
// Increment
switch (postfix_buffer.back().var.size()) {
case 8: write_inst(INC(postfix_buffer.back().var.get_eff(), PTR_SIZE::QWORD)); break;
case 4: write_inst(INC(postfix_buffer.back().var.get_eff(), PTR_SIZE::DWORD)); break;
case 2: write_inst(INC(postfix_buffer.back().var.get_eff(), PTR_SIZE::WORD)); break;
case 1: write_inst(INC(postfix_buffer.back().var.get_eff(), PTR_SIZE::BYTE)); break;
}
// Change to stack value
postfix_buffer.back() = postfix_buffer.back().var.get_type();
} else if (pe_op == pe_operator::RIGHT_DEC_ONE) {
// Push the value to stack
postfix_buffer.back().var.push_to_stack();
// Cannot be an nclass variable
if (postfix_buffer.back().var.is_nclass_type()) {
error_handler::compilation_error("cannot decrement value of an '" + C_GREEN + "nclass" + C_CLR + "' variable");
return;
}
// Decrement
switch (postfix_buffer.back().var.size()) {
case 8: write_inst(DEC(postfix_buffer.back().var.get_eff(), PTR_SIZE::QWORD)); break;
case 4: write_inst(DEC(postfix_buffer.back().var.get_eff(), PTR_SIZE::DWORD)); break;
case 2: write_inst(DEC(postfix_buffer.back().var.get_eff(), PTR_SIZE::WORD)); break;
case 1: write_inst(DEC(postfix_buffer.back().var.get_eff(), PTR_SIZE::BYTE)); break;
}
// Change to stack value
postfix_buffer.back() = postfix_buffer.back().var.get_type();
}
// Find the correct assignment operation
else {
// Assign value to the variable
parser p;
// TODO: Add all operators
VARIABLE_OPERATION var_op;
switch (pe_op) {
case pe_operator::ASSIGN: var_op = VARIABLE_OPERATION::ASSIGN; break;
case pe_operator::ASSIGN_AMPERSAND: var_op = VARIABLE_OPERATION::AND; break;
case pe_operator::ASSIGN_VERTICAL_BAR: var_op = VARIABLE_OPERATION::OR; break;
case pe_operator::ASSIGN_XOR: var_op = VARIABLE_OPERATION::XOR; break;
case pe_operator::ASSIGN_LEFT_SHIFT: var_op = VARIABLE_OPERATION::SHL; break;
case pe_operator::ASSIGN_RIGHT_SHIFT: var_op = VARIABLE_OPERATION::SHR; break;
case pe_operator::ASSIGN_ADD: var_op = VARIABLE_OPERATION::ADD; break;
case pe_operator::ASSIGN_SUBTRACT: var_op = VARIABLE_OPERATION::SUBTRACT; break;
case pe_operator::ASSIGN_MULTIPLY: var_op = VARIABLE_OPERATION::MULTIPLY; break;
case pe_operator::ASSIGN_DIVIDE: var_op = VARIABLE_OPERATION::DIVIDE; break;
case pe_operator::ASSIGN_MODULO: var_op = VARIABLE_OPERATION::MODULO; break;
}
// Parse, assign
p.parse_value_and_assign(postfix_buffer.back().var, *file, {';', ')', ','}, true, var_op);
// Re-roll a terminate character
for (char& c : *terminate_characters) {
if (p.terminate_character == c) {
--file->get_current_offset(); break;
}
}
}
// Check left operator
check_left_operator();
}
// Ternary question mark ?
else if (pe_op == pe_operator::TERNARY_QUESTION_MARK) {
if (postfix_buffer.empty()) {
error_handler::compilation_error("stack empty");
} else {
// Save ternary (multiple nested ternaries change ternary_id)
ulong ternary = ternary_id++;
// Pop until precedence
pop_until_precedence(precedence);
// Check type
check_type(CONDITION_TYPE, postfix_buffer.back().var.get_type());
// CMOVes maybe? I've heard some negative things about them though
// Not sure if correct branch prediction is faster, but I think
// that in almost all scenarios jmps are better
bool number = false;
// Compare and jump if false
if (postfix_buffer.back().is_variable()) {
switch (postfix_buffer.back().var.size(true)) {
case 8: _WI(CMP(postfix_buffer.back().var.get_eff(), (char) 0x0, PTR_SIZE::QWORD)); break;
case 4: _WI(CMP(postfix_buffer.back().var.get_eff(), (char) 0x0, PTR_SIZE::DWORD)); break;
case 2: _WI(CMP(postfix_buffer.back().var.get_eff(), (char) 0x0, PTR_SIZE::WORD)); break;
case 1: _WI(CMP(postfix_buffer.back().var.get_eff(), (char) 0x0, PTR_SIZE::BYTE)); break;
}
}
// Check number
else if (postfix_buffer.back().is_number()) {
// Set number to true; do not compare numbers, as we know them at compile time
number = true;
} else if (postfix_buffer.back().is_stack_val()) {
// POP so that it adjusts rsp
_WI(POP(reg64::RAX));
switch (postfix_buffer.back().var.size(true)) {
case 8: _WI(CMP(reg64::RAX, (char) 0x0)); break;
case 4: _WI(CMP(reg32::EAX, (char) 0x0)); break;
case 2: _WI(CMP(reg16::AX, (char) 0x0)); break;
case 1: _WI(CMP(reg8::AL, (char) 0x0)); break;
}
}
// Create a new parser expression and
// use number as the ternary id
parser_expression pe = pe_op;
// Jmp to end
// Kinda crap but will optimize later
if (number) {
if (postfix_buffer.back().number == 0)
_WI(JMP(get_ternary_second(ternary)));
} else
_WI(JE(get_ternary_second(ternary)));
// Pop postfix buffer
postfix_buffer.pop_back();
// Save obj_rbp offset
ulong s_sub_obj_rbp_sub_val = sub_obj_rbp_sub_val,
s_begin_rbp_offset = begin_rbp_offset;
// **************************
// FIRST VARIABLE
// **************************
// Get first value
parser p;
// Pushes nothing to stack
p.parse_value(*file, {':'}, nullptr, false, false);
// Push to stack
p.push_to_stack();
// Check stack empty
if (p.postfix_buffer.empty()) {
error_handler::compilation_error("stack empty after ternary ?");
goto main;
}
// If not empty
TYPE t = p.postfix_buffer.back().var.get_type();
// Jmp to end
_WI(JMP(get_ternary_end(ternary)));
// Create label if valid
CREATE_LABEL(get_ternary_second(ternary), true);
// **************************
// SECOND VARIABLE
// **************************
// Allocate is null
if (type == nullptr) {
_WI(SUB(reg64::RSP, (int) obj_rbp_sub_val));
}
// Adjust obj_rbp value
if (t.data_type == DATA_TYPE::NCLASS && t.mdata_type == META_DATA_TYPE::STORAGE)
obj_rbp_sub_val -= ::size(t);
// Load obj_rbp
sub_obj_rbp_sub_val = s_sub_obj_rbp_sub_val;
begin_rbp_offset = s_begin_rbp_offset;
// Get second value
p = parser();
p.parse_value(*file, {',', ')', ';'}, nullptr, false, false);
// Push value to stack if needed
p.push_to_stack();
// Check stack empty
if (p.postfix_buffer.empty()) {
error_handler::compilation_error("stack empty after ternary ?");
goto main;
}
// Re-roll a terminate character
for (char c : {',', ')', ';'}) {
if (p.terminate_character == c) {
--p.file->get_current_offset(); break;
}
}
// Create label if valid
CREATE_LABEL(get_ternary_end(ternary), true);
// Set to stack value
if (!p.postfix_buffer.back().var.is_nclass())
p.postfix_buffer.back().pe_id = parser_expression_id::STACK_VALUE;
// Push to stack
postfix_buffer.push_back(p.postfix_buffer.back());
// Check left operator
check_left_operator();
}
}
// PLUS / MINUS / STAR / FORWARD SLASH ...
else if (pe_op != pe_operator::NULL_OPERATOR) {
// Pop until precedence
pop_until_precedence(precedence);
// And push operator to stack
pe_stack.push(pe_op);
// Check left operator
check_left_operator();
}
// *************************************
// Operand
// *************************************
else {
// Number system
num_sys ns;
// Check if it is a number
if ((ns = is_number(token)) != (num_sys) -1) {
// Push the number to the stack
try {
postfix_buffer.push_back(std::stoul(token, nullptr, (int) ns));
} catch (std::exception& ex) {
// TODO: give types on error
postfix_buffer.push_back(0);
error_handler::compilation_error("number too large; must be in '" + C_GREEN + "64-bit " + C_GREEN + "(<" + C_RED + "-" + C_BLUE + "9223372036854775809" + C_GREEN + "," + C_BLUE + "18446744073709551615" + C_GREEN + ">)'" + C_CLR + " value range");
}
}
// Else it must be a variable/method
else {
// *******************************
// CONSTANTS
// *******************************
// Check if constant
// TRUE
if (token == "true") {
// Push 1
postfix_buffer.push_back(1);
continue;
}
// FALSE
else if (token == "false") {
// Push 0
postfix_buffer.push_back(0);
continue;
}
// NULLPTR
else if (token == "nullptr") {
// Push 0
postfix_buffer.push_back(0);
continue;
}
// Check character
else if (token == "'") {
// Push character to stack
postfix_buffer.push_back(parse_char(*file));
continue;
}
// String parsing
else if (token == "\"") {
// Parse string and push to stack
postfix_buffer.push_back(*create_string(parse_string(*file)));
continue;
}
// *******************************
// SETUP
// *******************************
// Current nclass, voffset
uint voffset = 0;
nclass* save_cn = compiling_nclass;
method* save_cm = compiling_method;
// First variable flags
bool first_var = true, in_rax = false;
// The variable path
path var_path;
// Create a variable to return if found
variable var;
// *******************************
// CHECK NAMESPACE AND TEMPORARY NCLASS CREATION / ENUM
// *******************************
ENUM* en = nullptr;
// Check namespace and get enum if found
check_for_namespace(token, file, en);
// If enum found
if (en) {
// Set type of enum, name, pointer
var.get_type().data_type = DATA_TYPE::ENUM;
var.get_type().en = en;
var.on_stack = true;
var.is_data_pointer = true;
// Get enum
for (auto& p : en->values) {
if (p.first == token) {
_WI(PUSH((int) p.second));
// Push var to stack
postfix_buffer.push_back(var);
goto main;
}
}
// If enum value does not exists
error_handler::compilation_error("enum value '" + get_name_from_type(var.get_type()) + C_RED + "::" + C_BLUE + token + C_CLR + "' not found");
// Push var to stack
postfix_buffer.push_back(var);
continue;
}
// *******************************
// VARIABLE/METHOD REFERENCING
// *******************************
// While not end of file, parse value
while (!file->eof()) {
// Variable (var) is pushed to program stack => (var).X
if (token == ".") {
// ********************************
// CHECK ERRORS
// ********************************
// Check stack empty
if (postfix_buffer.empty()) {
error_handler::compilation_error("stack empty");
return;
}
// Check nclass type
else if (!postfix_buffer.back().is_variable() || !postfix_buffer.back().var.is_nclass()) {
error_handler::compilation_error("variable is not of an nclass type");
return;
}
// ********************************
// SET VARIABLE
// ********************************
// Set variable
var = postfix_buffer.back().var;
// Don't check method again
compiling_method = nullptr;
// Set compiling nclass
compiling_nclass = var.get_type().obj_nclass;
// Remove it from stack
postfix_buffer.pop_back();
// ********************************
// MOVE VARIABLE TO RAX
// ********************************
// If variable is on stack => mov to RAX
if (var.on_stack || var.is_nclass_pointer_type()) {
// Move variable to rax from stack
var.move_to_reg((int) reg64::RAX);
// Reset on stack
var.on_stack = false;
// Set method in RAX
in_rax = true;
} else {
// Set voffset
voffset = var.get_var_offset();
}
// Set var path
var_path = var.get_path();
// Add var to var path
var_path.get_instances().push_back(var);
// Reset first var
first_var = false;
// Get next token
token = file->get_token();
}
// Variable (var) is pushed to program stack => (var)[X]
if (token == "[") {
// Check stack empty
if (postfix_buffer.empty()) {
error_handler::compilation_error("stack empty");
return;
}
// Set variable
var = postfix_buffer.back().var;
// Set var path to var.get_path()
var_path = var.get_path();
// Remove it from stack
postfix_buffer.pop_back();
// Check array
check_array(var, save_cn, save_cm, save_ns, file, in_rax, voffset, var_path);
}
// Check if next token is a bracket
// Method check
else if (file->is_token("(")) {
// ********************************
// TEMPORARY INSTANCE CREATION
// ********************************
// TODO: fix, it's broken; do not use
// Temporary instance creation
if (first_var) {
nclass* n;
if (n = get_nclass(token)) {
// NClass data type
DATA_TYPE dt = DATA_TYPE::NCLASS;
// Set variable props
var = variable("", {dt, META_DATA_TYPE::STORAGE, 0, n}, {}, file, 0, 0);
// Get obj size
uint size = align8(var.size());
// ***************************
// SETUP TEMPORARY STACK
// ***************************
// Subtract from rbp if not already
if (obj_rbp_sub == nullptr && !get_insts().empty())
_WI(SUB(reg64::RSP, (int) 0)), obj_rbp_sub = get_insts().back();
// Set rbp offset
var.get_rbp_offset() = ::begin_rbp_offset - 8 + size;
// Set obj_rbp_sub
obj_rbp_sub_val += size;
::begin_rbp_offset += size;
// Set var in var path
if (var_path.get_instances().empty())
var_path.get_instances().push_back(var);
else
// Set zeroth var_path
var_path.get_instances()[0] = var;
// Reset in rax, on stack
in_rax = false;
var.is_data_pointer = true;
// ***************************
// CALL CONSTRUCTOR
// ***************************
// Call its constructor
var.call_constructor();
// Reset first var
first_var = false;
// Reset method, load nclass, load namespace
compiling_namespace = save_ns;
compiling_nclass = n;
compiling_method = nullptr;
goto array_check;
}
}
// ********************************
// GETTING ARGUMENTS
// ********************************
// Create vectors for arguments
std::vector<variable> args;
std::vector<parser_expression> pargs;
// Reload the default nclass, method, namespace
nclass* nsave_cn = compiling_nclass;
method* nsave_cm = compiling_method;
NAMESPACE* nsave_ns = compiling_namespace;
compiling_nclass = save_cn;
compiling_method = save_cm;
compiling_namespace = save_ns;
// Get arguments
while (true) {
// Create a new parser
parser p;
// Set terminate characters, file, push
std::vector<char> term = {',', ')'};
p.terminate_characters = &term;
p.file = file;
// Convert the method arguments
p.to_postfix_notation();
// If empty => no argument
if (p.postfix_buffer.empty())
break;
// Save postfix buffer
pargs.push_back(p.postfix_buffer.back());
// Set every postfix expression to this method's variables
args.push_back(p.postfix_buffer.back().var);
// If end found, return
if (p.terminate_character == ')') {
break;
}
// If next character is not a comma, throw error
else if (p.terminate_character != ',') {
error_handler::compilation_error("missing dot");
return;
}
}
// Load back nclass, method, namespace
compiling_nclass = nsave_cn;
compiling_method = nsave_cm;
compiling_namespace = nsave_ns;
// The method to set
method m; nclass* obj_nclass = nullptr;
// Check if method exists
if (get_method(m, token, args, obj_nclass)) {
// ***************************
// METHOD CALLING
// ***************************
// Set caller to ME object
if (first_var == true && compiling_method != nullptr)
if (!compiling_method->get_variables().empty())
var = compiling_method->get_variables()[0], var_path.get_instances().push_back(var);
// If return type is an nclass -> change the compiling nclass
if (m.get_type().data_type == DATA_TYPE::NCLASS)
compiling_nclass = m.get_type().obj_nclass;
else
compiling_nclass = nullptr;
// ***************************
// CALL METHOD
// ***************************
// Whether we're returning an nclass
bool returning_nclass = m.get_type().data_type == DATA_TYPE::NCLASS
&& m.get_type().mdata_type == META_DATA_TYPE::STORAGE &&
m.get_type().obj_nclass->size() != 0;
// Set in rax
if (in_rax)
var.in_rax = true;
// Subtract from rbp if not already
if (returning_nclass && obj_rbp_sub == nullptr && !get_insts().empty())
_WI(SUB(reg64::RSP, (int) 0)), obj_rbp_sub = get_insts().back();
// Set voffset
var.get_var_offset() = voffset;
// If variable is a pointer and in rax => reset var_offset as
// lvalue is already set in rax
if (var.is_nclass_pointer_type() && var.in_rax)
var.get_var_offset() = 0;
// Set path
var.get_path() = var_path;
// Call the method (nclass / normal)
if (obj_nclass != nullptr)
m.in_nclass_call(var, pargs, obj_nclass);
else
m.call(pargs);
// ***************************
// SET RETURN TYPE
// ***************************
// Set lvalue to false
var.lvalue = false;
// Return type found in rax (IF NOT void OR nclass storage)
if (!(m.get_type().data_type == DATA_TYPE::VOID
&& m.get_type().mdata_type == META_DATA_TYPE::STORAGE))
in_rax = true;
// Set type
var.get_type() = m.get_type();
// Set var to copied
if (var.is_nclass_type())
var.is_copied = true;
// Reset voffset
voffset = 0;
// ***************************
// SETUP TEMPORARY STACK
// ***************************
// Set compiling nclass, method
if (returning_nclass) {
// Set to method's nclass
compiling_nclass = m.get_type().obj_nclass;
// Reset method
compiling_method = nullptr;
// Get obj size
uint size = align8(var.size());
// Set rbp offset
var.get_rbp_offset() = ::begin_rbp_offset - 8 + size;
// Set obj_rbp_sub
obj_rbp_sub_val += size;
::begin_rbp_offset += size;
// Set var in var path
if (var_path.get_instances().empty())
var_path.get_instances().push_back(var);
else
// Set zeroth var_path
var_path.get_instances()[0] = var;
// Reset in rax
in_rax = false;
}
// Reset first var
first_var = false;
}
// Method not found error
else {
// Throw method error
method_error(first_var, token, args);
}
}
// Check if token is a dot (variable already on top of stack)
else if (get_variable(var, token)) {
// Reset non method, compiling namespace, compiling method
compiling_namespace = nullptr;
compiling_method = nullptr;
// If var_path is empty -> copy var path
// This is because if the variable already has some path
// like me in nclasses, the me will be erased, so we need to copy it
if (first_var)
// Set var path
var_path = var.get_path();
// Set current compiling nclass
compiling_nclass = var.get_type().obj_nclass;
// Add the var to the var path (if an nclass)
if (file->check_token() == ".") {
// If an nclass type found -> add to voffset
if (var.is_nclass_type()) {
var_path.get_instances().push_back(var), voffset += var.get_var_offset();
}
// If nclass pointer type found -> reset voffset and go to pointer
else if (var.is_nclass_pointer_type()) {
// Set var path
var.get_path() = var_path;
// Add voffset
var.get_var_offset() += voffset;
// Move pointer to rax from lvalue rax
if (in_rax)
var.in_rax = true;
// Move pointer to rax
var.move_to_reg((int) reg64::RAX);
// Set var in rax to true, as we have just moved it to rax
in_rax = true;
var.on_stack = false;
// Push var to var path
var_path.get_instances().push_back(var);
// Reset voffset
voffset = 0;
// var.get_var_offset() = 0;
}
}
// Toggle first var flags
first_var = false;
}
// Token does not exist
else {
// Add to prev offset
error_handler::move_prev_offset(1);
// No matching variable found
error_handler::compilation_error("expression with the name '" + C_GREEN + token + C_CLR + "' could not be found");
}
// If an array
array_check: if (file->is_token("[")) {
// Add offset to voffset and set to var
var.get_var_offset() = voffset + var.get_var_offset();
// Add values to variable path
var.get_path() = var_path;
// Check array
check_array(var, save_cn, save_cm, save_ns, file, in_rax, voffset, var_path);
}
// Dot not found -> break while
if (!file->is_token(".") || file->check_token() == ";") {
// Add offset to voffset and set to var
var.get_var_offset() = voffset + var.get_var_offset();
// Set var path
var.get_path() = var_path;
// If variable in rax => push to stack
if (in_rax) {
// Reset in rax
var.in_rax = false;
// Set var on stack
var.on_stack = true;
// Push rax if not void
if (!(var.get_type().data_type == DATA_TYPE::VOID && var.get_type().mdata_type == META_DATA_TYPE::STORAGE))
// Push rax to stack
_WI(PUSH(reg64::RAX));
}
// Push variable to stack
postfix_buffer.push_back(var);
break;
}
// Get next token
token = file->get_token();
}
// Load compiling nclass, method, namespace
compiling_nclass = save_cn;
compiling_method = save_cm;
compiling_namespace = save_ns;
}
}
}
}
// Pop till end
pop_till_end();
}
// Executes the operation
void parser::do_operation(pe_operator& pe, parser_expression& pe1, parser_expression& pe2) {
// Get types from parser expressions
TYPE t1 = get_type(pe2);
TYPE t2 = get_type(pe1);
// Check type
if (!type_equal(t1, t2)) {
// Throw only non-ambiguous errors
if (t1.data_type <= (DATA_TYPE) DATA_TYPE_SIZE && t2.data_type <= (DATA_TYPE) DATA_TYPE_SIZE)
error_handler::compilation_error("cannot perform arithmetic on '" + get_type_info(t1) + "' and '" + get_type_info(t2) + "'");
return;
}
// No operator overloading
if ((pe1.is_variable() && pe1.var.get_type().data_type == DATA_TYPE::NCLASS && pe1.var.get_type().mdata_type == META_DATA_TYPE::STORAGE)
|| (pe2.is_variable() && pe2.var.get_type().data_type == DATA_TYPE::NCLASS && pe2.var.get_type().mdata_type == META_DATA_TYPE::STORAGE))
error_handler::compilation_error("cannot perform arithmetic on an nclass type");
// If both are numbers, just do the operation on them
if ((pe1.is_number() && pe2.is_number())) {
// ADD
if (pe == pe_operator::PLUS) {
// Numbers can't be too big; this can later be mended
postfix_buffer.push_back(pe2.number + pe1.number);
}
// SUBTRACT
else if (pe == pe_operator::MINUS) {
// Numbers can't be too big; this can later be mended
postfix_buffer.push_back(pe2.number - pe1.number);
}
// MULTIPLY
else if (pe == pe_operator::STAR) {
// Numbers can't be too big; this can later be mended
postfix_buffer.push_back(pe2.number * pe1.number);
}
// DIVIDE
else if (pe == pe_operator::FORWARD_SLASH) {
// Throw error if dividing by zero
if (pe1.number == 0) {
error_handler::compilation_error("cannot divide by zero");
postfix_buffer.push_back(pe2.number);
} else {
// Numbers can't be too big; this can later be mended
postfix_buffer.push_back(pe2.number / pe1.number);
}
}
// MODULO
else if (pe == pe_operator::MODULO) {
// Throw error if dividing by zero
if (pe1.number == 0) {
error_handler::compilation_error("cannot divide by zero");
postfix_buffer.push_back(pe2.number);
} else {
// Numbers can't be too big; this can later be mended
postfix_buffer.push_back(pe2.number % pe1.number);
}
}
// EQUAL
else if (pe == pe_operator::EQUAL) {
// Check equal
postfix_buffer.push_back(pe1.number == pe2.number);
}
// NOT EQUAL
else if (pe == pe_operator::NOT_EQUAL) {
// Check equal
postfix_buffer.push_back(pe1.number != pe2.number);
}
// LESSER
else if (pe == pe_operator::LESSER) {
// Check equal
postfix_buffer.push_back(pe1.number < pe2.number);
}
// LESSER OR EQUAL
else if (pe == pe_operator::LESSER_OR_EQUAL) {
// Check equal
postfix_buffer.push_back(pe1.number <= pe2.number);
}
// GREATER
else if (pe == pe_operator::GREATER) {
// Check equal
postfix_buffer.push_back(pe1.number > pe2.number);
}
// LESSER OR EQUAL
else if (pe == pe_operator::GREATER_OR_EQUAL) {
// Check equal
postfix_buffer.push_back(pe1.number >= pe2.number);
}
// AND
else if (pe == pe_operator::AMPERSAND) {
// Check equal
postfix_buffer.push_back(pe1.number & pe2.number);
}
// BINARY AND
else if (pe == pe_operator::DOUBLE_AMPERSAND) {
// Check equal
postfix_buffer.push_back(pe1.number && pe2.number);
}
// OR
else if (pe == pe_operator::VERTICAL_BAR) {
// Check equal
postfix_buffer.push_back(pe1.number | pe2.number);
}
// BINARY OR
else if (pe == pe_operator::DOUBLE_VERTICAL_BAR) {
// Check equal
postfix_buffer.push_back(pe1.number || pe2.number);
}
// XOR
else if (pe == pe_operator::XOR) {
// Check equal
postfix_buffer.push_back(pe1.number ^ pe2.number);
}
// MODULO
else if (pe == pe_operator::MODULO) {
// Check equal
postfix_buffer.push_back(pe1.number % pe2.number);
}
// RIGHT SHIFT
else if (pe == pe_operator::RIGHT_SHIFT) {
// Check equal
postfix_buffer.push_back(pe1.number >> pe2.number);
}
// LEFT SHIFT
else if (pe == pe_operator::LEFT_SHIFT) {
// Check equal
postfix_buffer.push_back(pe1.number << pe2.number);
}
}
// If not assigning to a variable
else {
// If first is a variable and second a number
// NUM <- VAR
if (pe2.is_number() && pe1.is_variable()) {
// ADD
if (pe == pe_operator::PLUS) {
// Add values from stack
ADD(pe1.var, pe2.number);
}
// SUBTRACT
else if (pe == pe_operator::MINUS) {
// Subtract values from stack
SUB(pe2.number, pe1.var);
}
// MULTIPLY
else if (pe == pe_operator::STAR) {
// Multiply values from stack
MUL(pe1.var, pe2.number);
}
// DIVIDE
else if (pe == pe_operator::FORWARD_SLASH) {
// Divide values from stack
DIV(pe2.number, pe1.var);
}
// MODULO
else if (pe == pe_operator::MODULO) {
// Divide values from stack
MOD(pe2.number, pe1.var);
}
// XOR
else if (pe == pe_operator::XOR) {
// Do operation
DO_OPERATION(OPERATION::XOR, pe1.var, pe2.number);
}
// RIGHT SHIFT
else if (pe == pe_operator::RIGHT_SHIFT) {
// Shift
SHIFT(INST_SHIFT::RIGHT_SHIFT, pe2.number, pe1.var);
}
// LEFT SHIFT
else if (pe == pe_operator::LEFT_SHIFT) {
// Shift
SHIFT(INST_SHIFT::LEFT_SHIFT, pe2.number, pe1.var);
}
// OR
else if (pe == pe_operator::VERTICAL_BAR) {
// Do operation
DO_OPERATION(OPERATION::OR, pe1.var, pe2.number);
}
// AND
else if (pe == pe_operator::AMPERSAND) {
// Do operation
DO_OPERATION(OPERATION::AND, pe1.var, pe2.number);
}
else goto bool_op_nv;
// Push stack value
postfix_buffer.push_back(pe1.var.get_type());
return;
bool_op_nv:
// EQUAL
if (pe == pe_operator::EQUAL) {
// Check equal values from stack
BOOL_OPER(pe1.var, pe2.number, BOOL_OP::EQUAL);
}
// NOT EQUAL
else if (pe == pe_operator::NOT_EQUAL) {
// Check values from stack
BOOL_OPER(pe2.number, pe1.var, BOOL_OP::NOT_EQUAL);
}
// LESSER
else if (pe == pe_operator::LESSER) {
// Check equal values from stack
BOOL_OPER(pe2.number, pe1.var, BOOL_OP::LESSER);
}
// LESSER_OR_EQUAL
else if (pe == pe_operator::LESSER_OR_EQUAL) {
// Check equal values from stack
BOOL_OPER(pe2.number, pe1.var, BOOL_OP::LESSER_OR_EQUAL);
}
// GREATER
else if (pe == pe_operator::GREATER) {
// Check equal values from stack
BOOL_OPER(pe2.number, pe1.var, BOOL_OP::GREATER);
}
// GREATER_OR_EQUAL
else if (pe == pe_operator::GREATER_OR_EQUAL) {
// Check equal values from stack
BOOL_OPER(pe2.number, pe1.var, BOOL_OP::GREATER_OR_EQUAL);
}
// BINARY AND
else if (pe == pe_operator::DOUBLE_AMPERSAND) {
// Do operation
DO_OPERATION(OPERATION::AND, pe1.var, pe2.number);
}
// BINARY OR
else if (pe == pe_operator::DOUBLE_VERTICAL_BAR) {
// Do operation
DO_OPERATION(OPERATION::OR, pe1.var, pe2.number);
}
// Push stack value
postfix_buffer.push_back(BOOL);
}
// If first is a number and second a variable
// VAR <- NUM
else if (pe2.is_variable() && pe1.is_number()) {
// ADD
if (pe == pe_operator::PLUS) {
// Add values from stack
ADD(pe2.var, pe1.number);
}
// SUBTRACT
else if (pe == pe_operator::MINUS) {
// Subtract values from stack
SUB(pe2.var, pe1.number);
}
// MULTIPLY
else if (pe == pe_operator::STAR) {
// Multiply values from stack
MUL(pe2.var, pe1.number);
}
// DIVIDE
else if (pe == pe_operator::FORWARD_SLASH) {
// Divide values from stack
DIV(pe2.var, pe1.number);
}
// MODULO
else if (pe == pe_operator::MODULO) {
// Divide values from stack
MOD(pe2.var, pe1.number);
}
// XOR
else if (pe == pe_operator::XOR) {
// Do operation
DO_OPERATION(OPERATION::XOR, pe2.var, pe1.number);
}
// RIGHT SHIFT
else if (pe == pe_operator::RIGHT_SHIFT) {
// Shift
SHIFT(INST_SHIFT::RIGHT_SHIFT, pe2.var, pe1.number);
}
// LEFT SHIFT
else if (pe == pe_operator::LEFT_SHIFT) {
// Shift
SHIFT(INST_SHIFT::LEFT_SHIFT, pe2.var, pe1.number);
}
// OR
else if (pe == pe_operator::VERTICAL_BAR) {
// Do operation
DO_OPERATION(OPERATION::OR, pe2.var, pe1.number);
}
// AND
else if (pe == pe_operator::AMPERSAND) {
// Do operation
DO_OPERATION(OPERATION::AND, pe2.var, pe1.number);
}
else goto bool_op_vn;
// Push stack value
postfix_buffer.push_back(pe2.var.get_type());
return;
bool_op_vn:
// EQUAL
if (pe == pe_operator::EQUAL) {
// Divide values from stack
BOOL_OPER(pe2.var, pe1.number, BOOL_OP::EQUAL);
}
// NOT EQUAL
else if (pe == pe_operator::NOT_EQUAL) {
// Divide values from stack
BOOL_OPER(pe2.var, pe1.number, BOOL_OP::NOT_EQUAL);
}
// LESSER
else if (pe == pe_operator::LESSER) {
// Check equal values from stack
BOOL_OPER(pe2.var, pe1.number, BOOL_OP::LESSER);
}
// LESSER_OR_EQUAL
else if (pe == pe_operator::LESSER_OR_EQUAL) {
// Check equal values from stack
BOOL_OPER(pe2.var, pe1.number, BOOL_OP::LESSER_OR_EQUAL);
}
// GREATER
else if (pe == pe_operator::GREATER) {
// Check equal values from stack
BOOL_OPER(pe2.var, pe1.number, BOOL_OP::GREATER);
}
// GREATER_OR_EQUAL
else if (pe == pe_operator::GREATER_OR_EQUAL) {
// Check equal values from stack
BOOL_OPER(pe2.var, pe1.number, BOOL_OP::GREATER_OR_EQUAL);
}
// BINARY AND
else if (pe == pe_operator::DOUBLE_AMPERSAND) {
// Do operation
DO_OPERATION(OPERATION::AND, pe2.var, pe1.number);
}
// BINARY OR
else if (pe == pe_operator::DOUBLE_VERTICAL_BAR) {
// Do operation
DO_OPERATION(OPERATION::OR, pe2.var, pe1.number);
}
// Push stack value
postfix_buffer.push_back(BOOL);
}
// If variable & variable
// VAR <- VAR
else if (pe2.is_variable() && pe1.is_variable()) {
// ADD
if (pe == pe_operator::PLUS) {
// Add values from stack
ADD(pe2.var, pe1.var);
}
// SUBTRACT
else if (pe == pe_operator::MINUS) {
// Subtract values from stack
SUB(pe2.var, pe1.var);
}
// MULTIPLY
else if (pe == pe_operator::STAR) {
// Multiply values from stack
MUL(pe2.var, pe1.var);
}
// DIVIDE
else if (pe == pe_operator::FORWARD_SLASH) {
// Divide values from stack
DIV(pe2.var, pe1.var);
}
// MODULO
else if (pe == pe_operator::MODULO) {
// Divide values from stack
MOD(pe2.var, pe1.var);
}
// XOR
else if (pe == pe_operator::XOR) {
// Do operation
DO_OPERATION(OPERATION::XOR, pe2.var, pe1.var);
}
// RIGHT SHIFT
else if (pe == pe_operator::RIGHT_SHIFT) {
// Shift
SHIFT(INST_SHIFT::RIGHT_SHIFT, pe2.var, pe1.var);
}
// LEFT SHIFT
else if (pe == pe_operator::LEFT_SHIFT) {
// Shift
SHIFT(INST_SHIFT::LEFT_SHIFT, pe2.var, pe1.var);
}
// OR
else if (pe == pe_operator::VERTICAL_BAR) {
// Do operation
DO_OPERATION(OPERATION::OR, pe2.var, pe1.var);
}
// AND
else if (pe == pe_operator::AMPERSAND) {
// Do operation
DO_OPERATION(OPERATION::AND, pe2.var, pe1.var);
}
else goto bool_op_vv;
// Push stack value
pe1.var.size() > pe2.var.size()
? postfix_buffer.push_back(pe1.var.get_type())
: postfix_buffer.push_back(pe2.var.get_type());
return;
bool_op_vv:
// EQUAL
if (pe == pe_operator::EQUAL) {
// Divide values from stack
BOOL_OPER(pe2.var, pe1.var, BOOL_OP::EQUAL);
}
// NOT EQUAL
else if (pe == pe_operator::NOT_EQUAL) {
// Divide values from stack
BOOL_OPER(pe2.var, pe1.var, BOOL_OP::NOT_EQUAL);
}
// LESSER
else if (pe == pe_operator::LESSER) {
// Check equal values from stack
BOOL_OPER(pe2.var, pe1.var, BOOL_OP::LESSER);
}
// LESSER_OR_EQUAL
else if (pe == pe_operator::LESSER_OR_EQUAL) {
// Check equal values from stack
BOOL_OPER(pe2.var, pe1.var, BOOL_OP::LESSER_OR_EQUAL);
}
// GREATER
else if (pe == pe_operator::GREATER) {
// Check equal values from stack
BOOL_OPER(pe2.var, pe1.var, BOOL_OP::GREATER);
}
// GREATER_OR_EQUAL
else if (pe == pe_operator::GREATER_OR_EQUAL) {
// Check equal values from stack
BOOL_OPER(pe2.var, pe1.var, BOOL_OP::GREATER_OR_EQUAL);
}
// BINARY AND
else if (pe == pe_operator::DOUBLE_AMPERSAND) {
// Do operation
DO_OPERATION(OPERATION::AND, pe2.var, pe1.var);
}
// BINARY OR
else if (pe == pe_operator::DOUBLE_VERTICAL_BAR) {
// Do operation
DO_OPERATION(OPERATION::OR, pe2.var, pe1.var);
}
// Push stack value
postfix_buffer.push_back(BOOL);
}
// If stack variable & number
// STACK_VAR <- NUM
else if (pe2.is_stack_val() && pe1.is_number()) {
// ADD
if (pe == pe_operator::PLUS) {
// Add values from stack
ADD(pe2.var.get_type(), pe1.number);
}
// SUBTRACT
else if (pe == pe_operator::MINUS) {
// Subtract values from stack
SUB(pe2.var.get_type(), pe1.number);
}
// MULTIPLY
else if (pe == pe_operator::STAR) {
// Multiply values from stack
MUL(pe2.var.get_type(), pe1.number);
}
// DIVIDE
else if (pe == pe_operator::FORWARD_SLASH) {
// Divide values from stack
DIV(pe2.var.get_type(), pe1.number);
}
// MODULO
else if (pe == pe_operator::MODULO) {
// Divide values from stack
MOD(pe2.var.get_type(), pe1.number);
}
// XOR
else if (pe == pe_operator::XOR) {
// Do operation
DO_OPERATION(OPERATION::XOR, pe2.var.get_type(), pe1.number);
}
// RIGHT SHIFT
else if (pe == pe_operator::RIGHT_SHIFT) {
// Shift
SHIFT(INST_SHIFT::RIGHT_SHIFT, pe2.var.get_type(), pe1.number);
}
// LEFT SHIFT
else if (pe == pe_operator::LEFT_SHIFT) {
// Shift
SHIFT(INST_SHIFT::LEFT_SHIFT, pe2.var.get_type(), pe1.number);
}
// AND
else if (pe == pe_operator::AMPERSAND) {
// Do operation
DO_OPERATION(OPERATION::AND, pe2.var.get_type(), pe1.number);
}
// OR
else if (pe == pe_operator::VERTICAL_BAR) {
// Do operation
DO_OPERATION(OPERATION::OR, pe2.var.get_type(), pe1.number);
}
else goto bool_op_sn;
// Push stack value
postfix_buffer.push_back(pe2.var.get_type());
return;
bool_op_sn:
// EQUAL
if (pe == pe_operator::EQUAL) {
// Divide values from stack
BOOL_OPER(pe2.var.get_type(), pe1.number, BOOL_OP::EQUAL);
}
// NOT EQUAL
else if (pe == pe_operator::NOT_EQUAL) {
// Divide values from stack
BOOL_OPER(pe2.var.get_type(), pe1.number, BOOL_OP::NOT_EQUAL);
}
// LESSER
else if (pe == pe_operator::LESSER) {
// Check equal values from stack
BOOL_OPER(pe2.var.get_type(), pe1.number, BOOL_OP::LESSER);
}
// LESSER_OR_EQUAL
else if (pe == pe_operator::LESSER_OR_EQUAL) {
// Check equal values from stack
BOOL_OPER(pe2.var.get_type(), pe1.number, BOOL_OP::LESSER_OR_EQUAL);
}
// GREATER
else if (pe == pe_operator::GREATER) {
// Check equal values from stack
BOOL_OPER(pe2.var.get_type(), pe1.number, BOOL_OP::GREATER);
}
// GREATER_OR_EQUAL
else if (pe == pe_operator::GREATER_OR_EQUAL) {
// Check equal values from stack
BOOL_OPER(pe2.var.get_type(), pe1.number, BOOL_OP::GREATER_OR_EQUAL);
}
// BINARY AND
else if (pe == pe_operator::DOUBLE_AMPERSAND) {
// Do operation
DO_OPERATION(OPERATION::AND, pe2.var.get_type(), pe1.number);
}
// BINARY OR
else if (pe == pe_operator::DOUBLE_VERTICAL_BAR) {
// Do operation
DO_OPERATION(OPERATION::OR, pe2.var.get_type(), pe1.number);
}
// Push bool value
postfix_buffer.push_back(BOOL);
}
// If number & stack variable
// NUM -> STACK_VAR
else if (pe2.is_number() && pe1.is_stack_val()) {
// ADD
if (pe == pe_operator::PLUS) {
// Add values from stack
ADD(pe1.var.get_type(), pe2.number);
}
// SUBTRACT
else if (pe == pe_operator::MINUS) {
// Subtract values from stack
SUB(pe2.number, pe1.var.get_type());
}
// MULTIPLY
else if (pe == pe_operator::STAR) {
// Multiply values from stack
MUL(pe1.var.get_type(), pe2.number);
}
// DIVIDE
else if (pe == pe_operator::FORWARD_SLASH) {
// Divide values from stack
DIV(pe2.number, pe1.var.get_type());
}
// MODULO
else if (pe == pe_operator::MODULO) {
// Divide values from stack
MOD(pe2.number, pe1.var.get_type());
}
// XOR
else if (pe == pe_operator::XOR) {
// Do operation
DO_OPERATION(OPERATION::XOR, pe1.var.get_type(), pe2.number);
}
// RIGHT SHIFT
else if (pe == pe_operator::RIGHT_SHIFT) {
// Shift
SHIFT(INST_SHIFT::RIGHT_SHIFT, pe2.number, pe1.var.get_type());
}
// LEFT SHIFT
else if (pe == pe_operator::LEFT_SHIFT) {
// Shift
SHIFT(INST_SHIFT::LEFT_SHIFT, pe2.number, pe1.var.get_type());
}
// AND
else if (pe == pe_operator::AMPERSAND) {
// Do operation
DO_OPERATION(OPERATION::AND, pe1.var.get_type(), pe2.number);
}
// OR
else if (pe == pe_operator::VERTICAL_BAR) {
// Do operation
DO_OPERATION(OPERATION::OR, pe1.var.get_type(), pe2.number);
}
else goto bool_op_ns;
// Push stack value
// Push stack value
postfix_buffer.push_back(pe1.var.get_type());
return;
bool_op_ns:
// EQUAL
if (pe == pe_operator::EQUAL) {
// Divide values from stack
BOOL_OPER(pe1.var.get_type(), pe2.number, BOOL_OP::EQUAL);
}
// NOT EQUAL
else if (pe == pe_operator::NOT_EQUAL) {
// Divide values from stack
BOOL_OPER(pe2.number, pe1.var.get_type(), BOOL_OP::NOT_EQUAL);
}
// LESSER
else if (pe == pe_operator::LESSER) {
// Check equal values from stack
BOOL_OPER(pe2.number, pe1.var.get_type(), BOOL_OP::LESSER);
}
// LESSER_OR_EQUAL
else if (pe == pe_operator::LESSER_OR_EQUAL) {
// Check equal values from stack
BOOL_OPER(pe2.number, pe1.var.get_type(), BOOL_OP::LESSER_OR_EQUAL);
}
// GREATER
else if (pe == pe_operator::GREATER) {
// Check equal values from stack
BOOL_OPER(pe2.number, pe1.var.get_type(), BOOL_OP::GREATER);
}
// GREATER_OR_EQUAL
else if (pe == pe_operator::GREATER_OR_EQUAL) {
// Check equal values from stack
BOOL_OPER(pe2.number, pe1.var.get_type(), BOOL_OP::GREATER_OR_EQUAL);
}
// BINARY AND
else if (pe == pe_operator::DOUBLE_AMPERSAND) {
// Do operation
DO_OPERATION(OPERATION::AND, pe1.var.get_type(), pe2.number);
}
// BINARY OR
else if (pe == pe_operator::DOUBLE_VERTICAL_BAR) {
// Do operation
DO_OPERATION(OPERATION::OR, pe1.var.get_type(), pe2.number);
}
// Push bool value
postfix_buffer.push_back(BOOL);
}
// If stack variable & number
// STACK_VAR <- VAR
else if (pe2.is_stack_val() && pe1.is_variable()) {
// ADD
if (pe == pe_operator::PLUS) {
// Add values from stack
ADD(pe2.var.get_type(), pe1.var);
}
// SUBTRACT
else if (pe == pe_operator::MINUS) {
// Subtract values from stack
SUB(pe2.var.get_type(), pe1.var);
}
// MULTIPLY
else if (pe == pe_operator::STAR) {
// Multiply values from stack
MUL(pe2.var.get_type(), pe1.var);
}
// DIVIDE
else if (pe == pe_operator::FORWARD_SLASH) {
// Divide values from stack
DIV(pe2.var.get_type(), pe1.var);
}
// MODULO
else if (pe == pe_operator::MODULO) {
// Divide values from stack
MOD(pe2.var.get_type(), pe1.var);
}
// XOR
else if (pe == pe_operator::XOR) {
// Do operation
DO_OPERATION(OPERATION::XOR, pe2.var.get_type(), pe1.var);
}
// RIGHT SHIFT
else if (pe == pe_operator::RIGHT_SHIFT) {
// Shift
SHIFT(INST_SHIFT::RIGHT_SHIFT, pe2.var.get_type(), pe1.var);
}
// LEFT SHIFT
else if (pe == pe_operator::LEFT_SHIFT) {
// Shift
SHIFT(INST_SHIFT::LEFT_SHIFT, pe2.var.get_type(), pe1.var);
}
// AND
else if (pe == pe_operator::AMPERSAND) {
// Do operation
DO_OPERATION(OPERATION::AND, pe2.var.get_type(), pe1.var);
}
// OR
else if (pe == pe_operator::VERTICAL_BAR) {
// Do operation
DO_OPERATION(OPERATION::OR, pe2.var.get_type(), pe1.var);
}
else goto bool_op_sv;
// Push stack value
pe1.var.size() > pe2.var.size()
? postfix_buffer.push_back(pe1.var.get_type())
: postfix_buffer.push_back(pe2.var.get_type());
return;
bool_op_sv:
// EQUAL
if (pe == pe_operator::EQUAL) {
// Divide values from stack
BOOL_OPER(pe1.var, pe2.var.get_type(), BOOL_OP::EQUAL);
}
// NOT EQUAL
else if (pe == pe_operator::NOT_EQUAL) {
// Divide values from stack
BOOL_OPER(pe2.var.get_type(), pe1.var, BOOL_OP::NOT_EQUAL);
}
// LESSER
else if (pe == pe_operator::LESSER) {
// Check equal values from stack
BOOL_OPER(pe2.var.get_type(), pe1.var, BOOL_OP::LESSER);
}
// LESSER_OR_EQUAL
else if (pe == pe_operator::LESSER_OR_EQUAL) {
// Check equal values from stack
BOOL_OPER(pe2.var.get_type(), pe1.var, BOOL_OP::LESSER_OR_EQUAL);
}
// GREATER
else if (pe == pe_operator::GREATER) {
// Check equal values from stack
BOOL_OPER(pe2.var.get_type(), pe1.var, BOOL_OP::GREATER);
}
// GREATER_OR_EQUAL
else if (pe == pe_operator::GREATER_OR_EQUAL) {
// Check equal values from stack
BOOL_OPER(pe2.var.get_type(), pe1.var, BOOL_OP::GREATER_OR_EQUAL);
}
// BINARY AND
else if (pe == pe_operator::DOUBLE_AMPERSAND) {
// Do operation
DO_OPERATION(OPERATION::AND, pe2.var.get_type(), pe1.var);
}
// BINARY OR
else if (pe == pe_operator::DOUBLE_VERTICAL_BAR) {
// Do operation
DO_OPERATION(OPERATION::OR, pe2.var.get_type(), pe1.var);
}
// Push bool value
postfix_buffer.push_back(BOOL);
}
// If number & stack variable
// VAR -> STACK_VAR
else if (pe2.is_variable() && pe1.is_stack_val()) {
// ADD
if (pe == pe_operator::PLUS) {
// Add values from stack
ADD(pe2.var, pe1.var.get_type());
}
// SUBTRACT
else if (pe == pe_operator::MINUS) {
// Subtract values from stack
SUB(pe2.var, pe1.var.get_type());
}
// MULTIPLY
else if (pe == pe_operator::STAR) {
// Multiply values from stack
MUL(pe2.var, pe1.var.get_type());
}
// DIVIDE
else if (pe == pe_operator::FORWARD_SLASH) {
// Divide values from stack
DIV(pe2.var, pe1.var.get_type());
}
// MODULO
else if (pe == pe_operator::MODULO) {
// Divide values from stack
MOD(pe2.var, pe1.var.get_type());
}
// XOR
else if (pe == pe_operator::XOR) {
// Do operation
DO_OPERATION(OPERATION::XOR, pe2.var, pe1.var.get_type());
}
// RIGHT SHIFT
else if (pe == pe_operator::RIGHT_SHIFT) {
// Shift
SHIFT(INST_SHIFT::RIGHT_SHIFT, pe2.var, pe1.var.get_type());
}
// LEFT SHIFT
else if (pe == pe_operator::LEFT_SHIFT) {
// Shift
SHIFT(INST_SHIFT::LEFT_SHIFT, pe2.var, pe1.var.get_type());
}
// AND
else if (pe == pe_operator::AMPERSAND) {
// Do operation
DO_OPERATION(OPERATION::AND, pe2.var, pe1.var.get_type());
}
// OR
else if (pe == pe_operator::VERTICAL_BAR) {
// Do operation
DO_OPERATION(OPERATION::OR, pe2.var, pe1.var.get_type());
}
else goto bool_op_vs;
// Push stack value
pe1.var.size() > pe2.var.size()
? postfix_buffer.push_back(pe1.var.get_type())
: postfix_buffer.push_back(pe2.var.get_type());
return;
bool_op_vs:
// EQUAL
if (pe == pe_operator::EQUAL) {
// Divide values from stack
BOOL_OPER(pe2.var, pe1.var.get_type(), BOOL_OP::EQUAL);
}
// NOT EQUAL
else if (pe == pe_operator::NOT_EQUAL) {
// Divide values from stack
BOOL_OPER(pe2.var, pe1.var.get_type(), BOOL_OP::NOT_EQUAL);
}
// LESSER
else if (pe == pe_operator::LESSER) {
// Check equal values from stack
BOOL_OPER(pe2.var, pe1.var.get_type(), BOOL_OP::LESSER);
}
// LESSER_OR_EQUAL
else if (pe == pe_operator::LESSER_OR_EQUAL) {
// Check equal values from stack
BOOL_OPER(pe2.var, pe1.var.get_type(), BOOL_OP::LESSER_OR_EQUAL);
}
// GREATER
else if (pe == pe_operator::GREATER) {
// Check equal values from stack
BOOL_OPER(pe2.var, pe1.var.get_type(), BOOL_OP::GREATER);
}
// GREATER_OR_EQUAL
else if (pe == pe_operator::GREATER_OR_EQUAL) {
// Check equal values from stack
BOOL_OPER(pe2.var, pe1.var.get_type(), BOOL_OP::GREATER_OR_EQUAL);
}
// BINARY AND
else if (pe == pe_operator::DOUBLE_AMPERSAND) {
// Do operation
DO_OPERATION(OPERATION::AND, pe2.var, pe1.var.get_type());
}
// BINARY OR
else if (pe == pe_operator::DOUBLE_VERTICAL_BAR) {
// Do operation
DO_OPERATION(OPERATION::OR, pe2.var, pe1.var.get_type());
}
// Push bool value
postfix_buffer.push_back(BOOL);
}
// If both are stack values
else {
// ADD
if (pe == pe_operator::PLUS) {
// Add values from stack
ADD(pe2.var.get_type(), pe1.var.get_type());
}
// SUBTRACT
else if (pe == pe_operator::MINUS) {
// Subtract values from stack
SUB(pe2.var.get_type(), pe1.var.get_type());
}
// MULTIPLY
else if (pe == pe_operator::STAR) {
// Multiply values from stack
MUL(pe2.var.get_type(), pe1.var.get_type());
}
// DIVIDE
else if (pe == pe_operator::FORWARD_SLASH) {
DIV(pe2.var.get_type(), pe1.var.get_type());
}
// MODULO
else if (pe == pe_operator::MODULO) {
MOD(pe2.var.get_type(), pe1.var.get_type());
}
// XOR
else if (pe == pe_operator::XOR) {
// Do operation
DO_OPERATION(OPERATION::XOR, pe2.var.get_type(), pe1.var.get_type());
}
// RIGHT SHIFT
else if (pe == pe_operator::RIGHT_SHIFT) {
// Shift
SHIFT(INST_SHIFT::RIGHT_SHIFT, pe2.var.get_type(), pe1.var.get_type());
}
// LEFT SHIFT
else if (pe == pe_operator::LEFT_SHIFT) {
// Shift
SHIFT(INST_SHIFT::LEFT_SHIFT, pe2.var.get_type(), pe1.var.get_type());
}
// OR
else if (pe == pe_operator::VERTICAL_BAR) {
// Do operation
DO_OPERATION(OPERATION::OR, pe2.var.get_type(), pe1.var.get_type());
}
// AND
else if (pe == pe_operator::AMPERSAND) {
// Do operation
DO_OPERATION(OPERATION::AND, pe2.var.get_type(), pe1.var.get_type());
}
else goto bool_op_ss;
// Push stack value
pe1.var.size() > pe2.var.size()
? postfix_buffer.push_back(pe1.var.get_type())
: postfix_buffer.push_back(pe2.var.get_type());
return;
bool_op_ss:
// EQUAL
if (pe == pe_operator::EQUAL) {
BOOL_OPER(pe2.var.get_type(), pe1.var.get_type(), BOOL_OP::EQUAL);
}
// NOT EQUAL
else if (pe == pe_operator::NOT_EQUAL) {
BOOL_OPER(pe2.var.get_type(), pe1.var.get_type(), BOOL_OP::NOT_EQUAL);
}
// LESSER
else if (pe == pe_operator::LESSER) {
// Check equal values from stack
BOOL_OPER(pe2.var.get_type(), pe1.var.get_type(), BOOL_OP::LESSER);
}
// LESSER_OR_EQUAL
else if (pe == pe_operator::LESSER_OR_EQUAL) {
// Check equal values from stack
BOOL_OPER(pe2.var.get_type(), pe1.var.get_type(), BOOL_OP::LESSER_OR_EQUAL);
}
// GREATER
else if (pe == pe_operator::GREATER) {
// Check equal values from stack
BOOL_OPER(pe2.var.get_type(), pe1.var.get_type(), BOOL_OP::GREATER);
}
// GREATER_OR_EQUAL
else if (pe == pe_operator::GREATER_OR_EQUAL) {
// Check equal values from stack
BOOL_OPER(pe2.var.get_type(), pe1.var.get_type(), BOOL_OP::GREATER_OR_EQUAL);
}
// BINARY AND
else if (pe == pe_operator::DOUBLE_AMPERSAND) {
// Do operation
DO_OPERATION(OPERATION::AND, pe2.var.get_type(), pe1.var.get_type());
}
// BINARY OR
else if (pe == pe_operator::DOUBLE_VERTICAL_BAR) {
// Do operation
DO_OPERATION(OPERATION::OR, pe2.var.get_type(), pe1.var.get_type());
}
// Push stack value
postfix_buffer.push_back(BOOL);
}
}
}
// Evaluates the operator
void parser::evaluate_operator() {
// If it's an operator
// Get operator from stack and execute the operation if found
parser_expression& pe = pe_stack.top();
// Throw error if stack empty
if (postfix_buffer.empty()) {
if (pe._operator == pe_operator::CAST)
error_handler::compilation_error("cannot cast; no expression was found to be cast");
else
error_handler::compilation_error("cannot use operator; no expression was found to be used");
return;
}
// If negate
if (pe._operator == pe_operator::NEGATE || pe._operator == pe_operator::NEGATE_VALUE) {
// Get parser expr
parser_expression& pe1 = postfix_buffer.back();
// Cannot negate nclass variable
if (pe1.var.get_type().data_type == DATA_TYPE::NCLASS) {
error_handler::compilation_error("cannot negate an nclass variable");
return;
}
// If number -> negate
if (pe1.is_number()) {
// Negate number
pe1.number = -pe1.number;
// Put back on stack
postfix_buffer.back() = pe1;
}
// Negate a variable
else if (pe1.is_variable()) {
// Neg RAX
switch (pe1.var.size()) {
case 8: {
pe1.var.move_to_reg((int) reg64::RAX);
_WI(NEG(reg64::RAX));
break;
}
case 4: {
pe1.var.move_to_reg((int) reg64::RAX);
_WI(NEG(reg32::EAX));
break;
}
case 2: {
pe1.var.move_to_reg((int) reg64::RAX);
_WI(NEG(reg16::AX));
break;
}
case 1: {
pe1.var.move_to_reg((int) reg64::RAX);
_WI(NEG(reg8::AL));
break;
}
}
// Push RAX
_PUSH_REG(RAX);
// Put type on stack
postfix_buffer.back() = pe1.var.get_type();
}
// Negate stack variable
else {
// Negate top of stack
_WI(NEG(effective_address<reg64>(reg64::RSP), PTR_SIZE::QWORD));
// Put type on stack
postfix_buffer.back() = pe1.var.get_type();
}
}
// If reference
else if (pe._operator == pe_operator::REFERENCE) {
// Get parser expr
parser_expression& pe1 = postfix_buffer.back();
// TODO: add stack val
// If not a variable -> throw error
if (pe1.is_variable()) {
// Variable must be an lvalue
if (!pe1.var.lvalue) {
error_handler::compilation_error("cannot get a pointer from an " + C_GREEN + "rvalue" + C_CLR + " token");
return;
}
// Push to stack
pe1.var.push_pointer_to_stack();
// Set on stack, reset in rax
pe1.var.on_stack = true;
pe1.var.in_rax = false;
// Change type to pointer type
pe1.var.get_type().mdata_type = META_DATA_TYPE::POINTER;
++pe1.var.get_type().mdata_size;
// Change to stack value
pe1.pe_id = parser_expression_id::STACK_VALUE;
}
// Throw error -> only lvalues allowed
else {
error_handler::compilation_error("only variables can be referenced");
}
}
// If pointer
else if (pe._operator == pe_operator::POINTER) {
// Get parser expr
parser_expression& pe1 = postfix_buffer.back();
// If not a variable -> throw error
if (pe1.var.get_type().mdata_type == META_DATA_TYPE::POINTER) {
if (pe1.var.on_stack && pe1.is_variable()) {
// Change type to pointer type
// Go into the variable on top of stack
pe1.var.move_to_reg((int) reg64::RAX);
_WI(PUSH(reg64::RAX));
}
// Value is a variable not on stack
else if (pe1.is_variable()) {
// Dereference the pointer
pe1.var.push_to_stack();
}
// Expr must be a variable
else if (!pe1.is_stack_val()) {
error_handler::compilation_error("expression must be a modifiable " + C_BLUE + "lvalue" + C_CLR);
}
}
// Throw error as type is not a pointer
else {
error_handler::compilation_error("dereferencing a non-pointer type '" + get_type_info(pe1.var.get_type()) + "'; value must be a pointer");
return;
}
// Let's keep the lvalue, on stack to true, in rax to false
pe1.var.lvalue = true;
pe1.var.on_stack = true;
pe1.var.in_rax = false;
// Reset var offset
pe1.var.get_var_offset() = 0;
// If size is zero -> change to storage
if (--pe1.var.get_type().mdata_size == 0)
pe1.var.get_type().mdata_type = META_DATA_TYPE::STORAGE, pe1.var.get_type().asize.clear();
// Change to stack value
pe1.pe_id = parser_expression_id::VARIABLE;
}
// If bool negate
else if (pe._operator == pe_operator::BOOL_NEGATE) {
// Get parser expr
parser_expression& pe1 = postfix_buffer.back(); postfix_buffer.pop_back();
// Can only invert a number
if (pe1.var.get_type().data_type == DATA_TYPE::NCLASS) {
error_handler::compilation_error("cannot invert an nclass variable");
return;
}
// If number -> invert
if (pe1.is_number()) {
// Invert number
pe1.number = !pe1.number;
// Put back on stack
postfix_buffer.push_back(pe1);
}
// Invert a variable
else if (pe1.is_variable()) {
// Invert RAX
switch (pe1.var.size()) {
case 8: {
pe1.var.move_to_reg((int) reg64::RAX);
_WI(NOT(reg64::RAX));
break;
}
case 4: {
pe1.var.move_to_reg((int) reg64::RAX);
_WI(NOT(reg32::EAX));
break;
}
case 2: {
pe1.var.move_to_reg((int) reg64::RAX);
_WI(NOT(reg16::AX));
break;
}
case 1: {
pe1.var.move_to_reg((int) reg64::RAX);
_WI(NOT(reg8::AL));
break;
}
}
// Push RAX
_PUSH_REG(RAX);
// Put type on stack
postfix_buffer.push_back(pe1.var.get_type());
}
// Invert stack variable
else {
// Negate top of stack
_WI(NOT(effective_address<reg64>(reg64::RSP), PTR_SIZE::QWORD));
// Put type on stack
postfix_buffer.push_back(pe1.var.get_type());
}
}
// If inc or dec left
else if (pe._operator == pe_operator::LEFT_INC_ONE || pe._operator == pe_operator::LEFT_DEC_ONE) {
// If parser expr is not a variable -> error
if (!postfix_buffer.back().is_variable()) {
// Throw assignment error
error_handler::compilation_error("cannot assign to a non-variable token");
return;
}
// If variable is not an lvalue -> error
else if (postfix_buffer.back().var.lvalue == false) {
error_handler::compilation_error("cannot assign value to an '" + C_GREEN + "rvalue" + C_CLR + "' token");
return;
}
// If variable is an nclass variable
else if (postfix_buffer.back().var.is_nclass()) {
error_handler::compilation_error("cannot assign value to an '" + C_GREEN + "nclass" + C_CLR + "' variable");
return;
}
// Check inc, dec
if (pe._operator == pe_operator::LEFT_INC_ONE) {
// Check increment, decrement
switch (postfix_buffer.back().var.size()) {
case 8: _WI(INC(postfix_buffer.back().var.get_eff(), PTR_SIZE::QWORD)); break;
case 4: _WI(INC(postfix_buffer.back().var.get_eff(), PTR_SIZE::DWORD)); break;
case 2: _WI(INC(postfix_buffer.back().var.get_eff(), PTR_SIZE::WORD)); break;
case 1: _WI(INC(postfix_buffer.back().var.get_eff(), PTR_SIZE::BYTE)); break;
}
} else {
switch (postfix_buffer.back().var.size()) {
case 8: _WI(DEC(postfix_buffer.back().var.get_eff(), PTR_SIZE::QWORD)); break;
case 4: _WI(DEC(postfix_buffer.back().var.get_eff(), PTR_SIZE::DWORD)); break;
case 2: _WI(DEC(postfix_buffer.back().var.get_eff(), PTR_SIZE::WORD)); break;
case 1: _WI(DEC(postfix_buffer.back().var.get_eff(), PTR_SIZE::BYTE)); break;
}
}
}
// If casting
else if (pe._operator == pe_operator::CAST) {
// Get parser expr
parser_expression& pe_to_cast = postfix_buffer.back();
// Get types
TYPE& t1 = pe_to_cast.var.get_type(), t2 = pe.var.get_type();
// If same types found => do nothing
bool equal_primitive = false;
// Check types for casting
if (!type_equal(t1, t2, &equal_primitive, true)) {
// If both pointers => cast type
if (t1.mdata_type == META_DATA_TYPE::POINTER
&& t2.mdata_type == META_DATA_TYPE::POINTER
&& ((t1.asize.size() <= 1 && t2.asize.size() <= 1) || (t1.asize == t2.asize))) {
// Cast type
pe_to_cast.var.get_type() = pe.var.get_type();
}
// Cast enum to primitive TODO: both ways
else if (t1.data_type == DATA_TYPE::ENUM && t2.data_type != DATA_TYPE::NCLASS) {
// Cast type and set on stack
pe_to_cast.var.get_type() = pe.var.get_type();
}
else {
// Cast type error
error_handler::compilation_error("cannot cast type '" + get_type_info(t1) + "' to '" + get_type_info(t2) + "'");
}
} else {
// Cast type
if (equal_primitive == false) {
// If converting from array
if ((pe_to_cast.var.get_type().mdata_type == META_DATA_TYPE::ARRAY || pe_to_cast.var.get_type().mdata_type == META_DATA_TYPE::POINTER) &&
t2.mdata_type == META_DATA_TYPE::STORAGE) {
// If a variable
if (pe_to_cast.is_variable() && !pe_to_cast.var.on_stack)
pe_to_cast.var.push_to_stack();
// Else already on stack
// Change to stack value
pe_to_cast.pe_id = parser_expression_id::STACK_VALUE;
// Set variable type
pe_to_cast.var.get_type() = pe.var.get_type();
return;
}
// Convert from pe.var.get_type() to var.get_type()
uint var_size = size(t2);
uint pe_var_size = pe_to_cast.var.size();
// Variable conversion
if (pe_to_cast.is_variable() && var_size > pe_var_size) {
// Convert if greater
// Convert size and push to stack
conv::convert_eff((int) reg64::RAX, var_size, pe_var_size, pe_to_cast.var);
_WI(PUSH(reg64::RAX));
// Change to stack value
pe_to_cast.pe_id = parser_expression_id::STACK_VALUE;
} else if (pe_to_cast.is_stack_val() && var_size > pe_var_size) {
// Convert and push back to stack
_WI(POP(reg64::RAX));
conv::convert_reg((int) reg64::RAX, var_size, pe_var_size, pe_to_cast.var.is_signed());
_WI(PUSH(reg64::RAX));
}
// Set variable type
pe_to_cast.var.get_type() = pe.var.get_type();
}
}
}
// Else search for arithmetic operators
else {
// If not enough variables on stack
if (postfix_buffer.size() < 2)
error_handler::utility_error("missing second expression for arithmetic operation");
else {
// The 2 operands from stack
parser_expression pe1 = postfix_buffer.back(); postfix_buffer.pop_back();
parser_expression pe2 = postfix_buffer.back(); postfix_buffer.pop_back();
// Executes the operation
do_operation(pe._operator, pe1, pe2);
}
}
}
// Copies the nclass
void nclass_copy(variable& var, bool stack = false) {
// Variable copy from stack
if (stack)
_WI(assembler::POP(reg64::RSI));
// If variable is known
else {
// Deprecated?
// Sum up the variable offsets
// For an instance in the class itself
for (variable& v : var.get_path().get_instances())
var.get_var_offset() += v.get_var_offset();
// Move the class to copy to RSI
var.move_pointer_to_reg(reg64::RSI);
}
// Move the new variable's pointer to RDI
_WI(assembler::MOV(reg64::RDI, reg64::RSP));
// The name of the method
std::string mname = "c#" + get_namespace_name(var.get_type().obj_nclass->get_namespace()) + var.get_type().obj_nclass->get_name() + "#n_" + var.get_type().obj_nclass->get_name() + get_namespace_name(var.get_type().obj_nclass->get_namespace()) + + "p";
// If already compiled => get from another object file
if ((var.get_type().obj_nclass->get_copy_constructor()->is_compiled() || !var.get_type().obj_nclass->get_copy_constructor()->is_defined()) && !externed(mname)) {
// Method full name -> no namespace
_EXTERN(mname);
// Add to list (so we do not add it again)
externed_methods.push_back(mname);
}
// Call copy constructor
_WI(assembler::CALL(mname));
// Reset var on stack
var.on_stack = false;
}
// Converts [rsp] to a smaller size
extern void conv::convert_eff(uint reg, uint var_size, uint pe_var_size, variable& var);
extern void conv::convert_rsp(uint reg, uint var_size, uint pe_var_size, bool is_signed);
extern long align8(long val);
// RSP effective address
effective_address rsp = effective_address<reg64>(reg64::RSP);
// Push pe expr to stack
void parser::push_to_stack() {
// If type of nclass => copy
if (postfix_buffer.back().is_variable() && postfix_buffer.back().var.is_nclass_type()) {
// Already on stack => variable not needed on stack
// postfix_buffer.back().var.push_to_stack();
return;
}
// Push number
else if (postfix_buffer.back().is_number()) {
// If size is 4 => push immediately
if (postfix_buffer.back().var.size() == 4) {
_WI(PUSH((int) postfix_buffer.back().number));
}
// Move to reg first, then to stack
else {
// Move to stack
switch (postfix_buffer.back().var.size(true)) {
case 8: _WI(MOV_opt(reg64::RAX, postfix_buffer.back().number)); break;
case 2: _WI(MOV(reg16::AX, (short) postfix_buffer.back().number)); break;
case 1: _WI(MOV(reg8::AL, (char) postfix_buffer.back().number)); break;
}
// Push to stack
_WI(PUSH(reg64::RAX));
}
}
// Push variable
else if (postfix_buffer.back().is_variable()) {
postfix_buffer.back().var.push_to_stack();
}
}
// Push pe expr to stack
void parser::push_to_stack(TYPE& type, parser_expression& pe) {
// If type of nclass => copy
if (pe.is_variable() && pe.var.is_nclass_type()) {
// Check for error only, as the nclass is already copied
if (this->type != nullptr && pe.var.is_copied || (!pe.var.get_path().get_instances().empty() && pe.var.get_path().get_instances()[0].is_copied)) {
// Check if the last value is not copied => illegal rvalue binding reference
for (variable& var : pe.var.get_path().get_instances()) {
if (var.is_copied) {
if (!pe.var.is_copied) {
error_handler::compilation_error("illegal '" + C_GREEN + "rvalue" + C_CLR + "' binding reference");
return;
}
}
}
}
// Call copy constructor
else {
nclass_copy(pe.var, !pe.is_variable());
}
return;
}
// Push number
else if (pe.is_number()) {
// If size is 4 => push immediately
if (size(type) == 4) {
_WI(PUSH((int) postfix_buffer.back().number));
}
// Move to reg first, then to stack
else {
// Move to stack
switch (size(type, true)) {
case 8: _WI(MOV_opt(reg64::RAX, postfix_buffer.back().number)); break;
case 2: _WI(MOV(reg16::AX, (short) postfix_buffer.back().number)); break;
case 1: _WI(MOV(reg8::AL, (char) postfix_buffer.back().number)); break;
}
// Push to stack
_WI(PUSH(reg64::RAX));
}
}
// Push variable
else if (pe.is_variable()) {
// If on stack / lvalue
if (postfix_buffer.back().var.on_stack && postfix_buffer.back().var.lvalue) {
// Go into pointer which is on top of stack
_WI(MOV(reg64::RAX, effective_address<reg64>(reg64::RSP)));
switch (postfix_buffer.back().var.size(true)) {
case 8: _WI(MOV(reg64::RAX, effective_address<reg64>(reg64::RAX, (int) postfix_buffer.back().var.get_var_offset()))); break;
case 4: _WI(MOV(reg32::EAX, effective_address<reg64>(reg64::RAX, (int) postfix_buffer.back().var.get_var_offset()))); break;
case 2: _WI(MOV(reg16::AX, effective_address<reg64>(reg64::RAX, (int) postfix_buffer.back().var.get_var_offset()))); break;
case 1: _WI(MOV(reg8::AL, effective_address<reg64>(reg64::RAX, (int) postfix_buffer.back().var.get_var_offset()))); break;
}
// Pop value pointer to rax and push it's value to the top of stack
if (size(type, true) > postfix_buffer.back().var.size(true)) {
conv::convert_reg(int(reg64::RAX), size(type), postfix_buffer.back().var.size(), is_signed(type));
switch (size(type, true)) {
case 8: _WI(MOV(effective_address<reg64>(reg64::RSP), reg64::RAX)); break;
case 4: _WI(MOV(effective_address<reg64>(reg64::RSP), reg32::EAX)); break;
case 2: _WI(MOV(effective_address<reg64>(reg64::RSP), reg16::AX)); break;
case 1: _WI(MOV(effective_address<reg64>(reg64::RSP), reg8::AL)); break;
}
} else {
switch (postfix_buffer.back().var.size(true)) {
case 8: _WI(MOV(effective_address<reg64>(reg64::RSP), reg64::RAX)); break;
case 4: _WI(MOV(effective_address<reg64>(reg64::RSP), reg32::EAX)); break;
case 2: _WI(MOV(effective_address<reg64>(reg64::RSP), reg16::AX)); break;
case 1: _WI(MOV(effective_address<reg64>(reg64::RSP), reg8::AL)); break;
}
}
}
// Convert variable to type
else if (size(type, true) > postfix_buffer.back().var.size(true)) {
// Convert var to type
conv::convert_eff((int) reg64::RAX, size(type), postfix_buffer.back().var.size(), postfix_buffer.back().var);
_WI(assembler::PUSH(reg64::RAX));
}
// Don't convert just push
else {
pe.var.push_to_stack();
}
}
// Convert stack variable (Push not needed; already on stack)
else {
// Or already pushed to stack so proceed
if (size(type, true) > postfix_buffer.back().var.size(true)) {
// Convert stack to rax
conv::convert_rsp(int(reg64::RAX), size(type), postfix_buffer.back().var.size(), is_signed(type));
// Move back to stack
switch (size(type, true)) {
case 8: _WI(MOV(rsp, reg64::RAX)); break;
case 4: _WI(MOV(rsp, reg32::EAX)); break;
case 2: _WI(MOV(rsp, reg16::AX)); break;
case 1: _WI(MOV(rsp, reg8::AL)); break;
}
}
}
}
// Move pe expr to reg
void parser::move_to_reg(unsigned char reg, TYPE& type, parser_expression& pe) {
// If type of nclass => lea to reg
if (pe.var.is_nclass_type()) {
// Move the new variable's pointer to RDI
if (pe.var.size() != 0) {
// Mov variable pointer to RSI
// If variable is known
// Sum up the variable offsets
// For an instance in the class itself
for (variable& v : pe.var.get_path().get_instances())
pe.var.get_var_offset() += v.get_var_offset();
// Move the class to copy to RSI
pe.var.move_pointer_to_reg(reg64::RSI);
// Variable is at 1
int pos = 8;
if (compiling_method != nullptr && compiling_method->get_type().obj_nclass != nullptr &&
compiling_nclass != nullptr && compiling_method->get_type().obj_nclass->size() != 0)
pos = 16;
// Move pointer to RDI
_WI(assembler::MOV(reg64::RDI, effective_address<reg64>(reg64::RBP, (int) -pos)));
// The name of the constructor
std::string mname = "c#" + get_namespace_name(pe.var.get_type().obj_nclass->get_namespace()) + pe.var.get_type().obj_nclass->get_name() + "#n_" + pe.var.get_type().obj_nclass->get_name() + get_namespace_name(pe.var.get_type().obj_nclass->get_namespace()) + + "p";
// If already compiled => get from another object file
if ((pe.var.get_type().obj_nclass->get_copy_constructor()->is_compiled() || !pe.var.get_type().obj_nclass->get_copy_constructor()->is_defined()) && !externed(mname)) {
// Method full name -> no namespace
_EXTERN(mname);
// Add to list (so we do not add it again)
externed_methods.push_back(mname);
}
// Call copy constructor
_WI(assembler::CALL(mname));
// Reset var on stack
pe.var.on_stack = false;
// Move pointer to RAX
_WI(assembler::MOV(reg64::RAX, effective_address<reg64>(reg64::RBP, (int) -pos)));
}
return;
}
// Move num to reg
if (pe.is_number()) {
switch(pe.var.size(true)) {
case 8: _WI(MOV((reg64) reg, pe.number)); break;
case 4: _WI(MOV((reg32) reg, pe.number)); break;
case 2: _WI(MOV((reg16) reg, pe.number)); break;
case 1: _WI(MOV((reg8) reg, pe.number)); break;
}
}
// Move var to reg
else if (pe.is_variable()) {
// If on stack / lvalue
if (pe.var.on_stack && pe.var.lvalue) {
// Pop value to RAX
_WI(POP(reg64::RAX));
// Go into pointer
switch (pe.var.size(true)) {
case 8: _WI(MOV(reg64(reg), effective_address<reg64>(reg64::RAX))); break;
case 4: _WI(MOV(reg32(reg), effective_address<reg64>(reg64::RAX))); break;
case 2: _WI(MOV(reg16(reg), effective_address<reg64>(reg64::RAX))); break;
case 1: _WI(MOV(reg8(reg), effective_address<reg64>(reg64::RAX))); break;
}
// Convert value
if (size(type) > pe.var.size()) {
conv::convert_reg(int(reg), size(type), pe.var.size(), is_signed(type));
}
}
// Convert variable to type
else if (size(type, true) > pe.var.size(true)) {
// Convert var to type
conv::convert_eff((int) reg64(reg), size(type), pe.var.size(), pe.var);
}
// Don't convert, just move
else {
pe.var.move_to_reg(reg);
}
}
// Pop stack variable to reg
else {
// Convert if needed
if (size(type, true) > pe.var.size(true)) {
// Convert from stack
conv::convert_rsp(reg, size(type), pe.var.size(), is_signed(type));
// Remove from stack
_WI(ADD(reg64::RSP, 8));
}
// Else pop to reg
else {
_WI(assembler::POP((reg64) reg));
}
}
}
// Move pe expr to eff
void parser::move_to_eff(effective_address<reg64>& eff, TYPE& type, parser_expression& pe) {
// If type of nclass => lea to reg
if (pe.var.is_nclass_type()) {
// Move the new variable's pointer to RDI
if (pe.var.size() != 0) {
// Mov variable pointer to RSI
// If variable is known
// Sum up the variable offsets
// For an instance in the class itself
for (variable& v : pe.var.get_path().get_instances())
pe.var.get_var_offset() += v.get_var_offset();
// Move the class to copy to RSI
pe.var.move_pointer_to_reg(reg64::RSI);
// Variable is at 1
int pos = 8;
if (compiling_method != nullptr && compiling_method->get_type().obj_nclass != nullptr &&
compiling_nclass != nullptr && compiling_method->get_type().obj_nclass->size() != 0)
pos = 16;
// Move pointer to RDI
_WI(assembler::MOV(reg64::RDI, effective_address<reg64>(reg64::RBP, (int) -pos)));
// The name of the constructor
std::string mname = "c#" + get_namespace_name(pe.var.get_type().obj_nclass->get_namespace()) + pe.var.get_type().obj_nclass->get_name() + "#n_" + pe.var.get_type().obj_nclass->get_name() + get_namespace_name(pe.var.get_type().obj_nclass->get_namespace()) + + "p";
// If already compiled => get from another object file
if ((pe.var.get_type().obj_nclass->get_copy_constructor()->is_compiled() || !pe.var.get_type().obj_nclass->get_copy_constructor()->is_defined()) && !externed(mname)) {
// Method full name -> no namespace
_EXTERN(mname);
// Add to list (so we do not add it again)
externed_methods.push_back(mname);
}
// Call copy constructor
_WI(assembler::CALL(mname));
// Reset var on stack
pe.var.on_stack = false;
// Move pointer to RAX
_WI(assembler::MOV(reg64::RAX, effective_address<reg64>(reg64::RBP, (int) -pos)));
}
return;
}
// Move num to eff
if (pe.is_number()) {
switch(pe.var.size(true)) {
case 8: _WI(MOV(eff, pe.number, PTR_SIZE::QWORD)); break;
case 4: _WI(MOV(eff, pe.number, PTR_SIZE::DWORD)); break;
case 2: _WI(MOV(eff, pe.number, PTR_SIZE::WORD)); break;
case 1: _WI(MOV(eff, pe.number, PTR_SIZE::BYTE)); break;
}
}
// Move var to reg
else if (pe.is_variable()) {
// If on stack / lvalue
if (pe.var.on_stack && pe.var.lvalue) {
// Pop value to RAX
_WI(POP(reg64::RAX));
// Go into pointer
switch (pe.var.size(true)) {
case 8: _WI(MOV(reg64::RAX, effective_address<reg64>(reg64::RAX))); break;
case 4: _WI(MOV(reg32::EAX, effective_address<reg64>(reg64::RAX))); break;
case 2: _WI(MOV(reg16::AX, effective_address<reg64>(reg64::RAX))); break;
case 1: _WI(MOV(reg8::AL, effective_address<reg64>(reg64::RAX))); break;
}
// Convert value
if (size(type) > pe.var.size()) {
conv::convert_reg((uint) reg64::RAX, size(type), pe.var.size(), is_signed(type));
}
}
// Convert variable to type
else if (size(type, true) > pe.var.size(true)) {
// Convert var to type
conv::convert_eff((int) reg64::RAX, size(type), pe.var.size(), pe.var);
}
// Don't convert, just move
else {
pe.var.move_to_reg((int) reg64::RAX);
}
// Move to eff
switch (pe.var.size(true)) {
case 8: _WI(MOV(eff, reg64::RAX)); break;
case 4: _WI(MOV(eff, reg32::EAX)); break;
case 2: _WI(MOV(eff, reg16::AX)); break;
case 1: _WI(MOV(eff, reg8::AL));; break;
}
}
// Pop stack variable to reg
else {
// Convert if needed
if (size(type, true) > pe.var.size(true)) {
// Convert from stack
conv::convert_rsp((int) reg64::RAX, size(type), pe.var.size(), is_signed(type));
// Remove from stack
_WI(ADD(reg64::RSP, 8));
}
// Else pop to reg
else {
_WI(assembler::POP((reg64) reg64::RAX));
}
// Move to eff
switch (pe.var.size(true)) {
case 8: _WI(MOV(eff, reg64::RAX)); break;
case 4: _WI(MOV(eff, reg32::EAX)); break;
case 2: _WI(MOV(eff, reg16::AX)); break;
case 1: _WI(MOV(eff, reg8::AL));; break;
}
}
}
// Get insts vector
extern std::vector<assembler::byte*> insts;
// Stack error
inline bool stack_error(std::vector<parser_expression>& postfix_buffer) {
// Check if empty
if (postfix_buffer.empty()) {
error_handler::compilation_error("no expression was to be found");
return true;
}
// Check if more than one value found
else if (postfix_buffer.size() != 1) {
error_handler::compilation_error("more than one expression was found");
return true;
}
return false;
}
// Parses a value from a line
void parser::parse_value(source_file& file, std::vector<char> terminate_characters, TYPE* type, bool push, bool remove) {
// Set file, terminate characters
this->file = &file;
this->terminate_characters = &terminate_characters;
this->push = push;
this->type = type;
// Convert to postfix notation
to_postfix_notation();
// Check stack
if (stack_error(postfix_buffer))
return;
// Remove temporary object
if (obj_rbp_sub != nullptr && remove) {
char* c = reinterpret_cast<char*>(&obj_rbp_sub_val);
for (int i = 0; i < 4; ++i)
(*obj_rbp_sub)[i + 3] = c[i];
// On stack var
bool var_on_stack = postfix_buffer.back().is_stack_val() || postfix_buffer.back().var.on_stack;
// Check if something is on top of stack => POP to RAX
if (var_on_stack)
_POP_REG(RAX);
// Check type and remove from stack
if (type != nullptr) {
int val = obj_rbp_sub_val;
int tsize = align8(size(*type));
// rbp_offset += obj_rbp_sub_val - tsize;
// Remove obj_rbp_sub_val - tsize or for 8-byte vars only obj_rbp_sub_val
if (type->obj_nclass != nullptr && (val -= tsize) != 0) {
_WI(ADD(reg64::RSP, (int) (val)));
::begin_rbp_offset -= val;
} else if (val != 0){
_WI(ADD(reg64::RSP, (int) (val)));
::begin_rbp_offset -= val;
}
}
// Else if type is unknown => remove everything
else {
// rbp_offset += obj_rbp_sub_val;
_WI(ADD(reg64::RSP, (int) obj_rbp_sub_val));
::begin_rbp_offset -= obj_rbp_sub_val;
}
// Push it back to stack
if (var_on_stack)
_PUSH_REG(RAX);
// Reset rbp sub
obj_rbp_sub = nullptr;
}
#ifdef DEBUG
std::cout << "PE of size: " << postfix_buffer.size() << std::endl;
std::cout << "EXPRESSION: ";
for (parser_expression& pe : postfix_buffer)
pe.print();
std::cout << std::endl;
#endif
// If type is checkable
if (type != nullptr) {
// Check if type is equal, else throw error
check_type(*type, postfix_buffer.back().var.get_type());
// Push to stack
if (push)
// Push parser expression to stack
push_to_stack(*type, postfix_buffer.back());
}
// Remove from stack
if (!push && remove
&& ((postfix_buffer.back().is_variable() && postfix_buffer.back().var.on_stack) || postfix_buffer.back().is_stack_val())
&& postfix_buffer.back().var.get_type().data_type != DATA_TYPE::VOID) {
// Remove 8 byte allocs and remove from stack
_WI(POP(reg64::RAX));
/*if (postfix_buffer.back().var.size() <= 8) {
_WI(POP(reg64::RAX));
}
// Remove larger nclass allocations
else {
_WI(ADD(reg64::RSP, (int) align8(postfix_buffer.back().var.size())));
}*/
}
}
// Parses a value from a line and assigns to an effective address
TYPE parser::parse_value_and_assign_to_eff(effective_address<reg64>& eff, source_file& file, std::vector<char> terchars, TYPE& type) {
// Set file, terminate characters
this->file = &file;
this->terminate_characters = &terchars;
this->push = push;
this->type = &type;
// Convert to postfix notation
to_postfix_notation();
#ifdef DEBUG
std::cout << "PE of size: " << postfix_buffer.size() << std::endl;
std::cout << "EXPRESSION: ";
for (parser_expression& pe : postfix_buffer)
pe.print();
std::cout << std::endl;
#endif
// Check stack
if (stack_error(postfix_buffer))
return {};
// Assign to eff
move_to_eff(eff, type, postfix_buffer.back());
// Return the type
return postfix_buffer.back().var.get_type();
}
// Parses a value from a line and assigns to a variable
TYPE parser::parse_value_and_assign(variable& var, source_file& file, std::vector<char> terchars, bool push, VARIABLE_OPERATION var_op) {
// Set file, terminate characters
this->file = &file;
this->terminate_characters = &terchars;
this->push = push;
this->type = &var.get_type();
// Convert to postfix notation
to_postfix_notation();
#ifdef DEBUG
std::cout << "PE of size: " << postfix_buffer.size() << std::endl;
std::cout << "EXPRESSION: ";
for (parser_expression& pe : postfix_buffer)
pe.print();
std::cout << std::endl;
#endif
// Check if type is equal, else throw error
check_type(var.get_type(), postfix_buffer.back().var.get_type());
// Check size and clear stack
// Check stack
if (stack_error(postfix_buffer))
return {};
// Mov to variable
do_to_variable(var_op, var);
// Return the type
return postfix_buffer.back().var.get_type();
}
// Parses a value from a line and assigns to a register
TYPE parser::parse_value_and_assign_to_reg(unsigned char reg, std::vector<char> terchars, source_file& file, TYPE& type) {
// Parse value
parse_value(file, terchars, &type, false, false);
// If type is void
if (type.data_type == DATA_TYPE::VOID && type.mdata_type == META_DATA_TYPE::STORAGE) {
error_handler::compilation_error("cannot assign type '" + C_GREEN + "void" + C_CLR + "'");
return {};
}
// Move to reg
move_to_reg(reg, type, postfix_buffer.back());
return postfix_buffer.back().var.get_type();
}
#endif
| 39.5479 | 288 | 0.468545 | giag3 |
c48cfba9d42cfb4716984d276820d78152cc8c38 | 10,864 | cpp | C++ | src/megaobd.cpp | ConnorRigby/megaobd | b1434444991e512237a81a54ee39f87fc3dd063d | [
"MIT"
] | null | null | null | src/megaobd.cpp | ConnorRigby/megaobd | b1434444991e512237a81a54ee39f87fc3dd063d | [
"MIT"
] | null | null | null | src/megaobd.cpp | ConnorRigby/megaobd | b1434444991e512237a81a54ee39f87fc3dd063d | [
"MIT"
] | 1 | 2021-04-16T09:56:13.000Z | 2021-04-16T09:56:13.000Z | #include "OBD9141sim.h"
#include <AltSoftSerial.h>
#include <CRC32.h>
// OBD constants
#define OBD_TX_PIN 9
#define OBD_RX_PIN 8
AltSoftSerial OBD_SERIAL;
OBD9141sim OBD;
CRC32 CRC;
// Megasquirt Constants
#define MEGASQUIRT_SERIAL Serial
const uint8_t CMD_A_PAYLOAD[7] = {0x0, 0x1, 0x41, 0xD3, 0xD9, 0x9E, 0x8B};
enum STATUS_RECV_STATE {
STATUS_RECV_SIZE_MSB,
STATUS_RECV_SIZE_LSB,
STATUS_RECV_STATUS,
STATUS_RECV_DATA,
STATUS_RECV_CRC32,
STATUS_RECV_COMPLETE,
STATUS_RECV_ERROR_CRC32
};
#define BUFFER_MAX_SIZE 0xFFFF
/**
Structure for holding state of a Megasquirt serial command.
*/
struct payload {
STATUS_RECV_STATE state;
uint16_t size;
uint16_t read;
uint32_t crc32;
uint8_t status;
uint8_t buffer[];
};
typedef enum status_field {
STATUS_UINT8,
STATUS_INT8,
STATUS_UINT16,
STATUS_INT16
} status_field_type_t;
/**
Structure for holding MegaSquirt A command
*/
struct status {
uint16_t secs;
uint16_t pw1;
uint16_t pw2;
uint16_t rpm;
int16_t advance;
// TODO(Connor) - Change this to a union
uint8_t squirt;
// TODO(Connor) - Change this to a union
uint8_t engine;
uint8_t afrtgt1raw;
uint8_t afrtgt2raw;
int16_t barometer;
int16_t map;
int16_t mat;
int16_t clt;
int16_t tps;
uint16_t maf;
uint16_t vss1;
};
/**
Structure for holding fault codes
*/
struct dtc {
uint16_t fuel;
uint8_t load;
uint8_t clt;
uint8_t shortTermTrim;
uint8_t longTermTrim;
uint16_t rpm;
uint8_t vss;
};
/**
Used to store fault codes
*/
struct dtc faults[16];
/**
Stores the most recent payload from Megasquirt
*/
struct payload msPayload;
/**
Stores the most recent result of the `A` command
*/
struct status msStatus;
/**
* Writes the A command to the serial port.
*/
void writeMegasquirtPayload();
/**
* Process data in the msPayload struct
*/
void processMegasquirtPayload();
void realTimeValue(void*, size_t, status_field_type_t);
void setup() {
// Initialize OBD stuff
OBD.begin(OBD_SERIAL, OBD_RX_PIN, OBD_TX_PIN);
OBD.keep_init_state(true);
OBD.initialize();
// Initialize MegaSquirt transport
MEGASQUIRT_SERIAL.begin(115200);
*msPayload.buffer = malloc(0xFFFF);
writeMegasquirtPayload();
}
void loop() {
// Process MegaSquirt data
while(MEGASQUIRT_SERIAL.available()) {
switch(msPayload.state) {
case STATUS_RECV_SIZE_MSB:
msPayload.buffer[0] = MEGASQUIRT_SERIAL.read();
msPayload.state = STATUS_RECV_SIZE_LSB;
break;
case STATUS_RECV_SIZE_LSB:
msPayload.size = (msPayload.buffer[0] << 8) | MEGASQUIRT_SERIAL.read();
msPayload.state = STATUS_RECV_STATUS;
break;
case STATUS_RECV_STATUS:
msPayload.status = MEGASQUIRT_SERIAL.read();
msPayload.state = STATUS_RECV_DATA;
break;
case STATUS_RECV_DATA:
msPayload.buffer[msPayload.read++] = MEGASQUIRT_SERIAL.read();
// Data read complete
if(msPayload.read == msPayload.size) {
msPayload.state = STATUS_RECV_CRC32;
}
break;
case STATUS_RECV_CRC32:
msPayload.buffer[msPayload.read++] = MEGASQUIRT_SERIAL.read();
// read 4 more bytes
if(msPayload.read = (msPayload.size + 4)) {
msPayload.crc32 = msPayload.buffer[msPayload.read-3] | (msPayload.buffer[msPayload.read-2] << 8) | (msPayload.buffer[msPayload.read-1] << 16) | (msPayload.buffer[msPayload.read] << 24);
uint32_t calculated = CRC.calculate(msPayload.buffer, msPayload.size);
// Check crc32
if(msPayload.crc32 == calculated) {
msPayload.state = STATUS_RECV_COMPLETE;
} else {
msPayload.state = STATUS_RECV_ERROR_CRC32;
}
}
break;
case STATUS_RECV_COMPLETE:
processMegasquirtPayload();
break;
default:
// Handle error here
break;
}
}
// Process OBD requests.
// Only 8 answers can be sent at a time.
OBD.loop();
/**
Miata ECU supports the following type 1 PIDS:
0x00 - PIDs supported (01-20) [01, 03-07, 0C-11, 13-15, 1C, 20]
0x01 - Monitor status since DTCs cleared
0x03 - Fuel system status
0x04 - Calculated engine load value
0x05 - Engine coolant temperature
0x06 - Short term fuel % trim - Bank 1
0x07 - Long term fuel % trim - Bank 1
0x0C - Engine RPM
0x0D - Vehicle speed
0x0E - Timing advance
0x0F - Intake air temperature
0x10 - MAF air flow rate
0x11 - Throttle position
0x13 - Oxygen sensors present
0x14 - Bank 1, Sensor 1: O2S Voltage, Short term fuel trim
0x15 - Bank 1, Sensor 2: O2S Voltage, Short term fuel trim
0x1C - OBD standards this vehicle conforms to
0x20 - PIDs supported (21-40)
0x21 - Distance traveled with MIL on
*/
// Helper vars
uint8_t a;
uint8_t b;
// Supported PIDS: [01, 03-07, 0C-11, 13-15, 1C, 20]
// 01 02 03 04 05 06 07 08 09 0A 0B 0C 0D 0E 0F 10 11 12 13 14 15 16 17 18 19 1A 1B 1C 1D 1E 1F 20
// 1 0 1 1 1 1 1 0 0 0 0 1 1 1 1 1 1 0 1 1 1 0 0 0 0 0 0 1 0 0 0 1
// 10111110000111111011100000010001
OBD.setAnswer(0x01, 0x00, 32, 0b10111110000111111011100000010001);
// Note that test availability is indicated by set (1) bit and completeness is indicated by reset (0) bit.
// ByteA: MIL + number of active codes
// ByteB: Spark mode and tests available/complete
// ByteC: CARB tests available
// ByteD: CARB tests complete
OBD.setAnswer(0x01, 0x01, 32, 0b0000000000000111111111110000);
// Fuel System status
// Should be built from the `msStatus.squirt`
// OBD.setAnswer(0x01, 0x03, );
// Engine status
// Should be built from the `msStatus.engine`
// OBD.setAnswer(0x01, 0x04, );
// Coolant
// This may need to be converted to C?
OBD.setAnswer(0x01, 0x05, (uint8_t)(msStatus.clt + 40));
// Short term fuel trim
// OBD.setAnswer(0x01, 0x06, (uint8_t));
// Long term fuel trim
// OBD.setAnswer(0x01, 0x07, (uint8_t));
// Engine RPM
a = msStatus.rpm & 0xFF;
b = msStatus.rpm >> 8;
uint16_t rpm = (256 * a + b) / 4;
OBD.setAnswer(0x01, 0x0C, (uint16_t)rpm);
// VSS
// OBD.setAnswer(0x01, 0x0D, (uint8_t) );
// Every 8 answers.
OBD.loop();
// Advance
uint8_t advance = (msStatus.advance / 2) - 64;
OBD.setAnswer(0x01, 0x0E, (uint8_t)advance);
// IAT (may need to convert to C?)
OBD.setAnswer(0x01, 0x0F, (uint8_t)(msStatus.mat - 40));
// MAF
a = msStatus.maf & 0xFF;
b = msStatus.maf >> 8;
uint16_t maf = (256 * a + b) / 100;
OBD.setAnswer(0x01, 0x10, (uint16_t)maf);
// TPS
uint8_t tps = (100/255) * msStatus.tps;
OBD.setAnswer(0x01, 0x11, (uint8_t)tps);
// Number of O2 sensors
// These bytes might be backwards, but the result is the same?
OBD.setAnswer(0x01, 0x13, (uint8_t)0b11001100);
// O2 Sensors (2 is not used)
// TODO 0x14 second byte should be the same as pid 0x06
// TODO the first byte should be voltage of the sensor for both answers
OBD.setAnswer(0x01, 0x14, (uint16_t)0x00FF);
OBD.setAnswer(0x01, 0x15, (uint16_t)0x00FF);
// OBD compliance
// 0x01 = CARB
OBD.setAnswer(0x01, 0x1C, (uint8_t)0x01);
// Every 8 answers.
OBD.loop();
// PIDs 21-40
// Miata only supports 21
OBD.setAnswer(0x01, 0x20, 32, 0b10000000000000000000000000000000);
OBD.setAnswer(0x01, 0x21, (uint16_t)0);
/**
Miata ECU supports the following type 2 PIDS:
0x00 - PIDs supported (01-20)
0x02 - Freeze DTC
0x03 - Fuel system status
0x04 - Calculated engine load value
0x05 - Engine coolant temperature
0x06 - Short term fuel % trim - Bank 1
0x07 - Long term fuel % trim - Bank 1
0x0C - Engine RPM
0x0D - Vehicle speed
*/
// Supported PIDS: [01, 02, 03, 04, 05, 06, 07, 0C, 0D]
OBD.setAnswer(0x02, 0x01, 32, 0b1111111100011000000000000000000);
// OBD.setAnswer(0x02, 0x02);
// OBD.setAnswer(0x02, 0x03)
// OBD.setAnswer(0x02, 0x04)
// OBD.setAnswer(0x02, 0x05)
// OBD.setAnswer(0x02, 0x06)
// Every 8 answers.
OBD.loop();
// OBD.setAnswer(0x02, 0x07)
// OBD.setAnswer(0x02, 0x0C)
// OBD.setAnswer(0x02, 0x0D)
// End loop with telling MegaSquirt we want another status.
writeMegasquirtPayload();
}
void processMegasquirtPayload() {
switch(msPayload.status) {
// Realtime data
case 0x01:
// This is a huge, ugly assign.
// uint16_t msStatus.secs
realTimeValue(&msStatus.secs, 0, STATUS_UINT16);
// uint16_t msStatus.pw1;
realTimeValue(&msStatus.pw1, 2, STATUS_UINT16);
// uint16_t msStatus.pw2;
realTimeValue(&msStatus.pw2, 4, STATUS_UINT16);
// uint16_t msStatus.rpm;
realTimeValue(&msStatus.rpm, 6, STATUS_UINT16);
// int16_t msStatus.advance;
realTimeValue(&msStatus.advance, 8, STATUS_INT16);
// uint8_t msStatus.squirt;
realTimeValue(&msStatus.squirt, 10, STATUS_UINT8);
// uint8_t msStatus.engine;
realTimeValue(&msStatus.engine, 11, STATUS_UINT8);
// uint8_t msStatus.afrtgt1raw;
// uint8_t msStatus.afrtgt2raw;
// int16_t msStatus.barometer;
realTimeValue(&msStatus.barometer, 16, STATUS_INT16);
// int16_t msStatus.map;
realTimeValue(&msStatus.map, 18, STATUS_INT16);
// int16_t msStatus.mat;
realTimeValue(&msStatus.mat, 20, STATUS_INT16);
// int16_t msStatus.clt;
realTimeValue(&msStatus.clt, 22, STATUS_INT16);
// int16_t msStatus.tps;
realTimeValue(&msStatus.tps, 24, STATUS_INT16);
// uint16_t maf;
realTimeValue(&msStatus.maf, 210, STATUS_UINT16);
// uint16_t vss1;
realTimeValue(&msStatus.vss1, 336, STATUS_INT16);
break;
default:
// Unknown status
break;
}
}
void realTimeValue(void *valuePtr, size_t offset, status_field_type_t type) {
switch(type) {
case STATUS_UINT8: {
uint8_t *fieldPtr = (uint8_t*)valuePtr;
*fieldPtr = msPayload.buffer[offset];
break;
}
case STATUS_INT8: {
int8_t *fieldPtr = (int8_t*)valuePtr;
*fieldPtr = msPayload.buffer[offset];
break;
}
case STATUS_UINT16: {
uint16_t *fieldPtr = (uint16_t*)valuePtr;
*fieldPtr = (msPayload.buffer[offset] << 8) | msPayload.buffer[offset+1];
break;
}
case STATUS_INT16: {
uint16_t tmp = (msPayload.buffer[offset] << 8) | msPayload.buffer[offset+1];
int16_t *fieldPtr = (int16_t*)valuePtr;
*fieldPtr = (int16_t) tmp;
break;
}
}
}
void writeMegasquirtPayload() {
uint16_t i;
for(i = 0; i < 7; i++) {
MEGASQUIRT_SERIAL.write(CMD_A_PAYLOAD[i]);
}
// Reset state machine
msPayload.state = STATUS_RECV_SIZE_MSB;
msPayload.size = 0;
msPayload.crc32 = 0;
msPayload.read = 0;
// Clear buffer
for(i=0; i < BUFFER_MAX_SIZE; i++) {
msPayload.buffer[i] = 0;
}
} | 25.928401 | 195 | 0.657861 | ConnorRigby |
c48e2c67895bfaf6a4505b02335a24157fb46692 | 7,949 | cpp | C++ | LTSketchbook/libraries/LT_PMBUS/LT_FaultLog.cpp | LinduinoBob/Linduino | a6465b549ee8daee4eec11c36cabf5487bd2a3bc | [
"FSFAP"
] | null | null | null | LTSketchbook/libraries/LT_PMBUS/LT_FaultLog.cpp | LinduinoBob/Linduino | a6465b549ee8daee4eec11c36cabf5487bd2a3bc | [
"FSFAP"
] | null | null | null | LTSketchbook/libraries/LT_PMBUS/LT_FaultLog.cpp | LinduinoBob/Linduino | a6465b549ee8daee4eec11c36cabf5487bd2a3bc | [
"FSFAP"
] | null | null | null | /*!
LTC PMBus Support: API for a shared LTC Fault Log
@verbatim
This API is shared with Linduino and RTOS code. End users should code to this
API to enable use of the PMBus code without modifications.
@endverbatim
Copyright 2018(c) Analog Devices, Inc.
All rights reserved.
Redistribution and use in source and binary forms, with or without
modification, are permitted provided that the following conditions are met:
- Redistributions of source code must retain the above copyright
notice, this list of conditions and the following disclaimer.
- Redistributions in binary form must reproduce the above copyright
notice, this list of conditions and the following disclaimer in
the documentation and/or other materials provided with the
distribution.
- Neither the name of Analog Devices, Inc. nor the names of its
contributors may be used to endorse or promote products derived
from this software without specific prior written permission.
- The use of this software may or may not infringe the patent rights
of one or more patent holders. This license does not release you
from the requirement that you obtain separate licenses from these
patent holders to use this software.
- Use of the software either in source or binary form, must be run
on or directly connected to an Analog Devices Inc. component.
THIS SOFTWARE IS PROVIDED BY ANALOG DEVICES "AS IS" AND ANY EXPRESS OR
IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, NON-INFRINGEMENT,
MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE DISCLAIMED.
IN NO EVENT SHALL ANALOG DEVICES BE LIABLE FOR ANY DIRECT, INDIRECT,
INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT
LIMITED TO, INTELLECTUAL PROPERTY RIGHTS, PROCUREMENT OF SUBSTITUTE GOODS OR
SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER
CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY,
OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE
OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
*/
//! @ingroup PMBus_SMBus
//! @{
//! @defgroup LT_FaultLog LT_FaultLog: PLTC PSM Fault Log support
//! @}
/*! @file
@ingroup LT_FaultLog
Library Header File for LT_FaultLog
*/
#include <Arduino.h>
#include "LT_FaultLog.h"
LT_FaultLog::LT_FaultLog(LT_PMBus *pmbus)
{
pmbus_ = pmbus;
}
/*
* Read the status byte
*
* address: PMBUS address
*/
uint8_t
LT_FaultLog::readMfrStatusByte(uint8_t address)
{
uint8_t status_byte;
status_byte = pmbus_->smbus()->readByte(address, STATUS_MFR_SPECIFIC);
return status_byte;
}
/*
* Read the mfr status byte
*
* address: PMBUS address
*/
uint8_t
LT_FaultLog::readMfrFaultLogStatusByte(uint8_t address)
{
uint8_t status_byte;
status_byte = pmbus_->smbus()->readByte(address, MFR_FAULT_LOG_STATUS);
return status_byte;
}
/*
* Check if there is a fault log
*
* address: PMBUS address
*/
bool
LT_FaultLog::hasFaultLog(uint8_t address)
{
uint8_t status;
PsmDeviceType t = pmbus_->deviceType(address);
if (t == LTC3880 || t == LTC3886 || t == LTC3887 || t == LTM4675 || t == LTM4676|| t == LTM4676A || t == LTM4677)
{
status = readMfrStatusByte(address);
return (status & LTC3880_SMFR_FAULT_LOG) > 0;
}
else if (t == LTC3882 || t == LTC3882_1)
{
status = readMfrStatusByte(address);
return (status & LTC3882_SMFR_FAULT_LOG) > 0;
}
else if (t == LTC3883)
{
status = readMfrStatusByte(address);
return (status & LTC3883_SMFR_FAULT_LOG) > 0;
}
else if (t == LTC2974 || t == LTC2975)
{
status = readMfrFaultLogStatusByte(address);
return (status & LTC2974_SFL_EEPROM) > 0;
}
else if (t == LTC2977 || t == LTC2978 || t == LTC2980 || t == LTM2987)
{
status = readMfrFaultLogStatusByte(address);
return (status & LTC2978_SFL_EEPROM) > 0;
}
else
return false;
}
/*
* Enable fault log
*
* address: PMBUS address
*/
void
LT_FaultLog::enableFaultLog(uint8_t address)
{
uint8_t config8;
uint16_t config16;
PsmDeviceType t = pmbus_->deviceType(address);
if (
(t == LTC3880)
|| (t == LTC3882)
|| (t == LTC3882_1)
|| (t == LTC3883)
|| (t == LTC3886)
|| (t == LTM4675)
|| (t == LTM4676)
|| (t == LTM4676A)
|| (t == LTM4677)
|| (t == LTC2978)
)
{
config8 = pmbus_->smbus()->readByte(address, MFR_CONFIG_ALL);
pmbus_->smbus()->writeByte(address, MFR_CONFIG_ALL, config8 | CFGALL_EFL);
}
else if (
(t == LTC2974)
|| (t == LTC2975)
|| (t == LTC2977)
|| (t == LTC2980)
|| (t == LTM2987)
)
{
config16 = pmbus_->smbus()->readWord(address, MFR_CONFIG_ALL);
pmbus_->smbus()->writeWord(address, MFR_CONFIG_ALL, config16 | LTC2974_CFGALL_EFL);
}
}
/*
* Disable fault log
*
* address: PMBUS address
*/
void
LT_FaultLog::disableFaultLog(uint8_t address)
{
uint8_t config8;
uint16_t config16;
PsmDeviceType t = pmbus_->deviceType(address);
if (
(t == LTC3880)
|| (t == LTC3882)
|| (t == LTC3882_1)
|| (t == LTC3883)
|| (t == LTC3886)
|| (t == LTM4675)
|| (t == LTM4676)
|| (t == LTM4676A)
|| (t == LTM4677)
|| (t == LTC2978)
)
{
config8 = pmbus_->smbus()->readByte(address, MFR_CONFIG_ALL);
pmbus_->smbus()->writeByte(address, MFR_CONFIG_ALL, config8 & ~CFGALL_EFL);
}
else if (
(t == LTC2974)
|| (t == LTC2975)
|| (t == LTC2977)
|| (t == LTC2980)
|| (t == LTM2987)
)
{
config16 = pmbus_->smbus()->readWord(address, MFR_CONFIG_ALL);
pmbus_->smbus()->writeWord(address, MFR_CONFIG_ALL, config16 & ~CFGALL_EFL);
}
}
void LT_FaultLog::dumpBin(Print *printer, uint8_t *log, uint8_t size)
{
if (printer == 0)
printer = &Serial;
uint8_t *temp = log;
for (uint8_t i = 0; i < size; i++)
{
if (!(i % 16))
printer->println();
if (temp[i] < 0x10)
printer->write('0');
printer->print(temp[i], HEX);
}
printer->println();
}
/*
* Clear fault log
*
* address: PMBUS address
*/
void
LT_FaultLog::clearFaultLog(uint8_t address)
{
pmbus_->smbus()->sendByte(address, MFR_FAULT_LOG_CLEAR);
}
uint64_t
LT_FaultLog::getSharedTime200us(FaultLogTimeStamp time_stamp)
{
uint64_t num200us = ((uint64_t) time_stamp.shared_time_byte5 << 40);
num200us = num200us | ((uint64_t) time_stamp.shared_time_byte4 << 32);
num200us = num200us | ((uint32_t) time_stamp.shared_time_byte3 << 24);
num200us = num200us | ((uint32_t) time_stamp.shared_time_byte2 << 16);
num200us = num200us | ((uint32_t) time_stamp.shared_time_byte1 << 8);
num200us = num200us | (time_stamp.shared_time_byte0);
return num200us;
}
float
LT_FaultLog::getTimeInMs(FaultLogTimeStamp time_stamp)
{
double ms = getSharedTime200us(time_stamp)/5.0;
return ms;
}
uint8_t
LT_FaultLog::getRawByteVal(RawByte value)
{
return (uint8_t) value.uint8_tValue;
}
uint16_t
LT_FaultLog::getRawWordVal(RawWord value)
{
return (uint16_t) (value.lo_byte | (value.hi_byte << 8));
}
uint16_t
LT_FaultLog::getRawWordReverseVal(RawWordReverse value)
{
return (uint16_t) (value.lo_byte | (value.hi_byte << 8));
}
uint16_t
LT_FaultLog::getLin5_11WordVal(Lin5_11Word value)
{
return (uint16_t) (value.lo_byte | (value.hi_byte << 8));
}
uint16_t
LT_FaultLog::getLin5_11WordReverseVal(Lin5_11WordReverse value)
{
return (uint16_t) (value.lo_byte | (value.hi_byte << 8));
}
uint16_t
LT_FaultLog::getLin16WordVal(Lin16Word value)
{
return (uint16_t) (value.lo_byte | (value.hi_byte << 8));
}
uint16_t
LT_FaultLog::getLin16WordReverseVal(Lin16WordReverse value)
{
return (uint16_t) (value.lo_byte | (value.hi_byte << 8));
} | 25.977124 | 116 | 0.662473 | LinduinoBob |
c48f8537943766823af0757390ae7330b5a663fc | 1,604 | hpp | C++ | include/dish2/viz/artists/TaxaArtist.hpp | schregardusc/dishtiny | b0b1841a457a955fa4c22f36a050d91f12484f9e | [
"MIT"
] | 1 | 2021-02-12T23:53:55.000Z | 2021-02-12T23:53:55.000Z | include/dish2/viz/artists/TaxaArtist.hpp | schregardusc/dishtiny | b0b1841a457a955fa4c22f36a050d91f12484f9e | [
"MIT"
] | null | null | null | include/dish2/viz/artists/TaxaArtist.hpp | schregardusc/dishtiny | b0b1841a457a955fa4c22f36a050d91f12484f9e | [
"MIT"
] | null | null | null | #pragma once
#ifndef DISH2_VIZ_ARTISTS_TAXAARTIST_HPP_INCLUDE
#define DISH2_VIZ_ARTISTS_TAXAARTIST_HPP_INCLUDE
#include <string>
#include "../../spec/Spec.hpp"
#include "../border_colormaps/TaxaBorderColorMap.hpp"
#include "../fill_colormaps/IsAliveColorMap.hpp"
#include "../fill_colormaps/KinGroupIDGrayscaleFillColorMap.hpp"
#include "../getters/GenomeGetter.hpp"
#include "../getters/IsAliveGetter.hpp"
#include "../getters/KinGroupIDGetter.hpp"
#include "../renderers/CellBorderRenderer.hpp"
#include "../renderers/CellFillRenderer.hpp"
#include "Artist.hpp"
namespace dish2 {
namespace internal::taxa_artist {
template<
typename GenomeGetter,
typename IsAliveGetter,
typename KinGroupIDGetter
>
using parent_t = dish2::Artist<
dish2::CellFillRenderer<
dish2::IsAliveColorMap,
IsAliveGetter
>,
dish2::CellBorderRenderer<
dish2::TaxaBorderColorMap,
GenomeGetter
>
>;
} // namespace internal::taxa_artist
template<
typename GenomeGetter=dish2::GenomeGetter<dish2::Spec>,
typename IsAliveGetter=dish2::IsAliveGetter<dish2::Spec>,
typename KinGroupIDGetter=dish2::KinGroupIDGetter<dish2::Spec>
>
class TaxaArtist
: public internal::taxa_artist::parent_t<
GenomeGetter,
IsAliveGetter,
KinGroupIDGetter
> {
using parent_t = internal::taxa_artist::parent_t<
GenomeGetter,
IsAliveGetter,
KinGroupIDGetter
>;
public:
// inherit constructors
using parent_t::parent_t;
static std::string GetName() { return "Taxa"; }
};
} // namespace dish2
#endif // #ifndef DISH2_VIZ_ARTISTS_TAXAARTIST_HPP_INCLUDE
| 22.277778 | 64 | 0.747506 | schregardusc |
c490e76884dcc19d44bbdc4fee5099ed5becb757 | 5,990 | cc | C++ | servlib/cmd/DiscoveryCommand.cc | LeoIannacone/dtn | b7ee725bb147e29cc05ac8790b1d24efcd9f841e | [
"Apache-2.0"
] | 2 | 2017-10-29T11:15:47.000Z | 2019-09-15T13:43:25.000Z | servlib/cmd/DiscoveryCommand.cc | LeoIannacone/dtn | b7ee725bb147e29cc05ac8790b1d24efcd9f841e | [
"Apache-2.0"
] | null | null | null | servlib/cmd/DiscoveryCommand.cc | LeoIannacone/dtn | b7ee725bb147e29cc05ac8790b1d24efcd9f841e | [
"Apache-2.0"
] | 3 | 2015-03-27T05:56:05.000Z | 2020-01-02T22:18:02.000Z | /*
* Copyright 2006 Baylor University
*
* 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 HAVE_CONFIG_H
# include <dtn-config.h>
#endif
#include <climits>
#include "DiscoveryCommand.h"
#include "discovery/Discovery.h"
#include "discovery/DiscoveryTable.h"
#include "conv_layers/ConvergenceLayer.h"
#include <oasys/util/StringBuffer.h>
namespace dtn {
DiscoveryCommand::DiscoveryCommand()
: TclCommand("discovery")
{
add_to_help("add <discovery_name> <cl_type> [ <port=val> "
"<continue_on_error=val> <addr=val> <local_addr=val> "
"<multicast_ttl=val> <unicast=val> ]",
"add a discovery agent\n"
" valid options:\n"
" <discovery_name>\n"
" A string to define agent name\n"
" <cl_type>\n"
" The CLA type\n"
" bt\n"
" ip\n"
" bonjour\n"
" [ CLA specific options ]\n"
" <port=port>\n"
" <continue_on_error=true or false>\n"
" <addr=A.B.C.D>\n"
" <local_addr=A.B.C.D>\n"
" <multicast_ttl=TTL number>\n"
" <unicast=true or false>\n");
add_to_help("del <discovery_name>",
"remove discovery agent\n"
" valid options:\n"
" <discovery_name>\n"
" A string to define agent name\n");
add_to_help("announce <cl_name> <discovery_name> <cl_type> "
"<interval=val> [ <cl_addr=val> <cl_port=val> ]",
"announce the address of a local interface (convergence "
"layer)\n"
" valid options:\n"
" <cl_name>\n"
" The CLA name\n"
" <discovery_name>\n"
" An agent name string\n"
" <cl_type>\n"
" The CLA type\n"
" bt\n"
" ip\n"
" <interval=val>\n"
" Periodic announcement interval\n"
" <interval=number>\n"
" [ CLA specific options ]\n"
" <cl_addr=A.B.C.D>\n"
" <cl_port=port number>\n");
add_to_help("remove <cl_name>",
"remove announcement for local interface\n"
" valid options:\n"
" <cl_name>\n"
" The CLA name\n");
add_to_help("list",
"list all discovery agents and announcements\n");
}
int
DiscoveryCommand::exec(int argc, const char** argv, Tcl_Interp* interp)
{
(void)interp;
if (strncasecmp("list",argv[1],4) == 0)
{
if (argc > 2)
{
wrong_num_args(argc, argv, 1, 2, 2);
}
oasys::StringBuffer buf;
DiscoveryTable::instance()->dump(&buf);
set_result(buf.c_str());
return TCL_OK;
}
else
// discovery add <name> <address family> <port>
// [<local_addr> <addr> <multicast_ttl> <channel>]
if (strncasecmp("add",argv[1],3) == 0)
{
if (argc < 4)
{
wrong_num_args(argc, argv, 2, 4, INT_MAX);
return TCL_ERROR;
}
const char* name = argv[2];
const char* afname = argv[3];
const char* err = "(unknown error)";
if (! DiscoveryTable::instance()->add(name, afname,
argc - 4, argv + 4,
&err))
{
resultf("error adding agent %s: %s", name, err);
return TCL_ERROR;
}
return TCL_OK;
}
else
// discovery del <name>
if (strncasecmp("del",argv[1],3) == 0)
{
if (argc != 3)
{
wrong_num_args(argc,argv,2,3,3);
return TCL_ERROR;
}
const char* name = argv[2];
if (! DiscoveryTable::instance()->del(name))
{
resultf("error removing agent %s", name);
return TCL_ERROR;
}
return TCL_OK;
}
// discovery announce <name> <discovery name> <cl type> <interval>
// [<cl_addr> <cl_port>]
else
if (strncasecmp("announce",argv[1],8) == 0)
{
if (argc < 6)
{
wrong_num_args(argc,argv,2,6,INT_MAX);
return TCL_ERROR;
}
const char* name = argv[2];
const char* dname = argv[3];
DiscoveryList::iterator iter;
if (! DiscoveryTable::instance()->find(dname,&iter))
{
resultf("error adding announce %s to %s: "
"no such discovery agent",
name,dname);
return TCL_ERROR;
}
Discovery* disc = *iter;
if (! disc->announce(name,argc - 4,argv + 4))
{
resultf("error adding announce %s to %s",name,dname);
return TCL_ERROR;
}
return TCL_OK;
}
else
// discovery remove <name> <discovery name>
if (strncasecmp("remove",argv[1],6) == 0)
{
if (argc != 4)
{
wrong_num_args(argc,argv,2,4,4);
return TCL_ERROR;
}
const char* name = argv[2];
const char* dname = argv[3];
DiscoveryList::iterator iter;
if (! DiscoveryTable::instance()->find(dname,&iter))
{
resultf("error removing announce %s from %s: no such discovery agent",
name,dname);
return TCL_ERROR;
}
Discovery* disc = *iter;
if (! disc->remove(name))
{
resultf("error removing announce %s from %s: no such announce",
name,dname);
return TCL_ERROR;
}
return TCL_OK;
}
resultf("invalid discovery command: %s",argv[1]);
return TCL_ERROR;
}
} // namespace dtn
| 27.603687 | 82 | 0.539399 | LeoIannacone |
c491824e4c2d94f6e0cb1902c7fb9ca02e48d2c9 | 2,293 | hpp | C++ | private/inc/avb_watchdog/IasWatchdogResult.hpp | tnishiok/AVBStreamHandler | 7621daf8c9238361e030fe35188b921ee8ea2466 | [
"BSL-1.0",
"BSD-3-Clause"
] | 13 | 2018-09-26T13:32:35.000Z | 2021-05-20T10:01:12.000Z | private/inc/avb_watchdog/IasWatchdogResult.hpp | tnishiok/AVBStreamHandler | 7621daf8c9238361e030fe35188b921ee8ea2466 | [
"BSL-1.0",
"BSD-3-Clause"
] | 23 | 2018-10-03T22:45:21.000Z | 2020-03-05T23:40:12.000Z | private/inc/avb_watchdog/IasWatchdogResult.hpp | tnishiok/AVBStreamHandler | 7621daf8c9238361e030fe35188b921ee8ea2466 | [
"BSL-1.0",
"BSD-3-Clause"
] | 22 | 2018-09-14T03:55:34.000Z | 2021-12-07T01:13:27.000Z | /*
* Copyright (C) 2018 Intel Corporation. All rights reserved.
*
* SPDX-License-Identifier: BSD-3-Clause
*
*/
#ifndef IAS_MONITORING_AND_LIFECYCLE_WATCHDOG_IAS_WATCHDOG_RESULT_HPP
#define IAS_MONITORING_AND_LIFECYCLE_WATCHDOG_IAS_WATCHDOG_RESULT_HPP
#include "media_transport/avb_streamhandler_api/IasAvbStreamHandlerTypes.hpp"
#include "avb_helper/IasResult.hpp"
#include <dlt/dlt_cpp_extension.hpp>
#include <string>
/**
* @brief Ias
*/
namespace IasWatchdog
{
/**
* @brief Ias
*/
enum IasResultMonitoringAndLifecycleGroups {
cIasResultGroupWatchdog
};
/**
* @brief Custom result class for the Watchdog component.
*/
class /*IAS_DSO_PUBLIC*/ IasWatchdogResult : public IasMediaTransportAvb::IasResult
{
public:
/**
* @brief WatchdogResult Constructor.
* @param[in] value the value of the thread result.
*/
explicit IasWatchdogResult(uint32_t const value)
: IasResult(value, cIasResultGroupWatchdog, IasMediaTransportAvb::cIasResultModuleMonitoringAndLifeCycle)
{
}
/**
* @brief IasWatchdogResult Constructor creating IasWatchdogResult from IasResult.
* @param[in] result IasResult to convert.
*/
IasWatchdogResult(IasMediaTransportAvb::IasResult const & result)
: IasResult(result)
{
}
virtual std::string toString()const;
static const IasWatchdogResult cObjectNotFound; /**< Result value cObjectNotFound */
static const IasWatchdogResult cAlreadyRegistered; /**< Result value cAlreadyRegistered */
static const IasWatchdogResult cWatchdogUnregistered; /**< Result value cWatchdogUnregistered */
static const IasWatchdogResult cWatchdogNotConnected; /**< Result value cWatchdogNotConnected */
static const IasWatchdogResult cAcquireLockFailed; /**<acquire of lock failed */
static const IasWatchdogResult cIncorrectThread; /**<reset called by incorrect thread */
static const IasWatchdogResult cTimedOut; /**<reset called too late. Watchdog already timed out */
static const IasWatchdogResult cWatchdogNotPreconfigured;/**< Result value cWatchdogNotPreconfigured */
};
}
template<>
IAS_DSO_PUBLIC int32_t logToDlt(DltContextData &log, IasWatchdog::IasWatchdogResult const & value);
#endif // IAS_MONITORING_AND_LIFECYCLE_WATCHDOG_IAS_WATCHDOG_RESULT_HPP
| 32.295775 | 115 | 0.764065 | tnishiok |
c497352f239e93012d3d811519f38cd17a7264a1 | 17,127 | cpp | C++ | src/shogun/io/HDF5File.cpp | rka97/shogun | 93d7afa8073fcb5a9f3d9e6492a6fd3c8a2e48be | [
"BSD-3-Clause"
] | null | null | null | src/shogun/io/HDF5File.cpp | rka97/shogun | 93d7afa8073fcb5a9f3d9e6492a6fd3c8a2e48be | [
"BSD-3-Clause"
] | null | null | null | src/shogun/io/HDF5File.cpp | rka97/shogun | 93d7afa8073fcb5a9f3d9e6492a6fd3c8a2e48be | [
"BSD-3-Clause"
] | null | null | null | /*
* This software is distributed under BSD 3-clause license (see LICENSE file).
*
* Authors: Soeren Sonnenburg, Soumyajit De, Viktor Gal, Thoralf Klein,
* Evan Shelhamer, Bjoern Esser, Abhinav Agarwalla
*/
#include <shogun/lib/config.h>
#ifdef HAVE_HDF5
#include <stdio.h>
#include <string.h>
#include <hdf5.h>
#include <shogun/lib/memory.h>
#include <shogun/io/HDF5File.h>
#include <shogun/io/SGIO.h>
using namespace shogun;
CHDF5File::CHDF5File()
{
SG_UNSTABLE("CHDF5File::CHDF5File()", "\n")
get_boolean_type();
h5file = -1;
}
CHDF5File::CHDF5File(char* fname, char rw, const char* name) : CFile()
{
get_boolean_type();
H5Eset_auto2(H5E_DEFAULT, NULL, NULL);
if (name)
set_variable_name(name);
switch (rw)
{
case 'r':
h5file = H5Fopen(fname, H5F_ACC_RDONLY, H5P_DEFAULT);
break;
case 'w':
h5file = H5Fcreate(fname, H5F_ACC_TRUNC, H5P_DEFAULT, H5P_DEFAULT);
break;
case 'a':
h5file = H5Fopen(fname, H5F_ACC_RDWR, H5P_DEFAULT);
if (h5file <0)
h5file = H5Fcreate(fname, H5F_ACC_TRUNC, H5P_DEFAULT, H5P_DEFAULT);
break;
default:
SG_ERROR("unknown mode '%c'\n", rw)
};
if (h5file<0)
SG_ERROR("Could not open file '%s'\n", fname)
}
CHDF5File::~CHDF5File()
{
H5Fclose(h5file);
}
#define GET_VECTOR(fname, sg_type, datatype) \
void CHDF5File::fname(sg_type*& vec, int32_t& len) \
{ \
if (!h5file) \
SG_ERROR("File invalid.\n") \
\
int32_t* dims; \
int32_t ndims; \
int64_t nelements; \
hid_t dataset = H5Dopen2(h5file, variable_name, H5P_DEFAULT); \
if (dataset<0) \
SG_ERROR("Error opening data set\n") \
hid_t dtype = H5Dget_type(dataset); \
H5T_class_t t_class=H5Tget_class(dtype); \
TSGDataType t datatype; hid_t h5_type=get_compatible_type(t_class, &t); \
if (h5_type==-1) \
{ \
H5Dclose(dataset); \
SG_INFO("No compatible datatype found\n") \
} \
get_dims(dataset, dims, ndims, nelements); \
if (!((ndims==2 && dims[0]==nelements && dims[1]==1) || \
(ndims==2 && dims[0]==1 && dims[1]==nelements) || \
(ndims==1 && dims[0]==nelements))) \
SG_ERROR("Error not a 1-dimensional vector (ndims=%d, dims[0]=%d)\n", ndims, dims[0]) \
vec=SG_MALLOC(sg_type, nelements); \
len=nelements; \
herr_t status = H5Dread(dataset, h5_type, H5S_ALL, \
H5S_ALL, H5P_DEFAULT, vec); \
H5Dclose(dataset); \
H5Tclose(dtype); \
SG_FREE(dims); \
if (status<0) \
{ \
SG_FREE(vec); \
SG_ERROR("Error reading dataset\n") \
} \
}
GET_VECTOR(get_vector, bool, (CT_VECTOR, ST_NONE, PT_BOOL))
GET_VECTOR(get_vector, int8_t, (CT_VECTOR, ST_NONE, PT_INT8))
GET_VECTOR(get_vector, uint8_t, (CT_VECTOR, ST_NONE, PT_UINT8))
GET_VECTOR(get_vector, char, (CT_VECTOR, ST_NONE, PT_CHAR))
GET_VECTOR(get_vector, int32_t, (CT_VECTOR, ST_NONE, PT_INT32))
GET_VECTOR(get_vector, uint32_t, (CT_VECTOR, ST_NONE, PT_UINT32))
GET_VECTOR(get_vector, float32_t, (CT_VECTOR, ST_NONE, PT_FLOAT32))
GET_VECTOR(get_vector, float64_t, (CT_VECTOR, ST_NONE, PT_FLOAT64))
GET_VECTOR(get_vector, floatmax_t, (CT_VECTOR, ST_NONE, PT_FLOATMAX))
GET_VECTOR(get_vector, int16_t, (CT_VECTOR, ST_NONE, PT_INT16))
GET_VECTOR(get_vector, uint16_t, (CT_VECTOR, ST_NONE, PT_INT16))
GET_VECTOR(get_vector, int64_t, (CT_VECTOR, ST_NONE, PT_INT64))
GET_VECTOR(get_vector, uint64_t, (CT_VECTOR, ST_NONE, PT_UINT64))
#undef GET_VECTOR
#define GET_MATRIX(fname, sg_type, datatype) \
void CHDF5File::fname(sg_type*& matrix, int32_t& num_feat, int32_t& num_vec) \
{ \
if (!h5file) \
SG_ERROR("File invalid.\n") \
\
int32_t* dims; \
int32_t ndims; \
int64_t nelements; \
hid_t dataset = H5Dopen2(h5file, variable_name, H5P_DEFAULT); \
if (dataset<0) \
SG_ERROR("Error opening data set\n") \
hid_t dtype = H5Dget_type(dataset); \
H5T_class_t t_class=H5Tget_class(dtype); \
TSGDataType t datatype; hid_t h5_type=get_compatible_type(t_class, &t); \
if (h5_type==-1) \
{ \
H5Dclose(dataset); \
SG_INFO("No compatible datatype found\n") \
} \
get_dims(dataset, dims, ndims, nelements); \
if (ndims!=2) \
SG_ERROR("Error not a 2-dimensional matrix\n") \
matrix=SG_MALLOC(sg_type, nelements); \
num_feat=dims[0]; \
num_vec=dims[1]; \
herr_t status = H5Dread(dataset, h5_type, H5S_ALL, \
H5S_ALL, H5P_DEFAULT, matrix); \
H5Dclose(dataset); \
H5Tclose(dtype); \
SG_FREE(dims); \
if (status<0) \
{ \
SG_FREE(matrix); \
SG_ERROR("Error reading dataset\n") \
} \
}
GET_MATRIX(get_matrix, bool, (CT_MATRIX, ST_NONE, PT_BOOL))
GET_MATRIX(get_matrix, char, (CT_MATRIX, ST_NONE, PT_CHAR))
GET_MATRIX(get_matrix, uint8_t, (CT_MATRIX, ST_NONE, PT_UINT8))
GET_MATRIX(get_matrix, int32_t, (CT_MATRIX, ST_NONE, PT_INT32))
GET_MATRIX(get_matrix, uint32_t, (CT_MATRIX, ST_NONE, PT_INT32))
GET_MATRIX(get_matrix, int64_t, (CT_MATRIX, ST_NONE, PT_INT64))
GET_MATRIX(get_matrix, uint64_t, (CT_MATRIX, ST_NONE, PT_INT64))
GET_MATRIX(get_matrix, int16_t, (CT_MATRIX, ST_NONE, PT_INT16))
GET_MATRIX(get_matrix, uint16_t, (CT_MATRIX, ST_NONE, PT_INT16))
GET_MATRIX(get_matrix, float32_t, (CT_MATRIX, ST_NONE, PT_FLOAT32))
GET_MATRIX(get_matrix, float64_t, (CT_MATRIX, ST_NONE, PT_FLOAT64))
GET_MATRIX(get_matrix, floatmax_t, (CT_MATRIX, ST_NONE, PT_FLOATMAX))
#undef GET_MATRIX
#define GET_SPARSEMATRIX(fname, sg_type, datatype) \
void CHDF5File::fname(SGSparseVector<sg_type>*& matrix, int32_t& num_feat, int32_t& num_vec) \
{ \
if (!(file)) \
SG_ERROR("File invalid.\n") \
}
GET_SPARSEMATRIX(get_sparse_matrix, bool, DT_SPARSE_BOOL)
GET_SPARSEMATRIX(get_sparse_matrix, char, DT_SPARSE_CHAR)
GET_SPARSEMATRIX(get_sparse_matrix, int8_t, DT_SPARSE_INT8)
GET_SPARSEMATRIX(get_sparse_matrix, uint8_t, DT_SPARSE_BYTE)
GET_SPARSEMATRIX(get_sparse_matrix, int32_t, DT_SPARSE_INT)
GET_SPARSEMATRIX(get_sparse_matrix, uint32_t, DT_SPARSE_UINT)
GET_SPARSEMATRIX(get_sparse_matrix, int64_t, DT_SPARSE_LONG)
GET_SPARSEMATRIX(get_sparse_matrix, uint64_t, DT_SPARSE_ULONG)
GET_SPARSEMATRIX(get_sparse_matrix, int16_t, DT_SPARSE_SHORT)
GET_SPARSEMATRIX(get_sparse_matrix, uint16_t, DT_SPARSE_WORD)
GET_SPARSEMATRIX(get_sparse_matrix, float32_t, DT_SPARSE_SHORTREAL)
GET_SPARSEMATRIX(get_sparse_matrix, float64_t, DT_SPARSE_REAL)
GET_SPARSEMATRIX(get_sparse_matrix, floatmax_t, DT_SPARSE_LONGREAL)
#undef GET_SPARSEMATRIX
#define GET_STRING_LIST(fname, sg_type, datatype) \
void CHDF5File::fname(SGVector<sg_type>*& strings, int32_t& num_str, int32_t& max_string_len) \
{ \
}
GET_STRING_LIST(get_string_list, bool, DT_STRING_BOOL)
GET_STRING_LIST(get_string_list, char, DT_STRING_CHAR)
GET_STRING_LIST(get_string_list, int8_t, DT_STRING_INT8)
GET_STRING_LIST(get_string_list, uint8_t, DT_STRING_BYTE)
GET_STRING_LIST(get_string_list, int32_t, DT_STRING_INT)
GET_STRING_LIST(get_string_list, uint32_t, DT_STRING_UINT)
GET_STRING_LIST(get_string_list, int64_t, DT_STRING_LONG)
GET_STRING_LIST(get_string_list, uint64_t, DT_STRING_ULONG)
GET_STRING_LIST(get_string_list, int16_t, DT_STRING_SHORT)
GET_STRING_LIST(get_string_list, uint16_t, DT_STRING_WORD)
GET_STRING_LIST(get_string_list, float32_t, DT_STRING_SHORTREAL)
GET_STRING_LIST(get_string_list, float64_t, DT_STRING_REAL)
GET_STRING_LIST(get_string_list, floatmax_t, DT_STRING_LONGREAL)
#undef GET_STRING_LIST
/** set functions - to pass data from shogun to the target interface */
#define SET_VECTOR(fname, sg_type, dtype, h5type) \
void CHDF5File::fname(const sg_type* vec, int32_t len) \
{ \
if (h5file<0 || !vec) \
SG_ERROR("File or vector invalid.\n") \
\
create_group_hierarchy(); \
\
hsize_t dims=(hsize_t) len; \
hid_t dataspace, dataset, status; \
dataspace=H5Screate_simple(1, &dims, NULL); \
if (dataspace<0) \
SG_ERROR("Could not create hdf5 dataspace\n") \
dataset=H5Dcreate2(h5file, variable_name, h5type, dataspace, H5P_DEFAULT,\
H5P_DEFAULT, H5P_DEFAULT); \
if (dataset<0) \
{ \
SG_ERROR("Could not create hdf5 dataset - does" \
" dataset '%s' already exist?\n", variable_name); \
} \
status=H5Dwrite(dataset, h5type, H5S_ALL, H5S_ALL, H5P_DEFAULT, vec); \
if (status<0) \
SG_ERROR("Failed to write hdf5 dataset\n") \
H5Dclose(dataset); \
H5Sclose(dataspace); \
}
SET_VECTOR(set_vector, bool, DT_VECTOR_BOOL, boolean_type)
SET_VECTOR(set_vector, int8_t, DT_VECTOR_BYTE, H5T_NATIVE_INT8)
SET_VECTOR(set_vector, uint8_t, DT_VECTOR_BYTE, H5T_NATIVE_UINT8)
SET_VECTOR(set_vector, char, DT_VECTOR_CHAR, H5T_NATIVE_CHAR)
SET_VECTOR(set_vector, int32_t, DT_VECTOR_INT, H5T_NATIVE_INT32)
SET_VECTOR(set_vector, uint32_t, DT_VECTOR_UINT, H5T_NATIVE_UINT32)
SET_VECTOR(set_vector, float32_t, DT_VECTOR_SHORTREAL, H5T_NATIVE_FLOAT)
SET_VECTOR(set_vector, float64_t, DT_VECTOR_REAL, H5T_NATIVE_DOUBLE)
SET_VECTOR(set_vector, floatmax_t, DT_VECTOR_LONGREAL, H5T_NATIVE_LDOUBLE)
SET_VECTOR(set_vector, int16_t, DT_VECTOR_SHORT, H5T_NATIVE_INT16)
SET_VECTOR(set_vector, uint16_t, DT_VECTOR_WORD, H5T_NATIVE_UINT16)
SET_VECTOR(set_vector, int64_t, DT_VECTOR_LONG, H5T_NATIVE_LLONG)
SET_VECTOR(set_vector, uint64_t, DT_VECTOR_ULONG, H5T_NATIVE_ULLONG)
#undef SET_VECTOR
#define SET_MATRIX(fname, sg_type, dtype, h5type) \
void CHDF5File::fname(const sg_type* matrix, int32_t num_feat, int32_t num_vec) \
{ \
if (h5file<0 || !matrix) \
SG_ERROR("File or matrix invalid.\n") \
\
create_group_hierarchy(); \
\
hsize_t dims[2]={(hsize_t) num_feat, (hsize_t) num_vec}; \
hid_t dataspace, dataset, status; \
dataspace=H5Screate_simple(2, dims, NULL); \
if (dataspace<0) \
SG_ERROR("Could not create hdf5 dataspace\n") \
dataset=H5Dcreate2(h5file, variable_name, h5type, dataspace, H5P_DEFAULT, \
H5P_DEFAULT, H5P_DEFAULT); \
if (dataset<0) \
{ \
SG_ERROR("Could not create hdf5 dataset - does" \
" dataset '%s' already exist?\n", variable_name); \
} \
status=H5Dwrite(dataset, h5type, H5S_ALL, H5S_ALL, H5P_DEFAULT, matrix); \
if (status<0) \
SG_ERROR("Failed to write hdf5 dataset\n") \
H5Dclose(dataset); \
H5Sclose(dataspace); \
}
SET_MATRIX(set_matrix, bool, DT_DENSE_BOOL, boolean_type)
SET_MATRIX(set_matrix, char, DT_DENSE_CHAR, H5T_NATIVE_CHAR)
SET_MATRIX(set_matrix, int8_t, DT_DENSE_BYTE, H5T_NATIVE_INT8)
SET_MATRIX(set_matrix, uint8_t, DT_DENSE_BYTE, H5T_NATIVE_UINT8)
SET_MATRIX(set_matrix, int32_t, DT_DENSE_INT, H5T_NATIVE_INT32)
SET_MATRIX(set_matrix, uint32_t, DT_DENSE_UINT, H5T_NATIVE_UINT32)
SET_MATRIX(set_matrix, int64_t, DT_DENSE_LONG, H5T_NATIVE_INT64)
SET_MATRIX(set_matrix, uint64_t, DT_DENSE_ULONG, H5T_NATIVE_UINT64)
SET_MATRIX(set_matrix, int16_t, DT_DENSE_SHORT, H5T_NATIVE_INT16)
SET_MATRIX(set_matrix, uint16_t, DT_DENSE_WORD, H5T_NATIVE_UINT16)
SET_MATRIX(set_matrix, float32_t, DT_DENSE_SHORTREAL, H5T_NATIVE_FLOAT)
SET_MATRIX(set_matrix, float64_t, DT_DENSE_REAL, H5T_NATIVE_DOUBLE)
SET_MATRIX(set_matrix, floatmax_t, DT_DENSE_LONGREAL, H5T_NATIVE_LDOUBLE)
#undef SET_MATRIX
#define SET_SPARSEMATRIX(fname, sg_type, dtype) \
void CHDF5File::fname(const SGSparseVector<sg_type>* matrix, \
int32_t num_feat, int32_t num_vec) \
{ \
if (!(file && matrix)) \
SG_ERROR("File or matrix invalid.\n") \
\
}
SET_SPARSEMATRIX(set_sparse_matrix, bool, DT_SPARSE_BOOL)
SET_SPARSEMATRIX(set_sparse_matrix, char, DT_SPARSE_CHAR)
SET_SPARSEMATRIX(set_sparse_matrix, int8_t, DT_SPARSE_INT8)
SET_SPARSEMATRIX(set_sparse_matrix, uint8_t, DT_SPARSE_BYTE)
SET_SPARSEMATRIX(set_sparse_matrix, int32_t, DT_SPARSE_INT)
SET_SPARSEMATRIX(set_sparse_matrix, uint32_t, DT_SPARSE_UINT)
SET_SPARSEMATRIX(set_sparse_matrix, int64_t, DT_SPARSE_LONG)
SET_SPARSEMATRIX(set_sparse_matrix, uint64_t, DT_SPARSE_ULONG)
SET_SPARSEMATRIX(set_sparse_matrix, int16_t, DT_SPARSE_SHORT)
SET_SPARSEMATRIX(set_sparse_matrix, uint16_t, DT_SPARSE_WORD)
SET_SPARSEMATRIX(set_sparse_matrix, float32_t, DT_SPARSE_SHORTREAL)
SET_SPARSEMATRIX(set_sparse_matrix, float64_t, DT_SPARSE_REAL)
SET_SPARSEMATRIX(set_sparse_matrix, floatmax_t, DT_SPARSE_LONGREAL)
#undef SET_SPARSEMATRIX
#define SET_STRING_LIST(fname, sg_type, dtype) \
void CHDF5File::fname(const SGVector<sg_type>* strings, int32_t num_str) \
{ \
if (!(file && strings)) \
SG_ERROR("File or strings invalid.\n") \
\
}
SET_STRING_LIST(set_string_list, bool, DT_STRING_BOOL)
SET_STRING_LIST(set_string_list, char, DT_STRING_CHAR)
SET_STRING_LIST(set_string_list, int8_t, DT_STRING_INT8)
SET_STRING_LIST(set_string_list, uint8_t, DT_STRING_BYTE)
SET_STRING_LIST(set_string_list, int32_t, DT_STRING_INT)
SET_STRING_LIST(set_string_list, uint32_t, DT_STRING_UINT)
SET_STRING_LIST(set_string_list, int64_t, DT_STRING_LONG)
SET_STRING_LIST(set_string_list, uint64_t, DT_STRING_ULONG)
SET_STRING_LIST(set_string_list, int16_t, DT_STRING_SHORT)
SET_STRING_LIST(set_string_list, uint16_t, DT_STRING_WORD)
SET_STRING_LIST(set_string_list, float32_t, DT_STRING_SHORTREAL)
SET_STRING_LIST(set_string_list, float64_t, DT_STRING_REAL)
SET_STRING_LIST(set_string_list, floatmax_t, DT_STRING_LONGREAL)
#undef SET_STRING_LIST
void CHDF5File::get_boolean_type()
{
boolean_type=H5T_NATIVE_UCHAR;
switch (sizeof(bool))
{
case 1:
boolean_type = H5T_NATIVE_UCHAR;
break;
case 2:
boolean_type = H5T_NATIVE_UINT16;
break;
case 4:
boolean_type = H5T_NATIVE_UINT32;
break;
case 8:
boolean_type = H5T_NATIVE_UINT64;
break;
default:
SG_ERROR("Boolean type not supported on this platform\n")
}
}
hid_t CHDF5File::get_compatible_type(H5T_class_t t_class,
const TSGDataType* datatype)
{
switch (t_class)
{
case H5T_FLOAT:
case H5T_INTEGER:
switch (datatype->m_ptype)
{
case PT_BOOL: return boolean_type;
case PT_CHAR: return H5T_NATIVE_CHAR;
case PT_INT8: return H5T_NATIVE_INT8;
case PT_UINT8: return H5T_NATIVE_UINT8;
case PT_INT16: return H5T_NATIVE_INT16;
case PT_UINT16: return H5T_NATIVE_UINT16;
case PT_INT32: return H5T_NATIVE_INT32;
case PT_UINT32: return H5T_NATIVE_UINT32;
case PT_INT64: return H5T_NATIVE_INT64;
case PT_UINT64: return H5T_NATIVE_UINT64;
case PT_FLOAT32: return H5T_NATIVE_FLOAT;
case PT_FLOAT64: return H5T_NATIVE_DOUBLE;
case PT_FLOATMAX: return H5T_NATIVE_LDOUBLE;
case PT_COMPLEX128:
SG_ERROR("complex128_t not compatible with HDF5File!");
return -1;
case PT_SGOBJECT:
case PT_UNDEFINED:
SG_ERROR("Implementation error during writing "
"HDF5File!");
return -1;
}
case H5T_STRING:
SG_ERROR("Strings not supported")
return -1;
case H5T_VLEN:
SG_ERROR("Variable length containers currently not supported")
return -1;
case H5T_ARRAY:
SG_ERROR("Array containers currently not supported")
return -1;
default:
SG_ERROR("Datatype mismatchn")
return -1;
}
}
void CHDF5File::get_dims(hid_t dataset, int32_t*& dims, int32_t& ndims, int64_t& total_elements)
{
hid_t dataspace = H5Dget_space(dataset);
if (dataspace<0)
SG_ERROR("Error obtaining hdf5 dataspace\n")
ndims = H5Sget_simple_extent_ndims(dataspace);
total_elements=H5Sget_simple_extent_npoints(dataspace);
hsize_t* dims_out=SG_MALLOC(hsize_t, ndims);
dims=SG_MALLOC(int32_t, ndims);
H5Sget_simple_extent_dims(dataspace, dims_out, NULL);
for (int32_t i=0; i<ndims; i++)
dims[i]=dims_out[i];
SG_FREE(dims_out);
H5Sclose(dataspace);
}
void CHDF5File::create_group_hierarchy()
{
char* vname=get_strdup(variable_name);
int32_t vlen=strlen(vname);
for (int32_t i=0; i<vlen; i++)
{
if (i!=0 && vname[i]=='/')
{
vname[i]='\0';
hid_t g = H5Gopen2(h5file, vname, H5P_DEFAULT);
if (g<0)
{
g=H5Gcreate2(h5file, vname, H5P_DEFAULT, H5P_DEFAULT,
H5P_DEFAULT);
if (g<0)
SG_ERROR("Error creating group '%s'\n", vname)
vname[i]='/';
}
H5Gclose(g);
}
}
SG_FREE(vname);
}
#endif // HDF5
| 38.144766 | 96 | 0.688795 | rka97 |
7bcf92faf4120d40cff902712e7f64451cdc89aa | 93 | cpp | C++ | tools/stb_image.cpp | ShirokoSama/ShadingSandbox | b407aea1c018bcb46061f3d165c9671d2cb3c139 | [
"MIT"
] | null | null | null | tools/stb_image.cpp | ShirokoSama/ShadingSandbox | b407aea1c018bcb46061f3d165c9671d2cb3c139 | [
"MIT"
] | null | null | null | tools/stb_image.cpp | ShirokoSama/ShadingSandbox | b407aea1c018bcb46061f3d165c9671d2cb3c139 | [
"MIT"
] | 1 | 2019-12-05T11:50:24.000Z | 2019-12-05T11:50:24.000Z | //
// Created by Srf on 2017/10/5.
//
#define STB_IMAGE_IMPLEMENTATION
#include "stb_image.h" | 18.6 | 32 | 0.731183 | ShirokoSama |
7bd161d94216488999bf33ab627feddf42b5fb37 | 5,785 | cpp | C++ | KFPlugin/KFMongo/KFMongoReadExecute.cpp | 282951387/KFrame | 5d6e953f7cc312321c36632715259394ca67144c | [
"Apache-2.0"
] | 1 | 2021-04-26T09:31:32.000Z | 2021-04-26T09:31:32.000Z | KFPlugin/KFMongo/KFMongoReadExecute.cpp | 282951387/KFrame | 5d6e953f7cc312321c36632715259394ca67144c | [
"Apache-2.0"
] | null | null | null | KFPlugin/KFMongo/KFMongoReadExecute.cpp | 282951387/KFrame | 5d6e953f7cc312321c36632715259394ca67144c | [
"Apache-2.0"
] | null | null | null | #include "KFMongoReadExecute.hpp"
namespace KFrame
{
KFResult< uint64 >::UniqueType KFMongoReadExecute::Count( const std::string& table )
{
Poco::MongoDB::Database db( _database );
auto request = db.createQueryRequest( "$cmd" );
request->setNumberToReturn( 1 );
request->selector().add( MongoKeyword::_count, table );
__NEW_RESULT__( uint64 );
ResponseMessage response;
auto ok = SendRequest( *request, response );
if ( ok && response.documents().size() > 0 )
{
Poco::MongoDB::Document::Ptr doc = response.documents()[ 0 ];
try
{
kfresult->_value = doc->getInteger( "n" );
}
catch ( Poco::Exception& )
{
__LOG_DEBUG__( "table=[{}] count failed", table );
}
}
else
{
kfresult->SetResult( KFEnum::Error );
}
return kfresult;
}
KFResult< uint64 >::UniqueType KFMongoReadExecute::Count( const std::string& table, const std::string& field, uint64 key )
{
auto fullname = __FORMAT__( "{}.{}", _database, table );
QueryRequest request( fullname, QueryRequest::QUERY_DEFAULT );
auto& selector = request.selector();
selector.add( field, key );
auto& fields = request.returnFieldSelector();
fields.add( MongoKeyword::_id, MongoKeyword::_asc );
__NEW_RESULT__( uint64 );
ResponseMessage response;
auto ok = SendRequest( request, response );
if ( ok )
{
kfresult->_value = response.documents().size();
}
else
{
kfresult->SetResult( KFEnum::Error );
}
return kfresult;
}
/////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////
/////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////
KFResult< std::list< KFDBValue > >::UniqueType KFMongoReadExecute::QueryListRecord( const std::string& table, const KFMongoSelector& kfselector )
{
auto fullname = __FORMAT__( "{}.{}", _database, table );
QueryRequest request( fullname, QueryRequest::QUERY_DEFAULT );
// 查询条件
AddPocoDocument( request.selector(), kfselector );
// 返回的字段
if ( !kfselector._returns.empty() )
{
auto& fields = request.returnFieldSelector();
auto iter = kfselector._returns.find( MongoKeyword::_id );
if ( iter == kfselector._returns.end() )
{
fields.add( MongoKeyword::_id, 0 );
}
for ( auto& iter : kfselector._returns )
{
fields.add( iter.first, iter.second );
}
}
// 数量限制
if ( kfselector._limit_count != 0u )
{
request.setNumberToReturn( kfselector._limit_count );
}
///////////////////////////////////////////////////////////////////////////////////
__NEW_RESULT__( std::list< KFDBValue > );
ResponseMessage response;
auto ok = SendRequest( request, response );
if ( ok )
{
for ( auto i = 0u; i < response.documents().size(); ++i )
{
KFDBValue dbvalue;
Poco::MongoDB::Document::Ptr doc = response.documents()[ i ];
try
{
auto elements = doc->getSet();
for ( auto iter = elements->begin(); iter != elements->end(); ++iter )
{
auto& name = ( *iter )->name();
if ( kfselector._limit_returns.find( name ) != kfselector._limit_returns.end() )
{
continue;
}
auto type = ( *iter )->type();
if ( type == ElementTraits<Poco::Int64>::TypeId )
{
auto concrete = dynamic_cast< const ConcreteElement<Poco::Int64>* >( ( *iter ).get() );
if ( concrete != nullptr )
{
dbvalue.AddValue( name, concrete->value() );
}
}
else if ( type == ElementTraits<std::string>::TypeId )
{
auto concrete = dynamic_cast< const ConcreteElement<std::string>* >( ( *iter ).get() );
if ( concrete != nullptr )
{
dbvalue.AddValue( name, concrete->value(), false );
}
}
else if ( type == ElementTraits<Poco::MongoDB::Binary::Ptr>::TypeId )
{
auto concrete = dynamic_cast< const ConcreteElement<Poco::MongoDB::Binary::Ptr>* >( ( *iter ).get() );
if ( concrete != nullptr )
{
dbvalue.AddValue( name, concrete->value()->toRawString(), true );
}
}
}
}
catch ( Poco::Exception& ex )
{
__LOG_ERROR__( "mongo error=[{}]", ex.displayText() );
}
kfresult->_value.emplace_back( dbvalue );
}
}
else
{
kfresult->SetResult( KFEnum::Error );
}
return kfresult;
}
}
| 37.322581 | 149 | 0.429213 | 282951387 |
7bd412bb28a07a8106fed187fdc54dffd0c6f1db | 10,601 | cpp | C++ | Crisp/ShadingLanguage/Reflection.cpp | FallenShard/Crisp | d4cf22c0f9af73a6c4ba2b7d67696f1a188fd423 | [
"MIT"
] | 6 | 2017-09-14T03:26:49.000Z | 2021-09-18T05:40:59.000Z | Crisp/ShadingLanguage/Reflection.cpp | FallenShard/Crisp | d4cf22c0f9af73a6c4ba2b7d67696f1a188fd423 | [
"MIT"
] | null | null | null | Crisp/ShadingLanguage/Reflection.cpp | FallenShard/Crisp | d4cf22c0f9af73a6c4ba2b7d67696f1a188fd423 | [
"MIT"
] | null | null | null | #include "Reflection.hpp"
#include <optional>
#include <fstream>
#include <IO/FileUtils.hpp>
#include "Lexer.hpp"
#include "Parser.hpp"
#include <spdlog/spdlog.h>
namespace crisp::sl
{
namespace
{
uint32_t getPushConstantFieldOffset(const StructFieldDeclaration& field)
{
for (const auto& qualif : field.fullType->qualifiers)
{
if (qualif->qualifier.type == crisp::sl::TokenType::Layout)
{
auto layoutQualifier = dynamic_cast<crisp::sl::LayoutQualifier*>(qualif.get());
if (!layoutQualifier || layoutQualifier->ids.empty())
return 0;
if (auto bin = dynamic_cast<BinaryExpr*>(layoutQualifier->ids[0].get()))
{
auto* left = dynamic_cast<Variable*>(bin->left.get());
auto* right = dynamic_cast<Literal*>(bin->right.get());
if (left && right && left->name.lexeme == "offset")
return std::any_cast<int>(right->value);
}
}
}
return 0;
}
uint32_t getPushConstantFieldArraySize(const StructFieldDeclaration& field)
{
if (field.variable->arraySpecifiers.empty())
return 1;
else if (auto e = dynamic_cast<Literal*>(field.variable->arraySpecifiers[0]->expr.get()))
{
return std::any_cast<int>(e->value);
}
return 1;
}
VkPushConstantRange parsePushConstant(const Statement* statement, VkShaderStageFlags stage)
{
VkPushConstantRange pc = {};
pc.stageFlags = stage;
pc.offset = 0xFFFFFFFF;
const auto* block = dynamic_cast<const BlockDeclaration*>(statement);
if (block)
{
for (const auto& field : block->fields)
{
auto tokenType = field->fullType->specifier->type.type;
pc.offset = std::min(pc.offset, getPushConstantFieldOffset(*field));
uint32_t multiplier = getPushConstantFieldArraySize(*field);
uint32_t fieldSize = 0;
switch (tokenType)
{
case TokenType::Mat4: fieldSize = 16 * sizeof(float); break;
case TokenType::Mat3: fieldSize = 9 * sizeof(float); break;
case TokenType::Vec4: fieldSize = 4 * sizeof(float); break;
case TokenType::Vec2: fieldSize = 2 * sizeof(float); break;
case TokenType::Float: fieldSize = sizeof(float); break;
case TokenType::Uint: fieldSize = sizeof(unsigned int); break;
case TokenType::Int: fieldSize = sizeof(int); break;
default: spdlog::critical("Unknown token size '{}' while parsing push constant!", field->fullType->specifier->type.lexeme); break;
}
pc.size += fieldSize * multiplier;
}
}
return pc;
}
}
Reflection::Reflection()
{
}
void Reflection::parseDescriptorSets(const std::filesystem::path& sourcePath)
{
auto shaderType = sourcePath.stem().extension().string().substr(1);
VkShaderStageFlags stageFlags = 0;
if (shaderType == "vert")
stageFlags = VK_SHADER_STAGE_VERTEX_BIT;
else if (shaderType == "frag")
stageFlags = VK_SHADER_STAGE_FRAGMENT_BIT;
else if (shaderType == "tesc")
stageFlags = VK_SHADER_STAGE_TESSELLATION_CONTROL_BIT;
else if (shaderType == "tese")
stageFlags = VK_SHADER_STAGE_TESSELLATION_EVALUATION_BIT;
else if (shaderType == "geom")
stageFlags = VK_SHADER_STAGE_GEOMETRY_BIT;
else if (shaderType == "comp")
stageFlags = VK_SHADER_STAGE_COMPUTE_BIT;
else
std::terminate();
auto tokens = sl::Lexer(sourcePath).scanTokens();
auto statements = sl::Parser(tokens).parse();
for (const auto& statement : statements)
{
std::optional<uint32_t> setId;
VkDescriptorSetLayoutBinding binding = {};
binding.descriptorCount = 1;
binding.stageFlags = stageFlags;
bool isDynamic = false;
bool isBuffered = false;
std::string name;
auto parseLayoutQualifier = [&](const sl::LayoutQualifier& layoutQualifier)
{
for (auto& id : layoutQualifier.ids)
{
if (auto bin = dynamic_cast<sl::BinaryExpr*>(id.get()))
{
auto* left = dynamic_cast<sl::Variable*>(bin->left.get());
auto* right = dynamic_cast<sl::Literal*>(bin->right.get());
if (left && right)
{
if (left->name.lexeme == "set")
setId = std::any_cast<int>(right->value);
else if (left->name.lexeme == "binding")
binding.binding = std::any_cast<int>(right->value);
}
}
else if (auto identifier = dynamic_cast<sl::Variable*>(id.get()))
{
if (identifier->name.lexeme == "dynamic")
isDynamic = true;
else if (identifier->name.lexeme == "buffered")
isBuffered = true;
else if (identifier->name.lexeme == "push_constant")
m_pushConstants.push_back(parsePushConstant(statement.get(), stageFlags));
}
}
};
if (auto initList = dynamic_cast<sl::InitDeclaratorList*>(statement.get()))
{
for (auto& qualifier : initList->fullType->qualifiers)
{
if (qualifier->qualifier.type == sl::TokenType::Layout)
{
auto layoutQualifier = dynamic_cast<sl::LayoutQualifier*>(qualifier.get());
parseLayoutQualifier(*layoutQualifier);
name = initList->vars[0]->name.lexeme;
}
}
auto typeLexeme = initList->fullType->specifier->type.lexeme;
if (typeLexeme == "sampler" || typeLexeme == "samplerShadow")
binding.descriptorType = VK_DESCRIPTOR_TYPE_SAMPLER;
else if (typeLexeme.find("sampler") != std::string::npos)
binding.descriptorType = VK_DESCRIPTOR_TYPE_COMBINED_IMAGE_SAMPLER;
else if (typeLexeme.find("texture") != std::string::npos)
binding.descriptorType = VK_DESCRIPTOR_TYPE_SAMPLED_IMAGE;
else if (typeLexeme.find("image") != std::string::npos)
binding.descriptorType = VK_DESCRIPTOR_TYPE_STORAGE_IMAGE;
else if (typeLexeme.find("textureBuffer") != std::string::npos)
binding.descriptorType = VK_DESCRIPTOR_TYPE_UNIFORM_TEXEL_BUFFER;
else if (typeLexeme.find("imageBuffer") != std::string::npos)
binding.descriptorType = VK_DESCRIPTOR_TYPE_STORAGE_TEXEL_BUFFER;
else if (typeLexeme.find("subpassInput") != std::string::npos)
binding.descriptorType = VK_DESCRIPTOR_TYPE_INPUT_ATTACHMENT;
}
else if (auto block = dynamic_cast<sl::BlockDeclaration*>(statement.get()))
{
name = block->name.lexeme;
for (uint32_t i = 0; i < block->qualifiers.size(); ++i)
{
const auto& qualifier = block->qualifiers[i];
if (qualifier->qualifier.type == sl::TokenType::Layout)
{
auto layoutQualifier = dynamic_cast<sl::LayoutQualifier*>(qualifier.get());
parseLayoutQualifier(*layoutQualifier);
}
else if (qualifier->qualifier.type == sl::TokenType::Uniform)
binding.descriptorType = VK_DESCRIPTOR_TYPE_UNIFORM_BUFFER;
else if (qualifier->qualifier.type == sl::TokenType::Buffer)
binding.descriptorType = VK_DESCRIPTOR_TYPE_STORAGE_BUFFER;
}
if (isDynamic)
if (binding.descriptorType == VK_DESCRIPTOR_TYPE_UNIFORM_BUFFER)
binding.descriptorType = VK_DESCRIPTOR_TYPE_UNIFORM_BUFFER_DYNAMIC;
else if (binding.descriptorType == VK_DESCRIPTOR_TYPE_STORAGE_BUFFER)
binding.descriptorType = VK_DESCRIPTOR_TYPE_STORAGE_BUFFER_DYNAMIC;
}
if (setId)
{
addSetLayoutBinding(setId.value(), binding, isBuffered);
//std::cout << "Name: " << name << " (" << setId.value() << ", " << binding.binding << ")\n";
}
}
}
uint32_t Reflection::getDescriptorSetCount() const
{
return static_cast<uint32_t>(m_setLayoutBindings.size());
}
std::vector<VkDescriptorSetLayoutBinding> Reflection::getDescriptorSetLayouts(uint32_t index) const
{
return m_setLayoutBindings.at(index);
}
bool Reflection::isSetBuffered(uint32_t index) const
{
return m_isSetBuffered.at(index);
}
std::vector<VkPushConstantRange> Reflection::getPushConstants() const
{
return m_pushConstants;
}
void Reflection::addSetLayoutBinding(uint32_t setId, const VkDescriptorSetLayoutBinding& binding, bool isBuffered)
{
if (m_setLayoutBindings.size() <= setId)
m_setLayoutBindings.resize(setId + 1);
if (m_setLayoutBindings[setId].size() <= binding.binding)
m_setLayoutBindings[setId].resize(binding.binding + 1);
auto prevFlags = m_setLayoutBindings[setId][binding.binding].stageFlags;
m_setLayoutBindings[setId][binding.binding] = binding;
m_setLayoutBindings[setId][binding.binding].stageFlags |= prevFlags;
if (m_isSetBuffered.size() <= setId)
m_isSetBuffered.resize(setId + 1);
m_isSetBuffered[setId] = m_isSetBuffered[setId] | isBuffered;
}
}
| 42.06746 | 150 | 0.541175 | FallenShard |
7bd504d6d506758db9a3b977f982ca32290ce900 | 12,170 | cpp | C++ | src/common/pfs.cpp | xackery/eqx | 777685a6f793014116855805d719899cfa4169d8 | [
"MIT"
] | null | null | null | src/common/pfs.cpp | xackery/eqx | 777685a6f793014116855805d719899cfa4169d8 | [
"MIT"
] | null | null | null | src/common/pfs.cpp | xackery/eqx | 777685a6f793014116855805d719899cfa4169d8 | [
"MIT"
] | null | null | null | #include "pfs.h"
#include "pfs_crc.h"
#include "compression.h"
#include <algorithm>
#include <cctype>
#include <cstring>
#include <tuple>
#include <errno.h>
#include "log_macros.h"
#define MAX_BLOCK_SIZE 8192 // the client will crash if you make this bigger, so don't.
#define ReadFromBuffer(type, var, buffer, idx) if(idx + sizeof(type) > buffer.size()) { return false; } type var = *(type*)&buffer[idx];
#define ReadFromBufferLength(var, len, buffer, idx) if(idx + len > buffer.size()) { return false; } memcpy(var, &buffer[idx], len);
#define WriteToBuffer(type, val, buffer, idx) if(idx + sizeof(type) > buffer.size()) { buffer.resize(idx + sizeof(type)); } *(type*)&buffer[idx] = val;
#define WriteToBufferLength(var, len, buffer, idx) if(idx + len > buffer.size()) { buffer.resize(idx + len); } memcpy(&buffer[idx], var, len);
bool EQEmu::PFS::Archive::Open() {
Close();
return true;
}
bool EQEmu::PFS::Archive::Open(uint32_t date) {
Close();
footer = true;
footer_date = date;
return true;
}
bool EQEmu::PFS::Archive::Open(std::string filename) {
Close();
std::vector<char> buffer;
FILE *f = fopen(filename.c_str(), "rb");
if (!f) {
eqLogMessage(LogError, "cannot open file '%s'", filename.c_str());
return false;
}
fseek(f, 0, SEEK_END);
size_t sz = ftell(f);
rewind(f);
buffer.resize(sz);
size_t res = fread(&buffer[0], 1, sz, f);
if (res != sz) {
eqLogMessage(LogError, "fread buffer failed, malformed file");
return false;
}
fclose(f);
char magic[4];
ReadFromBuffer(uint32_t, dir_offset, buffer, 0);
ReadFromBufferLength(magic, 4, buffer, 4);
if(magic[0] != 'P' || magic[1] != 'F' || magic[2] != 'S' || magic[3] != ' ') {
eqLogMessage(LogError, "magic word header mismatch");
return false;
}
ReadFromBuffer(uint32_t, dir_count, buffer, dir_offset);
std::vector<std::tuple<int32_t, uint32_t, uint32_t>> directory_entries;
std::vector<std::tuple<int32_t, std::string>> filename_entries;
for(uint32_t i = 0; i < dir_count; ++i) {
ReadFromBuffer(int32_t, crc, buffer, dir_offset + 4 + (i * 12));
ReadFromBuffer(uint32_t, offset, buffer, dir_offset + 8 + (i * 12));
ReadFromBuffer(uint32_t, size, buffer, dir_offset + 12 + (i * 12));
if (crc != 0x61580ac9) {
directory_entries.push_back(std::make_tuple(crc, offset, size));
continue;
}
std::vector<char> filename_buffer;
if(!InflateByFileOffset(offset, size, buffer, filename_buffer)) {
eqLogMessage(LogError, "inflate directory failed");
return false;
}
uint32_t filename_pos = 0;
ReadFromBuffer(uint32_t, filename_count, filename_buffer, filename_pos);
filename_pos += 4;
for(uint32_t j = 0; j < filename_count; ++j) {
ReadFromBuffer(uint32_t, filename_length, filename_buffer, filename_pos);
filename_pos += 4;
std::string filename;
filename.resize(filename_length - 1);
ReadFromBufferLength(&filename[0], filename_length, filename_buffer, filename_pos);
filename_pos += filename_length;
std::transform(filename.begin(), filename.end(), filename.begin(), ::tolower);
int32_t crc = EQEmu::PFS::CRC::Instance().Get(filename);
filename_entries.push_back(std::make_tuple(crc, filename));
}
}
auto iter = directory_entries.begin();
while(iter != directory_entries.end()) {
int32_t crc = std::get<0>((*iter));
auto f_iter = filename_entries.begin();
while(f_iter != filename_entries.end()) {
int32_t f_crc = std::get<0>((*f_iter));
if(crc == f_crc) {
uint32_t offset = std::get<1>((*iter));
uint32_t size = std::get<2>((*iter));
std::string filename = std::get<1>((*f_iter));
if (!StoreBlocksByFileOffset(offset, size, buffer, filename)) {
eqLogMessage(LogError, "store blocks by file offset failed");
return false;
}
break;
}
++f_iter;
}
++iter;
}
uint32_t footer_offset = dir_offset + 4 + (12 * dir_count);
if (footer_offset == buffer.size()) {
footer = false;
return true;
}
char footer_magic[5];
ReadFromBufferLength(footer_magic, 5, buffer, footer_offset);
ReadFromBuffer(uint32_t, date, buffer, footer_offset + 5);
footer = true;
footer_date = date;
return true;
}
bool EQEmu::PFS::Archive::Save(std::string filename) {
std::vector<char> buffer;
//Write Header
WriteToBuffer(uint32_t, 0, buffer, 0);
WriteToBuffer(uint8_t, 'P', buffer, 4);
WriteToBuffer(uint8_t, 'F', buffer, 5);
WriteToBuffer(uint8_t, 'S', buffer, 6);
WriteToBuffer(uint8_t, ' ', buffer, 7);
WriteToBuffer(uint32_t, 131072, buffer, 8);
std::vector<std::tuple<int32_t, uint32_t, uint32_t>> dir_entries;
std::vector<char> files_list;
uint32_t file_offset = 0;
uint32_t file_size = 0;
uint32_t dir_offset = 0;
uint32_t file_count = (uint32_t)files.size();
uint32_t file_pos = 0;
WriteToBuffer(uint32_t, file_count, files_list, file_pos);
file_pos += 4;
auto iter = files.begin();
while(iter != files.end()) {
int32_t crc = EQEmu::PFS::CRC::Instance().Get(iter->first);
uint32_t offset = (uint32_t)buffer.size();
uint32_t sz = files_uncompressed_size[iter->first];
buffer.insert(buffer.end(), iter->second.begin(), iter->second.end());
dir_entries.push_back(std::make_tuple(crc, offset, sz));
uint32_t filename_len = (uint32_t)iter->first.length() + 1;
WriteToBuffer(uint32_t, filename_len, files_list, file_pos);
file_pos += 4;
WriteToBufferLength(&(iter->first[0]), filename_len - 1, files_list, file_pos);
file_pos += filename_len;
WriteToBuffer(uint8_t, 0, files_list, file_pos - 1);
++iter;
}
file_offset = (uint32_t)buffer.size();
if (!WriteDeflatedFileBlock(files_list, buffer)) {
return false;
}
file_size = (uint32_t)files_list.size();
dir_offset = (uint32_t)buffer.size();
WriteToBuffer(uint32_t, dir_offset, buffer, 0);
uint32_t cur_dir_entry_offset = dir_offset;
uint32_t dir_count = (uint32_t)dir_entries.size() + 1;
WriteToBuffer(uint32_t, dir_count, buffer, cur_dir_entry_offset);
cur_dir_entry_offset += 4;
auto dir_iter = dir_entries.begin();
while(dir_iter != dir_entries.end())
{
int32_t crc = std::get<0>(*dir_iter);
uint32_t offset = std::get<1>(*dir_iter);
uint32_t size = std::get<2>(*dir_iter);
WriteToBuffer(int32_t, crc, buffer, cur_dir_entry_offset);
WriteToBuffer(uint32_t, offset, buffer, cur_dir_entry_offset + 4);
WriteToBuffer(uint32_t, size, buffer, cur_dir_entry_offset + 8);
cur_dir_entry_offset += 12;
++dir_iter;
}
WriteToBuffer(int32_t, 0x61580AC9, buffer, cur_dir_entry_offset);
WriteToBuffer(uint32_t, file_offset, buffer, cur_dir_entry_offset + 4);
WriteToBuffer(uint32_t, file_size, buffer, cur_dir_entry_offset + 8);
cur_dir_entry_offset += 12;
if(footer) {
WriteToBuffer(int8_t, 'S', buffer, cur_dir_entry_offset);
WriteToBuffer(int8_t, 'T', buffer, cur_dir_entry_offset + 1);
WriteToBuffer(int8_t, 'E', buffer, cur_dir_entry_offset + 2);
WriteToBuffer(int8_t, 'V', buffer, cur_dir_entry_offset + 3);
WriteToBuffer(int8_t, 'E', buffer, cur_dir_entry_offset + 4);
WriteToBuffer(uint32_t, footer_date, buffer, cur_dir_entry_offset + 5);
}
FILE *f = fopen(filename.c_str(), "wb");
if (!f) {
eqLogMessage(LogError, "cannot open file '%s': %s", filename.c_str(), strerror(errno));
return false;
}
size_t sz = fwrite(&buffer[0], buffer.size(), 1, f);
if(sz != 1) {
fclose(f);
return false;
}
fclose(f);
return true;
}
void EQEmu::PFS::Archive::Close() {
footer = false;
footer_date = 0;
files.clear();
files_uncompressed_size.clear();
}
bool EQEmu::PFS::Archive::Get(std::string filename, std::vector<char> &buf) {
std::transform(filename.begin(), filename.end(), filename.begin(), ::tolower);
auto iter = files.find(filename);
if(iter != files.end()) {
buf.clear();
uint32_t uc_size = files_uncompressed_size[filename];
if(!InflateByFileOffset(0, uc_size, iter->second, buf)) {
return false;
}
return true;
}
return false;
}
bool EQEmu::PFS::Archive::Set(std::string filename, const std::vector<char> &buf) {
std::transform(filename.begin(), filename.end(), filename.begin(), ::tolower);
std::vector<char> vec;
uint32_t uc_size = (uint32_t)buf.size();
if(!WriteDeflatedFileBlock(buf, vec)) {
return false;
}
files[filename] = vec;
files_uncompressed_size[filename] = uc_size;
return true;
}
bool EQEmu::PFS::Archive::Delete(std::string filename) {
std::transform(filename.begin(), filename.end(), filename.begin(), ::tolower);
files.erase(filename);
files_uncompressed_size.erase(filename);
return true;
}
bool EQEmu::PFS::Archive::Rename(std::string filename, std::string filename_new) {
std::transform(filename.begin(), filename.end(), filename.begin(), ::tolower);
std::transform(filename_new.begin(), filename_new.end(), filename_new.begin(), ::tolower);
if (files.count(filename_new) != 0) {
return false;
}
auto iter = files.find(filename);
if (iter != files.end()) {
files[filename_new] = iter->second;
files.erase(iter);
auto iter_s = files_uncompressed_size.find(filename);
files_uncompressed_size[filename_new] = iter_s->second;
files_uncompressed_size.erase(iter_s);
return true;
}
return false;
}
bool EQEmu::PFS::Archive::Exists(std::string filename) {
std::transform(filename.begin(), filename.end(), filename.begin(), ::tolower);
return files.count(filename) != 0;
}
bool EQEmu::PFS::Archive::GetFilenames(std::string ext, std::vector<std::string> &out_files) {
std::transform(ext.begin(), ext.end(), ext.begin(), ::tolower);
out_files.clear();
size_t elen = ext.length();
bool all_files = !ext.compare("*");
auto iter = files.begin();
while (iter != files.end()) {
if (all_files) {
out_files.push_back(iter->first);
++iter;
continue;
}
size_t flen = iter->first.length();
if (flen <= elen) {
++iter;
continue;
}
if (!strcmp(iter->first.c_str() + (flen - elen), ext.c_str())) {
out_files.push_back(iter->first);
}
++iter;
}
return out_files.size() > 0;
}
bool EQEmu::PFS::Archive::StoreBlocksByFileOffset(uint32_t offset, uint32_t size, const std::vector<char> &in_buffer, std::string filename) {
uint32_t position = offset;
uint32_t block_size = 0;
uint32_t inflate = 0;
while (inflate < size) {
ReadFromBuffer(uint32_t, deflate_length, in_buffer, position);
ReadFromBuffer(uint32_t, inflate_length, in_buffer, position + 4);
inflate += inflate_length;
position += deflate_length + 8;
}
block_size = position - offset;
std::vector<char> tbuffer;
tbuffer.resize(block_size);
memcpy(&tbuffer[0], &in_buffer[offset], block_size);
files[filename] = tbuffer;
files_uncompressed_size[filename] = size;
return true;
}
bool EQEmu::PFS::Archive::InflateByFileOffset(uint32_t offset, uint32_t size, const std::vector<char> &in_buffer, std::vector<char> &out_buffer) {
out_buffer.resize(size);
memset(&out_buffer[0], 0, size);
uint32_t position = offset;
uint32_t inflate = 0;
while (inflate < size) {
std::vector<char> temp_buffer;
ReadFromBuffer(uint32_t, deflate_length, in_buffer, position);
ReadFromBuffer(uint32_t, inflate_length, in_buffer, position + 4);
temp_buffer.resize(deflate_length + 1);
ReadFromBufferLength(&temp_buffer[0], deflate_length, in_buffer, position + 8);
EQEmu::InflateData(&temp_buffer[0], deflate_length, &out_buffer[inflate], inflate_length);
inflate += inflate_length;
position += deflate_length + 8;
}
return true;
}
bool EQEmu::PFS::Archive::WriteDeflatedFileBlock(const std::vector<char> &file, std::vector<char> &out_buffer) {
uint32_t pos = 0;
uint32_t remain = (uint32_t)file.size();
uint8_t block[MAX_BLOCK_SIZE + 128];
while(remain > 0) {
uint32_t sz;
if (remain >= MAX_BLOCK_SIZE) {
sz = MAX_BLOCK_SIZE;
remain -= MAX_BLOCK_SIZE;
} else {
sz = remain;
remain = 0;
}
uint32_t block_len = sz + 128;
uint32_t deflate_size = (uint32_t)EQEmu::DeflateData(&file[pos], sz, (char*)&block[0], block_len);
if(deflate_size == 0)
return false;
pos += sz;
uint32_t idx = (uint32_t)out_buffer.size();
WriteToBuffer(uint32_t, deflate_size, out_buffer, idx);
WriteToBuffer(uint32_t, sz, out_buffer, idx + 4);
out_buffer.insert(out_buffer.end(), block, block + deflate_size);
}
return true;
}
| 28.635294 | 153 | 0.694577 | xackery |
7bd77c37429090f62d3db356b42a313c37f22fee | 10,358 | cpp | C++ | third party/openRTMFP-Cumulus/CumulusLib/sources/RTMFPServer.cpp | Patrick-Bay/SocialCastr | 888a57ca63037e566f6c0bf03a646ae91b484086 | [
"MIT"
] | 5 | 2015-04-30T09:08:30.000Z | 2018-08-13T05:00:39.000Z | third party/openRTMFP-Cumulus/CumulusLib/sources/RTMFPServer.cpp | Patrick-Bay/SocialCastr | 888a57ca63037e566f6c0bf03a646ae91b484086 | [
"MIT"
] | null | null | null | third party/openRTMFP-Cumulus/CumulusLib/sources/RTMFPServer.cpp | Patrick-Bay/SocialCastr | 888a57ca63037e566f6c0bf03a646ae91b484086 | [
"MIT"
] | null | null | null | /*
Copyright 2010 OpenRTMFP
This program is free software: you can redistribute it and/or modify
it under the terms of the GNU General Public License as published by
the Free Software Foundation, either version 3 of the License, or
(at your option) any later version.
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 received along this program for more
details (or else see http://www.gnu.org/licenses/).
This file is a part of Cumulus.
*/
#include "RTMFPServer.h"
#include "RTMFP.h"
#include "Handshake.h"
#include "Middle.h"
#include "PacketWriter.h"
#include "Util.h"
#include "Logs.h"
#include "Poco/Format.h"
#include "string.h"
using namespace std;
using namespace Poco;
using namespace Poco::Net;
namespace Cumulus {
RTMFPServer::RTMFPServer() : Startable("RTMFPServer"),_pCirrus(NULL),_handshake(*this,_edgesSocket,*this,*this),_sessions(*this) {
#ifndef POCO_OS_FAMILY_WINDOWS
// static const char rnd_seed[] = "string to make the random number generator think it has entropy";
// RAND_seed(rnd_seed, sizeof(rnd_seed));
#endif
DEBUG("Id of this RTMFP server : %s",Util::FormatHex(id,ID_SIZE).c_str());
}
RTMFPServer::RTMFPServer(const string& name) : Startable(name),_pCirrus(NULL),_handshake(*this,_edgesSocket,*this,*this),_sessions(*this) {
#ifndef POCO_OS_FAMILY_WINDOWS
// static const char rnd_seed[] = "string to make the random number generator think it has entropy";
// RAND_seed(rnd_seed, sizeof(rnd_seed));
#endif
DEBUG("Id of this RTMFP server : %s",Util::FormatHex(id,ID_SIZE).c_str());
}
RTMFPServer::~RTMFPServer() {
stop();
}
Session* RTMFPServer::findSession(UInt32 id) {
// Id session can't be egal to 0 (it's reserved to Handshake)
if(id==0) {
DEBUG("Handshaking");
return &_handshake;
}
Session* pSession = _sessions.find(id);
if(pSession)
return pSession;
WARN("Unknown session %u",id);
return NULL;
}
void RTMFPServer::start() {
RTMFPServerParams params;
start(params);
}
void RTMFPServer::start(RTMFPServerParams& params) {
if(running()) {
ERROR("RTMFPServer server is yet running, call stop method before");
return;
}
_port = params.port;
if(_port==0) {
ERROR("RTMFPServer port must have a positive value");
return;
}
_edgesPort = params.edgesPort;
if(_port==_edgesPort) {
ERROR("RTMFPServer port must different than RTMFPServer edges.port");
return;
}
_freqManage = 2000000; // 2 sec by default
if(params.pCirrus) {
_pCirrus = new Target(*params.pCirrus);
_freqManage = 0; // no waiting, direct process in the middle case!
NOTE("RTMFPServer started in man-in-the-middle mode with server %s (unstable debug mode)",_pCirrus->address.toString().c_str());
}
_middle = params.middle;
if(_middle)
NOTE("RTMFPServer started in man-in-the-middle mode between peers (unstable debug mode)");
(UInt32&)udpBufferSize = params.udpBufferSize==0 ? _socket.getReceiveBufferSize() : params.udpBufferSize;
_socket.setReceiveBufferSize(udpBufferSize);_socket.setSendBufferSize(udpBufferSize);
_edgesSocket.setReceiveBufferSize(udpBufferSize);_edgesSocket.setSendBufferSize(udpBufferSize);
DEBUG("Socket buffer receving/sending size = %u/%u",udpBufferSize,udpBufferSize);
(UInt32&)keepAliveServer = params.keepAliveServer<5 ? 5000 : params.keepAliveServer*1000;
(UInt32&)keepAlivePeer = params.keepAlivePeer<5 ? 5000 : params.keepAlivePeer*1000;
(UInt8&)edgesAttemptsBeforeFallback = params.edgesAttemptsBeforeFallback;
setPriority(params.threadPriority);
Startable::start();
}
bool RTMFPServer::prerun() {
NOTE("RTMFP server starts on %u port",_port);
if(_edgesPort>0)
NOTE("RTMFP edges server starts on %u port",_edgesPort);
bool result=true;
try {
onStart();
result=Startable::prerun();
} catch(Exception& ex) {
FATAL("RTMFPServer : %s",ex.displayText().c_str());
} catch (exception& ex) {
FATAL("RTMFPServer : %s",ex.what());
} catch (...) {
FATAL("RTMFPServer unknown error");
}
onStop();
NOTE("RTMFP server stops");
return result;
}
void RTMFPServer::run(const volatile bool& terminate) {
SocketAddress address("0.0.0.0",_port);
_socket.bind(address,true);
SocketAddress edgesAddress("0.0.0.0",_edgesPort);
if(_edgesPort>0)
_edgesSocket.bind(edgesAddress,true);
SocketAddress sender;
UInt8 buff[PACKETRECV_SIZE];
int size = 0;
while(!terminate) {
bool stop=false;
bool idle = realTime(stop);
if(stop)
break;
_handshake.isEdges=false;
if(_socket.available()>0) {
try {
size = _socket.receiveFrom(buff,sizeof(buff),sender);
} catch(Exception& ex) {
DEBUG("Main socket reception : %s",ex.displayText().c_str());
_socket.close();
_socket.bind(address,true);
continue;
}
} else if(_edgesPort>0 && _edgesSocket.available()>0) {
try {
size = _edgesSocket.receiveFrom(buff,sizeof(buff),sender);
_handshake.isEdges=true;
} catch(Exception& ex) {
DEBUG("Main socket reception : %s",ex.displayText().c_str());
_edgesSocket.close();
_edgesSocket.bind(edgesAddress,true);
continue;
}
Edge* pEdge = edges(sender);
if(pEdge)
pEdge->update();
} else {
if(idle) {
Thread::sleep(1);
if(!_timeLastManage.isElapsed(_freqManage)) {
// Just middle session!
if(_middle) {
Sessions::Iterator it;
for(it=_sessions.begin();it!=_sessions.end();++it) {
Middle* pMiddle = dynamic_cast<Middle*>(it->second);
if(pMiddle)
pMiddle->manage();
}
}
} else {
_timeLastManage.update();
manage();
}
}
continue;
}
if(isBanned(sender.host())) {
INFO("Data rejected because client %s is banned",sender.host().toString().c_str());
continue;
}
if(size<RTMFP_MIN_PACKET_SIZE) {
ERROR("Invalid packet");
continue;
}
PacketReader packet(buff,size);
Session* pSession=findSession(RTMFP::Unpack(packet));
if(!pSession)
continue;
if(!pSession->checked)
_handshake.commitCookie(*pSession);
pSession->setEndPoint(_handshake.isEdges ? _edgesSocket : _socket,sender);
pSession->receive(packet);
}
_handshake.clear();
_sessions.clear();
_socket.close();
if(_edgesPort>0)
_edgesSocket.close();
if(_pCirrus) {
delete _pCirrus;
_pCirrus = NULL;
}
}
UInt8 RTMFPServer::p2pHandshake(const string& tag,PacketWriter& response,const SocketAddress& address,const UInt8* peerIdWanted) {
// find the flash client equivalence
Session* pSession = NULL;
Sessions::Iterator it;
for(it=_sessions.begin();it!=_sessions.end();++it) {
pSession = it->second;
if(Util::SameAddress(pSession->peer.address,address))
break;
}
if(it==_sessions.end())
pSession=NULL;
ServerSession* pSessionWanted = (ServerSession*)_sessions.find(peerIdWanted);
if(_pCirrus) {
// Just to make working the man in the middle mode !
if(!pSession) {
ERROR("UDP Hole punching error : middle equivalence not found for session wanted");
return 0;
}
PacketWriter& request = ((Middle*)pSession)->handshaker();
request.write8(0x22);request.write8(0x21);
request.write8(0x0F);
request.writeRaw(pSessionWanted ? ((Middle*)pSessionWanted)->middlePeer().id : peerIdWanted,ID_SIZE);
request.writeRaw(tag);
((Middle*)pSession)->sendHandshakeToTarget(0x30);
// no response here!
return 0;
}
if(!pSessionWanted) {
DEBUG("UDP Hole punching : session wanted not found, must be dead");
return 0;
} else if(pSessionWanted->failed()) {
DEBUG("UDP Hole punching : session wanted is deleting");
return 0;
}
UInt8 result = 0x00;
if(_middle) {
if(pSessionWanted->pTarget) {
HelloAttempt& attempt = _handshake.helloAttempt<HelloAttempt>(tag);
attempt.pTarget = pSessionWanted->pTarget;
_handshake.createCookie(response,attempt,tag,"");
response.writeRaw("\x81\x02\x1D\x02");
response.writeRaw(pSessionWanted->pTarget->publicKey,KEY_SIZE);
result = 0x70;
} else
ERROR("Peer/peer dumped exchange impossible : no corresponding 'Target' with the session wanted");
}
if(result==0x00) {
/// Udp hole punching normal process
pSessionWanted->p2pHandshake(address,tag,pSession);
bool first=true;
list<Address>::const_iterator it2;
for(it2=pSessionWanted->peer.addresses.begin();it2!=pSessionWanted->peer.addresses.end();++it2) {
const Address& addr = *it2;
if(addr == address) {
CRITIC("Two peers with the same %s address?",address.toString().c_str());
continue;
}
response.writeAddress(addr,first);
first=false;
}
result = 0x71;
}
return result;
}
Session& RTMFPServer::createSession(UInt32 farId,const Peer& peer,const UInt8* decryptKey,const UInt8* encryptKey,Cookie& cookie) {
Target* pTarget=_pCirrus;
if(_middle) {
if(!cookie.pTarget) {
cookie.pTarget = new Target(peer.address,&cookie);
memcpy((UInt8*)cookie.pTarget->peerId,peer.id,ID_SIZE);
memcpy((UInt8*)peer.id,cookie.pTarget->id,ID_SIZE);
NOTE("Mode 'man in the middle' : to connect to peer '%s' use the id :\n%s",Util::FormatHex(cookie.pTarget->peerId,ID_SIZE).c_str(),Util::FormatHex(cookie.pTarget->id,ID_SIZE).c_str());
} else
pTarget = cookie.pTarget;
}
ServerSession* pSession;
if(pTarget) {
pSession = new Middle(_sessions.nextId(),farId,peer,decryptKey,encryptKey,*this,_sessions,*pTarget);
if(_pCirrus==pTarget)
pSession->pTarget = cookie.pTarget;
DEBUG("500ms sleeping to wait cirrus handshaking");
Thread::sleep(500); // to wait the cirrus handshake
pSession->manage();
} else {
pSession = new ServerSession(_sessions.nextId(),farId,peer,decryptKey,encryptKey,*this);
pSession->pTarget = cookie.pTarget;
}
_sessions.add(pSession);
return *pSession;
}
void RTMFPServer::destroySession(Session& session) {
if(session.flags&SESSION_BY_EDGE) {
Edge* pEdge = edges(session.peer.address);
if(pEdge)
pEdge->removeSession(session);
}
}
void RTMFPServer::manage() {
_handshake.manage();
if(_sessions.manage())
displayCount(_sessions.count());
if(!_middle && !_pCirrus && _timeLastManage.isElapsed(20000))
WARN("Process management has lasted more than 20ms : %ums",UInt32(_timeLastManage.elapsed()/1000));
}
void RTMFPServer::displayCount(UInt32 sessions) {
INFO("%u clients",clients.count());
}
} // namespace Cumulus
| 28.070461 | 187 | 0.708728 | Patrick-Bay |
7be001f583ac88d094026d147a65c3162eb98336 | 948 | hpp | C++ | mpllibs/metamonad/v1/do_.hpp | sabel83/mpllibs | 8e245aedcf658fe77bb29537aeba1d4e1a619a19 | [
"BSL-1.0"
] | 70 | 2015-01-15T09:05:15.000Z | 2021-12-08T15:49:31.000Z | mpllibs/metamonad/v1/do_.hpp | sabel83/mpllibs | 8e245aedcf658fe77bb29537aeba1d4e1a619a19 | [
"BSL-1.0"
] | 4 | 2015-06-18T19:25:34.000Z | 2016-05-13T19:49:51.000Z | mpllibs/metamonad/v1/do_.hpp | sabel83/mpllibs | 8e245aedcf658fe77bb29537aeba1d4e1a619a19 | [
"BSL-1.0"
] | 5 | 2015-07-10T08:18:09.000Z | 2021-12-01T07:17:57.000Z | #ifndef MPLLIBS_METAMONAD_V1_DO__HPP
#define MPLLIBS_METAMONAD_V1_DO__HPP
// Copyright Abel Sinkovics ([email protected]) 2010.
// 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)
#include <mpllibs/metamonad/v1/fwd/do_.hpp>
#include <mpllibs/metamonad/v1/do_c.hpp>
namespace mpllibs
{
namespace metamonad
{
namespace v1
{
#ifdef MPLLIBS_DO_ARG
# error MPLLIBS_DO_ARG already defined
#endif
#define MPLLIBS_DO_ARG(z, n, unused) , syntax<BOOST_PP_CAT(E, n)>
template <
class Monad,
BOOST_PP_ENUM_PARAMS(MPLLIBS_LIMIT_DO_SIZE, class E)
>
struct
do_<Monad BOOST_PP_REPEAT(MPLLIBS_LIMIT_DO_SIZE, MPLLIBS_DO_ARG, ~)> :
do_c<Monad, BOOST_PP_ENUM_PARAMS(MPLLIBS_LIMIT_DO_SIZE, E)>
{};
#undef MPLLIBS_DO_ARG
}
}
}
#endif
| 24.307692 | 78 | 0.682489 | sabel83 |
7be17250bb5a5867e9d12b70e22cd0236963a20c | 944 | cpp | C++ | Duet Editor/Particle.cpp | mvandevander/duetgame | 6fd083d22b0eab9e7988e0ba46a6ec10757b7720 | [
"MIT"
] | 9 | 2016-03-18T23:59:24.000Z | 2022-02-09T01:09:56.000Z | Duet Editor/Particle.cpp | mvandevander/duetgame | 6fd083d22b0eab9e7988e0ba46a6ec10757b7720 | [
"MIT"
] | null | null | null | Duet Editor/Particle.cpp | mvandevander/duetgame | 6fd083d22b0eab9e7988e0ba46a6ec10757b7720 | [
"MIT"
] | null | null | null | #include "Particle.hpp"
#include <math.h>
Particle::Particle(float x, float y, float w, float h, float rot, int max_life, float xv, float yv, float xa, float ya, float rotv, float rota, float widthv, float widtha, float heightv, float heighta)
{
this->x = x;
this->y = y;
this->w = w;
this->h = h;
this->rot = rot;
this->max_life = max_life;
this->remaining_life = max_life+1;
this->xv = xv;
this->yv = yv;
this->xa = xa;
this->ya = ya;
this->rotv = rotv;
this->rota = rota;
this->widthv = widthv;
this->widtha = widtha;
this->heightv = heightv;
this->heighta = heighta;
}
void Particle::update()
{
xv+=(xa);
yv+=(ya);
rotv+=rota;
widthv+=widtha;
heightv+=heighta;
x+=xv;
y+=yv;
rot+=rotv;
w+=widthv;
h+=heightv;
remaining_life-=1;
if (remaining_life<=0) remaining_life = 0;
}
| 20.977778 | 202 | 0.551907 | mvandevander |
7be21384a3b260f692196cd770af695389efdf5b | 7,885 | cpp | C++ | lib/logic/factpp/data_range.cpp | GreyMerlin/owl_cpp | ccc6128dbd08dcf7fcbe6679ec6acd714732bbb6 | [
"BSL-1.0"
] | null | null | null | lib/logic/factpp/data_range.cpp | GreyMerlin/owl_cpp | ccc6128dbd08dcf7fcbe6679ec6acd714732bbb6 | [
"BSL-1.0"
] | null | null | null | lib/logic/factpp/data_range.cpp | GreyMerlin/owl_cpp | ccc6128dbd08dcf7fcbe6679ec6acd714732bbb6 | [
"BSL-1.0"
] | null | null | null | /** @file "/owlcpp/lib/logic/factpp/data_range.cpp"
part of owlcpp project.
@n @n Distributed under the Boost Software License, Version 1.0; see doc/license.txt.
@n Copyright Mikhail K Levin 2013
*******************************************************************************/
#include "data_range.hpp"
#include "data_instance.hpp"
#include "owlcpp/terms/node_tags_owl.hpp"
#include "owlcpp/terms/node_tags_system.hpp"
#include "owlcpp/rdf/triple_store.hpp"
#include "owlcpp/rdf/query_triples.hpp"
#include "factpp/Kernel.hpp"
namespace owlcpp{ namespace logic{ namespace factpp{
using namespace owlcpp::terms;
/*
*******************************************************************************/
Facet_restriction::Facet_restriction(
const Node_id facet,
Node_literal const& val,
Triple_store const& ts
)
: facet_(facet),
val_(new D_value(val, ts))
{
switch(facet_()) {
case xsd_maxExclusive::index:
case xsd_maxInclusive::index:
case xsd_minExclusive::index:
case xsd_minInclusive::index:
break;
default: BOOST_THROW_EXCEPTION(
Err()
<< Err::msg_t("unsupported facet")
<< Err::str1_t(to_string(facet, ts))
);
/* no break */
}
}
/*
*******************************************************************************/
Facet_restriction::generated_t Facet_restriction::get(ReasoningKernel& k ) const {
TExpressionManager& em = *k.getExpressionManager();
const TDLDataValue* val = val_->get(k);
switch(facet_()) {
case xsd_maxExclusive::index: return em.FacetMaxExclusive(val);
case xsd_maxInclusive::index: return em.FacetMaxInclusive(val);
case xsd_minExclusive::index: return em.FacetMinExclusive(val);
case xsd_minInclusive::index: return em.FacetMinInclusive(val);
default: BOOST_THROW_EXCEPTION( Err() << Err::msg_t("unsupported facet") );
/* no break */
}
}
/*
*******************************************************************************/
Dr_standard::Dr_standard(Expression_args const& ea, Triple_store const& ts)
: nid_(ea.handle)
{
switch( internal_type_id(nid_) ) {
case detail::Top_tid:
case detail::Bool_tid:
case detail::Int_tid:
case detail::Unsigned_tid:
case detail::Double_tid:
case detail::Time_tid:
case detail::String_tid:
break;
default: BOOST_THROW_EXCEPTION(
Err()
<< Err::msg_t("unknown standard datatype")
<< Err::str1_t(ea.string(ts))
);
/* no break */
}
}
/*
*******************************************************************************/
Dr_standard::generated_t Dr_standard::get(ReasoningKernel& k ) const {
TExpressionManager& em = *k.getExpressionManager();
switch( internal_type_id(nid_) ) {
case detail::Top_tid: return em.DataTop();
case detail::Bool_tid: return em.getBoolDataType();
case detail::Int_tid:
case detail::Unsigned_tid: return em.getIntDataType();
case detail::Double_tid: return em.getRealDataType();
case detail::Time_tid: return em.getTimeDataType();
case detail::String_tid:
default: return em.getStrDataType();
}
}
/*
*******************************************************************************/
Dt_restriction::Dt_restriction(
Expression_args const& ea, Triple_store const& ts
) : dt_(make_expression<Data_type>(ea.obj1, ts))
{
if(
ea.e_type != rdfs_Datatype::id() ||
ea.pred1 != owl_onDatatype::id() ||
ea.pred2 != owl_withRestrictions::id()
) {
char const* msg =
"_:x rdf:type rdfs:Datatype; "
"_:x owl:onDatatype *:y; "
"_:x owl:withRestrictions "
"is expected";
BOOST_THROW_EXCEPTION(
Err()
<< Err::msg_t(msg)
<< Err::str1_t(ea.string(ts))
);
}
BOOST_FOREACH(Node_id const nid, rdf_list(ea.obj2, ts)) {
facets_.push_back(make_expression<Data_facet>(nid, ts));
}
if( facets_.empty() ) BOOST_THROW_EXCEPTION(
Err()
<< Err::msg_t("no facets in datatype restriction")
);
}
/*
*******************************************************************************/
Dt_restriction::generated_t Dt_restriction::get(ReasoningKernel& k ) const {
BOOST_ASSERT( ! facets_.empty() );
TExpressionManager& em = *k.getExpressionManager();
Expression<Data_type>::generated_t e = dt_->get(k);
for(std::size_t n = 0; n != facets_.size(); ++n) {
e = em.RestrictedType(e, facets_[n].get(k));
}
return e;
}
/*
*******************************************************************************/
Dt_junction::Dt_junction(Expression_args const& ea, Triple_store const& ts)
: nid_(ea.pred1)
{
if( ea.e_type != rdfs_Datatype::id() ) BOOST_THROW_EXCEPTION(
Err()
<< Err::msg_t("rdf:type rdfs:Datatype is expected")
<< Err::str1_t(ea.string(ts))
);
switch(nid_()) {
case owl_intersectionOf::index:
case owl_unionOf::index:
break;
default: BOOST_THROW_EXCEPTION(
Err()
<< Err::msg_t("owl:intersectionOf or owl:unionOf is expected")
<< Err::str1_t(to_string(nid_, ts))
);
/* no break */
}
BOOST_FOREACH(Node_id const nid, rdf_list(ea.obj1, ts)) {
l_.push_back(make_expression<Data_range>(nid, ts));
}
if( l_.size() < 2 ) BOOST_THROW_EXCEPTION(
Err()
<< Err::msg_t("at least 2 data ranges should be provided")
);
}
/*
*******************************************************************************/
Dt_junction::generated_t Dt_junction::get(ReasoningKernel& k ) const {
BOOST_ASSERT(nid_ == owl_intersectionOf::id() || nid_ == owl_unionOf::id() );
BOOST_ASSERT( l_.size() >= 2U );
TExpressionManager& em = *k.getExpressionManager();
em.newArgList();
for(std::size_t n = 0; n != l_.size(); ++n) em.addArg(l_[n].get(k));
switch(nid_()) {
case owl_intersectionOf::index: return em.DataAnd();
case owl_unionOf::index: return em.DataOr();
break;
default: BOOST_THROW_EXCEPTION(
Err()
<< Err::msg_t("owl:intersectionOf or owl:unionOf is expected")
);
/* no break */
}
}
/*
*******************************************************************************/
Dt_oneof::Dt_oneof(Expression_args const& ea, Triple_store const& ts) {
if( ea.e_type != rdfs_Datatype::id() ) BOOST_THROW_EXCEPTION(
Err()
<< Err::msg_t("rdf:type rdfs:Datatype is expected")
<< Err::str1_t(ea.string(ts))
);
BOOST_FOREACH(Node_id const nid, rdf_list(ea.obj1, ts)) {
l_.push_back(make_expression<Data_inst>(nid, ts));
}
if( l_.empty() ) BOOST_THROW_EXCEPTION(
Err()
<< Err::msg_t("at least 1 data value should be provided")
);
}
/*
*******************************************************************************/
Dt_oneof::generated_t Dt_oneof::get(ReasoningKernel& k ) const {
BOOST_ASSERT( ! l_.empty() );
TExpressionManager& em = *k.getExpressionManager();
em.newArgList();
for(std::size_t n = 0; n != l_.size(); ++n) em.addArg(l_[n].get(k));
return em.DataOneOf();
}
/*
*******************************************************************************/
Dt_complement::Dt_complement(Expression_args const& ea, Triple_store const& ts)
: de_(make_expression<Data_range>(ea.obj1, ts))
{
if( ea.e_type != rdfs_Datatype::id() ) BOOST_THROW_EXCEPTION(
Err()
<< Err::msg_t("rdf:type rdfs:Datatype is expected")
<< Err::str1_t(ea.string(ts))
);
}
/*
*******************************************************************************/
Dt_complement::generated_t Dt_complement::get(ReasoningKernel& k ) const {
TExpressionManager& em = *k.getExpressionManager();
return em.DataNot(de_->get(k));
}
}//namespace factpp
}//namespace logic
}//namespace owlcpp
| 32.582645 | 85 | 0.554344 | GreyMerlin |
7be24e7ed66ad99bc669d42a4ad779741098c477 | 24 | cpp | C++ | src/grape/tensor.cpp | sunnythree/JaverNN | 8c5dc803ac3e49b569a89118fcaf5d4ca6ec673b | [
"BSD-2-Clause"
] | 19 | 2019-11-09T08:51:21.000Z | 2022-03-25T07:55:45.000Z | src/grape/tensor.cpp | sunnythree/JaverNN | 8c5dc803ac3e49b569a89118fcaf5d4ca6ec673b | [
"BSD-2-Clause"
] | null | null | null | src/grape/tensor.cpp | sunnythree/JaverNN | 8c5dc803ac3e49b569a89118fcaf5d4ca6ec673b | [
"BSD-2-Clause"
] | 7 | 2019-11-19T14:20:43.000Z | 2022-03-25T18:36:34.000Z |
namespace Grape{
}
| 3 | 16 | 0.583333 | sunnythree |
7be6cda482acbf4120e764d2e5b3621154112962 | 1,390 | cpp | C++ | src/cpp/226. Invert Binary Tree.cpp | yjjnls/D.S.A-Leet | be19c3ccc1f704e75590786fdfd4cd3ab4818d4f | [
"MIT"
] | 222 | 2018-09-25T08:46:31.000Z | 2022-02-07T12:33:42.000Z | src/cpp/226. Invert Binary Tree.cpp | yjjnls/D.S.A-Leet | be19c3ccc1f704e75590786fdfd4cd3ab4818d4f | [
"MIT"
] | 1 | 2017-11-23T04:39:48.000Z | 2017-11-23T04:39:48.000Z | src/cpp/226. Invert Binary Tree.cpp | yjjnls/D.S.A-Leet | be19c3ccc1f704e75590786fdfd4cd3ab4818d4f | [
"MIT"
] | 12 | 2018-10-05T03:16:05.000Z | 2020-12-19T04:25:33.000Z | /*
Invert a binary tree.
4
/ \
2 7
/ \ / \
1 3 6 9
to
4
/ \
7 2
/ \ / \
9 6 3 1
Trivia:
This problem was inspired by this original tweet by Max Howell:
Google: 90% of our engineers use the software you wrote (Homebrew), but you can’t invert a binary tree on a whiteboard so fuck off.
*/
/**
* Definition for a binary tree node.
* struct TreeNode {
* int val;
* TreeNode *left;
* TreeNode *right;
* TreeNode(int x) : val(x), left(NULL), right(NULL) {}
* };
*/
#include <common.hpp>
class Solution1
{
public:
TreeNode *invertTree(TreeNode *root)
{
//recursion terminator
//current level processing
//drill down
if (root == NULL)
{
return NULL;
}
std::swap(root->left, root->right);
invertTree(root->left);
invertTree(root->right);
return root;
}
};
//solution 2 no-recursion
class Solution2
{
public:
TreeNode *invertTree(TreeNode *root)
{
std::stack<TreeNode *> stk;
stk.push(root);
while (!stk.empty())
{
TreeNode *p = stk.top();
stk.pop();
if (p)
{
stk.push(p->left);
stk.push(p->right);
std::swap(p->left, p->right);
}
}
return root;
}
}; | 18.533333 | 131 | 0.5 | yjjnls |
7be6ea2e235a3c7e1f21663f18f5768eefa94172 | 1,936 | cpp | C++ | Source/FactoryGame/Buildables/FGBuildableTradingPost.cpp | iam-Legend/Project-Assembly | 1ff3587704232d5e330515bc0d2aceb64ff09a7f | [
"MIT"
] | null | null | null | Source/FactoryGame/Buildables/FGBuildableTradingPost.cpp | iam-Legend/Project-Assembly | 1ff3587704232d5e330515bc0d2aceb64ff09a7f | [
"MIT"
] | null | null | null | Source/FactoryGame/Buildables/FGBuildableTradingPost.cpp | iam-Legend/Project-Assembly | 1ff3587704232d5e330515bc0d2aceb64ff09a7f | [
"MIT"
] | null | null | null | // This file has been automatically generated by the Unreal Header Implementation tool
#include "FGBuildableTradingPost.h"
AFGBuildableTradingPost::AFGBuildableTradingPost(){ }
void AFGBuildableTradingPost::GetLifetimeReplicatedProps( TArray<FLifetimeProperty>& OutLifetimeProps) const{ }
void AFGBuildableTradingPost::BeginPlay(){ }
void AFGBuildableTradingPost::GetDismantleRefundReturns( TArray< FInventoryStack >& out_returns) const{ }
void AFGBuildableTradingPost::Dismantle_Implementation(){ }
void AFGBuildableTradingPost::GetDismantleRefund_Implementation( TArray< FInventoryStack >& out_refund) const{ }
void AFGBuildableTradingPost::StartIsLookedAtForDismantle_Implementation( AFGCharacterPlayer* byCharacter){ }
void AFGBuildableTradingPost::StopIsLookedAtForDismantle_Implementation( AFGCharacterPlayer* byCharacter){ }
void AFGBuildableTradingPost::OnTradingPostUpgraded_Implementation( int32 level, bool suppressBuildEffects ){ }
void AFGBuildableTradingPost::UpdateGeneratorVisibility(){ }
void AFGBuildableTradingPost::UpdateStorageVisibility(){ }
void AFGBuildableTradingPost::UpdateMAMVisibility(){ }
int32 AFGBuildableTradingPost::GetTradingPostLevel() const{ return int32(); }
void AFGBuildableTradingPost::PlayBuildEffects( AActor* inInstigator){ }
void AFGBuildableTradingPost::ExecutePlayBuildEffects(){ }
void AFGBuildableTradingPost::PlayBuildEffectsOnAllClients(AActor* instigator ){ }
bool AFGBuildableTradingPost::AreChildBuildingsLoaded(){ return bool(); }
void AFGBuildableTradingPost::OnBuildEffectFinished(){ }
void AFGBuildableTradingPost::TogglePendingDismantleMaterial( bool enabled){ }
void AFGBuildableTradingPost::AdjustPlayerSpawnsToGround(){ }
AFGSchematicManager* AFGBuildableTradingPost::GetSchematicManager(){ return nullptr; }
TArray<AActor*> AFGBuildableTradingPost::GetAllActiveSubBuildings(){ return TArray<AActor*>(); }
void AFGBuildableTradingPost::OnRep_NeedPlayingBuildEffect(){ }
| 69.142857 | 112 | 0.845558 | iam-Legend |
7be76930a2d6cbc28e5a47e0443d13cee4afb2a2 | 1,219 | cpp | C++ | EntityComponentSystem/PbrRenderer/Material.cpp | Spheya/Slamanander-Engine | d0708399eacab26b243045b33b51ff30d614b7bd | [
"MIT"
] | null | null | null | EntityComponentSystem/PbrRenderer/Material.cpp | Spheya/Slamanander-Engine | d0708399eacab26b243045b33b51ff30d614b7bd | [
"MIT"
] | null | null | null | EntityComponentSystem/PbrRenderer/Material.cpp | Spheya/Slamanander-Engine | d0708399eacab26b243045b33b51ff30d614b7bd | [
"MIT"
] | null | null | null | #include "Material.hpp"
renderer::MaterialTexture::MaterialTexture(const Texture* texture) :
_texture(texture)
{}
renderer::MaterialTexture::MaterialTexture(float value) :
_textureOwner(true)
{
auto tex = new Texture();
const uint8_t byteVal = uint8_t(value * 255.0f);
tex->loadFromMemory(&byteVal, 1, 1, 1);
_texture = tex;
}
renderer::MaterialTexture::MaterialTexture(const glm::vec3& value) {
auto tex = new Texture();
const uint8_t byteVal[] = { uint8_t(value.x * 255.0f), uint8_t(value.y * 255.0f), uint8_t(value.z * 255.0f) };
tex->loadFromMemory(&byteVal[0], 3, 1, 1);
_texture = tex;
}
renderer::MaterialTexture::MaterialTexture(MaterialTexture&& other) :
_texture(other._texture),
_textureOwner(other._textureOwner)
{
other._texture = nullptr;
other._textureOwner = false;
}
renderer::MaterialTexture& renderer::MaterialTexture::operator=(MaterialTexture&& other) {
_texture = other._texture;
_textureOwner = other._textureOwner;
other._texture = nullptr;
other._textureOwner = false;
return *this;
}
renderer::MaterialTexture::~MaterialTexture() {
if (_textureOwner)
delete _texture;
}
const renderer::Texture* renderer::MaterialTexture::getTexture() const {
return _texture;
}
| 25.395833 | 111 | 0.73913 | Spheya |
7be7e3a9791d159ff8ed1d8d403e49dc34097259 | 4,029 | cc | C++ | cc/test-settings-v1.cc | acorg/acmacs-base | a1a6e5b346ea3746f3fc1750ed4b7f29c7c0d049 | [
"MIT"
] | null | null | null | cc/test-settings-v1.cc | acorg/acmacs-base | a1a6e5b346ea3746f3fc1750ed4b7f29c7c0d049 | [
"MIT"
] | null | null | null | cc/test-settings-v1.cc | acorg/acmacs-base | a1a6e5b346ea3746f3fc1750ed4b7f29c7c0d049 | [
"MIT"
] | null | null | null | #include <iostream>
#include "acmacs-base/settings-v1.hh"
// ----------------------------------------------------------------------
struct AAAtPos : public acmacs::settings::v1::object
{
acmacs::settings::v1::field<size_t> diverse_index_threshold{this, "diverse_index_threshold", 3};
acmacs::settings::v1::field<double> line_length{this, "line_length", 0.5};
acmacs::settings::v1::field<bool> report_most_diverse_positions{this, "report_most_diverse_positions", false};
acmacs::settings::v1::field<std::string> comment{this, "comment"};
using acmacs::settings::v1::object::object;
};
struct Mod : public acmacs::settings::v1::object
{
acmacs::settings::v1::field<std::string> name{this, "N"};
acmacs::settings::v1::field<double> d1{this, "d1", 1.0/8.0};
using acmacs::settings::v1::object::object;
};
struct Settings : public acmacs::settings::v1::toplevel
{
acmacs::settings::v1::field<std::string> version{this, " version", "signature-page-settings-v4"};
acmacs::settings::v1::field_object<AAAtPos> aa_at_pos{this, "aa_at_pos"};
acmacs::settings::v1::field_array<double> viewport{this, "viewport", {0.125, 0.25, 122}};
acmacs::settings::v1::field_array_of<Mod> mods{this, "mods"};
acmacs::settings::v1::field<acmacs::Size> size{this, "size", {7, 8}};
acmacs::settings::v1::field<acmacs::Offset> offset{this, "offset", {-1, 111}};
acmacs::settings::v1::field<Color> fill{this, "fill", "cornflowerblue"};
acmacs::settings::v1::field<acmacs::TextStyle> text_style{this, "text_style", "monospace"};
};
// ----------------------------------------------------------------------
int main()
{
int exit_code = 0;
try {
Settings s1;
s1.inject_default();
std::cout << s1.pretty() << '\n';
std::cout << "report_most_diverse_positions: " << s1.aa_at_pos->report_most_diverse_positions << '\n';
s1.aa_at_pos->report_most_diverse_positions = true;
std::cout << "report_most_diverse_positions: " << s1.aa_at_pos->report_most_diverse_positions << '\n';
std::cout << "line_length: " << s1.aa_at_pos->line_length << '\n';
s1.aa_at_pos->line_length = 1.2;
std::cout << "line_length: " << s1.aa_at_pos->line_length << '\n';
std::cout << "size: " << acmacs::to_string(s1.size) << '\n';
s1.size = acmacs::Size{9, 10};
std::cout << "size: " << acmacs::to_string(s1.size) << '\n';
std::cout << "offset: " << s1.offset << '\n';
s1.offset = acmacs::Offset{12, -13.5};
std::cout << "offset: " << s1.offset << '\n';
std::cout << fmt::format("fill: \"{}\"\n", *s1.fill);
s1.fill = Color("#123456");
std::cout << fmt::format("fill: \"{}\"\n", *s1.fill);
std::cout << "text_style: " << s1.text_style << '\n';
s1.text_style = acmacs::TextStyle("serif");
std::cout << "text_style: " << s1.text_style << '\n';
std::cout << "aa_at_pos: " << s1.aa_at_pos << '\n';
std::cout << "viewport: " << s1.viewport << '\n';
s1.viewport.append(s1.viewport[2]);
std::cout << "viewport: " << s1.viewport << '\n';
std::cout << '\n';
auto mod1 = s1.mods.append();
mod1->name = "first";
std::cout << "mod1->name: " << *mod1->name << '\n';
s1.mods.append()->name = "second";
std::cout << s1.pretty() << '\n';
if (auto found = s1.mods.find_if([](const Mod& mod) { AD_DEBUG("mod.name {}", *mod.name); return mod.name == "second"; }); found)
std::cout << "found: " << *found << '\n';
else
std::cout << "mod \"second\" not found!\n";
}
catch (std::exception& err) {
std::cerr << "ERROR: " << err.what() << '\n';
exit_code = 1;
}
return exit_code;
}
// ----------------------------------------------------------------------
/// Local Variables:
/// eval: (if (fboundp 'eu-rename-buffer) (eu-rename-buffer))
/// End:
| 41.96875 | 137 | 0.542318 | acorg |
7beb2cb601e9c1c7329936e53f4a86066dfeea24 | 8,301 | cpp | C++ | src/solver/LevMarqGaussNewtonSolver.cpp | neophack/steam | 28f0637e3ae4ff2c21ad12b2331c535e9873c997 | [
"BSD-3-Clause"
] | null | null | null | src/solver/LevMarqGaussNewtonSolver.cpp | neophack/steam | 28f0637e3ae4ff2c21ad12b2331c535e9873c997 | [
"BSD-3-Clause"
] | null | null | null | src/solver/LevMarqGaussNewtonSolver.cpp | neophack/steam | 28f0637e3ae4ff2c21ad12b2331c535e9873c997 | [
"BSD-3-Clause"
] | null | null | null | //////////////////////////////////////////////////////////////////////////////////////////////
/// \file LevMarqGaussNewtonSolver.cpp
///
/// \author Sean Anderson, ASRL
//////////////////////////////////////////////////////////////////////////////////////////////
#include <steam/solver/LevMarqGaussNewtonSolver.hpp>
#include <iostream>
#include <steam/common/Timer.hpp>
namespace steam {
//////////////////////////////////////////////////////////////////////////////////////////////
/// \brief Constructor
//////////////////////////////////////////////////////////////////////////////////////////////
LevMarqGaussNewtonSolver::LevMarqGaussNewtonSolver(OptimizationProblem* problem, const Params& params)
: GaussNewtonSolverBase(problem), params_(params) {
// a small diagonal coefficient means that it is closer to using just a gauss newton step
diagCoeff = 1e-7;
}
//////////////////////////////////////////////////////////////////////////////////////////////
/// \brief Solve the Levenberg–Marquardt system of equations:
/// A*x = b, A = (J^T*J + diagonalCoeff*diag(J^T*J))
//////////////////////////////////////////////////////////////////////////////////////////////
Eigen::VectorXd LevMarqGaussNewtonSolver::solveLevMarq(const Eigen::VectorXd& gradientVector,
double diagonalCoeff) {
// Augment diagonal of the 'hessian' matrix
for (int i = 0; i < approximateHessian_.outerSize(); i++) {
approximateHessian_.coeffRef(i,i) *= (1.0 + diagonalCoeff);
}
// Solve system
Eigen::VectorXd levMarqStep;
try {
// Solve for the LM step using the Cholesky factorization (fast)
levMarqStep = this->solveGaussNewton(approximateHessian_, gradientVector, true);
} catch (const decomp_failure& ex) {
// Revert diagonal of the 'hessian' matrix
for (int i = 0; i < approximateHessian_.outerSize(); i++) {
approximateHessian_.coeffRef(i,i) /= (1.0 + diagonalCoeff);
}
// Throw up again
throw ex;
}
// Revert diagonal of the 'hessian' matrix
for (int i = 0; i < approximateHessian_.outerSize(); i++) {
approximateHessian_.coeffRef(i,i) /= (1.0 + diagonalCoeff);
}
return levMarqStep;
}
//////////////////////////////////////////////////////////////////////////////////////////////
/// \brief Perform a plain LLT decomposition on the approx. Hessian matrix in
/// order to solve for the proper covariances (unmodified by the LM diagonal)
//////////////////////////////////////////////////////////////////////////////////////////////
void LevMarqGaussNewtonSolver::solveCovariances() {
// Factorize the unaugmented hessian (the covariance matrix)
this->factorizeHessian(approximateHessian_, false);
}
//////////////////////////////////////////////////////////////////////////////////////////////
/// \brief Build the system, solve for a step size and direction, and update the state
//////////////////////////////////////////////////////////////////////////////////////////////
bool LevMarqGaussNewtonSolver::linearizeSolveAndUpdate(double* newCost, double* gradNorm) {
if (newCost == NULL) {
throw std::invalid_argument("Null pointer provided to return-input "
"'newCost' in linearizeSolveAndUpdate");
}
// Logging variables
steam::Timer iterTimer;
steam::Timer timer;
double buildTime = 0;
double solveTime = 0;
double updateTime = 0;
double actualToPredictedRatio = 0;
unsigned int numTrDecreases = 0;
// Initialize new cost with old cost incase of failure
*newCost = this->getPrevCost();
// The 'right-hand-side' of the Gauss-Newton problem, generally known as the gradient vector
Eigen::VectorXd gradientVector;
// Construct system of equations
timer.reset();
this->buildGaussNewtonTerms(&approximateHessian_, &gradientVector);
*gradNorm = gradientVector.norm();
buildTime = timer.milliseconds();
// Perform LM Search
unsigned int nBacktrack = 0;
for (; nBacktrack < params_.maxShrinkSteps; nBacktrack++) {
// Solve system
timer.reset();
bool decompSuccess = true;
Eigen::VectorXd levMarqStep;
try {
// Solve system
levMarqStep = this->solveLevMarq(gradientVector, diagCoeff);
} catch (const decomp_failure& e) {
decompSuccess = false;
}
solveTime += timer.milliseconds();
// Test new cost
timer.reset();
// If decomposition was successful, calculate step quality
double proposedCost = 0;
if (decompSuccess) {
// Calculate the predicted reduction; note that a positive value denotes a reduction in cost
proposedCost = this->proposeUpdate(levMarqStep);
double actualReduc = this->getPrevCost() - proposedCost;
double predictedReduc = this->predictedReduction(approximateHessian_, gradientVector, levMarqStep);
actualToPredictedRatio = actualReduc/predictedReduc;
}
// Check ratio of predicted reduction to actual reduction achieved
if (actualToPredictedRatio > params_.ratioThreshold && decompSuccess) {
// Good enough ratio to accept proposed state
this->acceptProposedState();
*newCost = proposedCost;
diagCoeff = std::max(diagCoeff*params_.shrinkCoeff, 1e-7); // move towards gauss newton
// Timing
updateTime += timer.milliseconds();
break;
} else {
// Cost did not reduce enough, possibly increased, or decomposition failed.
// Reject proposed state and reduce the size of the trust region
if (decompSuccess) {
// Restore old state vector
this->rejectProposedState();
}
diagCoeff = std::min(diagCoeff*params_.growCoeff, 1e7); // Move towards gradient descent
numTrDecreases++; // Count number of shrinks for logging
// Timing
updateTime += timer.milliseconds();
}
}
// Print report line if verbose option enabled
if (params_.verbose) {
if (this->getCurrIteration() == 1) {
std::cout << std::right << std::setw( 4) << std::setfill(' ') << "iter"
<< std::right << std::setw(12) << std::setfill(' ') << "cost"
<< std::right << std::setw(12) << std::setfill(' ') << "build (ms)"
<< std::right << std::setw(12) << std::setfill(' ') << "solve (ms)"
<< std::right << std::setw(13) << std::setfill(' ') << "update (ms)"
<< std::right << std::setw(11) << std::setfill(' ') << "time (ms)"
<< std::right << std::setw(11) << std::setfill(' ') << "TR shrink"
<< std::right << std::setw(11) << std::setfill(' ') << "AvP Ratio"
<< std::endl;
}
std::cout << std::right << std::setw(4) << std::setfill(' ') << this->getCurrIteration()
<< std::right << std::setw(12) << std::setfill(' ') << std::setprecision(5) << *newCost
<< std::right << std::setw(12) << std::setfill(' ') << std::setprecision(3) << std::fixed << buildTime << std::resetiosflags(std::ios::fixed)
<< std::right << std::setw(12) << std::setfill(' ') << std::setprecision(3) << std::fixed << solveTime << std::resetiosflags(std::ios::fixed)
<< std::right << std::setw(13) << std::setfill(' ') << std::setprecision(3) << std::fixed << updateTime << std::resetiosflags(std::ios::fixed)
<< std::right << std::setw(11) << std::setfill(' ') << std::setprecision(3) << std::fixed << iterTimer.milliseconds() << std::resetiosflags(std::ios::fixed)
<< std::right << std::setw(11) << std::setfill(' ') << numTrDecreases
<< std::right << std::setw(11) << std::setfill(' ') << std::setprecision(3) << std::fixed << actualToPredictedRatio << std::resetiosflags(std::ios::fixed)
<< std::endl;
}
// Return successfulness
if (nBacktrack < params_.maxShrinkSteps) {
return true;
} else {
return false;
}
}
//////////////////////////////////////////////////////////////////////////////////////////////
/// \brief Casts parameters to base type (for SolverBase class)
//////////////////////////////////////////////////////////////////////////////////////////////
const SolverBase::Params& LevMarqGaussNewtonSolver::getSolverBaseParams() const {
return params_;
}
} // steam
| 40.691176 | 170 | 0.54909 | neophack |
7bf07c22a67edd7d4b8d6b643289a500931acee5 | 1,963 | hpp | C++ | include/xul/lua/io/lua_message_packet_pipe.hpp | hindsights/xul | 666ce90742a9919d538ad5c8aad618737171e93b | [
"MIT"
] | 2 | 2018-03-16T07:06:48.000Z | 2018-04-02T03:02:14.000Z | include/xul/lua/io/lua_message_packet_pipe.hpp | hindsights/xul | 666ce90742a9919d538ad5c8aad618737171e93b | [
"MIT"
] | null | null | null | include/xul/lua/io/lua_message_packet_pipe.hpp | hindsights/xul | 666ce90742a9919d538ad5c8aad618737171e93b | [
"MIT"
] | 1 | 2019-08-12T05:15:29.000Z | 2019-08-12T05:15:29.000Z | #pragma once
#include <xul/io/codec/message_packet_pipe.hpp>
#include <xul/lua/lua_utility.hpp>
#include <xul/log/log.hpp>
namespace xul {
class lua_message_packet_pipe
{
public:
static const luaL_Reg* get_methods()
{
static const luaL_Reg url_request_functions[] =
{
{ "new", &lua_message_packet_pipe::create },
{ "feed", &lua_message_packet_pipe::feed },
{ "read", &lua_message_packet_pipe::read },
{ NULL, NULL },
};
return url_request_functions;
}
static void register_class(lua_State* L)
{
lua_utility::register_object_class(L, "xul.message_pipe", get_methods());
}
static int create(lua_State* L)
{
bool isBigEndian;
if (!lua_utility::try_get_bool(L, 1, &isBigEndian))
return -1;
int maxsize;
message_packet_pipe * pipe;
if (!lua_utility::try_get_integer(L, 2, &maxsize))
pipe = new message_packet_pipe(isBigEndian);
else
pipe = new message_packet_pipe(isBigEndian, maxsize);
lua_utility::register_object(L, pipe, "xul.message_pipe");
return 1;
}
static int feed(lua_State* L)
{
message_packet_pipe* self = lua_utility::get_object<message_packet_pipe>(L, 1);
const uint8_t* data = static_cast<const uint8_t*>(lua_utility::get_userdata(L, 2, NULL));
int size = lua_utility::get_integer(L, 3, -1);
if(size < 0)
assert(false);
self->feed(data, size);
return 0;
}
static int read(lua_State* L)
{
message_packet_pipe* self = lua_utility::get_object<message_packet_pipe>(L, 1);
int size = lua_utility::get_integer(L, 2, -1);
const uint8_t* data = self->read(&size);
//std::string str;
//str.assign(size, data);
//lua_pushstring(L,str);
//const char *testdata = reinterpret_cast<const char*>(data);
lua_pushlstring(L, reinterpret_cast<const char*>(data), size);
//lua_pushlightuserdata(L, const_cast<uint8_t*>(data));
lua_pushnumber(L, size);
return 2;
}
};
}
| 26.527027 | 91 | 0.669384 | hindsights |
7bf1e848e0abb491cc33d48d9f674e40421a4bb1 | 1,303 | cpp | C++ | DesignPattern/Creational/Builder/Builder.cpp | lostcoder0812/DesignPattern | c2ddee1ad7f4996ce6cb101a994ebaa192b7d3ce | [
"MIT"
] | null | null | null | DesignPattern/Creational/Builder/Builder.cpp | lostcoder0812/DesignPattern | c2ddee1ad7f4996ce6cb101a994ebaa192b7d3ce | [
"MIT"
] | null | null | null | DesignPattern/Creational/Builder/Builder.cpp | lostcoder0812/DesignPattern | c2ddee1ad7f4996ce6cb101a994ebaa192b7d3ce | [
"MIT"
] | null | null | null | #include "Builder.h"
#include <iostream>
using namespace std;
Product::Product()
{
ProducePart();
cout<<"return a product"<<endl;
}
Product::~Product()
{
}
void Product::ProducePart()
{
cout<<"build part of product.."<<endl;
}
ProductPart::ProductPart()
{
//cout<<"build productpart.."<<endl;
}
ProductPart::~ProductPart()
{
}
ProductPart* ProductPart::BuildPart()
{
return new ProductPart;
}
Builder::Builder()
{
}
Builder::~Builder()
{
}
ConcreteBuilder::ConcreteBuilder()
{
}
ConcreteBuilder::~ConcreteBuilder()
{
}
void ConcreteBuilder::BuildPartA(const string& buildPara)
{
cout<<"Step1:Build PartA..." << buildPara<<endl;
}
void ConcreteBuilder::BuildPartB(const string& buildPara)
{
cout<<"Step1:Build PartB..."<<buildPara<<endl;
}
void ConcreteBuilder::BuildPartC(const string& buildPara)
{
cout<<"Step1:Build PartC..."<<buildPara<<endl;
}
Product* ConcreteBuilder::GetProduct()
{
BuildPartA(std::string("pre-defined"));
BuildPartB(std::string("pre-defined"));
BuildPartC(std::string("pre-defined"));
return new Product();
}
Director::Director(Builder* bld)
{
_bld = bld;
}
Director::~Director()
{
}
void Director::Construct()
{
_bld->BuildPartA("user-defined");
_bld->BuildPartB("user-defined");
_bld->BuildPartC("user-defined");
} | 15.890244 | 58 | 0.679969 | lostcoder0812 |
7bf66aa3fc73f2f32b1e1f7988a03ac0d00df831 | 4,256 | cc | C++ | arcane/src/arcane/mesh/GhostLayerMng.cc | JeromeDuboisPro/framework | d88925495e3787fdaf640c29728dcac385160188 | [
"Apache-2.0"
] | null | null | null | arcane/src/arcane/mesh/GhostLayerMng.cc | JeromeDuboisPro/framework | d88925495e3787fdaf640c29728dcac385160188 | [
"Apache-2.0"
] | null | null | null | arcane/src/arcane/mesh/GhostLayerMng.cc | JeromeDuboisPro/framework | d88925495e3787fdaf640c29728dcac385160188 | [
"Apache-2.0"
] | null | null | null | // -*- tab-width: 2; indent-tabs-mode: nil; coding: utf-8-with-signature -*-
//-----------------------------------------------------------------------------
// Copyright 2000-2021 CEA (www.cea.fr) IFPEN (www.ifpenergiesnouvelles.com)
// See the top-level COPYRIGHT file for details.
// SPDX-License-Identifier: Apache-2.0
//-----------------------------------------------------------------------------
/*---------------------------------------------------------------------------*/
/* GhostLayerMng.cc (C) 2000-2013 */
/* */
/* Gestionnaire de couche fantômes d'un maillage. */
/*---------------------------------------------------------------------------*/
/*---------------------------------------------------------------------------*/
#include "arcane/utils/ArcanePrecomp.h"
#include "arcane/utils/ArgumentException.h"
#include "arcane/utils/ValueConvert.h"
#include "arcane/utils/PlatformUtils.h"
#include "arcane/mesh/GhostLayerMng.h"
/*---------------------------------------------------------------------------*/
/*---------------------------------------------------------------------------*/
ARCANE_BEGIN_NAMESPACE
ARCANE_MESH_BEGIN_NAMESPACE
/*---------------------------------------------------------------------------*/
/*---------------------------------------------------------------------------*/
GhostLayerMng::
GhostLayerMng(ITraceMng* tm)
: TraceAccessor(tm)
, m_nb_ghost_layer(1)
, m_builder_version(3)
{
String nb_ghost_str = platform::getEnvironmentVariable("ARCANE_NB_GHOSTLAYER");
Integer nb_ghost = 1;
if (!nb_ghost_str.null())
builtInGetValue(nb_ghost,nb_ghost_str);
if (nb_ghost<=0)
nb_ghost = 1;
m_nb_ghost_layer = nb_ghost;
_initBuilderVersion();
}
/*---------------------------------------------------------------------------*/
/*---------------------------------------------------------------------------*/
void GhostLayerMng::
setNbGhostLayer(Integer n)
{
if (n<0)
ARCANE_THROW(ArgumentException,"Bad number of ghost layer '{0}'<0",n);
m_nb_ghost_layer = n;
}
/*---------------------------------------------------------------------------*/
/*---------------------------------------------------------------------------*/
Integer GhostLayerMng::
nbGhostLayer() const
{
return m_nb_ghost_layer;
}
/*---------------------------------------------------------------------------*/
/*---------------------------------------------------------------------------*/
void GhostLayerMng::
setBuilderVersion(Integer n)
{
if (n<1 || n>3)
ARCANE_THROW(ArgumentException,"Bad value for builder version '{0}'. valid values are 2 or 3.",n);
m_builder_version = n;
}
/*---------------------------------------------------------------------------*/
/*---------------------------------------------------------------------------*/
void GhostLayerMng::
_initBuilderVersion()
{
// La version par défaut est la 2.
// La version 1 n'existe plus.
// La version 3 est opérationnelle et plus extensible que la 2.
// Si OK pour IFP, il faudra passer la version par défaut à la 3. Il
// reste cependant à traiter le cas des maillages AMR
Integer default_version = 2;
Integer version = default_version;
String version_str = platform::getEnvironmentVariable("ARCANE_GHOSTLAYER_VERSION");
if (!version_str.null()){
if (builtInGetValue(version,version_str)){
pwarning() << "Bad value for 'ARCANE_GHOSTLAYER_VERSION'";
}
if (version<1 || version>3)
version = default_version;
}
m_builder_version = version;
}
/*---------------------------------------------------------------------------*/
/*---------------------------------------------------------------------------*/
Integer GhostLayerMng::
builderVersion() const
{
return m_builder_version;
}
/*---------------------------------------------------------------------------*/
/*---------------------------------------------------------------------------*/
ARCANE_MESH_END_NAMESPACE
ARCANE_END_NAMESPACE
/*---------------------------------------------------------------------------*/
/*---------------------------------------------------------------------------*/
| 35.466667 | 102 | 0.390038 | JeromeDuboisPro |
7bfc9c9692accf77ebdcced6a2db22ba8979b873 | 5,356 | cpp | C++ | Cpp/SDK/W_Marker_Request_functions.cpp | MrManiak/Squad-SDK | 742feb5991ae43d6f0cedd2d6b32b949923ca4f9 | [
"Apache-2.0"
] | 1 | 2020-08-15T08:31:55.000Z | 2020-08-15T08:31:55.000Z | Cpp/SDK/W_Marker_Request_functions.cpp | MrManiak/Squad-SDK | 742feb5991ae43d6f0cedd2d6b32b949923ca4f9 | [
"Apache-2.0"
] | 2 | 2020-08-15T08:43:56.000Z | 2021-01-15T05:04:48.000Z | Cpp/SDK/W_Marker_Request_functions.cpp | MrManiak/Squad-SDK | 742feb5991ae43d6f0cedd2d6b32b949923ca4f9 | [
"Apache-2.0"
] | 2 | 2020-08-10T12:05:42.000Z | 2021-02-12T19:56:10.000Z | // Name: S, Version: b
#include "../SDK.h"
#ifdef _MSC_VER
#pragma pack(push, 0x01)
#endif
/*!!HELPER_DEF!!*/
/*!!DEFINE!!*/
namespace UFT
{
//---------------------------------------------------------------------------
// Functions
//---------------------------------------------------------------------------
// Function W_Marker_Request.W_Marker_Request_C.OnPreviewMouseButtonDown
// (BlueprintCosmetic, Event, Public, HasOutParms, HasDefaults, BlueprintCallable, BlueprintEvent)
// Parameters:
// struct FGeometry MyGeometry (BlueprintVisible, BlueprintReadOnly, Parm, IsPlainOldData, NoDestructor)
// struct FPointerEvent MouseEvent (ConstParm, BlueprintVisible, BlueprintReadOnly, Parm, OutParm, ReferenceParm)
// struct FEventReply ReturnValue (Parm, OutParm, ReturnParm)
struct FEventReply UW_Marker_Request_C::OnPreviewMouseButtonDown(const struct FGeometry& MyGeometry, const struct FPointerEvent& MouseEvent)
{
static auto fn = UObject::FindObject<UFunction>("Function W_Marker_Request.W_Marker_Request_C.OnPreviewMouseButtonDown");
UW_Marker_Request_C_OnPreviewMouseButtonDown_Params params;
params.MyGeometry = MyGeometry;
params.MouseEvent = MouseEvent;
auto flags = fn->FunctionFlags;
UObject::ProcessEvent(fn, ¶ms);
fn->FunctionFlags = flags;
return params.ReturnValue;
}
// Function W_Marker_Request.W_Marker_Request_C.OnScaleChanged
// (Event, Public, BlueprintEvent)
// Parameters:
// float UniformScale (BlueprintVisible, BlueprintReadOnly, Parm, ZeroConstructor, IsPlainOldData, NoDestructor, HasGetValueTypeHash)
void UW_Marker_Request_C::OnScaleChanged(float UniformScale)
{
static auto fn = UObject::FindObject<UFunction>("Function W_Marker_Request.W_Marker_Request_C.OnScaleChanged");
UW_Marker_Request_C_OnScaleChanged_Params params;
params.UniformScale = UniformScale;
auto flags = fn->FunctionFlags;
UObject::ProcessEvent(fn, ¶ms);
fn->FunctionFlags = flags;
}
// Function W_Marker_Request.W_Marker_Request_C.Construct
// (BlueprintCosmetic, Event, Public, BlueprintEvent)
void UW_Marker_Request_C::Construct()
{
static auto fn = UObject::FindObject<UFunction>("Function W_Marker_Request.W_Marker_Request_C.Construct");
UW_Marker_Request_C_Construct_Params params;
auto flags = fn->FunctionFlags;
UObject::ProcessEvent(fn, ¶ms);
fn->FunctionFlags = flags;
}
// Function W_Marker_Request.W_Marker_Request_C.Find Map Icon
// (BlueprintCallable, BlueprintEvent)
void UW_Marker_Request_C::Find_Map_Icon()
{
static auto fn = UObject::FindObject<UFunction>("Function W_Marker_Request.W_Marker_Request_C.Find Map Icon");
UW_Marker_Request_C_Find_Map_Icon_Params params;
auto flags = fn->FunctionFlags;
UObject::ProcessEvent(fn, ¶ms);
fn->FunctionFlags = flags;
}
// Function W_Marker_Request.W_Marker_Request_C.OnRightClicked
// (Event, Protected, BlueprintEvent)
void UW_Marker_Request_C::OnRightClicked()
{
static auto fn = UObject::FindObject<UFunction>("Function W_Marker_Request.W_Marker_Request_C.OnRightClicked");
UW_Marker_Request_C_OnRightClicked_Params params;
auto flags = fn->FunctionFlags;
UObject::ProcessEvent(fn, ¶ms);
fn->FunctionFlags = flags;
}
// Function W_Marker_Request.W_Marker_Request_C.Set Vis to Commander
// (BlueprintCallable, BlueprintEvent)
void UW_Marker_Request_C::Set_Vis_to_Commander()
{
static auto fn = UObject::FindObject<UFunction>("Function W_Marker_Request.W_Marker_Request_C.Set Vis to Commander");
UW_Marker_Request_C_Set_Vis_to_Commander_Params params;
auto flags = fn->FunctionFlags;
UObject::ProcessEvent(fn, ¶ms);
fn->FunctionFlags = flags;
}
// Function W_Marker_Request.W_Marker_Request_C.Tick
// (BlueprintCosmetic, Event, Public, BlueprintEvent)
// Parameters:
// struct FGeometry MyGeometry (BlueprintVisible, BlueprintReadOnly, Parm, IsPlainOldData, NoDestructor)
// float InDeltaTime (BlueprintVisible, BlueprintReadOnly, Parm, ZeroConstructor, IsPlainOldData, NoDestructor, HasGetValueTypeHash)
void UW_Marker_Request_C::Tick(const struct FGeometry& MyGeometry, float InDeltaTime)
{
static auto fn = UObject::FindObject<UFunction>("Function W_Marker_Request.W_Marker_Request_C.Tick");
UW_Marker_Request_C_Tick_Params params;
params.MyGeometry = MyGeometry;
params.InDeltaTime = InDeltaTime;
auto flags = fn->FunctionFlags;
UObject::ProcessEvent(fn, ¶ms);
fn->FunctionFlags = flags;
}
// Function W_Marker_Request.W_Marker_Request_C.ExecuteUbergraph_W_Marker_Request
// (Final, HasDefaults)
// Parameters:
// int EntryPoint (BlueprintVisible, BlueprintReadOnly, Parm, ZeroConstructor, IsPlainOldData, NoDestructor, HasGetValueTypeHash)
void UW_Marker_Request_C::ExecuteUbergraph_W_Marker_Request(int EntryPoint)
{
static auto fn = UObject::FindObject<UFunction>("Function W_Marker_Request.W_Marker_Request_C.ExecuteUbergraph_W_Marker_Request");
UW_Marker_Request_C_ExecuteUbergraph_W_Marker_Request_Params params;
params.EntryPoint = EntryPoint;
auto flags = fn->FunctionFlags;
UObject::ProcessEvent(fn, ¶ms);
fn->FunctionFlags = flags;
}
}
#ifdef _MSC_VER
#pragma pack(pop)
#endif
| 31.321637 | 176 | 0.740291 | MrManiak |
d00b9d8d7344ff904c32a720495edaf7a4c57d70 | 20,026 | cpp | C++ | Platformer 2D/Motor2D/j1Player.cpp | Scarzard/Game_Development_HO | fe3441c23df03c15120d159671f0cd41d7b8c370 | [
"MIT"
] | null | null | null | Platformer 2D/Motor2D/j1Player.cpp | Scarzard/Game_Development_HO | fe3441c23df03c15120d159671f0cd41d7b8c370 | [
"MIT"
] | null | null | null | Platformer 2D/Motor2D/j1Player.cpp | Scarzard/Game_Development_HO | fe3441c23df03c15120d159671f0cd41d7b8c370 | [
"MIT"
] | 1 | 2018-11-18T21:30:45.000Z | 2018-11-18T21:30:45.000Z | #include "p2Log.h"
#include "j1Player.h"
#include "j1App.h"
#include "j1Render.h"
#include "j1Window.h"
#include "j1Textures.h"
#include "j1Map.h"
#include "p2Log.h"
#include <string>
#include "j1Input.h"
#include "j1Collision.h"
#include "j1Scene.h"
#include "Brofiler/Brofiler.h"
#include <math.h>
j1Player::j1Player()
{
name.create("player");
}
j1Player::~j1Player()
{
}
bool j1Player::Awake(pugi::xml_node &config)
{
player1 = new Player;
player1->alive = config.child("alive").attribute("value").as_bool();
player1->position.x = config.child("position").attribute("x").as_int();
player1->position.y = config.child("position").attribute("y").as_int();
player1->camera1.x = config.child("cameraStartPos1").attribute("x").as_int();
player1->camera1.y = config.child("cameraStartPos1").attribute("y").as_int();
player1->camera2.x = config.child("cameraStartPos2").attribute("x").as_int();
player1->camera2.y = config.child("cameraStartPos2").attribute("y").as_int();
player1->playerSpeed = config.child("playerSpeed").attribute("value").as_int();
player1->jumpStrength = config.child("jumpStrength").attribute("value").as_int();
player1->gravity = config.child("gravity").attribute("value").as_int();
return true;
}
bool j1Player::Start()
{
player1->playerTexture = App->tex->Load("textures/main_character.png");
player1->godmodeTexture = App->tex->Load("textures/main_character_godmode.png");
App->render->camera.x = player1->camera1.x;
App->render->camera.y = player1->camera1.y;
pugi::xml_parse_result result = storedAnims.load_file("textures/animations.tmx");
if (result == NULL)
LOG("Couldn't load player animations! Error:", result.description());
else
{
LoadAnimations();
}
player1->playerCollider = App->collision->FindPlayer();
player1->playerNextFrameCol = App->collision->AddCollider({ player1->playerCollider->rect.x, player1->playerCollider->rect.y,
player1->playerCollider->rect.w, player1->playerCollider->rect.h }, COLLIDER_PLAYERFUTURE, this);
player1->currentAnimation = &player1->idle;
player1->jumpsLeft = 2;
return true;
}
bool j1Player::PreUpdate()
{
BROFILER_CATEGORY("Player_PreUpdate", Profiler::Color::Aquamarine)
if (player1->alive == true) {
SetSpeed();
player1->normalizedSpeed.x = player1->speed.x * player1->dtPlayer;
player1->normalizedSpeed.y = player1->speed.y * player1->dtPlayer;
player1->playerNextFrameCol->SetPos(player1->playerCollider->rect.x + player1->speed.x, player1->playerCollider->rect.y + player1->speed.y);
if (player1->jumping == false)
player1->jumpsLeft = 2;
}
return true;
}
bool j1Player::Update(float dt)
{
BROFILER_CATEGORY("Player_Update", Profiler::Color::Orchid)
dt = player1->dtPlayer;
//Player controls
if (player1->alive == true)
{
if (player1->godmode)
player1->jumpsLeft = 2;
if (App->render->camera.x > 4500)App->render->camera.x = 4000;
if (App->render->camera.x < 0)App->render->camera.x = 0;
//Check Horizontal Movement
//Right
if (App->input->GetKey(SDL_SCANCODE_D) == KEY_DOWN)
player1->facingLeft = false;
//Left
else if (App->input->GetKey(SDL_SCANCODE_A) == KEY_DOWN)
player1->facingLeft = true;
//---------------------------
//Prevent animations from glitching
if (player1->speed.x > 0)
player1->facingLeft = false;
if (player1->speed.x < 0)
player1->facingLeft = true;
//---------------------------------
//Check Jump ----------------------
if (App->input->GetKey(SDL_SCANCODE_J) == KEY_DOWN && player1->jumpsLeft != 0)
{
player1->jumpsLeft--;
player1->jumping = true;
}
if (player1->jumpsLeft == 2 && player1->speed.y > 0)
player1->jumpsLeft--;
//---------------------------------
//Check godmode debug -------------
if (App->input->GetKey(SDL_SCANCODE_F10) == KEY_DOWN)
player1->godmode = !player1->godmode;
// Set the correct animation for current movement
SetAnimations();
// Move player as of its current speed
Move();
// Update present collider
player1->playerCollider->SetPos(player1->position.x + player1->colliderOffset.x, player1->position.y + player1->colliderOffset.y);
// Blit player
if (player1->facingLeft)
{
if (!player1->godmode)
App->render->Blit(player1->playerTexture, player1->position.x, player1->position.y, &player1->currentAnimation->GetCurrentFrame(), SDL_FLIP_NONE);
else if (player1->godmode)
App->render->Blit(player1->godmodeTexture, player1->position.x, player1->position.y, &player1->currentAnimation->GetCurrentFrame(), SDL_FLIP_NONE);
}
else if (!player1->facingLeft)
{
if (!player1->godmode)
App->render->Blit(player1->playerTexture, player1->position.x, player1->position.y, &player1->currentAnimation->GetCurrentFrame(), SDL_FLIP_HORIZONTAL);
else if (player1->godmode)
App->render->Blit(player1->godmodeTexture, player1->position.x, player1->position.y, &player1->currentAnimation->GetCurrentFrame(), SDL_FLIP_HORIZONTAL);
}
CenterCameraOnPlayer();
}
else if (!player1->alive)
{
Respawn();
}
if (player1->changingLevel)
RespawnInNewLevel();
return true;
}
bool j1Player::PostUpdate()
{
BROFILER_CATEGORY("Player_PostUpdate", Profiler::Color::Crimson)
p2List_item<ImageLayer*>* img = nullptr;
for (img = App->map->data.image.start; img; img = img->next)
{
if (img->data->speed > 0)
{
if (player1->parallaxToLeft = true)
{
img->data->position.x += player1->speed.x / img->data->speed;
}
else if (player1->parallaxToRight = true)
{
img->data->position.x -= player1->speed.x / img->data->speed;
}
}
}
return true;
}
bool j1Player::CleanUp()
{
App->tex->UnLoad(player1->playerTexture);
App->tex->UnLoad(player1->godmodeTexture);
player1->currentAnimation = nullptr;
delete player1;
return true;
}
void j1Player::LoadAnimations()
{
std::string tmp;
// Loop all different animations (each one is an object layer in the tmx)
for (animFinder = storedAnims.child("map").child("objectgroup"); animFinder; animFinder = animFinder.next_sibling())
{
tmp = animFinder.child("properties").first_child().attribute("value").as_string();
// Load idle
if (tmp == "idle")
{
// Loop all frames and push them into animation
for (pugi::xml_node frameIterator = animFinder.child("object"); frameIterator; frameIterator = frameIterator.next_sibling())
{
SDL_Rect frameToPush = { frameIterator.attribute("x").as_int(), frameIterator.attribute("y").as_int(), frameIterator.attribute("width").as_int(), frameIterator.attribute("height").as_int() };
player1->idle.PushBack(frameToPush);
}
for (pugi::xml_node propertyIterator = animFinder.child("properties").first_child(); propertyIterator; propertyIterator = propertyIterator.next_sibling())
{
std::string checkName = propertyIterator.attribute("name").as_string();
if (checkName == "loop")
player1->idle.loop = propertyIterator.attribute("value").as_bool();
else if (checkName == "speed")
player1->idle.speed = propertyIterator.attribute("value").as_float();
}
}
// Load run
if (tmp == "run")
{
// Loop all frames and push them into animation
for (pugi::xml_node frameIterator = animFinder.child("object"); frameIterator; frameIterator = frameIterator.next_sibling())
{
SDL_Rect frameToPush = { frameIterator.attribute("x").as_int(), frameIterator.attribute("y").as_int(), frameIterator.attribute("width").as_int(), frameIterator.attribute("height").as_int() };
player1->run.PushBack(frameToPush);
}
for (pugi::xml_node propertyIterator = animFinder.child("properties").first_child(); propertyIterator; propertyIterator = propertyIterator.next_sibling())
{
std::string checkName = propertyIterator.attribute("name").as_string();
if (checkName == "loop")
player1->run.loop = propertyIterator.attribute("value").as_bool();
else if (checkName == "speed")
player1->run.speed = propertyIterator.attribute("value").as_float();
}
}
// Load jump
if (tmp == "jump")
{
// Loop all frames and push them into animation
for (pugi::xml_node frameIterator = animFinder.child("object"); frameIterator; frameIterator = frameIterator.next_sibling())
{
SDL_Rect frameToPush = { frameIterator.attribute("x").as_int(), frameIterator.attribute("y").as_int(), frameIterator.attribute("width").as_int(), frameIterator.attribute("height").as_int() };
player1->jump.PushBack(frameToPush);
}
for (pugi::xml_node propertyIterator = animFinder.child("properties").first_child(); propertyIterator; propertyIterator = propertyIterator.next_sibling())
{
std::string checkName = propertyIterator.attribute("name").as_string();
if (checkName == "loop")
player1->jump.loop = propertyIterator.attribute("value").as_bool();
else if (checkName == "speed")
player1->jump.speed = propertyIterator.attribute("value").as_float();
}
}
// Load fall
if (tmp == "fall")
{
// Loop all frames and push them into animation
for (pugi::xml_node frameIterator = animFinder.child("object"); frameIterator; frameIterator = frameIterator.next_sibling())
{
SDL_Rect frameToPush = { frameIterator.attribute("x").as_int(), frameIterator.attribute("y").as_int(), frameIterator.attribute("width").as_int(), frameIterator.attribute("height").as_int() };
player1->fall.PushBack(frameToPush);
}
for (pugi::xml_node propertyIterator = animFinder.child("properties").first_child(); propertyIterator; propertyIterator = propertyIterator.next_sibling())
{
std::string checkName = propertyIterator.attribute("name").as_string();
if (checkName == "loop")
player1->fall.loop = propertyIterator.attribute("value").as_bool();
else if (checkName == "speed")
player1->fall.speed = propertyIterator.attribute("value").as_float();
}
}
}
}
void j1Player::ApplyGravity()
{
if (player1->speed.y < 9)
player1->speed.y += player1->gravity;
else if (player1->speed.y > 9)
player1->speed.y = player1->gravity;
}
void j1Player::Respawn()
{
player1->speed.SetToZero();
player1->position.x = App->map->data.startingPointX;
player1->position.y = App->map->data.startingPointY;
App->render->cameraRestart = true;
ResetParallax();
player1->alive = true;
}
void j1Player::RespawnInNewLevel()
{
player1->speed.SetToZero();
player1->position.x = App->map->data.startingPointX;
player1->position.y = App->map->data.startingPointY;
player1->playerCollider = nullptr;
player1->playerNextFrameCol = nullptr;
player1->playerCollider = App->collision->FindPlayer();
player1->playerNextFrameCol = App->collision->AddCollider({ player1->playerCollider->rect.x, player1->playerCollider->rect.y,
player1->playerCollider->rect.w, player1->playerCollider->rect.h }, COLLIDER_PLAYERFUTURE, this);
App->render->cameraRestart = true;
ResetParallax();
player1->changingLevel = false;
}
void j1Player::SetAnimations()
{
// Reset to idle if no input is received
player1->currentAnimation = &player1->idle;
// Run if moving on the x axis
if (player1->speed.x != 0)
player1->currentAnimation = &player1->run;
// Idle if A and D are pressed simultaneously
if (player1->speed.x == 0)
player1->currentAnimation = &player1->idle;
// Set jumping animations
if (App->input->GetKey(SDL_SCANCODE_J) == KEY_DOWN)
player1->jump.Reset();
if (player1->jumping)
{
if (player1->speed.y > 0)
player1->currentAnimation = &player1->fall;
else if (player1->speed.y < 0)
player1->currentAnimation = &player1->jump;
}
}
void j1Player::SetSpeed()
{
// Apply gravity in each frame
ApplyGravity();
// Check for horizontal movement
if (App->input->GetKey(SDL_SCANCODE_D) == KEY_REPEAT && App->input->GetKey(SDL_SCANCODE_A) != KEY_REPEAT)
player1->speed.x = player1->playerSpeed;
else if (App->input->GetKey(SDL_SCANCODE_A) == KEY_REPEAT && App->input->GetKey(SDL_SCANCODE_D) != KEY_REPEAT)
player1->speed.x = -player1->playerSpeed;
else
player1->speed.x = 0;
// Check for jumps
if (App->input->GetKey(SDL_SCANCODE_J) == KEY_DOWN && player1->jumpsLeft > 0)
player1->speed.y = -player1->jumpStrength;
}
void j1Player::Move()
{
player1->position.x += player1->speed.x;
player1->position.y += player1->speed.y;
}
void j1Player::ResetParallax()
{
p2List_item<ImageLayer*>* img = nullptr;
if (!player1->alive)
{
for (img = App->map->data.image.start; img; img = img->next)
{
img->data->position.x = 0;
}
}
}
void j1Player::OnCollision(Collider* collider1, Collider* collider2)
{
// COLLISIONS ------------------------------------------------------------------------------------ //
if (collider1->type == COLLIDER_PLAYERFUTURE && collider2->type == COLLIDER_SOLID_FLOOR)
{
SDL_Rect intersectCol;
if (SDL_IntersectRect(&collider1->rect, &collider2->rect, &intersectCol));
//future player collider and a certain wall collider have collided
{
if (player1->speed.y > 0) // If player is falling
{
if (collider1->rect.y < collider2->rect.y) // Checking if player is colliding from above
{
if (player1->speed.x == 0)
player1->speed.y -= intersectCol.h, player1->jumping = false;
else if (player1->speed.x < 0)
if (intersectCol.h >= intersectCol.w)
{
if (collider1->rect.x <= collider2->rect.x + collider2->rect.w)
player1->speed.y -= intersectCol.h, player1->jumping = false;
else
player1->speed.x += intersectCol.w;
}
else
player1->speed.y -= intersectCol.h, player1->jumping = false;
else if (player1->speed.x > 0)
if (intersectCol.h >= intersectCol.w)
{
if (collider1->rect.x + collider1->rect.w <= collider2->rect.x)
player1->speed.y -= intersectCol.h, player1->jumping = false;
else
player1->speed.x -= intersectCol.w;
}
else
player1->speed.y -= intersectCol.h, player1->jumping = false;
}
else
{
if (player1->speed.x < 0)
player1->speed.x += intersectCol.w;
else if (player1->speed.x > 0)
player1->speed.x -= intersectCol.w;
}
}
else if (player1->speed.y == 0) // If player is not moving vertically
{
if (player1->speed.x > 0)
player1->speed.x -= intersectCol.w;
if (player1->speed.x < 0)
player1->speed.x += intersectCol.w;
}
else if (player1->speed.y < 0) // If player is moving up
{
if (collider1->rect.y + collider1->rect.h > collider2->rect.y + collider2->rect.h) // Checking if player is colliding from below
{
if (player1->speed.x == 0)
player1->speed.y += intersectCol.h;
else if (player1->speed.x < 0)
{
if (intersectCol.h >= intersectCol.w)
{
if (collider1->rect.x <= collider2->rect.x + collider2->rect.w)
player1->speed.y += intersectCol.h;
else
player1->speed.x += intersectCol.w;
}
else
player1->speed.y += intersectCol.h;
}
else if (player1->speed.x > 0)
{
if (intersectCol.h >= intersectCol.w)
{
if (collider1->rect.x + collider1->rect.w >= collider2->rect.x)
player1->speed.y += intersectCol.h;
else
player1->speed.x -= intersectCol.w;
}
else
player1->speed.y += intersectCol.h;
}
}
else
{
if (player1->speed.x < 0)
player1->speed.x += intersectCol.w;
else if (player1->speed.x > 0)
player1->speed.x -= intersectCol.w;
}
}
}
}
// COLLISIONS ------------------------------------------------------------------------------------ //
else if (collider1->type == COLLIDER_PLAYERFUTURE && collider2->type == COLLIDER_DEATH)
{
if (!player1->godmode)
player1->alive = false;
else if (player1->godmode)
{
SDL_Rect intersectCol;
if (SDL_IntersectRect(&collider1->rect, &collider2->rect, &intersectCol));
//future player collider and a certain wall collider have collided
{
if (player1->speed.y > 0) // If player is falling
{
if (collider1->rect.y < collider2->rect.y) // Checking if player is colliding from above
{
if (player1->speed.x == 0)
player1->speed.y -= intersectCol.h, player1->jumping = false;
else if (player1->speed.x < 0)
if (intersectCol.h >= intersectCol.w)
{
if (collider1->rect.x <= collider2->rect.x + collider2->rect.w)
player1->speed.y -= intersectCol.h, player1->jumping = false;
else
player1->speed.x += intersectCol.w;
}
else
player1->speed.y -= intersectCol.h, player1->jumping = false;
else if (player1->speed.x > 0)
if (intersectCol.h >= intersectCol.w)
{
if (collider1->rect.x + collider1->rect.w <= collider2->rect.x)
player1->speed.y -= intersectCol.h, player1->jumping = false;
else
player1->speed.x -= intersectCol.w;
}
else
player1->speed.y -= intersectCol.h, player1->jumping = false;
}
else
{
if (player1->speed.x < 0)
player1->speed.x += intersectCol.w;
else if (player1->speed.x > 0)
player1->speed.x -= intersectCol.w;
}
}
else if (player1->speed.y == 0) // If player is not moving vertically
{
if (player1->speed.x > 0)
player1->speed.x -= intersectCol.w;
if (player1->speed.x < 0)
player1->speed.x += intersectCol.w;
}
else if (player1->speed.y < 0) // If player is moving up
{
if (collider1->rect.y + collider1->rect.h > collider2->rect.y + collider2->rect.h) // Checking if player is colliding from below
{
if (player1->speed.x == 0)
player1->speed.y += intersectCol.h;
else if (player1->speed.x < 0)
{
if (intersectCol.h >= intersectCol.w)
{
if (collider1->rect.x <= collider2->rect.x + collider2->rect.w)
player1->speed.y += intersectCol.h;
else
player1->speed.x += intersectCol.w;
}
else
player1->speed.y += intersectCol.h;
}
else if (player1->speed.x > 0)
{
if (intersectCol.h >= intersectCol.w)
{
if (collider1->rect.x + collider1->rect.w >= collider2->rect.x)
player1->speed.y += intersectCol.h;
else
player1->speed.x -= intersectCol.w;
}
else
player1->speed.y += intersectCol.h;
}
}
else
{
if (player1->speed.x < 0)
player1->speed.x += intersectCol.w;
else if (player1->speed.x > 0)
player1->speed.x -= intersectCol.w;
}
}
}
}
}
else if (collider1->type == COLLIDER_PLAYERFUTURE && collider2->type == COLLIDER_LEVELEND)
{
App->player->player1->changingLevel = true;
if (App->scene->currentLevel == 1)
App->scene->LoadLevel(2), App->scene->currentLevel = 2;
else if (App->scene->currentLevel == 2)
App->scene->LoadLevel(1), App->scene->currentLevel = 1;
}
}
bool j1Player::CenterCameraOnPlayer()
{
uint w, h;
App->win->GetWindowSize(w, h);
if (player1->position.x > App->render->camera.x + w)
{
App->render->camera.x -= player1->speed.x * 2;
player1->parallaxToRight = true;
}
else if (player1->position.x < App->render->camera.x + w)
{
App->render->camera.x += player1->speed.x * 2;
player1->parallaxToLeft = true;
}
if (player1->position.y > App->render->camera.y + h) { App->render->camera.y -= player1->speed.y * 2; }
else if (player1->position.y < App->render->camera.y + h) { App->render->camera.y += player1->speed.y * 2; }
return true;
}
bool j1Player::Load(pugi::xml_node &node)
{
player1->position.x = node.child("position").attribute("x").as_int();
player1->position.y = node.child("position").attribute("y").as_int();
return true;
}
bool j1Player::Save(pugi::xml_node &node) const
{
pugi::xml_node position = node.append_child("position");
position.append_attribute("x") = player1->position.x;
position.append_attribute("y") = player1->position.y;
return true;
} | 28.897547 | 195 | 0.647159 | Scarzard |
d0170188157eab7993fe3f2abc6975a63324cf66 | 3,629 | hpp | C++ | smacc2_client_library/nav2z_client/custom_planners/pure_spinning_local_planner/include/pure_spinning_local_planner/pure_spinning_local_planner.hpp | droidware-ai/SMACC2 | 1aa0680f71c1b22f06e1a9b129a0a42b36911139 | [
"Apache-2.0"
] | 48 | 2021-05-28T01:33:20.000Z | 2022-03-24T03:16:03.000Z | smacc2_client_library/nav2z_client/custom_planners/pure_spinning_local_planner/include/pure_spinning_local_planner/pure_spinning_local_planner.hpp | droidware-ai/SMACC2 | 1aa0680f71c1b22f06e1a9b129a0a42b36911139 | [
"Apache-2.0"
] | 75 | 2021-06-25T22:11:21.000Z | 2022-03-30T13:05:38.000Z | smacc2_client_library/nav2z_client/custom_planners/pure_spinning_local_planner/include/pure_spinning_local_planner/pure_spinning_local_planner.hpp | droidware-ai/SMACC2 | 1aa0680f71c1b22f06e1a9b129a0a42b36911139 | [
"Apache-2.0"
] | 14 | 2021-06-16T12:10:57.000Z | 2022-03-01T18:23:27.000Z | // Copyright 2021 RobosoftAI Inc.
//
// Licensed under the Apache License, Version 2.0 (the "License");
// you may not use this file except in compliance with the License.
// You may obtain a copy of the License at
//
// http://www.apache.org/licenses/LICENSE-2.0
//
// Unless required by applicable law or agreed to in writing, software
// distributed under the License is distributed on an "AS IS" BASIS,
// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
// See the License for the specific language governing permissions and
// limitations under the License.
/*****************************************************************************************************************
*
* Authors: Pablo Inigo Blasco, Brett Aldrich
*
******************************************************************************************************************/
#pragma once
//#include <dynamic_reconfigure/server.h>
//#include <pure_spinning_local_planner/PureSpinningLocalPlannerConfig.h>
#include <tf2/transform_datatypes.h>
#include <tf2_ros/buffer.h>
#include <Eigen/Eigen>
#include <geometry_msgs/msg/pose_stamped.hpp>
#include <geometry_msgs/msg/quaternion.hpp>
#include <nav2_core/controller.hpp>
#include <tf2_geometry_msgs/tf2_geometry_msgs.hpp>
#include <visualization_msgs/msg/marker_array.hpp>
typedef double meter;
typedef double rad;
typedef double rad_s;
namespace cl_nav2z
{
namespace pure_spinning_local_planner
{
class PureSpinningLocalPlanner : public nav2_core::Controller
{
public:
PureSpinningLocalPlanner();
virtual ~PureSpinningLocalPlanner();
void configure(
const rclcpp_lifecycle::LifecycleNode::WeakPtr & parent, std::string name,
const std::shared_ptr<tf2_ros::Buffer> & tf,
const std::shared_ptr<nav2_costmap_2d::Costmap2DROS> & costmap_ros) override;
void activate() override;
void deactivate() override;
void cleanup() override;
/**
* @brief nav2_core setPlan - Sets the global plan
* @param path The global plan
*/
void setPlan(const nav_msgs::msg::Path & path) override;
/**
* @brief nav2_core computeVelocityCommands - calculates the best command given the current pose and velocity
*
* It is presumed that the global plan is already set.
*
* This is mostly a wrapper for the protected computeVelocityCommands
* function which has additional debugging info.
*
* @param pose Current robot pose
* @param velocity Current robot velocity
* @return The best command for the robot to drive
*/
virtual geometry_msgs::msg::TwistStamped computeVelocityCommands(
const geometry_msgs::msg::PoseStamped & pose, const geometry_msgs::msg::Twist & velocity,
nav2_core::GoalChecker * goal_checker) override;
/*deprecated in navigation2*/
bool isGoalReached();
virtual void setSpeedLimit(const double & speed_limit, const bool & percentage) override;
private:
void updateParameters();
nav2_util::LifecycleNode::SharedPtr nh_;
std::string name_;
void publishGoalMarker(double x, double y, double phi);
std::shared_ptr<nav2_costmap_2d::Costmap2DROS> costmapRos_;
std::shared_ptr<rclcpp_lifecycle::LifecyclePublisher<visualization_msgs::msg::MarkerArray>>
goalMarkerPublisher_;
std::vector<geometry_msgs::msg::PoseStamped> plan_;
std::shared_ptr<tf2_ros::Buffer> tf_;
double k_betta_;
bool goalReached_;
int currentPoseIndex_;
rad yaw_goal_tolerance_;
rad intermediate_goal_yaw_tolerance_;
rad_s max_angular_z_speed_;
double transform_tolerance_;
bool use_shortest_angular_distance_;
};
} // namespace pure_spinning_local_planner
} // namespace cl_nav2z
| 32.990909 | 116 | 0.712869 | droidware-ai |
d018b1683a2f79ab756a843d34e3d70cb55aed71 | 1,542 | cpp | C++ | src/nxcraft/protocol/socket.cpp | ConsoleLogLuke/NXCraft | 9d53df6143c050d3e8be8d7a717f0dc6069bc00a | [
"MIT"
] | 4 | 2020-08-29T10:20:18.000Z | 2022-01-18T23:03:44.000Z | src/nxcraft/protocol/socket.cpp | ConsoleLogLuke/NXCraft | 9d53df6143c050d3e8be8d7a717f0dc6069bc00a | [
"MIT"
] | null | null | null | src/nxcraft/protocol/socket.cpp | ConsoleLogLuke/NXCraft | 9d53df6143c050d3e8be8d7a717f0dc6069bc00a | [
"MIT"
] | null | null | null | #include "socket.hpp"
#include <vector>
#include <sys/socket.h>
#include <netinet/in.h>
#include <arpa/inet.h>
namespace nxcraft {
namespace protocol {
bool Socket::init() {
sockfd = socket(AF_INET, SOCK_STREAM, 0);
return sockfd >= 0;
}
bool Socket::connect(std::string address, int port) {
struct sockaddr_in sockAddr;
memset(&sockAddr, 0, sizeof(sockAddr));
sockAddr.sin_family = AF_INET;
sockAddr.sin_port = htons(port);
if (inet_pton(AF_INET, address.c_str(), &sockAddr.sin_addr) <= 0) {
return false;
}
return ::connect(sockfd, (struct sockaddr *) &sockAddr, sizeof(sockAddr)) >= 0;
}
bool Socket::disconnect() {
return close(sockfd) >= 0;
}
bool Socket::writeBuffer(Buffer buffer) {
buffer.buffer.insert(buffer.buffer.begin(), (std::byte) buffer.buffer.size());
std::vector<std::byte> copy = buffer.buffer;
return write(sockfd, ©[0], copy.size()) >= 0;
}
void Socket::readBuffer(Buffer *buffer) {
int numRead = 0;
int length = 0;
std::byte read;
do {
char readBuffer[1];
recv(sockfd, readBuffer, 1, 0);
read = (std::byte) readBuffer[0];
int value = ((int) read & 0b01111111);
length = length | (value << (7 * numRead));
++numRead;
} while (((int) read & 0b10000000) != 0);
char oldBuffer[length];
recv(sockfd, oldBuffer, length, 0);
for (int i = 0; i < length; ++i) {
buffer->writeByte((std::byte) oldBuffer[i]);
}
}
} // namespace protocol
} // namespace nxcraft
| 23.723077 | 83 | 0.616732 | ConsoleLogLuke |
d024d1fc9dcb16580496307490682952fe8af3cf | 10,233 | cpp | C++ | Algorithm/cloth/graph/GraphsSewing.cpp | dolphin-li/ClothDesigner | 82b186d6db320b645ac67a4d32d7746cc9bdd391 | [
"MIT"
] | 32 | 2016-12-13T05:49:12.000Z | 2022-02-04T06:15:47.000Z | Algorithm/cloth/graph/GraphsSewing.cpp | dolphin-li/ClothDesigner | 82b186d6db320b645ac67a4d32d7746cc9bdd391 | [
"MIT"
] | 2 | 2019-07-30T02:01:16.000Z | 2020-03-12T15:06:51.000Z | Algorithm/cloth/graph/GraphsSewing.cpp | dolphin-li/ClothDesigner | 82b186d6db320b645ac67a4d32d7746cc9bdd391 | [
"MIT"
] | 18 | 2017-11-16T13:37:06.000Z | 2022-03-11T08:13:46.000Z | #include "GraphsSewing.h"
#include "AbstractGraphCurve.h"
#include "tinyxml\tinyxml.h"
namespace ldp
{
GraphsSewing::GraphsSewing() : AbstractGraphObject()
{
}
GraphsSewing::~GraphsSewing()
{
clear();
}
void GraphsSewing::clear()
{
auto tmp = m_firsts;
tmp.insert(tmp.end(), m_seconds.begin(), m_seconds.end());
for (auto t : tmp)
remove(t.curve->getId());
m_firsts.clear();
m_seconds.clear();
m_sewingType = SewingTypeStitch;
}
void GraphsSewing::addFirst(Unit unit)
{
add(m_firsts, unit);
}
void GraphsSewing::addSecond(Unit unit)
{
add(m_seconds, unit);
}
void GraphsSewing::add(std::vector<Unit>& units, Unit unit)const
{
auto iter_same = units.end();
for (auto iter = units.begin(); iter != units.end(); ++iter)
{
if (iter->curve == unit.curve)
{
iter_same = iter;
break;
}
}
if (iter_same == units.end())
{
units.push_back(unit);
unit.curve->graphSewings().insert((GraphsSewing*)this);
}
else
iter_same->reverse = unit.reverse;
}
void GraphsSewing::addFirsts(const std::vector<Unit>& unit)
{
for (const auto& u : unit)
addFirst(u);
}
void GraphsSewing::addSeconds(const std::vector<Unit>& unit)
{
for (const auto& u : unit)
addSecond(u);
}
void GraphsSewing::remove(size_t id)
{
remove(m_firsts, id);
remove(m_seconds, id);
}
void GraphsSewing::remove(const std::set<size_t>& s)
{
for (auto id : s)
remove(id);
}
void GraphsSewing::remove(std::vector<Unit>& units, size_t curveId)const
{
for (auto iter = units.begin(); iter != units.end(); ++iter)
{
if (iter->curve->getId() != curveId)
continue;
auto siter = iter->curve->graphSewings().find((GraphsSewing*)this);
if (siter == iter->curve->graphSewings().end())
{
printf("GraphsSewing remove warning: curve %d not relate to sew %d",
iter->curve->getId(), getId());
}
else
iter->curve->graphSewings().erase(siter);
units.erase(iter);
break;
}
}
void GraphsSewing::swapCurve(AbstractGraphCurve* oldCurve, AbstractGraphCurve* newCurve)
{
swapCurve(m_firsts, oldCurve, newCurve);
swapCurve(m_seconds, oldCurve, newCurve);
}
void GraphsSewing::swapCurve(AbstractGraphCurve* oldCurve, const std::vector<AbstractGraphCurve*>& newCurves)
{
swapCurve(m_firsts, oldCurve, newCurves);
swapCurve(m_seconds, oldCurve, newCurves);
}
void GraphsSewing::swapUnit(Unit ou, Unit nu)
{
swapUnit(m_firsts, ou, nu);
swapUnit(m_seconds, ou, nu);
}
void GraphsSewing::swapUnit(Unit ou, const std::vector<Unit>& nus)
{
swapUnit(m_firsts, ou, nus);
swapUnit(m_seconds, ou, nus);
}
void GraphsSewing::swapUnit(std::vector<Unit>& units, Unit ou, Unit nu)
{
for (auto& u : units)
{
if (u.curve == ou.curve)
{
if (u.curve->graphSewings().find(this) == u.curve->graphSewings().end())
printf("GraphsSewing::swapUnit warning: curve %d does not relate to sew %d\n",
u.curve->getId(), getId());
else
u.curve->graphSewings().erase(this);
u = nu;
u.curve->graphSewings().insert(this);
}
} // end for u
}
void GraphsSewing::swapUnit(std::vector<Unit>& units, Unit ou, const std::vector<Unit>& nus)
{
std::vector<Unit> tmpUnits;
for (const auto& u : units)
{
if (u.curve == ou.curve)
{
if (u.curve->graphSewings().find(this) == u.curve->graphSewings().end())
printf("GraphsSewing::swapUnit warning: curve %d does not relate to sew %d\n",
u.curve->getId(), getId());
else
u.curve->graphSewings().erase(this);
for (auto nu : nus)
{
nu.curve->graphSewings().insert(this);
tmpUnits.push_back(nu);
} // end for nu
}
else
tmpUnits.push_back(u);
} // end for u
units = tmpUnits;
}
void GraphsSewing::swapCurve(std::vector<Unit>& units, AbstractGraphCurve* oldCurve, AbstractGraphCurve* newCurve)
{
Unit ou, nu;
for (auto& u : units)
{
if (u.curve == oldCurve)
{
ou = u;
break;
}
}
nu.curve = newCurve;
nu.reverse = ou.reverse;
if (ou.curve)
swapUnit(units, ou, nu);
}
void GraphsSewing::swapCurve(std::vector<Unit>& units, AbstractGraphCurve* oldCurve,
const std::vector<AbstractGraphCurve*>& newCurves)
{
Unit ou;
for (auto& u : units)
{
if (u.curve == oldCurve)
{
ou = u;
break;
}
}
std::vector<Unit> nus;
for (auto c : newCurves)
nus.push_back(Unit(c, ou.reverse));
if (ou.curve)
{
if (ou.reverse)
std::reverse(nus.begin(), nus.end());
swapUnit(units, ou, nus);
}
}
void GraphsSewing::reverse(size_t curveId)
{
for (auto& u : m_firsts)
if (u.curve->getId() == curveId)
{
u.reverse = !u.reverse;
return;
}
for (auto& u : m_seconds)
if (u.curve->getId() == curveId)
{
u.reverse = !u.reverse;
return;
}
}
void GraphsSewing::reverseFirsts()
{
for (auto& u : m_firsts)
u.reverse = !u.reverse;
std::reverse(m_firsts.begin(), m_firsts.end());
}
void GraphsSewing::reverseSeconds()
{
for (auto& u : m_seconds)
u.reverse = !u.reverse;
std::reverse(m_seconds.begin(), m_seconds.end());
}
bool GraphsSewing::select(int idx, SelectOp op)
{
if (op == SelectEnd)
return false;
std::set<int> idxSet;
idxSet.insert(idx);
return select(idxSet, op);
}
bool GraphsSewing::select(const std::set<int>& idxSet, SelectOp op)
{
if (op == SelectEnd)
return false;
static std::vector<AbstractGraphObject*> objs;
objs.clear();
objs.push_back(this);
bool changed = false;
for (auto& obj : objs)
{
bool oldSel = obj->isSelected();
switch (op)
{
case AbstractGraphObject::SelectThis:
if (idxSet.find(obj->getId()) != idxSet.end())
obj->setSelected(true);
else
obj->setSelected(false);
break;
case AbstractGraphObject::SelectUnion:
if (idxSet.find(obj->getId()) != idxSet.end())
obj->setSelected(true);
break;
case AbstractGraphObject::SelectUnionInverse:
if (idxSet.find(obj->getId()) != idxSet.end())
obj->setSelected(!obj->isSelected());
break;
case AbstractGraphObject::SelectAll:
obj->setSelected(true);
break;
case AbstractGraphObject::SelectNone:
obj->setSelected(false);
break;
case AbstractGraphObject::SelectInverse:
obj->setSelected(!obj->isSelected());
break;
default:
break;
}
bool newSel = obj->isSelected();
if (oldSel != newSel)
changed = true;
} // end for obj
return changed;
}
void GraphsSewing::highLight(int idx, int lastIdx)
{
auto cur = getObjByIdx(idx);
if (cur)
cur->setHighlighted(true);
if (idx != lastIdx)
{
auto pre = getObjByIdx(lastIdx);
if (pre)
pre->setHighlighted(false);
}
}
GraphsSewing* GraphsSewing::clone() const
{
GraphsSewing* r = (GraphsSewing*)AbstractGraphObject::create(getType());
r->m_firsts = m_firsts;
r->m_seconds = m_seconds;
r->m_sewingType = m_sewingType;
r->setSelected(isSelected());
return r;
}
static const char* sewingTypeToStr(GraphsSewing::SewingType s)
{
switch (s)
{
case ldp::GraphsSewing::SewingTypeStitch:
return "stitch";
case ldp::GraphsSewing::SewingTypePosition:
return "position";
case ldp::GraphsSewing::SewingTypeEnd:
default:
throw std::exception("sewingTypeToStr(): unknown type!");
}
}
const char* GraphsSewing::getSewingTypeStr()const
{
return sewingTypeToStr(m_sewingType);
}
TiXmlElement* GraphsSewing::toXML(TiXmlNode* parent)const
{
TiXmlElement* ele = AbstractGraphObject::toXML(parent);
ele->SetAttribute("type", getSewingTypeStr());
ele->SetAttribute("angle", getAngleInDegree());
TiXmlElement* fele = new TiXmlElement("Firsts");
ele->LinkEndChild(fele);
for (const auto& f : m_firsts)
{
TiXmlElement* uele = new TiXmlElement("unit");
fele->LinkEndChild(uele);
uele->SetAttribute("shape_id", f.curve->getId());
uele->SetAttribute("reverse", f.reverse);
}
TiXmlElement* sele = new TiXmlElement("Seconds");
ele->LinkEndChild(sele);
for (const auto& s : m_seconds)
{
TiXmlElement* uele = new TiXmlElement("unit");
sele->LinkEndChild(uele);
uele->SetAttribute("shape_id", s.curve->getId());
uele->SetAttribute("reverse", s.reverse);
}
return ele;
}
void GraphsSewing::fromXML(TiXmlElement* self)
{
AbstractGraphObject::fromXML(self);
clear();
const char* sewTypeStr = self->Attribute("type");
if (sewTypeStr)
{
for (size_t i = 0; i < (size_t)SewingTypeEnd; i++)
{
if (sewingTypeToStr((SewingType)i) == std::string(sewTypeStr))
{
m_sewingType = (SewingType)i;
break;
}
}
} // end if sewTypeStr
double tmp = 0;
if (self->Attribute("angle", &tmp))
setAngleInDegree(tmp);
for (auto child = self->FirstChildElement(); child; child = child->NextSiblingElement())
{
if (child->Value() == std::string("Firsts"))
{
for (auto child1 = child->FirstChildElement(); child1; child1 = child1->NextSiblingElement())
{
if (child1->Value() == std::string("unit"))
{
Unit u;
int tmp = 0;
if (!child1->Attribute("shape_id", &tmp))
throw std::exception("unit id lost");
auto obj = getObjByIdx_loading(tmp);
if (!obj->isCurve())
throw std::exception("sewing loading error: units type not matched!\n");
u.curve = (AbstractGraphCurve*)obj;
if (!child1->Attribute("reverse", &tmp))
throw std::exception("unit reverse lost");
u.reverse = !!tmp;
addFirst(u);
}
} // end for child1
} // end if firsts
if (child->Value() == std::string("Seconds"))
{
for (auto child1 = child->FirstChildElement(); child1; child1 = child1->NextSiblingElement())
{
if (child1->Value() == std::string("unit"))
{
Unit u;
int tmp = 0;
if (!child1->Attribute("shape_id", &tmp))
throw std::exception("unit id lost");
auto obj = getObjByIdx_loading(tmp);
if (!obj->isCurve())
throw std::exception("sewing loading error: units type not matched!\n");
u.curve = (AbstractGraphCurve*)obj;
if (!child1->Attribute("reverse", &tmp))
throw std::exception("unit reverse lost");
u.reverse = !!tmp;
addSecond(u);
}
} // end for child1
} // end if seconds
} // end for child
}
} | 23.853147 | 115 | 0.637545 | dolphin-li |
d025f68139eeaa0b982334abd7b1084ec24cbb98 | 9,136 | cc | C++ | worker.cc | reedacartwright/sim1942 | 849a5da67c3925a448c0aaf02736067a8fd240a6 | [
"MIT"
] | null | null | null | worker.cc | reedacartwright/sim1942 | 849a5da67c3925a448c0aaf02736067a8fd240a6 | [
"MIT"
] | null | null | null | worker.cc | reedacartwright/sim1942 | 849a5da67c3925a448c0aaf02736067a8fd240a6 | [
"MIT"
] | null | null | null | #include "worker.h"
#include "sim1942.h"
#include "rexp.h"
#include <glibmm/timer.h>
#include <iostream>
#include <cassert>
#include <array>
Worker::Worker(int width, int height, double mu,int delay) :
grid_width_{width}, grid_height_{height}, mu_{mu},
pop_a_{new pop_t(width*height)},
pop_b_{new pop_t(width*height)},
rand{create_random_seed()},
delay_{delay}
{
}
void Worker::stop() {
go_ = false;
do_next_generation();
}
const double mutation[128] = {
2.0, 1.5, 1.2, 1.2, 1.2, 1.1, 1.1, 1.1, 1.1, 1.1, 1.1, 0.999, 0.999, 0.99, 0.99, 0.99,
0.95, 0.95, 0.95, 0.9, 0.9, 0.9, 1.0, 1.0, 1.0, 1.0, 1.0, 1.0, 1.0, 1.0, 1.0, 1.0,
1.0, 1.0, 1.0, 1.0, 1.0, 1.0, 1.0, 1.0, 1.0, 1.0, 1.0, 1.0, 1.0, 1.0, 1.0, 1.0,
1.0, 1.0, 1.0, 1.0, 1.0, 1.0, 1.0, 1.0, 1.0, 1.0, 1.0, 1.0, 1.0, 1.0, 1.0, 1.0,
1.0, 1.0, 1.0, 1.0, 1.0, 1.0, 1.0, 1.0, 1.0, 1.0, 1.0, 1.0, 1.0, 1.0, 1.0, 1.0,
1.0, 1.0, 1.0, 1.0, 1.0, 1.0, 1.0, 1.0, 1.0, 1.0, 1.0, 1.0, 1.0, 1.0, 1.0, 1.0,
1.0, 1.0, 1.0, 1.0, 1.0, 1.0, 1.0, 1.0, 1.0, 1.0, 1.0, 1.0, 1.0, 1.0, 1.0, 1.0,
1.0, 1.0, 1.0, 1.0, 1.0, 1.0, 1.0, 1.0, 1.0, 1.0, 1.0, 1.0, 1.0, 1.0, 1.0, 1.0
};
void Worker::do_work(Sim1942* caller)
{
static_assert(num_alleles < 256, "Too many colors.");
go_ = true;
next_generation_ = false;
gen_ = 0;
sleep(delay_);
std::array<int,num_colors> color_count;
std::vector<int> empty_colors(num_colors);
while(go_) {
Glib::Threads::RWLock::ReaderLock lock{data_lock_};
//boost::timer::auto_cpu_timer measure_speed(std::cerr, "do_work: " "%ws wall, %us user + %ss system = %ts CPU (%p%)\n");
const pop_t &a = *pop_a_.get();
pop_t &b = *pop_b_.get();
b = a;
color_count.fill(0);
for(int y=0;y<grid_height_;++y) {
for(int x=0;x<grid_width_;++x) {
int pos = x+y*grid_width_;
if(a[pos].is_null()) {
continue; // cell is null
}
double w;
double weight = a[pos].is_fertile() ? rand_exp(rand, a[pos].fitness) : INFINITY;
int pos2 = (x-1)+y*grid_width_;
if(x > 0 && a[pos2].is_fertile() && (w = rand_exp(rand, a[pos2].fitness)) < weight ) {
weight = w;
b[pos] = a[pos2];
}
pos2 = x+(y-1)*grid_width_;
if(y > 0 && a[pos2].is_fertile() && (w = rand_exp(rand, a[pos2].fitness)) < weight ) {
weight = w;
b[pos] = a[pos2];
}
pos2 = (x+1)+y*grid_width_;
if(x < grid_width_-1 && a[pos2].is_fertile() && (w = rand_exp(rand, a[pos2].fitness)) < weight ) {
weight = w;
b[pos] = a[pos2];
}
pos2 = x+(y+1)*grid_width_;
if(y < grid_height_-1 && a[pos2].is_fertile() && (w = rand_exp(rand, a[pos2].fitness)) < weight ) {
weight = w;
b[pos] = a[pos2];
}
color_count[b[pos].color()] += 1;
}
}
// Do Mutation
int pos = static_cast<int>(floor(rand_exp(rand,mu_)));
if(pos < grid_width_*grid_height_) {
// Setup colors since will will have to do at least one mutation
empty_colors.clear();
for(int color = 0; color < num_alleles; ++color) {
if(color_count[color] == 0)
empty_colors.emplace_back(color);
}
}
while(pos < grid_width_*grid_height_) {
// save pos
int opos = pos;
pos += static_cast<int>(floor(rand_exp(rand,mu_)));
if(!b[opos].is_fertile())
continue;
// mutate
uint64_t r = rand.get_uint64();
static_assert(sizeof(mutation)/sizeof(double) == 128, "number of possible mutations is not 128");
b[opos].fitness *= mutation[r >> 57]; // use top 7 bits for phenotype
r &= 0x01FFFFFFFFFFFFFF;
uint64_t color;
if(empty_colors.empty()) {
// Get the color of the parent
color = b[opos].color();
// Mutate color so that it does not match the parent
color = (color + r % (num_alleles-1)) % num_alleles;
} else {
// retrieve random empty color and erase it
int col = r % empty_colors.size();
color = empty_colors[col];
if(pos < grid_width_*grid_height_)
empty_colors.erase(empty_colors.begin()+col);
}
// Store the allele color in the bottom 8 bits.
b[opos].type = (b[opos].type & CELL_FITNESS_MASK) | color;
}
// Every so often rescale fitnesses to prevent underflow/overflow
if((1+gen_) % 10000 == 0) {
auto it = std::max_element(b.begin(),b.end());
double m = it->fitness;
if(m > 1e6) {
for(auto &aa : b) {
uint64_t color = aa.color();
aa.fitness = aa.fitness/m + (DBL_EPSILON/2.0);
aa.type = (aa.type & CELL_FITNESS_MASK) | color;
}
}
}
lock.release();
swap_buffers();
caller->notify_queue_draw();
Glib::Threads::Mutex::Lock slock{sync_mutex_};
while(!next_generation_) {
sync_.wait(sync_mutex_);
}
next_generation_ = false;
}
}
std::pair<pop_t,unsigned long long> Worker::get_data() {
Glib::Threads::RWLock::ReaderLock lock{data_lock_};
return {*pop_a_.get(),gen_};
}
void Worker::swap_buffers() {
Glib::Threads::RWLock::WriterLock lock{data_lock_};
gen_ += 1;
std::swap(pop_a_,pop_b_);
apply_toggles();
char buf[128];
std::snprintf(buf, 128, "%0.2fs: Generation %'llu done.\n", timer_.elapsed(), gen_);
std::cout << buf;
std::cout.flush();
}
void Worker::do_next_generation() {
Glib::Threads::Mutex::Lock lock{sync_mutex_};
next_generation_ = true;
sync_.signal();
}
void Worker::do_clear_nulls() {
Glib::Threads::Mutex::Lock lock{toggle_mutex_};
clear_all_nulls_ = true;
}
bool Worker::is_cell_valid(int x, int y) const {
return (0 <= x && x < grid_width_ && 0 <= y && y < grid_height_);
}
void Worker::toggle_cell(int x, int y, bool on) {
Glib::Threads::Mutex::Lock lock{toggle_mutex_};
if(is_cell_valid(x,y))
toggle_map_[{x,y}] = on;
}
// http://stackoverflow.com/a/4609795
template <typename T> int sgn(T val) {
return (T(0) < val) - (val < T(0));
}
// toggle a line beginning at {x1,y1} and ending at {x2,y2}
// assumes that {x1,y1} has already been toggled
void Worker::toggle_line(int x1, int y1, int x2, int y2, bool on) {
Glib::Threads::Mutex::Lock lock{toggle_mutex_};
int dx = x2 - x1;
int dy = y2 - y1;
if(dx == 0 && dy == 0) {
return;
}
if(abs(dx) > abs(dy)) {
int o = sgn(dx);
for(int d=o; d != dx; d += o) {
int nx = x1+d;
int ny = y1+(d*dy)/dx;
if(is_cell_valid(nx,ny))
toggle_map_[{nx,ny}] = on;
}
} else {
int o = sgn(dy);
for(int d=o; d != dy; d += o) {
int ny = y1+d;
int nx = x1+(d*dx)/dy;
if(is_cell_valid(nx,ny))
toggle_map_[{nx,ny}] = on;
}
}
if(is_cell_valid(x2,y2))
toggle_map_[{x2,y2}] = on;
}
void Worker::toggle_cells(const barriers_t & cells, bool on) {
Glib::Threads::Mutex::Lock lock{toggle_mutex_};
for(auto &&a : cells) {
int x = a.first;
int y = a.second;
if(is_cell_valid(x,y))
toggle_map_[{x,y}] = on;
}
}
const std::pair<int,int> erase_area_[] = {
{-1,0},{0,-1},{1,0},{0,1},
{-1,-1},{1,-1},{1,1},{-1,1}
};
void Worker::apply_toggles() {
Glib::Threads::Mutex::Lock lock{toggle_mutex_};
pop_t &a = *pop_a_.get();
if(clear_all_nulls_) {
toggle_map_.clear();
for(auto && pos : null_cells_) {
int x = pos.first;
int y = pos.second;
assert(is_cell_valid(x,y));
a[x+y*grid_width_].toggle_off();
}
null_cells_.clear();
clear_all_nulls_ = false;
return;
}
for(auto && cell : toggle_map_) {
int x = cell.first.first;
int y = cell.first.second;
assert(is_cell_valid(x,y));
if(cell.second) {
null_cells_.insert(cell.first);
a[x+y*grid_width_].toggle_on();
} else if(null_cells_.erase(cell.first) > 0) {
a[x+y*grid_width_].toggle_off();
} else {
for(auto && off : erase_area_) {
if(null_cells_.erase({cell.first.first+off.first,cell.first.second+off.second}) > 0) {
a[(x+off.first)+(y+off.second)*grid_width_].toggle_off();
break;
}
}
}
}
toggle_map_.clear();
}
| 33.465201 | 130 | 0.50613 | reedacartwright |
d029db8f1e67ea83c4f02d187a9c7e822bed729e | 10,375 | cpp | C++ | myodd/log/logfile.cpp | FFMG/myoddweb.piger | 6c5e9dff6ab8e2e02d6990c1959450f087acf371 | [
"MIT"
] | 18 | 2016-03-04T15:44:24.000Z | 2021-12-31T11:06:25.000Z | myodd/log/logfile.cpp | FFMG/myoddweb.piger | 6c5e9dff6ab8e2e02d6990c1959450f087acf371 | [
"MIT"
] | 49 | 2016-02-29T17:59:52.000Z | 2019-05-05T04:59:26.000Z | myodd/log/logfile.cpp | FFMG/myoddweb.piger | 6c5e9dff6ab8e2e02d6990c1959450f087acf371 | [
"MIT"
] | 2 | 2016-07-30T10:17:12.000Z | 2016-08-11T20:31:46.000Z | #include "stdafx.h"
#include "log.h"
#include "logfile.h"
#include <io.h>
#include <chrono>
#include "../math/math.h"
#include "../files/files.h"
// the maxfile size we want to use.
static size_t MAX_FILE_SIZE_IN_MEGABYTES = 5;
static const MYODD_CHAR* LogFile_default_Prefix = _T("myodd");
static const MYODD_CHAR* LogFile_default_Extention = _T("log");
namespace myodd{ namespace log{
LogFile::LogFile() :
m_fp( NULL ),
m_uCurrentSize( 0 ),
m_bInOpenCall( false ),
_maxFileSizeInMegabytes(MAX_FILE_SIZE_IN_MEGABYTES)
{
}
LogFile::~LogFile()
{
// close the log file.
Close();
}
/**
* Check if the log file is open or not.
* @param none
* @return bool if the log file is open or not.
*/
bool LogFile::IsOpen() const
{
return ( m_fp != NULL && !m_bInOpenCall );
}
struct tm LogFile::GetCurrentTimeStruct() const
{
// the current time.
auto timeNow = std::chrono::system_clock::now();
// to a time_t struct
auto tTime = std::chrono::system_clock::to_time_t(timeNow);
// to a tm structure.
return *localtime(&tTime);
}
/**
* Updated the started time of the log file.
* this will set the _tStarted structure.
*/
void LogFile::UpdateStartedTime()
{
// update the started time with the current structure.
_tStarted = GetCurrentTimeStruct();
}
/**
* Create the log file given the prefix and extension
* We will check that the file size if within limit
* And the date/time is up to date.
*/
bool LogFile::Create()
{
// is the file open already.
if (IsOpen())
{
return true;
}
// lock the current
if( m_bInOpenCall )
{
return false;
}
// we are in open call
// that way we can log things ourselves.
m_bInOpenCall = true;
bool bResult = false;
try
{
// get the time now.
UpdateStartedTime();
// look for a file that matches
for ( unsigned int i = 0;; ++i )
{
// get the log file.
MYODD_CHAR szDateLogStarted[40] = {};
_tcsftime(szDateLogStarted, _countof(szDateLogStarted), _T("%Y-%m-%d"), &_tStarted );
// add a number if the file number is > 0
// so we will create more than one file for today if need be.
MYODD_CHAR szFileCount[10] = {};
if (i > 0)
{
swprintf(szFileCount, _T("-%u"), i);
}
// we have already added a back slash at the end of the directory.
// the file could exist already.
std::wstring proposedCurrentFile = m_sDirectory + m_sPrefix + szDateLogStarted + szFileCount + _T(".") + m_sExtention;
double fileSizeInMegabytes = myodd::math::BytesToMegabytes(myodd::files::GetFileSizeInBytes(proposedCurrentFile));
if (fileSizeInMegabytes < GetMaxFileSizeInMegabytes())
{
m_sCurrentFile = proposedCurrentFile;
break;
}
}
// try and open the new file.
m_fp = _tfsopen(m_sCurrentFile.c_str(), _T("a+b"), _SH_DENYWR);
// did the file open?
if( NULL == m_fp )
{
myodd::log::LogError( _T("Could not open log file : \"%s\"."), m_sCurrentFile.c_str() );
bResult = false;
}
else
{
myodd::log::LogSuccess( _T("Log file, \"%s\", opened."), m_sCurrentFile.c_str() );
// get the size of the file.
m_uCurrentSize = _filelengthi64(_fileno(m_fp));
// is it a brand new file?
if( m_uCurrentSize == 0 )
{
// add the unicode byte order format.
fputwc(0xFEFF, m_fp);
}
#ifdef _DEBUG
// just make sure that we have the right format.
// if the file was changed by the user, then something will go wrong at some stage.
// but we cannot go around and police user misbehaving
//
// so the debug version will make sure that the app is not misbehaving.
else if (m_uCurrentSize >= sizeof(WORD))
{
WORD wBOM;
if (fread(&wBOM, sizeof(wBOM), 1, m_fp) == 1)
{
assert( wBOM == 0xFEFF );
}
}
#endif // Check for the UNICODE param
// go to the end of the file.
(void)fseek(m_fp, 0, SEEK_END);
}
// if we made it here, then it worked.
bResult = true;
}
catch ( ... )
{
bResult = false;
}
// we are no longer in open call.
m_bInOpenCall = false;
// return if this worked.
return bResult;
}
/**
* Ensure that the file is not too big and not out of date.
*/
void LogFile::ValidateDateAndSize()
{
if (!IsOpen())
{
return;
}
// recreate?
bool bRecreate = false;
// check the size.
double fileSizeInMegabytes = myodd::math::BytesToMegabytes(myodd::files::GetFileSizeInBytes( GetCurrentLogFile()));
if (fileSizeInMegabytes > GetMaxFileSizeInMegabytes())
{
bRecreate = true;
}
else
{
// get the current time and check if the file is out of date.
auto tStarted = GetCurrentTimeStruct();
// compare it to the started time.
auto tm = GetStartedDate();
if (tm.tm_yday != tStarted.tm_yday)
{
// close the old one and force a re-open
// this will force a check to be done.
bRecreate = true;
}
}
if (bRecreate)
{
// close the old file
Close();
// create a new one.
Create();
}
}
/**
* Open the file for login.
* @param none
* @return none
*/
bool LogFile::Open()
{
// is the file open already.
if (IsOpen())
{
return true;
}
// lock the current
if( m_bInOpenCall )
{
return false;
}
// we are in open call
// that way we can log things ourselves.
m_bInOpenCall = true;
// assume an error.
bool bResult = false;
try
{
// do we already know the name of the file?
if( m_sCurrentFile.empty() )
{
if( !Create() )
{
// there was a problem.
m_bInOpenCall = true;
return false;
}
}
// try and open the new file.
m_fp = _tfsopen(m_sCurrentFile.c_str(), _T("a+b"), _SH_DENYWR);
// get the size of the file.
m_uCurrentSize = _filelengthi64(_fileno(m_fp));
// go to the end of the file.
(void)fseek(m_fp, 0, SEEK_END);
// if we made it here, then it worked.
bResult = true;
}
catch ( ... )
{
bResult = false;
}
// we are no longer in open call.
m_bInOpenCall = false;
return bResult;
}
/**
* Close a log file.
* @param none
* @return bool if the file was closed or not.
*/
bool LogFile::Close()
{
// is it open?
if (!IsOpen())
{
return true;
}
// close it.
bool bResult = (fclose(m_fp) == 0);
m_fp = NULL;
m_uCurrentSize = 0;
return bResult;
}
/**
* Log an entry to the file.
* @param unsigned int uiType the log type
* @param const MYODD_CHAR* the line we are adding.
* @return bool success or not.
*/
bool LogFile::LogToFile( unsigned int uiType, const MYODD_CHAR* pszLine )
{
// are we logging?
if (m_sCurrentFile.empty())
{
return false;
}
if (!Open())
{
return false;
}
// check the size and date
ValidateDateAndSize();
bool bResult = false;
try
{
// get the current date so we can add it to the log.
auto tStarted = GetCurrentTimeStruct();
MYODD_CHAR szDateLogStarted[40];
_tcsftime(szDateLogStarted, _countof(szDateLogStarted), _T("%Y/%m/%d %H:%M:%S"), &tStarted );
// build the return message.
MYODD_STRING stdMsg = szDateLogStarted;
stdMsg += _T(" ") + myodd::strings::ToString( uiType, _T("%04d") );
stdMsg += _T(" ");
stdMsg += (pszLine ? pszLine : _T(""));
stdMsg += _T("\r\n");
const MYODD_CHAR* pszMsg = stdMsg.c_str();
// get the total size of what we are about to write..
size_t uToWrite = _tcslen(pszMsg) * sizeof(MYODD_CHAR);
// then we can write to the file.
size_t uWritten = fwrite(pszMsg, 1, uToWrite, m_fp);
// did it work?
bResult = !ferror(m_fp);
// get the file size.
m_uCurrentSize += uWritten;
}
catch( ... )
{
}
Close();
return bResult;
}
/**
* Set the log path directory.
* If we pass a NULL argument then we want to stop/disable the logging.
* @param const std::wstring& wPath the log path we will be using.
* @param const std::wstring& wPrefix the prefix of the filename we will create, (default is blank).
* @param const std::wstring& wExtention the file extension.
* @param size_t maxFileSize the max file size in megabytes.
* @return bool success or not
*/
bool LogFile::Initialise(const std::wstring& wPath, const std::wstring& wPrefix, const std::wstring& wExtention, size_t maxFileSize)
{
// close the file
Close();
// is the new, given path valid?
// or is the user telling us that they want to close it?
if( wPath.length() == 0 )
{
m_sPrefix = m_sExtention = m_sDirectory = _T("");
return true;
}
// set the prefix and extension.
// if the user is giving us some silly values then there is nothing we can do about really.
m_sPrefix = wPrefix.length() > 0 ? wPrefix : LogFile_default_Prefix;
m_sExtention = wExtention.length() > 0 ? wExtention : LogFile_default_Extention;
// It seems to be valid, so we can set the path here.
m_sDirectory = wPath;
// expand the file name
if (!myodd::files::ExpandEnvironment(m_sDirectory, m_sDirectory))
{
return false;
}
// add a trailing backslash
myodd::files::AddTrailingBackSlash( m_sDirectory );
// expand the path, in case the user changes their path or something.
if( !myodd::files::GetAbsolutePath( m_sDirectory, m_sDirectory, _T(".") ))
{
return false;
}
// expand the path, in case the user changes their path or something.
if( !myodd::files::CreateFullDirectory( m_sDirectory.c_str(), false ) )
{
return false;
}
// simply open the next file
// if there is a problem then nothing will log.
return Create();
}
} // log
} // myodd | 24.880096 | 134 | 0.586602 | FFMG |
d02abc89cb014d4c0f855ffb737f5786d45a8535 | 2,132 | cpp | C++ | NITIKA.cpp | yashji9/COMPETITIVE-PROGRAMMING | 5c7a255be9b01001ddcde8ca4e6ff4bcb1c62f0f | [
"MIT"
] | 2 | 2018-01-18T13:39:48.000Z | 2018-09-18T09:27:07.000Z | NITIKA.cpp | yashji9/COMPETITIVE-PROGRAMMING | 5c7a255be9b01001ddcde8ca4e6ff4bcb1c62f0f | [
"MIT"
] | null | null | null | NITIKA.cpp | yashji9/COMPETITIVE-PROGRAMMING | 5c7a255be9b01001ddcde8ca4e6ff4bcb1c62f0f | [
"MIT"
] | 2 | 2018-09-30T19:12:02.000Z | 2018-10-01T09:31:55.000Z | #include<iostream>
#include<string.h>
#include<ctype.h>
using namespace std;
int main()
{
int t;
cin>>t;
cin.ignore();
while(t--)
{
string s;
getline(cin,s);
char name[12],c,ch1,ch2;
int c1=0;
for(int i=0;s[i]!='\0';i++)
{
if(s[i]==' ')
c1++;
}
if(c1==0)
{
c=toupper(s[0]);
name[0]=c;
int i;
for(i=1;s[i]!='\0';i++)
{
c=tolower(s[i]);
name[i]=c;
}
name[i]='\0';
cout<<name<<endl;
}
else if(c1==1)
{
ch1=toupper(s[0]);
int j=0;
int flag=0;
for(int i=1;s[i]!='\0';i++)
{
if(s[i]==' ')
{
flag=1;
i++;
name[j]=toupper(s[i]);
j++;
}
else if(flag)
{
c=tolower(s[i]);
name[j]=c;
j++;
}
}
name[j]='\0';
cout<<ch1<<". "<<name<<endl;
}
else
{
ch1=toupper(s[0]);
int j=0;
int flag=0;
for(int i=1;s[i]!='\0';i++)
{
if(s[i]==' '&&flag==0)
{
i++;
ch2=toupper(s[i]);
flag=1;
}
else if(flag==1&&s[i]==' ')
{
flag=2;
i++;
name[j]=toupper(s[i]);
j++;
}
else if(flag==2)
{
c=tolower(s[i]);
name[j]=c;
j++;
}
}
name[j]='\0';
cout<<ch1<<". "<<ch2<<". "<<name<<endl;
}
}
}
| 21.535354 | 52 | 0.229362 | yashji9 |
d02fa762e7c129999f73e53a95ced23af429a711 | 34,360 | cpp | C++ | src/algorithms/three_edge_connected_components.cpp | meredith705/libsnarls | 1ebeb57a56a5bcd311055ee79ac008bbfa7b0adf | [
"MIT"
] | null | null | null | src/algorithms/three_edge_connected_components.cpp | meredith705/libsnarls | 1ebeb57a56a5bcd311055ee79ac008bbfa7b0adf | [
"MIT"
] | null | null | null | src/algorithms/three_edge_connected_components.cpp | meredith705/libsnarls | 1ebeb57a56a5bcd311055ee79ac008bbfa7b0adf | [
"MIT"
] | 1 | 2021-10-06T19:09:58.000Z | 2021-10-06T19:09:58.000Z | #include "snarls/algorithms/three_edge_connected_components.hpp"
#include <structures/union_find.hpp>
#include <limits>
#include <cassert>
#include <iostream>
#include <sstream>
//#define debug
namespace snarls {
namespace algorithms {
using namespace std;
void three_edge_connected_component_merges_dense(size_t node_count, size_t first_root,
const function<void(size_t, const function<void(size_t)>&)>& for_each_connected_node,
const function<void(size_t, size_t)>& same_component) {
// Independent implementation of Norouzi and Tsin (2014) "A simple 3-edge
// connected component algorithm revisited", which can't really be
// understood without Tsin (2007) "A Simple 3-Edge-Connected Component
// Algorithm".
// That algorithm assumes that all bridge edges are removed (i.e.
// everything is at least 2-connected), but we hack it a bit to generalize
// to graphs with bridge edges. It also assumes there are no self loops,
// but this implementation detects and allows self loops.
// The algorithm does a depth-first search through the graph, and is based
// on this "absorb-eject" operation. You do it at a node, across ("on") an
// edge. It (conceptually) steals all the edges from the node at the other
// end of the edge, deletes the edge, and deletes the other node as well if
// it has a degree greater than 2. (The original algorithm didn't have to
// deal with degree 1; here we treat it about the same as degree 2 and
// leave the node floating in its own 3 edge connected component, while
// hiding the single edge from the real logic of the algorithm.)
// Because of guarantees about the order in which we traverse the graph, we
// don't actually have to *do* any of the absorb-eject graph topology
// modifications. Instead, we just have to keep track of updates to nodes'
// "effective degree" in what would be the modified graph, and allow
// certain paths that we track during the algorithm to traverse the stolen
// edges.
// For each node, we keep track of a path. Because of guarantees we get
// from the algorithm, we know that paths can safely share tails. So to
// represent the tail of a path, we can just point to another node (or
// nowhere if the path ends). The head of a path is tougher, because a
// node's path can be empty. The node may not be on its own path. It is not
// immediately clear from analyzing the algorithm whether a node can have a
// nonempty path that it itself is not on, or be the tail of another node's
// path without being on that path. To support those cases, we also give
// each node a flag for whether it is on its own path.
// TODO: should we template this on an integer size so we can fit more work
// in less memory bandwidth when possible?
using number_t = size_t;
assert(node_count < numeric_limits<number_t>::max());
/// This defines the data we track for each node in the graph
struct TsinNode {
/// When in the DFS were we first visited?
number_t dfs_counter;
/// When in the DFS were we last visited?
/// Needed for finding replacement neighbors to implement path range
/// absorption in part 1.3, when we're asked for a range to a neighbor
/// that got eaten.
number_t dfs_exit;
/// What is our "low point" in the search. This is the earliest
/// dfs_counter for a node that this node or any node in its DFS
/// subtree has a back-edge to.
number_t low_point;
/// What is the effective degree of this node in the graph with all the
/// absorb-eject modifications applied?
number_t effective_degree = 0;
/// What node has the continuation of this node's path? If equal to
/// numeric_limits<number_t>::max(), the path ends after here.
/// The node's path is the path from this node, into its DFS subtree,
/// to (one of) the nodes in the subtree that has the back-edge that
/// caused this node's low point to be so low. Basically a low point
/// traceback.
number_t path_tail;
/// Is this node actually on its own path?
/// Nodes can be removed from their paths if those nodes don't matter
/// any more (i.e. got absorbed) but their paths still need to be tails
/// for other paths.
bool is_on_path;
/// Has the node been visited yet? Must be 0. TODO: Move to its own
/// vector to make zeroing them all free-ish with page table
/// shenanigans.
bool visited = false;
};
// We need to have all the nodes pre-allocated, so node references don't
// invalidate when we follow edges.
vector<TsinNode> nodes(node_count);
// We need to say how to absorb-eject along a whole path.
//
// We let you specify the node to absorb into; if it isn't
// numeric_limits<number_t>::max(), it is assumed to be the first node, and
// actually on the path, and path_start (if itself on its path) is also
// absorbed into it. This lets you absorb into a path with something
// prepended, without constructing the path.
//
// Similarly, we let you specify a past end to stop before. If this isn't
// numeric_limits<number_t>::max(), we stop and don't absorb the specified
// node, if we reach it. This lets us implement absorbing a range of a
// path, as called for in the algorithm.
//
// If you specify a past_end, and we never reach it, but also don't have
// just a single-node, no-edge "null" path, then something has gone wrong
// and we've violated known truths about the algorithm.
auto absorb_all_along_path = [&](number_t into, number_t path_start, number_t path_past_end) {
#ifdef debug
cerr << "(Absorbing all along path into " << into << " from " << path_start << " to before " << path_past_end << ")" << endl;
#endif
// Set this to false as soon as we cross an edge
bool path_null = true;
number_t here = path_start;
while (here != path_past_end) {
// Until we hit the end of the path
#ifdef debug
cerr << "(\tAt " << here << ")" << endl;
#endif
if (here == numeric_limits<number_t>::max()) {
// We hit the end of the path and never saw path_past_end.
#ifdef debug
cerr << "(\t\tReached path end and missed waypoint)" << endl;
#endif
// Only allowed if the path was actually edge-free and no merges needed to happen.
assert(path_null);
#ifdef debug
cerr << "(\t\t\tBut path was empty of edges)" << endl;
#endif
// Stop now.
break;
}
// Find the node we are at
auto& here_node = nodes[here];
if (here_node.is_on_path) {
// We're actually on the path.
#ifdef debug
cerr << "(\t\tOn path)" << endl;
#endif
if (into == numeric_limits<number_t>::max()) {
// We haven't found a first node to merge into yet; it is
// this one.
#ifdef debug
cerr << "(\t\tUse as into)" << endl;
#endif
into = here;
} else {
// We already have a first node to merge into, so merge.
#ifdef debug
cerr << "(\t\tMerge with " << into << ")" << endl;
#endif
// We are doing a merge! We'd better actually find the
// ending range bound, or something is wrong with our
// implementation of the algorithm.
path_null = false;
// Update the effective degrees as if we merged this node
// with the connected into node.
nodes[into].effective_degree = (nodes[into].effective_degree +
here_node.effective_degree - 2);
// Merge us into the same 3 edge connected component
same_component(into, here);
}
}
// Advance to the tail of the path
here = here_node.path_tail;
#ifdef debug
cerr << "(\t\tNext: " << here << ")" << endl;
#endif
}
#ifdef debug
cerr << "(Done absorbing)" << endl;
#endif
};
// For debugging, we need to be able to dump a node's stored path
auto path_to_string = [&](number_t node) {
stringstream s;
number_t here = node;
bool first = true;
while (here != numeric_limits<number_t>::max()) {
if (nodes[here].is_on_path) {
if (first && nodes[here].path_tail == numeric_limits<number_t>::max()) {
// Just a single node, no edge
s << "(just " << here << ")";
break;
}
if (first) {
first = false;
} else {
s << "-";
}
s << here;
}
here = nodes[here].path_tail;
}
return s.str();
};
// We need a DFS stack that we manage ourselves, to avoid stack-overflowing
// as we e.g. walk along big cycles.
struct DFSStackFrame {
/// Track the node that this stack frame represents
number_t current;
/// Track all the neighbors left to visit.
/// When we visit a neighbor we pop it off the back.
vector<number_t> neighbors;
/// When we look at the neighbors, we need to be able to tell the tree
/// edge to the parent from further back edges to the parent. So we
/// have a flag for whether we have seen the parent tree edge already,
/// and the first neighbors entry that is our parent will get called
/// the tree edge.
bool saw_parent_tree_edge = false;
/// Track whether we made a recursive DFS call into the last neighbor
/// or not. If we did, we need to do some work when we come out of it
/// and return to this frame.
bool recursing = false;
};
vector<DFSStackFrame> stack;
// We need a way to produce unvisited nodes when we run out of nodes in a
// connected component. This will always point to the next unvisited node
// in order. If it points to node_count, all nodes are visited. When we
// fisit this node, we have to scan ahead for the next unvisited node, in
// number order.
number_t next_unvisited = 0;
// We also keep a global DFS counter, so we don't have to track parent
// relationships when filling it in on the nodes.
//
// The paper starts it at 1, so we do too.
number_t dfs_counter = 1;
while (next_unvisited != node_count) {
// We haven't visited everything yet.
if (!nodes[first_root].visited) {
// If possible start at the suggested root
stack.emplace_back();
stack.back().current = first_root;
} else {
// Stack up the next unvisited node.
stack.emplace_back();
stack.back().current = next_unvisited;
}
#ifdef debug
cerr << "Root a search at " << stack.back().current << endl;
#endif
while (!stack.empty()) {
// While there's still nodes on the DFS stack from the last component we broke into
// Grab the stack frame.
// Note that this reference will be invalidated if we add stuff to the stack!
auto& frame = stack.back();
// And the current node
auto& node = nodes[frame.current];
if (!node.visited) {
// This is the first time we are in this stack frame. We need
// to do the initial visit of the node and set up the frame
// with the list of edges to do.
node.visited = true;
#ifdef debug
cerr << "First visit of node " << frame.current << endl;
#endif
if (frame.current == next_unvisited) {
// We need to find the next unvisited node, if any, since
// we just visited what it used to be.
do {
next_unvisited++;
} while (next_unvisited != node_count && nodes[next_unvisited].visited);
}
node.dfs_counter = dfs_counter;
dfs_counter++;
node.low_point = node.dfs_counter;
// Make sure the node's path is just itself
node.path_tail = numeric_limits<number_t>::max();
node.is_on_path = true;
#ifdef debug
cerr << "\tDFS: " << node.dfs_counter
<< " low point: " << node.low_point
<< " degree: " << node.effective_degree
<< " path: " << path_to_string(frame.current) << endl;
#endif
// Stack up all the edges to follow.
for_each_connected_node(frame.current, [&](size_t connected) {
frame.neighbors.push_back(connected);
});
#ifdef debug
cerr << "\tPut " << frame.neighbors.size() << " edges on to do list" << endl;
#endif
// Now we're in a state where we can process edges.
// So kick back to the work loop as if we just processed an edge.
continue;
} else {
// We have (possibly 0) edges left to do for this node.
if (!frame.neighbors.empty()) {
#ifdef debug
cerr << "Return to node " << frame.current << " with more edges to do" << endl;
cerr << "\tDFS: " << node.dfs_counter
<< " low point: " << node.low_point
<< " degree: " << node.effective_degree
<< " path: " << path_to_string(frame.current) << endl;
#endif
// We have an edge to do!
// Look up the neighboring node.
number_t neighbor_number = frame.neighbors.back();
auto& neighbor = nodes[neighbor_number];
if (!frame.recursing) {
// This is the first time we are thinking about this neighbor.
#ifdef debug
cerr << "\tThink of edge to neighbor " << neighbor_number << " for the first time" << endl;
#endif
// Increment degree of the node we're coming from
node.effective_degree++;
#ifdef debug
cerr << "\t\tBump degree to " << node.effective_degree << endl;
#endif
if (!neighbor.visited) {
// We need to recurse on this neighbor.
#ifdef debug
cerr << "\t\tRecurse on unvisited neighbor" << endl;
#endif
// So remember we are recursing.
frame.recursing = true;
// And set up the recursive frame.
stack.emplace_back();
stack.back().current = neighbor_number;
// Kick back to the work loop; we will see the
// unvisited node on top of the stack and do its
// visit and add its edges to its to do list.
} else {
// No need to recurse.This is either a back-edge or the back side of the tree edge to the parent.
if (stack.size() > 1 && neighbor_number == stack[stack.size() - 2].current && !frame.saw_parent_tree_edge) {
// This is the edge we took to get here (tree edge)
#ifdef debug
cerr << "\t\tNeighbor is parent; this is the tree edge in." << endl;
#endif
// For tree edges, since they aren't either kind of back edge, neither 1.2 nor 1.3 fires.
// But the next edge to the parent will be a back edge.
frame.saw_parent_tree_edge = true;
} else if (neighbor.dfs_counter < node.dfs_counter) {
// The edge to the neighbor is an outgoing
// back-edge (i.e. the neighbor was visited
// first). Paper step 1.2.
#ifdef debug
cerr << "\t\tNeighbor is upstream of us (outgoing back edge)." << endl;
#endif
if (neighbor.dfs_counter < node.low_point) {
// The neighbor is below our low point.
#ifdef debug
cerr << "\t\t\tNeighbor has a lower low point ("
<< neighbor.dfs_counter << " < " << node.low_point << ")" << endl;
cerr << "\t\t\t\tAbsorb along path to old low point source" << endl;
#endif
// Absorb along our whole path.
absorb_all_along_path(numeric_limits<number_t>::max(),
frame.current,
numeric_limits<number_t>::max());
// Adopt the neighbor's DFS counter as our
// new, lower low point.
node.low_point = neighbor.dfs_counter;
#ifdef debug
cerr << "\t\t\t\tNew lower low point " << node.low_point << endl;
#endif
// Our path is now just us.
node.is_on_path = true;
node.path_tail = numeric_limits<number_t>::max();
#ifdef debug
cerr << "\t\t\t\tNew path " << path_to_string(frame.current) << endl;
#endif
} else {
#ifdef debug
cerr << "\t\t\tWe have a sufficiently low low point" << endl;
#endif
}
} else if (node.dfs_counter < neighbor.dfs_counter) {
// The edge to the neighbor is an incoming
// back-edge (i.e. we were visited first, but
// we recursed into something that got us to
// this neighbor already). Paper step 1.3.
#ifdef debug
cerr << "\t\tWe are upstream of neighbor (incoming back edge)." << endl;
#endif
// Drop our effective degree by 2 (I think
// we're closing a cycle or something?)
node.effective_degree -= 2;
#ifdef debug
cerr << "\t\t\tDrop degree to " << node.effective_degree << endl;
cerr << "\t\t\tWant to absorb along path towards low point source through neighbor" << endl;
#endif
// Now, the algorithm says to absorb
// "P_w[w..u]", a notation that it does not
// rigorously define. w is here, and u is the
// neighbor. The neighbor is not necessarily
// actually *on* our path at this point, not
// least of which because the neighbor may have
// already been eaten and merged into another
// node, which in theory adopted the back edge
// we are looking at. In practice we don't have
// the data structure to find that node. So
// here's the part where we have to do
// something clever to "allow certain paths
// that we track to traverse the stolen edges".
// What we have to do is find the node that
// *is* along our path that either is or ate
// the neighbor. We don't track the union-find
// logic we would need to answer that question,
// but both 2007 algorithm implementations I've
// seen deal with this by tracking DFS counter
// intervals/subtree sizes, and deciding that
// the last thin on our path visited no later
// than the neighbor, and exited no earlier
// than the neighbor (i.e. the last ancestor of
// the neighbor on our path) should be our
// replacement neighbor.
// This makes sense because if the neighbor
// merged into anything, it's an ancestor of
// the neighbor. So we go looking for it.
// TODO: let absorb_all_along_path do this instead?
// Start out with ourselves as the replacement neighbor ancestor.
number_t replacement_neighbor_number = frame.current;
// Consider the next candidate
number_t candidate = nodes[replacement_neighbor_number].path_tail;
while (candidate != numeric_limits<number_t>::max() &&
nodes[candidate].dfs_counter <= neighbor.dfs_counter &&
nodes[candidate].dfs_exit >= neighbor.dfs_exit) {
// This candidate is a lower ancestor of the neighbor, so adopt it.
replacement_neighbor_number = candidate;
candidate = nodes[replacement_neighbor_number].path_tail;
}
auto& replacement_neighbor = nodes[replacement_neighbor_number];
#ifdef debug
cerr << "\t\t\tNeighbor currently belongs to node " << replacement_neighbor_number << endl;
cerr << "\t\t\tAbsorb along path towards low point source through there" << endl;
#endif
// Absorb along our path from ourselves to the
// replacement neighbor, inclusive.
// Ignores trivial paths.
absorb_all_along_path(numeric_limits<number_t>::max(),
frame.current,
replacement_neighbor.path_tail);
// We also have to (or at least can) adopt the
// path of the replacement neighbor as our own
// path now. That's basically the rest of the
// path that we didn't merge.
// This isn't mentioned in the paper either,
// but I've seen the official implementation do
// it, and if we don't do it our path is going
// to go through a bunch of stuff we already
// merged, and waste time when we merge again.
// If we ever merge us down our path again,
// continue with the part we didn't already
// eat.
node.path_tail = replacement_neighbor.path_tail;
} else {
// The other possibility is the neighbor is just
// us. Officially self loops aren't allowed, so
// we censor the edge.
#ifdef debug
cerr << "\t\tWe are neighbor (self loop). Hide edge!" << endl;
#endif
node.effective_degree--;
}
// Clean up the neighbor from the to do list; we
// finished it without recursing.
frame.neighbors.pop_back();
// Kick back to the work loop to do the next
// neighbor, if any.
}
} else {
// We have returned from a recursive call on this neighbor.
#ifdef debug
cerr << "\tReturned from recursion on neighbor " << neighbor_number << endl;
#endif
// Support bridge edges: detect if we are returning
// across a bridge edge and censor it. Norouzi and Tsin
// 2014 as written in the paper assumes no bridge
// edges, and what we're about to do relies on all
// neighbors connecting back somewhere.
if (neighbor.low_point == neighbor.dfs_counter) {
// It has no back-edges out of its own subtree, so it must be across a bridge.
#ifdef debug
cerr << "\t\tNeighbor is across a bridge edge! Hide edge!" << endl;
#endif
// Hide the edge we just took from degree calculations.
neighbor.effective_degree--;
node.effective_degree--;
// Don't do anything else with the edge
} else {
// Wasn't a bridge edge, so we care about more than just traversing that part of the graph.
// Do steps 1.1.1 and 1.1.2 of the algorithm as described in the paper.
if (neighbor.effective_degree == 2) {
// This neighbor gets absorbed and possibly ejected.
#ifdef debug
cerr << "\t\tNeighbor is on a stick" << endl;
cerr << "\t\t\tEdge " << frame.current << "-" << neighbor_number << " should never be seen again" << endl;
#endif
// Take it off of its own path.
neighbor.is_on_path = false;
#ifdef debug
cerr << "\t\t\tNew neighbor path: " << path_to_string(neighbor_number) << endl;
#endif
}
// Because we hid the bridge edges, degree 1 nodes should never happen
assert(neighbor.effective_degree != 1);
if (node.low_point <= neighbor.low_point) {
#ifdef debug
cerr << "\t\tWe have a sufficiently low low point; neighbor comes back in in our subtree" << endl;
cerr << "\t\t\tAbsorb us and then the neighbor's path to the end" << endl;
#endif
// Absorb all along the path starting with here and
// continuing with this neighbor's path, to the
// end.
absorb_all_along_path(frame.current,
neighbor_number,
numeric_limits<number_t>::max());
} else {
#ifdef debug
cerr << "\t\tNeighbor has a lower low point ("
<< neighbor.low_point << " < " << node.low_point << "); comes back in outside our subtree" << endl;
#endif
// Lower our low point to that of the neighbor
node.low_point = neighbor.low_point;
#ifdef debug
cerr << "\t\t\tNew low point: " << node.low_point << endl;
cerr << "\t\t\tAbsorb along path to old low point soure" << endl;
#endif
// Absorb all along our own path
absorb_all_along_path(numeric_limits<number_t>::max(),
frame.current,
numeric_limits<number_t>::max());
// Adjust our path to be us and then our neighbor's path
node.is_on_path = true;
node.path_tail = neighbor_number;
#ifdef debug
cerr << "\t\t\tNew path " << path_to_string(frame.current) << endl;
#endif
}
}
// Say we aren't coming back from a recursive call
// anymore.
frame.recursing = false;
// Clean up the neighbor,
frame.neighbors.pop_back();
// Kick back to the work loop to do the next neighbor,
// if any.
}
#ifdef debug
cerr << "\tDFS: " << node.dfs_counter
<< " low point: " << node.low_point
<< " degree: " << node.effective_degree
<< " path: " << path_to_string(frame.current) << endl;
#endif
} else {
// All the neighbors left to do for this node are done.
#ifdef debug
cerr << "\tNode is visited and no neighbors are on the to do list." << endl;
cerr << "\tDFS: " << node.dfs_counter
<< " low point: " << node.low_point
<< " degree: " << node.effective_degree
<< " path: " << path_to_string(frame.current) << endl;
#endif
// This node is done.
// Remember when we exited it
node.dfs_exit = dfs_counter;
// Clean up the stack frame.
stack.pop_back();
}
}
}
}
// When we run out of unvisited nodes and the stack is empty, we've
// completed out search through all connected components of the graph.
}
void three_edge_connected_components_dense(size_t node_count, size_t first_root,
const function<void(size_t, const function<void(size_t)>&)>& for_each_connected_node,
const function<void(const function<void(const function<void(size_t)>&)>&)>& component_callback) {
// Make a union-find over all the nodes
structures::UnionFind uf(node_count, true);
// Call Tsin's Algorithm
three_edge_connected_component_merges_dense(node_count, first_root, for_each_connected_node, [&](size_t a, size_t b) {
// When it says to do a merge, do it
uf.union_groups(a, b);
});
for (auto& component : uf.all_groups()) {
// Call the callback for each group
component_callback([&](const function<void(size_t)>& emit_member) {
// And whrn it asks for the members
for (auto& member : component) {
// Send them all
emit_member(member);
}
});
}
}
}
}
| 47.855153 | 138 | 0.472934 | meredith705 |
d035a85216f35451abf857aec3f1e70f4c974c4e | 2,663 | cpp | C++ | CodechefCodes/MSTICK.cpp | debashish05/competitive_programming | e2c0a7a741ac988e4393eda3b5006d6b8c88a5a9 | [
"MIT"
] | null | null | null | CodechefCodes/MSTICK.cpp | debashish05/competitive_programming | e2c0a7a741ac988e4393eda3b5006d6b8c88a5a9 | [
"MIT"
] | null | null | null | CodechefCodes/MSTICK.cpp | debashish05/competitive_programming | e2c0a7a741ac988e4393eda3b5006d6b8c88a5a9 | [
"MIT"
] | null | null | null | #include<bits/stdc++.h>
#define ll long long int
#define loop(k) for(i=0;i<k;++i)
#define loop2(k,l) for(j=k;j<l;++j)
#define mod 100000000
using namespace std;
int main()
{
std::ios_base::sync_with_stdio(false);//cin.tie(NULL);
ll t=1,i=0,j=0;
//cin>>t;
while(t--){
int n;cin>>n;
ll a[n];
loop(n)cin>>a[i];
int len=(int)sqrt(n)+1;
ll bmax[len]={0},bmin[len];
loop(len)bmin[i]=100000000;
loop(n){
bmax[i/len]=max(bmax[i/len],a[i]);
}
loop(n){
bmin[i/len]=min(bmin[i/len],a[i]);
}
int q;cin>>q;
while(q--){
int l,r;
cin>>l>>r;
int r1=r;
double max=a[l],min=a[l];
ll lt=l/len,rt=r/len;
if(lt==rt){ //find max and min bw l r
for(i=l;i<=r;++i){
if(a[i]>max)max=a[i];
if(a[i]<min)min=a[i];
}
}
else{
for(i=l;i<(lt+1)*len;++i){
if(a[i]>max)max=a[i];
if(a[i]<min)min=a[i];
}
for(i=lt+1;i<rt;++i){
if(bmax[i]>max)max=bmax[i];
if(bmin[i]<min)min=bmin[i];
}
for(i=rt*len;i<=r;++i){
if(a[i]>max)max=a[i];
if(a[i]<min)min=a[i];
}
}
double maxout=0; //find out max in array a excluding l to r
r=l-1;l=0;
if(r>=0){
rt=r/len;lt=l/len; //0-l-1
if(lt==rt){
for(i=l;i<=r;++i){
if(a[i]>maxout)maxout=a[i];
}
}
else{
for(i=l;i<(lt+1)*len;++i){
if(a[i]>maxout)maxout=a[i];
}
for(i=lt+1;i<rt;++i){
if(bmax[i]>maxout)maxout=bmax[i];
}
for(i=rt*len;i<=r;++i){
if(a[i]>maxout)maxout=a[i];
}
}
}
l=r1+1;r=n-1;
if(l<=n-1){
rt=r/len;lt=l/len;
if(lt==rt){
for(i=l;i<=r;++i){
if(a[i]>maxout)maxout=a[i];
}
}
else{
for(i=l;i<(lt+1)*len;++i){
if(a[i]>maxout)maxout=a[i];
}
for(i=lt+1;i<rt;++i){
if(bmax[i]>maxout)maxout=bmax[i];
}
for(i=rt*len;i<=r;++i){
if(a[i]>maxout)maxout=a[i];
}
}
}
//cout<<maxout<<" "<<min<<" "<<max<<"\n";
double temp=maxout+min;
max-=min;
double temp2=min+max/2;
//cout<<temp<<" "<<temp2<<"\n";
if(temp<temp2)temp=temp2;
cout<<fixed<<setprecision(1)<<temp<<"\n";
}
}
return 0;
}
| 25.605769 | 68 | 0.38528 | debashish05 |
d03813c0a96da1a770e70bf10fc0e8e94b666430 | 1,913 | hpp | C++ | C++ Development Root/SourceCode/Domain/Subscription/SubscriptionHandler.hpp | Dpham181/CPSC-462-GROUP-2 | 36f55ec4980e2e98d58f1f0a63ecc5070d7faa47 | [
"MIT"
] | 1 | 2021-05-19T06:35:15.000Z | 2021-05-19T06:35:15.000Z | C++ Development Root/SourceCode/Domain/Subscription/SubscriptionHandler.hpp | Dpham181/CPSC-462-GROUP-2 | 36f55ec4980e2e98d58f1f0a63ecc5070d7faa47 | [
"MIT"
] | null | null | null | C++ Development Root/SourceCode/Domain/Subscription/SubscriptionHandler.hpp | Dpham181/CPSC-462-GROUP-2 | 36f55ec4980e2e98d58f1f0a63ecc5070d7faa47 | [
"MIT"
] | null | null | null | #pragma once
#include <any>
#include <memory> // unique_ptr
#include <stdexcept> // runtime_error
#include <string>
#include <vector> // domain_error, runtime_error
#include "TechnicalServices/Persistence/PersistenceHandler.hpp"
namespace Domain::Subscription
{
using TechnicalServices::Persistence::UserCredentials;
using TechnicalServices::Persistence::Subcripstion;
using TechnicalServices::Persistence::PaymentOption;
using TechnicalServices::Persistence::SubscriptionStatus;
using TechnicalServices::Persistence::Paid;
// Product Package within the Domain Layer Abstract class
class SubscriptionHandler
{
public:
static std::unique_ptr<SubscriptionHandler> MaintainSubscription( const UserCredentials& User);
// Operations menu
virtual std::vector<std::string> getCommandsSubscription() =0; // retrieves the list of actions (commands)
virtual std::any executeCommandSubscription(const std::string& command, const std::vector<std::string>& args) =0; // executes one of the actions retrieved
// Operations of Maintain Subscription
// default operations
virtual SubscriptionStatus viewSubscriptionStatus() = 0 ;
virtual std::vector<PaymentOption> selectSubscription(const int SelectedId) = 0;
virtual std::string completePayment() = 0;
virtual bool verifyPaymentInformation( const std::string CCnumber, const int CVCnumber) = 0;
virtual ~SubscriptionHandler() noexcept = 0;
protected:
// Copy assignment operators, protected to prevent mix derived-type assignments
SubscriptionHandler&
operator=( const SubscriptionHandler& rhs ) = default; // copy assignment
SubscriptionHandler& operator=(SubscriptionHandler&& rhs ) = default; // move assignment
}; // class SubscriptionHandler
} // namespace Domain:: Subscription
| 39.854167 | 177 | 0.723471 | Dpham181 |
d03816ec0b0945bc98e9139da6daa3df998bcf13 | 4,617 | cpp | C++ | common/filesystem.cpp | Thalhammer/pve-simple-container | bfe7e72961fe6ae350587c71c71ef1be8e5fd5f5 | [
"MIT"
] | 1 | 2020-05-12T03:17:51.000Z | 2020-05-12T03:17:51.000Z | common/filesystem.cpp | Thalhammer/pve-simple-container | bfe7e72961fe6ae350587c71c71ef1be8e5fd5f5 | [
"MIT"
] | 6 | 2018-09-08T13:00:49.000Z | 2019-02-12T13:43:23.000Z | common/filesystem.cpp | Thalhammer/pve-simple-container | bfe7e72961fe6ae350587c71c71ef1be8e5fd5f5 | [
"MIT"
] | null | null | null | #include "filesystem.h"
#include <cstdlib>
#include <experimental/filesystem>
#include <fstream>
#include <unistd.h>
#include <sys/types.h>
#include <pwd.h>
#include "string_helper.h"
#include <regex>
namespace fs = std::experimental::filesystem;
namespace pvesc {
namespace common {
std::string filesystem::create_temporary_directory(const std::string& tpl)
{
char buf[tpl.size() + 1];
std::string::traits_type::copy(buf, tpl.c_str(), tpl.size());
buf[tpl.size()] = 0x00;
auto res = mkdtemp(buf);
if(res == nullptr) throw std::runtime_error("Failed to temporary create directory:" + std::to_string(errno));
else return res;
}
void filesystem::delete_directory(const std::string& dir)
{
for(auto& p: fs::directory_iterator(dir)) {
if(p.status().type() == fs::file_type::directory) {
delete_directory(p.path());
} else {
if(!fs::remove(p.path())) throw std::runtime_error("Failed to remove directory");
}
}
if(!fs::remove(dir)) throw std::runtime_error("Failed to remove directory");
}
void filesystem::copy_file(const std::string& source, const std::string& dest) {
fs::path pdest(dest);
if (!fs::is_directory(pdest.parent_path()) && !fs::create_directories(pdest.parent_path())) throw std::runtime_error("Failed to create directory");
if (!fs::copy_file(source, dest)) throw std::runtime_error("Failed to copy file");
}
std::map<std::string, std::string> filesystem::glob_files(const std::string& glob, const std::string& dest) {
auto pos = glob.find('*');
pos = std::min(pos, glob.find('?'));
if(pos != std::string::npos) {
auto regex = glob;
auto base = glob;
pos = glob.substr(0, pos).find_last_of('/');
if(pos == std::string::npos) base = ".";
else {
base = base.substr(0, pos + 1);
}
common::replace(regex, ".", "\\.");
common::replace(regex, "*", "(.*)");
common::replace(regex, "?", "(.)");
std::regex reg("^" + regex + "$");
std::smatch matches;
std::map<std::string, std::string> res;
for(auto& p : fs::recursive_directory_iterator(base)) {
auto path = p.path().string();
if(std::regex_match(path, matches, reg)) {
res.insert({path, matches.format(dest)});
}
}
return res;
} else return {{glob, dest}};
}
void filesystem::create_directories(const std::string& dir) {
if (!fs::is_directory(dir) && !fs::create_directories(dir)) throw std::runtime_error("Failed to create directory");
}
std::string filesystem::current_directory() {
return fs::current_path().string();
}
size_t filesystem::tree_size(const std::string& dir) {
size_t size = 0;
for(auto& p : fs::recursive_directory_iterator(dir)) {
if(p.symlink_status().type() == fs::file_type::regular) {
auto s = fs::file_size(p.path());
size += s;
} else size += 4096;
}
return size;
}
bool filesystem::try_read_file(const std::string& fname, std::string& out) {
if(fs::exists(fname)) {
std::ifstream stream(fname, std::ios::binary);
if(stream) {
out = read_stream(stream);
return true;
}
}
return false;
}
std::string filesystem::read_stream(std::istream& stream) {
std::string res;
while(!stream.eof()) {
char buf[4096];
auto size = stream.read(buf, sizeof(buf)).gcount();
res += std::string(buf, buf + size);
}
return res;
}
std::string filesystem::read_file(const std::string& path) {
std::ifstream stream(path, std::ios::binary);
if(!stream) throw std::runtime_error("Failed to open file");
return read_stream(stream);
}
std::string filesystem::get_home_directory() {
auto homedir = getenv("HOME");
if(homedir == nullptr) {
struct passwd pwd;
struct passwd *result;
int s;
size_t bufsize = sysconf(_SC_GETPW_R_SIZE_MAX);
if (bufsize == size_t(-1))
bufsize = 0x4000; // = all zeroes with the 14th bit set (1 << 14)
std::string buf(bufsize, '\0');
s = getpwuid_r(getuid(), &pwd, (char*)buf.data(), buf.size(), &result);
if (result == NULL) {
if (s == 0)
throw std::runtime_error("Failed to get home directory: user not found");
else {
throw std::runtime_error("Failed to get home directory:" + std::to_string(s));
}
}
homedir = result->pw_dir;
}
return homedir;
}
bool filesystem::exists(const std::string& path) {
return fs::exists(path);
}
void filesystem::make_executable(const std::string& path) {
fs::permissions(path, fs::status(path).permissions() | fs::perms::group_exec | fs::perms::others_exec | fs::perms::owner_exec);
}
}
} | 31.408163 | 150 | 0.632012 | Thalhammer |
d03b4fa828cf3f58853c1f36b32e379562622a20 | 755 | cpp | C++ | C_C++_Projects/BAPS Contest/charlie/drunkenbinary.cpp | sunjerry019/RandomCodes | 4402604aaeee63bb1ce6fa962c496b438bb17e50 | [
"MIT"
] | null | null | null | C_C++_Projects/BAPS Contest/charlie/drunkenbinary.cpp | sunjerry019/RandomCodes | 4402604aaeee63bb1ce6fa962c496b438bb17e50 | [
"MIT"
] | null | null | null | C_C++_Projects/BAPS Contest/charlie/drunkenbinary.cpp | sunjerry019/RandomCodes | 4402604aaeee63bb1ce6fa962c496b438bb17e50 | [
"MIT"
] | null | null | null | #include <bits/stdc++.h>
using namespace std;
long long arr[1000000];
int r(int x){
long long ans;
if(x==0)
ans=1;
else if(x<1000000&&arr[x]!=-1)
return arr[x];
else if(x%2==1)
ans=r(x/2);
else ans=r(x/2)+r(x/2-1);
if(x<1000000)
arr[x]=ans;
return ans;
}
int main(){
int n,tc;
scanf("%d %d",&n,&tc);
int i,j;
for(int i=0;i<1000000;i++){
arr[i]=-1;
}
// printf("%d",r(4));
for(int i=0;i<1000000;i++){
r(i);
}
for (int ii=0;ii<tc;ii++){
scanf("%d %d",&i,&j);
if(i==j)
printf("%d\n",0);
else if(i==0)
printf("%d\n",(int)floor(sqrt(r(j))));
else if(r(j)-r(i)>0)
printf("%d\n",(int)floor(sqrt(r(j)-r(i))));
else
printf("%d\n",(int)-floor(sqrt(r(i)-r(j))));
}
}
| 18.414634 | 47 | 0.490066 | sunjerry019 |
d03bb81d8ae81df9c7ffa78f6931d124b66881d9 | 1,542 | hpp | C++ | include/Framework/Button.hpp | AdlanSADOU/SDL_Space | b8c72b50942b939be0207d8ecd9c924d1124ceb7 | [
"Unlicense"
] | 1 | 2020-08-20T17:42:11.000Z | 2020-08-20T17:42:11.000Z | include/Framework/Button.hpp | AdlanSADOU/SDL_Space | b8c72b50942b939be0207d8ecd9c924d1124ceb7 | [
"Unlicense"
] | null | null | null | include/Framework/Button.hpp | AdlanSADOU/SDL_Space | b8c72b50942b939be0207d8ecd9c924d1124ceb7 | [
"Unlicense"
] | null | null | null | /*
** EPITECH PROJECT, 2020
** SDL_Space
** File description:
** Button
*/
#ifndef BUTTON_HPP_
#define BUTTON_HPP_
#include "Entity.hpp"
enum buttonState {
IDLE,
HOVER,
CLICKED
};
class Button : public Entity {
public:
Button();
Button(SDL_Renderer *renderer);
Button(SDL_Renderer *renderer, float x, float y, float width, float height);
void Update();
void Draw();
void SetPosition(float x, float y);
SDL_FRect GetPosition();
void SetColorIdle(Uint8 r, Uint8 g, Uint8 b, Uint8 a);
void SetColorHover(Uint8 r, Uint8 g, Uint8 b, Uint8 a);
void SetColorClicked(Uint8 r, Uint8 g, Uint8 b, Uint8 a);
void SetTexture(const char *path);
void SetRenderer(SDL_Renderer *renderer);
void SetEvent(SDL_Event *event);
void SetState(buttonState state);
void UpdateTexture(SDL_Surface *surface);
void UpdateHoverState();
void UpdateClickedState();
void UpdateColorFromState();
private:
SDL_Surface *background_surface_idle;
SDL_Surface *background_surface_hover;
SDL_Surface *background_surface_clicked;
SDL_FRect background_rect;
SDL_Texture *texture;
SDL_Renderer *renderer;
buttonState state;
SDL_Event *event;
};
#endif /* !BUTTON_HPP_ */
| 25.7 | 96 | 0.568093 | AdlanSADOU |
d04040dee2c4d38af49b4f205f073a872d53cc66 | 2,548 | cpp | C++ | src/parser/mode/createCoroutine.cpp | tositeru/watagashi | d4fcfbb4a7f44fcbf68652e7d99a4b13c6e035d4 | [
"MIT"
] | null | null | null | src/parser/mode/createCoroutine.cpp | tositeru/watagashi | d4fcfbb4a7f44fcbf68652e7d99a4b13c6e035d4 | [
"MIT"
] | null | null | null | src/parser/mode/createCoroutine.cpp | tositeru/watagashi | d4fcfbb4a7f44fcbf68652e7d99a4b13c6e035d4 | [
"MIT"
] | null | null | null | #include "createCoroutine.h"
#include "../line.h"
#include "../enviroment.h"
#include "normal.h"
namespace parser
{
IParseMode::Result CreateCoroutineParseMode::parse(Enviroment& env, Line& line)
{
if (line.length() <= 0) {
return Result::Continue;
}
switch (env.currentScope().type()) {
case IScope::Type::Normal: return parseDefault(env, line);
case IScope::Type::CallFunctionArguments: return parseArguments(env, line);
default:
AWESOME_THROW(std::runtime_error) << "unknown parse mode...";
}
return Result::Continue;
}
IParseMode::Result CreateCoroutineParseMode::parseDefault(Enviroment& env, Line line)
{
if (env.currentScope().valueType() != Value::Type::Coroutine) {
AWESOME_THROW(FatalException) << "The scope of CreateCoroutineParseMode must have Coroutine value.";
}
auto& coroutine = env.currentScope().value().get<Value::coroutine>();
auto[opStart, opEnd] = line.getRangeSeparatedBySpace(0);
auto callOperator = toCallFunctionOperaotr(line.substr(opStart, opEnd));
switch (callOperator) {
case CallFunctionOperator::ByUsing:
env.pushScope(std::make_shared<CallFunctionArgumentsScope>(env.currentScope(), coroutine.pFunction->arguments.size()));
return this->parseArguments(env, Line(line, opEnd));
break;
default:
AWESOME_THROW(SyntaxException) << "unknown operator...";
break;
}
return Result::Continue;
}
IParseMode::Result CreateCoroutineParseMode::parseArguments(Enviroment& env, Line line)
{
auto pCurrentScope = dynamic_cast<CallFunctionArgumentsScope*>(env.currentScopePointer().get());
bool doSeekParseReturnValue = false;
auto endPos = foreachArrayElement(line, 0, [&](auto elementLine) {
while (pCurrentScope != env.currentScopePointer().get()) {
env.closeTopScope();
}
bool isFoundValue = false;
auto[nestName, nameEndPos] = parseName(elementLine, 0, isFoundValue);
Value const* pValue = nullptr;
if (isFoundValue) {
pValue = env.searchValue(toStringList(nestName), false, nullptr);
}
if (pValue) {
pCurrentScope->pushArgument(Value(*pValue));
} else {
env.pushScope(std::make_shared<NormalScope>(std::list<std::string>{""}, Value()));
env.pushMode(std::make_shared<NormalParseMode>());
parseValue(env, elementLine);
}
return GO_NEXT_ELEMENT;
});
return Result::Continue;
}
} | 32.666667 | 127 | 0.658163 | tositeru |
d040ad32d8e9a8dd8265530692d9ab8983b35d8c | 3,410 | cpp | C++ | library/Java/Lang/ArithmeticException/ArithmeticExceptionTest.cpp | VietAnh14/native | 8f9f23c2ff21ac14c69745556e04aaec36dbcd13 | [
"Zlib"
] | 1 | 2018-12-12T13:04:09.000Z | 2018-12-12T13:04:09.000Z | library/Java/Lang/ArithmeticException/ArithmeticExceptionTest.cpp | vothaosontlu/native | 2b8d062ce6db66dfdaa8b17087ba32455c9531e8 | [
"Zlib"
] | null | null | null | library/Java/Lang/ArithmeticException/ArithmeticExceptionTest.cpp | vothaosontlu/native | 2b8d062ce6db66dfdaa8b17087ba32455c9531e8 | [
"Zlib"
] | null | null | null | /**
* Copyright (c) 2016 Food Tiny Project. All rights reserved.
*
* Redistribution and use in source and binary forms, with or without
* modification, are permitted provided that the following conditions are met:
*
* Redistributions of source code must retain the above copyright
* notice, this list of conditions and the following disclaimer.
* Redistributions in binary form must reproduce the above
* copyright notice, this list of conditions and the following disclaimer
* in the documentation and/or other materials provided with the
* distribution.
*
* THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS
* "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT
* LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR
* A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT
* OWNER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL,
* SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT
* LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE,
* DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY
* THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT
* (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE
* OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
*/
#include "../../../Test.hpp"
#include "ArithmeticException.hpp"
using namespace Java::Lang;
TEST (JavaLangArithmeticException, Constructor) {
// Constructs a new ArithmeticException with null as its detail message.
InterruptedException arithmeticExceptionWithNullMessage;
assertEquals("", arithmeticExceptionWithNullMessage.getMessage());
// Constructs a new ArithmeticException with the specified detail message.
InterruptedException arithmeticExceptionWithMessage = InterruptedException(
"ArithmeticException with the specified message");
assertEquals("ArithmeticException with the specified message",
arithmeticExceptionWithMessage.getMessage());
// Constructs a new ArithmeticException with the specified detail message and cause.
InterruptedException arithmeticExceptionWithMessageAndCause = InterruptedException(
"ArithmeticException with the specified message and cause",
&arithmeticExceptionWithMessage);
assertEquals("ArithmeticException with the specified message and cause",
arithmeticExceptionWithMessageAndCause.getMessage());
assertEquals("ArithmeticException with the specified message",
arithmeticExceptionWithMessageAndCause.getCause()->getMessage());
// Constructs a new ArithmeticException with the specified cause.
InterruptedException arithmeticExceptionWithCause = InterruptedException(
&arithmeticExceptionWithMessageAndCause);
assertEquals("ArithmeticException with the specified message and cause",
arithmeticExceptionWithCause.getCause()->getMessage());
assertEquals("ArithmeticException with the specified message",
arithmeticExceptionWithCause.getCause()->getCause()->getMessage());
}
TEST (JavaLangArithmeticException, TryCatch) {
try {
throw InterruptedException("Throw ArithmeticException");
}
catch (InterruptedException e) {
assertEquals("Throw ArithmeticException", e.getMessage());
}
} | 50.147059 | 88 | 0.758651 | VietAnh14 |
d04267cbcfaddd0dc0bef5714ec0988d668d1593 | 9,854 | cpp | C++ | src/d3d10/d3d10_texture.cpp | lacc97/dxvk | 5fe8d823a03cc1c90361a4e89c385cefee8cbcf6 | [
"Zlib"
] | 8,148 | 2017-10-29T10:51:20.000Z | 2022-03-31T12:52:51.000Z | src/d3d10/d3d10_texture.cpp | lacc97/dxvk | 5fe8d823a03cc1c90361a4e89c385cefee8cbcf6 | [
"Zlib"
] | 2,270 | 2017-12-04T12:08:13.000Z | 2022-03-31T19:56:41.000Z | src/d3d10/d3d10_texture.cpp | lacc97/dxvk | 5fe8d823a03cc1c90361a4e89c385cefee8cbcf6 | [
"Zlib"
] | 732 | 2017-11-28T13:08:15.000Z | 2022-03-31T21:05:59.000Z | #include "d3d10_texture.h"
#include "d3d10_device.h"
#include "../d3d11/d3d11_device.h"
#include "../d3d11/d3d11_context.h"
#include "../d3d11/d3d11_texture.h"
namespace dxvk {
HRESULT STDMETHODCALLTYPE D3D10Texture1D::QueryInterface(
REFIID riid,
void** ppvObject) {
return m_d3d11->QueryInterface(riid, ppvObject);
}
ULONG STDMETHODCALLTYPE D3D10Texture1D::AddRef() {
return m_d3d11->AddRef();
}
ULONG STDMETHODCALLTYPE D3D10Texture1D::Release() {
return m_d3d11->Release();
}
void STDMETHODCALLTYPE D3D10Texture1D::GetDevice(
ID3D10Device** ppDevice) {
GetD3D10Device(m_d3d11, ppDevice);
}
HRESULT STDMETHODCALLTYPE D3D10Texture1D::GetPrivateData(
REFGUID guid,
UINT* pDataSize,
void* pData) {
return m_d3d11->GetPrivateData(guid, pDataSize, pData);
}
HRESULT STDMETHODCALLTYPE D3D10Texture1D::SetPrivateData(
REFGUID guid,
UINT DataSize,
const void* pData) {
return m_d3d11->SetPrivateData(guid, DataSize, pData);
}
HRESULT STDMETHODCALLTYPE D3D10Texture1D::SetPrivateDataInterface(
REFGUID guid,
const IUnknown* pData) {
return m_d3d11->SetPrivateDataInterface(guid, pData);
}
void STDMETHODCALLTYPE D3D10Texture1D::GetType(
D3D10_RESOURCE_DIMENSION* rType) {
*rType = D3D10_RESOURCE_DIMENSION_TEXTURE1D;
}
void STDMETHODCALLTYPE D3D10Texture1D::SetEvictionPriority(
UINT EvictionPriority) {
m_d3d11->SetEvictionPriority(EvictionPriority);
}
UINT STDMETHODCALLTYPE D3D10Texture1D::GetEvictionPriority() {
return m_d3d11->GetEvictionPriority();
}
HRESULT STDMETHODCALLTYPE D3D10Texture1D::Map(
UINT Subresource,
D3D10_MAP MapType,
UINT MapFlags,
void** ppData) {
Com<ID3D11DeviceContext> ctx;
GetD3D11Context(m_d3d11, &ctx);
D3D11_MAPPED_SUBRESOURCE sr;
HRESULT hr = ctx->Map(m_d3d11, Subresource,
D3D11_MAP(MapType), MapFlags, &sr);
if (FAILED(hr))
return hr;
if (ppData != nullptr) {
*ppData = sr.pData;
return S_OK;
} return S_FALSE;
}
void STDMETHODCALLTYPE D3D10Texture1D::Unmap(
UINT Subresource) {
Com<ID3D11DeviceContext> ctx;
GetD3D11Context(m_d3d11, &ctx);
ctx->Unmap(m_d3d11, Subresource);
}
void STDMETHODCALLTYPE D3D10Texture1D::GetDesc(
D3D10_TEXTURE1D_DESC* pDesc) {
D3D11_TEXTURE1D_DESC d3d11Desc;
m_d3d11->GetDesc(&d3d11Desc);
pDesc->Width = d3d11Desc.Width;
pDesc->MipLevels = d3d11Desc.MipLevels;
pDesc->ArraySize = d3d11Desc.ArraySize;
pDesc->Format = d3d11Desc.Format;
pDesc->Usage = D3D10_USAGE(d3d11Desc.Usage);
pDesc->BindFlags = d3d11Desc.BindFlags;
pDesc->CPUAccessFlags = d3d11Desc.CPUAccessFlags;
pDesc->MiscFlags = ConvertD3D11ResourceFlags(d3d11Desc.MiscFlags);
}
HRESULT STDMETHODCALLTYPE D3D10Texture2D::QueryInterface(
REFIID riid,
void** ppvObject) {
return m_d3d11->QueryInterface(riid, ppvObject);
}
ULONG STDMETHODCALLTYPE D3D10Texture2D::AddRef() {
return m_d3d11->AddRef();
}
ULONG STDMETHODCALLTYPE D3D10Texture2D::Release() {
return m_d3d11->Release();
}
void STDMETHODCALLTYPE D3D10Texture2D::GetDevice(
ID3D10Device** ppDevice) {
GetD3D10Device(m_d3d11, ppDevice);
}
HRESULT STDMETHODCALLTYPE D3D10Texture2D::GetPrivateData(
REFGUID guid,
UINT* pDataSize,
void* pData) {
return m_d3d11->GetPrivateData(guid, pDataSize, pData);
}
HRESULT STDMETHODCALLTYPE D3D10Texture2D::SetPrivateData(
REFGUID guid,
UINT DataSize,
const void* pData) {
return m_d3d11->SetPrivateData(guid, DataSize, pData);
}
HRESULT STDMETHODCALLTYPE D3D10Texture2D::SetPrivateDataInterface(
REFGUID guid,
const IUnknown* pData) {
return m_d3d11->SetPrivateDataInterface(guid, pData);
}
void STDMETHODCALLTYPE D3D10Texture2D::GetType(
D3D10_RESOURCE_DIMENSION* rType) {
*rType = D3D10_RESOURCE_DIMENSION_TEXTURE2D;
}
void STDMETHODCALLTYPE D3D10Texture2D::SetEvictionPriority(
UINT EvictionPriority) {
m_d3d11->SetEvictionPriority(EvictionPriority);
}
UINT STDMETHODCALLTYPE D3D10Texture2D::GetEvictionPriority() {
return m_d3d11->GetEvictionPriority();
}
HRESULT STDMETHODCALLTYPE D3D10Texture2D::Map(
UINT Subresource,
D3D10_MAP MapType,
UINT MapFlags,
D3D10_MAPPED_TEXTURE2D* pMappedTex2D) {
Com<ID3D11DeviceContext> ctx;
GetD3D11Context(m_d3d11, &ctx);
D3D11_MAPPED_SUBRESOURCE sr;
HRESULT hr = ctx->Map(m_d3d11, Subresource,
D3D11_MAP(MapType), MapFlags, &sr);
if (FAILED(hr))
return hr;
if (pMappedTex2D != nullptr) {
pMappedTex2D->pData = sr.pData;
pMappedTex2D->RowPitch = sr.RowPitch;
return S_OK;
} return S_FALSE;
}
void STDMETHODCALLTYPE D3D10Texture2D::Unmap(
UINT Subresource) {
Com<ID3D11DeviceContext> ctx;
GetD3D11Context(m_d3d11, &ctx);
ctx->Unmap(m_d3d11, Subresource);
}
void STDMETHODCALLTYPE D3D10Texture2D::GetDesc(
D3D10_TEXTURE2D_DESC* pDesc) {
D3D11_TEXTURE2D_DESC d3d11Desc;
m_d3d11->GetDesc(&d3d11Desc);
pDesc->Width = d3d11Desc.Width;
pDesc->Height = d3d11Desc.Height;
pDesc->MipLevels = d3d11Desc.MipLevels;
pDesc->ArraySize = d3d11Desc.ArraySize;
pDesc->Format = d3d11Desc.Format;
pDesc->SampleDesc = d3d11Desc.SampleDesc;
pDesc->Usage = D3D10_USAGE(d3d11Desc.Usage);
pDesc->BindFlags = d3d11Desc.BindFlags;
pDesc->CPUAccessFlags = d3d11Desc.CPUAccessFlags;
pDesc->MiscFlags = ConvertD3D11ResourceFlags(d3d11Desc.MiscFlags);
}
HRESULT STDMETHODCALLTYPE D3D10Texture3D::QueryInterface(
REFIID riid,
void** ppvObject) {
return m_d3d11->QueryInterface(riid, ppvObject);
}
ULONG STDMETHODCALLTYPE D3D10Texture3D::AddRef() {
return m_d3d11->AddRef();
}
ULONG STDMETHODCALLTYPE D3D10Texture3D::Release() {
return m_d3d11->Release();
}
void STDMETHODCALLTYPE D3D10Texture3D::GetDevice(
ID3D10Device** ppDevice) {
GetD3D10Device(m_d3d11, ppDevice);
}
HRESULT STDMETHODCALLTYPE D3D10Texture3D::GetPrivateData(
REFGUID guid,
UINT* pDataSize,
void* pData) {
return m_d3d11->GetPrivateData(guid, pDataSize, pData);
}
HRESULT STDMETHODCALLTYPE D3D10Texture3D::SetPrivateData(
REFGUID guid,
UINT DataSize,
const void* pData) {
return m_d3d11->SetPrivateData(guid, DataSize, pData);
}
HRESULT STDMETHODCALLTYPE D3D10Texture3D::SetPrivateDataInterface(
REFGUID guid,
const IUnknown* pData) {
return m_d3d11->SetPrivateDataInterface(guid, pData);
}
void STDMETHODCALLTYPE D3D10Texture3D::GetType(
D3D10_RESOURCE_DIMENSION* rType) {
*rType = D3D10_RESOURCE_DIMENSION_TEXTURE3D;
}
void STDMETHODCALLTYPE D3D10Texture3D::SetEvictionPriority(
UINT EvictionPriority) {
m_d3d11->SetEvictionPriority(EvictionPriority);
}
UINT STDMETHODCALLTYPE D3D10Texture3D::GetEvictionPriority() {
return m_d3d11->GetEvictionPriority();
}
HRESULT STDMETHODCALLTYPE D3D10Texture3D::Map(
UINT Subresource,
D3D10_MAP MapType,
UINT MapFlags,
D3D10_MAPPED_TEXTURE3D* pMappedTex3D) {
Com<ID3D11DeviceContext> ctx;
GetD3D11Context(m_d3d11, &ctx);
D3D11_MAPPED_SUBRESOURCE sr;
HRESULT hr = ctx->Map(m_d3d11, Subresource,
D3D11_MAP(MapType), MapFlags, &sr);
if (FAILED(hr))
return hr;
if (pMappedTex3D != nullptr) {
pMappedTex3D->pData = sr.pData;
pMappedTex3D->RowPitch = sr.RowPitch;
pMappedTex3D->DepthPitch = sr.DepthPitch;
return S_OK;
} return S_FALSE;
}
void STDMETHODCALLTYPE D3D10Texture3D::Unmap(
UINT Subresource) {
Com<ID3D11DeviceContext> ctx;
GetD3D11Context(m_d3d11, &ctx);
ctx->Unmap(m_d3d11, Subresource);
}
void STDMETHODCALLTYPE D3D10Texture3D::GetDesc(
D3D10_TEXTURE3D_DESC* pDesc) {
D3D11_TEXTURE3D_DESC d3d11Desc;
m_d3d11->GetDesc(&d3d11Desc);
pDesc->Width = d3d11Desc.Width;
pDesc->Height = d3d11Desc.Height;
pDesc->Depth = d3d11Desc.Depth;
pDesc->MipLevels = d3d11Desc.MipLevels;
pDesc->Format = d3d11Desc.Format;
pDesc->Usage = D3D10_USAGE(d3d11Desc.Usage);
pDesc->BindFlags = d3d11Desc.BindFlags;
pDesc->CPUAccessFlags = d3d11Desc.CPUAccessFlags;
pDesc->MiscFlags = ConvertD3D11ResourceFlags(d3d11Desc.MiscFlags);
}
} | 28.562319 | 76 | 0.608382 | lacc97 |
d043f0dce85f1f9137d6821d5215a3bbe781b19e | 620 | cpp | C++ | src/libtoast/tests/toast_test_env.cpp | jrs584/toast | c0e2a9296348a22075271236457ad5c23713af82 | [
"BSD-2-Clause"
] | 29 | 2017-03-23T04:51:32.000Z | 2022-02-10T13:17:42.000Z | src/libtoast/tests/toast_test_env.cpp | jrs584/toast | c0e2a9296348a22075271236457ad5c23713af82 | [
"BSD-2-Clause"
] | 362 | 2016-05-06T18:26:35.000Z | 2022-03-30T16:39:46.000Z | src/libtoast/tests/toast_test_env.cpp | jrs584/toast | c0e2a9296348a22075271236457ad5c23713af82 | [
"BSD-2-Clause"
] | 37 | 2016-05-20T09:31:03.000Z | 2022-02-24T13:56:27.000Z |
// Copyright (c) 2015-2020 by the parties listed in the AUTHORS file.
// All rights reserved. Use of this source code is governed by
// a BSD-style license that can be found in the LICENSE file.
#include <toast_test.hpp>
TEST_F(TOASTenvTest, print) {
auto & env = toast::Environment::get();
env.print();
}
TEST_F(TOASTenvTest, setlog) {
auto & env = toast::Environment::get();
std::string check = env.log_level();
ASSERT_STREQ(check.c_str(), "INFO");
env.set_log_level("CRITICAL");
check = env.log_level();
ASSERT_STREQ(check.c_str(), "CRITICAL");
env.set_log_level("INFO");
}
| 25.833333 | 69 | 0.670968 | jrs584 |
d0457573445856636cd6e94e29860fd552c2194e | 479 | cpp | C++ | RedWolfTests/src/FixedQueueTest.cpp | DavidePistilli173/RedWolf | 1ca752c8e4c6becfb9de942d6059f6076384f3af | [
"Apache-2.0"
] | null | null | null | RedWolfTests/src/FixedQueueTest.cpp | DavidePistilli173/RedWolf | 1ca752c8e4c6becfb9de942d6059f6076384f3af | [
"Apache-2.0"
] | null | null | null | RedWolfTests/src/FixedQueueTest.cpp | DavidePistilli173/RedWolf | 1ca752c8e4c6becfb9de942d6059f6076384f3af | [
"Apache-2.0"
] | null | null | null | #include "RedWolf/utility.hpp"
#include <RedWolf/gl/Buffer.hpp>
#include <gtest/gtest.h>
constexpr size_t fqt_max_queue_size{ 1024 };
constexpr size_t fqt_max_iterations{ 2 * fqt_max_queue_size };
TEST(FixedQueue, SizeAfterPush)
{
/* Create a queue. */
rw::FixedQueue<int, fqt_max_queue_size> q;
/* Push more elements than the queue can hold. */
for (int i = 0; i < fqt_max_iterations; ++i)
{
q.push(i);
}
ASSERT_EQ(q.size(), fqt_max_queue_size);
} | 23.95 | 62 | 0.688935 | DavidePistilli173 |
d046219048613d784aa0c0cdc68adf8af518af96 | 18,852 | cc | C++ | wrappers/7.0.0/vtkImageBlendWrap.cc | axkibe/node-vtk | 900ad7b5500f672519da5aa24c99aa5a96466ef3 | [
"BSD-3-Clause"
] | 6 | 2016-02-03T12:48:36.000Z | 2020-09-16T15:07:51.000Z | wrappers/7.0.0/vtkImageBlendWrap.cc | axkibe/node-vtk | 900ad7b5500f672519da5aa24c99aa5a96466ef3 | [
"BSD-3-Clause"
] | 4 | 2016-02-13T01:30:43.000Z | 2020-03-30T16:59:32.000Z | wrappers/7.0.0/vtkImageBlendWrap.cc | axkibe/node-vtk | 900ad7b5500f672519da5aa24c99aa5a96466ef3 | [
"BSD-3-Clause"
] | null | null | null | /* this file has been autogenerated by vtkNodeJsWrap */
/* editing this might proof futile */
#define VTK_WRAPPING_CXX
#define VTK_STREAMS_FWD_ONLY
#include <nan.h>
#include "vtkThreadedImageAlgorithmWrap.h"
#include "vtkImageBlendWrap.h"
#include "vtkObjectWrap.h"
#include "vtkAlgorithmOutputWrap.h"
#include "vtkDataObjectWrap.h"
#include "vtkImageStencilDataWrap.h"
#include "../../plus/plus.h"
using namespace v8;
extern Nan::Persistent<v8::Object> vtkNodeJsNoWrap;
Nan::Persistent<v8::FunctionTemplate> VtkImageBlendWrap::ptpl;
VtkImageBlendWrap::VtkImageBlendWrap()
{ }
VtkImageBlendWrap::VtkImageBlendWrap(vtkSmartPointer<vtkImageBlend> _native)
{ native = _native; }
VtkImageBlendWrap::~VtkImageBlendWrap()
{ }
void VtkImageBlendWrap::Init(v8::Local<v8::Object> exports)
{
Nan::SetAccessor(exports, Nan::New("vtkImageBlend").ToLocalChecked(), ConstructorGetter);
Nan::SetAccessor(exports, Nan::New("ImageBlend").ToLocalChecked(), ConstructorGetter);
}
void VtkImageBlendWrap::ConstructorGetter(
v8::Local<v8::String> property,
const Nan::PropertyCallbackInfo<v8::Value>& info)
{
InitPtpl();
info.GetReturnValue().Set(Nan::New(ptpl)->GetFunction());
}
void VtkImageBlendWrap::InitPtpl()
{
if (!ptpl.IsEmpty()) return;
v8::Local<v8::FunctionTemplate> tpl = Nan::New<v8::FunctionTemplate>(New);
VtkThreadedImageAlgorithmWrap::InitPtpl( );
tpl->Inherit(Nan::New<FunctionTemplate>(VtkThreadedImageAlgorithmWrap::ptpl));
tpl->SetClassName(Nan::New("VtkImageBlendWrap").ToLocalChecked());
tpl->InstanceTemplate()->SetInternalFieldCount(1);
Nan::SetPrototypeMethod(tpl, "GetBlendMode", GetBlendMode);
Nan::SetPrototypeMethod(tpl, "getBlendMode", GetBlendMode);
Nan::SetPrototypeMethod(tpl, "GetBlendModeAsString", GetBlendModeAsString);
Nan::SetPrototypeMethod(tpl, "getBlendModeAsString", GetBlendModeAsString);
Nan::SetPrototypeMethod(tpl, "GetBlendModeMaxValue", GetBlendModeMaxValue);
Nan::SetPrototypeMethod(tpl, "getBlendModeMaxValue", GetBlendModeMaxValue);
Nan::SetPrototypeMethod(tpl, "GetBlendModeMinValue", GetBlendModeMinValue);
Nan::SetPrototypeMethod(tpl, "getBlendModeMinValue", GetBlendModeMinValue);
Nan::SetPrototypeMethod(tpl, "GetClassName", GetClassName);
Nan::SetPrototypeMethod(tpl, "getClassName", GetClassName);
Nan::SetPrototypeMethod(tpl, "GetCompoundThreshold", GetCompoundThreshold);
Nan::SetPrototypeMethod(tpl, "getCompoundThreshold", GetCompoundThreshold);
Nan::SetPrototypeMethod(tpl, "GetInput", GetInput);
Nan::SetPrototypeMethod(tpl, "getInput", GetInput);
Nan::SetPrototypeMethod(tpl, "GetNumberOfInputs", GetNumberOfInputs);
Nan::SetPrototypeMethod(tpl, "getNumberOfInputs", GetNumberOfInputs);
Nan::SetPrototypeMethod(tpl, "GetOpacity", GetOpacity);
Nan::SetPrototypeMethod(tpl, "getOpacity", GetOpacity);
Nan::SetPrototypeMethod(tpl, "GetStencil", GetStencil);
Nan::SetPrototypeMethod(tpl, "getStencil", GetStencil);
Nan::SetPrototypeMethod(tpl, "IsA", IsA);
Nan::SetPrototypeMethod(tpl, "isA", IsA);
Nan::SetPrototypeMethod(tpl, "NewInstance", NewInstance);
Nan::SetPrototypeMethod(tpl, "newInstance", NewInstance);
Nan::SetPrototypeMethod(tpl, "ReplaceNthInputConnection", ReplaceNthInputConnection);
Nan::SetPrototypeMethod(tpl, "replaceNthInputConnection", ReplaceNthInputConnection);
Nan::SetPrototypeMethod(tpl, "SafeDownCast", SafeDownCast);
Nan::SetPrototypeMethod(tpl, "safeDownCast", SafeDownCast);
Nan::SetPrototypeMethod(tpl, "SetBlendMode", SetBlendMode);
Nan::SetPrototypeMethod(tpl, "setBlendMode", SetBlendMode);
Nan::SetPrototypeMethod(tpl, "SetBlendModeToCompound", SetBlendModeToCompound);
Nan::SetPrototypeMethod(tpl, "setBlendModeToCompound", SetBlendModeToCompound);
Nan::SetPrototypeMethod(tpl, "SetBlendModeToNormal", SetBlendModeToNormal);
Nan::SetPrototypeMethod(tpl, "setBlendModeToNormal", SetBlendModeToNormal);
Nan::SetPrototypeMethod(tpl, "SetCompoundThreshold", SetCompoundThreshold);
Nan::SetPrototypeMethod(tpl, "setCompoundThreshold", SetCompoundThreshold);
Nan::SetPrototypeMethod(tpl, "SetInputData", SetInputData);
Nan::SetPrototypeMethod(tpl, "setInputData", SetInputData);
Nan::SetPrototypeMethod(tpl, "SetOpacity", SetOpacity);
Nan::SetPrototypeMethod(tpl, "setOpacity", SetOpacity);
Nan::SetPrototypeMethod(tpl, "SetStencilConnection", SetStencilConnection);
Nan::SetPrototypeMethod(tpl, "setStencilConnection", SetStencilConnection);
Nan::SetPrototypeMethod(tpl, "SetStencilData", SetStencilData);
Nan::SetPrototypeMethod(tpl, "setStencilData", SetStencilData);
#ifdef VTK_NODE_PLUS_VTKIMAGEBLENDWRAP_INITPTPL
VTK_NODE_PLUS_VTKIMAGEBLENDWRAP_INITPTPL
#endif
ptpl.Reset( tpl );
}
void VtkImageBlendWrap::New(const Nan::FunctionCallbackInfo<v8::Value>& info)
{
if(!info.IsConstructCall())
{
Nan::ThrowError("Constructor not called in a construct call.");
return;
}
if(info.Length() == 0)
{
vtkSmartPointer<vtkImageBlend> native = vtkSmartPointer<vtkImageBlend>::New();
VtkImageBlendWrap* obj = new VtkImageBlendWrap(native);
obj->Wrap(info.This());
}
else
{
if(info[0]->ToObject() != vtkNodeJsNoWrap )
{
Nan::ThrowError("Parameter Error");
return;
}
}
info.GetReturnValue().Set(info.This());
}
void VtkImageBlendWrap::GetBlendMode(const Nan::FunctionCallbackInfo<v8::Value>& info)
{
VtkImageBlendWrap *wrapper = ObjectWrap::Unwrap<VtkImageBlendWrap>(info.Holder());
vtkImageBlend *native = (vtkImageBlend *)wrapper->native.GetPointer();
int r;
if(info.Length() != 0)
{
Nan::ThrowError("Too many parameters.");
return;
}
r = native->GetBlendMode();
info.GetReturnValue().Set(Nan::New(r));
}
void VtkImageBlendWrap::GetBlendModeAsString(const Nan::FunctionCallbackInfo<v8::Value>& info)
{
VtkImageBlendWrap *wrapper = ObjectWrap::Unwrap<VtkImageBlendWrap>(info.Holder());
vtkImageBlend *native = (vtkImageBlend *)wrapper->native.GetPointer();
char const * r;
if(info.Length() != 0)
{
Nan::ThrowError("Too many parameters.");
return;
}
r = native->GetBlendModeAsString();
info.GetReturnValue().Set(Nan::New(r).ToLocalChecked());
}
void VtkImageBlendWrap::GetBlendModeMaxValue(const Nan::FunctionCallbackInfo<v8::Value>& info)
{
VtkImageBlendWrap *wrapper = ObjectWrap::Unwrap<VtkImageBlendWrap>(info.Holder());
vtkImageBlend *native = (vtkImageBlend *)wrapper->native.GetPointer();
int r;
if(info.Length() != 0)
{
Nan::ThrowError("Too many parameters.");
return;
}
r = native->GetBlendModeMaxValue();
info.GetReturnValue().Set(Nan::New(r));
}
void VtkImageBlendWrap::GetBlendModeMinValue(const Nan::FunctionCallbackInfo<v8::Value>& info)
{
VtkImageBlendWrap *wrapper = ObjectWrap::Unwrap<VtkImageBlendWrap>(info.Holder());
vtkImageBlend *native = (vtkImageBlend *)wrapper->native.GetPointer();
int r;
if(info.Length() != 0)
{
Nan::ThrowError("Too many parameters.");
return;
}
r = native->GetBlendModeMinValue();
info.GetReturnValue().Set(Nan::New(r));
}
void VtkImageBlendWrap::GetClassName(const Nan::FunctionCallbackInfo<v8::Value>& info)
{
VtkImageBlendWrap *wrapper = ObjectWrap::Unwrap<VtkImageBlendWrap>(info.Holder());
vtkImageBlend *native = (vtkImageBlend *)wrapper->native.GetPointer();
char const * r;
if(info.Length() != 0)
{
Nan::ThrowError("Too many parameters.");
return;
}
r = native->GetClassName();
info.GetReturnValue().Set(Nan::New(r).ToLocalChecked());
}
void VtkImageBlendWrap::GetCompoundThreshold(const Nan::FunctionCallbackInfo<v8::Value>& info)
{
VtkImageBlendWrap *wrapper = ObjectWrap::Unwrap<VtkImageBlendWrap>(info.Holder());
vtkImageBlend *native = (vtkImageBlend *)wrapper->native.GetPointer();
double r;
if(info.Length() != 0)
{
Nan::ThrowError("Too many parameters.");
return;
}
r = native->GetCompoundThreshold();
info.GetReturnValue().Set(Nan::New(r));
}
void VtkImageBlendWrap::GetInput(const Nan::FunctionCallbackInfo<v8::Value>& info)
{
VtkImageBlendWrap *wrapper = ObjectWrap::Unwrap<VtkImageBlendWrap>(info.Holder());
vtkImageBlend *native = (vtkImageBlend *)wrapper->native.GetPointer();
if(info.Length() > 0 && info[0]->IsInt32())
{
vtkDataObject * r;
if(info.Length() != 1)
{
Nan::ThrowError("Too many parameters.");
return;
}
r = native->GetInput(
info[0]->Int32Value()
);
VtkDataObjectWrap::InitPtpl();
v8::Local<v8::Value> argv[1] =
{ Nan::New(vtkNodeJsNoWrap) };
v8::Local<v8::Function> cons =
Nan::New<v8::FunctionTemplate>(VtkDataObjectWrap::ptpl)->GetFunction();
v8::Local<v8::Object> wo = cons->NewInstance(1, argv);
VtkDataObjectWrap *w = new VtkDataObjectWrap();
w->native = r;
w->Wrap(wo);
info.GetReturnValue().Set(wo);
return;
}
vtkDataObject * r;
if(info.Length() != 0)
{
Nan::ThrowError("Too many parameters.");
return;
}
r = native->GetInput();
VtkDataObjectWrap::InitPtpl();
v8::Local<v8::Value> argv[1] =
{ Nan::New(vtkNodeJsNoWrap) };
v8::Local<v8::Function> cons =
Nan::New<v8::FunctionTemplate>(VtkDataObjectWrap::ptpl)->GetFunction();
v8::Local<v8::Object> wo = cons->NewInstance(1, argv);
VtkDataObjectWrap *w = new VtkDataObjectWrap();
w->native = r;
w->Wrap(wo);
info.GetReturnValue().Set(wo);
}
void VtkImageBlendWrap::GetNumberOfInputs(const Nan::FunctionCallbackInfo<v8::Value>& info)
{
VtkImageBlendWrap *wrapper = ObjectWrap::Unwrap<VtkImageBlendWrap>(info.Holder());
vtkImageBlend *native = (vtkImageBlend *)wrapper->native.GetPointer();
int r;
if(info.Length() != 0)
{
Nan::ThrowError("Too many parameters.");
return;
}
r = native->GetNumberOfInputs();
info.GetReturnValue().Set(Nan::New(r));
}
void VtkImageBlendWrap::GetOpacity(const Nan::FunctionCallbackInfo<v8::Value>& info)
{
VtkImageBlendWrap *wrapper = ObjectWrap::Unwrap<VtkImageBlendWrap>(info.Holder());
vtkImageBlend *native = (vtkImageBlend *)wrapper->native.GetPointer();
if(info.Length() > 0 && info[0]->IsInt32())
{
double r;
if(info.Length() != 1)
{
Nan::ThrowError("Too many parameters.");
return;
}
r = native->GetOpacity(
info[0]->Int32Value()
);
info.GetReturnValue().Set(Nan::New(r));
return;
}
Nan::ThrowError("Parameter mismatch");
}
void VtkImageBlendWrap::GetStencil(const Nan::FunctionCallbackInfo<v8::Value>& info)
{
VtkImageBlendWrap *wrapper = ObjectWrap::Unwrap<VtkImageBlendWrap>(info.Holder());
vtkImageBlend *native = (vtkImageBlend *)wrapper->native.GetPointer();
vtkImageStencilData * r;
if(info.Length() != 0)
{
Nan::ThrowError("Too many parameters.");
return;
}
r = native->GetStencil();
VtkImageStencilDataWrap::InitPtpl();
v8::Local<v8::Value> argv[1] =
{ Nan::New(vtkNodeJsNoWrap) };
v8::Local<v8::Function> cons =
Nan::New<v8::FunctionTemplate>(VtkImageStencilDataWrap::ptpl)->GetFunction();
v8::Local<v8::Object> wo = cons->NewInstance(1, argv);
VtkImageStencilDataWrap *w = new VtkImageStencilDataWrap();
w->native = r;
w->Wrap(wo);
info.GetReturnValue().Set(wo);
}
void VtkImageBlendWrap::IsA(const Nan::FunctionCallbackInfo<v8::Value>& info)
{
VtkImageBlendWrap *wrapper = ObjectWrap::Unwrap<VtkImageBlendWrap>(info.Holder());
vtkImageBlend *native = (vtkImageBlend *)wrapper->native.GetPointer();
if(info.Length() > 0 && info[0]->IsString())
{
Nan::Utf8String a0(info[0]);
int r;
if(info.Length() != 1)
{
Nan::ThrowError("Too many parameters.");
return;
}
r = native->IsA(
*a0
);
info.GetReturnValue().Set(Nan::New(r));
return;
}
Nan::ThrowError("Parameter mismatch");
}
void VtkImageBlendWrap::NewInstance(const Nan::FunctionCallbackInfo<v8::Value>& info)
{
VtkImageBlendWrap *wrapper = ObjectWrap::Unwrap<VtkImageBlendWrap>(info.Holder());
vtkImageBlend *native = (vtkImageBlend *)wrapper->native.GetPointer();
vtkImageBlend * r;
if(info.Length() != 0)
{
Nan::ThrowError("Too many parameters.");
return;
}
r = native->NewInstance();
VtkImageBlendWrap::InitPtpl();
v8::Local<v8::Value> argv[1] =
{ Nan::New(vtkNodeJsNoWrap) };
v8::Local<v8::Function> cons =
Nan::New<v8::FunctionTemplate>(VtkImageBlendWrap::ptpl)->GetFunction();
v8::Local<v8::Object> wo = cons->NewInstance(1, argv);
VtkImageBlendWrap *w = new VtkImageBlendWrap();
w->native = r;
w->Wrap(wo);
info.GetReturnValue().Set(wo);
}
void VtkImageBlendWrap::ReplaceNthInputConnection(const Nan::FunctionCallbackInfo<v8::Value>& info)
{
VtkImageBlendWrap *wrapper = ObjectWrap::Unwrap<VtkImageBlendWrap>(info.Holder());
vtkImageBlend *native = (vtkImageBlend *)wrapper->native.GetPointer();
if(info.Length() > 0 && info[0]->IsInt32())
{
if(info.Length() > 1 && info[1]->IsObject() && (Nan::New(VtkAlgorithmOutputWrap::ptpl))->HasInstance(info[1]))
{
VtkAlgorithmOutputWrap *a1 = ObjectWrap::Unwrap<VtkAlgorithmOutputWrap>(info[1]->ToObject());
if(info.Length() != 2)
{
Nan::ThrowError("Too many parameters.");
return;
}
native->ReplaceNthInputConnection(
info[0]->Int32Value(),
(vtkAlgorithmOutput *) a1->native.GetPointer()
);
return;
}
}
Nan::ThrowError("Parameter mismatch");
}
void VtkImageBlendWrap::SafeDownCast(const Nan::FunctionCallbackInfo<v8::Value>& info)
{
VtkImageBlendWrap *wrapper = ObjectWrap::Unwrap<VtkImageBlendWrap>(info.Holder());
vtkImageBlend *native = (vtkImageBlend *)wrapper->native.GetPointer();
if(info.Length() > 0 && info[0]->IsObject() && (Nan::New(VtkObjectWrap::ptpl))->HasInstance(info[0]))
{
VtkObjectWrap *a0 = ObjectWrap::Unwrap<VtkObjectWrap>(info[0]->ToObject());
vtkImageBlend * r;
if(info.Length() != 1)
{
Nan::ThrowError("Too many parameters.");
return;
}
r = native->SafeDownCast(
(vtkObject *) a0->native.GetPointer()
);
VtkImageBlendWrap::InitPtpl();
v8::Local<v8::Value> argv[1] =
{ Nan::New(vtkNodeJsNoWrap) };
v8::Local<v8::Function> cons =
Nan::New<v8::FunctionTemplate>(VtkImageBlendWrap::ptpl)->GetFunction();
v8::Local<v8::Object> wo = cons->NewInstance(1, argv);
VtkImageBlendWrap *w = new VtkImageBlendWrap();
w->native = r;
w->Wrap(wo);
info.GetReturnValue().Set(wo);
return;
}
Nan::ThrowError("Parameter mismatch");
}
void VtkImageBlendWrap::SetBlendMode(const Nan::FunctionCallbackInfo<v8::Value>& info)
{
VtkImageBlendWrap *wrapper = ObjectWrap::Unwrap<VtkImageBlendWrap>(info.Holder());
vtkImageBlend *native = (vtkImageBlend *)wrapper->native.GetPointer();
if(info.Length() > 0 && info[0]->IsInt32())
{
if(info.Length() != 1)
{
Nan::ThrowError("Too many parameters.");
return;
}
native->SetBlendMode(
info[0]->Int32Value()
);
return;
}
Nan::ThrowError("Parameter mismatch");
}
void VtkImageBlendWrap::SetBlendModeToCompound(const Nan::FunctionCallbackInfo<v8::Value>& info)
{
VtkImageBlendWrap *wrapper = ObjectWrap::Unwrap<VtkImageBlendWrap>(info.Holder());
vtkImageBlend *native = (vtkImageBlend *)wrapper->native.GetPointer();
if(info.Length() != 0)
{
Nan::ThrowError("Too many parameters.");
return;
}
native->SetBlendModeToCompound();
}
void VtkImageBlendWrap::SetBlendModeToNormal(const Nan::FunctionCallbackInfo<v8::Value>& info)
{
VtkImageBlendWrap *wrapper = ObjectWrap::Unwrap<VtkImageBlendWrap>(info.Holder());
vtkImageBlend *native = (vtkImageBlend *)wrapper->native.GetPointer();
if(info.Length() != 0)
{
Nan::ThrowError("Too many parameters.");
return;
}
native->SetBlendModeToNormal();
}
void VtkImageBlendWrap::SetCompoundThreshold(const Nan::FunctionCallbackInfo<v8::Value>& info)
{
VtkImageBlendWrap *wrapper = ObjectWrap::Unwrap<VtkImageBlendWrap>(info.Holder());
vtkImageBlend *native = (vtkImageBlend *)wrapper->native.GetPointer();
if(info.Length() > 0 && info[0]->IsNumber())
{
if(info.Length() != 1)
{
Nan::ThrowError("Too many parameters.");
return;
}
native->SetCompoundThreshold(
info[0]->NumberValue()
);
return;
}
Nan::ThrowError("Parameter mismatch");
}
void VtkImageBlendWrap::SetInputData(const Nan::FunctionCallbackInfo<v8::Value>& info)
{
VtkImageBlendWrap *wrapper = ObjectWrap::Unwrap<VtkImageBlendWrap>(info.Holder());
vtkImageBlend *native = (vtkImageBlend *)wrapper->native.GetPointer();
if(info.Length() > 0 && info[0]->IsObject() && (Nan::New(VtkDataObjectWrap::ptpl))->HasInstance(info[0]))
{
VtkDataObjectWrap *a0 = ObjectWrap::Unwrap<VtkDataObjectWrap>(info[0]->ToObject());
if(info.Length() != 1)
{
Nan::ThrowError("Too many parameters.");
return;
}
native->SetInputData(
(vtkDataObject *) a0->native.GetPointer()
);
return;
}
else if(info.Length() > 0 && info[0]->IsInt32())
{
if(info.Length() > 1 && info[1]->IsObject() && (Nan::New(VtkDataObjectWrap::ptpl))->HasInstance(info[1]))
{
VtkDataObjectWrap *a1 = ObjectWrap::Unwrap<VtkDataObjectWrap>(info[1]->ToObject());
if(info.Length() != 2)
{
Nan::ThrowError("Too many parameters.");
return;
}
native->SetInputData(
info[0]->Int32Value(),
(vtkDataObject *) a1->native.GetPointer()
);
return;
}
}
Nan::ThrowError("Parameter mismatch");
}
void VtkImageBlendWrap::SetOpacity(const Nan::FunctionCallbackInfo<v8::Value>& info)
{
VtkImageBlendWrap *wrapper = ObjectWrap::Unwrap<VtkImageBlendWrap>(info.Holder());
vtkImageBlend *native = (vtkImageBlend *)wrapper->native.GetPointer();
if(info.Length() > 0 && info[0]->IsInt32())
{
if(info.Length() > 1 && info[1]->IsNumber())
{
if(info.Length() != 2)
{
Nan::ThrowError("Too many parameters.");
return;
}
native->SetOpacity(
info[0]->Int32Value(),
info[1]->NumberValue()
);
return;
}
}
Nan::ThrowError("Parameter mismatch");
}
void VtkImageBlendWrap::SetStencilConnection(const Nan::FunctionCallbackInfo<v8::Value>& info)
{
VtkImageBlendWrap *wrapper = ObjectWrap::Unwrap<VtkImageBlendWrap>(info.Holder());
vtkImageBlend *native = (vtkImageBlend *)wrapper->native.GetPointer();
if(info.Length() > 0 && info[0]->IsObject() && (Nan::New(VtkAlgorithmOutputWrap::ptpl))->HasInstance(info[0]))
{
VtkAlgorithmOutputWrap *a0 = ObjectWrap::Unwrap<VtkAlgorithmOutputWrap>(info[0]->ToObject());
if(info.Length() != 1)
{
Nan::ThrowError("Too many parameters.");
return;
}
native->SetStencilConnection(
(vtkAlgorithmOutput *) a0->native.GetPointer()
);
return;
}
Nan::ThrowError("Parameter mismatch");
}
void VtkImageBlendWrap::SetStencilData(const Nan::FunctionCallbackInfo<v8::Value>& info)
{
VtkImageBlendWrap *wrapper = ObjectWrap::Unwrap<VtkImageBlendWrap>(info.Holder());
vtkImageBlend *native = (vtkImageBlend *)wrapper->native.GetPointer();
if(info.Length() > 0 && info[0]->IsObject() && (Nan::New(VtkImageStencilDataWrap::ptpl))->HasInstance(info[0]))
{
VtkImageStencilDataWrap *a0 = ObjectWrap::Unwrap<VtkImageStencilDataWrap>(info[0]->ToObject());
if(info.Length() != 1)
{
Nan::ThrowError("Too many parameters.");
return;
}
native->SetStencilData(
(vtkImageStencilData *) a0->native.GetPointer()
);
return;
}
Nan::ThrowError("Parameter mismatch");
}
| 31.36772 | 112 | 0.719977 | axkibe |
d04cabc98f292b5118db2465877acdb1ec1fb338 | 13,727 | cpp | C++ | Source/Scripting/bsfScript/Generated/BsScriptDepthOfFieldSettings.generated.cpp | bsf2dev/bsf | b318cd4eb1b0299773d625e6c870b8d503cf539e | [
"MIT"
] | 1,745 | 2018-03-16T02:10:28.000Z | 2022-03-26T17:34:21.000Z | Source/Scripting/bsfScript/Generated/BsScriptDepthOfFieldSettings.generated.cpp | bsf2dev/bsf | b318cd4eb1b0299773d625e6c870b8d503cf539e | [
"MIT"
] | 395 | 2018-03-16T10:18:20.000Z | 2021-08-04T16:52:08.000Z | Source/Scripting/bsfScript/Generated/BsScriptDepthOfFieldSettings.generated.cpp | bsf2dev/bsf | b318cd4eb1b0299773d625e6c870b8d503cf539e | [
"MIT"
] | 267 | 2018-03-17T19:32:54.000Z | 2022-02-17T16:55:50.000Z | //********************************* bs::framework - Copyright 2018-2019 Marko Pintera ************************************//
//*********** Licensed under the MIT license. See LICENSE.md for full terms. This notice is not to be removed. ***********//
#include "BsScriptDepthOfFieldSettings.generated.h"
#include "BsMonoMethod.h"
#include "BsMonoClass.h"
#include "BsMonoUtil.h"
#include "BsScriptResourceManager.h"
#include "Wrappers/BsScriptRRefBase.h"
#include "../../../Foundation/bsfCore/Image/BsTexture.h"
#include "Wrappers/BsScriptVector.h"
namespace bs
{
ScriptDepthOfFieldSettings::ScriptDepthOfFieldSettings(MonoObject* managedInstance, const SPtr<DepthOfFieldSettings>& value)
:TScriptReflectable(managedInstance, value)
{
}
void ScriptDepthOfFieldSettings::initRuntimeData()
{
metaData.scriptClass->addInternalCall("Internal_DepthOfFieldSettings", (void*)&ScriptDepthOfFieldSettings::Internal_DepthOfFieldSettings);
metaData.scriptClass->addInternalCall("Internal_getbokehShape", (void*)&ScriptDepthOfFieldSettings::Internal_getbokehShape);
metaData.scriptClass->addInternalCall("Internal_setbokehShape", (void*)&ScriptDepthOfFieldSettings::Internal_setbokehShape);
metaData.scriptClass->addInternalCall("Internal_getenabled", (void*)&ScriptDepthOfFieldSettings::Internal_getenabled);
metaData.scriptClass->addInternalCall("Internal_setenabled", (void*)&ScriptDepthOfFieldSettings::Internal_setenabled);
metaData.scriptClass->addInternalCall("Internal_gettype", (void*)&ScriptDepthOfFieldSettings::Internal_gettype);
metaData.scriptClass->addInternalCall("Internal_settype", (void*)&ScriptDepthOfFieldSettings::Internal_settype);
metaData.scriptClass->addInternalCall("Internal_getfocalDistance", (void*)&ScriptDepthOfFieldSettings::Internal_getfocalDistance);
metaData.scriptClass->addInternalCall("Internal_setfocalDistance", (void*)&ScriptDepthOfFieldSettings::Internal_setfocalDistance);
metaData.scriptClass->addInternalCall("Internal_getfocalRange", (void*)&ScriptDepthOfFieldSettings::Internal_getfocalRange);
metaData.scriptClass->addInternalCall("Internal_setfocalRange", (void*)&ScriptDepthOfFieldSettings::Internal_setfocalRange);
metaData.scriptClass->addInternalCall("Internal_getnearTransitionRange", (void*)&ScriptDepthOfFieldSettings::Internal_getnearTransitionRange);
metaData.scriptClass->addInternalCall("Internal_setnearTransitionRange", (void*)&ScriptDepthOfFieldSettings::Internal_setnearTransitionRange);
metaData.scriptClass->addInternalCall("Internal_getfarTransitionRange", (void*)&ScriptDepthOfFieldSettings::Internal_getfarTransitionRange);
metaData.scriptClass->addInternalCall("Internal_setfarTransitionRange", (void*)&ScriptDepthOfFieldSettings::Internal_setfarTransitionRange);
metaData.scriptClass->addInternalCall("Internal_getnearBlurAmount", (void*)&ScriptDepthOfFieldSettings::Internal_getnearBlurAmount);
metaData.scriptClass->addInternalCall("Internal_setnearBlurAmount", (void*)&ScriptDepthOfFieldSettings::Internal_setnearBlurAmount);
metaData.scriptClass->addInternalCall("Internal_getfarBlurAmount", (void*)&ScriptDepthOfFieldSettings::Internal_getfarBlurAmount);
metaData.scriptClass->addInternalCall("Internal_setfarBlurAmount", (void*)&ScriptDepthOfFieldSettings::Internal_setfarBlurAmount);
metaData.scriptClass->addInternalCall("Internal_getmaxBokehSize", (void*)&ScriptDepthOfFieldSettings::Internal_getmaxBokehSize);
metaData.scriptClass->addInternalCall("Internal_setmaxBokehSize", (void*)&ScriptDepthOfFieldSettings::Internal_setmaxBokehSize);
metaData.scriptClass->addInternalCall("Internal_getadaptiveColorThreshold", (void*)&ScriptDepthOfFieldSettings::Internal_getadaptiveColorThreshold);
metaData.scriptClass->addInternalCall("Internal_setadaptiveColorThreshold", (void*)&ScriptDepthOfFieldSettings::Internal_setadaptiveColorThreshold);
metaData.scriptClass->addInternalCall("Internal_getadaptiveRadiusThreshold", (void*)&ScriptDepthOfFieldSettings::Internal_getadaptiveRadiusThreshold);
metaData.scriptClass->addInternalCall("Internal_setadaptiveRadiusThreshold", (void*)&ScriptDepthOfFieldSettings::Internal_setadaptiveRadiusThreshold);
metaData.scriptClass->addInternalCall("Internal_getapertureSize", (void*)&ScriptDepthOfFieldSettings::Internal_getapertureSize);
metaData.scriptClass->addInternalCall("Internal_setapertureSize", (void*)&ScriptDepthOfFieldSettings::Internal_setapertureSize);
metaData.scriptClass->addInternalCall("Internal_getfocalLength", (void*)&ScriptDepthOfFieldSettings::Internal_getfocalLength);
metaData.scriptClass->addInternalCall("Internal_setfocalLength", (void*)&ScriptDepthOfFieldSettings::Internal_setfocalLength);
metaData.scriptClass->addInternalCall("Internal_getsensorSize", (void*)&ScriptDepthOfFieldSettings::Internal_getsensorSize);
metaData.scriptClass->addInternalCall("Internal_setsensorSize", (void*)&ScriptDepthOfFieldSettings::Internal_setsensorSize);
metaData.scriptClass->addInternalCall("Internal_getbokehOcclusion", (void*)&ScriptDepthOfFieldSettings::Internal_getbokehOcclusion);
metaData.scriptClass->addInternalCall("Internal_setbokehOcclusion", (void*)&ScriptDepthOfFieldSettings::Internal_setbokehOcclusion);
metaData.scriptClass->addInternalCall("Internal_getocclusionDepthRange", (void*)&ScriptDepthOfFieldSettings::Internal_getocclusionDepthRange);
metaData.scriptClass->addInternalCall("Internal_setocclusionDepthRange", (void*)&ScriptDepthOfFieldSettings::Internal_setocclusionDepthRange);
}
MonoObject* ScriptDepthOfFieldSettings::create(const SPtr<DepthOfFieldSettings>& value)
{
if(value == nullptr) return nullptr;
bool dummy = false;
void* ctorParams[1] = { &dummy };
MonoObject* managedInstance = metaData.scriptClass->createInstance("bool", ctorParams);
new (bs_alloc<ScriptDepthOfFieldSettings>()) ScriptDepthOfFieldSettings(managedInstance, value);
return managedInstance;
}
void ScriptDepthOfFieldSettings::Internal_DepthOfFieldSettings(MonoObject* managedInstance)
{
SPtr<DepthOfFieldSettings> instance = bs_shared_ptr_new<DepthOfFieldSettings>();
new (bs_alloc<ScriptDepthOfFieldSettings>())ScriptDepthOfFieldSettings(managedInstance, instance);
}
MonoObject* ScriptDepthOfFieldSettings::Internal_getbokehShape(ScriptDepthOfFieldSettings* thisPtr)
{
ResourceHandle<Texture> tmp__output;
tmp__output = thisPtr->getInternal()->bokehShape;
MonoObject* __output;
ScriptRRefBase* script__output;
script__output = ScriptResourceManager::instance().getScriptRRef(tmp__output);
if(script__output != nullptr)
__output = script__output->getManagedInstance();
else
__output = nullptr;
return __output;
}
void ScriptDepthOfFieldSettings::Internal_setbokehShape(ScriptDepthOfFieldSettings* thisPtr, MonoObject* value)
{
ResourceHandle<Texture> tmpvalue;
ScriptRRefBase* scriptvalue;
scriptvalue = ScriptRRefBase::toNative(value);
if(scriptvalue != nullptr)
tmpvalue = static_resource_cast<Texture>(scriptvalue->getHandle());
thisPtr->getInternal()->bokehShape = tmpvalue;
}
bool ScriptDepthOfFieldSettings::Internal_getenabled(ScriptDepthOfFieldSettings* thisPtr)
{
bool tmp__output;
tmp__output = thisPtr->getInternal()->enabled;
bool __output;
__output = tmp__output;
return __output;
}
void ScriptDepthOfFieldSettings::Internal_setenabled(ScriptDepthOfFieldSettings* thisPtr, bool value)
{
thisPtr->getInternal()->enabled = value;
}
DepthOfFieldType ScriptDepthOfFieldSettings::Internal_gettype(ScriptDepthOfFieldSettings* thisPtr)
{
DepthOfFieldType tmp__output;
tmp__output = thisPtr->getInternal()->type;
DepthOfFieldType __output;
__output = tmp__output;
return __output;
}
void ScriptDepthOfFieldSettings::Internal_settype(ScriptDepthOfFieldSettings* thisPtr, DepthOfFieldType value)
{
thisPtr->getInternal()->type = value;
}
float ScriptDepthOfFieldSettings::Internal_getfocalDistance(ScriptDepthOfFieldSettings* thisPtr)
{
float tmp__output;
tmp__output = thisPtr->getInternal()->focalDistance;
float __output;
__output = tmp__output;
return __output;
}
void ScriptDepthOfFieldSettings::Internal_setfocalDistance(ScriptDepthOfFieldSettings* thisPtr, float value)
{
thisPtr->getInternal()->focalDistance = value;
}
float ScriptDepthOfFieldSettings::Internal_getfocalRange(ScriptDepthOfFieldSettings* thisPtr)
{
float tmp__output;
tmp__output = thisPtr->getInternal()->focalRange;
float __output;
__output = tmp__output;
return __output;
}
void ScriptDepthOfFieldSettings::Internal_setfocalRange(ScriptDepthOfFieldSettings* thisPtr, float value)
{
thisPtr->getInternal()->focalRange = value;
}
float ScriptDepthOfFieldSettings::Internal_getnearTransitionRange(ScriptDepthOfFieldSettings* thisPtr)
{
float tmp__output;
tmp__output = thisPtr->getInternal()->nearTransitionRange;
float __output;
__output = tmp__output;
return __output;
}
void ScriptDepthOfFieldSettings::Internal_setnearTransitionRange(ScriptDepthOfFieldSettings* thisPtr, float value)
{
thisPtr->getInternal()->nearTransitionRange = value;
}
float ScriptDepthOfFieldSettings::Internal_getfarTransitionRange(ScriptDepthOfFieldSettings* thisPtr)
{
float tmp__output;
tmp__output = thisPtr->getInternal()->farTransitionRange;
float __output;
__output = tmp__output;
return __output;
}
void ScriptDepthOfFieldSettings::Internal_setfarTransitionRange(ScriptDepthOfFieldSettings* thisPtr, float value)
{
thisPtr->getInternal()->farTransitionRange = value;
}
float ScriptDepthOfFieldSettings::Internal_getnearBlurAmount(ScriptDepthOfFieldSettings* thisPtr)
{
float tmp__output;
tmp__output = thisPtr->getInternal()->nearBlurAmount;
float __output;
__output = tmp__output;
return __output;
}
void ScriptDepthOfFieldSettings::Internal_setnearBlurAmount(ScriptDepthOfFieldSettings* thisPtr, float value)
{
thisPtr->getInternal()->nearBlurAmount = value;
}
float ScriptDepthOfFieldSettings::Internal_getfarBlurAmount(ScriptDepthOfFieldSettings* thisPtr)
{
float tmp__output;
tmp__output = thisPtr->getInternal()->farBlurAmount;
float __output;
__output = tmp__output;
return __output;
}
void ScriptDepthOfFieldSettings::Internal_setfarBlurAmount(ScriptDepthOfFieldSettings* thisPtr, float value)
{
thisPtr->getInternal()->farBlurAmount = value;
}
float ScriptDepthOfFieldSettings::Internal_getmaxBokehSize(ScriptDepthOfFieldSettings* thisPtr)
{
float tmp__output;
tmp__output = thisPtr->getInternal()->maxBokehSize;
float __output;
__output = tmp__output;
return __output;
}
void ScriptDepthOfFieldSettings::Internal_setmaxBokehSize(ScriptDepthOfFieldSettings* thisPtr, float value)
{
thisPtr->getInternal()->maxBokehSize = value;
}
float ScriptDepthOfFieldSettings::Internal_getadaptiveColorThreshold(ScriptDepthOfFieldSettings* thisPtr)
{
float tmp__output;
tmp__output = thisPtr->getInternal()->adaptiveColorThreshold;
float __output;
__output = tmp__output;
return __output;
}
void ScriptDepthOfFieldSettings::Internal_setadaptiveColorThreshold(ScriptDepthOfFieldSettings* thisPtr, float value)
{
thisPtr->getInternal()->adaptiveColorThreshold = value;
}
float ScriptDepthOfFieldSettings::Internal_getadaptiveRadiusThreshold(ScriptDepthOfFieldSettings* thisPtr)
{
float tmp__output;
tmp__output = thisPtr->getInternal()->adaptiveRadiusThreshold;
float __output;
__output = tmp__output;
return __output;
}
void ScriptDepthOfFieldSettings::Internal_setadaptiveRadiusThreshold(ScriptDepthOfFieldSettings* thisPtr, float value)
{
thisPtr->getInternal()->adaptiveRadiusThreshold = value;
}
float ScriptDepthOfFieldSettings::Internal_getapertureSize(ScriptDepthOfFieldSettings* thisPtr)
{
float tmp__output;
tmp__output = thisPtr->getInternal()->apertureSize;
float __output;
__output = tmp__output;
return __output;
}
void ScriptDepthOfFieldSettings::Internal_setapertureSize(ScriptDepthOfFieldSettings* thisPtr, float value)
{
thisPtr->getInternal()->apertureSize = value;
}
float ScriptDepthOfFieldSettings::Internal_getfocalLength(ScriptDepthOfFieldSettings* thisPtr)
{
float tmp__output;
tmp__output = thisPtr->getInternal()->focalLength;
float __output;
__output = tmp__output;
return __output;
}
void ScriptDepthOfFieldSettings::Internal_setfocalLength(ScriptDepthOfFieldSettings* thisPtr, float value)
{
thisPtr->getInternal()->focalLength = value;
}
void ScriptDepthOfFieldSettings::Internal_getsensorSize(ScriptDepthOfFieldSettings* thisPtr, Vector2* __output)
{
Vector2 tmp__output;
tmp__output = thisPtr->getInternal()->sensorSize;
*__output = tmp__output;
}
void ScriptDepthOfFieldSettings::Internal_setsensorSize(ScriptDepthOfFieldSettings* thisPtr, Vector2* value)
{
thisPtr->getInternal()->sensorSize = *value;
}
bool ScriptDepthOfFieldSettings::Internal_getbokehOcclusion(ScriptDepthOfFieldSettings* thisPtr)
{
bool tmp__output;
tmp__output = thisPtr->getInternal()->bokehOcclusion;
bool __output;
__output = tmp__output;
return __output;
}
void ScriptDepthOfFieldSettings::Internal_setbokehOcclusion(ScriptDepthOfFieldSettings* thisPtr, bool value)
{
thisPtr->getInternal()->bokehOcclusion = value;
}
float ScriptDepthOfFieldSettings::Internal_getocclusionDepthRange(ScriptDepthOfFieldSettings* thisPtr)
{
float tmp__output;
tmp__output = thisPtr->getInternal()->occlusionDepthRange;
float __output;
__output = tmp__output;
return __output;
}
void ScriptDepthOfFieldSettings::Internal_setocclusionDepthRange(ScriptDepthOfFieldSettings* thisPtr, float value)
{
thisPtr->getInternal()->occlusionDepthRange = value;
}
}
| 38.45098 | 152 | 0.810811 | bsf2dev |
d050bad08ff6baef46c9ae0185335ff561245b97 | 2,077 | cpp | C++ | PrettyEngine/src/engine/Events/Input.cpp | cristi191096/Pretty_Engine | 53a5d305b3de5786223e3ad6775199dbc7b5e90c | [
"Apache-2.0"
] | null | null | null | PrettyEngine/src/engine/Events/Input.cpp | cristi191096/Pretty_Engine | 53a5d305b3de5786223e3ad6775199dbc7b5e90c | [
"Apache-2.0"
] | null | null | null | PrettyEngine/src/engine/Events/Input.cpp | cristi191096/Pretty_Engine | 53a5d305b3de5786223e3ad6775199dbc7b5e90c | [
"Apache-2.0"
] | 1 | 2021-04-16T09:10:46.000Z | 2021-04-16T09:10:46.000Z | #include "pepch.h"
#include "Input.h"
#include "engine\Core\Context.h"
#include "Platform\OpenGL\GLInput.h"
namespace PrettyEngine {
bool InternalInput::m_Keys[MAX_KEYS];
bool InternalInput::m_MouseButtons[MAX_BUTTONS];
uint InternalInput::m_Mods = 0;
Vector2 InternalInput::m_MousePosition = Vector2(0, 0);
namespace Internal {
InternalInput* InternalInput::s_InputInstance = nullptr;
InternalInput::InternalInput()
{
ClearKeys();
ClearButtons();
}
InternalInput * InternalInput::GetInstance()
{
return s_InputInstance;
}
void InternalInput::Init()
{
if (s_InputInstance == nullptr)
{
switch (Context::GetRenderAPI())
{
case RenderAPI::OPENGL:
s_InputInstance = new GLInput();
break;
}
}
}
void InternalInput::ClearKeys()
{
for (int i = 0; i < MAX_KEYS; i++) {
m_Keys[i] = false;
}
}
void InternalInput::ClearButtons()
{
for (int i = 0; i < MAX_BUTTONS; i++)
m_MouseButtons[i] = false;
}
}
const Vector2& InternalInput::GetMousePosition() const
{
return m_MousePosition;
}
bool Input::GetKey(keyCode key)
{
return m_Keys[key];
}
bool Input::GetKeyUp(keyCode key)
{
if (!IsKeyPressed(key))
return true;
return false;
}
bool Input::GetKeyDown(keyCode key)
{
if (IsKeyPressed(key))
return true;
return false;
}
bool Input::IsModOn(uint mod)
{
if (m_Mods & mod)
return true;
return false;
}
bool Input::GetMouseButton(Mouse button)
{
return m_MouseButtons[button];
}
bool Input::GetMouseButtonDown(Mouse button)
{
if (IsButtonPressed(button))
return true;
return false;
}
bool Input::GetMouseButtonUp(Mouse button)
{
if (!IsButtonPressed(button))
return true;
return false;
}
bool Input::IsKeyPressed(keyCode k)
{
if (k >= MAX_KEYS || k == keyCode::NONE)
return false;
if (m_Keys[k] == true) {
return true;
}
return m_Keys[k];
}
bool Input::IsButtonPressed(Mouse b)
{
if (b >= MAX_BUTTONS)
return false;
return m_MouseButtons[b];
}
}
| 14.423611 | 58 | 0.649013 | cristi191096 |
d052a85a353cc0d92ab2f297471868b8907d4e6e | 562 | cpp | C++ | examples/q0_basics/src/objects/Cat.cpp | ubc333/library | 069d68e822992950739661f5f7a7bdffe8d425d4 | [
"MIT"
] | null | null | null | examples/q0_basics/src/objects/Cat.cpp | ubc333/library | 069d68e822992950739661f5f7a7bdffe8d425d4 | [
"MIT"
] | null | null | null | examples/q0_basics/src/objects/Cat.cpp | ubc333/library | 069d68e822992950739661f5f7a7bdffe8d425d4 | [
"MIT"
] | null | null | null | #include "Cat.h"
#include <string>
Cat::Cat(std::string name, int age) : Animal(name, age) { // pass the name and age to the parent constructor
// initialize anything else unique to Cat
}
Cat::~Cat() {
// clear any dynamic memory unique to Cat
}
// Override "Speak"
std::string Cat::speak() {
return "meow";
}
// Class of referring type (not overridden, but can be hidden)
std::string Cat::type() {
return "Cat";
}
std::string Cat::rule() {
// ... if you are a cat person, I suppose you might think so...
return "rule";
} | 22.48 | 109 | 0.624555 | ubc333 |
d053cde7f47f41ecae161805137b82bd4fdc4c9a | 1,439 | cpp | C++ | tests/stopwatch_test.cpp | cameronbroe/libstopwatch | e050a2f20caf66d18c9473d2a31f501e783ab679 | [
"MIT"
] | null | null | null | tests/stopwatch_test.cpp | cameronbroe/libstopwatch | e050a2f20caf66d18c9473d2a31f501e783ab679 | [
"MIT"
] | null | null | null | tests/stopwatch_test.cpp | cameronbroe/libstopwatch | e050a2f20caf66d18c9473d2a31f501e783ab679 | [
"MIT"
] | null | null | null | #include <catch2/catch.hpp>
#include <iostream>
#include "stopwatch.h"
TEST_CASE("Testing single task stopwatch", "[multi-file:stopwatch]") {
stopwatch::Stopwatch stopwatch;
SECTION("should execute a task at 5 ticks") {
bool five_ticks_ran = false;
auto five_ticks = [&five_ticks_ran]() {
five_ticks_ran = true;
};
stopwatch.add_single_task(5, five_ticks);
stopwatch.start();
std::this_thread::sleep_for(std::chrono::seconds(6));
stopwatch.stop();
REQUIRE(five_ticks_ran);
}
SECTION("should execute a task at 10 ticks") {
bool ten_ticks_ran = false;
auto ten_ticks = [&ten_ticks_ran]() {
ten_ticks_ran = true;
};
stopwatch.add_single_task(10, ten_ticks);
stopwatch.start();
std::this_thread::sleep_for(std::chrono::seconds(11));
stopwatch.stop();
REQUIRE(ten_ticks_ran);
}
}
TEST_CASE("Testing recurring task stopwatch", "[multi-file:stopwatch]") {
stopwatch::Stopwatch stopwatch;
SECTION("should execute 5 times in 5 ticks") {
int tick_count = 0;
auto increment_tick = [&tick_count]() {
tick_count++;
};
stopwatch.add_recurring_task(1, increment_tick);
stopwatch.start();
std::this_thread::sleep_for(std::chrono::seconds(5));
stopwatch.stop();
REQUIRE(tick_count == 5);
}
} | 30.617021 | 73 | 0.608756 | cameronbroe |
d05726041161b0a56f6c0fcaf1a4fb75ec047fea | 571 | cpp | C++ | src/ndhist/stats/mean.cpp | martwo/ndhist | 193cef3585b5d0277f0721bb9c3a1e78cc67cf1f | [
"BSD-2-Clause"
] | null | null | null | src/ndhist/stats/mean.cpp | martwo/ndhist | 193cef3585b5d0277f0721bb9c3a1e78cc67cf1f | [
"BSD-2-Clause"
] | null | null | null | src/ndhist/stats/mean.cpp | martwo/ndhist | 193cef3585b5d0277f0721bb9c3a1e78cc67cf1f | [
"BSD-2-Clause"
] | null | null | null | /**
* $Id$
*
* Copyright (C)
* 2015 - $Date$
* Martin Wolf <[email protected]>
*
* This file is distributed under the BSD 2-Clause Open Source License
* (See LICENSE file).
*
*/
#include <boost/python.hpp>
#include <ndhist/stats/expectation.hpp>
#include <ndhist/stats/mean.hpp>
namespace bp = boost::python;
namespace bn = boost::numpy;
namespace ndhist {
namespace stats {
namespace py {
bp::object
mean(ndhist const & h, bp::object const & axis)
{
return expectation(h, 1, axis);
}
}// namespace py
}// namespace stats
}// namespace ndhist
| 17.30303 | 70 | 0.672504 | martwo |
d05a883ddf9c9707c89ad87fd2660c45d3b9ae24 | 10,981 | cc | C++ | src/tools/detector_repeatability.cc | jackyspeed/libmv | aae2e0b825b1c933d6e8ec796b8bb0214a508a84 | [
"MIT"
] | 160 | 2015-01-16T19:35:28.000Z | 2022-03-16T02:55:30.000Z | src/tools/detector_repeatability.cc | rgkoo/libmv-blender | cdf65edbb80d8904e2df9a20116d02546df93a81 | [
"MIT"
] | 3 | 2015-04-04T17:54:35.000Z | 2015-12-15T18:09:03.000Z | src/tools/detector_repeatability.cc | rgkoo/libmv-blender | cdf65edbb80d8904e2df9a20116d02546df93a81 | [
"MIT"
] | 51 | 2015-01-12T08:38:12.000Z | 2022-02-19T06:37:25.000Z | // Copyright (c) 2010 libmv authors.
//
// Permission is hereby granted, free of charge, to any person obtaining a copy
// of this software and associated documentation files (the "Software"), to
// deal in the Software without restriction, including without limitation the
// rights to use, copy, modify, merge, publish, distribute, sublicense, and/or
// sell copies of the Software, and to permit persons to whom the Software is
// furnished to do so, subject to the following conditions:
//
// The above copyright notice and this permission notice shall be included in
// all copies or substantial portions of the Software.
//
// THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
// IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
// FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
// AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
// LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING
// FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS
// IN THE SOFTWARE.
#include <fstream>
#include <iostream>
#include "libmv/base/scoped_ptr.h"
#include "libmv/base/vector.h"
#include "libmv/base/vector_utils.h"
#include "libmv/correspondence/feature.h"
#include "libmv/detector/detector.h"
#include "libmv/detector/fast_detector.h"
#include "libmv/detector/star_detector.h"
#include "libmv/detector/surf_detector.h"
#include "libmv/image/image.h"
#include "libmv/image/image_converter.h"
#include "libmv/image/image_drawing.h"
#include "libmv/image/image_io.h"
#include "libmv/tools/tool.h"
using namespace libmv;
using namespace std;
void usage() {
LOG(ERROR) << " repreatability ImageReference ImageA ImageB ... " <<std::endl
<< " ImageReference : the input image on which features will be extrated,"
<< std::endl
<< " ImageA : an image to test repeatability with ImageReference"
<< std::endl
<< " ImageB : an image to test repeatability with ImageReference"
<< std::endl
<< " ... : images names to test repeatability with ImageReference"
<< std::endl
<< " Gound truth transformation between ImageReference and ImageX is named\
in ImageX.txt"
<< " INFO : !!! experimental !!! ." << std::endl;
}
enum eDetectorType
{
FAST_DETECTOR = 0,
SURF_DETECTOR = 1,
STAR_DETECTOR = 2
};
// Detect features over the image im with the choosen detector type.
bool detectFeatures(const eDetectorType DetectorType,
const Image & im,
libmv::vector<libmv::Feature *> * featuresOut);
// Search how many feature are considered as repeatable.
// Ground Truth transformation is encoded in a matrix saved into a file.
// Example : ImageNameB.jpg.txt encode the transformation matrix from
// imageReference to ImageNameB.jpg.
bool testRepeatability(const libmv::vector<libmv::Feature *> & featuresA,
const libmv::vector<libmv::Feature *> & featuresB,
const string & ImageNameB,
const Image & imageB,
libmv::vector<double> * exportedData = NULL,
ostringstream * stringStream = NULL);
int main(int argc, char **argv) {
libmv::Init("Extract features from on images series and test detector \
repeatability", &argc, &argv);
if (argc < 3 ||
(GetFormat(argv[1])==Unknown && GetFormat(argv[2])==Unknown)) {
usage();
LOG(ERROR) << "Missing parameters or errors in the command line.";
return 1;
}
// Parse input parameter.
const string sImageReference = argv[1];
ByteImage byteImage;
if ( 0 == ReadImage( sImageReference.c_str(), &byteImage) ) {
LOG(ERROR) << "Invalid inputImage.";
return 1;
}
Image imageReference(new ByteImage(byteImage));
if( byteImage.Depth() == 3)
{
// Convert Image to desirable format => uchar 1 gray channel
ByteImage byteImageGray;
Rgb2Gray(byteImage, &byteImageGray);
imageReference=Image(new ByteImage(byteImageGray));
}
eDetectorType DETECTOR_TYPE = FAST_DETECTOR;
libmv::vector<libmv::Feature *> featuresRef;
if ( !detectFeatures( DETECTOR_TYPE,
imageReference,
&featuresRef))
{
LOG(ERROR) << "No feature found on Reference Image.";
return 1;
}
libmv::vector<double> repeatabilityStat;
// Run repeatability test on the N remaining images.
for(int i = 2; i < argc; ++i)
{
const string sImageToCompare = argv[i];
libmv::vector<libmv::Feature *> featuresToCompare;
if ( 0 == ReadImage( sImageToCompare.c_str(), &byteImage) ) {
LOG(ERROR) << "Invalid inputImage (Image to compare to reference).";
return 1;
}
Image imageToCompare(new ByteImage(byteImage));
if( byteImage.Depth() == 3)
{
// Convert Image to desirable format => uchar 1 gray channel
ByteImage byteImageGray;
Rgb2Gray(byteImage, &byteImageGray);
imageToCompare = Image(new ByteImage(byteImageGray));
}
if (detectFeatures(DETECTOR_TYPE,
imageToCompare,
&featuresToCompare))
{
testRepeatability( featuresRef,
featuresToCompare,
sImageToCompare + string(".txt"),
imageToCompare,
&repeatabilityStat);
}
else
{
LOG(INFO) << "Image : " << sImageToCompare
<< " have no feature detected with the choosen detector.";
}
DeleteElements(&featuresToCompare);
}
// Export data :
ofstream fileStream("Repeatability.xls");
fileStream << "RepeatabilityStats" << endl;
fileStream << "ImageName \t Feature In Reference \t Features In ImageName \
\t Position Repeatability \t Position Accuracy" << endl;
int cpt=0;
for (int i = 2; i < argc; ++i) {
fileStream << argv[i] << "\t";
for (int j=0; j < repeatabilityStat.size()/(argc-2); ++j) {
fileStream << repeatabilityStat[cpt] << "\t";
cpt++;
}
fileStream << endl;
}
DeleteElements(&featuresRef);
fileStream.close();
}
bool detectFeatures(const eDetectorType DetectorType,
const Image & im,
libmv::vector<libmv::Feature *> * featuresOut)
{
using namespace detector;
switch (DetectorType) {
case FAST_DETECTOR:
{
scoped_ptr<Detector> detector(CreateFastDetector(9, 30));
detector->Detect( im, featuresOut, NULL);
}
break;
case SURF_DETECTOR:
{
scoped_ptr<Detector> detector(CreateSURFDetector());
detector->Detect( im, featuresOut, NULL);
}
break;
case STAR_DETECTOR:
{
scoped_ptr<Detector> detector(CreateStarDetector());
detector->Detect( im, featuresOut, NULL);
}
break;
default:
{
scoped_ptr<Detector> detector(CreateFastDetector(9, 30));
detector->Detect( im, featuresOut, NULL);
}
}
return (featuresOut->size() >= 1);
}
bool testRepeatability(const libmv::vector<libmv::Feature *> & featuresA,
const libmv::vector<libmv::Feature *> & featuresB,
const string & ImageNameB,
const Image & imageB,
libmv::vector<double> * exportedData,
ostringstream * stringStream)
{
// Config Threshold for repeatability
const double distThreshold = 1.5;
//
Mat3 transfoMatrix;
if(ImageNameB.size() > 0 ) {
// Read transformation matrix from data
ifstream file( ImageNameB.c_str());
if(file.is_open()) {
for(int i=0; i<3*3; ++i) {
file>>transfoMatrix(i);
}
// Transpose cannot be used inplace.
Mat3 temp = transfoMatrix.transpose();
transfoMatrix = temp;
}
else {
LOG(ERROR) << "Invalid input transformation file.";
if (stringStream) {
(*stringStream) << "Invalid input transformation file.";
}
if(exportedData) {
exportedData->push_back(featuresA.size());
exportedData->push_back(featuresB.size());
exportedData->push_back(0);
exportedData->push_back(0);
}
return 0;
}
}
int nbRepeatable = 0;
int nbRepeatablePossible = 0;
double localisationError = 0;
for (int iA=0; iA < featuresA.size(); ++iA) {
const libmv::PointFeature * featureA =
dynamic_cast<libmv::PointFeature *>( featuresA[iA] );
// Project A into the image coord system B.
Vec3 pos; pos << featureA->x(), featureA->y(), 1.0;
Vec3 transformed = transfoMatrix * pos;
transformed/=transformed(2);
//Search the nearest featureB
double distanceSearch = std::numeric_limits<double>::max();
int indiceFound = -1;
// Check if imageB Contain the projected point.
if ( imageB.AsArray3Du()->Contains(pos(0), pos(1)) ) {
++nbRepeatablePossible; //This feature could be detected in imageB also
for (int iB=0; iB < featuresB.size(); ++iB) {
const libmv::PointFeature * featureB =
dynamic_cast<libmv::PointFeature *>( featuresB[iB] );
Vec3 posB; posB << featureB->x(), featureB->y(), 1.0;
//Test distance over the two points.
double distance = DistanceL2(transformed,posB);
//If small enough consider the point can be the same
if ( distance <= distThreshold ) {
distanceSearch = distance;
indiceFound = iB;
}
}
}
if ( indiceFound != -1 ) {
//(test other parameter scale, orientation if any)
++nbRepeatable;
const libmv::PointFeature * featureB =
dynamic_cast<libmv::PointFeature *>( featuresB[indiceFound] );
Vec3 posB; posB << featureB->x(), featureB->y(), 1.0;
//Test distance over the two points.
double distance = DistanceL2(transformed,posB);
//cout << endl << distance;
localisationError += distance;
}
}
if( nbRepeatable >0 ) {
localisationError/= nbRepeatable;
}
else {
localisationError = 0;
}
nbRepeatablePossible = min(nbRepeatablePossible, featuresB.size());
ostringstream os;
os<< endl << " Feature Repeatability " << ImageNameB << endl
<< " ---------------------- " << endl
<< " Image A get\t" << featuresA.size() << "\tfeatures" << endl
<< " Image B get\t" << featuresB.size() << "\tfeatures" << endl
<< " ---------------------- " << endl
<< " Position repeatability :\t" <<
nbRepeatable / (double) nbRepeatablePossible * 100 << endl
<< " Position mean error :\t" << localisationError << endl;
cout << os.str();
if (stringStream) {
(*stringStream) << os.str();
}
if(exportedData) {
exportedData->push_back(featuresA.size());
exportedData->push_back(featuresB.size());
exportedData->push_back(nbRepeatable/(double) nbRepeatablePossible * 100);
exportedData->push_back(localisationError);
}
return (nbRepeatable != 0);
}
| 34.315625 | 79 | 0.63282 | jackyspeed |
d0652089a44a2e967f114c79d7184a24b5410986 | 1,310 | cpp | C++ | problems/592.fraction-addition-and-subtraction.cpp | bigfishi/leetcode | 3e512f2822a742349384a0bdd7954696f5867683 | [
"MIT"
] | null | null | null | problems/592.fraction-addition-and-subtraction.cpp | bigfishi/leetcode | 3e512f2822a742349384a0bdd7954696f5867683 | [
"MIT"
] | null | null | null | problems/592.fraction-addition-and-subtraction.cpp | bigfishi/leetcode | 3e512f2822a742349384a0bdd7954696f5867683 | [
"MIT"
] | null | null | null | // 中等 需要用到求最大公约数,需要注意越界,另外,提交错了一次,因为没考虑分子分母为10的情况
typedef long long llong;
class Solution {
int calcGcd(llong x, llong y) {
int z = y;
while (z)
{
y = x%y;
x = z;
z = y;
}
return x;
}
void calcFraction(int& x, int& y, int x2, int y2) {
llong tx = x*y2 + x2*y;
llong ty = y*y2;
int c = calcGcd(abs(tx), ty);
x = tx / c;
y = ty / c;
}
public:
string fractionAddition(string expression) {
int x = 0, y = 1;
if (expression.size() == 0) return to_string(x) + "/" + to_string(y);
int n = expression.size();
int i = 0;
while (i<n)
{
int x2, y2;
bool isNag = false;
if (expression[i] == '+') i++;
if (expression[i] == '-') {
isNag = true;
i++;
}
if (i + 1 < n && expression[i + 1] >= '0' && expression[i + 1] <= '9') {
x2 = (expression[i] - '0') * 10 + expression[i + 1] - '0';
i += 3;
}
else {
x2 = expression[i] - '0';
i+=2;
}
if (isNag) x2 = -x2;
if (i + 1 < n && expression[i + 1] >= '0' && expression[i + 1] <= '9') {
y2 = (expression[i] - '0') * 10 + expression[i + 1] - '0';
i++;
}
else {
y2 = expression[i] - '0';
}
calcFraction(x, y, x2, y2);
i++;
}
string res = "";
if (x < 0) {
res += '-';
x = -x;
}
res += to_string(x) + "/" + to_string(y);
return res;
}
}; | 20.793651 | 75 | 0.478626 | bigfishi |
d07799f859fdd5946f514a4a8014043e145777cf | 4,468 | cc | C++ | src/planereel/main.cc | grendello/notcursespp | bc04b1445c7e50fc3cb7b3c7f0fc15b8781d2f31 | [
"BSD-3-Clause"
] | null | null | null | src/planereel/main.cc | grendello/notcursespp | bc04b1445c7e50fc3cb7b3c7f0fc15b8781d2f31 | [
"BSD-3-Clause"
] | null | null | null | src/planereel/main.cc | grendello/notcursespp | bc04b1445c7e50fc3cb7b3c7f0fc15b8781d2f31 | [
"BSD-3-Clause"
] | 1 | 2020-02-13T02:00:06.000Z | 2020-02-13T02:00:06.000Z | #include <cstdlib>
#include <clocale>
#include <sstream>
#include <getopt.h>
#include <iostream>
#include <ncpp/NotCurses.hh>
#include <ncpp/PanelReel.hh>
#include <ncpp/NCKey.hh>
using namespace ncpp;
// FIXME ought be able to get pr from tablet, methinks?
static PanelReel* PR;
class TabletCtx {
public:
TabletCtx () : lines (rand() % 5 + 3)
{}
int getLines () const
{
return lines;
}
private:
int lines;
};
int tabletfxn (tablet* tb, int begx, int begy, int maxx, int maxy, bool cliptop)
{
Tablet *t = Tablet::map_tablet (tb);
Plane* p = t->get_plane ();
auto *tctx = t->get_userptr<TabletCtx> ();
p->erase ();
Cell c (' ');
c.set_bg ((((uintptr_t)t) % 0x1000000) + cliptop + begx + maxx);
p->set_base (c);
p->release (c);
return tctx->getLines () > maxy - begy ? maxy - begy : tctx->getLines ();
}
void usage (const char* argv0, std::ostream& c, int status)
{
c << "usage: " << argv0 << " [ -h ] | options" << std::endl;
c << " --ot: offset from top" << std::endl;
c << " --ob: offset from bottom" << std::endl;
c << " --ol: offset from left" << std::endl;
c << " --or: offset from right" << std::endl;
c << " -b bordermask: hex panelreel border mask (0x0..0xf)" << std::endl;
c << " -t tabletmask: hex tablet border mask (0x0..0xf)" << std::endl;
exit (status);
}
constexpr int OPT_TOPOFF = 100;
constexpr int OPT_BOTTOMOFF = 101;
constexpr int OPT_LEFTOFF = 102;
constexpr int OPT_RIGHTOFF = 103;
void parse_args (int argc, char** argv, struct notcurses_options* opts, struct panelreel_options* popts)
{
const struct option longopts[] = {
{ /*.name =*/ "ot", /*.has_arg =*/ 1, /*.flag =*/ nullptr, OPT_TOPOFF, },
{ /*.name =*/ "ob", /*.has_arg =*/ 1, /*.flag =*/ nullptr, OPT_BOTTOMOFF, },
{ /*.name =*/ "ol", /*.has_arg =*/ 1, /*.flag =*/ nullptr, OPT_LEFTOFF, },
{ /*.name =*/ "or", /*.has_arg =*/ 1, /*.flag =*/ nullptr, OPT_RIGHTOFF, },
{ /*.name =*/ nullptr, /*.has_arg =*/ 0, /*.flag =*/ nullptr, 0, },
};
int c;
while ((c = getopt_long (argc, argv, "b:t:h", longopts, nullptr)) != -1) {
switch (c) {
case OPT_BOTTOMOFF: {
std::stringstream ss;
ss << optarg;
ss >> popts->boff;
break;
}
case OPT_TOPOFF: {
std::stringstream ss;
ss << optarg;
ss >> popts->toff;
break;
}
case OPT_LEFTOFF: {
std::stringstream ss;
ss << optarg;
ss >> popts->loff;
break;
}
case OPT_RIGHTOFF: {
std::stringstream ss;
ss << optarg;
ss >> popts->roff;
break;
}
case 'b': {
std::stringstream ss;
ss << std::hex << optarg;
ss >> popts->bordermask;
break;
}
case 't': {
std::stringstream ss;
ss << std::hex << optarg;
ss >> popts->tabletmask;
break;
}
case 'h':
usage (argv[0], std::cout, EXIT_SUCCESS);
break;
default:
std::cerr << "Unknown option" << std::endl;
usage (argv[0], std::cerr, EXIT_FAILURE);
break;
}
}
opts->suppress_banner = true;
opts->clear_screen_start = true;
}
int main (int argc, char **argv)
{
if (setlocale(LC_ALL, "") == nullptr) {
return EXIT_FAILURE;
}
parse_args (argc, argv, &NotCurses::default_notcurses_options, &PanelReel::default_options);
NotCurses &nc = NotCurses::get_instance ();
nc.init ();
if(!nc) {
return EXIT_FAILURE;
}
Plane* nstd = nc.get_stdplane ();
int dimy, dimx;
nstd->get_dim (&dimy, &dimx);
auto n = new Plane (dimy - 1, dimx, 1, 0);
if(!n) {
return EXIT_FAILURE;
}
if (!n->set_fg (0xb11bb1)) {
return EXIT_FAILURE;
}
if(n->putstr (0, NCAlign::Center, "(a)dd (d)el (q)uit") <= 0) {
return EXIT_FAILURE;
}
channels_set_fg (&PanelReel::default_options.focusedchan, 0xffffff);
channels_set_bg (&PanelReel::default_options.focusedchan, 0x00c080);
channels_set_fg (&PanelReel::default_options.borderchan, 0x00c080);
PanelReel* pr = n->panelreel_create ();
if (pr == nullptr || !nc.render ()) {
return EXIT_FAILURE;
}
PR = pr; // FIXME eliminate
char32_t key;
while ((key = nc.getc (true)) != (char32_t)-1) {
switch (key) {
case 'q':
return EXIT_SUCCESS;
case 'a':{
TabletCtx* tctx = new TabletCtx ();
pr->add (nullptr, nullptr, tabletfxn, tctx);
break;
}
case 'd':
pr->del_focused ();
break;
case NCKey::Up:
pr->prev ();
break;
case NCKey::Down:
pr->next ();
break;
default:
break;
}
if (!nc.render ()) {
break;
}
}
return EXIT_FAILURE;
}
| 21.68932 | 104 | 0.591316 | grendello |
d07a4890c416de6063c444d8d564eee1b8990a9d | 4,544 | cc | C++ | crawl-ref/source/misc.cc | ricobadico/crawl | 4b524a92c8bf23403f40adf829a1419efde1a0ee | [
"CC0-1.0"
] | 5 | 2019-11-18T11:05:13.000Z | 2021-04-08T15:49:06.000Z | crawl-ref/source/misc.cc | ricobadico/crawl | 4b524a92c8bf23403f40adf829a1419efde1a0ee | [
"CC0-1.0"
] | null | null | null | crawl-ref/source/misc.cc | ricobadico/crawl | 4b524a92c8bf23403f40adf829a1419efde1a0ee | [
"CC0-1.0"
] | 5 | 2019-11-20T14:28:02.000Z | 2021-09-17T14:47:55.000Z | /**
* @file
* @brief Misc functions.
**/
#include "AppHdr.h"
#include "misc.h"
#include <algorithm>
#include <cstdio>
#include <cstdlib>
#include <cstring>
#ifdef UNIX
#include <unistd.h>
#endif
#include "database.h"
#include "english.h"
#include "items.h"
#include "libutil.h"
#include "monster.h"
#include "state.h"
#include "terrain.h"
#include "tileview.h"
#include "traps.h"
string weird_glowing_colour()
{
return getMiscString("glowing_colour_name");
}
// Make the player swap positions with a given monster.
void swap_with_monster(monster* mon_to_swap)
{
monster& mon(*mon_to_swap);
ASSERT(mon.alive());
const coord_def newpos = mon.pos();
if (you.stasis())
{
mpr("Your stasis prevents you from teleporting.");
return;
}
// Be nice: no swapping into uninhabitable environments.
if (!you.is_habitable(newpos) || !mon.is_habitable(you.pos()))
{
mpr("You spin around.");
return;
}
const bool mon_caught = mon.caught();
const bool you_caught = you.attribute[ATTR_HELD];
mprf("You swap places with %s.", mon.name(DESC_THE).c_str());
mon.move_to_pos(you.pos(), true, true);
// XXX: destroy ammo == 1 webs if they don't catch the mons? very rare case
if (you_caught)
{
// XXX: this doesn't correctly handle web traps
check_net_will_hold_monster(&mon);
if (!mon_caught)
stop_being_held();
}
// Move you to its previous location.
move_player_to_grid(newpos, false);
if (mon_caught)
{
// XXX: destroy ammo == 1 webs? (rare case)
if (you.body_size(PSIZE_BODY) >= SIZE_GIANT) // e.g. dragonform
{
int net = get_trapping_net(you.pos());
if (net != NON_ITEM)
{
destroy_item(net);
mpr("The net rips apart!");
}
if (you_caught)
stop_being_held();
}
else // XXX: doesn't handle e.g. spiderform swapped into webs
{
you.attribute[ATTR_HELD] = 1;
if (get_trapping_net(you.pos()) != NON_ITEM)
mpr("You become entangled in the net!");
else
mpr("You get stuck in the web!");
you.redraw_quiver = true; // Account for being in a net.
you.redraw_evasion = true;
}
if (!you_caught)
mon.del_ench(ENCH_HELD, true);
}
}
void handle_real_time(chrono::time_point<chrono::system_clock> now)
{
const chrono::milliseconds elapsed =
chrono::duration_cast<chrono::milliseconds>(now - you.last_keypress_time);
you.real_time_delta = min<chrono::milliseconds>(
elapsed,
(chrono::milliseconds)(IDLE_TIME_CLAMP * 1000));
you.real_time_ms += you.real_time_delta;
you.last_keypress_time = now;
}
unsigned int breakpoint_rank(int val, const int breakpoints[],
unsigned int num_breakpoints)
{
unsigned int result = 0;
while (result < num_breakpoints && val >= breakpoints[result])
++result;
return result;
}
void counted_monster_list::add(const monster* mons)
{
const string name = mons->name(DESC_PLAIN);
for (auto &entry : list)
{
if (entry.first->name(DESC_PLAIN) == name)
{
entry.second++;
return;
}
}
list.emplace_back(mons, 1);
}
int counted_monster_list::count()
{
int nmons = 0;
for (const auto &entry : list)
nmons += entry.second;
return nmons;
}
string counted_monster_list::describe(description_level_type desc)
{
string out;
for (auto i = list.begin(); i != list.end();)
{
const counted_monster &cm(*i);
if (i != list.begin())
{
++i;
out += (i == list.end() ? " and " : ", ");
}
else
++i;
out += cm.second > 1
? pluralise_monster(cm.first->name(desc, false, true))
: cm.first->name(desc);
}
return out;
}
bool tobool(maybe_bool mb, bool def)
{
switch (mb)
{
case MB_TRUE:
return true;
case MB_FALSE:
return false;
case MB_MAYBE:
default:
return def;
}
}
maybe_bool frombool(bool b)
{
return b ? MB_TRUE : MB_FALSE;
}
const string maybe_to_string(const maybe_bool mb)
{
switch (mb)
{
case MB_TRUE:
return "true";
case MB_FALSE:
return "false";
case MB_MAYBE:
default:
return "maybe";
}
}
| 22.49505 | 79 | 0.578345 | ricobadico |
4ee3fdadfd9b232f59bcc391252582692619b014 | 735 | cpp | C++ | 3. Longest Substring Without Repeating Characters.cpp | TIAN-2001/leetcode | 90374b976a1db24c0cb4ebf25593aad0207e3706 | [
"Apache-2.0"
] | null | null | null | 3. Longest Substring Without Repeating Characters.cpp | TIAN-2001/leetcode | 90374b976a1db24c0cb4ebf25593aad0207e3706 | [
"Apache-2.0"
] | null | null | null | 3. Longest Substring Without Repeating Characters.cpp | TIAN-2001/leetcode | 90374b976a1db24c0cb4ebf25593aad0207e3706 | [
"Apache-2.0"
] | null | null | null | // sliding window / two pointers
class Solution {
public:
int lengthOfLongestSubstring(string s) {
int res = 0;
if(s.length() == 0)
return res;
int left = 0;
int right = 0;
unordered_map<char,int> mp;
char c;
while(right < s.length()){
c = s[right];
mp[c] += 1;
if(mp[c] == 1){
res = max(res, right - left + 1);
} else {
while(mp[c] > 1){
char cl = s[left];
--mp[cl];
++left;
}
}
++right;
}
return res;
}
}; | 22.96875 | 62 | 0.334694 | TIAN-2001 |
4ee600fac45e55d775f4ed0e974b4dafa265f1c4 | 2,216 | cc | C++ | src/logkafka/file_position_entry.cc | Qihoo360/logkafka | f329b5a9806e0b0f716884759edbe54e72e4dec0 | [
"MIT"
] | 568 | 2015-06-23T07:41:50.000Z | 2022-03-30T11:32:05.000Z | src/logkafka/file_position_entry.cc | Qihoo360/logkafka | f329b5a9806e0b0f716884759edbe54e72e4dec0 | [
"MIT"
] | 26 | 2015-09-27T07:25:31.000Z | 2021-07-25T13:30:09.000Z | src/logkafka/file_position_entry.cc | Qihoo360/logkafka | f329b5a9806e0b0f716884759edbe54e72e4dec0 | [
"MIT"
] | 138 | 2015-06-23T07:41:50.000Z | 2021-12-13T02:31:40.000Z | ///////////////////////////////////////////////////////////////////////////
//
// logkafka - Collect logs and send lines to Apache Kafka v0.8+
//
///////////////////////////////////////////////////////////////////////////
//
// Copyright (c) 2015 Qihoo 360 Technology Co., Ltd. All rights reserved.
//
// Licensed under the MIT 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://opensource.org/licenses/MIT
//
// 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 "logkafka/file_position_entry.h"
namespace logkafka {
const size_t FilePositionEntry::POS_SIZE = 16;
const size_t FilePositionEntry::INO_OFFSET = 17;
const size_t FilePositionEntry::INO_SIZE = 8;
const int FilePositionEntry::LN_OFFSET = 25;
const int FilePositionEntry::SIZE = 26;
FilePositionEntry::FilePositionEntry(FILE *file, off_t seek)
{/*{{{*/
m_file = file;
m_seek = seek;
}/*}}}*/
bool FilePositionEntry::update(ino_t inode, off_t pos)
{/*{{{*/
fseek(m_file, m_seek, SEEK_SET);
fprintf(m_file, "%016llx\t%08x",
(unsigned long long)pos, (unsigned int)inode);
return true;
}/*}}}*/
bool FilePositionEntry::updatePos(off_t pos)
{/*{{{*/
fseek(m_file, m_seek, SEEK_SET);
fprintf(m_file, "%016llx", (unsigned long long)pos);
return true;
}/*}}}*/
off_t FilePositionEntry::readPos()
{/*{{{*/
fseek(m_file, m_seek, SEEK_SET);
char buf[POS_SIZE + 1] = {'\0'};
return (1 == fread(buf, POS_SIZE, 1, m_file)) ?
hexstr2num(buf, -1): -1;
}/*}}}*/
ino_t FilePositionEntry::readInode()
{/*{{{*/
fseek(m_file, m_seek + INO_OFFSET, SEEK_SET);
char buf[INO_SIZE + 1] = {'\0'};
return (1 == fread(buf, INO_SIZE, 1, m_file)) ?
hexstr2num(buf, INO_NONE): INO_NONE;
}/*}}}*/
} // namespace logkafka
| 30.777778 | 75 | 0.603791 | Qihoo360 |
4ee9a23806391c6723a2a998e4565d221823d456 | 337 | hpp | C++ | src/graphics/TestWindow.hpp | TobiasNienhaus/npp | ff6023ad5c160240cbaa029dce065b2cdf58ae74 | [
"MIT"
] | null | null | null | src/graphics/TestWindow.hpp | TobiasNienhaus/npp | ff6023ad5c160240cbaa029dce065b2cdf58ae74 | [
"MIT"
] | null | null | null | src/graphics/TestWindow.hpp | TobiasNienhaus/npp | ff6023ad5c160240cbaa029dce065b2cdf58ae74 | [
"MIT"
] | null | null | null | //
// Created by Tobias on 1/5/2021.
//
#ifndef NPP_TESTWINDOW_HPP
#define NPP_TESTWINDOW_HPP
#include "Win32Context.hpp"
class TestWindow : public Win32Context<TestWindow> {
public:
[[nodiscard]] LPCWSTR class_name() const override;
LRESULT handle_message(UINT msg, WPARAM wp, LPARAM lp) override;
};
#endif // NPP_TESTWINDOW_HPP
| 19.823529 | 65 | 0.759644 | TobiasNienhaus |
4eea6555b105295ce9dad341ada76a386bc7f836 | 2,539 | cpp | C++ | src/anytime.cpp | erdos-project/frenet-optimal-trajectory-planner | ba0cb5662a0e2ea668b1c2b2951c0f6b84f44f5b | [
"Apache-2.0"
] | null | null | null | src/anytime.cpp | erdos-project/frenet-optimal-trajectory-planner | ba0cb5662a0e2ea668b1c2b2951c0f6b84f44f5b | [
"Apache-2.0"
] | null | null | null | src/anytime.cpp | erdos-project/frenet-optimal-trajectory-planner | ba0cb5662a0e2ea668b1c2b2951c0f6b84f44f5b | [
"Apache-2.0"
] | 1 | 2020-03-07T01:49:50.000Z | 2020-03-07T01:49:50.000Z | #include "AnytimeFrenetOptimalTrajectory.h"
#include "FrenetPath.h"
#include "py_cpp_struct.h"
#include <iostream>
#include <assert.h>
#include <unistd.h>
using namespace std;
int main() {
double wx [25] = {132.67, 128.67, 124.67, 120.67, 116.67, 112.67, 108.67,
104.67, 101.43, 97.77, 94.84, 92.89, 92.4 , 92.4 ,
92.4 , 92.4 , 92.4 , 92.4 , 92.4 , 92.39, 92.39,
92.39, 92.39, 92.39, 92.39};
double wy [25] = {195.14, 195.14, 195.14, 195.14, 195.14, 195.14, 195.14,
195.14, 195.14, 195.03, 193.88, 191.75, 188.72, 185.32,
181.32, 177.32, 173.32, 169.32, 165.32, 161.32, 157.32,
153.32, 149.32, 145.32, 141.84};
double o_llx[1] = {92.89};
double o_lly[1] = {191.75};
double o_urx[1] = {92.89};
double o_ury[1] = {191.75};
// set up experiment
FrenetInitialConditions fot_ic = {
34.6,
7.10964962,
-1.35277168,
-1.86,
0.0,
10,
wx,
wy,
25,
o_llx,
o_lly,
o_urx,
o_ury,
1
};
FrenetHyperparameters fot_hp = {
25.0,
15.0,
15.0,
5.0,
5.0,
0.5,
0.2,
5.0,
2.0,
0.5,
2.0,
0.1,
1.0,
0.1,
0.1,
0.1,
0.1,
0.1,
1.0,
1.0,
2 // num thread
};
// run experiment
AnytimeFrenetOptimalTrajectory fot = AnytimeFrenetOptimalTrajectory(&fot_ic, &fot_hp);
fot.asyncPlan(); // start planning
const int NUM_ITER = 50;
const int TEST_INTERVAL_TIME = 2; // in microseconds
double prev_final_cf = INFINITY;
double curr_cf;
for (int i = 0; i < NUM_ITER; i ++) {
FrenetPath* curr_frenet_path = fot.getBestPath();
if (curr_frenet_path) {
curr_cf = curr_frenet_path->cf;
cout << "Found Valid Path with Cost: " << curr_cf << "\n";
} else {
curr_cf = INFINITY;
cout << "No Valid Path Found\n";
}
// anytime algo consistency test, cost should only reduce or stay unchanged
// assert(curr_cf > prev_final_cf);
if (prev_final_cf < curr_cf) {
cout << "Not Consistent\n";
return -1;
}
prev_final_cf = curr_cf;
usleep(TEST_INTERVAL_TIME);
}
cout << "All iterations are consistent\n";
fot.stopPlanning();
return 0;
} | 24.413462 | 90 | 0.493895 | erdos-project |
4eeb627169bedae2d2155591f0d9cbfc63e7cb55 | 2,824 | cpp | C++ | vm/external_libs/llvm/tools/llvmc2/llvmc.cpp | marnen/rubinius | 05b3f9789d01bada0604a7f09921c956bc9487e7 | [
"BSD-3-Clause"
] | 1 | 2016-05-08T16:58:14.000Z | 2016-05-08T16:58:14.000Z | vm/external_libs/llvm/tools/llvmc2/llvmc.cpp | taf2/rubinius | 493bfa2351fc509ca33d3bb03991c2e9c2b6dafa | [
"BSD-3-Clause"
] | null | null | null | vm/external_libs/llvm/tools/llvmc2/llvmc.cpp | taf2/rubinius | 493bfa2351fc509ca33d3bb03991c2e9c2b6dafa | [
"BSD-3-Clause"
] | null | null | null | //===--- llvmc.cpp - The LLVM Compiler Driver ------------------*- C++ -*-===//
//
// The LLVM Compiler Infrastructure
//
// This file is distributed under the University of Illinois Open
// Source License. See LICENSE.TXT for details.
//
//===----------------------------------------------------------------------===//
//
// This tool provides a single point of access to the LLVM
// compilation tools. It has many options. To discover the options
// supported please refer to the tools' manual page or run the tool
// with the --help option.
//
//===----------------------------------------------------------------------===//
#include "CompilationGraph.h"
#include "Tool.h"
#include "llvm/System/Path.h"
#include "llvm/Support/CommandLine.h"
#include <iostream>
#include <stdexcept>
#include <string>
namespace cl = llvm::cl;
namespace sys = llvm::sys;
using namespace llvmc;
// Built-in command-line options.
// External linkage here is intentional.
cl::list<std::string> InputFilenames(cl::Positional, cl::desc("<input file>"),
cl::ZeroOrMore);
cl::opt<std::string> OutputFilename("o", cl::desc("Output file name"),
cl::value_desc("file"));
cl::list<std::string> Languages("x",
cl::desc("Specify the language of the following input files"),
cl::ZeroOrMore);
cl::opt<bool> VerboseMode("v",
cl::desc("Enable verbose mode"));
cl::opt<bool> WriteGraph("write-graph",
cl::desc("Write compilation-graph.dot file"),
cl::Hidden);
cl::opt<bool> ViewGraph("view-graph",
cl::desc("Show compilation graph in GhostView"),
cl::Hidden);
namespace {
/// BuildTargets - A small wrapper for CompilationGraph::Build.
int BuildTargets(CompilationGraph& graph) {
int ret;
sys::Path tempDir(sys::Path::GetTemporaryDirectory());
try {
ret = graph.Build(tempDir);
}
catch(...) {
tempDir.eraseFromDisk(true);
throw;
}
tempDir.eraseFromDisk(true);
return ret;
}
}
int main(int argc, char** argv) {
try {
CompilationGraph graph;
cl::ParseCommandLineOptions(argc, argv,
"LLVM Compiler Driver (Work In Progress)");
PopulateCompilationGraph(graph);
if (WriteGraph) {
graph.writeGraph();
if (!ViewGraph)
return 0;
}
if (ViewGraph) {
graph.viewGraph();
return 0;
}
if (InputFilenames.empty()) {
std::cerr << "No input files.\n";
return 1;
}
return BuildTargets(graph);
}
catch(const std::exception& ex) {
std::cerr << ex.what() << '\n';
}
catch(...) {
std::cerr << "Unknown error!\n";
}
return 1;
}
| 27.417476 | 80 | 0.549929 | marnen |
4ef2b7d19d0802d49f65ebbc5eddc3e341ee57eb | 717 | cpp | C++ | src/propagation/types/value_context_ordering.cpp | RMGiroux/clangmetatool | 38071867d56a9c5dfa4fac1eb298b8058a026acd | [
"Apache-2.0"
] | null | null | null | src/propagation/types/value_context_ordering.cpp | RMGiroux/clangmetatool | 38071867d56a9c5dfa4fac1eb298b8058a026acd | [
"Apache-2.0"
] | null | null | null | src/propagation/types/value_context_ordering.cpp | RMGiroux/clangmetatool | 38071867d56a9c5dfa4fac1eb298b8058a026acd | [
"Apache-2.0"
] | null | null | null | #include "value_context_ordering.h"
namespace clangmetatool {
namespace propagation {
namespace types {
void ValueContextOrdering::print(std::ostream &stream, Value value) {
switch (value) {
case ValueContextOrdering::CONTROL_FLOW_MERGE:
stream << "Control flow merge";
break;
case ValueContextOrdering::CHANGED_BY_CODE:
stream << "Changed by code";
break;
default:
break;
}
}
} // namespace types
} // namespace propagation
} // namespace clangmetatool
std::ostream &operator<<(
std::ostream &stream,
clangmetatool::propagation::types::ValueContextOrdering::Value value) {
clangmetatool::propagation::types::ValueContextOrdering::print(stream, value);
return stream;
}
| 23.129032 | 80 | 0.728033 | RMGiroux |
4ef3bd8789d4e15e40a9dccdc5743feff5a98df6 | 519 | cpp | C++ | src/util/nm_log.cpp | nolmoonen/pbr | c5ed37795c8e67de1716762206fe7c58e9079ac0 | [
"MIT"
] | null | null | null | src/util/nm_log.cpp | nolmoonen/pbr | c5ed37795c8e67de1716762206fe7c58e9079ac0 | [
"MIT"
] | null | null | null | src/util/nm_log.cpp | nolmoonen/pbr | c5ed37795c8e67de1716762206fe7c58e9079ac0 | [
"MIT"
] | null | null | null | #include "nm_log.hpp"
const char *const nm_log::LEVEL_NAMES[] = {
"TRACE", "INFO ", "WARN ", "ERROR"
};
log_level_e nm_log::m_level = LOG_TRACE;
void nm_log::set_log_level(log_level_e t_level)
{
m_level = t_level;
}
void nm_log::log(log_level_e t_level, const char *t_format, ...)
{
if (t_level >= m_level) {
fprintf(stdout, "%s ", LEVEL_NAMES[t_level]);
va_list argptr;
va_start(argptr, t_format);
vfprintf(stdout, t_format, argptr);
va_end(argptr);
}
}
| 21.625 | 64 | 0.624277 | nolmoonen |
4ef3d0ae2a286a4ee6a1f5480b6113fdbe4af7e5 | 1,303 | cpp | C++ | src/main.cpp | dancol90/wifi-led-clock | d4d391226ddc26ff92fd894e184c5348953b3bfa | [
"MIT"
] | 2 | 2018-10-10T12:37:05.000Z | 2018-12-07T22:36:42.000Z | src/main.cpp | dancol90/wifi-led-clock | d4d391226ddc26ff92fd894e184c5348953b3bfa | [
"MIT"
] | null | null | null | src/main.cpp | dancol90/wifi-led-clock | d4d391226ddc26ff92fd894e184c5348953b3bfa | [
"MIT"
] | null | null | null | /*
Drivers (still services):
- [OK] Led display
- [OK] Time
- [OK] WiFi
- [OK] File System
List of needed services:
- [OK] Scroll management
- [OK] Configuration (over SPIFFS)
- [OK*] HTTP Server (?)
- [OK] NTP
- MQTT handling
*/
#include <Arduino.h>
#include "Service.hpp"
#include "drivers/LED.hpp"
#include "drivers/Clock.hpp"
#include "drivers/WiFi.hpp"
#include "drivers/FS.hpp"
#include "services/Scroll.hpp"
#include "services/HTTP.hpp"
#include "services/Registry.hpp"
#include "services/NTP.hpp"
#include "services/WebSocket.hpp"
#include "services/OTA.hpp"
#include "application/SlackApplication.hpp"
#include "application/ClockApplication.hpp"
void setup()
{
Serial.begin(115200);
Service* drivers[] = {
// "Priority" services & drivers
new FileSystemDriver(),
new RegistryService(),
// Drivers
new ClockDriver(),
new WiFiDriver(),
new LedMatrixDriver(),
// Services
new ScrollService(),
new HTTPService(),
new NTPService(),
new WebSocket(),
new OTAService(),
// Application
//new SlackApplication(),
new ClockApplication()
};
Service::InitAll();
}
void loop()
{
Service::SyncUpdate();
delay(0);
}
| 19.447761 | 43 | 0.6132 | dancol90 |
4ef4d8b1a1af8be443fee78f25a6ba05823fccf0 | 3,226 | cpp | C++ | cpp/varint/leveldb/varint.cpp | yyyshi/asshole_algorithm | 270460f2afcdb7a00a08979053e8cfb80ef93b5b | [
"Apache-2.0"
] | null | null | null | cpp/varint/leveldb/varint.cpp | yyyshi/asshole_algorithm | 270460f2afcdb7a00a08979053e8cfb80ef93b5b | [
"Apache-2.0"
] | null | null | null | cpp/varint/leveldb/varint.cpp | yyyshi/asshole_algorithm | 270460f2afcdb7a00a08979053e8cfb80ef93b5b | [
"Apache-2.0"
] | null | null | null | // encode
char* EncodeVarint32(char* dst, uint32_t v) {
// Operate on characters as unsigneds
uint8_t* ptr = reinterpret_cast<uint8_t*>(dst);
static const int B = 128;
if (v < (1 << 7)) {
*(ptr++) = v;
} else if (v < (1 << 14)) {
*(ptr++) = v | B;
*(ptr++) = v >> 7;
} else if (v < (1 << 21)) {
*(ptr++) = v | B;
*(ptr++) = (v >> 7) | B;
*(ptr++) = v >> 14;
} else if (v < (1 << 28)) {
*(ptr++) = v | B;
*(ptr++) = (v >> 7) | B;
*(ptr++) = (v >> 14) | B;
*(ptr++) = v >> 21;
} else {
*(ptr++) = v | B;
*(ptr++) = (v >> 7) | B;
*(ptr++) = (v >> 14) | B;
*(ptr++) = (v >> 21) | B;
*(ptr++) = v >> 28;
}
return reinterpret_cast<char*>(ptr);
}
char* EncodeVarint64(char* dst, uint64_t v) {
static const int B = 128;
uint8_t* ptr = reinterpret_cast<uint8_t*>(dst);
while (v >= B) {
*(ptr++) = v | B;
v >>= 7;
}
*(ptr++) = static_cast<uint8_t>(v);
return reinterpret_cast<char*>(ptr);
}
<!解码就是编码的逆过程,这里涉及到对Slice数据的解析
重点关注“GetVarint32Ptr()”,“GetVarint32PtrFallback()”
>
bool GetVarint32(Slice* input, uint32_t* value) {
const char* p = input->data();
const char* limit = p + input->size();
const char* q = GetVarint32Ptr(p, limit, value);
if (q == nullptr) {
return false;
} else {
*input = Slice(q, limit - q);
return true;
}
}
inline const char* GetVarint32Ptr(const char* p, const char* limit,
uint32_t* value) {
if (p < limit) {
uint32_t result = *(reinterpret_cast<const uint8_t*>(p));
if ((result & 128) == 0) {
<!128就是一个八位,最高位为1,其余位为0,
与128相与为0表示待解码的result<=127,所以长度就是一个字节
直接赋值给*Value即可。
>
*value = result;
return p + 1;
}
}
return GetVarint32PtrFallback(p, limit, value);
}
const char* GetVarint32PtrFallback(const char* p, const char* limit,
uint32_t* value) {
<!对于超过一个字节的长度编码,解码的过程就是按小端顺序,
每7位取出,然后移位来组装最后的实际长度,组装结束的表示就是MSB位为0>
uint32_t result = 0;
for (uint32_t shift = 0; shift <= 28 && p < limit; shift += 7) {
uint32_t byte = *(reinterpret_cast<const uint8_t*>(p));
p++;
if (byte & 128) {
// More bytes are present
result |= ((byte & 127) << shift);
} else {
result |= (byte << shift);
*value = result;
return reinterpret_cast<const char*>(p);
}
}
return nullptr;
}
<!Varint64位的流程可Varint32原理一样>
bool GetVarint64(Slice* input, uint64_t* value) {
const char* p = input->data();
const char* limit = p + input->size();
const char* q = GetVarint64Ptr(p, limit, value);
if (q == nullptr) {
return false;
} else {
*input = Slice(q, limit - q);
return true;
}
}
const char* GetVarint64Ptr(const char* p, const char* limit, uint64_t* value) {
uint64_t result = 0;
for (uint32_t shift = 0; shift <= 63 && p < limit; shift += 7) {
uint64_t byte = *(reinterpret_cast<const uint8_t*>(p));
p++;
if (byte & 128) {
// More bytes are present
result |= ((byte & 127) << shift);
} else {
result |= (byte << shift);
*value = result;
return reinterpret_cast<const char*>(p);
}
}
return nullptr;
}
| 26.442623 | 79 | 0.534408 | yyyshi |
4ef77cb8295f8f1e90370c72d417ed17e70c0bd2 | 537 | hpp | C++ | engine/generators/crypts/include/ICryptLayoutStrategy.hpp | sidav/shadow-of-the-wyrm | 747afdeebed885b1a4f7ab42f04f9f756afd3e52 | [
"MIT"
] | null | null | null | engine/generators/crypts/include/ICryptLayoutStrategy.hpp | sidav/shadow-of-the-wyrm | 747afdeebed885b1a4f7ab42f04f9f756afd3e52 | [
"MIT"
] | null | null | null | engine/generators/crypts/include/ICryptLayoutStrategy.hpp | sidav/shadow-of-the-wyrm | 747afdeebed885b1a4f7ab42f04f9f756afd3e52 | [
"MIT"
] | null | null | null | #pragma once
#include <tuple>
#include "common.hpp"
#include "Directions.hpp"
#include "Map.hpp"
// Interface for defining crypt layout strategies. These operate on a
// given map and crypt boundary, producing the characteristic look of the
// crypt: pillars, rooms, a central vault, etc.
class ICryptLayoutStrategy
{
public:
virtual void create_layout(MapPtr map, const std::tuple<Coordinate, Coordinate, Coordinate>& stair_loc_and_room_boundary) = 0;
};
using ICryptLayoutStrategyPtr = std::shared_ptr<ICryptLayoutStrategy>;
| 29.833333 | 130 | 0.772812 | sidav |
f600003f47e60792dabea9657b35e02919c55e2e | 2,956 | hpp | C++ | common/SoapySSDPEndpoint.hpp | bastille-attic/SoapyRemote | 63664b890ccfe2d5472901b879b1593aacc92ef1 | [
"BSL-1.0"
] | null | null | null | common/SoapySSDPEndpoint.hpp | bastille-attic/SoapyRemote | 63664b890ccfe2d5472901b879b1593aacc92ef1 | [
"BSL-1.0"
] | null | null | null | common/SoapySSDPEndpoint.hpp | bastille-attic/SoapyRemote | 63664b890ccfe2d5472901b879b1593aacc92ef1 | [
"BSL-1.0"
] | null | null | null | // Copyright (c) 2015-2016 Josh Blum
// SPDX-License-Identifier: BSL-1.0
#pragma once
#include "SoapyRPCSocket.hpp"
#include <string>
#include <csignal> //sig_atomic_t
#include <mutex>
#include <vector>
#include <memory>
class SoapyHTTPHeader;
struct SoapySSDPEndpointData;
/*!
* Service an SSDP endpoint to:
* keep track of discovered servers of interest,
* and to respond to discovery packets for us.
*/
class SoapySSDPEndpoint
{
public:
//! Get a singleton instance of the endpoint
static std::shared_ptr<SoapySSDPEndpoint> getInstance(void);
/*!
* Create a discovery endpoint
*/
SoapySSDPEndpoint(void);
~SoapySSDPEndpoint(void);
/*!
* Allow the endpoint to advertise that its running the RPC service
*/
void registerService(const std::string &uuid, const std::string &service);
/*!
* Enable the client endpoint to search for running services.
*/
void enablePeriodicSearch(const bool enable);
/*!
* Enable the server to send periodic notification messages.
*/
void enablePeriodicNotify(const bool enable);
/*!
* Get a list of all active server URLs.
*
* The same endpoint can be discovered under both IPv4 and IPv6.
* When 'only' is false, the ipVer specifies the IP version preference
* when both are discovered but will fallback to the other version.
* But when 'only' is true, only addresses of the ipVer type are used.
*
* \param ipVer the preferred IP version to discover (6 or 4)
* \param only true to ignore other discovered IP versions
*/
std::vector<std::string> getServerURLs(const int ipVer = 4, const bool only = false);
private:
SoapySocketSession sess;
//protection between threads
std::mutex mutex;
//service settings
bool serviceRegistered;
std::string uuid;
std::string service;
//configured messages
bool periodicSearchEnabled;
bool periodicNotifyEnabled;
//server data
std::vector<SoapySSDPEndpointData *> handlers;
//signal done to the thread
sig_atomic_t done;
void spawnHandler(const std::string &bindAddr, const std::string &groupAddr, const int ipVer);
void handlerLoop(SoapySSDPEndpointData *data);
void sendHeader(SoapyRPCSocket &sock, const SoapyHTTPHeader &header, const std::string &addr);
void sendSearchHeader(SoapySSDPEndpointData *data);
void sendNotifyHeader(SoapySSDPEndpointData *data, const std::string &nts);
void handleSearchRequest(SoapySSDPEndpointData *data, const SoapyHTTPHeader &header, const std::string &addr);
void handleSearchResponse(SoapySSDPEndpointData *data, const SoapyHTTPHeader &header, const std::string &addr);
void handleNotifyRequest(SoapySSDPEndpointData *data, const SoapyHTTPHeader &header, const std::string &addr);
void handleRegisterService(SoapySSDPEndpointData *, const SoapyHTTPHeader &header, const std::string &recvAddr);
};
| 31.784946 | 116 | 0.715832 | bastille-attic |
f60875c75cf897e0084395bae0c133aa63f02728 | 1,145 | cpp | C++ | src/tmp/student.cpp | asankagit/wacms | f6ecf9e1c740417a934acb8f6c53e2bb3388b5ee | [
"MIT"
] | 5 | 2021-10-14T07:27:31.000Z | 2022-01-04T17:20:15.000Z | src/tmp/student.cpp | asankagit/wacms | f6ecf9e1c740417a934acb8f6c53e2bb3388b5ee | [
"MIT"
] | null | null | null | src/tmp/student.cpp | asankagit/wacms | f6ecf9e1c740417a934acb8f6c53e2bb3388b5ee | [
"MIT"
] | null | null | null | // similar to MyClass, in this we are testing header file usage
#include <student.h>
#include "emscripten/bind.h"
using namespace emscripten;
Student::Student() {
}
void Student::setName(std::string name) {
this->name = name;
}
const std::string& Student::getName() {
for(int i=0; i<10000; i++) {
printf("%d",i);
}
std::string str = "response'data hi "+this->name+ "--";
return str;
}
// https://stackoverflow.com/questions/2298242/callback-functions-in-c
// typedef int (ClassName::*CallbackType)(float);
// void DoWorkObject(CallbackType callback)
// {
// //Class instance to invoke it through
// ClassName objectInstance;
// //Invocation
// int result = (objectInstance.*callback)(1.0f);
// }
// int main(int argc, char ** argv)
// {
// //Pass in SomeCallback to the DoWork
// DoWorkObject(&ClassName::Method);
// }
EMSCRIPTEN_BINDINGS(Student_example)
{
class_<Student>("Student").
constructor().
function("setName", &Student::setName).
function("getName", &Student::getName);
}
// em++ --bind student.cpp CombineClass.cpp -o student.js -I .
// | 21.203704 | 70 | 0.637555 | asankagit |
f60aebecafaaaf52fe9d95041c392350f6185103 | 1,531 | cpp | C++ | common/comline.cpp | yalehwy/linepw | 8e22ffaa49fa49dca44a6a8d6e38a16a64a41aa0 | [
"Apache-2.0"
] | null | null | null | common/comline.cpp | yalehwy/linepw | 8e22ffaa49fa49dca44a6a8d6e38a16a64a41aa0 | [
"Apache-2.0"
] | null | null | null | common/comline.cpp | yalehwy/linepw | 8e22ffaa49fa49dca44a6a8d6e38a16a64a41aa0 | [
"Apache-2.0"
] | null | null | null | #include "comline.hpp"
#define MOVESPACE 1
ComLine::ComLine()
{
map = new std::map<std::string, std::string>;
}
ComLine::~ComLine()
{
if (map)
{
delete map;
map = nullptr;
}
}
std::map<std::string, std::string>*
ComLine::getKeyValue(int argc, char* argv[])
{
for (int i = 1; i < argc; i++)
{
std::string t = std::string(argv[i]);
int idx = t.find('=', 1);
std::string key = t.substr(2, idx - MOVESPACE * 2);
std::string value = t.substr(idx + MOVESPACE);
if (!map)
{
map = new std::map<std::string, std::string>;
}
map->insert(std::make_pair(key, value));
}
return map;
}
bool ComLine::haveHelp()
{
for(std::map<std::string, std::string>::iterator iter = map->begin();
iter != map->end(); iter++)
{
if(iter->first == "help")
return true;
}
return false;
}
void ComLine::printHelpInfo()
{
std::cout << " --listen-port " << std::endl;
std::cout << " --pool-num " << std::endl;
std::cout << " --mysql-port " << std::endl;
std::cout << " --mysql-host " << std::endl;
std::cout << " --mysql-user " << std::endl;
std::cout << "--mysql-passwd " << std::endl;
std::cout << " --mysql-db " << std::endl;
}
// find args address
int ComLine::findParamIndex(int argc, char**argv, std::string param)
{
for (int i = 1; i < argc; i++)
{
std::string t = std::string(argv[i]);
int idx = t.find('=', 1);
std::string key = t.substr(2, idx - MOVESPACE * 2);
if(key == param) return i;
}
return -1;
}
| 21.263889 | 71 | 0.546048 | yalehwy |
f6121cfdbab82fc640601de7f28d2d1300055ee8 | 8,281 | cpp | C++ | examples/prepared_statement.cpp | tstrutz/sqlite_orm | 1ee0a8653fe57ed4d4f69b5a65839b1861c41d32 | [
"BSD-3-Clause"
] | 1,566 | 2016-12-20T15:31:04.000Z | 2022-03-31T18:17:34.000Z | examples/prepared_statement.cpp | tstrutz/sqlite_orm | 1ee0a8653fe57ed4d4f69b5a65839b1861c41d32 | [
"BSD-3-Clause"
] | 620 | 2017-01-06T13:53:35.000Z | 2022-03-31T12:05:50.000Z | examples/prepared_statement.cpp | tstrutz/sqlite_orm | 1ee0a8653fe57ed4d4f69b5a65839b1861c41d32 | [
"BSD-3-Clause"
] | 274 | 2017-01-07T05:34:24.000Z | 2022-03-27T18:22:47.000Z | /**
* There are two member functions in storage_t class which you need to use to operate with
* prepared statements: storage_t::prepare and storage_t::execute.
* Also if you need to rebind arguments just use get<N>(statement) = ... syntax
* just like you do with std::tuple.
* Once a statement is prepared it holds a connection to a database inside. This connection will be open
* until at least one statement object exists.
*/
#include <sqlite_orm/sqlite_orm.h>
#include <iostream>
using namespace sqlite_orm;
using std::cout;
using std::endl;
struct Doctor {
int doctor_id = 0;
std::string doctor_name;
std::string degree;
};
struct Speciality {
int spl_id = 0;
std::string spl_descrip;
int doctor_id = 0;
};
struct Visit {
int doctor_id = 0;
std::string patient_name;
std::string vdate;
};
int main() {
auto storage = make_storage("prepared.sqlite",
make_table("doctors",
make_column("doctor_id", &Doctor::doctor_id, primary_key()),
make_column("doctor_name", &Doctor::doctor_name),
make_column("degree", &Doctor::degree)),
make_table("speciality",
make_column("spl_id", &Speciality::spl_id, primary_key()),
make_column("spl_descrip", &Speciality::spl_descrip),
make_column("doctor_id", &Speciality::doctor_id)),
make_table("visits",
make_column("doctor_id", &Visit::doctor_id),
make_column("patient_name", &Visit::patient_name),
make_column("vdate", &Visit::vdate)));
storage.sync_schema();
storage.remove_all<Doctor>();
storage.remove_all<Speciality>();
storage.remove_all<Visit>();
{
// first we create a statement object for replace query with a doctor object
auto replaceStatement = storage.prepare(replace(Doctor{210, "Dr. John Linga", "MD"}));
cout << "replaceStatement = " << replaceStatement.sql() << endl;
// next we execute our statement
storage.execute(replaceStatement);
// now 'doctors' table has one row [210, 'Dr. John Linga', 'MD']
// Next we shall reuse the statement to replace another doctor
// replaceStatement contains a doctor inside it which can be obtained
// with get<0>(statement) function
get<0>(replaceStatement) = {211, "Dr. Peter Hall", "MBBS"};
storage.execute(replaceStatement);
// now 'doctors' table has two rows.
// Next we shall reuse the statement again with member assignment
auto &doctor = get<0>(replaceStatement); // doctor is Doctor &
doctor.doctor_id = 212;
doctor.doctor_name = "Dr. Ke Gee";
doctor.degree = "MD";
storage.execute(replaceStatement);
// now 'doctors' table has three rows.
}
{
// also prepared statement can store arguments by reference. To do this you can
// pass a std::reference_wrapper instead of object value.
Doctor doctorToReplace{213, "Dr. Pat Fay", "MD"};
auto replaceStatementByRef = storage.prepare(replace(std::ref(doctorToReplace)));
cout << "replaceStatementByRef = " << replaceStatementByRef.sql() << endl;
storage.execute(replaceStatementByRef);
// now 'doctors' table has four rows.
// next we shall change doctorToReplace object and then execute our statement.
// Statement will be affected cause it stores a reference to the doctor
doctorToReplace.doctor_id = 214;
doctorToReplace.doctor_name = "Mosby";
doctorToReplace.degree = "MBBS";
storage.execute(replaceStatementByRef);
// and now 'doctors' table has five rows
}
cout << "Doctors count = " << storage.count<Doctor>() << endl;
for(auto &doctor: storage.iterate<Doctor>()) {
cout << storage.dump(doctor) << endl;
}
{
auto insertStatement = storage.prepare(insert(Speciality{1, "CARDIO", 211}));
cout << "insertStatement = " << insertStatement.sql() << endl;
storage.execute(insertStatement);
get<0>(insertStatement) = {2, "NEURO", 213};
storage.execute(insertStatement);
get<0>(insertStatement) = {3, "ARTHO", 212};
storage.execute(insertStatement);
get<0>(insertStatement) = {4, "GYNO", 210};
storage.execute(insertStatement);
}
cout << "Specialities count = " << storage.count<Speciality>() << endl;
for(auto &speciality: storage.iterate<Speciality>()) {
cout << storage.dump(speciality) << endl;
}
{
// let's insert (replace) 5 visits. We create two vectors with 2 visits each
std::vector<Visit> visits;
visits.push_back({210, "Julia Nayer", "2013-10-15"});
visits.push_back({214, "TJ Olson", "2013-10-14"});
// let's make a statement
auto replaceRangeStatement = storage.prepare(replace_range(visits.begin(), visits.end()));
cout << "replaceRangeStatement = " << replaceRangeStatement.sql() << endl;
// replace two objects
storage.execute(replaceRangeStatement);
std::vector<Visit> visits2;
visits2.push_back({215, "John Seo", "2013-10-15"});
visits2.push_back({212, "James Marlow", "2013-10-16"});
// reassign iterators to point to other visits. Beware that if end - begin
// will have different distance then you'll get a runtime error cause statement is
// already compiled with a fixed amount of arguments to bind
get<0>(replaceRangeStatement) = visits2.begin();
get<1>(replaceRangeStatement) = visits2.end();
storage.execute(replaceRangeStatement);
storage.replace(Visit{212, "Jason Mallin", "2013-10-12"});
}
cout << "Visits count = " << storage.count<Visit>() << endl;
for(auto &visit: storage.iterate<Visit>()) {
cout << storage.dump(visit) << endl;
}
{
// SELECT doctor_id
// FROM visits
// WHERE LENGTH(patient_name) > 8
auto selectStatement = storage.prepare(select(&Visit::doctor_id, where(length(&Visit::patient_name) > 8)));
cout << "selectStatement = " << selectStatement.sql() << endl;
{
auto rows = storage.execute(selectStatement);
cout << "rows count = " << rows.size() << endl;
for(auto &id: rows) {
cout << id << endl;
}
}
// same statement, other bound values
// SELECT doctor_id
// FROM visits
// WHERE LENGTH(patient_name) > 11
{
get<0>(selectStatement) = 11;
auto rows = storage.execute(selectStatement);
cout << "rows count = " << rows.size() << endl;
for(auto &id: rows) {
cout << id << endl;
}
}
}
{
// SELECT rowid, 'Doctor ' || doctor_name
// FROM doctors
// WHERE degree LIKE '%S'
auto selectStatement = storage.prepare(
select(columns(rowid(), "Doctor " || c(&Doctor::doctor_name)), where(like(&Doctor::degree, "%S"))));
cout << "selectStatement = " << selectStatement.sql() << endl;
{
auto rows = storage.execute(selectStatement);
cout << "rows count = " << rows.size() << endl;
for(auto &row: rows) {
cout << get<0>(row) << '\t' << get<1>(row) << endl;
}
}
// SELECT rowid, 'Nice ' || doctor_name
// FROM doctors
// WHERE degree LIKE '%D'
get<0>(selectStatement) = "Nice ";
get<1>(selectStatement) = "%D";
{
auto rows = storage.execute(selectStatement);
cout << "rows count = " << rows.size() << endl;
for(auto &row: rows) {
cout << get<0>(row) << '\t' << get<1>(row) << endl;
}
}
}
return 0;
}
| 39.433333 | 115 | 0.567685 | tstrutz |
f6158dae5583f50ddac7a7d1cd73e8f50a57350b | 3,903 | cpp | C++ | 7th_100/problem650.cpp | takekoputa/project-euler | 6f434be429bd26f5d0f84f5ab0f5fa2bd677c790 | [
"MIT"
] | null | null | null | 7th_100/problem650.cpp | takekoputa/project-euler | 6f434be429bd26f5d0f84f5ab0f5fa2bd677c790 | [
"MIT"
] | null | null | null | 7th_100/problem650.cpp | takekoputa/project-euler | 6f434be429bd26f5d0f84f5ab0f5fa2bd677c790 | [
"MIT"
] | 1 | 2021-11-02T12:08:46.000Z | 2021-11-02T12:08:46.000Z | // Problem: https://projecteuler.net/problem=650
// g++ problem650.cpp -I$HOME/pari/include/ -L$HOME/pari/lib -lpari -O3
#include<pari/pari.h>
#include<iostream>
#include<vector>
#include<cmath>
#include<unordered_map>
#include<functional>
using namespace std;
#define endl "\n"
typedef int64_t i64;
const i64 N = 20000;
//const i64 N = 5;
const i64 MOD = 1'000'000'007;
vector<i64> get_primes(i64 n)
{
vector<i64> primes;
primes.reserve(n/10);
vector<bool> is_prime = vector<bool>(n/2+1, true);
i64 sqrt_n = i64(sqrt(n));
for (i64 p = 3; p <= sqrt_n; p+=2)
{
if (!is_prime[(p-3)/2])
continue;
for (i64 np = 3*p; np <= n; np += 2*p)
is_prime[(np-3)/2] = false;
}
primes.push_back(2);
i64 size = is_prime.size();
for (i64 p = 0; 2*p+3 <= n; p++)
{
if (is_prime[p])
primes.push_back(2*p+3);
}
return primes;
}
i64 modpow(i64 base, i64 pow, i64 mod)
{
i64 result = 1;
base = base % mod;
while (pow > 0)
{
if (pow % 2 == 1)
result = (result * base) % mod;
pow = pow / 2;
base = (base * base) % mod;
}
return result;
}
void factor(i64 n, const vector<i64>& primes, vector<i64>& bases, vector<i64>& exponents)
{
if (n <= 1)
return;
i64 i_prime = 0;
while (n > 1)
{
while (n % primes[i_prime] != 0)
i_prime += 1;
i64 base = primes[i_prime];
i64 exponent = 0;
while (n % base == 0)
{
exponent = exponent + 1;
n = n / base;
}
bases.push_back(base);
exponents.push_back(exponent);
}
}
unordered_map<i64, vector<i64>> cached_bases;
unordered_map<i64, vector<i64>> cached_exponents;
void cached_factor(i64 n, const vector<i64>& primes, vector<i64>& bases, vector<i64>& exponents)
{
if (cached_bases.find(n) == cached_bases.end())
{
vector<i64> _bases;
vector<i64> _exponents;
factor(n, primes, _bases, _exponents);
cached_bases[n] = move(_bases);
cached_exponents[n] = move(_exponents);
}
bases = ref(cached_bases[n]);
exponents = ref(cached_exponents[n]);
}
i64 invmod(i64 base, i64 mod)
{
// if k is the multiplicative order of a mod M, then a^k = 1 (mod M)
// -> a * a^(k-1) = 1 (mod M)
// -> invmod(a, M) = a^(k-1)
i64 multiplicative_order = gtolong(order(gmodulss(base, mod)));
return modpow(base, multiplicative_order-1, mod);
};
i64 D(i64 n, const vector<i64>& primes, const vector<i64>& invmods)
{
i64 ans = 1;
unordered_map<i64, i64> exponents;
for (auto p: primes)
{
if (p > n)
break;
exponents[p] = 0;
}
for (i64 k = 2; k <= n; k++)
{
i64 k_exponent_coeff = -n-1+2*k;
vector<i64> k_bases;
vector<i64> k_exponents;
cached_factor(k, primes, k_bases, k_exponents);
for (i64 j = 0; j < k_bases.size(); j++)
{
i64 base = k_bases[j];
i64 exponent = k_exponents[j];
exponents[base] += exponent * k_exponent_coeff;
}
}
for (auto p: exponents)
{
i64 base = p.first;
i64 exponent = p.second;
i64 next_coeff = modpow(base, exponent+1, MOD) - 1;
next_coeff = next_coeff * invmods[base-1]; // a^-1 % MOD
next_coeff = next_coeff % MOD;
ans = ans * next_coeff;
ans = ans % MOD;
}
return ans;
}
int main()
{
i64 ans = 0;
vector<i64> primes = get_primes(N);
pari_init(500000000,2);
vector<i64> invmods = vector<i64>(N+1, 0);
for (auto p: primes)
invmods[p-1] = (invmod(p-1, MOD));
pari_close();
for (i64 i = 1; i <= N; i++)
{
ans = ans + D(i, primes, invmods);
ans = ans % MOD;
}
cout << ans << endl;
return 0;
}
| 22.958824 | 96 | 0.539329 | takekoputa |
f61998985015980fbba5f72e69a6f51ebff9ea8e | 13,031 | cpp | C++ | QP/v5.4.2/qpcpp/examples/lwip/arm-cm/lwip_ek-lm3s6965/lwipmgr.cpp | hyller/GladiatorCots | 36a69df68675bb40b562081c531e6674037192a8 | [
"Unlicense"
] | null | null | null | QP/v5.4.2/qpcpp/examples/lwip/arm-cm/lwip_ek-lm3s6965/lwipmgr.cpp | hyller/GladiatorCots | 36a69df68675bb40b562081c531e6674037192a8 | [
"Unlicense"
] | null | null | null | QP/v5.4.2/qpcpp/examples/lwip/arm-cm/lwip_ek-lm3s6965/lwipmgr.cpp | hyller/GladiatorCots | 36a69df68675bb40b562081c531e6674037192a8 | [
"Unlicense"
] | null | null | null | //****************************************************************************
// Product: lwIP-Manager Active Object
// Last Updated for Version: 5.4.0
// Date of the Last Update: 2015-05-12
//
// Q u a n t u m L e a P s
// ---------------------------
// innovating embedded systems
//
// Copyright (C) Quantum Leaps, LLC. All rights reserved.
//
// This program is open source software: you can redistribute it and/or
// modify it under the terms of the GNU General Public License as published
// by the Free Software Foundation, either version 3 of the License, or
// (at your option) any later version.
//
// Alternatively, this program may be distributed and modified under the
// terms of Quantum Leaps commercial licenses, which expressly supersede
// the GNU General Public License and are specifically designed for
// licensees interested in retaining the proprietary status of their code.
//
// 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, see <http://www.gnu.org/licenses/>.
//
// Contact information:
// Web : http://www.state-machine.com
// Email: [email protected]
//****************************************************************************
#define LWIP_ALLOWED
#include "qpcpp.h" // QP/C++ API
#include "dpp.h" // application events and active objects
#include "bsp.h" // Board Support Package
#include "lwip.h" // lwIP stack
#include "httpd.h" // lwIP application
#include <string.h>
#include <stdio.h>
Q_DEFINE_THIS_FILE
// application signals cannot overlap the device-driver signals
Q_ASSERT_COMPILE((LWIP_DRIVER_END - LWIP_DRIVER_GROUP) >= LWIP_MAX_OFFSET);
#define FLASH_USERREG0 (*(uint32_t const *)0x400FE1E0)
#define FLASH_USERREG1 (*(uint32_t const *)0x400FE1E4)
#define LWIP_SLOW_TICK_MS TCP_TMR_INTERVAL
// Active object class -------------------------------------------------------
class LwIPMgr : public QActive {
QTimeEvt m_te_LWIP_SLOW_TICK;
struct netif *m_netif;
struct udp_pcb *m_upcb;
uint32_t m_ip_addr; // IP address in the native host byte order
#if LWIP_TCP
uint32_t m_tcp_tmr;
#endif
#if LWIP_ARP
uint32_t m_arp_tmr;
#endif
#if LWIP_DHCP
uint32_t m_dhcp_fine_tmr;
uint32_t m_dhcp_coarse_tmr;
#endif
#if LWIP_AUTOIP
uint32_t m_auto_ip_tmr;
#endif
public:
LwIPMgr(); // ctor
private:
static QState initial(LwIPMgr *me, QEvt const *e);
static QState running(LwIPMgr *me, QEvt const *e);
};
// Local objects -------------------------------------------------------------
static LwIPMgr l_lwIPMgr; // the single instance of LwIPMgr AO
// Global-scope objects ------------------------------------------------------
QActive * const AO_LwIPMgr = (QActive *)&l_lwIPMgr; // "opaque" pointer
// Server-Side Include (SSI) demo ............................................
static char const * const ssi_tags[] = {
"s_xmit",
"s_recv",
"s_fw",
"s_drop",
"s_chkerr",
"s_lenerr",
"s_memerr",
"s_rterr",
"s_proerr",
"s_opterr",
"s_err",
};
static int ssi_handler(int iIndex, char *pcInsert, int iInsertLen);
// Common Gateway Iinterface (CG) demo .......................................
static char const *cgi_display(int index, int numParams,
char const *param[],
char const *value[]);
static tCGI const cgi_handlers[] = {
{ "/display.cgi", &cgi_display },
};
// UDP handler ...............................................................
static void udp_rx_handler(void *arg, struct udp_pcb *upcb,
struct pbuf *p, struct ip_addr *addr, u16_t port);
//............................................................................
LwIPMgr::LwIPMgr()
: QActive((QStateHandler)&LwIPMgr::initial),
m_te_LWIP_SLOW_TICK(LWIP_SLOW_TICK_SIG)
{}
//............................................................................
QState LwIPMgr::initial(LwIPMgr *me, QEvt const *e) {
unsigned long user0, user1;
uint8_t macaddr[NETIF_MAX_HWADDR_LEN];
(void)e; // suppress the compiler warning about unused parameter
// Configure the hardware MAC address for the Ethernet Controller
//
// For the Stellaris Eval Kits, the MAC address will be stored in the
// non-volatile USER0 and USER1 registers. These registers can be read
// using the FlashUserGet function, as illustrated below.
//
user0 = FLASH_USERREG0;
user1 = FLASH_USERREG1;
// the MAC address must have been programmed!
Q_ASSERT((user0 != 0xFFFFFFFF) && (user1 != 0xFFFFFFFF));
//
// Convert the 24/24 split MAC address from NV ram into a 32/16 split MAC
// address needed to program the hardware registers, then program the MAC
// address into the Ethernet Controller registers.
//
macaddr[0] = (uint8_t)user0; user0 >>= 8;
macaddr[1] = (uint8_t)user0; user0 >>= 8;
macaddr[2] = (uint8_t)user0; user0 >>= 8;
macaddr[3] = (uint8_t)user1; user1 >>= 8;
macaddr[4] = (uint8_t)user1; user1 >>= 8;
macaddr[5] = (uint8_t)user1;
// initialize the Ethernet Driver
me->m_netif = eth_driver_init((QActive *)me, LWIP_DRIVER_GROUP, macaddr);
me->m_ip_addr = 0xFFFFFFFF; // initialize to impossible value
// initialize the lwIP applications...
httpd_init(); // initialize the simple HTTP-Deamon (web server)
http_set_ssi_handler(&ssi_handler, ssi_tags, Q_DIM(ssi_tags));
http_set_cgi_handlers(cgi_handlers, Q_DIM(cgi_handlers));
me->m_upcb = udp_new();
udp_bind(me->m_upcb, IP_ADDR_ANY, 777); // use port 777 for UDP
udp_recv(me->m_upcb, &udp_rx_handler, me);
QS_OBJ_DICTIONARY(&l_lwIPMgr);
QS_OBJ_DICTIONARY(&l_lwIPMgr.m_te_LWIP_SLOW_TICK);
QS_FUN_DICTIONARY(&QHsm::top);
QS_FUN_DICTIONARY(&LwIPMgr::initial);
QS_FUN_DICTIONARY(&LwIPMgr::running);
QS_SIG_DICTIONARY(SEND_UDP_SIG, me);
QS_SIG_DICTIONARY(LWIP_SLOW_TICK_SIG, me);
QS_SIG_DICTIONARY(LWIP_DRIVER_GROUP + LWIP_RX_READY_OFFSET, me);
QS_SIG_DICTIONARY(LWIP_DRIVER_GROUP + LWIP_TX_READY_OFFSET, me);
QS_SIG_DICTIONARY(LWIP_DRIVER_GROUP + LWIP_RX_OVERRUN_OFFSET, me);
return Q_TRAN(&LwIPMgr::running);
}
//............................................................................
QState LwIPMgr::running(LwIPMgr *me, QEvt const *e) {
switch (e->sig) {
case Q_ENTRY_SIG: {
me->m_te_LWIP_SLOW_TICK.postEvery((QActive *)me,
(LWIP_SLOW_TICK_MS * BSP_TICKS_PER_SEC) / 1000);
return Q_HANDLED();
}
case Q_EXIT_SIG: {
me->m_te_LWIP_SLOW_TICK.disarm();
return Q_HANDLED();
}
case SEND_UDP_SIG: {
if (me->m_upcb->remote_port != (uint16_t)0) {
struct pbuf *p = pbuf_new((u8_t *)((TextEvt const *)e)->text,
strlen(((TextEvt const *)e)->text) + 1);
if (p != (struct pbuf *)0) {
udp_send(me->m_upcb, p);
pbuf_free(p); // don't leak the pbuf!
}
}
return Q_HANDLED();
}
case LWIP_DRIVER_GROUP + LWIP_RX_READY_OFFSET: {
eth_driver_read();
return Q_HANDLED();
}
case LWIP_DRIVER_GROUP + LWIP_TX_READY_OFFSET: {
eth_driver_write();
return Q_HANDLED();
}
case LWIP_SLOW_TICK_SIG: {
if (me->m_ip_addr != me->m_netif->ip_addr.addr) {
me->m_ip_addr = me->m_netif->ip_addr.addr; // save the IP addr
uint32_t ip_net = ntohl(me->m_ip_addr);// IP in network order
// publish the text event to display the new IP address
TextEvt *te = Q_NEW(TextEvt, DISPLAY_IPADDR_SIG);
snprintf(te->text, Q_DIM(te->text), "%d.%d.%d.%d",
((ip_net) >> 24) & 0xFF,
((ip_net) >> 16) & 0xFF,
((ip_net) >> 8) & 0xFF,
ip_net & 0xFF);
QF::PUBLISH(te, me);
}
#if LWIP_TCP
me->m_tcp_tmr += LWIP_SLOW_TICK_MS;
if (me->m_tcp_tmr >= TCP_TMR_INTERVAL) {
me->m_tcp_tmr = 0;
tcp_tmr();
}
#endif
#if LWIP_ARP
me->m_arp_tmr += LWIP_SLOW_TICK_MS;
if (me->m_arp_tmr >= ARP_TMR_INTERVAL) {
me->m_arp_tmr = 0;
etharp_tmr();
}
#endif
#if LWIP_DHCP
me->m_dhcp_fine_tmr += LWIP_SLOW_TICK_MS;
if (me->m_dhcp_fine_tmr >= DHCP_FINE_TIMER_MSECS) {
me->m_dhcp_fine_tmr = 0;
dhcp_fine_tmr();
}
me->m_dhcp_coarse_tmr += LWIP_SLOW_TICK_MS;
if (me->m_dhcp_coarse_tmr >= DHCP_COARSE_TIMER_MSECS) {
me->m_dhcp_coarse_tmr = 0;
dhcp_coarse_tmr();
}
#endif
#if LWIP_AUTOIP
me->auto_ip_tmr += LWIP_SLOW_TICK_MS;
if (me->auto_ip_tmr >= AUTOIP_TMR_INTERVAL) {
me->auto_ip_tmr = 0;
autoip_tmr();
}
#endif
return Q_HANDLED();
}
case LWIP_DRIVER_GROUP + LWIP_RX_OVERRUN_OFFSET: {
LINK_STATS_INC(link.err);
return Q_HANDLED();
}
}
return Q_SUPER(&QHsm::top);
}
// HTTPD customizations ------------------------------------------------------
// Server-Side Include (SSI) handler .........................................
static int ssi_handler(int iIndex, char *pcInsert, int iInsertLen) {
struct stats_proto *stats = &lwip_stats.link;
STAT_COUNTER value;
switch (iIndex) {
case 0: // s_xmit
value = stats->xmit;
break;
case 1: // s_recv
value = stats->recv;
break;
case 2: // s_fw
value = stats->fw;
break;
case 3: // s_drop
value = stats->drop;
break;
case 4: // s_chkerr
value = stats->chkerr;
break;
case 5: // s_lenerr
value = stats->lenerr;
break;
case 6: // s_memerr
value = stats->memerr;
break;
case 7: // s_rterr
value = stats->rterr;
break;
case 8: // s_proerr
value = stats->proterr;
break;
case 9: // s_opterr
value = stats->opterr;
break;
case 10: // s_err
value = stats->err;
break;
}
return snprintf(pcInsert, MAX_TAG_INSERT_LEN, "%d", value);
}
// Common Gateway Iinterface (CG) handler ....................................
static char const *cgi_display(int index, int numParams,
char const *param[],
char const *value[])
{
for (int i = 0; i < numParams; ++i) {
if (strstr(param[i], "text") != (char *)0) { // param text found?
TextEvt *te = Q_NEW(TextEvt, DISPLAY_CGI_SIG);
strncpy(te->text, value[i], Q_DIM(te->text));
QF::PUBLISH((QEvt *)te, AO_LwIPMgr);
return "/thank_you.htm";
}
}
return (char *)0; // no URI, HTTPD will send 404 error page to the browser
}
// UDP receive handler -------------------------------------------------------
static void udp_rx_handler(void *arg, struct udp_pcb *upcb,
struct pbuf *p, struct ip_addr *addr, u16_t port)
{
TextEvt *te = Q_NEW(TextEvt, DISPLAY_UDP_SIG);
strncpy(te->text, (char *)p->payload, Q_DIM(te->text));
QF::PUBLISH(te, AO_LwIPMgr);
udp_connect(upcb, addr, port); // connect to the remote host
pbuf_free(p); // don't leak the pbuf!
}
| 37.771014 | 78 | 0.514159 | hyller |
f619fc1aac3f323fb765aa700b3ab4e0cfd251b2 | 2,027 | hpp | C++ | src/configure/Platform.hpp | hotgloupi/configure | 888cf725c93df5a1cf01794cc0a581586a82855c | [
"BSD-3-Clause"
] | 1 | 2015-11-13T10:37:35.000Z | 2015-11-13T10:37:35.000Z | src/configure/Platform.hpp | hotgloupi/configure | 888cf725c93df5a1cf01794cc0a581586a82855c | [
"BSD-3-Clause"
] | 19 | 2015-02-10T17:18:58.000Z | 2015-07-11T11:31:08.000Z | src/configure/Platform.hpp | hotgloupi/configure | 888cf725c93df5a1cf01794cc0a581586a82855c | [
"BSD-3-Clause"
] | null | null | null | #pragma once
#include <iosfwd>
#include <string>
namespace configure {
class Platform
{
public:
enum class Vendor {
unknown,
pc,
apple,
};
enum class Arch {
unknown,
x86,
x86_64,
};
enum class SubArch {
unknown,
};
enum class OS {
unknown,
windows,
linux,
osx,
ios,
dragonfly,
freebsd,
netbsd,
openbsd,
aix,
hpux,
solaris,
};
private:
Vendor _vendor;
Arch _arch;
SubArch _sub_arch;
OS _os;
std::string _os_version;
public:
Platform();
public:
#define CONFIGURE_PLATFORM_PROPERTY(EnumType, name) \
EnumType name() const \
{ return _ ## name; } \
std::string name ## _string() const \
{ return to_string<EnumType>(_ ## name); } \
Platform& name(EnumType value) \
{ _ ## name = value; return *this; } \
Platform& name(std::string const& value) \
{ _ ## name = from_string<EnumType>(value); return *this; } \
/**/
CONFIGURE_PLATFORM_PROPERTY(Vendor, vendor);
CONFIGURE_PLATFORM_PROPERTY(Arch, arch);
CONFIGURE_PLATFORM_PROPERTY(SubArch, sub_arch);
CONFIGURE_PLATFORM_PROPERTY(OS, os);
#undef CONFIGURE_PLATFORM_PROPERTY
std::string os_version() const
{ return _os_version; }
Platform& os_version(std::string const& version)
{ _os_version = version; return *this; }
public:
bool is_osx() const { return _os == OS::osx; }
bool is_windows() const { return _os == OS::windows; }
bool is_linux() const { return _os == OS::linux; }
// Returns the number of bits necessary to address memory or 0 if the
// architecture is unknown.
unsigned address_model() const;
bool is_32bit() const { return address_model() == 32; }
bool is_64bit() const { return address_model() == 64; }
public:
static Platform current();
template<typename EnumType>
static std::string const& to_string(EnumType value);
template<typename EnumType>
static EnumType from_string(std::string const& value);
};
std::ostream& operator <<(std::ostream& out, Platform const& p);
}
| 20.896907 | 71 | 0.660582 | hotgloupi |
f61eada41d605c8284e0bbb196d25322ae8faab8 | 2,103 | cc | C++ | common/config.cc | yonsei-icsl/nebula | 12bc2440978018d27996df6b97180056dddefa6c | [
"BSD-3-Clause"
] | 5 | 2020-02-13T04:12:41.000Z | 2021-02-08T04:53:55.000Z | common/config.cc | yonsei-icsl/Nebula | 12bc2440978018d27996df6b97180056dddefa6c | [
"BSD-3-Clause"
] | 1 | 2020-10-29T10:59:08.000Z | 2020-12-31T04:04:58.000Z | common/config.cc | yonsei-icsl/Nebula | 12bc2440978018d27996df6b97180056dddefa6c | [
"BSD-3-Clause"
] | 2 | 2021-03-21T02:45:40.000Z | 2022-03-10T12:31:06.000Z | #include <algorithm>
#include <assert.h>
#include <cstdlib>
#include <fstream>
#include <iostream>
#include <locale>
#include "config.h"
#include "utils.h"
namespace nebula {
// Configuration section
section_config_t::section_config_t(std::string m_name) :
name(m_name) {
}
section_config_t::~section_config_t() {
settings.clear();
}
// Add (key, value) pair to the section settings
void section_config_t::add_setting(std::string m_key, std::string m_value) {
settings.insert(std::pair<std::string,std::string>(lowercase(m_key), lowercase(m_value)));
}
// Check if a setting exists.
bool section_config_t::exists(std::string m_key) {
return settings.find(lowercase(m_key)) != settings.end();
}
// Configuration
config_t::config_t() {
}
config_t::~config_t() {
sections.clear();
}
// Parse configuration file
void config_t::parse(std::string m_config_name) {
std::fstream file_stream;
file_stream.open(m_config_name.c_str(), std::fstream::in);
if(!file_stream.is_open()) {
std::cerr << "Error: failed to open " << m_config_name << std::endl;
exit(1);
}
std::string line;
while(getline(file_stream, line)) {
// Erase all spaces
line.erase(remove(line.begin(),line.end(),' '),line.end());
// Skip blank lines or comments
if(!line.size() || (line[0] == '#')) continue;
// Beginning of [section]
if(line[0] == '[') {
std::string section_name = line.substr(1, line.size()-2);
sections.push_back(section_config_t(section_name));
}
else {
size_t eq = line.find('=');
if(eq == std::string::npos) {
std::cerr << "Error: invalid config" << std::endl << line << std::endl;
exit(1);
}
// Save (key, value) pair in the latest section setting.
std::string key = line.substr(0, eq);
std::string value = line.substr(eq+1, line.size()-1);
sections[sections.size()-1].add_setting(key, value);
}
}
}
}
// End of namespace nebula
| 26.620253 | 94 | 0.603899 | yonsei-icsl |
f622a2d64454d726a5561d310bfe9e66cbfc56c8 | 289 | hpp | C++ | engine/src/Resources/ImageData.hpp | aleksigron/graphics-toolkit | f8e60c57316a72dff9de07512e9771deb3799208 | [
"MIT"
] | 14 | 2017-10-17T16:20:20.000Z | 2021-12-21T14:49:00.000Z | engine/src/Resources/ImageData.hpp | aleksigron/graphics-toolkit | f8e60c57316a72dff9de07512e9771deb3799208 | [
"MIT"
] | null | null | null | engine/src/Resources/ImageData.hpp | aleksigron/graphics-toolkit | f8e60c57316a72dff9de07512e9771deb3799208 | [
"MIT"
] | 1 | 2019-05-12T13:50:23.000Z | 2019-05-12T13:50:23.000Z | #pragma once
#include <cstddef>
#include "Math/Vec2.hpp"
struct ImageData
{
unsigned char* imageData;
size_t imageDataSize;
Vec2i imageSize;
unsigned int pixelFormat;
unsigned int componentDataType;
size_t compressedSize;
bool compressed;
ImageData();
};
| 13.761905 | 33 | 0.705882 | aleksigron |
f624d363ac3f6f847615772a93146521aeef640b | 804 | cpp | C++ | bls_sig.cpp | ANSIIRU/BLS12_381-small_memory_c- | 6109d56c38a4c9243dcbcd0464b50feaa2f70a89 | [
"Unlicense"
] | null | null | null | bls_sig.cpp | ANSIIRU/BLS12_381-small_memory_c- | 6109d56c38a4c9243dcbcd0464b50feaa2f70a89 | [
"Unlicense"
] | null | null | null | bls_sig.cpp | ANSIIRU/BLS12_381-small_memory_c- | 6109d56c38a4c9243dcbcd0464b50feaa2f70a89 | [
"Unlicense"
] | null | null | null | #include "my_pairing.h"
#include <stdio.h>
void KeyGen(const char* s, EC_Fp2* pub, EC_Fp2* Q)
{
G2_SCM(pub, s, Q); // pub = sQ
// printf("pub=\n");
// EC_Fp2_print(pub);
}
void SignGen(EC_Fp *sign, const char* s, const char *m)
{
EC_Fp Hm;
hash_to_curve(&Hm,m);
// EC_Fp_from_Mont(&Hm);
// EC_Fp_print(&Hm);
//EC_Fp_to_Mont(&Hm.&Hm);
G1_SCM(sign,s,&Hm); // sign = s H(m)
}
int Verify(EC_Fp *sign,EC_Fp2 *Q,EC_Fp2 *pub,const char *m){
Fp12 e1,e2;
EC_Fp Hm;
hash_to_curve(&Hm,m);
// EC_Fp_print(sign);
// EC_Fp_print(&Hm);
// EC_Fp2_print(Q);
// EC_Fp2_print(pub);
my_pairing_proj(&e1,Q,sign);
my_pairing_proj(&e2,pub,&Hm);
printf("e1 = \n");
Fp12_print(&e1);
printf("e2 = \n");
Fp12_print(&e2);
return Fp12_cmp(&e1, &e2);
}
| 21.72973 | 61 | 0.588308 | ANSIIRU |
f629287e0571ed47dd294ebfb0d6cda890b59810 | 2,283 | cpp | C++ | codeforces/N - Wires/Wrong answer on test 1.cpp | kzvd4729/Problem-Solving | 13b105e725a4c2f8db7fecc5d7a8f932b9fef4ab | [
"MIT"
] | 1 | 2022-02-11T16:55:36.000Z | 2022-02-11T16:55:36.000Z | codeforces/N - Wires/Wrong answer on test 1.cpp | kzvd4729/Problem-Solving | 13b105e725a4c2f8db7fecc5d7a8f932b9fef4ab | [
"MIT"
] | null | null | null | codeforces/N - Wires/Wrong answer on test 1.cpp | kzvd4729/Problem-Solving | 13b105e725a4c2f8db7fecc5d7a8f932b9fef4ab | [
"MIT"
] | null | null | null | /****************************************************************************************
* @author: kzvd4729 created: Oct/27/2019 19:37
* solution_verdict: Wrong answer on test 1 language: GNU C++14
* run_time: 0 ms memory_used: 19700 KB
* problem: https://codeforces.com/contest/1250/problem/N
****************************************************************************************/
#include<bits/stdc++.h>
#define long long long
using namespace std;
const int N=1e6;
int par[N+2],uu[N+2],vv[N+2],ed[N+2],deg[N+2];
int get(int x)
{
if(x==par[x])return x;
return par[x]=get(par[x]);
}
int main()
{
ios_base::sync_with_stdio(0);cin.tie(0);
int t;cin>>t;
while(t--)
{
int n;cin>>n;vector<int>vc;
for(int i=1;i<=n;i++)
{
cin>>uu[i]>>vv[i];
vc.push_back(uu[i]);vc.push_back(vv[i]);
}
sort(vc.begin(),vc.end());
vc.erase(unique(vc.begin(),vc.end()),vc.end());
map<int,int>cn,rv;int sz=0;
for(auto x:vc)
{
cn[x]=++sz;rv[sz]=x;
}
for(int i=1;i<=n;i++)uu[i]=cn[uu[i]],vv[i]=cn[vv[i]];
for(int i=1;i<=sz;i++)par[i]=i,ed[i]=0,deg[i]=0;
// cout<<endl;
// for(int i=1;i<=n;i++)
// cout<<uu[i]<<"-->"<<vv[i]<<endl;
vector<int>ex;
for(int i=1;i<=n;i++)
{
int r1=get(uu[i]),r2=get(vv[i]);
if(r1==r2)ex.push_back(i);
else par[r1]=r2;
deg[uu[i]]++,deg[vv[i]]++;
}
// for(int i=1;i<=sz;i++)
// cout<<deg[i]<<" ";
// cout<<endl;
vector<int>rt;
for(int i=1;i<=sz;i++)
rt.push_back(get(i));
sort(rt.begin(),rt.end());
rt.erase(unique(rt.begin(),rt.end()),rt.end());
for(auto x:ex)
{
int r=get(uu[x]);
if(!ed[r])ed[r]=x;
}
for(int i=1;i<=n;i++)
{
if(deg[uu[i]]==1||deg[vv[i]]==1)
{
int r=get(uu[i]);
if(!ed[r])ed[r]=i;
}
}
cout<<rt.size()-1<<"\n";
for(int i=1;i<rt.size();i++)
{
int nm=ed[rt[i]];
cout<<nm<<" ";
if(deg[uu[nm]]==0)cout<<rv[uu[nm]]<<" "<<rv[rt[i-1]]<<"\n";
else cout<<rv[vv[nm]]<<" "<<rv[rt[i-1]]<<"\n";
}
}
return 0;
} | 28.5375 | 111 | 0.412615 | kzvd4729 |
f62b23f95c442075e0a6cadee50fc25b565bf479 | 4,132 | cpp | C++ | src/download.cpp | toyobayashi/evm-windows | 5734cfe8555ccc492671e15bc30b54467681c749 | [
"MIT"
] | null | null | null | src/download.cpp | toyobayashi/evm-windows | 5734cfe8555ccc492671e15bc30b54467681c749 | [
"MIT"
] | null | null | null | src/download.cpp | toyobayashi/evm-windows | 5734cfe8555ccc492671e15bc30b54467681c749 | [
"MIT"
] | null | null | null | #include <sstream>
#include <math.h>
#include <time.h>
#include "download.h"
#include <curl/curl.h>
#include <iostream>
#include "path.hpp"
//static size_t onDataString(void* buffer, size_t size, size_t nmemb, progressInfo * userp) {
// const char* d = (const char*)buffer;
// // userp->headerString.append(d, size * nmemb);
// std::string tmp(d);
// unsigned int contentlengthIndex = tmp.find(std::string("Content-Length: "));
// if (contentlengthIndex != std::string::npos) {
// userp->total = atoi(tmp.substr(16, tmp.find_first_of('\r')).c_str()) + userp->size;
// }
// return size * nmemb;
//}
static size_t onDataWrite(void* buffer, size_t size, size_t nmemb, progressInfo * userp) {
if (userp->code == -1) {
curl_easy_getinfo(userp->curl, CURLINFO_RESPONSE_CODE, &(userp->code));
}
if (userp->code >= 400) {
return size * nmemb;
}
if (userp->total == -1) {
curl_off_t cl;
curl_easy_getinfo(userp->curl, CURLINFO_CONTENT_LENGTH_DOWNLOAD_T, &cl);
if (cl != -1) {
userp->total = (long)cl + userp->size;
} else {
return size * nmemb;
}
}
if (userp->fp == nullptr) {
Path::mkdirp(Path::dirname(userp->path));
_wfopen_s(&(userp->fp), (userp->path + L".tmp").c_str(), L"ab+");
if (!(userp->fp)) {
return size * nmemb;
}
}
size_t iRec = fwrite(buffer, size, nmemb, userp->fp);
if (iRec < 0) {
return iRec;
}
userp->sum += iRec;
userp->speed += iRec;
int now = clock();
if (now - userp->last_time > 200) {
userp->last_time = now;
userp->speed = 0;
if (userp->callback) {
userp->callback(userp, userp->param);
}
} else if (userp->sum == userp->total - userp->size) {
userp->end_time = clock();
if (userp->callback) {
userp->callback(userp, userp->param);
}
}
return iRec;
}
bool download (std::wstring url, std::wstring path, downloadCallback callback, void* param) {
if (Path::exists(path)) {
if (Path::isDirectory(path)) {
return false;
}
return true;
}
CURL* curl = curl_easy_init();
struct curl_slist* headers = nullptr;
/*headers = curl_slist_append(headers, "Connection: Keep-Alive");
headers = curl_slist_append(headers, "Accept-Encoding: gzip");*/
headers = curl_slist_append(headers, "Accept: */*");
headers = curl_slist_append(headers, "User-Agent: Electron Version Manager");
struct _stat stat;
int res = _wstat((path + L".tmp").c_str(), &stat);
long size = stat.st_size;
if (size != 0) {
headers = curl_slist_append(headers, (std::string("Range: bytes=") + std::to_string(size) + "-").c_str());
}
curl_easy_setopt(curl, CURLOPT_HTTPHEADER, headers);
curl_easy_setopt(curl, CURLOPT_URL, Util::w2a(url, CP_UTF8).c_str());
curl_easy_setopt(curl, CURLOPT_CUSTOMREQUEST, "GET");
curl_easy_setopt(curl, CURLOPT_CONNECTTIMEOUT, 10);
curl_easy_setopt(curl, CURLOPT_FOLLOWLOCATION, 1);
//curl_easy_setopt(curl, CURLOPT_TIMEOUT, 10);
progressInfo info;
info.path = path;
info.curl = curl;
info.fp = nullptr;
info.size = size;
info.sum = 0;
info.speed = 0;
info.start_time = clock();
info.end_time = 0;
info.last_time = 0;
info.total = -1;
info.param = param;
info.code = -1;
info.callback = callback;
// curl_easy_setopt(curl, CURLOPT_HEADERFUNCTION, &onDataString);
// curl_easy_setopt(curl, CURLOPT_HEADERDATA, &info);
curl_easy_setopt(curl, CURLOPT_WRITEFUNCTION, &onDataWrite);
curl_easy_setopt(curl, CURLOPT_WRITEDATA, &info);
curl_easy_setopt(curl, CURLOPT_SSL_VERIFYPEER, 0L);
curl_easy_setopt(curl, CURLOPT_SSL_VERIFYHOST, 0L);
CURLcode code = curl_easy_perform(curl);
if (code != CURLE_OK) {
printf("%s\n", curl_easy_strerror(code));
if (info.fp != nullptr) {
fclose(info.fp);
info.fp = nullptr;
}
curl_slist_free_all(headers);
curl_easy_cleanup(curl);
return false;
}
if (info.fp != nullptr) {
fclose(info.fp);
info.fp = nullptr;
if (Path::exists(path + L".tmp")) {
Path::rename(path + L".tmp", path);
}
}
curl_slist_free_all(headers);
curl_easy_cleanup(curl);
return true;
}
| 27.731544 | 110 | 0.644966 | toyobayashi |
f62f1a39f186141cf5bcc647a9be7668ac6314ad | 7,801 | cpp | C++ | app/src/main/engine/android/esutil_android.cpp | qige023/learning-opengles3-android | cbe0742637a6eeed41c76756021913cc570cc30e | [
"MIT"
] | 10 | 2015-05-06T17:59:51.000Z | 2019-12-03T10:08:23.000Z | app/src/main/engine/android/esutil_android.cpp | qige023/OpenGL-ES3-Programming-On-Android | cbe0742637a6eeed41c76756021913cc570cc30e | [
"MIT"
] | null | null | null | app/src/main/engine/android/esutil_android.cpp | qige023/OpenGL-ES3-Programming-On-Android | cbe0742637a6eeed41c76756021913cc570cc30e | [
"MIT"
] | null | null | null | //
// This file contains the Android implementation of the windowing functions.
#include <android/log.h>
#include <android/keycodes.h>
#include <android/input.h>
#include <android_native_app_glue.h>
#include <time.h>
#include <iostream>
#include <stdexcept>
using std::cout;
using std::cerr;
using std::endl;
#include "esutil.h"
#include "esfile.h"
#include "android/buf_android.hpp"
///
// Global extern. The application must declare this function
// that runs the application.
//
extern ESScene *esCreateScene(ESContext *esContext);
static int esMain(ESContext *esContext) {
cout << "exec esMain..." << endl;
ESScene *scene = esCreateScene(esContext);
AAssetManager *assetManager = (( ANativeActivity * ) esContext->platformData)->assetManager;
ESFileWrapper::setAssetmanager(assetManager);
if(scene != NULL) {
esContext->scene = scene;
GLboolean result = esCreateWindow(esContext, "Simple VertexShader", 320, 240,
ES_WINDOW_RGB | ES_WINDOW_DEPTH);
if (result != GL_TRUE) {
throw new std::runtime_error("Unable to create EGL native window.");
return false;
}
scene->initScene(esContext);
return TRUE;
}
return FALSE;
}
//////////////////////////////////////////////////////////////////
//
// Private Functions
//
//
///
// GetCurrentTime()
//
static float GetCurrentTime() {
struct timespec clockRealTime;
clock_gettime( CLOCK_MONOTONIC, &clockRealTime);
double curTimeInSeconds = clockRealTime.tv_sec
+ (double) clockRealTime.tv_nsec / 1e9;
return (float) curTimeInSeconds;
}
///
// Android callback for onAppCmd
//
static void HandleCommand(struct android_app *pApp, int32_t cmd) {
ESContext *esContext = (ESContext *) pApp->userData;
switch (cmd) {
case APP_CMD_SAVE_STATE:
cout << "HandleCommand APP_CMD_SAVE_STATE" << endl;
// the OS asked us to save the state of the app
break;
case APP_CMD_INIT_WINDOW:
cout << "HandleCommand APP_CMD_INIT_WINDOW" << endl;
esContext->platformData = (void *) pApp->activity;
esContext->eglNativeDisplay = EGL_DEFAULT_DISPLAY;
esContext->eglNativeWindow = pApp->window;
cout.rdbuf(new outlogbuf());
cerr.rdbuf(new outlogbuf());
// Call the main entry point for the app
if (esMain(esContext) != GL_TRUE) {
exit(0); //@TEMP better way to exit?
}
break;
case APP_CMD_TERM_WINDOW:
cout << "HandleCommand APP_CMD_TERM_WINDOW" << endl;
delete esContext->scene;
cout.rdbuf(0);
cerr.rdbuf(0);
//reset esContext
memset(esContext, 0, sizeof(ESContext));
break;
case APP_CMD_LOST_FOCUS:
cout << "HandleCommand APP_CMD_LOST_FOCUS" << endl;
// if the app lost focus, avoid unnecessary processing (like monitoring the accelerometer)
break;
case APP_CMD_GAINED_FOCUS:
cout << "HandleCommand APP_CMD_GAINED_FOCUS" << endl;
// bring back a certain functionality, like monitoring the accelerometer
break;
}
}
///
// Android callback for onAppInput
//
static int32_t HandleInput(struct android_app* pApp, AInputEvent* event) {
ESContext *esContext = (ESContext *) pApp->userData;
int32_t eventType = AInputEvent_getType(event);
int32_t eventSource = AInputEvent_getSource(event);
int32_t eventAction;
float motionX, motionY;
size_t pointerIndex;
int32_t pointerId ,pointerCount;
switch (eventType) {
case AINPUT_EVENT_TYPE_MOTION:
switch (eventSource) {
case AINPUT_SOURCE_TOUCHSCREEN:
eventAction = AMotionEvent_getAction(event) & AMOTION_EVENT_ACTION_MASK;
pointerIndex = (AMotionEvent_getAction(event) & AMOTION_EVENT_ACTION_POINTER_INDEX_MASK) >> AMOTION_EVENT_ACTION_POINTER_INDEX_SHIFT;
pointerId = AMotionEvent_getPointerId(event, pointerIndex);
motionX = AMotionEvent_getX(event, pointerId);
motionY = AMotionEvent_getY(event, pointerId);
switch (eventAction) {
case AMOTION_EVENT_ACTION_MOVE:
//http://stackoverflow.com/questions/9028357/android-multitouch-second-finger-action-move-ignored
cout << "HandleInput AMOTION_EVENT_ACTION_MOVE" << endl;
pointerCount = AMotionEvent_getPointerCount(event);
for(int i = 0; i < pointerCount; ++i) {
pointerIndex = i;
pointerId = AMotionEvent_getPointerId(event, pointerIndex);
motionX = AMotionEvent_getX(event, pointerId);
motionY = AMotionEvent_getY(event, pointerId);
if(esContext->onMotionListener != NULL) {
esContext->onMotionListener->onMotionMove(pointerId, motionX, motionY);
cout <<"pointerId: "<< pointerId << " X: " << motionX << " Y: " << motionY << endl;
}
}
break;
case AMOTION_EVENT_ACTION_DOWN:
case AMOTION_EVENT_ACTION_POINTER_DOWN:
cout << "HandleInput AMOTION_EVENT_ACTION_POINTER_DOWN" << endl;
if(esContext->onMotionListener != NULL) {
esContext->onMotionListener->onMotionDown(pointerId, motionX, motionY);
cout <<"pointerId: "<< pointerId << " X: " << motionX << " Y: " << motionY << endl;
}
break;
case AMOTION_EVENT_ACTION_UP:
case AMOTION_EVENT_ACTION_POINTER_UP:
cout << "HandleInput AMOTION_EVENT_ACTION_UP" << endl;
if(esContext->onMotionListener != NULL) {
esContext->onMotionListener->onMotionUp(pointerId, motionX, motionY);
cout <<"pointerId: "<< pointerId << " X: " << motionX << " Y: " << motionY << endl;
}
break;
}
break;
case AINPUT_SOURCE_TRACKBALL:
break;
}
return 0;
break;
case AINPUT_EVENT_TYPE_KEY:
switch (AKeyEvent_getKeyCode(event))
case AKEYCODE_BACK:
return 0;
break;
default:
return 0;
}
}
//////////////////////////////////////////////////////////////////
//
// Public Functions
//
///
// android_main()
//
// Main entrypoint for Android application
//
void android_main(struct android_app *pApp) {
ESContext *esContext = new ESContext();
float lastTime;
// Make sure glue isn't stripped.
app_dummy();
// Initialize the context
memset(esContext, 0, sizeof(ESContext));
pApp->userData = esContext;
pApp->onAppCmd = HandleCommand;
//设置输入事件的处理函数,如触摸响应
pApp->onInputEvent = HandleInput;
lastTime = GetCurrentTime();
while (TRUE) {
int ident;
int events;
struct android_poll_source *pSource;
while ((ident = ALooper_pollAll(0, NULL, &events, (void **) &pSource))
>= 0) {
if (pSource != NULL) {
pSource->process(pApp, pSource);
}
if (pApp->destroyRequested != 0) {
return;
}
}
if (esContext->eglNativeWindow == NULL) {
continue;
}
// Call app update function
if (esContext->scene != NULL) {
float curTime = GetCurrentTime();
float deltaTime = (curTime - lastTime);
lastTime = curTime;
esContext->scene->update(esContext, deltaTime);
esContext->scene->render(esContext);
eglSwapBuffers(esContext->eglDisplay, esContext->eglSurface);
}
}
}
| 31.329317 | 145 | 0.596077 | qige023 |
f6350a75839dd98d27716a02d3fc370e117f9ddf | 1,002 | cpp | C++ | include/h3api/H3AdventureMap/H3MapMine.cpp | Patrulek/H3API | 91f10de37c6b86f3160706c1fdf4792f927e9952 | [
"MIT"
] | 14 | 2020-09-07T21:49:26.000Z | 2021-11-29T18:09:41.000Z | include/h3api/H3AdventureMap/H3MapMine.cpp | Day-of-Reckoning/H3API | a82d3069ec7d5127b13528608d5350d2b80d57be | [
"MIT"
] | 2 | 2021-02-12T15:52:31.000Z | 2021-02-12T16:21:24.000Z | include/h3api/H3AdventureMap/H3MapMine.cpp | Day-of-Reckoning/H3API | a82d3069ec7d5127b13528608d5350d2b80d57be | [
"MIT"
] | 8 | 2021-02-12T15:52:41.000Z | 2022-01-31T15:28:10.000Z | //////////////////////////////////////////////////////////////////////
// //
// Created by RoseKavalier: //
// [email protected] //
// Created or last updated on: 2021-02-02 //
// ***You may use or distribute these files freely //
// so long as this notice remains present.*** //
// //
//////////////////////////////////////////////////////////////////////
#include "h3api/H3AdventureMap/H3MapMine.hpp"
#include "h3api/H3GameData/H3Main.hpp"
namespace h3
{
_H3API_ H3Mine* H3MapitemMine::Get()
{
return Get(H3Main::Get());
}
_H3API_ H3Mine* H3MapitemMine::Get(H3Main* main)
{
return &main->minesLighthouses[index];
}
_H3API_ BOOL H3Mine::IsAbandonned() const
{
return abandoned;
}
} /* namespace h3 */
| 33.4 | 70 | 0.398204 | Patrulek |
f63801e52141d3566d949e3eabc9309d3d2ec863 | 987 | hpp | C++ | src/point.hpp | xyl1t/Cidr | 48ee260ec4871eddb795ccc0f3aa1fddfc2cd0aa | [
"MIT"
] | 6 | 2020-09-10T17:44:49.000Z | 2021-03-14T16:41:11.000Z | src/point.hpp | xyl1t/Cidr | 48ee260ec4871eddb795ccc0f3aa1fddfc2cd0aa | [
"MIT"
] | 1 | 2021-07-22T20:25:00.000Z | 2021-11-27T19:44:35.000Z | src/point.hpp | xyl1t/Cidr | 48ee260ec4871eddb795ccc0f3aa1fddfc2cd0aa | [
"MIT"
] | null | null | null | /********************************
* Project: Cidr *
* File: point.hpp *
* Date: 12.9.2020 *
********************************/
#ifndef CIDR_POINT_HPP
#define CIDR_POINT_HPP
#include "tensorMath.hpp"
// TODO: ADD CONSTURCTORS!
// In order to keep the code "consice" I just derive the point classes from vectors
// But Since points are not really vectors they shouldn't have length functions so I hide them
namespace cdr {
struct FPoint;
struct Point : public tem::ivec2 {
public:
Point();
Point(int x, int y);
operator cdr::FPoint() const;
private:
using tem::ivec2::length;
using tem::ivec2::setLength;
using tem::ivec2::addLength;
using tem::ivec2::subLength;
};
struct FPoint : public tem::vec2 {
public:
FPoint();
FPoint(float x, float y);
operator cdr::Point() const;
private:
using tem::vec2::length;
using tem::vec2::setLength;
using tem::vec2::addLength;
using tem::vec2::subLength;
};
}
#endif | 21.456522 | 94 | 0.616008 | xyl1t |
f63979213498b360b480d39e0eb915fec6641e5c | 4,595 | hpp | C++ | Kuplung/kuplung/objects/ObjectsManager.hpp | supudo/Kuplung | f0e11934fde0675fa531e6dc263bedcc20a5ea1a | [
"Unlicense"
] | 14 | 2017-02-17T17:12:40.000Z | 2021-12-22T01:55:06.000Z | Kuplung/kuplung/objects/ObjectsManager.hpp | supudo/Kuplung | f0e11934fde0675fa531e6dc263bedcc20a5ea1a | [
"Unlicense"
] | null | null | null | Kuplung/kuplung/objects/ObjectsManager.hpp | supudo/Kuplung | f0e11934fde0675fa531e6dc263bedcc20a5ea1a | [
"Unlicense"
] | 1 | 2019-10-15T08:10:10.000Z | 2019-10-15T08:10:10.000Z | //
// ObjectsManager.hpp
// Kuplung
//
// Created by Sergey Petrov on 12/3/15.
// Copyright © 2015 supudo.net. All rights reserved.
//
#ifndef ObjectsManager_hpp
#define ObjectsManager_hpp
#include <functional>
#include <map>
#include <string>
#include <vector>
#include <glm/glm.hpp>
#include "kuplung/objects/ObjectDefinitions.h"
#include "kuplung/meshes/helpers/Camera.hpp"
#include "kuplung/meshes/helpers/CameraModel.hpp"
#include "kuplung/meshes/helpers/Light.hpp"
#include "kuplung/meshes/helpers/AxisHelpers.hpp"
#include "kuplung/meshes/helpers/AxisLabels.hpp"
#include "kuplung/meshes/helpers/MiniAxis.hpp"
#include "kuplung/meshes/helpers/Skybox.hpp"
#include "kuplung/meshes/helpers/WorldGrid.hpp"
#include "kuplung/meshes/helpers/Grid2D.hpp"
#include "kuplung/meshes/artefacts/Terrain.hpp"
#include "kuplung/meshes/artefacts/Spaceship.hpp"
#include "kuplung/utilities/parsers/FileModelManager.hpp"
typedef enum GeometryEditMode {
GeometryEditMode_Vertex,
GeometryEditMode_Line,
GeometryEditMode_Face
} GeometryEditMode;
class ObjectsManager {
public:
~ObjectsManager();
void init(const std::function<void(float)>& doProgress,
const std::function<void()>& addTerrain,
const std::function<void()>& addSpaceship);
void loadSystemModels(const std::unique_ptr<FileModelManager> &fileParser);
void render();
void renderSkybox();
void resetPropertiesSystem();
void resetSettings();
void generateTerrain();
void generateSpaceship();
void clearAllLights();
void initCamera();
void initCameraModel();
void initGrid();
void initGrid2D();
void initAxisSystem();
void initAxisHelpers();
void initAxisLabels();
void initSkybox();
void initTerrain();
void initSpaceship();
void addLight(const LightSourceType type, std::string const& title = "", std::string const& description = "");
std::vector<Light*> lightSources;
std::unique_ptr<Camera> camera;
std::unique_ptr<CameraModel> cameraModel;
std::unique_ptr<WorldGrid> grid;
std::unique_ptr<Grid2D> grid2d;
std::unique_ptr<MiniAxis> axisSystem;
std::unique_ptr<Skybox> skybox;
std::unique_ptr<AxisHelpers> axisHelpers_xMinus, axisHelpers_xPlus, axisHelpers_yMinus, axisHelpers_yPlus, axisHelpers_zMinus, axisHelpers_zPlus;
std::unique_ptr<AxisLabels> axisLabels;
std::unique_ptr<Terrain> terrain;
std::unique_ptr<Spaceship> spaceship;
glm::mat4 matrixProjection;
float Setting_FOV = 45.0;
float Setting_OutlineThickness = 1.01f;
float Setting_RatioWidth = 4.0f, Setting_RatioHeight = 3.0f;
float Setting_PlaneClose = 0.1f, Setting_PlaneFar = 100.0f;
int Setting_GridSize = 30, Setting_Skybox = 0;
glm::vec4 Setting_OutlineColor;
glm::vec3 Setting_UIAmbientLight;
bool Setting_FixedGridWorld = true, Setting_OutlineColorPickerOpen = false, Setting_ShowAxisHelpers = true;
bool Setting_UseWorldGrid = false;
bool Settings_ShowZAxis = true;
bool Setting_DeferredTestMode, Setting_DeferredTestLights, Setting_DeferredRandomizeLightPositions;
int Setting_LightingPass_DrawMode, Setting_DeferredTestLightsNumber;
float Setting_DeferredAmbientStrength;
float Setting_GammaCoeficient;
ViewModelSkin viewModelSkin;
glm::vec3 SolidLight_Direction;
glm::vec3 SolidLight_MaterialColor, SolidLight_Ambient, SolidLight_Diffuse, SolidLight_Specular;
float SolidLight_Ambient_Strength, SolidLight_Diffuse_Strength, SolidLight_Specular_Strength;
bool SolidLight_MaterialColor_ColorPicker, SolidLight_Ambient_ColorPicker, SolidLight_Diffuse_ColorPicker, SolidLight_Specular_ColorPicker;
bool Setting_ShowTerrain, Setting_TerrainModel, Setting_TerrainAnimateX, Setting_TerrainAnimateY;
std::string heightmapImage;
int Setting_TerrainWidth = 100, Setting_TerrainHeight = 100;
bool Setting_ShowSpaceship, Setting_GenerateSpaceship, Setting_Cuda_ShowOceanFFT;
bool Setting_VertexSphere_Visible, Setting_VertexSphere_ColorPickerOpen;
bool Setting_VertexSphere_IsSphere, Setting_VertexSphere_ShowWireframes;
float Setting_VertexSphere_Radius;
int Setting_VertexSphere_Segments;
glm::vec4 Setting_VertexSphere_Color;
int VertexEditorModeID;
glm::vec3 VertexEditorMode;
GeometryEditMode Setting_GeometryEditMode;
std::map<std::string, MeshModel> systemModels;
bool Setting_Rendering_Depth, Setting_DebugShadowTexture;
std::string shaderSourceVertex, shaderSourceTCS, shaderSourceTES, shaderSourceGeometry, shaderSourceFragment;
private:
std::function<void(float)> funcProgress;
std::function<void()> funcAddTerrain;
std::function<void()> funcAddSpaceship;
};
#endif /* ObjectsManager_hpp */
| 36.181102 | 146 | 0.796953 | supudo |
f64dec40bd138e76dd99b023fda095d959fab0c3 | 149 | cpp | C++ | libng/core/src/libng_core/ui/platform/mac/MacWindow.cpp | gapry/libng | 8fbf927e5bb73f105bddbb618430d3e1bf2cf877 | [
"MIT"
] | null | null | null | libng/core/src/libng_core/ui/platform/mac/MacWindow.cpp | gapry/libng | 8fbf927e5bb73f105bddbb618430d3e1bf2cf877 | [
"MIT"
] | null | null | null | libng/core/src/libng_core/ui/platform/mac/MacWindow.cpp | gapry/libng | 8fbf927e5bb73f105bddbb618430d3e1bf2cf877 | [
"MIT"
] | null | null | null | #include <libng_core/ui/platform/mac/MacWindow.hpp>
namespace libng {
MacWindow::MacWindow() {
}
MacWindow::~MacWindow() {
}
} // namespace libng | 13.545455 | 51 | 0.711409 | gapry |
f64e1d74027d448ea856d893613a9544aa81cacb | 46,045 | cpp | C++ | hi_scripting/scripting/ScriptProcessorModules.cpp | Matt-Dub/HISE | ae2dd1653e1c8d749a9088edcd573de6252b0b96 | [
"Intel"
] | null | null | null | hi_scripting/scripting/ScriptProcessorModules.cpp | Matt-Dub/HISE | ae2dd1653e1c8d749a9088edcd573de6252b0b96 | [
"Intel"
] | null | null | null | hi_scripting/scripting/ScriptProcessorModules.cpp | Matt-Dub/HISE | ae2dd1653e1c8d749a9088edcd573de6252b0b96 | [
"Intel"
] | null | null | null | /* ===========================================================================
*
* This file is part of HISE.
* Copyright 2016 Christoph Hart
*
* HISE is free software: you can redistribute it and/or modify
* it under the terms of the GNU General Public License as published by
* the Free Software Foundation, either version 3 of the License, or
* (at your option) any later version.
*
* HISE 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 HISE. If not, see <http://www.gnu.org/licenses/>.
*
* Commercial licenses for using HISE in an closed source project are
* available on request. Please visit the project's website to get more
* information about commercial licensing:
*
* http://www.hise.audio/
*
* HISE is based on the JUCE library,
* which also must be licenced for commercial applications:
*
* http://www.juce.com
*
* ===========================================================================
*/
namespace hise { using namespace juce;
JavascriptMidiProcessor::JavascriptMidiProcessor(MainController *mc, const String &id) :
ScriptBaseMidiProcessor(mc, id),
JavascriptProcessor(mc),
onInitCallback(new SnippetDocument("onInit")),
onNoteOnCallback(new SnippetDocument("onNoteOn")),
onNoteOffCallback(new SnippetDocument("onNoteOff")),
onControllerCallback(new SnippetDocument("onController")),
onTimerCallback(new SnippetDocument("onTimer")),
onControlCallback(new SnippetDocument("onControl", "number value")),
front(false),
deferred(false),
deferredExecutioner(this),
deferredUpdatePending(false)
{
initContent();
editorStateIdentifiers.add("contentShown");
editorStateIdentifiers.add("onInitOpen");
editorStateIdentifiers.add("onNoteOnOpen");
editorStateIdentifiers.add("onNoteOffOpen");
editorStateIdentifiers.add("onControllerOpen");
editorStateIdentifiers.add("onTimerOpen");
editorStateIdentifiers.add("onControlOpen");
editorStateIdentifiers.add("externalPopupShown");
setEditorState(Identifier("contentShown"), true);
setEditorState(Identifier("onInitOpen"), true);
}
JavascriptMidiProcessor::~JavascriptMidiProcessor()
{
cleanupEngine();
clearExternalWindows();
serverObject = nullptr;
onInitCallback = nullptr;
onNoteOnCallback = nullptr;
onNoteOffCallback = nullptr;
onControllerCallback = nullptr;
onTimerCallback = nullptr;
onControlCallback = nullptr;
#if USE_BACKEND
if (consoleEnabled)
{
getMainController()->setWatchedScriptProcessor(nullptr, nullptr);
}
#endif
}
Path JavascriptMidiProcessor::getSpecialSymbol() const
{
Path path; path.loadPathFromData(HiBinaryData::SpecialSymbols::scriptProcessor, sizeof(HiBinaryData::SpecialSymbols::scriptProcessor)); return path;
}
ValueTree JavascriptMidiProcessor::exportAsValueTree() const
{
ValueTree v = ScriptBaseMidiProcessor::exportAsValueTree();
saveScript(v);
return v;
}
void JavascriptMidiProcessor::restoreFromValueTree(const ValueTree &v)
{
restoreScript(v);
ScriptBaseMidiProcessor::restoreFromValueTree(v);
}
JavascriptMidiProcessor::SnippetDocument * JavascriptMidiProcessor::getSnippet(int c)
{
switch (c)
{
case onInit: return onInitCallback;
case onNoteOn: return onNoteOnCallback;
case onNoteOff: return onNoteOffCallback;
case onController: return onControllerCallback;
case onTimer: return onTimerCallback;
case onControl: return onControlCallback;
default: jassertfalse; return nullptr;
}
}
const JavascriptMidiProcessor::SnippetDocument * JavascriptMidiProcessor::getSnippet(int c) const
{
switch (c)
{
case onInit: return onInitCallback;
case onNoteOn: return onNoteOnCallback;
case onNoteOff: return onNoteOffCallback;
case onController: return onControllerCallback;
case onTimer: return onTimerCallback;
case onControl: return onControlCallback;
default: jassertfalse; return nullptr;
}
}
ProcessorEditorBody *JavascriptMidiProcessor::createEditor(ProcessorEditor *parentEditor)
{
#if USE_BACKEND
return new ScriptingEditor(parentEditor);
#else
ignoreUnused(parentEditor);
jassertfalse;
return nullptr;
#endif
};
void JavascriptMidiProcessor::processHiseEvent(HiseEvent &m)
{
if (isDeferred())
{
deferredExecutioner.addPendingEvent(m);
}
else
{
ADD_GLITCH_DETECTOR(this, DebugLogger::Location::ScriptMidiEventCallback);
if (currentMidiMessage != nullptr)
{
ScopedValueSetter<HiseEvent*> svs(currentEvent, &m);
currentMidiMessage->setHiseEvent(m);
runScriptCallbacks();
}
}
}
void JavascriptMidiProcessor::registerApiClasses()
{
//content = new ScriptingApi::Content(this);
front = false;
currentMidiMessage = new ScriptingApi::Message(this);
engineObject = new ScriptingApi::Engine(this);
synthObject = new ScriptingApi::Synth(this, currentMidiMessage.get(), getOwnerSynth());
scriptEngine->registerApiClass(new ScriptingApi::ModuleIds(getOwnerSynth()));
samplerObject = new ScriptingApi::Sampler(this, dynamic_cast<ModulatorSampler*>(getOwnerSynth()));
scriptEngine->registerNativeObject("Content", getScriptingContent());
scriptEngine->registerApiClass(currentMidiMessage.get());
scriptEngine->registerApiClass(engineObject.get());
scriptEngine->registerApiClass(new ScriptingApi::Settings(this));
scriptEngine->registerApiClass(new ScriptingApi::FileSystem(this));
scriptEngine->registerApiClass(serverObject = new ScriptingApi::Server(this));
scriptEngine->registerApiClass(new ScriptingApi::Console(this));
scriptEngine->registerApiClass(new ScriptingApi::Colours());
scriptEngine->registerApiClass(synthObject);
scriptEngine->registerApiClass(samplerObject);
scriptEngine->registerNativeObject("Libraries", new DspFactory::LibraryLoader(this));
scriptEngine->registerNativeObject("Buffer", new VariantBuffer::Factory(64));
}
void JavascriptMidiProcessor::addToFront(bool addToFront_) noexcept
{
front = addToFront_;
#if USE_FRONTEND
content->getUpdateDispatcher()->suspendUpdates(false);
#endif
}
void JavascriptMidiProcessor::runScriptCallbacks()
{
if (currentEvent->isAllNotesOff())
{
synthObject->handleNoteCounter(*currentEvent);
// All notes off are controller message, so they should not be processed, or it can lead to loop.
currentMidiMessage->onAllNotesOff();
return;
}
#if ENABLE_SCRIPTING_BREAKPOINTS
breakpointWasHit(-1);
#endif
scriptEngine->maximumExecutionTime = isDeferred() ? RelativeTime(0.5) : RelativeTime(0.03);
synthObject->handleNoteCounter(*currentEvent);
switch (currentEvent->getType())
{
case HiseEvent::Type::NoteOn:
{
if (onNoteOnCallback->isSnippetEmpty()) return;
scriptEngine->executeCallback(onNoteOn, &lastResult);
BACKEND_ONLY(if (!lastResult.wasOk()) debugError(this, lastResult.getErrorMessage()));
break;
}
case HiseEvent::Type::NoteOff:
{
if (onNoteOffCallback->isSnippetEmpty()) return;
scriptEngine->executeCallback(onNoteOff, &lastResult);
BACKEND_ONLY(if (!lastResult.wasOk()) debugError(this, lastResult.getErrorMessage()));
break;
}
case HiseEvent::Type::Controller:
case HiseEvent::Type::PitchBend:
case HiseEvent::Type::Aftertouch:
case HiseEvent::Type::ProgramChange:
{
if (currentEvent->isControllerOfType(64))
{
synthObject->setSustainPedal(currentEvent->getControllerValue() > 64);
}
if (onControllerCallback->isSnippetEmpty()) return;
Result r = Result::ok();
scriptEngine->executeCallback(onController, &lastResult);
BACKEND_ONLY(if (!lastResult.wasOk()) debugError(this, lastResult.getErrorMessage()));
break;
}
case HiseEvent::Type::TimerEvent:
{
if (!currentEvent->isIgnored() && currentEvent->getChannel() == getIndexInChain())
{
runTimerCallback(currentEvent->getTimeStamp());
currentEvent->ignoreEvent(true);
}
break;
}
case HiseEvent::Type::AllNotesOff:
{
break;
}
case HiseEvent::Type::Empty:
case HiseEvent::Type::SongPosition:
case HiseEvent::Type::MidiStart:
case HiseEvent::Type::MidiStop:
case HiseEvent::Type::VolumeFade:
case HiseEvent::Type::PitchFade:
case HiseEvent::Type::numTypes:
break;
}
#if 0
else if (currentEvent->isSongPositionPointer())
{
Result r = Result::ok();
static const Identifier onClock("onClock");
var args = currentEvent->getSongPositionPointerMidiBeat();
scriptEngine->callInlineFunction(onClock, &args, 1, &r);
//scriptEngine->executeWithoutAllocation(onClock, var::NativeFunctionArgs(dynamic_cast<ReferenceCountedObject*>(this), args, 1), &r);
if (!r.wasOk()) debugError(this, r.getErrorMessage());
}
else if (currentEvent->isMidiStart() || currentEvent->isMidiStop())
{
Result r = Result::ok();
static const Identifier onTransport("onTransport");
var args = currentEvent->isMidiStart();
scriptEngine->callInlineFunction(onTransport, &args, 1, &r);
//scriptEngine->executeWithoutAllocation(onClock, var::NativeFunctionArgs(dynamic_cast<ReferenceCountedObject*>(this), args, 1), &r);
}
#endif
}
void JavascriptMidiProcessor::runTimerCallback(int /*offsetInBuffer*//*=-1*/)
{
if (isBypassed() || onTimerCallback->isSnippetEmpty()) return;
scriptEngine->maximumExecutionTime = isDeferred() ? RelativeTime(0.5) : RelativeTime(0.002);
if (lastResult.failed()) return;
scriptEngine->executeCallback(onTimer, &lastResult);
if (isDeferred())
{
sendSynchronousChangeMessage();
}
BACKEND_ONLY(if (!lastResult.wasOk()) debugError(this, lastResult.getErrorMessage()));
}
void JavascriptMidiProcessor::deferCallbacks(bool addToFront_)
{
deferred = addToFront_;
if (deferred)
{
getOwnerSynth()->stopSynthTimer(getIndexInChain());
}
else
{
stopTimer();
}
};
StringArray JavascriptMidiProcessor::getImageFileNames() const
{
jassert(isFront());
StringArray fileNames;
for (int i = 0; i < content->getNumComponents(); i++)
{
const ScriptingApi::Content::ScriptImage *image = dynamic_cast<const ScriptingApi::Content::ScriptImage*>(content->getComponent(i));
if (image != nullptr) fileNames.add(image->getScriptObjectProperty(ScriptingApi::Content::ScriptImage::FileName));
}
return fileNames;
}
JavascriptPolyphonicEffect::JavascriptPolyphonicEffect(MainController *mc, const String &id, int numVoices):
JavascriptProcessor(mc),
ProcessorWithScriptingContent(mc),
VoiceEffectProcessor(mc, id, numVoices),
onInitCallback(new SnippetDocument("onInit")),
onControlCallback(new SnippetDocument("onControl"))
{
initContent();
finaliseModChains();
editorStateIdentifiers.add("contentShown");
editorStateIdentifiers.add("onInitOpen");
editorStateIdentifiers.add("onControlOpen");
editorStateIdentifiers.add("externalPopupShown");
}
JavascriptPolyphonicEffect::~JavascriptPolyphonicEffect()
{
clearExternalWindows();
cleanupEngine();
#if USE_BACKEND
if (consoleEnabled)
{
getMainController()->setWatchedScriptProcessor(nullptr, nullptr);
}
#endif
}
juce::Path JavascriptPolyphonicEffect::getSpecialSymbol() const
{
Path path; path.loadPathFromData(HiBinaryData::SpecialSymbols::scriptProcessor, sizeof(HiBinaryData::SpecialSymbols::scriptProcessor)); return path;
}
hise::ProcessorEditorBody * JavascriptPolyphonicEffect::createEditor(ProcessorEditor *parentEditor)
{
#if USE_BACKEND
return new ScriptingEditor(parentEditor);
#else
ignoreUnused(parentEditor);
jassertfalse;
return nullptr;
#endif
}
hise::JavascriptProcessor::SnippetDocument * JavascriptPolyphonicEffect::getSnippet(int c)
{
Callback ca = (Callback)c;
switch (ca)
{
case Callback::onInit: return onInitCallback;
case Callback::onControl: return onControlCallback;
case Callback::numCallbacks: return nullptr;
default:
break;
}
return nullptr;
}
const hise::JavascriptProcessor::SnippetDocument * JavascriptPolyphonicEffect::getSnippet(int c) const
{
Callback ca = (Callback)c;
switch (ca)
{
case Callback::onInit: return onInitCallback;
case Callback::onControl: return onControlCallback;
case Callback::numCallbacks: return nullptr;
default:
break;
}
return nullptr;
}
void JavascriptPolyphonicEffect::registerApiClasses()
{
engineObject = new ScriptingApi::Engine(this);
scriptEngine->registerNativeObject("Content", content.get());
scriptEngine->registerApiClass(engineObject);
scriptEngine->registerApiClass(new ScriptingApi::Console(this));
scriptEngine->registerApiClass(new ScriptingApi::Settings(this));
scriptEngine->registerApiClass(new ScriptingApi::FileSystem(this));
scriptEngine->registerNativeObject("Libraries", new DspFactory::LibraryLoader(this));
scriptEngine->registerNativeObject("Buffer", new VariantBuffer::Factory(64));
}
void JavascriptPolyphonicEffect::postCompileCallback()
{
prepareToPlay(getSampleRate(), getLargestBlockSize());
}
void JavascriptPolyphonicEffect::prepareToPlay(double sampleRate, int samplesPerBlock)
{
VoiceEffectProcessor::prepareToPlay(sampleRate, samplesPerBlock);
if (sampleRate == -1.0)
return;
if (auto n = getActiveNetwork())
{
auto numChannels = dynamic_cast<RoutableProcessor*>(getParentProcessor(true))->getMatrix().getNumSourceChannels();
n->setNumChannels(numChannels);
n->prepareToPlay(sampleRate, (double)samplesPerBlock);
}
}
void JavascriptPolyphonicEffect::renderVoice(int voiceIndex, AudioSampleBuffer &b, int startSample, int numSamples)
{
if (auto n = getActiveNetwork())
{
float* channels[NUM_MAX_CHANNELS];
int numChannels = b.getNumChannels();
memcpy(channels, b.getArrayOfWritePointers(), sizeof(float*) * numChannels);
for (int i = 0; i < numChannels; i++)
channels[i] += startSample;
scriptnode::ProcessDataDyn d(channels, numSamples, numChannels);
scriptnode::DspNetwork::VoiceSetter vs(*n, voiceIndex);
n->getRootNode()->process(d);
}
}
void JavascriptPolyphonicEffect::startVoice(int voiceIndex, const HiseEvent& e)
{
if (auto n = getActiveNetwork())
{
voiceData.startVoice(*n, *n->getPolyHandler(), voiceIndex, e);
}
}
void JavascriptPolyphonicEffect::reset(int voiceIndex)
{
voiceData.reset(voiceIndex);
}
void JavascriptPolyphonicEffect::handleHiseEvent(const HiseEvent &m)
{
if (m.isNoteOn())
return;
HiseEvent c(m);
if (auto n = getActiveNetwork())
{
voiceData.handleHiseEvent(*n, *n->getPolyHandler(), m);
}
}
JavascriptMasterEffect::JavascriptMasterEffect(MainController *mc, const String &id):
JavascriptProcessor(mc),
ProcessorWithScriptingContent(mc),
MasterEffectProcessor(mc, id),
onInitCallback(new SnippetDocument("onInit")),
prepareToPlayCallback(new SnippetDocument("prepareToPlay", "sampleRate blockSize")),
processBlockCallback(new SnippetDocument("processBlock", "channels")),
onControlCallback(new SnippetDocument("onControl", "number value"))
{
initContent();
finaliseModChains();
editorStateIdentifiers.add("contentShown");
editorStateIdentifiers.add("onInitOpen");
editorStateIdentifiers.add("prepareToPlayOpen");
editorStateIdentifiers.add("processBlockOpen");
editorStateIdentifiers.add("onControlOpen");
editorStateIdentifiers.add("externalPopupShown");
getMatrix().setNumAllowedConnections(NUM_MAX_CHANNELS);
for (int i = 0; i < NUM_MAX_CHANNELS; i++)
{
buffers[i] = new VariantBuffer(0);
}
channels.ensureStorageAllocated(16);
channelIndexes.ensureStorageAllocated(16);
channelData = var(channels);
connectionChanged();
}
JavascriptMasterEffect::~JavascriptMasterEffect()
{
clearExternalWindows();
cleanupEngine();
#if USE_BACKEND
if (consoleEnabled)
{
getMainController()->setWatchedScriptProcessor(nullptr, nullptr);
}
#endif
}
Path JavascriptMasterEffect::getSpecialSymbol() const
{
Path path; path.loadPathFromData(HiBinaryData::SpecialSymbols::scriptProcessor, sizeof(HiBinaryData::SpecialSymbols::scriptProcessor)); return path;
}
void JavascriptMasterEffect::connectionChanged()
{
channels.clear();
channelIndexes.clear();
for (int i = 0; i < getMatrix().getNumSourceChannels(); i++)
{
if (getMatrix().getConnectionForSourceChannel(i) >= 0)
{
channels.add(buffers[channelIndexes.size()]);
channelIndexes.add(i);
}
}
auto numChannels = channels.size();
for (auto n : networks)
{
n->setNumChannels(numChannels);
}
channelData = var(channels);
}
ProcessorEditorBody * JavascriptMasterEffect::createEditor(ProcessorEditor *parentEditor)
{
#if USE_BACKEND
return new ScriptingEditor(parentEditor);
#else
ignoreUnused(parentEditor);
jassertfalse;
return nullptr;
#endif
}
JavascriptProcessor::SnippetDocument * JavascriptMasterEffect::getSnippet(int c)
{
Callback ca = (Callback)c;
switch (ca)
{
case Callback::onInit: return onInitCallback;
case Callback::prepareToPlay: return prepareToPlayCallback;
case Callback::processBlock: return processBlockCallback;
case Callback::onControl: return onControlCallback;
case Callback::numCallbacks: return nullptr;
default:
break;
}
return nullptr;
}
const JavascriptProcessor::SnippetDocument * JavascriptMasterEffect::getSnippet(int c) const
{
Callback ca = (Callback)c;
switch (ca)
{
case Callback::onInit: return onInitCallback;
case Callback::prepareToPlay: return prepareToPlayCallback;
case Callback::processBlock: return processBlockCallback;
case Callback::onControl: return onControlCallback;
case Callback::numCallbacks: return nullptr;
default:
break;
}
return nullptr;
}
void JavascriptMasterEffect::registerApiClasses()
{
//content = new ScriptingApi::Content(this);
engineObject = new ScriptingApi::Engine(this);
scriptEngine->registerNativeObject("Content", content.get());
scriptEngine->registerApiClass(engineObject);
scriptEngine->registerApiClass(new ScriptingApi::Console(this));
scriptEngine->registerApiClass(new ScriptingApi::Settings(this));
scriptEngine->registerApiClass(new ScriptingApi::FileSystem(this));
scriptEngine->registerNativeObject("Libraries", new DspFactory::LibraryLoader(this));
scriptEngine->registerNativeObject("Buffer", new VariantBuffer::Factory(64));
}
void JavascriptMasterEffect::postCompileCallback()
{
prepareToPlay(getSampleRate(), getLargestBlockSize());
}
void JavascriptMasterEffect::voicesKilled()
{
if (auto n = getActiveNetwork())
{
n->reset();
}
}
bool JavascriptMasterEffect::hasTail() const
{
if (auto n = getActiveNetwork())
{
return n->hasTail();
}
return false;
}
void JavascriptMasterEffect::prepareToPlay(double sampleRate, int samplesPerBlock)
{
MasterEffectProcessor::prepareToPlay(sampleRate, samplesPerBlock);
connectionChanged();
if (getActiveNetwork() != nullptr)
getActiveNetwork()->prepareToPlay(sampleRate, samplesPerBlock);
if (!prepareToPlayCallback->isSnippetEmpty() && lastResult.wasOk())
{
scriptEngine->setCallbackParameter((int)Callback::prepareToPlay, 0, sampleRate);
scriptEngine->setCallbackParameter((int)Callback::prepareToPlay, 1, samplesPerBlock);
scriptEngine->executeCallback((int)Callback::prepareToPlay, &lastResult);
BACKEND_ONLY(if (!lastResult.wasOk()) debugError(this, lastResult.getErrorMessage()));
}
}
void JavascriptMasterEffect::renderWholeBuffer(AudioSampleBuffer &buffer)
{
if (channelIndexes.size() == 2)
{
MasterEffectProcessor::renderWholeBuffer(buffer);
}
else
{
if (getActiveNetwork() != nullptr)
{
getActiveNetwork()->process(buffer, eventBuffer);
return;
}
if (!processBlockCallback->isSnippetEmpty() && lastResult.wasOk())
{
const int numSamples = buffer.getNumSamples();
jassert(channelIndexes.size() == channels.size());
for (int i = 0; i < channelIndexes.size(); i++)
{
float* d = buffer.getWritePointer(channelIndexes[i], 0);
CHECK_AND_LOG_BUFFER_DATA(this, DebugLogger::Location::ScriptFXRendering, d, true, numSamples);
auto b = channels[i].getBuffer();
if (b != nullptr)
b->referToData(d, numSamples);
}
scriptEngine->setCallbackParameter((int)Callback::processBlock, 0, channelData);
scriptEngine->executeCallback((int)Callback::processBlock, &lastResult);
BACKEND_ONLY(if (!lastResult.wasOk()) debugError(this, lastResult.getErrorMessage()));
}
}
}
void JavascriptMasterEffect::applyEffect(AudioSampleBuffer &b, int startSample, int numSamples)
{
ignoreUnused(startSample);
if (getActiveNetwork() != nullptr)
{
getActiveNetwork()->process(b, eventBuffer);
return;
}
if (!processBlockCallback->isSnippetEmpty() && lastResult.wasOk())
{
jassert(startSample == 0);
CHECK_AND_LOG_ASSERTION(this, DebugLogger::Location::ScriptFXRendering, startSample == 0, startSample);
float *l = b.getWritePointer(0, 0);
float *r = b.getWritePointer(1, 0);
if (auto lb = channels[0].getBuffer())
lb->referToData(l, numSamples);
if (auto rb = channels[1].getBuffer())
rb->referToData(r, numSamples);
scriptEngine->setCallbackParameter((int)Callback::processBlock, 0, channelData);
scriptEngine->executeCallback((int)Callback::processBlock, &lastResult);
BACKEND_ONLY(if (!lastResult.wasOk()) debugError(this, lastResult.getErrorMessage()));
}
}
void JavascriptMasterEffect::setBypassed(bool shouldBeBypassed, NotificationType notifyChangeHandler) noexcept
{
MasterEffectProcessor::setBypassed(shouldBeBypassed, notifyChangeHandler);
if (!shouldBeBypassed)
{
if (auto n = getActiveNetwork())
{
n->reset();
}
}
}
JavascriptVoiceStartModulator::JavascriptVoiceStartModulator(MainController *mc, const String &id, int voiceAmount, Modulation::Mode m) :
JavascriptProcessor(mc),
ProcessorWithScriptingContent(mc),
VoiceStartModulator(mc, id, voiceAmount, m),
Modulation(m)
{
initContent();
onInitCallback = new SnippetDocument("onInit");
onVoiceStartCallback = new SnippetDocument("onVoiceStart", "voiceIndex");
onVoiceStopCallback = new SnippetDocument("onVoiceStop", "voiceIndex");
onControllerCallback = new SnippetDocument("onController");
onControlCallback = new SnippetDocument("onControl", "number value");
editorStateIdentifiers.add("contentShown");
editorStateIdentifiers.add("onInitOpen");
editorStateIdentifiers.add("onVoiceStartOpen");
editorStateIdentifiers.add("onVoiceStopOpen");
editorStateIdentifiers.add("onControllerOpen");
editorStateIdentifiers.add("onControlOpen");
editorStateIdentifiers.add("externalPopupShown");
}
JavascriptVoiceStartModulator::~JavascriptVoiceStartModulator()
{
clearExternalWindows();
cleanupEngine();
#if USE_BACKEND
if (consoleEnabled)
{
getMainController()->setWatchedScriptProcessor(nullptr, nullptr);
}
#endif
}
Path JavascriptVoiceStartModulator::getSpecialSymbol() const
{
Path path; path.loadPathFromData(HiBinaryData::SpecialSymbols::scriptProcessor, sizeof(HiBinaryData::SpecialSymbols::scriptProcessor)); return path;
}
ProcessorEditorBody * JavascriptVoiceStartModulator::createEditor(ProcessorEditor *parentEditor)
{
#if USE_BACKEND
return new ScriptingEditor(parentEditor);
#else
ignoreUnused(parentEditor);
jassertfalse;
return nullptr;
#endif
}
void JavascriptVoiceStartModulator::handleHiseEvent(const HiseEvent& m)
{
currentMidiMessage->setHiseEvent(m);
synthObject->handleNoteCounter(m);
if (m.isNoteOff())
{
if (!onVoiceStopCallback->isSnippetEmpty())
{
scriptEngine->setCallbackParameter(onVoiceStop, 0, 0);
scriptEngine->executeCallback(onVoiceStop, &lastResult);
BACKEND_ONLY(if (!lastResult.wasOk()) debugError(this, lastResult.getErrorMessage()));
}
}
else if (m.isController() && !onControllerCallback->isSnippetEmpty())
{
scriptEngine->executeCallback(onController, &lastResult);
BACKEND_ONLY(if (!lastResult.wasOk()) debugError(this, lastResult.getErrorMessage()));
}
}
float JavascriptVoiceStartModulator::startVoice(int voiceIndex)
{
if (!onVoiceStartCallback->isSnippetEmpty())
{
synthObject->setVoiceGainValue(voiceIndex, 1.0f);
synthObject->setVoicePitchValue(voiceIndex, 1.0f);
scriptEngine->setCallbackParameter(onVoiceStart, 0, voiceIndex);
unsavedValue = (float)scriptEngine->executeCallback(onVoiceStart, &lastResult);
}
return VoiceStartModulator::startVoice(voiceIndex);
}
JavascriptProcessor::SnippetDocument * JavascriptVoiceStartModulator::getSnippet(int c)
{
switch (c)
{
case Callback::onInit: return onInitCallback;
case Callback::onVoiceStart: return onVoiceStartCallback;
case Callback::onVoiceStop: return onVoiceStopCallback;
case Callback::onController: return onControllerCallback;
case Callback::onControl: return onControlCallback;
}
return nullptr;
}
const JavascriptProcessor::SnippetDocument * JavascriptVoiceStartModulator::getSnippet(int c) const
{
switch (c)
{
case Callback::onInit: return onInitCallback;
case Callback::onVoiceStart: return onVoiceStartCallback;
case Callback::onVoiceStop: return onVoiceStopCallback;
case Callback::onController: return onControllerCallback;
case Callback::onControl: return onControlCallback;
}
return nullptr;
}
void JavascriptVoiceStartModulator::registerApiClasses()
{
currentMidiMessage = new ScriptingApi::Message(this);
engineObject = new ScriptingApi::Engine(this);
synthObject = new ScriptingApi::Synth(this, currentMidiMessage.get(), dynamic_cast<ModulatorSynth*>(ProcessorHelpers::findParentProcessor(this, true)));
scriptEngine->registerNativeObject("Content", content.get());
scriptEngine->registerApiClass(currentMidiMessage.get());
scriptEngine->registerApiClass(engineObject.get());
scriptEngine->registerApiClass(new ScriptingApi::Console(this));
scriptEngine->registerApiClass(new ScriptingApi::ModulatorApi(this));
scriptEngine->registerApiClass(synthObject);
}
JavascriptTimeVariantModulator::JavascriptTimeVariantModulator(MainController *mc, const String &id, Modulation::Mode m) :
TimeVariantModulator(mc, id, m),
Modulation(m),
JavascriptProcessor(mc),
ProcessorWithScriptingContent(mc),
buffer(new VariantBuffer(0))
{
initContent();
onInitCallback = new SnippetDocument("onInit");
prepareToPlayCallback = new SnippetDocument("prepareToPlay", "sampleRate samplesPerBlock");
processBlockCallback = new SnippetDocument("processBlock", "buffer");
onNoteOnCallback = new SnippetDocument("onNoteOn");
onNoteOffCallback = new SnippetDocument("onNoteOff");
onControllerCallback = new SnippetDocument("onController");
onControlCallback = new SnippetDocument("onControl", "number value");
editorStateIdentifiers.add("contentShown");
editorStateIdentifiers.add("onInitOpen");
editorStateIdentifiers.add("prepareToPlayOpen");
editorStateIdentifiers.add("processBlockOpen");
editorStateIdentifiers.add("onNoteOnOpen");
editorStateIdentifiers.add("onNoteOffOpen");
editorStateIdentifiers.add("onControllerOpen");
editorStateIdentifiers.add("onControlOpen");
editorStateIdentifiers.add("externalPopupShown");
}
JavascriptTimeVariantModulator::~JavascriptTimeVariantModulator()
{
clearExternalWindows();
cleanupEngine();
onInitCallback = new SnippetDocument("onInit");
prepareToPlayCallback = new SnippetDocument("prepareToPlay", "sampleRate samplesPerBlock");
processBlockCallback = new SnippetDocument("processBlock", "buffer");
onNoteOnCallback = new SnippetDocument("onNoteOn");
onNoteOffCallback = new SnippetDocument("onNoteOff");
onControllerCallback = new SnippetDocument("onController");
onControlCallback = new SnippetDocument("onControl", "number value");
bufferVar = var::undefined();
buffer = nullptr;
#if USE_BACKEND
if (consoleEnabled)
{
getMainController()->setWatchedScriptProcessor(nullptr, nullptr);
}
#endif
}
Path JavascriptTimeVariantModulator::getSpecialSymbol() const
{
Path path; path.loadPathFromData(HiBinaryData::SpecialSymbols::scriptProcessor, sizeof(HiBinaryData::SpecialSymbols::scriptProcessor)); return path;
}
ProcessorEditorBody * JavascriptTimeVariantModulator::createEditor(ProcessorEditor *parentEditor)
{
#if USE_BACKEND
return new ScriptingEditor(parentEditor);
#else
ignoreUnused(parentEditor);
jassertfalse;
return nullptr;
#endif
}
void JavascriptTimeVariantModulator::handleHiseEvent(const HiseEvent &m)
{
if (auto n = getActiveNetwork())
{
HiseEvent c(m);
n->getRootNode()->handleHiseEvent(c);
}
currentMidiMessage->setHiseEvent(m);
synthObject->handleNoteCounter(m);
if (m.isNoteOn())
{
if (!onNoteOnCallback->isSnippetEmpty())
scriptEngine->executeCallback(onNoteOn, &lastResult);
BACKEND_ONLY(if (!lastResult.wasOk()) debugError(this, lastResult.getErrorMessage()));
}
else if (m.isNoteOff())
{
if (!onNoteOffCallback->isSnippetEmpty())
scriptEngine->executeCallback(onNoteOff, &lastResult);
BACKEND_ONLY(if (!lastResult.wasOk()) debugError(this, lastResult.getErrorMessage()));
}
else if (m.isController() && !onControllerCallback->isSnippetEmpty())
{
scriptEngine->executeCallback(onController, &lastResult);
BACKEND_ONLY(if (!lastResult.wasOk()) debugError(this, lastResult.getErrorMessage()));
}
}
void JavascriptTimeVariantModulator::prepareToPlay(double sampleRate, int samplesPerBlock)
{
TimeVariantModulator::prepareToPlay(sampleRate, samplesPerBlock);
if (auto n = getActiveNetwork())
{
n->prepareToPlay(getControlRate(), samplesPerBlock / HISE_EVENT_RASTER);
n->setNumChannels(1);
}
if(internalBuffer.getNumChannels() > 0)
buffer->referToData(internalBuffer.getWritePointer(0), samplesPerBlock);
bufferVar = var(buffer.get());
if (!prepareToPlayCallback->isSnippetEmpty())
{
scriptEngine->setCallbackParameter(Callback::prepare, 0, sampleRate);
scriptEngine->setCallbackParameter(Callback::prepare, 1, samplesPerBlock);
scriptEngine->executeCallback(Callback::prepare, &lastResult);
BACKEND_ONLY(if (!lastResult.wasOk()) debugError(this, lastResult.getErrorMessage()));
}
}
void JavascriptTimeVariantModulator::calculateBlock(int startSample, int numSamples)
{
if (auto n = getActiveNetwork())
{
auto ptr = internalBuffer.getWritePointer(0, startSample);
FloatVectorOperations::clear(ptr, numSamples);
snex::Types::ProcessDataDyn d(&ptr, numSamples, 1);
if (auto s = SimpleReadWriteLock::ScopedTryReadLock(n->getConnectionLock()))
{
if(n->getExceptionHandler().isOk())
n->getRootNode()->process(d);
}
FloatVectorOperations::clip(ptr, ptr, 0.0f, 1.0f, numSamples);
}
else if (!processBlockCallback->isSnippetEmpty() && lastResult.wasOk())
{
buffer->referToData(internalBuffer.getWritePointer(0, startSample), numSamples);
scriptEngine->setCallbackParameter(Callback::processBlock, 0, bufferVar);
scriptEngine->executeCallback(Callback::processBlock, &lastResult);
BACKEND_ONLY(if (!lastResult.wasOk()) debugError(this, lastResult.getErrorMessage()));
}
#if ENABLE_ALL_PEAK_METERS
setOutputValue(internalBuffer.getSample(0, startSample));
#endif
}
JavascriptProcessor::SnippetDocument* JavascriptTimeVariantModulator::getSnippet(int c)
{
switch (c)
{
case Callback::onInit: return onInitCallback;
case Callback::prepare: return prepareToPlayCallback;
case Callback::processBlock: return processBlockCallback;
case Callback::onNoteOn: return onNoteOnCallback;
case Callback::onNoteOff: return onNoteOffCallback;
case Callback::onController: return onControllerCallback;
case Callback::onControl: return onControlCallback;
}
return nullptr;
}
const JavascriptProcessor::SnippetDocument * JavascriptTimeVariantModulator::getSnippet(int c) const
{
switch (c)
{
case Callback::onInit: return onInitCallback;
case Callback::prepare: return prepareToPlayCallback;
case Callback::processBlock: return processBlockCallback;
case Callback::onNoteOn: return onNoteOnCallback;
case Callback::onNoteOff: return onNoteOffCallback;
case Callback::onController: return onControllerCallback;
case Callback::onControl: return onControlCallback;
}
return nullptr;
}
void JavascriptTimeVariantModulator::registerApiClasses()
{
currentMidiMessage = new ScriptingApi::Message(this);
engineObject = new ScriptingApi::Engine(this);
synthObject = new ScriptingApi::Synth(this, currentMidiMessage.get(), dynamic_cast<ModulatorSynth*>(ProcessorHelpers::findParentProcessor(this, true)));
scriptEngine->registerNativeObject("Content", content.get());
scriptEngine->registerApiClass(currentMidiMessage.get());
scriptEngine->registerApiClass(engineObject.get());
scriptEngine->registerApiClass(new ScriptingApi::Console(this));
scriptEngine->registerApiClass(new ScriptingApi::ModulatorApi(this));
scriptEngine->registerApiClass(synthObject);
scriptEngine->registerNativeObject("Libraries", new DspFactory::LibraryLoader(this));
scriptEngine->registerNativeObject("Buffer", new VariantBuffer::Factory(64));
}
void JavascriptTimeVariantModulator::postCompileCallback()
{
prepareToPlay(getSampleRate(), getLargestBlockSize());
}
JavascriptEnvelopeModulator::JavascriptEnvelopeModulator(MainController *mc, const String &id, int numVoices, Modulation::Mode m):
ProcessorWithScriptingContent(mc),
JavascriptProcessor(mc),
EnvelopeModulator(mc, id, numVoices, m),
Modulation(m)
{
setVoiceKillerToUse(this);
initContent();
onInitCallback = new SnippetDocument("onInit");
onControlCallback = new SnippetDocument("onControl", "number value");
for (int i = 0; i < polyManager.getVoiceAmount(); i++) states.add(createSubclassedState(i));
editorStateIdentifiers.add("contentShown");
editorStateIdentifiers.add("onInitOpen");
editorStateIdentifiers.add("onControlOpen");
editorStateIdentifiers.add("externalPopupShown");
}
JavascriptEnvelopeModulator::~JavascriptEnvelopeModulator()
{
cleanupEngine();
clearExternalWindows();
}
Path JavascriptEnvelopeModulator::getSpecialSymbol() const
{
Path path; path.loadPathFromData(HiBinaryData::SpecialSymbols::scriptProcessor, sizeof(HiBinaryData::SpecialSymbols::scriptProcessor)); return path;
}
int JavascriptEnvelopeModulator::getNumActiveVoices() const
{
int counter = 0;
for (int i = 0; i < polyManager.getVoiceAmount(); i++)
{
if (auto ses = static_cast<ScriptEnvelopeState*>(states[i]))
{
if (ses->isPlaying)
counter++;
}
}
return counter;
}
ProcessorEditorBody * JavascriptEnvelopeModulator::createEditor(ProcessorEditor *parentEditor)
{
#if USE_BACKEND
return new ScriptingEditor(parentEditor);
#else
ignoreUnused(parentEditor);
jassertfalse;
return nullptr;
#endif
}
void JavascriptEnvelopeModulator::handleHiseEvent(const HiseEvent &m)
{
currentMidiMessage->setHiseEvent(m);
if (m.isNoteOn())
lastNoteOn = m;
if (auto n = getActiveNetwork())
{
voiceData.handleHiseEvent(*n, *n->getPolyHandler(), m);
}
}
void JavascriptEnvelopeModulator::prepareToPlay(double sampleRate, int samplesPerBlock)
{
EnvelopeModulator::prepareToPlay(sampleRate, samplesPerBlock);
if (auto n = getActiveNetwork())
{
n->prepareToPlay(getControlRate(), samplesPerBlock / HISE_EVENT_RASTER);
n->setNumChannels(1);
}
}
void JavascriptEnvelopeModulator::calculateBlock(int startSample, int numSamples)
{
if (auto n = getActiveNetwork())
{
scriptnode::DspNetwork::VoiceSetter vs(*n, polyManager.getCurrentVoice());
float* ptr = internalBuffer.getWritePointer(0, startSample);
memset(ptr, 0, sizeof(float)*numSamples);
scriptnode::ProcessDataDyn d(&ptr, numSamples, 1);
if (auto s = SimpleReadWriteLock::ScopedTryReadLock(n->getConnectionLock()))
{
if(n->getExceptionHandler().isOk())
n->getRootNode()->process(d);
}
}
#if ENABLE_ALL_PEAK_METERS
setOutputValue(internalBuffer.getSample(0, startSample));
#endif
}
float JavascriptEnvelopeModulator::startVoice(int voiceIndex)
{
ScriptEnvelopeState* state = static_cast<ScriptEnvelopeState*>(states[voiceIndex]);
state->uptime = 0.0f;
state->isPlaying = true;
state->isRingingOff = false;
if (auto n = getActiveNetwork())
{
voiceData.startVoice(*n, *n->getPolyHandler(), voiceIndex, lastNoteOn);
}
return 0.0f;
}
void JavascriptEnvelopeModulator::stopVoice(int voiceIndex)
{
ScriptEnvelopeState* state = static_cast<ScriptEnvelopeState*>(states[voiceIndex]);
state->isRingingOff = true;
}
void JavascriptEnvelopeModulator::reset(int voiceIndex)
{
ScriptEnvelopeState* state = static_cast<ScriptEnvelopeState*>(states[voiceIndex]);
state->uptime = 0.0f;
state->isPlaying = false;
state->isRingingOff = false;
voiceData.reset(voiceIndex);
}
bool JavascriptEnvelopeModulator::isPlaying(int voiceIndex) const
{
ScriptEnvelopeState* state = static_cast<ScriptEnvelopeState*>(states[voiceIndex]);
return state->isPlaying;
}
JavascriptProcessor::SnippetDocument * JavascriptEnvelopeModulator::getSnippet(int c)
{
Callback cb = (Callback)c;
switch (cb)
{
case JavascriptEnvelopeModulator::onInit: return onInitCallback;
case JavascriptEnvelopeModulator::onControl: return onControlCallback;
case JavascriptEnvelopeModulator::numCallbacks:
default:
break;
}
jassertfalse;
return nullptr;
}
const JavascriptProcessor::SnippetDocument * JavascriptEnvelopeModulator::getSnippet(int c) const
{
Callback cb = (Callback)c;
switch (cb)
{
case JavascriptEnvelopeModulator::onInit: return onInitCallback;
case JavascriptEnvelopeModulator::onControl: return onControlCallback;
case JavascriptEnvelopeModulator::numCallbacks:
default:
break;
}
jassertfalse;
return nullptr;
}
void JavascriptEnvelopeModulator::registerApiClasses()
{
currentMidiMessage = new ScriptingApi::Message(this);
engineObject = new ScriptingApi::Engine(this);
synthObject = new ScriptingApi::Synth(this, currentMidiMessage.get(), dynamic_cast<ModulatorSynth*>(ProcessorHelpers::findParentProcessor(this, true)));
scriptEngine->registerNativeObject("Content", content.get());
scriptEngine->registerApiClass(currentMidiMessage.get());
scriptEngine->registerApiClass(engineObject.get());
scriptEngine->registerApiClass(new ScriptingApi::Console(this));
scriptEngine->registerApiClass(new ScriptingApi::ModulatorApi(this));
scriptEngine->registerApiClass(new ScriptingApi::Settings(this));
scriptEngine->registerApiClass(new ScriptingApi::FileSystem(this));
scriptEngine->registerApiClass(synthObject);
scriptEngine->registerNativeObject("Libraries", new DspFactory::LibraryLoader(this));
scriptEngine->registerNativeObject("Buffer", new VariantBuffer::Factory(64));
}
void JavascriptEnvelopeModulator::postCompileCallback()
{
prepareToPlay(getSampleRate(), getLargestBlockSize());
}
JavascriptSynthesiser::JavascriptSynthesiser(MainController *mc, const String &id, int numVoices):
JavascriptProcessor(mc),
ProcessorWithScriptingContent(mc),
ModulatorSynth(mc, id, numVoices)
{
initContent();
onInitCallback = new SnippetDocument("onInit");
onControlCallback = new SnippetDocument("onControl", "number value");
editorStateIdentifiers.add("contentShown");
editorStateIdentifiers.add("onInitOpen");
editorStateIdentifiers.add("onControlOpen");
modChains += { this, "Extra1" };
modChains += { this, "Extra2" };
finaliseModChains();
modChains[Extra1].setIncludeMonophonicValuesInVoiceRendering(true);
modChains[Extra1].setExpandToAudioRate(false);
modChains[Extra2].setIncludeMonophonicValuesInVoiceRendering(true);
modChains[Extra2].setExpandToAudioRate(false);
modChains[Extra1].getChain()->setColour(Colour(0xFF888888));
modChains[Extra2].getChain()->setColour(Colour(0xFF888888));
for (int i = 0; i < numVoices; i++)
{
addVoice(new Voice(this));
}
addSound(new Sound());
}
JavascriptSynthesiser::~JavascriptSynthesiser()
{
}
juce::Path JavascriptSynthesiser::getSpecialSymbol() const
{
Path path; path.loadPathFromData(HiBinaryData::SpecialSymbols::scriptProcessor, sizeof(HiBinaryData::SpecialSymbols::scriptProcessor)); return path;
}
hise::ProcessorEditorBody * JavascriptSynthesiser::createEditor(ProcessorEditor *parentEditor)
{
#if USE_BACKEND
return new ScriptingEditor(parentEditor);
#else
ignoreUnused(parentEditor);
jassertfalse;
return nullptr;
#endif
}
hise::JavascriptProcessor::SnippetDocument * JavascriptSynthesiser::getSnippet(int c)
{
Callback ca = (Callback)c;
switch (ca)
{
case Callback::onInit: return onInitCallback;
case Callback::onControl: return onControlCallback;
case Callback::numCallbacks: return nullptr;
default:
break;
}
return nullptr;
}
const hise::JavascriptProcessor::SnippetDocument * JavascriptSynthesiser::getSnippet(int c) const
{
Callback ca = (Callback)c;
switch (ca)
{
case Callback::onInit: return onInitCallback;
case Callback::onControl: return onControlCallback;
case Callback::numCallbacks: return nullptr;
default:
break;
}
return nullptr;
}
void JavascriptSynthesiser::registerApiClasses()
{
engineObject = new ScriptingApi::Engine(this);
scriptEngine->registerNativeObject("Content", content.get());
scriptEngine->registerApiClass(engineObject);
scriptEngine->registerApiClass(new ScriptingApi::Console(this));
scriptEngine->registerApiClass(new ScriptingApi::Settings(this));
scriptEngine->registerApiClass(new ScriptingApi::FileSystem(this));
scriptEngine->registerNativeObject("Libraries", new DspFactory::LibraryLoader(this));
scriptEngine->registerNativeObject("Buffer", new VariantBuffer::Factory(64));
}
void JavascriptSynthesiser::postCompileCallback()
{
prepareToPlay(getSampleRate(), getLargestBlockSize());
}
void JavascriptSynthesiser::preHiseEventCallback(HiseEvent &e)
{
ModulatorSynth::preHiseEventCallback(e);
if (e.isNoteOn())
return; // will be handled by preStartVoice
if (auto n = getActiveNetwork())
{
voiceData.handleHiseEvent(*n, *n->getPolyHandler(), e);
}
}
void JavascriptSynthesiser::preStartVoice(int voiceIndex, const HiseEvent& e)
{
ModulatorSynth::preStartVoice(voiceIndex, e);
if (auto n = getActiveNetwork())
{
static_cast<Voice*>(getVoice(voiceIndex))->setVoiceStartDataForNextRenderCallback();
currentVoiceStartSample = jlimit(0, getLargestBlockSize(), e.getTimeStamp());
}
}
void JavascriptSynthesiser::prepareToPlay(double newSampleRate, int samplesPerBlock)
{
ModulatorSynth::prepareToPlay(newSampleRate, samplesPerBlock);
if (newSampleRate == -1.0)
return;
if (auto n = getActiveNetwork())
{
if (auto vk = ProcessorHelpers::getFirstProcessorWithType<ScriptnodeVoiceKiller>(gainChain))
setVoiceKillerToUse(vk);
n->prepareToPlay(newSampleRate, (double)samplesPerBlock);
n->setNumChannels(getMatrix().getNumSourceChannels());
}
}
void JavascriptSynthesiser::restoreFromValueTree(const ValueTree &v)
{
ModulatorSynth::restoreFromValueTree(v);
if (auto vk = ProcessorHelpers::getFirstProcessorWithType<ScriptnodeVoiceKiller>(gainChain))
setVoiceKillerToUse(vk);
restoreScript(v);
restoreContent(v);
}
void JavascriptSynthesiser::Voice::calculateBlock(int startSample, int numSamples)
{
if (auto n = synth->getActiveNetwork())
{
if (isVoiceStart)
{
n->setVoiceKiller(synth->vk);
synth->voiceData.startVoice(*n, *n->getPolyHandler(), getVoiceIndex(), getCurrentHiseEvent());
isVoiceStart = false;
}
float* channels[NUM_MAX_CHANNELS];
voiceBuffer.clear();
int numChannels = voiceBuffer.getNumChannels();
memcpy(channels, voiceBuffer.getArrayOfWritePointers(), sizeof(float*) * numChannels);
for (int i = 0; i < numChannels; i++)
channels[i] += startSample;
scriptnode::ProcessDataDyn d(channels, numSamples, numChannels);
{
scriptnode::DspNetwork::VoiceSetter vs(*n, getVoiceIndex());
n->process(d);
}
if (auto modValues = getOwnerSynth()->getVoiceGainValues())
{
for(int i = 0; i < voiceBuffer.getNumChannels(); i++)
FloatVectorOperations::multiply(voiceBuffer.getWritePointer(i, startSample), modValues + startSample, numSamples);
}
else
{
const float gainValue = getOwnerSynth()->getConstantGainModValue();
for (int i = 0; i < voiceBuffer.getNumChannels(); i++)
FloatVectorOperations::multiply(voiceBuffer.getWritePointer(i, startSample), gainValue, numSamples);
}
getOwnerSynth()->effectChain->renderVoice(voiceIndex, voiceBuffer, startSample, numSamples);
}
}
hise::ProcessorEditorBody * ScriptnodeVoiceKiller::createEditor(ProcessorEditor *parentEditor)
{
#if USE_BACKEND
return new EmptyProcessorEditorBody(parentEditor);;
#else
ignoreUnused(parentEditor);
return nullptr;
#endif
}
void VoiceDataStack::reset(int voiceIndex)
{
for (int i = 0; i < voiceNoteOns.size(); i++)
{
if (voiceNoteOns[i].voiceIndex == voiceIndex)
{
voiceNoteOns.removeElement(i--);
break;
}
}
}
} // namespace hise
| 28.248466 | 154 | 0.738473 | Matt-Dub |
f65649ca1352400cf3cc53daee9b4085b521cf68 | 572 | cpp | C++ | hackerrank/non-divisible-subset/solution.cpp | SamProkopchuk/coding-problems | fa0ca2c05ac90e41945de1a5751e5545a8459ac4 | [
"MIT"
] | null | null | null | hackerrank/non-divisible-subset/solution.cpp | SamProkopchuk/coding-problems | fa0ca2c05ac90e41945de1a5751e5545a8459ac4 | [
"MIT"
] | null | null | null | hackerrank/non-divisible-subset/solution.cpp | SamProkopchuk/coding-problems | fa0ca2c05ac90e41945de1a5751e5545a8459ac4 | [
"MIT"
] | null | null | null | #include <iostream>
#include <unordered_map>
using namespace std;
int main() {
int n, mod, temp, res;
cin >> n >> mod;
unordered_map<int, int> remcount;
for (int posrem = 0; posrem < mod; posrem++) {
// Simple defaultdict-like behavior
remcount[posrem] = 0;
}
for (int c = 0; c < n; c++) {
cin >> temp;
remcount[temp % mod] += 1;
}
res = (remcount[0] > 0) + (mod % 2 == 0 && remcount[mod / 2]);
for (int rem = 1; rem < (mod + 1) / 2; rem++) {
res += max(remcount[rem], remcount[mod - rem]);
}
cout << res << endl;
return 0;
}
| 22.88 | 64 | 0.547203 | SamProkopchuk |
f657235d328c6925462f7c4b577082034446ce78 | 1,758 | cc | C++ | tsdf_plusplus/src/core/segment.cc | TheMangalex/tsdf-plusplus | aefb7fa40b53475ce424d5082b3045587bbb5de3 | [
"MIT"
] | 91 | 2021-05-18T03:15:18.000Z | 2022-03-28T01:53:02.000Z | tsdf_plusplus/src/core/segment.cc | ali-robot/tsdf-plusplus | 602f2aeec267a82ac3c5d88ef3eabba2ea2f3c04 | [
"MIT"
] | 4 | 2021-05-18T06:10:20.000Z | 2022-01-25T11:38:33.000Z | tsdf_plusplus/src/core/segment.cc | cmrobotics/tsdf-plusplus | 9cb15273b2bd5e7b13f67ef563856d2f92cd34dd | [
"MIT"
] | 16 | 2021-05-18T02:17:48.000Z | 2022-03-07T02:57:01.000Z | // Copyright (c) 2020- Margarita Grinvald, Autonomous Systems Lab, ETH Zurich
// Licensed under the MIT License (see LICENSE for details)
#include "tsdf_plusplus/core/segment.h"
#include <pcl/common/centroid.h>
Segment::Segment(const pcl::PointCloud<InputPointType>& pointcloud_pcl,
const voxblox::Transformation& T_G_C)
: T_G_C_(T_G_C), semantic_class_(pointcloud_pcl.points[0].semantic_class) {
pointcloud_ = pointcloud_pcl;
convertPointcloud();
}
Segment::Segment(const pcl::PointCloud<GTInputPointType>& pointcloud_pcl,
const voxblox::Transformation& T_G_C)
: T_G_C_(T_G_C),
object_id_(pointcloud_pcl.points[0].label + 1),
semantic_class_(BackgroundClass) {
pcl::copyPointCloud(pointcloud_pcl, pointcloud_);
convertPointcloud();
}
void Segment::convertPointcloud() {
points_C_.clear();
colors_.clear();
points_C_.reserve(pointcloud_.points.size());
colors_.reserve(pointcloud_.points.size());
for (size_t i = 0u; i < pointcloud_.points.size(); ++i) {
if (!std::isfinite(pointcloud_.points[i].x) ||
!std::isfinite(pointcloud_.points[i].y) ||
!std::isfinite(pointcloud_.points[i].z)) {
continue;
}
points_C_.push_back(voxblox::Point(pointcloud_.points[i].x,
pointcloud_.points[i].y,
pointcloud_.points[i].z));
colors_.push_back(
voxblox::Color(pointcloud_.points[i].r, pointcloud_.points[i].g,
pointcloud_.points[i].b, pointcloud_.points[i].a));
}
Eigen::Vector4f centroid_c;
pcl::compute3DCentroid(pointcloud_, centroid_c);
centroid_ =
T_G_C_ * voxblox::Point(centroid_c.x(), centroid_c.y(), centroid_c.z());
}
| 33.169811 | 79 | 0.661547 | TheMangalex |
f65767d98e7cbc5ab4836a02bd29a882e9f2f24a | 183 | cpp | C++ | src/GameOptions.cpp | ceilingfans/pnut-butta | d2f5d6f1f1379b4324d2b58edf102e30a6b792cb | [
"MIT"
] | null | null | null | src/GameOptions.cpp | ceilingfans/pnut-butta | d2f5d6f1f1379b4324d2b58edf102e30a6b792cb | [
"MIT"
] | null | null | null | src/GameOptions.cpp | ceilingfans/pnut-butta | d2f5d6f1f1379b4324d2b58edf102e30a6b792cb | [
"MIT"
] | null | null | null | #include "GameOptions.hpp"
bool isValidOption(const GameOptions& opt)
{
return opt.playerCount > 0 && opt.substringLength >= 2 && !opt.options.empty() && opt.options.size() >= 2;
} | 30.5 | 108 | 0.693989 | ceilingfans |
f658eb874ea759e96055caee9956cd764bbd35c7 | 3,889 | cpp | C++ | Libraries/xcassets/Sources/Asset/CubeTextureSet.cpp | djgalloway/xcbuild | 936df10e59e5f5d531efca8bd48e445d88e78e0c | [
"BSD-2-Clause-NetBSD"
] | 9 | 2018-04-30T23:18:27.000Z | 2021-06-20T15:13:38.000Z | Libraries/xcassets/Sources/Asset/CubeTextureSet.cpp | djgalloway/xcbuild | 936df10e59e5f5d531efca8bd48e445d88e78e0c | [
"BSD-2-Clause-NetBSD"
] | null | null | null | Libraries/xcassets/Sources/Asset/CubeTextureSet.cpp | djgalloway/xcbuild | 936df10e59e5f5d531efca8bd48e445d88e78e0c | [
"BSD-2-Clause-NetBSD"
] | 4 | 2018-10-10T19:44:17.000Z | 2020-01-12T11:56:31.000Z | /**
Copyright (c) 2015-present, Facebook, Inc.
All rights reserved.
This source code is licensed under the BSD-style license found in the
LICENSE file in the root directory of this source tree. An additional grant
of patent rights can be found in the PATENTS file in the same directory.
*/
#include <xcassets/Asset/CubeTextureSet.h>
#include <plist/Array.h>
#include <plist/Dictionary.h>
#include <plist/String.h>
#include <plist/Keys/Unpack.h>
using xcassets::Asset::CubeTextureSet;
bool CubeTextureSet::Texture::
parse(plist::Dictionary const *dict)
{
std::unordered_set<std::string> seen;
auto unpack = plist::Keys::Unpack("CubeTextureSetTexture", dict, &seen);
auto CS = unpack.cast <plist::String> ("color-space");
auto CF = unpack.cast <plist::String> ("cube-face");
auto F = unpack.cast <plist::String> ("filename");
auto GFS = unpack.cast <plist::String> ("graphics-feature-set");
auto I = unpack.cast <plist::String> ("idiom");
auto M = unpack.cast <plist::String> ("memory");
auto PF = unpack.cast <plist::String> ("pixel-format");
auto S = unpack.cast <plist::String> ("scale");
if (!unpack.complete(true)) {
fprintf(stderr, "%s", unpack.errorText().c_str());
}
if (CS != nullptr) {
_colorSpace = Slot::ColorSpaces::Parse(CS->value());
}
if (CF != nullptr) {
_cubeFace = CubeFaces::Parse(CF->value());
}
if (F != nullptr) {
_fileName = F->value();
}
if (GFS != nullptr) {
_graphicsFeatureSet = Slot::GraphicsFeatureSets::Parse(GFS->value());
}
if (I != nullptr) {
_idiom = Slot::Idioms::Parse(I->value());
}
if (M != nullptr) {
_memory = Slot::MemoryRequirements::Parse(M->value());
}
if (PF != nullptr) {
_pixelFormat = TexturePixelFormats::Parse(PF->value());
}
if (S != nullptr) {
_scale = Slot::Scale::Parse(S->value());
}
return true;
}
bool CubeTextureSet::
parse(plist::Dictionary const *dict, std::unordered_set<std::string> *seen, bool check)
{
if (!Asset::parse(dict, seen, false)) {
return false;
}
auto unpack = plist::Keys::Unpack("CubeTextureSet", dict, seen);
auto P = unpack.cast <plist::Dictionary> ("properties");
auto Ts = unpack.cast <plist::Array> ("textures");
if (!unpack.complete(check)) {
fprintf(stderr, "%s", unpack.errorText().c_str());
}
if (P != nullptr) {
std::unordered_set<std::string> seen;
auto unpack = plist::Keys::Unpack("Properties", P, &seen);
auto I = unpack.cast <plist::String> ("interpretation");
auto O = unpack.cast <plist::String> ("origin");
auto ODRT = unpack.cast <plist::Array> ("on-demand-resource-tags");
if (!unpack.complete(true)) {
fprintf(stderr, "%s", unpack.errorText().c_str());
}
if (I != nullptr) {
_interpretation = TextureInterpretations::Parse(I->value());
}
if (O != nullptr) {
_origin = TextureOrigins::Parse(O->value());
}
if (ODRT != nullptr) {
_onDemandResourceTags = std::vector<std::string>();
_onDemandResourceTags->reserve(ODRT->count());
for (size_t n = 0; n < ODRT->count(); n++) {
if (auto string = ODRT->value<plist::String>(n)) {
_onDemandResourceTags->push_back(string->value());
}
}
}
}
if (Ts != nullptr) {
_textures = std::vector<Texture>();
for (size_t n = 0; n < Ts->count(); ++n) {
if (auto dict = Ts->value<plist::Dictionary>(n)) {
Texture texture;
if (texture.parse(dict)) {
_textures->push_back(texture);
}
}
}
}
return true;
}
| 28.807407 | 87 | 0.568527 | djgalloway |
f65967a614d415e3dd4256e6d33476b1d14e53de | 2,729 | hpp | C++ | include/tudocomp/compressors/MTFCompressor.hpp | dominiKoeppl/tudocomp | b5512f85f6b3408fb88e19c08899ec4c2716c642 | [
"ECL-2.0",
"Apache-2.0"
] | 17 | 2017-03-04T13:04:49.000Z | 2021-12-03T06:58:20.000Z | include/tudocomp/compressors/MTFCompressor.hpp | dominiKoeppl/tudocomp | b5512f85f6b3408fb88e19c08899ec4c2716c642 | [
"ECL-2.0",
"Apache-2.0"
] | 27 | 2016-01-22T18:31:37.000Z | 2021-11-27T10:50:40.000Z | include/tudocomp/compressors/MTFCompressor.hpp | dominiKoeppl/tudocomp | b5512f85f6b3408fb88e19c08899ec4c2716c642 | [
"ECL-2.0",
"Apache-2.0"
] | 16 | 2017-03-14T12:46:51.000Z | 2021-06-25T18:19:50.000Z | #pragma once
#include <tudocomp/util.hpp>
#include <tudocomp/Compressor.hpp>
#include <tudocomp/Env.hpp>
#include <numeric>
#include <tudocomp/def.hpp>
namespace tdc {
/**
* Encodes a character 'v' by Move-To-Front Coding
* Needs and modifies a lookup table storing the last-used characters
*/
template<class value_type = uliteral_t>
value_type mtf_encode_char(const value_type v, value_type*const table, const size_t table_size) {
for(size_t i = 0; i < table_size; ++i) {
if(table[i] == v) {
for(size_t j = i; j > 0; --j) {
table[j] = table[j-1];
}
table[0] = v;
return i;
}
}
DCHECK(false) << v << "(" << static_cast<size_t>(static_cast<typename std::make_unsigned<value_type>::type>(v)) << " not in " << arr_to_debug_string(table,table_size);
return 0;
}
/**
* Decodes a character encoded as 'v' by Move-To-Front Coding
* Needs and modifies a lookup table storing the last-used characters
*/
template<class value_type = uliteral_t>
value_type mtf_decode_char(const value_type v, value_type*const table) {
const value_type return_value = table[v];
for(size_t j = v; j > 0; --j) {
table[j] = table[j-1];
}
table[0] = return_value;
return return_value;
}
template<class char_type = uliteral_t>
void mtf_encode(std::basic_istream<char_type>& is, std::basic_ostream<char_type>& os) {
typedef typename std::make_unsigned<char_type>::type value_type; // -> default: uint8_t
static constexpr size_t table_size = std::numeric_limits<value_type>::max()+1;
value_type table[table_size];
std::iota(table, table+table_size, 0);
char_type c;
while(is.get(c)) {
os << mtf_encode_char(static_cast<value_type>(c), table, table_size);
}
}
template<class char_type = uliteral_t>
void mtf_decode(std::basic_istream<char_type>& is, std::basic_ostream<char_type>& os) {
typedef typename std::make_unsigned<char_type>::type value_type; // -> default: uint8_t
static constexpr size_t table_size = std::numeric_limits<value_type>::max()+1;
value_type table[table_size];
std::iota(table, table+table_size, 0);
char_type c;
while(is.get(c)) {
os << mtf_decode_char(static_cast<value_type>(c), table);
}
}
class MTFCompressor : public Compressor {
public:
inline static Meta meta() {
Meta m("compressor", "mtf", "Move To Front Compressor");
return m;
}
inline MTFCompressor(Env&& env)
: Compressor(std::move(env)) {
}
inline virtual void compress(Input& input, Output& output) override {
auto is = input.as_stream();
auto os = output.as_stream();
mtf_encode(is,os);
}
inline virtual void decompress(Input& input, Output& output) override {
auto is = input.as_stream();
auto os = output.as_stream();
mtf_decode(is,os);
}
};
}//ns
| 28.427083 | 168 | 0.698791 | dominiKoeppl |
2cf243e0ff44f73c7888a0199c24ba62cea38e16 | 3,101 | cpp | C++ | src/thunderbots/software/ai/hl/stp/evaluation/calc_best_shot.cpp | FSXAC/Software | 3754f5ec2c513906f66a05d4399aca516d03ba9f | [
"MIT"
] | null | null | null | src/thunderbots/software/ai/hl/stp/evaluation/calc_best_shot.cpp | FSXAC/Software | 3754f5ec2c513906f66a05d4399aca516d03ba9f | [
"MIT"
] | null | null | null | src/thunderbots/software/ai/hl/stp/evaluation/calc_best_shot.cpp | FSXAC/Software | 3754f5ec2c513906f66a05d4399aca516d03ba9f | [
"MIT"
] | null | null | null | #include "ai/hl/stp/evaluation/calc_best_shot.h"
#include "geom/util.h"
namespace Evaluation
{
std::pair<Point, Angle> calcBestShotOnEnemyGoal(const Field &f,
const std::vector<Point> &obstacles,
const Point &p, double radius)
{
// Calculate the location of goalpost then use angleSweepCircle function to get
// the pair
const Point p1 = f.enemyGoalpostNeg();
const Point p2 = f.enemyGoalpostPos();
return angleSweepCircles(p, p1, p2, obstacles, radius);
}
std::vector<std::pair<Point, Angle>> calcBestShotOnEnemyGoalAll(
const Field &f, const std::vector<Point> &obstacles, const Point &p,
double radius)
{
const Point p1 = f.enemyGoalpostNeg();
const Point p2 = f.enemyGoalpostPos();
return angleSweepCirclesAll(p, p1, p2, obstacles, radius);
}
std::pair<Point, Angle> calcBestShotOnEnemyGoal(const World &world,
const Point &point, double radius)
{
std::vector<Point> obstacles;
const Team &enemy = world.enemyTeam();
const Team &friendly = world.friendlyTeam();
obstacles.reserve(enemy.numRobots() + friendly.numRobots());
// create a vector of points for all the robots except the shooting one
for (const Robot &i : enemy.getAllRobots())
{
obstacles.emplace_back(i.position());
}
for (const Robot &fpl : friendly.getAllRobots())
{
if (fpl.position() == point)
{
continue;
}
obstacles.emplace_back(fpl.position());
}
std::pair<Point, Angle> best_shot =
calcBestShotOnEnemyGoal(world.field(), obstacles, point, radius);
// if there is no good shot at least make the
// target within the goal area
if (best_shot.second == Angle::zero())
{
Point temp = world.field().enemyGoal();
best_shot.first = temp;
}
return best_shot;
}
std::vector<std::pair<Point, Angle>> calcBestShotOnEnemyGoalAll(const World &world,
const Point &point,
double radius)
{
std::vector<Point> obstacles;
const Team &enemy = world.enemyTeam();
const Team &friendly = world.friendlyTeam();
obstacles.reserve(enemy.numRobots() + friendly.numRobots());
for (const Robot &i : enemy.getAllRobots())
{
obstacles.push_back(i.position());
}
for (const Robot &fpl : friendly.getAllRobots())
{
if (fpl.position() == point)
{
continue;
}
obstacles.push_back(fpl.position());
}
return calcBestShotOnEnemyGoalAll(world.field(), obstacles, point, radius);
}
} // namespace Evaluation
| 37.361446 | 88 | 0.538858 | FSXAC |
2cf3c08183e51e9c16b5bc6a416df1032a818c7e | 98 | cpp | C++ | core/utilities.cpp | evias/web-irc-docbot | ffc05223eb580a363188dc361938d23b141c6091 | [
"BSD-3-Clause"
] | 1 | 2021-08-28T01:42:34.000Z | 2021-08-28T01:42:34.000Z | core/utilities.cpp | evias/web-irc-docbot | ffc05223eb580a363188dc361938d23b141c6091 | [
"BSD-3-Clause"
] | null | null | null | core/utilities.cpp | evias/web-irc-docbot | ffc05223eb580a363188dc361938d23b141c6091 | [
"BSD-3-Clause"
] | 1 | 2015-03-24T15:45:04.000Z | 2015-03-24T15:45:04.000Z | #include "utilities.hpp"
using namespace std;
using namespace evias;
using namespace utilities;
| 14 | 26 | 0.795918 | evias |
2cfe0fd3dda379a720e73736d58c1f0a8eb56baf | 103 | cpp | C++ | src/uniform-initialization-too-few-initializers.cpp | zzlc/cxx11tests | d471b3f8b96548c762be6b7e410abe56a57811ae | [
"MIT"
] | 48 | 2015-01-06T20:50:45.000Z | 2021-02-15T02:48:32.000Z | src/uniform-initialization-too-few-initializers.cpp | zzlc/cxx11tests | d471b3f8b96548c762be6b7e410abe56a57811ae | [
"MIT"
] | 3 | 2016-01-19T15:02:19.000Z | 2019-04-29T08:51:13.000Z | src/uniform-initialization-too-few-initializers.cpp | zzlc/cxx11tests | d471b3f8b96548c762be6b7e410abe56a57811ae | [
"MIT"
] | 24 | 2015-02-13T17:40:04.000Z | 2019-12-03T06:59:03.000Z | // Check if too few initializers are supported
struct Point3D {
int x, y, z;
};
Point3D p = {1, 2};
| 14.714286 | 46 | 0.640777 | zzlc |
2cfe6152d781ead5b251bb4a0c32fc277b8a1c1b | 965 | cpp | C++ | oli/vii2018puzzle/main.cpp | rockoanna/nirvana | 81fadbe66b0a24244feec312c6f7fe5c8effccaa | [
"MIT"
] | null | null | null | oli/vii2018puzzle/main.cpp | rockoanna/nirvana | 81fadbe66b0a24244feec312c6f7fe5c8effccaa | [
"MIT"
] | 12 | 2019-09-04T10:38:24.000Z | 2019-12-08T18:09:41.000Z | oli/vii2018puzzle/main.cpp | rockoanna/nirvana | 81fadbe66b0a24244feec312c6f7fe5c8effccaa | [
"MIT"
] | null | null | null | #include <iostream>
#include <vector>
using namespace std;
int main()
{
int n;
cin >> n;
vector<int> pieces(n);
for(int i = 0; i < n; i++)
{
cin >> pieces[i];
}
int res = 0;
for(int i = 0; i < n - 1; i++)
{
for(int j = i + 1; j < n; j++)
{
bool ok = true;
int nr1 = pieces[i];
int nr2 = pieces[j];
int x = nr1 % 10 + nr2 % 10;
nr1 = nr1 / 10;
nr2 = nr2 / 10;
while(nr1 != 0)
{
if(nr1 % 10 + nr2 % 10 == x)
{
nr1 = nr1 / 10;
nr2 = nr2 / 10;
}
else
{
ok = false;
break;
}
}
if(ok == true)
{
res += 1;
}
}
}
cout << res << endl;
return 0;
}
| 16.929825 | 44 | 0.288083 | rockoanna |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.