hexsha
stringlengths
40
40
size
int64
7
1.05M
ext
stringclasses
13 values
lang
stringclasses
1 value
max_stars_repo_path
stringlengths
4
269
max_stars_repo_name
stringlengths
5
108
max_stars_repo_head_hexsha
stringlengths
40
40
max_stars_repo_licenses
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
67k
max_issues_repo_issues_event_min_datetime
stringlengths
24
24
max_issues_repo_issues_event_max_datetime
stringlengths
24
24
max_forks_repo_path
stringlengths
4
269
max_forks_repo_name
stringlengths
5
116
max_forks_repo_head_hexsha
stringlengths
40
40
max_forks_repo_licenses
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
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 <lorenz@4z2.de> * * 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
c45ee3716591668e7b603a33eb3bd334e2661b35
5,348
cpp
C++
lib/src/platform/linux/user_accounting_database.cpp
jasonivey/mmotd
dfde0e37e1515dd9c47ce2af25d1631c01a44773
[ "MIT" ]
null
null
null
lib/src/platform/linux/user_accounting_database.cpp
jasonivey/mmotd
dfde0e37e1515dd9c47ce2af25d1631c01a44773
[ "MIT" ]
49
2020-10-30T09:26:11.000Z
2022-03-21T04:40:06.000Z
lib/src/platform/linux/user_accounting_database.cpp
jasonivey/mmotd
dfde0e37e1515dd9c47ce2af25d1631c01a44773
[ "MIT" ]
null
null
null
// vim: awa:sts=4:ts=4:sw=4:et:cin:fdm=manual:tw=120:ft=cpp #if defined(__linux__) #include "common/include/chrono_io.h" #include "common/include/logging.h" #include "common/include/posix_error.h" #include "lib/include/platform/user_accounting_database.h" #include <cerrno> #include <cstdio> #include <cstdlib> #include <cstring> #include <string> #include <vector> #include <boost/asio/ip/address.hpp> #include <fmt/format.h> #include <scope_guard.hpp> #include <pwd.h> #include <unistd.h> #include <utmp.h> #include <utmpx.h> using boost::asio::ip::make_address; using ip_address = boost::asio::ip::address; namespace pe = mmotd::error::posix_error; using fmt::format; using namespace std; namespace { using namespace mmotd::platform::user_account_database; DbEntries GetUserAccountEntriesImpl() { // resets the database, so that the next getutxent() call will get the first entry setutxent(); // read the next entry from the database; if the database was not yet open, it also opens it auto utmp_buf = utmp{}; utmp *utmp_ptr = nullptr; auto retval = getutent_r(&utmp_buf, &utmp_ptr); if (retval != 0 || utmp_ptr == nullptr) { auto error_str = retval != 0 ? pe::to_string(retval) : pe::to_string(); LOG_ERROR("attempting to read first value in user accounting database (utmp) and failed, {}", error_str); return DbEntries{}; } // auto close the database however we leave this function auto endutxent_closer = sg::make_scope_guard([]() noexcept { endutxent(); }); auto user_account_entries = DbEntries{}; size_t i = 0; while (utmp_ptr != nullptr) { auto ut_type_str = DbEntry::entry_type_to_string(utmp_ptr->ut_type); LOG_VERBOSE("iteration #{}, type: {}, utmpx *: {}", ++i, ut_type_str, fmt::ptr(utmp_ptr)); auto entry = DbEntry::from_utmp(*utmp_ptr); if (!entry.empty()) { user_account_entries.push_back(entry); LOG_VERBOSE("adding user account entry #{}", user_account_entries.size()); } // read the next entry from the database memset(&utmp_buf, 0, sizeof(utmp)); utmp_ptr = nullptr; retval = getutent_r(&utmp_buf, &utmp_ptr); if (retval != 0 || utmp_ptr == nullptr) { auto error_value = errno; auto error_str = pe::to_string(error_value); if (error_value == ENOENT) { LOG_VERBOSE("found the end of user accounting database (utmp), {}", error_str); } else { LOG_WARNING("attempting to read next value in user accounting database (utmp) and failed, {}", error_str); } utmp_ptr = nullptr; } } LOG_VERBOSE("returning {} user account entries", user_account_entries.size()); return user_account_entries; } } // namespace namespace mmotd::platform::user_account_database { string DbEntry::to_string() const { auto time_point = std::chrono::system_clock::from_time_t(seconds); auto time_str = mmotd::chrono::io::to_string(time_point, "%d-%h-%Y %I:%M%p %Z"); return format(FMT_STRING("user: {}, device: {}, hostname: {}, time: {}, ip: {}, type: {}"), user, device_name, hostname, time_str, ip.to_string(), DbEntry::entry_type_to_string(static_cast<int>(type))); } DbEntry DbEntry::from_utmp(const utmp &db) { if (db.ut_type != USER_PROCESS && db.ut_type != LOGIN_PROCESS) { return DbEntry{}; } auto device_name = strlen(db.ut_line) > 0 ? string{db.ut_line} : string{}; auto username = strlen(db.ut_user) > 0 ? string{db.ut_user} : string{}; auto hostname = strlen(db.ut_host) > 0 ? string{db.ut_host} : string{}; auto buffer = vector<char>(sizeof(db.ut_addr_v6), 0); memcpy(data(buffer), db.ut_addr_v6, size(buffer)); auto ec = boost::system::error_code{}; auto ip = make_address(data(buffer), ec); if (ec) { ip = ip_address{}; } auto entry = DbEntry{static_cast<ENTRY_TYPE>(db.ut_type), device_name, username, hostname, db.ut_tv.tv_sec, ip}; LOG_VERBOSE("parsed entry: {}", entry.to_string()); return entry; } string DbEntry::entry_type_to_string(int ut_type) { static_assert(ENTRY_TYPE::None == static_cast<ENTRY_TYPE>(EMPTY)); static_assert(ENTRY_TYPE::Login == static_cast<ENTRY_TYPE>(LOGIN_PROCESS)); static_assert(ENTRY_TYPE::User == static_cast<ENTRY_TYPE>(USER_PROCESS)); switch (ut_type) { case EMPTY: return "empty"; case RUN_LVL: return "run lvl"; case BOOT_TIME: return "boot time"; case OLD_TIME: return "old time"; case NEW_TIME: return "new time"; case INIT_PROCESS: return "init process"; case LOGIN_PROCESS: return "login process"; case USER_PROCESS: return "user process"; case DEAD_PROCESS: return "dead process"; default: return "unknown"; } } const DbEntries &detail::GetUserAccountEntries() { static const auto &user_account_entries = GetUserAccountEntriesImpl(); return user_account_entries; } } // namespace mmotd::platform::user_account_database #endif
34.503226
116
0.631264
jasonivey
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
c47171f2c1440e31b553a7d616ac860c2d1647e9
1,840
cc
C++
content/browser/ssl/ssl_host_state.cc
Crystalnix/BitPop
1fae4ecfb965e163f6ce154b3988b3181678742a
[ "BSD-3-Clause" ]
7
2015-05-20T22:41:35.000Z
2021-11-18T19:07:59.000Z
content/browser/ssl/ssl_host_state.cc
quisquous/chromium
b25660e05cddc9d0c3053b3514f07037acc69a10
[ "BSD-3-Clause" ]
1
2015-02-02T06:55:08.000Z
2016-01-20T06:11:59.000Z
content/browser/ssl/ssl_host_state.cc
quisquous/chromium
b25660e05cddc9d0c3053b3514f07037acc69a10
[ "BSD-3-Clause" ]
2
2015-12-08T00:37:41.000Z
2017-04-06T05:34:05.000Z
// Copyright (c) 2012 The Chromium Authors. All rights reserved. // Use of this source code is governed by a BSD-style license that can be // found in the LICENSE file. #include "content/browser/ssl/ssl_host_state.h" #include "base/logging.h" #include "base/lazy_instance.h" #include "content/public/browser/browser_context.h" static const char* kKeyName = "content_ssl_host_state"; SSLHostState* SSLHostState::GetFor(content::BrowserContext* context) { SSLHostState* rv = static_cast<SSLHostState*>(context->GetUserData(kKeyName)); if (!rv) { rv = new SSLHostState(); context->SetUserData(kKeyName, rv); } return rv; } SSLHostState::SSLHostState() { } SSLHostState::~SSLHostState() { } void SSLHostState::HostRanInsecureContent(const std::string& host, int pid) { DCHECK(CalledOnValidThread()); ran_insecure_content_hosts_.insert(BrokenHostEntry(host, pid)); } bool SSLHostState::DidHostRunInsecureContent(const std::string& host, int pid) const { DCHECK(CalledOnValidThread()); return !!ran_insecure_content_hosts_.count(BrokenHostEntry(host, pid)); } void SSLHostState::DenyCertForHost(net::X509Certificate* cert, const std::string& host) { DCHECK(CalledOnValidThread()); cert_policy_for_host_[host].Deny(cert); } void SSLHostState::AllowCertForHost(net::X509Certificate* cert, const std::string& host) { DCHECK(CalledOnValidThread()); cert_policy_for_host_[host].Allow(cert); } void SSLHostState::Clear() { DCHECK(CalledOnValidThread()); cert_policy_for_host_.clear(); } net::CertPolicy::Judgment SSLHostState::QueryPolicy( net::X509Certificate* cert, const std::string& host) { DCHECK(CalledOnValidThread()); return cert_policy_for_host_[host].Check(cert); }
28.307692
80
0.707065
Crystalnix
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 '&lt;' and '&gt;' 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
c47871a5d8133a4a65f916b37349926ab5def4aa
5,139
cpp
C++
base/fs/sis/groveler/pathlist.cpp
npocmaka/Windows-Server-2003
5c6fe3db626b63a384230a1aa6b92ac416b0765f
[ "Unlicense" ]
17
2020-11-13T13:42:52.000Z
2021-09-16T09:13:13.000Z
base/fs/sis/groveler/pathlist.cpp
sancho1952007/Windows-Server-2003
5c6fe3db626b63a384230a1aa6b92ac416b0765f
[ "Unlicense" ]
2
2020-10-19T08:02:06.000Z
2020-10-19T08:23:18.000Z
base/fs/sis/groveler/pathlist.cpp
sancho1952007/Windows-Server-2003
5c6fe3db626b63a384230a1aa6b92ac416b0765f
[ "Unlicense" ]
14
2020-11-14T09:43:20.000Z
2021-08-28T08:59:57.000Z
/*++ Copyright (c) 1998 Microsoft Corporation Module Name: pathlist.cpp Abstract: SIS Groveler path list manager Authors: John Douceur, 1998 Environment: User Mode Revision History: --*/ #include "all.hxx" static const _TCHAR *paths_ini_filename = _T("grovel.ini"); static const _TCHAR *paths_ini_section = _T("Excluded Paths"); static const _TCHAR *excluded_paths_path = _T("SOFTWARE\\Microsoft\\Windows NT\\CurrentVersion\\Groveler\\Excluded Paths"); static const int default_excluded_path_count = 1; static _TCHAR *default_path_tags[default_excluded_path_count] = { _T("System Volume Information directory") }; static _TCHAR *default_excluded_paths[default_excluded_path_count] = { _T("\\System Volume Information") }; PathList::PathList() { ASSERT(this != 0); paths = 0; buffer = 0; num_partitions = sis_drives.partition_count(); num_paths = new int[num_partitions]; paths = new const _TCHAR **[num_partitions]; partition_buffers = new _TCHAR *[num_partitions]; for (int part_num = 0; part_num < num_partitions; part_num++) { num_paths[part_num] = 1; paths[part_num] = 0; partition_buffers[part_num] = 0; } int num_strings; _TCHAR **strings = 0; bool ok = Registry::read_string_set(HKEY_LOCAL_MACHINE, excluded_paths_path, &num_strings, &strings, &buffer); if (!ok) { Registry::write_string_set(HKEY_LOCAL_MACHINE, excluded_paths_path, default_excluded_path_count, default_excluded_paths, default_path_tags); num_strings = default_excluded_path_count; strings = default_excluded_paths; buffer = 0; } ASSERT(num_strings >= 0); ASSERT(strings != 0); int bLen = SIS_CSDIR_STRING_NCHARS + _tcslen(paths_ini_filename) + MAX_PATH; _TCHAR *ini_file_partition_path = new _TCHAR[bLen]; int *num_partition_strings = new int[num_partitions]; _TCHAR ***partition_strings = new _TCHAR **[num_partitions]; for (part_num = 0; part_num < num_partitions; part_num++) { partition_strings[part_num] = NULL; // // Construct the string // (void)StringCchCopy(ini_file_partition_path, bLen, sis_drives.partition_guid_name(part_num)); TrimTrailingChar(ini_file_partition_path,L'\\'); (void)StringCchCat(ini_file_partition_path, bLen, SIS_CSDIR_STRING); (void)StringCchCat(ini_file_partition_path, bLen, paths_ini_filename); IniFile::read_string_set(ini_file_partition_path, paths_ini_section, &num_partition_strings[part_num], &partition_strings[part_num], &partition_buffers[part_num]); ASSERT(num_partition_strings[part_num] >= 0); ASSERT(num_partition_strings[part_num] == 0 || partition_strings[part_num] != 0); } delete[] ini_file_partition_path; ini_file_partition_path = 0; for (part_num = 0; part_num < num_partitions; part_num++) { paths[part_num] = new const _TCHAR *[num_strings + num_partition_strings[part_num] + 1]; paths[part_num][0] = SIS_CSDIR_STRING; for (int index = 0; index < num_strings; index++) { paths[part_num][num_paths[part_num]] = strings[index]; num_paths[part_num]++; } int num_part_strings = num_partition_strings[part_num]; _TCHAR **part_strings = partition_strings[part_num]; for (index = 0; index < num_part_strings; index++) { paths[part_num][num_paths[part_num]] = part_strings[index]; num_paths[part_num]++; } if (partition_strings[part_num] != 0) { delete[] partition_strings[part_num]; partition_strings[part_num] = 0; } } ASSERT(num_partition_strings != 0); delete[] num_partition_strings; num_partition_strings = 0; ASSERT(partition_strings != 0); delete[] partition_strings; partition_strings = 0; if (buffer != 0) { ASSERT(strings != 0); ASSERT(strings != default_excluded_paths); delete[] strings; strings = 0; } } PathList::~PathList() { ASSERT(this != 0); ASSERT(num_paths != 0); ASSERT(paths != 0); ASSERT(partition_buffers != 0); ASSERT(num_partitions > 0); for (int part_num = 0; part_num < num_partitions; part_num++) { ASSERT(paths[part_num] != 0); delete[] paths[part_num]; paths[part_num] = 0; if (partition_buffers[part_num] != 0) { delete[] partition_buffers[part_num]; partition_buffers[part_num] = 0; } } delete[] paths; paths = 0; delete[] partition_buffers; partition_buffers = 0; if (buffer != 0) { delete[] buffer; buffer = 0; } ASSERT(num_paths != 0); delete[] num_paths; num_paths = 0; }
28.870787
85
0.615684
npocmaka
c47bb1b899688d92bd0727ca8cfe6e5159f48e7a
5,428
cpp
C++
emulator/src/lib/util/strformat.cpp
rjw57/tiw-computer
5ef1c79893165b8622d1114d81cd0cded58910f0
[ "MIT" ]
1
2022-01-15T21:38:38.000Z
2022-01-15T21:38:38.000Z
emulator/src/lib/util/strformat.cpp
rjw57/tiw-computer
5ef1c79893165b8622d1114d81cd0cded58910f0
[ "MIT" ]
null
null
null
emulator/src/lib/util/strformat.cpp
rjw57/tiw-computer
5ef1c79893165b8622d1114d81cd0cded58910f0
[ "MIT" ]
null
null
null
// license:BSD-3-Clause // copyright-holders:Vas Crabb /*************************************************************************** strformat.h type-safe printf substitutes ***************************************************************************/ #include "strformat.h" #include "vecstream.h" #include <iostream> #include <sstream> namespace util { namespace detail { template class format_chars<char>; template class format_chars<wchar_t>; template void format_flags::apply(std::ostream &) const; template void format_flags::apply(std::wostream &) const; template void format_flags::apply(std::iostream &) const; template void format_flags::apply(std::wiostream &) const; template void format_flags::apply(std::ostringstream &) const; template void format_flags::apply(std::wostringstream &) const; template void format_flags::apply(std::stringstream &) const; template void format_flags::apply(std::wstringstream &) const; template void format_flags::apply(ovectorstream &) const; template void format_flags::apply(wovectorstream &) const; template void format_flags::apply(vectorstream &) const; template void format_flags::apply(wvectorstream &) const; template class format_argument<std::ostream>; template class format_argument<std::wostream>; template class format_argument<std::iostream>; template class format_argument<std::wiostream>; template class format_argument<std::ostringstream>; template class format_argument<std::wostringstream>; template class format_argument<std::stringstream>; template class format_argument<std::wstringstream>; template class format_argument<ovectorstream>; template class format_argument<wovectorstream>; template class format_argument<vectorstream>; template class format_argument<wvectorstream>; template class format_argument_pack<std::ostream>; template class format_argument_pack<std::wostream>; template class format_argument_pack<std::iostream>; template class format_argument_pack<std::wiostream>; template class format_argument_pack<std::ostringstream>; template class format_argument_pack<std::wostringstream>; template class format_argument_pack<std::stringstream>; template class format_argument_pack<std::wstringstream>; template class format_argument_pack<ovectorstream>; template class format_argument_pack<wovectorstream>; template class format_argument_pack<vectorstream>; template class format_argument_pack<wvectorstream>; template std::ostream::off_type stream_format(std::ostream &, format_argument_pack<std::ostream> const &); template std::wostream::off_type stream_format(std::wostream &, format_argument_pack<std::wostream> const &); template std::iostream::off_type stream_format(std::iostream &, format_argument_pack<std::ostream> const &); template std::iostream::off_type stream_format(std::iostream &, format_argument_pack<std::iostream> const &); template std::wiostream::off_type stream_format(std::wiostream &, format_argument_pack<std::wostream> const &); template std::wiostream::off_type stream_format(std::wiostream &, format_argument_pack<std::wiostream> const &); template std::ostringstream::off_type stream_format(std::ostringstream &, format_argument_pack<std::ostream> const &); template std::ostringstream::off_type stream_format(std::ostringstream &, format_argument_pack<std::ostringstream> const &); template std::wostringstream::off_type stream_format(std::wostringstream &, format_argument_pack<std::wostream> const &); template std::wostringstream::off_type stream_format(std::wostringstream &, format_argument_pack<std::wostringstream> const &); template std::stringstream::off_type stream_format(std::stringstream &, format_argument_pack<std::ostream> const &); template std::stringstream::off_type stream_format(std::stringstream &, format_argument_pack<std::iostream> const &); template std::stringstream::off_type stream_format(std::stringstream &, format_argument_pack<std::stringstream> const &); template std::wstringstream::off_type stream_format(std::wstringstream &, format_argument_pack<std::wostream> const &); template std::wstringstream::off_type stream_format(std::wstringstream &, format_argument_pack<std::wiostream> const &); template std::wstringstream::off_type stream_format(std::wstringstream &, format_argument_pack<std::wstringstream> const &); template ovectorstream::off_type stream_format(ovectorstream &, format_argument_pack<std::ostream> const &); template ovectorstream::off_type stream_format(ovectorstream &, format_argument_pack<ovectorstream> const &); template wovectorstream::off_type stream_format(wovectorstream &, format_argument_pack<std::wostream> const &); template wovectorstream::off_type stream_format(wovectorstream &, format_argument_pack<wovectorstream> const &); template vectorstream::off_type stream_format(vectorstream &, format_argument_pack<std::ostream> const &); template vectorstream::off_type stream_format(vectorstream &, format_argument_pack<std::iostream> const &); template vectorstream::off_type stream_format(vectorstream &, format_argument_pack<vectorstream> const &); template wvectorstream::off_type stream_format(wvectorstream &, format_argument_pack<std::wostream> const &); template wvectorstream::off_type stream_format(wvectorstream &, format_argument_pack<std::wiostream> const &); template wvectorstream::off_type stream_format(wvectorstream &, format_argument_pack<wvectorstream> const &); } // namespace detail } // namespace util
57.744681
127
0.792373
rjw57
c47dd1920ebc401e7714ad43dcd2773e70a57d3d
4,424
cc
C++
DQMOffline/L1Trigger/src/L1TCommon.cc
nistefan/cmssw
ea13af97f7f2117a4f590a5e654e06ecd9825a5b
[ "Apache-2.0" ]
3
2018-08-24T19:10:26.000Z
2019-02-19T11:45:32.000Z
DQMOffline/L1Trigger/src/L1TCommon.cc
nistefan/cmssw
ea13af97f7f2117a4f590a5e654e06ecd9825a5b
[ "Apache-2.0" ]
3
2018-08-23T13:40:24.000Z
2019-12-05T21:16:03.000Z
DQMOffline/L1Trigger/src/L1TCommon.cc
nistefan/cmssw
ea13af97f7f2117a4f590a5e654e06ecd9825a5b
[ "Apache-2.0" ]
5
2018-08-21T16:37:52.000Z
2020-01-09T13:33:17.000Z
#include "DQMOffline/L1Trigger/interface/L1TCommon.h" #include "DataFormats/Math/interface/deltaR.h" #include "FWCore/MessageLogger/interface/MessageLogger.h" #include <iostream> namespace dqmoffline { namespace l1t { std::vector<unsigned int> getTriggerIndices(const std::vector<std::string> &requestedTriggers, const std::vector<std::string> &triggersInEvent) { std::vector<unsigned int> triggerIndices; for (auto requestedTriggerName : requestedTriggers) { std::string name(requestedTriggerName); std::size_t wildcarPosition = name.find("*"); if (wildcarPosition != std::string::npos) { // take everything up to the wildcard name = name.substr(0, wildcarPosition - 1); } unsigned int triggerIndex = 0; for (auto triggerName : triggersInEvent) { if (triggerName.find(name) != std::string::npos) { triggerIndices.push_back(triggerIndex); break; } ++triggerIndex; } } return triggerIndices; } std::vector<bool> getTriggerResults(const std::vector<unsigned int> &triggers, const edm::TriggerResults &triggerResults) { std::vector<bool> results; results.resize(triggers.size()); for (unsigned int index = 0; index < triggers.size(); ++index) { if (triggers[index] >= triggerResults.size()) { results[index] = false; continue; } if (triggerResults.accept(triggers[index])) { results[index] = true; } else { results[index] = false; } } return results; } std::vector<unsigned int> getFiredTriggerIndices(const std::vector<unsigned int> &triggers, const std::vector<bool> &triggerResults) { std::vector<unsigned int> results; // std::copy_if instead? for (unsigned int i = 0; i < triggerResults.size(); ++i) { if (triggerResults[i]) { results.push_back(triggers[i]); } } return results; } bool passesAnyTriggerFromList(const std::vector<unsigned int> &triggers, const edm::TriggerResults &triggerResults) { std::vector<bool> results = dqmoffline::l1t::getTriggerResults(triggers, triggerResults); if (std::count(results.begin(), results.end(), true) == 0) { return false; } return true; } trigger::TriggerObjectCollection getTriggerObjects(const std::vector<edm::InputTag> &hltFilters, const trigger::TriggerEvent &triggerEvent) { trigger::TriggerObjectCollection triggerObjects = triggerEvent.getObjects(); trigger::TriggerObjectCollection results; for (auto filter : hltFilters) { const unsigned filterIndex = triggerEvent.filterIndex(filter); if (filterIndex < triggerEvent.sizeFilters()) { const trigger::Keys triggerKeys(triggerEvent.filterKeys(filterIndex)); const size_t nTriggers = triggerEvent.filterIds(filterIndex).size(); for (size_t i = 0; i < nTriggers; ++i) { results.push_back(triggerObjects[triggerKeys[i]]); } } } // sort by ET typedef trigger::TriggerObject trigObj; std::sort(results.begin(), results.end(), [](const trigObj &obj1, const trigObj &obj2) { return obj1.et() > obj2.et(); }); return results; } std::vector<edm::InputTag> getHLTFilters(const std::vector<unsigned int> &triggers, const HLTConfigProvider &hltConfig, const std::string triggerProcess) { std::vector<edm::InputTag> results; for (auto trigger : triggers) { unsigned int hltIndexOffset(2); unsigned int moduleIndex = hltConfig.size(trigger) - hltIndexOffset; const std::vector<std::string> modules(hltConfig.moduleLabels(trigger)); std::string module(modules[moduleIndex]); edm::InputTag filterInputTag = edm::InputTag(module, "", triggerProcess); results.push_back(filterInputTag); } return results; } trigger::TriggerObjectCollection getMatchedTriggerObjects( double eta, double phi, double maxDeltaR, const trigger::TriggerObjectCollection triggerObjects) { trigger::TriggerObjectCollection results; typedef trigger::TriggerObject trigObj; std::copy_if(triggerObjects.begin(), triggerObjects.end(), std::back_inserter(results), [eta, phi, maxDeltaR](const trigObj &obj) { return deltaR(obj.eta(), obj.phi(), eta, phi) < maxDeltaR; }); return results; } } // l1t } // dqmoffline
32.529412
80
0.667043
nistefan
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
c486e90f47875c249117d6c3e1da8fb11597e22f
1,437
hpp
C++
vize/include/vize/factory/async_volume_factory.hpp
oprogramadorreal/vize
042c16f96d8790303563be6787200558e1ec00b2
[ "MIT" ]
47
2020-03-30T14:36:46.000Z
2022-03-06T07:44:54.000Z
vize/include/vize/factory/async_volume_factory.hpp
oprogramadorreal/vize
042c16f96d8790303563be6787200558e1ec00b2
[ "MIT" ]
null
null
null
vize/include/vize/factory/async_volume_factory.hpp
oprogramadorreal/vize
042c16f96d8790303563be6787200558e1ec00b2
[ "MIT" ]
8
2020-04-01T01:22:45.000Z
2022-01-02T13:06:09.000Z
#ifndef VIZE_ASYNC_VOLUME_FACTORY_HPP #define VIZE_ASYNC_VOLUME_FACTORY_HPP #include "vize/config.hpp" #include <boost/signals2.hpp> #include <vector> namespace lucca_qt { class Async; } namespace vize { class Volume; class VolumeFactory; /** * @author O Programador */ class AsyncVolumeFactory final { public: AsyncVolumeFactory(std::unique_ptr<VolumeFactory> factory); virtual ~AsyncVolumeFactory(); public: /** * Run the volume importation asynchronously. */ void run(); bool isRunning() const; void showProgressDialog(const std::string& progressDialogTitle); void addVolumeImagesDirectory(const std::string& imagesDirectory); void addVolumeImage(const std::string& imageFile); void clearVolumeImages(); public: using VolumeBuiltSignal = boost::signals2::signal<void(const std::shared_ptr<Volume>& volume, const std::string& volumeName)>; using VolumeBuiltSignalListener = VolumeBuiltSignal::slot_function_type; /** * Register a listener to be notified when a volume is created. */ boost::signals2::connection connectToVolumeBuiltSignal(const VolumeBuiltSignalListener& listener); private: void _buildVolumeFinished(); void _buildVolume(); private: const std::unique_ptr<VolumeFactory> _factory; std::unique_ptr<lucca_qt::Async> _async; std::shared_ptr<Volume> _volume; std::vector<std::string> _volumeImages; VolumeBuiltSignal _volumeBuilt; }; } #endif // VIZE_ASYNC_VOLUME_FACTORY_HPP
22.453125
127
0.776618
oprogramadorreal
c4887840eda54fb39ad0b0b401ccf2d928813001
2,945
cpp
C++
src/test_hierarchical_clustering.cpp
UM-ARM-Lab/arc_utilities
e21bd5062983b25e61e33f832ec66b937540ba10
[ "BSD-2-Clause" ]
10
2017-01-09T14:37:14.000Z
2022-03-16T08:02:08.000Z
src/test_hierarchical_clustering.cpp
UM-ARM-Lab/arc_utilities
e21bd5062983b25e61e33f832ec66b937540ba10
[ "BSD-2-Clause" ]
62
2017-05-25T16:52:38.000Z
2022-03-08T20:05:09.000Z
src/test_hierarchical_clustering.cpp
UM-ARM-Lab/arc_utilities
e21bd5062983b25e61e33f832ec66b937540ba10
[ "BSD-2-Clause" ]
7
2017-08-04T13:06:17.000Z
2022-03-16T08:02:11.000Z
#include <stdio.h> #include <stdlib.h> #include <arc_utilities/abb_irb1600_145_fk_fast.hpp> #include <arc_utilities/arc_helpers.hpp> #include <arc_utilities/eigen_helpers.hpp> #include <arc_utilities/pretty_print.hpp> #include <arc_utilities/simple_hierarchical_clustering.hpp> #include <chrono> #include <fstream> #include <iostream> #include <random> int main(int argc, char** argv) { printf("%d arguments\n", argc); for (int idx = 0; idx < argc; idx++) { printf("Argument %d: %s\n", idx, argv[idx]); } const size_t num_points = (argc >= 2) ? (size_t)(atoi(argv[1])) : 1000; std::cout << "Generating " << num_points << " random points..." << std::endl; const auto seed = std::chrono::high_resolution_clock::now().time_since_epoch().count(); std::mt19937_64 prng(seed); std::uniform_real_distribution<double> dist(0.0, 10.0); EigenHelpers::VectorVector3d random_points(num_points); std::vector<size_t> indices(num_points); for (size_t idx = 0; idx < num_points; idx++) { const double x = dist(prng); const double y = dist(prng); random_points[idx] = Eigen::Vector3d(x, y, 0.0); indices[idx] = idx; } std::cout << "Clustering " << num_points << " points..." << std::endl; std::function<double(const Eigen::Vector3d&, const Eigen::Vector3d&)> distance_fn = [](const Eigen::Vector3d& v1, const Eigen::Vector3d& v2) { return EigenHelpers::Distance(v1, v2); }; const Eigen::MatrixXd distance_matrix = arc_helpers::BuildDistanceMatrixParallel(random_points, distance_fn); const std::vector<std::vector<size_t>> clusters = simple_hierarchical_clustering::SimpleHierarchicalClustering::Cluster( indices, distance_matrix, 1.0, simple_hierarchical_clustering::COMPLETE_LINK) .first; for (size_t cluster_idx = 0; cluster_idx < clusters.size(); cluster_idx++) { const std::vector<size_t>& current_cluster = clusters[cluster_idx]; const double cluster_num = 1.0 + (double)cluster_idx; for (size_t element_idx = 0; element_idx < current_cluster.size(); element_idx++) { const size_t index = current_cluster[element_idx]; random_points[index].z() = cluster_num; } } std::cout << "Saving to CSV..." << std::endl; const std::string log_file_name = (argc >= 3) ? std::string(argv[2]) : "/tmp/test_hierarchical_clustering.csv"; std::ofstream log_file(log_file_name, std::ios_base::out); if (!log_file.is_open()) { std::cerr << "\x1b[31;1m Unable to create folder/file to log to: " << log_file_name << "\x1b[0m \n"; throw std::invalid_argument("Log filename must be write-openable"); } for (size_t idx = 0; idx < num_points; idx++) { const Eigen::Vector3d& point = random_points[idx]; log_file << point.x() << "," << point.y() << "," << point.z() << std::endl; } log_file.close(); std::cout << "Done saving, you can import into matlab and draw with \"scatter3(x, y, z, 50, z, '.')\"" << std::endl; return 0; }
46.746032
118
0.678778
UM-ARM-Lab
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
c48efe9fe55ce710f8798cae5f040f4587aa5cf1
6,387
hh
C++
src/grid.hh
lanl/libparty
ae0ee61e23f4335a820d0aee04be58944450d251
[ "Apache-2.0" ]
2
2020-03-19T08:28:37.000Z
2020-06-29T08:05:12.000Z
src/grid.hh
lanl/libparty
ae0ee61e23f4335a820d0aee04be58944450d251
[ "Apache-2.0" ]
null
null
null
src/grid.hh
lanl/libparty
ae0ee61e23f4335a820d0aee04be58944450d251
[ "Apache-2.0" ]
3
2017-06-21T20:49:57.000Z
2020-03-19T08:28:38.000Z
/* * Copyright 2014. Los Alamos National Security, LLC. This material was produced * under U.S. Government contract DE-AC52-06NA25396 for Los Alamos National * Laboratory (LANL), which is operated by Los Alamos National Security, LLC * for the U.S. Department of Energy. The U.S. Government has rights to use, * reproduce, and distribute this software. NEITHER THE GOVERNMENT NOR * LOS ALAMOS NATIONAL SECURITY, LLC MAKES ANY WARRANTY, EXPRESS OR IMPLIED, * OR ASSUMES ANY LIABILITY FOR THE USE OF THIS SOFTWARE. If software is * modified to produce derivative works, such modified software should be * clearly marked, so as not to confuse it with the version available from LANL. * * 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. * * Additionally, redistribution and use in source and binary forms, with or without * modification, are permitted provided that the following conditions are met: * * Redistributions of source code must retain the above copyright * notice, this list of conditions and the following disclaimer. * * Redistributions in binary form must reproduce the above copyright * notice, this list of conditions and the following disclaimer in the * documentation and/or other materials provided with the distribution. * * Neither the name of the Los Alamos National Security, LLC, Los Alamos * National Laboratory, LANL, the U.S. Government, nor the names of its * contributors may be used to endorse or promote products derived from * this software without specific prior written permission. * * LibParty, Version 1.x, Copyright number C114122, LA-CC-14-086 * * Authors: * Matthew Kinsey, kinsey@lanl.gov * Verinder Rana, vrana@lanl.gov * Bob Robey, XCP-2, LANL, brobey@lanl.gov * Jeremy Sauer, EES-16, LANL, jsauer@lanl.gov * Jon Reisner, XCP-4 LANL, reisner@lanl.gov */ #ifndef GRID_HH #define GRID_HH #include <iostream> class grid { public: double xmin, ymin, zmin; // double xmax, ymax, zmax; int nx, ny, nz; double xstride, ystride, zstride; // void interp(double * x, double * y, double * z, double * val, int size, double * ret); // int ind1d(int i, int j, int k); //}; int ind1d(int i, int j, int k, bool fort_order = false) { // int nx, ny; // nx = (int)(( xmax - xmin ) / xstride) + 1; // ny = (int)(( ymax - ymin ) / ystride) + 1; // nz = (int)(( zmax - zmin ) / zstride); // if(fort_order) return k + nz*j + nz*ny*i; return i + nx*j + nx*ny*k; } void interp3d(double * x, double * y, double * z, double * val, int size, double * ret, bool fort_order = false) { // int i[size], j[size], k[size]; // double x0[size], y0[size], z0[size]; // double xd[size], yd[size], zd[size]; // double c00[size], c10[size], c01[size], c11[size], c0[size], c1[size]; // for(int i = 0; i < nx; ++i) std::cout << va #pragma ivdep #pragma omp parallel for for(int n = 0; n < size; ++n) { int i = (int)(( x[n] - xmin ) / xstride); int j = (int)(( y[n] - ymin ) / ystride); int k = (int)(( z[n] - zmin ) / zstride); double x0 = (i) * xstride + xmin; double y0 = (j) * ystride + ymin; double z0 = (k) * zstride + zmin; double xd = ( x[n] - x0 ) / xstride; double yd = ( y[n] - y0 ) / ystride; double zd = ( z[n] - z0 ) / zstride; double c00 = val[ind1d(i,j,k,fort_order)] * ( 1. - xd ) + val[ind1d(i+1,j,k,fort_order)] * xd; double c10 = val[ind1d(i,j+1,k,fort_order)] * ( 1. - xd ) + val[ind1d(i+1,j+1,k,fort_order)] * xd; double c01 = val[ind1d(i,j,k+1,fort_order)] * ( 1. - xd ) + val[ind1d(i+1,j,k+1,fort_order)] * xd; double c11 = val[ind1d(i,j+1,k+1,fort_order)] * ( 1. - xd ) + val[ind1d(i+1,j+1,k+1,fort_order)] * xd; double c0 = c00 * ( 1. - yd ) + c10 * yd; double c1 = c01 * ( 1. - yd ) + c11 * yd; ret[n] = c0 * ( 1. - zd ) + c1 * zd; } } void interp2d(double * x, double * y, double * val, int size, double * ret, bool fort_order = false) { // int i[size], j[size]; // double x0[size], y0[size]; // double xd[size], yd[size]; // double c0[size], c1[size]; #pragma ivdep #pragma omp parallel for for(int n = 0; n < size; ++n) { int i = (int)(( x[n] - xmin ) / xstride); int j = (int)(( y[n] - ymin ) / ystride); double x0 = i * xstride + xmin; double y0 = j * ystride + ymin; double xd = ( x[n] - x0 ) / xstride; double yd = ( y[n] - y0 ) / ystride; double c0 = val[ind1d(i,j,0,fort_order)] * (1. - xd) + val[ind1d(i+1,j,0,fort_order)] * xd; double c1 = val[ind1d(i,j+1,0,fort_order)] * (1. - xd) + val[ind1d(i+1,j+1,0,fort_order)] * xd; ret[n] = c0 * (1. - yd) + c1 * yd; } // std::cout << ret[0] << std::endl; } }; /* i[:] = (int)(( x[0:size] - xmin ) / xstride); j[:] = (int)(( y[0:size] - ymin ) / ystride); k[:] = (int)(( z[0:size] - zmin ) / zstride); x0[:] = i[:] * xstride + xmin; y0[:] = j[:] * ystride + ymin; z0[:] = k[:] * zstride + zmin; xd[:] = ( x[0:size] - x0[:] ) / xstride; yd[:] = ( y[0:size] - y0[:] ) / ystride; zd[:] = ( z[0:size] - z0[:] ) / zstride; c00[:] = val[ind1d(i[:],j[:],k[:])] * ( 1. - xd[:] ) + val[ind1d(i[:]+1,j[:],k[:])] * xd[:]; c10[:] = val[ind1d(i[:],j[:]+1,k[:])] * ( 1. - xd[:] ) + val[ind1d(i[:]+1,j[:]+1,k[:])] * xd[:]; c01[:] = val[ind1d(i[:],j[:],k[:]+1)] * ( 1. - xd[:] ) + val[ind1d(i[:]+1,j[:],k[:]+1)] * xd[:]; c11[:] = val[ind1d(i[:],j[:]+1,k[:]+1)] * ( 1. - xd[:] ) + val[ind1d(i[:]+1,j[:]+1,k[:]+1)] * xd[:]; c0[:] = c00[:] * ( 1. - yd[:] ) + c10[:] * yd[:]; c1[:] = c01[:] * ( 1. - yd[:] ) + c11[:] * yd[:]; ret[0:size] = c0[:] * ( 1. - zd[:] ) + c1[:] * zd[:]; }*/ #endif
38.945122
114
0.567716
lanl
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
c4941f0b4f462904d7d7964e0d3545b8bf9ce5da
3,111
cpp
C++
vegastrike/src/universe_util_server.cpp
Ezeer/VegaStrike_win32FR
75891b9ccbdb95e48e15d3b4a9cd977955b97d1f
[ "MIT" ]
null
null
null
vegastrike/src/universe_util_server.cpp
Ezeer/VegaStrike_win32FR
75891b9ccbdb95e48e15d3b4a9cd977955b97d1f
[ "MIT" ]
null
null
null
vegastrike/src/universe_util_server.cpp
Ezeer/VegaStrike_win32FR
75891b9ccbdb95e48e15d3b4a9cd977955b97d1f
[ "MIT" ]
null
null
null
#include "cmd/script/mission.h" #include "universe_util.h" #include "universe_generic.h" #include "cmd/unit_generic.h" #include "cmd/unit_factory.h" //for UnitFactory::getMasterPartList() #include "cmd/collection.h" #include "networking/netserver.h" #include "star_system_generic.h" #include <string> #include "lin_time.h" #include "load_mission.h" #include "configxml.h" #include "vs_globals.h" void SetStarSystemLoading( bool value ) {} using std::string; //less to write #define activeSys _Universe->activeStarSystem() void ClientServerSetLightContext( int lc ) {} namespace UniverseUtil { void playVictoryTune() {} int musicAddList( string str ) { return 0; } void musicLayerPlaySong( string str, int layer ) {} void addParticle( QVector loc, Vector velocity, Vector color, float size ) {} void musicLayerPlayList( int which, int layer ) {} void musicLayerLoopList( int numloops, int layer ) {} void musicLayerSetSoftVolume( float vol, float latency_override, int layer ) {} void musicLayerSetHardVolume( float vol, int layer ) {} void musicSetSoftVolume( float vol, float latency_override ) {} void musicSetHardVolume( float vol ) {} void musicMute( bool stopSound ) {} void playSound( string soundName, QVector loc, Vector speed ) {} void playSoundCockpit( string soundName ) {} void cacheAnimation( string aniName ) {} void playAnimation( string aniName, QVector loc, float size ) {} void playAnimationGrow( string aniName, QVector loc, float size, float growpercent ) {} unsigned int getCurrentPlayer() { return _Universe->CurrentCockpit(); } void musicLayerSkip( int layer ) {} void musicLayerStop( int layer ) {} void StopAllSounds( void ) {} void loadGame( const string &savename ) { unsigned int num = 0; sscanf( savename.c_str(), "%u", &num ); if ( num != UINT_MAX && num < _Universe->numPlayers() ) { Unit *un = _Universe->AccessCockpit( num )->GetParent(); if (un) { un->hull = 0; un->Destroy(); } } } void saveGame( const string &savename ) { unsigned int num = 0; sscanf( savename.c_str(), "%u", &num ); if ( num != UINT_MAX && num < _Universe->numPlayers() ) { if (SERVER) VSServer->saveAccount( num ); } else if (num == 0 && SERVER) { cout<<">>> Manually Saving server status..."<<endl; VSServer->save(); cout<<"<<< Finished saving."<<endl; } } void showSplashScreen( const string &filename ) {} void showSplashMessage( const string &text ) {} void showSplashProgress( float progress ) {} void hideSplashScreen() {} bool isSplashScreenShowing() { return false; } void startMenuInterface( bool firstTime, string error ) { //Critical game error... enough to bring you back to the game menu! printf( "GAME ERROR: %s\n", error.c_str() ); } void sendCustom( int cp, string cmd, string args, string id ) { if ( cp < 0 || (unsigned int) cp >= _Universe->numPlayers() ) { fprintf( stderr, "sendCustom %s with invalid player %d\n", cmd.c_str(), cp ); return; } VSServer->sendCustom( cp, cmd, args, id ); } } #undef activeSys
29.913462
87
0.681131
Ezeer
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
7bca2dbc1ca7552e5f6978fcb64478f85881a998
110
cpp
C++
src/UIKit/UIEvent.cpp
jjzhang166/uikit-cpp-win32
6887cef72334214c00cae95a671415f0e91dd886
[ "MIT" ]
4
2015-06-05T03:06:21.000Z
2021-02-13T18:07:58.000Z
src/UIKit/UIEvent.cpp
jjzhang166/uikit-cpp-win32
6887cef72334214c00cae95a671415f0e91dd886
[ "MIT" ]
null
null
null
src/UIKit/UIEvent.cpp
jjzhang166/uikit-cpp-win32
6887cef72334214c00cae95a671415f0e91dd886
[ "MIT" ]
4
2015-06-05T03:06:22.000Z
2022-03-25T01:03:05.000Z
#include "UIEvent.h" UIEvent::UIEvent() : x(0) , y(0) , view(NULL) { } UIEvent::~UIEvent() { }
9.166667
21
0.5
jjzhang166
7bcaa7dab52e901730b34cc0f6c1d474f25ac60f
129
cc
C++
Blob_Lib/assimp-5.2.3/assimp/contrib/draco/src/draco/compression/mesh/mesh_encoder.cc
antholuo/Blob_Traffic
5d6acf88044e9abc63c0ff356714179eaa4b75bf
[ "MIT" ]
null
null
null
Blob_Lib/assimp-5.2.3/assimp/contrib/draco/src/draco/compression/mesh/mesh_encoder.cc
antholuo/Blob_Traffic
5d6acf88044e9abc63c0ff356714179eaa4b75bf
[ "MIT" ]
null
null
null
Blob_Lib/assimp-5.2.3/assimp/contrib/draco/src/draco/compression/mesh/mesh_encoder.cc
antholuo/Blob_Traffic
5d6acf88044e9abc63c0ff356714179eaa4b75bf
[ "MIT" ]
null
null
null
version https://git-lfs.github.com/spec/v1 oid sha256:8c8bd90ea92d058b67832d126b5441f74ba246aed3a678bf4d3dd60d66de283a size 1068
32.25
75
0.883721
antholuo
7bce22766185f7a2e5cf180f54fecab8eb7d57fa
443
cpp
C++
baekjoon/stack/10799-iron-stick.cpp
honux77/algorithm
2ed8cef1fbee7ad96d8f2ae583666d52bd8892ee
[ "MIT" ]
2
2019-02-08T01:23:07.000Z
2020-11-19T12:23:52.000Z
baekjoon/stack/10799-iron-stick.cpp
honux77/algorithm
2ed8cef1fbee7ad96d8f2ae583666d52bd8892ee
[ "MIT" ]
null
null
null
baekjoon/stack/10799-iron-stick.cpp
honux77/algorithm
2ed8cef1fbee7ad96d8f2ae583666d52bd8892ee
[ "MIT" ]
null
null
null
#include <iostream> #include <stack> using namespace std; int main() { int res = 0; ios_base::sync_with_stdio(false); cin.tie(nullptr); stack<char> st; string p; cin >> p; bool prev = false; for (auto c: p) { if (c=='(') { st.push(c); prev = true; } else if (c == ')' && prev) { st.pop(); res += st.size(); prev = false; } else { st.pop(); res++; prev = false; } } cout << res << endl; return 0; }
14.766667
34
0.528217
honux77
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
7bd884dec92acb411f2637e8a6f065244c1475ca
170
cpp
C++
20181001/B.cpp
webturing/NOIP2018FinalCamp
aef2945377fab154a916edcde6f300b53619430d
[ "MIT" ]
null
null
null
20181001/B.cpp
webturing/NOIP2018FinalCamp
aef2945377fab154a916edcde6f300b53619430d
[ "MIT" ]
null
null
null
20181001/B.cpp
webturing/NOIP2018FinalCamp
aef2945377fab154a916edcde6f300b53619430d
[ "MIT" ]
null
null
null
#include <bits/stdc++.h> using namespace std; int main() { int N; cin >> N; while (N--) { string str; cin >> str; cout << str << endl; } return 0; }
14.166667
24
0.511765
webturing
7bda7b8671161a60717056e8b9f149dda12325a8
495
cpp
C++
DisjoinSetUnion/CPP/DSU.cpp
riship99/codeWith-hacktoberfest
f16fa9dc9a2af0009dea3dea3220e3eaa43d3d2b
[ "MIT" ]
29
2020-10-03T17:41:46.000Z
2021-10-04T17:59:22.000Z
DisjoinSetUnion/CPP/DSU.cpp
riship99/codeWith-hacktoberfest
f16fa9dc9a2af0009dea3dea3220e3eaa43d3d2b
[ "MIT" ]
117
2020-10-03T15:39:39.000Z
2021-10-06T08:21:37.000Z
DisjoinSetUnion/CPP/DSU.cpp
riship99/codeWith-hacktoberfest
f16fa9dc9a2af0009dea3dea3220e3eaa43d3d2b
[ "MIT" ]
160
2020-10-03T15:39:23.000Z
2021-10-13T09:07:05.000Z
#include <bits/stdc++.h> using namespace std; #define rank rnk const int N = 1e5 + 5; int rank[N], p[N]; void init() { for (int i = 0; i < N; i++) rank[i] = 0, p[i] = i; } int findp(int n) { return n == p[n] ? n : p[n] = findp(p[n]); } bool merge(int u, int v) { u = findp(u); v = findp(v); if (u == v) return false; if (rank[u] < rank[v]) swap(u, v); if (rank[u] == rank[v]) rank[u]++; p[v]=u; return true; } bool isSameSet(int u,int v){ return findp(u)==findp(v); }
13.378378
43
0.527273
riship99
7bdfa2ec3130d4e3e8222b483dd1c4cb342182f5
20,482
cpp
C++
Common/CoordinateSystem/CoordSysGeodeticTransformDef.cpp
achilex/MgDev
f7baf680a88d37659af32ee72b9a2046910b00d8
[ "PHP-3.0" ]
2
2017-04-19T01:38:30.000Z
2020-07-31T03:05:32.000Z
Common/CoordinateSystem/CoordSysGeodeticTransformDef.cpp
achilex/MgDev
f7baf680a88d37659af32ee72b9a2046910b00d8
[ "PHP-3.0" ]
null
null
null
Common/CoordinateSystem/CoordSysGeodeticTransformDef.cpp
achilex/MgDev
f7baf680a88d37659af32ee72b9a2046910b00d8
[ "PHP-3.0" ]
1
2021-12-29T10:46:12.000Z
2021-12-29T10:46:12.000Z
// // Copyright (C) 2004-2011 by Autodesk, Inc. // // This library is free software; you can redistribute it and/or // modify it under the terms of version 2.1 of the GNU Lesser // General Public License as published by the Free Software Foundation. // // This library is distributed in the hope that it will be useful, // but WITHOUT ANY WARRANTY; without even the implied warranty of // MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU // Lesser General Public License for more details. // // You should have received a copy of the GNU Lesser General Public // License along with this library; if not, write to the Free Software // Foundation, Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301 USA // #include "GeometryCommon.h" #include "CoordSysCommon.h" #include "CriticalSection.h" #include "CoordSysGeodeticTransformation.h" #include "CoordSysGeodeticTransformDefParams.h" #include "CoordSysGeodeticStandaloneTransformDefParams.h" #include "CoordSysGeodeticAnalyticalTransformDefParams.h" #include "CoordSysGeodeticInterpolationTransformDefParams.h" #include "CoordSysGeodeticMultipleRegressionTransformDefParams.h" #include "CoordSysGeodeticTransformDef.h" #include "CoordSysTransform.h" //for CCoordinateSystemTransform #include "CoordSysUtil.h" //for CsDictionaryOpenMode #include "MentorDictionary.h" using namespace CSLibrary; #define CS_MAP_DEF_VARIABLE this->transformDefinition //needed by CoordSysMacro #include "CoordSysMacro.h" //for DEFINE_GET_SET_STRING and DEFINE_GET_SET_NUMERIC CCoordinateSystemGeodeticTransformDef::CCoordinateSystemGeodeticTransformDef(MgCoordinateSystemCatalog* pCatalog) : transformationDefType(0), transformDefinition(NULL), catalog(SAFE_ADDREF(pCatalog) /* make sure, we take a count on it */) { //have we been passed a non-null argument? CHECKNULL(this->catalog, L"CCoordinateSystemGeodeticTransformDef.ctor"); } CCoordinateSystemGeodeticTransformDef::~CCoordinateSystemGeodeticTransformDef() { this->ReleaseInstance(); } void CCoordinateSystemGeodeticTransformDef::ReleaseInstance() { if (NULL != this->transformDefinition) { CS_free(this->transformDefinition); this->transformDefinition = NULL; } this->transformationDefType = 0; } void CCoordinateSystemGeodeticTransformDef::Dispose() { delete this; } void CCoordinateSystemGeodeticTransformDef::Reset(INT32 transformationDefType) { INT32 transformationType; switch(transformationDefType) { case MgCoordinateSystemGeodeticTransformDefType::Standalone: case MgCoordinateSystemGeodeticTransformDefType::Analytical: case MgCoordinateSystemGeodeticTransformDefType::Interpolation: case MgCoordinateSystemGeodeticTransformDefType::MultipleRegression: transformationType = transformationDefType; break; default: throw new MgInvalidArgumentException(L"CCoordinateSystemGeodeticTransformDef.Reset", __LINE__, __WFILE__, NULL, L"", NULL); } //try creating a new [cs_GeodeticTransform_] instance before we wipe out our own stuff cs_GeodeticTransform_* newEmptyDef = (cs_GeodeticTransform_*)CS_malc(sizeof(cs_GeodeticTransform_)); if (NULL == newEmptyDef) //uses CS_malc which returns NULL in case allocation fails throw new MgOutOfMemoryException(L"CCoordinateSystemGeodeticTransformDef.Initialize", __LINE__, __WFILE__, NULL, L"", NULL); MG_TRY() //now, 0 our temp memory we've allocated memset ((void*)newEmptyDef, 0, sizeof(cs_GeodeticTransform_)); //ok - everything worked out so far; release this instance's information this->ReleaseInstance(); _ASSERT(NULL == this->transformDefinition); this->transformDefinition = newEmptyDef; newEmptyDef = NULL; //make sure, we don't free that one after we get a hold on the (no longer temp) memory this->transformationDefType = transformationType; MG_CATCH(L"CCoordinateSystemGeodeticTransformDef.Reset") if (NULL != newEmptyDef) //will have been set to NULL before CS_free(newEmptyDef); MG_THROW() } INT32 CCoordinateSystemGeodeticTransformDef::GetTransformationDefType(INT32 methodCode /* method code as read from the dictionary entry */) { INT32 transformationType; switch(methodCode) { //standalone/built-in methods; see information in cs_geodetic.h case cs_DTCMTH_NULLX: case cs_DTCMTH_WGS72: transformationType = MgCoordinateSystemGeodeticTransformDefType::Standalone; break; //multiple Regression methods case cs_DTCMTH_MULRG: case cs_DTCMTH_PLYNM: transformationType = MgCoordinateSystemGeodeticTransformDefType::MultipleRegression; break; //geocentric methods case cs_DTCMTH_3PARM: case cs_DTCMTH_MOLOD: case cs_DTCMTH_AMOLO: case cs_DTCMTH_GEOCT: case cs_DTCMTH_4PARM: case cs_DTCMTH_6PARM: case cs_DTCMTH_BURSA: case cs_DTCMTH_FRAME: case cs_DTCMTH_7PARM: case cs_DTCMTH_BDKAS: transformationType = MgCoordinateSystemGeodeticTransformDefType::Analytical; break; //grid file interpolation methods; if a transformation uses grid file(s), this is the actual //type - the ones below are the format of the grid file(s) being used. For example, //the dictionary does then contains something like //GRID_FILE: NTv2,FWD,.\Australia\Agd66\A66National(13.09.01).gsb case cs_DTCMTH_GFILE: transformationType = MgCoordinateSystemGeodeticTransformDefType::Interpolation; break; //the next entries are not expected; we're mapping them to the interpolation transformation type case cs_DTCMTH_CNTv1: case cs_DTCMTH_CNTv2: case cs_DTCMTH_FRNCH: case cs_DTCMTH_JAPAN: case cs_DTCMTH_ATS77: case cs_DTCMTH_OST97: case cs_DTCMTH_OST02: _ASSERT(false); transformationType = MgCoordinateSystemGeodeticTransformDefType::Interpolation; break; default: //invalid / unknown [methodCode] given; don't know how to proceed here throw new MgInvalidArgumentException(L"CCoordinateSystemGeodeticTransformDef.Initialize", __LINE__, __WFILE__, NULL, L"", NULL); } return transformationType; } void CCoordinateSystemGeodeticTransformDef::Initialize(const cs_GeodeticTransform_& transformDef) { //take the transformation type from the param we've been passed; we'll use that information to build the correct //parameter object later on INT32 transformationType = this->GetTransformationDefType(transformDef.methodCode); this->Reset(transformationType); *this->transformDefinition = transformDef; } MgCoordinateSystemGeodeticTransformation* CCoordinateSystemGeodeticTransformDef::CreateTransformation(bool createInverse) { VERIFY_INITIALIZED(L"CCoordinateSystemGeodeticTransformDef.CreateTransformation"); if (!this->IsValid()) throw new MgInvalidOperationException(L"CCoordinateSystemGeodeticTransformDef.CreateTransformation", __LINE__,__WFILE__, NULL, L"", NULL); //we don't take ownership of the transformation being returned but //will release [sourceDatum] and [targetDatum]; //new [CCoordinateSystemGeodeticTransformation] will have to ADDREF if needed return new CCoordinateSystemGeodeticTransformation(this->catalog, this, createInverse); } MgCoordinateSystemGeodeticTransformDef* CCoordinateSystemGeodeticTransformDef::CreateClone() { VERIFY_INITIALIZED(L"CCoordinateSystemGeodeticTransformDef.CreateClone"); Ptr<CCoordinateSystemGeodeticTransformDef> clonedTransformDef = new CCoordinateSystemGeodeticTransformDef(this->catalog.p); clonedTransformDef->Initialize(*this->transformDefinition); //unset the EPSG code; we've an editable instance now where we neither can guarantee the correctness of the EPSG code //nor is it currently supported by CsMap's NameMapper anyway clonedTransformDef->transformDefinition->epsgCode = 0; clonedTransformDef->transformDefinition->epsgVariation = 0; clonedTransformDef->transformDefinition->protect = 0; //unset the protection flag; otherwise the caller wouldn't be able to change any values return clonedTransformDef.Detach(); } void CCoordinateSystemGeodeticTransformDef::CopyTo(cs_GeodeticTransform_& transformDef) const { VERIFY_INITIALIZED(L"CCoordinateSystemGeodeticTransformDef.CopyTo"); //copy our values into the [cs_GeodeticTransform_] we've been passed here transformDef = *this->transformDefinition; } INT32 CCoordinateSystemGeodeticTransformDef::GetTransformDefType() { return this->transformationDefType; //can be None } MgCoordinateSystemGeodeticTransformDefParams* CCoordinateSystemGeodeticTransformDef::GetParameters() { VERIFY_INITIALIZED(L"CCoordinateSystemGeodeticTransformDef.GetParameters"); switch(this->transformationDefType) { case MgCoordinateSystemGeodeticTransformDefType::Standalone: return static_cast<MgCoordinateSystemGeodeticStandaloneTransformDefParams*>(new CCoordinateSystemGeodeticStandaloneTransformDefParams( this->transformDefinition->methodCode, this->IsProtected())); case MgCoordinateSystemGeodeticTransformDefType::Analytical: return static_cast<MgCoordinateSystemGeodeticAnalyticalTransformDefParams*>(new CCoordinateSystemGeodeticAnalyticalTransformDefParams( this->transformDefinition->parameters.geocentricParameters, this->transformDefinition->methodCode, this->IsProtected())); case MgCoordinateSystemGeodeticTransformDefType::Interpolation: return static_cast<MgCoordinateSystemGeodeticInterpolationTransformDefParams*>( new CCoordinateSystemGeodeticInterpolationTransformDefParams(this->transformDefinition->parameters.fileParameters, this->IsProtected())); case MgCoordinateSystemGeodeticTransformDefType::MultipleRegression: return static_cast<MgCoordinateSystemGeodeticMultipleRegressionTransformDefParams*>(new CCoordinateSystemGeodeticMultipleRegressionTransformDefParams( this->transformDefinition->parameters.dmaMulRegParameters, this->transformDefinition->methodCode, this->IsProtected())); default: //invalid state; why's that? _ASSERT(false); throw new MgInvalidOperationException(L"CCoordinateSystemGeodeticTransformDef.GetParameters", __LINE__, __WFILE__, NULL, L"", NULL); } } void CCoordinateSystemGeodeticTransformDef::SetParameters(MgCoordinateSystemGeodeticTransformDefParams* parameters) { VERIFY_INITIALIZED(L"CCoordinateSystemGeodeticTransformDef.SetParameters"); VERIFY_NOT_PROTECTED(L"CCoordinateSystemGeodeticTransformDef.SetParameters"); //first check, whether this is a NONE transformation definition; if so, ignore the parameter altogether and wipe out //this instance's parameter information to NULL if (MgCoordinateSystemGeodeticTransformDefType::None == this->transformationDefType) { memset(&this->transformDefinition->parameters, 0, sizeof(this->transformDefinition->parameters.sizeDetermination.unionSize)); return; } //otherwise: make sure, we've been passed non null paramaters... ENSURE_NOT_NULL(parameters, L"CCoordinateSystemGeodeticTransformDef.SetParameters"); INT32 paramsMethodCode = 0x0; //...and the parameters are actually of the correct type, i.e. match whatever we've stored in [this->transformationDefType] CCoordinateSystemGeodeticTransformDefParams* transformDefParams = NULL; CCoordinateSystemGeodeticMultipleRegressionTransformDefParams* mulRegParams = NULL; CCoordinateSystemGeodeticAnalyticalTransformDefParams* analyticalParams = NULL; CCoordinateSystemGeodeticStandaloneTransformDefParams* standaloneParams = NULL; switch(this->transformationDefType) { case MgCoordinateSystemGeodeticTransformDefType::Standalone: standaloneParams = dynamic_cast<CCoordinateSystemGeodeticStandaloneTransformDefParams*>(parameters); if (NULL != standaloneParams) { paramsMethodCode = standaloneParams->GetTransformationMethod(); transformDefParams = standaloneParams; } break; case MgCoordinateSystemGeodeticTransformDefType::Analytical: analyticalParams = dynamic_cast<CCoordinateSystemGeodeticAnalyticalTransformDefParams*>(parameters); if (NULL != analyticalParams) { paramsMethodCode = analyticalParams->GetTransformationMethod(); transformDefParams = analyticalParams; } break; case MgCoordinateSystemGeodeticTransformDefType::Interpolation: transformDefParams = dynamic_cast<CCoordinateSystemGeodeticInterpolationTransformDefParams*>(parameters); //the transformation method is "grid file"; the actual type doesn't matter as this //is specified through the [MgCoordinateSystemGeodeticInterpolationTransformDefParams] object; //such a transformation can use multiple grid files where each can have a different format paramsMethodCode = cs_DTCMTH_GFILE; break; case MgCoordinateSystemGeodeticTransformDefType::MultipleRegression: mulRegParams = dynamic_cast<CCoordinateSystemGeodeticMultipleRegressionTransformDefParams*>(parameters); if (NULL != mulRegParams) { paramsMethodCode = mulRegParams->GetTransformationMethod(); transformDefParams = mulRegParams; } break; default: _ASSERT(false); //why's that? break; } if (NULL == transformDefParams) throw new MgInvalidOperationException(L"CCoordinateSystemGeodeticTransformDef.SetParameters", __LINE__, __WFILE__, NULL, L"", NULL); //copy the values from the parameter we've been passed into our own [parameters] section transformDefParams->CopyTo(&this->transformDefinition->parameters); this->transformDefinition->methodCode = paramsMethodCode; } bool CCoordinateSystemGeodeticTransformDef::IsProtected() { VERIFY_INITIALIZED(L"CCoordinateSystemGeodeticTransformDef.IsProtected"); return (DICTIONARY_SYS_DEF == this->transformDefinition->protect); } bool CCoordinateSystemGeodeticTransformDef::IsValid() { if (NULL == this->transformDefinition) //an unitialized definition is always invalid return false; Ptr<MgCoordinateSystemGeodeticTransformDefParams> params = this->GetParameters(); if (NULL == params) return true; //this is a NULL transformation; this is valid if (!params->IsValid()) return false; CriticalClass.Enter(); int nNumErrs = CS_gxchk(this->transformDefinition, 0, NULL, 0); CriticalClass.Leave(); return (0 == nNumErrs); } //helper - don't delete bool CCoordinateSystemGeodeticTransformDef::IsEncrypted() { return false; } DEFINE_GET_SET_STRING(CCoordinateSystemGeodeticTransformDef,TransformName,this->transformDefinition->xfrmName) DEFINE_GET_SET_STRING(CCoordinateSystemGeodeticTransformDef,SourceDatum,this->transformDefinition->srcDatum) DEFINE_GET_SET_STRING(CCoordinateSystemGeodeticTransformDef,TargetDatum,this->transformDefinition->trgDatum) DEFINE_GET_SET_STRING(CCoordinateSystemGeodeticTransformDef,Group,this->transformDefinition->group) DEFINE_GET_SET_STRING(CCoordinateSystemGeodeticTransformDef,Description,this->transformDefinition->description) DEFINE_GET_SET_STRING(CCoordinateSystemGeodeticTransformDef,Source,this->transformDefinition->source) DEFINE_GET_SET_NUMERIC(CCoordinateSystemGeodeticTransformDef,EpsgCode,INT32,this->transformDefinition->epsgCode) DEFINE_GET_SET_NUMERIC(CCoordinateSystemGeodeticTransformDef,EpsgVariation,INT32,this->transformDefinition->epsgVariation) DEFINE_GET_SET_NUMERIC(CCoordinateSystemGeodeticTransformDef,InverseSupported,bool,this->transformDefinition->inverseSupported) DEFINE_GET_SET_NUMERIC(CCoordinateSystemGeodeticTransformDef,MaxIterations,INT32,this->transformDefinition->maxIterations) DEFINE_GET_SET_NUMERIC(CCoordinateSystemGeodeticTransformDef,ConvergenceValue,double,this->transformDefinition->cnvrgValue) DEFINE_GET_SET_NUMERIC(CCoordinateSystemGeodeticTransformDef,ErrorValue,double,this->transformDefinition->errorValue) DEFINE_GET_SET_NUMERIC(CCoordinateSystemGeodeticTransformDef,Accuracy,double,this->transformDefinition->accuracy) DEFINE_GET_SET_NUMERIC(CCoordinateSystemGeodeticTransformDef,RangeMinLongitude,double,this->transformDefinition->rangeMinLng) DEFINE_GET_SET_NUMERIC(CCoordinateSystemGeodeticTransformDef,RangeMaxLongitude,double,this->transformDefinition->rangeMaxLng) DEFINE_GET_SET_NUMERIC(CCoordinateSystemGeodeticTransformDef,RangeMinLatitude,double,this->transformDefinition->rangeMinLat) DEFINE_GET_SET_NUMERIC(CCoordinateSystemGeodeticTransformDef,RangeMaxLatitude,double,this->transformDefinition->rangeMaxLat) //***************************************************************************** UINT8* CCoordinateSystemGeodeticTransformDef::SerializeFrom(UINT8* pStream) { UINT8* pStreamIn=pStream; char *pBuf; assert(NULL != pStream); if (!pStream) { throw new MgInvalidArgumentException(L"MgCoordinateSystemGeodeticTransformDef.SerializeFrom", __LINE__, __WFILE__, NULL, L"", NULL); } // In case an exception gets thrown. INT32 previousType = this->transformationDefType; cs_GeodeticTransform_* previousTransformPtr = this->transformDefinition; cs_GeodeticTransform_* allocatedBlock = NULL; MG_TRY() UINT8 nVersion=pStreamIn[0]; if (kGxRelease0==nVersion) { pStreamIn++; //Read the def from the stream allocatedBlock = (cs_GeodeticTransform_*)CS_malc(sizeof(cs_GeodeticTransform_)); if (NULL == allocatedBlock) throw new MgOutOfMemoryException (L"MgCoordinateSystemGeodeticTransformDef.SerializeFrom", __LINE__, __WFILE__, NULL, L"", NULL); this->transformDefinition = allocatedBlock; pBuf = reinterpret_cast<char *>(this->transformDefinition); memcpy(pBuf, pStreamIn, sizeof(cs_GeodeticTransform_)); pStreamIn = pStreamIn + sizeof(cs_GeodeticTransform_); // The following function nwill throw if the mthodCode is not one known to the function. this->transformationDefType = GetTransformationDefType(this->transformDefinition->methodCode); // Verify the validity of the result. if (IsValid()) { // Yup! its OK. Release the copy of the previous definition. CS_free (previousTransformPtr); previousTransformPtr = 0; } else { // Nope! It's not valid, but not valid in such a way that would cause // an exception to be thrown. transformationDefinition cannot be // NULL at this point. throw new MgInvalidArgumentException(L"MgCoordinateSystemGeodeticTransformDef.SerializeFrom", __LINE__, __WFILE__, NULL, L"", NULL); } } MG_CATCH (L"MgCoordinateSystemGeodeticTransformDef.SerializeFrom") if (mgException != NULL) { //in case an exception was thrown, we simply free the allocated block //and reset what we had before; no matter whether this had been valid or not CS_free (allocatedBlock); allocatedBlock = NULL; this->transformationDefType = previousType; this->transformDefinition = previousTransformPtr; } MG_THROW () return pStreamIn; } //***************************************************************************** UINT8* CCoordinateSystemGeodeticTransformDef::SerializeTo(UINT8* pStream) { char *pBuf; UINT8* pStreamOut=pStream; MG_TRY() assert(NULL != pStream); if (!pStream) { throw new MgInvalidArgumentException(L"MgCoordinateSystemGeodeticTransformDef.SerializeTo", __LINE__, __WFILE__, NULL, L"", NULL); } //save the version pStreamOut[0]=kGxRelease0; pStreamOut++; pBuf = reinterpret_cast<char *>(this->transformDefinition); memcpy(pStreamOut, pBuf, sizeof(*this->transformDefinition)); pStreamOut = pStreamOut + sizeof(*this->transformDefinition); MG_CATCH_AND_THROW(L"MgCoordinateSystemGeodeticTransformDef.SerializeTo") return pStreamOut; } //***************************************************************************** UINT32 CCoordinateSystemGeodeticTransformDef::GetSizeSerialized() { //size of the structure and the verison number size_t size=sizeof(cs_GeodeticTransform_) + sizeof(UINT8); return static_cast<UINT32>(size); }
42.939203
158
0.761303
achilex
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 (abel@sinkovics.hu) 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
7be2d2e4bac98b67b31bada4699c8f102f0f9bea
2,696
cpp
C++
Projects/Demo/source/Common/SpawnComponent.cpp
asheraryam/ETEngine
cac9b62146bfd2fe249a53eb8031cbbbd1db0931
[ "MIT" ]
552
2017-08-21T18:12:52.000Z
2022-03-31T15:41:56.000Z
Projects/Demo/source/Common/SpawnComponent.cpp
asheraryam/ETEngine
cac9b62146bfd2fe249a53eb8031cbbbd1db0931
[ "MIT" ]
14
2017-08-07T23:36:13.000Z
2021-05-10T08:41:19.000Z
Projects/Demo/source/Common/SpawnComponent.cpp
asheraryam/ETEngine
cac9b62146bfd2fe249a53eb8031cbbbd1db0931
[ "MIT" ]
40
2017-10-10T14:42:22.000Z
2022-03-10T07:14:33.000Z
#include "stdafx.h" #include "SpawnComponent.h" #include <EtCore/Reflection/Registration.h> #include <EtCore/Content/ResourceManager.h> #include <EtRendering/GraphicsTypes/Mesh.h> #include <EtRendering/MaterialSystem/MaterialInstance.h> #include <EtRendering/MaterialSystem/MaterialData.h> namespace et { namespace demo { // reflection //------------ RTTR_REGISTRATION { rttr::registration::class_<SpawnComponent>("spawn component"); BEGIN_REGISTER_CLASS(SpawnComponentDesc, "spawn comp desc") .property("mesh", &SpawnComponentDesc::mesh) .property("material", &SpawnComponentDesc::material) .property("scale", &SpawnComponentDesc::scale) .property("shape", &SpawnComponentDesc::shape) .property("mass", &SpawnComponentDesc::mass) .property("interval", &SpawnComponentDesc::interval) .property("impulse", &SpawnComponentDesc::impulse) END_REGISTER_CLASS_POLYMORPHIC(SpawnComponentDesc, fw::I_ComponentDescriptor); } DEFINE_FORCED_LINKING(SpawnComponentDesc) // force the linker to include this unit ECS_REGISTER_COMPONENT(SpawnComponent); //================= // Spawn Component //================= //----------------------- // SpawnComponent::c-tor // // load assets from ids // SpawnComponent::SpawnComponent(AssetPtr<render::MeshData> const meshPtr, AssetPtr<render::I_Material> const materialPtr, float const s, btCollisionShape* const shape, float const shapeMass, float const interv, float const imp ) : collisionShape(shape) , mass(shapeMass) , scale(s) , interval(interv) , impulse(imp) , mesh(meshPtr) , material(materialPtr) { } //============================ // Spawn Component Descriptor //============================ //----------------------------- // SpawnComponentDesc:: = // SpawnComponentDesc& SpawnComponentDesc::operator=(SpawnComponentDesc const& other) { mesh = other.mesh; material = other.material; scale = other.scale; mass = other.mass; interval = other.interval; impulse = other.impulse; delete shape; shape = nullptr; if (other.shape != nullptr) { shape = other.shape->Clone(); } return *this; } //------------------------------- // SpawnComponentDesc::c-tor // SpawnComponentDesc::SpawnComponentDesc(SpawnComponentDesc const& other) { *this = other; } //------------------------------- // SpawnComponentDesc::d-tor // SpawnComponentDesc::~SpawnComponentDesc() { delete shape; } //------------------------------ // SpawnComponentDesc::MakeData // // Create a spawn component from a descriptor // SpawnComponent* SpawnComponentDesc::MakeData() { return new SpawnComponent(mesh, material, scale, shape->MakeBulletCollisionShape(), mass, interval, impulse); } } // namespace demo } // namespace et
21.918699
110
0.676929
asheraryam
7be6271680c2f2a74713506038e3bf698dc70ccd
3,239
cpp
C++
Cpp-C/Ema/Src/Access/Impl/OmmIProviderActiveConfig.cpp
krico/Real-Time-SDK
534534199f1595f0dea121f02a57db4b2c0aeae2
[ "Apache-2.0" ]
107
2015-07-27T23:43:04.000Z
2019-01-03T07:11:27.000Z
Cpp-C/Ema/Src/Access/Impl/OmmIProviderActiveConfig.cpp
krico/Real-Time-SDK
534534199f1595f0dea121f02a57db4b2c0aeae2
[ "Apache-2.0" ]
91
2015-07-28T15:40:43.000Z
2018-12-31T09:37:19.000Z
Cpp-C/Ema/Src/Access/Impl/OmmIProviderActiveConfig.cpp
krico/Real-Time-SDK
534534199f1595f0dea121f02a57db4b2c0aeae2
[ "Apache-2.0" ]
68
2015-07-27T08:35:47.000Z
2019-01-01T07:59:39.000Z
#include "OmmIProviderActiveConfig.h" using namespace refinitiv::ema::access; #define DEFAULT_USER_DISPATCH OmmNiProviderConfig::ApiDispatchEnum #define DEFAULT_REFRESH_FIRST_REQUIRED true #define DEFAULT_ENFORCE_ACK_ID_VALIDATION false #define DEFAULT_DIRECTORY_ADMIN_CONTROL OmmNiProviderConfig::ApiControlEnum #define DEFAULT_FIELD_DICT_FRAGMENT_SIZE 8192 #define DEFAULT_ENUM_TYPE_FRAGMENT_SIZE 12288 #define DEFAULT_REQUEST_TIMEOUT 15000 static const EmaString DEFAULT_IPROVIDER_SERVICE_NAME("14002"); OmmIProviderActiveConfig::OmmIProviderActiveConfig() : ActiveServerConfig(DEFAULT_IPROVIDER_SERVICE_NAME), refreshFirstRequired(DEFAULT_REFRESH_FIRST_REQUIRED), enforceAckIDValidation(DEFAULT_ENFORCE_ACK_ID_VALIDATION) { maxFieldDictFragmentSize = DEFAULT_FIELD_DICT_FRAGMENT_SIZE; maxEnumTypeFragmentSize = DEFAULT_ENUM_TYPE_FRAGMENT_SIZE; } OmmIProviderActiveConfig::~OmmIProviderActiveConfig() { } void refinitiv::ema::access::OmmIProviderActiveConfig::clear() { ActiveServerConfig::clear(); refreshFirstRequired = DEFAULT_REFRESH_FIRST_REQUIRED; maxFieldDictFragmentSize = DEFAULT_FIELD_DICT_FRAGMENT_SIZE; maxEnumTypeFragmentSize = DEFAULT_ENUM_TYPE_FRAGMENT_SIZE; } EmaString OmmIProviderActiveConfig::configTrace() { ActiveServerConfig::configTrace(); traceStr.append("\n\t operationModel: ").append(operationModel) .append("\n\t dictionaryAdminControl: ").append(dictionaryAdminControl) .append("\n\t directoryAdminControl : ").append(directoryAdminControl) .append("\n\t refreshFirstRequired : ").append(refreshFirstRequired) .append("\n\t enforceAckIDValidation : ").append(enforceAckIDValidation) .append("\n\t maxFieldDictFragmentSize : ").append(maxFieldDictFragmentSize) .append("\n\t maxEnumTypeFragmentSize : ").append(maxEnumTypeFragmentSize); return traceStr; } OmmIProviderConfig::AdminControl OmmIProviderActiveConfig::getDictionaryAdminControl() { return dictionaryAdminControl; } OmmIProviderConfig::AdminControl OmmIProviderActiveConfig::getDirectoryAdminControl() { return directoryAdminControl; } UInt32 OmmIProviderActiveConfig::getMaxFieldDictFragmentSize() { return maxFieldDictFragmentSize; } UInt32 OmmIProviderActiveConfig::getMaxEnumTypeFragmentSize() { return maxEnumTypeFragmentSize; } void OmmIProviderActiveConfig::setMaxFieldDictFragmentSize(UInt64 value) { if (value <= 0) {} else if (value > RWF_MAX_32) maxFieldDictFragmentSize = RWF_MAX_32; else maxFieldDictFragmentSize = (UInt32)value; } void OmmIProviderActiveConfig::setMaxEnumTypeFragmentSize(UInt64 value) { if (value <= 0) {} else if (value > RWF_MAX_32) maxEnumTypeFragmentSize = RWF_MAX_32; else maxEnumTypeFragmentSize = (UInt32)value; } bool OmmIProviderActiveConfig::getRefreshFirstRequired() { return refreshFirstRequired; } void OmmIProviderActiveConfig::setRefreshFirstRequired(UInt64 value) { if (value <= 0) refreshFirstRequired = false; else refreshFirstRequired = true; } bool OmmIProviderActiveConfig::getEnforceAckIDValidation() { return enforceAckIDValidation; } void OmmIProviderActiveConfig::setEnforceAckIDValidation(UInt64 value) { if (value <= 0) enforceAckIDValidation = false; else enforceAckIDValidation = true; }
28.919643
86
0.820315
krico
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
7be7e64476cd97a7a8a935625fc1d6b4b1e345a0
21,222
cpp
C++
libraries/mne/c/mne_proj_op.cpp
Andrey1994/mne-cpp
6264b1107b9447b7db64309f73f09e848fd198c4
[ "BSD-3-Clause" ]
2
2021-11-16T19:38:12.000Z
2021-11-18T20:52:08.000Z
libraries/mne/c/mne_proj_op.cpp
Andrey1994/mne-cpp
6264b1107b9447b7db64309f73f09e848fd198c4
[ "BSD-3-Clause" ]
null
null
null
libraries/mne/c/mne_proj_op.cpp
Andrey1994/mne-cpp
6264b1107b9447b7db64309f73f09e848fd198c4
[ "BSD-3-Clause" ]
1
2021-11-16T19:39:01.000Z
2021-11-16T19:39:01.000Z
//============================================================================================================= /** * @file mne_proj_op.cpp * @author Lorenz Esch <lesch@mgh.harvard.edu>; * Matti Hamalainen <msh@nmr.mgh.harvard.edu>; * Christoph Dinh <chdinh@nmr.mgh.harvard.edu> * @version dev * @date January, 2017 * * @section LICENSE * * Copyright (C) 2017, Lorenz Esch, Matti Hamalainen, Christoph Dinh. 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 MNE-CPP authors nor the names of its contributors may be used * to endorse or promote products derived from this software without specific prior written permission. * * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" AND ANY EXPRESS OR IMPLIED * WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A * PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT OWNER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, * INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, * PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) * HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING * NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE * POSSIBILITY OF SUCH DAMAGE. * * * @brief Definition of the MNEProjOp Class. * */ //************************************************************************************************************* //============================================================================================================= // INCLUDES //============================================================================================================= #include <fiff/fiff_constants.h> #include <fiff/fiff_tag.h> #include "mne_proj_op.h" #include "mne_proj_item.h" #include <QFile> #include <Eigen/Core> #ifndef TRUE #define TRUE 1 #endif #ifndef FALSE #define FALSE 0 #endif #ifndef FAIL #define FAIL -1 #endif #ifndef OK #define OK 0 #endif #define MALLOC_23(x,t) (t *)malloc((x)*sizeof(t)) #define REALLOC_23(x,y,t) (t *)((x == NULL) ? malloc((y)*sizeof(t)) : realloc((x),(y)*sizeof(t))) #define FREE_23(x) if ((char *)(x) != NULL) free((char *)(x)) #define FREE_CMATRIX_23(m) mne_free_cmatrix_23((m)) void mne_free_cmatrix_23 (float **m) { if (m) { FREE_23(*m); FREE_23(m); } } #define ALLOC_CMATRIX_23(x,y) mne_cmatrix_23((x),(y)) static void matrix_error_23(int kind, int nr, int nc) { if (kind == 1) printf("Failed to allocate memory pointers for a %d x %d matrix\n",nr,nc); else if (kind == 2) printf("Failed to allocate memory for a %d x %d matrix\n",nr,nc); else printf("Allocation error for a %d x %d matrix\n",nr,nc); if (sizeof(void *) == 4) { printf("This is probably because you seem to be using a computer with 32-bit architecture.\n"); printf("Please consider moving to a 64-bit platform."); } printf("Cannot continue. Sorry.\n"); exit(1); } float **mne_cmatrix_23(int nr,int nc) { int i; float **m; float *whole; m = MALLOC_23(nr,float *); if (!m) matrix_error_23(1,nr,nc); whole = MALLOC_23(nr*nc,float); if (!whole) matrix_error_23(2,nr,nc); for(i=0;i<nr;i++) m[i] = whole + i*nc; return m; } float mne_dot_vectors_23 (float *v1, float *v2, int nn) { #ifdef BLAS int one = 1; float res = sdot(&nn,v1,&one,v2,&one); return res; #else float res = 0.0; int k; for (k = 0; k < nn; k++) res = res + v1[k]*v2[k]; return res; #endif } //============================= mne_named_matrix.c ============================= void mne_string_to_name_list_23(const QString& s, QStringList& listp,int &nlistp) /* * Convert a colon-separated list into a string array */ { QStringList list; if (!s.isEmpty() && s.size() > 0) { list = FIFFLIB::FiffStream::split_name_list(s); //list = s.split(":"); } listp = list; nlistp = list.size(); return; } void fromFloatEigenMatrix_23(const Eigen::MatrixXf& from_mat, float **& to_mat, const int m, const int n) { for ( int i = 0; i < m; ++i) for ( int j = 0; j < n; ++j) to_mat[i][j] = from_mat(i,j); } void fromFloatEigenMatrix_23(const Eigen::MatrixXf& from_mat, float **& to_mat) { fromFloatEigenMatrix_23(from_mat, to_mat, from_mat.rows(), from_mat.cols()); } QString mne_name_list_to_string_23(const QStringList& list) /* * Convert a string array to a colon-separated string */ { int nlist = list.size(); QString res; if (nlist == 0 || list.isEmpty()) return res; // res[0] = '\0'; for (int k = 0; k < nlist-1; k++) { res += list[k]; res += ":"; } res += list[nlist-1]; return res; } QString mne_channel_names_to_string_23(const QList<FIFFLIB::FiffChInfo>& chs, int nch) /* * Make a colon-separated string out of channel names */ { QStringList names; QString res; if (nch <= 0) return res; for (int k = 0; k < nch; k++) names.append(chs.at(k).ch_name); res = mne_name_list_to_string_23(names); return res; } //************************************************************************************************************* //============================================================================================================= // USED NAMESPACES //============================================================================================================= using namespace Eigen; using namespace FIFFLIB; using namespace MNELIB; //************************************************************************************************************* //============================================================================================================= // DEFINE MEMBER METHODS //============================================================================================================= MneProjOp::MneProjOp() : nitems (0) , names (NULL) , nch (0) , nvec (0) , proj_data (NULL) { } //************************************************************************************************************* MneProjOp::~MneProjOp() { // mne_free_proj_op for (int k = 0; k < nitems; k++) if(items[k]) delete items[k]; // mne_free_proj_op_proj } //************************************************************************************************************* void MneProjOp::mne_free_proj_op_proj(MneProjOp *op) { if (op == NULL) return; FREE_CMATRIX_23(op->proj_data); op->names.clear(); op->nch = 0; op->nvec = 0; op->proj_data = NULL; return; } //************************************************************************************************************* MneProjOp *MneProjOp::mne_proj_op_combine(MneProjOp *to, MneProjOp *from) /* * Copy items from 'from' operator to 'to' operator */ { int k; MneProjItem* it; if (to == NULL) to = new MneProjOp(); if (from) { for (k = 0; k < from->nitems; k++) { it = from->items[k]; mne_proj_op_add_item(to,it->vecs,it->kind,it->desc); to->items[to->nitems-1]->active_file = it->active_file; } } return to; } //************************************************************************************************************* void MneProjOp::mne_proj_op_add_item_act(MneProjOp *op, MneNamedMatrix *vecs, int kind, const QString& desc, int is_active) /* * Add a new item to an existing projection operator */ { MneProjItem* new_item; int k; // op->items = REALLOC(op->items,op->nitems+1,mneProjItem); // op->items[op->nitems] = new_item = new MneProjItem(); new_item = new MneProjItem(); op->items.append(new_item); new_item->active = is_active; new_item->vecs = new MneNamedMatrix(*vecs); if (kind == FIFFV_MNE_PROJ_ITEM_EEG_AVREF) { new_item->has_meg = FALSE; new_item->has_eeg = TRUE; } else { for (k = 0; k < vecs->ncol; k++) { if (vecs->collist[k].contains("EEG"))//strstr(vecs->collist[k],"EEG") == vecs->collist[k]) new_item->has_eeg = TRUE; if (vecs->collist[k].contains("MEG"))//strstr(vecs->collist[k],"MEG") == vecs->collist[k]) new_item->has_meg = TRUE; } if (!new_item->has_meg && !new_item->has_eeg) { new_item->has_meg = TRUE; new_item->has_eeg = FALSE; } else if (new_item->has_meg && new_item->has_eeg) { new_item->has_meg = TRUE; new_item->has_eeg = FALSE; } } if (!desc.isEmpty()) new_item->desc = desc; new_item->kind = kind; new_item->nvec = new_item->vecs->nrow; op->nitems++; MneProjOp::mne_free_proj_op_proj(op); /* These data are not valid any more */ return; } //************************************************************************************************************* void MneProjOp::mne_proj_op_add_item(MneProjOp *op, MneNamedMatrix *vecs, int kind, const QString& desc) { mne_proj_op_add_item_act(op, vecs, kind, desc, TRUE); } //************************************************************************************************************* MneProjOp *MneProjOp::mne_dup_proj_op(MneProjOp *op) /* * Provide a duplicate (item data only) */ { MneProjOp* dup = new MneProjOp(); MneProjItem* it; int k; if (!op) return NULL; for (k = 0; k < op->nitems; k++) { it = op->items[k]; mne_proj_op_add_item_act(dup,it->vecs,it->kind,it->desc,it->active); dup->items[k]->active_file = it->active_file; } return dup; } //************************************************************************************************************* MneProjOp *MneProjOp::mne_proj_op_average_eeg_ref(const QList<FiffChInfo>& chs, int nch) /* * Make the projection operator for average electrode reference */ { int eegcount = 0; int k; float **vec_data; QStringList names; MneNamedMatrix* vecs; MneProjOp* op; for (k = 0; k < nch; k++) if (chs.at(k).kind == FIFFV_EEG_CH) eegcount++; if (eegcount == 0) { qCritical("No EEG channels specified for average reference."); return NULL; } vec_data = ALLOC_CMATRIX_23(1,eegcount); for (k = 0; k < nch; k++) if (chs.at(k).kind == FIFFV_EEG_CH) names.append(chs.at(k).ch_name); for (k = 0; k < eegcount; k++) vec_data[0][k] = 1.0/sqrt((double)eegcount); QStringList emptyList; vecs = MneNamedMatrix::build_named_matrix(1,eegcount,emptyList,names,vec_data); op = new MneProjOp(); mne_proj_op_add_item(op,vecs,FIFFV_MNE_PROJ_ITEM_EEG_AVREF,"Average EEG reference"); return op; } //************************************************************************************************************* int MneProjOp::mne_proj_op_affect(MneProjOp *op, const QStringList& list, int nlist) { int k; int naff; if (!op) return 0; for (k = 0, naff = 0; k < op->nitems; k++) if (op->items[k]->active && MneProjItem::mne_proj_item_affect(op->items[k],list,nlist)) naff += op->items[k]->nvec; return naff; } //************************************************************************************************************* int MneProjOp::mne_proj_op_affect_chs(MneProjOp *op, const QList<FiffChInfo>& chs, int nch) { QString ch_string; int res; QStringList list; int nlist; if (nch == 0) return FALSE; ch_string = mne_channel_names_to_string_23(chs,nch); mne_string_to_name_list_23(ch_string,list,nlist); res = mne_proj_op_affect(op,list,nlist); list.clear(); return res; } //************************************************************************************************************* int MneProjOp::mne_proj_op_proj_vector(MneProjOp *op, float *vec, int nvec, int do_complement) /* * Apply projection operator to a vector (floats) * Assume that all dimension checking etc. has been done before */ { static float *res = NULL; int res_size = 0; float *pvec; float w; int k,p; if (!op || op->nitems <= 0 || op->nvec <= 0) return OK; if (op->nch != nvec) { printf("Data vector size does not match projection operator"); return FAIL; } if (op->nch > res_size) { res = REALLOC_23(res,op->nch,float); res_size = op->nch; } for (k = 0; k < op->nch; k++) res[k] = 0.0; for (p = 0; p < op->nvec; p++) { pvec = op->proj_data[p]; w = mne_dot_vectors_23(pvec,vec,op->nch); for (k = 0; k < op->nch; k++) res[k] = res[k] + w*pvec[k]; } if (do_complement) { for (k = 0; k < op->nch; k++) vec[k] = vec[k] - res[k]; } else { for (k = 0; k < op->nch; k++) vec[k] = res[k]; } return OK; } //************************************************************************************************************* MneProjOp *MneProjOp::mne_read_proj_op_from_node(FiffStream::SPtr &stream, const FiffDirNode::SPtr &start) /* * Load all the linear projection data */ { MneProjOp* op = NULL; QList<FiffDirNode::SPtr> proj; FiffDirNode::SPtr start_node; QList<FiffDirNode::SPtr> items; FiffDirNode::SPtr node; int k; QString item_desc,desc_tag; int global_nchan,item_nchan,nlist; QStringList item_names; int item_kind; float **item_vectors = NULL; int item_nvec; int item_active; MneNamedMatrix* item; FiffTag::SPtr t_pTag; if (!stream) { qCritical("File not open mne_read_proj_op_from_node"); goto bad; } if (!start || start->isEmpty()) start_node = stream->dirtree(); else start_node = start; op = new MneProjOp(); proj = start_node->dir_tree_find(FIFFB_PROJ); if (proj.size() == 0 || proj[0]->isEmpty()) /* The caller must recognize an empty projection */ goto out; /* * Only the first projection block is recognized */ items = proj[0]->dir_tree_find(FIFFB_PROJ_ITEM); if (items.size() == 0 || items[0]->isEmpty()) /* The caller must recognize an empty projection */ goto out; /* * Get a common number of channels */ node = proj[0]; if(!node->find_tag(stream, FIFF_NCHAN, t_pTag)) global_nchan = 0; else { global_nchan = *t_pTag->toInt(); // TAG_FREE(tag); } /* * Proceess each item */ for (k = 0; k < items.size(); k++) { node = items[k]; /* * Complicated procedure for getting the description */ item_desc.clear(); if (node->find_tag(stream, FIFF_NAME, t_pTag)) { item_desc += t_pTag->toString(); } /* * Take the first line of description if it exists */ if (node->find_tag(stream, FIFF_DESCRIPTION, t_pTag)) { desc_tag = t_pTag->toString(); int pos; if((pos = desc_tag.indexOf("\n")) >= 0) desc_tag.truncate(pos); if (!item_desc.isEmpty()) item_desc += " "; item_desc += desc_tag; } /* * Possibility to override number of channels here */ if (!node->find_tag(stream, FIFF_NCHAN, t_pTag)) { item_nchan = global_nchan; } else { item_nchan = *t_pTag->toInt(); } if (item_nchan <= 0) { qCritical("Number of channels incorrectly specified for one of the projection items."); goto bad; } /* * Take care of the channel names */ if (!node->find_tag(stream, FIFF_PROJ_ITEM_CH_NAME_LIST, t_pTag)) goto bad; item_names = FiffStream::split_name_list(t_pTag->toString()); if (item_names.size() != item_nchan) { printf("Channel name list incorrectly specified for proj item # %d",k+1); item_names.clear(); goto bad; } /* * Kind of item */ if (!node->find_tag(stream, FIFF_PROJ_ITEM_KIND, t_pTag)) goto bad; item_kind = *t_pTag->toInt(); /* * How many vectors */ if (!node->find_tag(stream,FIFF_PROJ_ITEM_NVEC, t_pTag)) goto bad; item_nvec = *t_pTag->toInt(); /* * The projection data */ if (!node->find_tag(stream,FIFF_PROJ_ITEM_VECTORS, t_pTag)) goto bad; MatrixXf tmp_item_vectors = t_pTag->toFloatMatrix().transpose(); item_vectors = ALLOC_CMATRIX_23(tmp_item_vectors.rows(),tmp_item_vectors.cols()); fromFloatEigenMatrix_23(tmp_item_vectors, item_vectors); /* * Is this item active? */ if (node->find_tag(stream, FIFF_MNE_PROJ_ITEM_ACTIVE, t_pTag)) { item_active = *t_pTag->toInt(); } else item_active = FALSE; /* * Ready to add */ QStringList emptyList; item = MneNamedMatrix::build_named_matrix(item_nvec,item_nchan,emptyList,item_names,item_vectors); mne_proj_op_add_item_act(op,item,item_kind,item_desc,item_active); delete item; op->items[op->nitems-1]->active_file = item_active; } out : return op; bad : { if(op) delete op; return NULL; } } //************************************************************************************************************* MneProjOp *MneProjOp::mne_read_proj_op(const QString &name) { QFile file(name); FiffStream::SPtr stream(new FiffStream(&file)); if(!stream->open()) return NULL; MneProjOp* res = NULL; FiffDirNode::SPtr t_default; res = mne_read_proj_op_from_node(stream,t_default); stream->close(); return res; } //************************************************************************************************************* void MneProjOp::mne_proj_op_report_data(FILE *out, const char *tag, MneProjOp *op, int list_data, char **exclude, int nexclude) /* * Output info about the projection operator */ { int j,k,p,q; MneProjItem* it; MneNamedMatrix* vecs; int found; if (out == NULL) return; if (op == NULL) return; if (op->nitems <= 0) { fprintf(out,"Empty operator\n"); return; } for (k = 0; k < op->nitems; k++) { it = op->items[k]; if (list_data && tag) fprintf(out,"%s\n",tag); if (tag) fprintf(out,"%s",tag); fprintf(out,"# %d : %s : %d vecs : %d chs %s %s\n", k+1,it->desc.toUtf8().constData(),it->nvec,it->vecs->ncol, it->has_meg ? "MEG" : "EEG", it->active ? "active" : "idle"); if (list_data && tag) fprintf(out,"%s\n",tag); if (list_data) { vecs = op->items[k]->vecs; for (q = 0; q < vecs->ncol; q++) { fprintf(out,"%-10s",vecs->collist[q].toUtf8().constData()); fprintf(out,q < vecs->ncol-1 ? " " : "\n"); } for (p = 0; p < vecs->nrow; p++) for (q = 0; q < vecs->ncol; q++) { for (j = 0, found = 0; j < nexclude; j++) { if (QString::compare(exclude[j],vecs->collist[q]) == 0) { found = 1; break; } } fprintf(out,"%10.5g ",found ? 0.0 : vecs->data[p][q]); fprintf(out,q < vecs->ncol-1 ? " " : "\n"); } if (list_data && tag) fprintf(out,"%s\n",tag); } } return; } //************************************************************************************************************* void MneProjOp::mne_proj_op_report(FILE *out, const char *tag, MneProjOp *op) { mne_proj_op_report_data(out,tag,op, FALSE, NULL, 0); }
27.66884
127
0.499105
Andrey1994
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
7bee476661433ad3fc5b8240c3051a8850334747
2,318
cpp
C++
src/ast_dumper.cpp
steakhal/wcomp
b52c1b77edc8f5242fd08338a9c72e5a9a709a46
[ "MIT" ]
null
null
null
src/ast_dumper.cpp
steakhal/wcomp
b52c1b77edc8f5242fd08338a9c72e5a9a709a46
[ "MIT" ]
null
null
null
src/ast_dumper.cpp
steakhal/wcomp
b52c1b77edc8f5242fd08338a9c72e5a9a709a46
[ "MIT" ]
null
null
null
#include "ast_dumper.h" #include "utility.h" #include <cassert> #include <iostream> #include <variant> std::ostream &ast_dumper::operator()(const ast &x) const noexcept { ast_dumper sub_dumper{os, indent + 2}; os << "program " << x.prog_name << '\n'; sub_dumper(x.syms); os << "begin\n"; sub_dumper(x.stmts); os << "end\n"; return os; } std::ostream &ast_dumper::operator()(const symbols &xs) const noexcept { for (const auto &pair : xs) { const symbol &sym = pair.second; repeat(os, ' ', indent) << (sym.symbol_type == boolean ? "boolean" : "natural") << ' ' << sym.name << '\n'; } return os; } std::ostream &ast_dumper::operator()(const statements &xs) const noexcept { for (const statement &x : xs) std::visit(*this, x); return os; } std::ostream &ast_dumper::operator()(const statement &x) const noexcept { std::visit(*this, x); return os; } std::ostream & ast_dumper::operator()(const invalid_statement &x) const noexcept { assert(false && "Unreachabel!"); return os; } std::ostream &ast_dumper::operator()(const assign_statement &x) const noexcept { repeat(os, ' ', indent) << x.left << " := "; std::visit(*this, *x.right); return os << '\n'; } std::ostream &ast_dumper::operator()(const read_statement &x) const noexcept { return repeat(os, ' ', indent) << "read(" << x.id << ")\n"; } std::ostream &ast_dumper::operator()(const write_statement &x) const noexcept { repeat(os, ' ', indent) << "write("; std::visit(*this, *x.value); return os << ")\n"; } std::ostream &ast_dumper::operator()(const if_statement &x) const noexcept { ast_dumper sub_dumper{os, indent + 2}; repeat(os, ' ', indent) << "if "; std::visit(*this, *x.condition); os << " then\n"; sub_dumper(x.true_branch); if (!x.false_branch.empty()) { repeat(os, ' ', indent) << "else\n"; sub_dumper(x.false_branch); } repeat(os, ' ', indent) << "endif\n"; return os; } std::ostream &ast_dumper::operator()(const while_statement &x) const noexcept { ast_dumper sub_dumper{os, indent + 2}; repeat(os, ' ', indent) << "while "; std::visit(*this, *x.condition); os << " do\n"; sub_dumper(x.body); repeat(os, ' ', indent) << "done\n"; return os; }
27.595238
81
0.599655
steakhal
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
7bf5d81cb14983955e18bd915974857ed5462277
10,598
cc
C++
google/cloud/servicedirectory/internal/registration_logging_decorator.cc
LaudateCorpus1/google-cloud-cpp
a9575c5af5e3938efc71bf5822e79b73027d1f3b
[ "Apache-2.0" ]
80
2017-11-24T00:19:45.000Z
2019-01-25T10:24:33.000Z
google/cloud/servicedirectory/internal/registration_logging_decorator.cc
LaudateCorpus1/google-cloud-cpp
a9575c5af5e3938efc71bf5822e79b73027d1f3b
[ "Apache-2.0" ]
1,579
2017-11-24T01:01:21.000Z
2019-01-28T23:41:21.000Z
google/cloud/servicedirectory/internal/registration_logging_decorator.cc
LaudateCorpus1/google-cloud-cpp
a9575c5af5e3938efc71bf5822e79b73027d1f3b
[ "Apache-2.0" ]
51
2017-11-24T00:56:11.000Z
2019-01-18T20:35:02.000Z
// 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 // // https://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. // Generated by the Codegen C++ plugin. // If you make any local changes, they will be lost. // source: google/cloud/servicedirectory/v1/registration_service.proto #include "google/cloud/servicedirectory/internal/registration_logging_decorator.h" #include "google/cloud/internal/log_wrapper.h" #include "google/cloud/status_or.h" #include <google/cloud/servicedirectory/v1/registration_service.grpc.pb.h> #include <memory> namespace google { namespace cloud { namespace servicedirectory_internal { GOOGLE_CLOUD_CPP_INLINE_NAMESPACE_BEGIN RegistrationServiceLogging::RegistrationServiceLogging( std::shared_ptr<RegistrationServiceStub> child, TracingOptions tracing_options, std::set<std::string> components) : child_(std::move(child)), tracing_options_(std::move(tracing_options)), components_(std::move(components)) {} StatusOr<google::cloud::servicedirectory::v1::Namespace> RegistrationServiceLogging::CreateNamespace( grpc::ClientContext& context, google::cloud::servicedirectory::v1::CreateNamespaceRequest const& request) { return google::cloud::internal::LogWrapper( [this](grpc::ClientContext& context, google::cloud::servicedirectory::v1::CreateNamespaceRequest const& request) { return child_->CreateNamespace(context, request); }, context, request, __func__, tracing_options_); } StatusOr<google::cloud::servicedirectory::v1::ListNamespacesResponse> RegistrationServiceLogging::ListNamespaces( grpc::ClientContext& context, google::cloud::servicedirectory::v1::ListNamespacesRequest const& request) { return google::cloud::internal::LogWrapper( [this](grpc::ClientContext& context, google::cloud::servicedirectory::v1::ListNamespacesRequest const& request) { return child_->ListNamespaces(context, request); }, context, request, __func__, tracing_options_); } StatusOr<google::cloud::servicedirectory::v1::Namespace> RegistrationServiceLogging::GetNamespace( grpc::ClientContext& context, google::cloud::servicedirectory::v1::GetNamespaceRequest const& request) { return google::cloud::internal::LogWrapper( [this](grpc::ClientContext& context, google::cloud::servicedirectory::v1::GetNamespaceRequest const& request) { return child_->GetNamespace(context, request); }, context, request, __func__, tracing_options_); } StatusOr<google::cloud::servicedirectory::v1::Namespace> RegistrationServiceLogging::UpdateNamespace( grpc::ClientContext& context, google::cloud::servicedirectory::v1::UpdateNamespaceRequest const& request) { return google::cloud::internal::LogWrapper( [this](grpc::ClientContext& context, google::cloud::servicedirectory::v1::UpdateNamespaceRequest const& request) { return child_->UpdateNamespace(context, request); }, context, request, __func__, tracing_options_); } Status RegistrationServiceLogging::DeleteNamespace( grpc::ClientContext& context, google::cloud::servicedirectory::v1::DeleteNamespaceRequest const& request) { return google::cloud::internal::LogWrapper( [this](grpc::ClientContext& context, google::cloud::servicedirectory::v1::DeleteNamespaceRequest const& request) { return child_->DeleteNamespace(context, request); }, context, request, __func__, tracing_options_); } StatusOr<google::cloud::servicedirectory::v1::Service> RegistrationServiceLogging::CreateService( grpc::ClientContext& context, google::cloud::servicedirectory::v1::CreateServiceRequest const& request) { return google::cloud::internal::LogWrapper( [this](grpc::ClientContext& context, google::cloud::servicedirectory::v1::CreateServiceRequest const& request) { return child_->CreateService(context, request); }, context, request, __func__, tracing_options_); } StatusOr<google::cloud::servicedirectory::v1::ListServicesResponse> RegistrationServiceLogging::ListServices( grpc::ClientContext& context, google::cloud::servicedirectory::v1::ListServicesRequest const& request) { return google::cloud::internal::LogWrapper( [this](grpc::ClientContext& context, google::cloud::servicedirectory::v1::ListServicesRequest const& request) { return child_->ListServices(context, request); }, context, request, __func__, tracing_options_); } StatusOr<google::cloud::servicedirectory::v1::Service> RegistrationServiceLogging::GetService( grpc::ClientContext& context, google::cloud::servicedirectory::v1::GetServiceRequest const& request) { return google::cloud::internal::LogWrapper( [this](grpc::ClientContext& context, google::cloud::servicedirectory::v1::GetServiceRequest const& request) { return child_->GetService(context, request); }, context, request, __func__, tracing_options_); } StatusOr<google::cloud::servicedirectory::v1::Service> RegistrationServiceLogging::UpdateService( grpc::ClientContext& context, google::cloud::servicedirectory::v1::UpdateServiceRequest const& request) { return google::cloud::internal::LogWrapper( [this](grpc::ClientContext& context, google::cloud::servicedirectory::v1::UpdateServiceRequest const& request) { return child_->UpdateService(context, request); }, context, request, __func__, tracing_options_); } Status RegistrationServiceLogging::DeleteService( grpc::ClientContext& context, google::cloud::servicedirectory::v1::DeleteServiceRequest const& request) { return google::cloud::internal::LogWrapper( [this](grpc::ClientContext& context, google::cloud::servicedirectory::v1::DeleteServiceRequest const& request) { return child_->DeleteService(context, request); }, context, request, __func__, tracing_options_); } StatusOr<google::cloud::servicedirectory::v1::Endpoint> RegistrationServiceLogging::CreateEndpoint( grpc::ClientContext& context, google::cloud::servicedirectory::v1::CreateEndpointRequest const& request) { return google::cloud::internal::LogWrapper( [this](grpc::ClientContext& context, google::cloud::servicedirectory::v1::CreateEndpointRequest const& request) { return child_->CreateEndpoint(context, request); }, context, request, __func__, tracing_options_); } StatusOr<google::cloud::servicedirectory::v1::ListEndpointsResponse> RegistrationServiceLogging::ListEndpoints( grpc::ClientContext& context, google::cloud::servicedirectory::v1::ListEndpointsRequest const& request) { return google::cloud::internal::LogWrapper( [this](grpc::ClientContext& context, google::cloud::servicedirectory::v1::ListEndpointsRequest const& request) { return child_->ListEndpoints(context, request); }, context, request, __func__, tracing_options_); } StatusOr<google::cloud::servicedirectory::v1::Endpoint> RegistrationServiceLogging::GetEndpoint( grpc::ClientContext& context, google::cloud::servicedirectory::v1::GetEndpointRequest const& request) { return google::cloud::internal::LogWrapper( [this](grpc::ClientContext& context, google::cloud::servicedirectory::v1::GetEndpointRequest const& request) { return child_->GetEndpoint(context, request); }, context, request, __func__, tracing_options_); } StatusOr<google::cloud::servicedirectory::v1::Endpoint> RegistrationServiceLogging::UpdateEndpoint( grpc::ClientContext& context, google::cloud::servicedirectory::v1::UpdateEndpointRequest const& request) { return google::cloud::internal::LogWrapper( [this](grpc::ClientContext& context, google::cloud::servicedirectory::v1::UpdateEndpointRequest const& request) { return child_->UpdateEndpoint(context, request); }, context, request, __func__, tracing_options_); } Status RegistrationServiceLogging::DeleteEndpoint( grpc::ClientContext& context, google::cloud::servicedirectory::v1::DeleteEndpointRequest const& request) { return google::cloud::internal::LogWrapper( [this](grpc::ClientContext& context, google::cloud::servicedirectory::v1::DeleteEndpointRequest const& request) { return child_->DeleteEndpoint(context, request); }, context, request, __func__, tracing_options_); } StatusOr<google::iam::v1::Policy> RegistrationServiceLogging::GetIamPolicy( grpc::ClientContext& context, google::iam::v1::GetIamPolicyRequest const& request) { return google::cloud::internal::LogWrapper( [this](grpc::ClientContext& context, google::iam::v1::GetIamPolicyRequest const& request) { return child_->GetIamPolicy(context, request); }, context, request, __func__, tracing_options_); } StatusOr<google::iam::v1::Policy> RegistrationServiceLogging::SetIamPolicy( grpc::ClientContext& context, google::iam::v1::SetIamPolicyRequest const& request) { return google::cloud::internal::LogWrapper( [this](grpc::ClientContext& context, google::iam::v1::SetIamPolicyRequest const& request) { return child_->SetIamPolicy(context, request); }, context, request, __func__, tracing_options_); } StatusOr<google::iam::v1::TestIamPermissionsResponse> RegistrationServiceLogging::TestIamPermissions( grpc::ClientContext& context, google::iam::v1::TestIamPermissionsRequest const& request) { return google::cloud::internal::LogWrapper( [this](grpc::ClientContext& context, google::iam::v1::TestIamPermissionsRequest const& request) { return child_->TestIamPermissions(context, request); }, context, request, __func__, tracing_options_); } GOOGLE_CLOUD_CPP_INLINE_NAMESPACE_END } // namespace servicedirectory_internal } // namespace cloud } // namespace google
44.158333
82
0.723816
LaudateCorpus1
7bf5f708382ae8e594df3687f8fdd31bf1b71cf0
6,652
cpp
C++
examples/lite/cv/test_lite_fsanet.cpp
IgiArdiyanto/litehub
54a43690d80e57f16bea1efc698e7d30f06b9d4f
[ "MIT" ]
null
null
null
examples/lite/cv/test_lite_fsanet.cpp
IgiArdiyanto/litehub
54a43690d80e57f16bea1efc698e7d30f06b9d4f
[ "MIT" ]
null
null
null
examples/lite/cv/test_lite_fsanet.cpp
IgiArdiyanto/litehub
54a43690d80e57f16bea1efc698e7d30f06b9d4f
[ "MIT" ]
null
null
null
// // Created by DefTruth on 2021/6/24. // #include "lite/lite.h" static void test_default() { std::string var_onnx_path = "../../../hub/onnx/cv/fsanet-var.onnx"; std::string conv_onnx_path = "../../../hub/onnx/cv/fsanet-1x1.onnx"; std::string test_img_path = "../../../examples/lite/resources/test_lite_fsanet.jpg"; std::string save_img_path = "../../../logs/test_lite_fsanet.jpg"; lite::cv::face::pose::FSANet *var_fsanet = new lite::cv::face::pose::FSANet(var_onnx_path); lite::cv::face::pose::FSANet *conv_fsanet = new lite::cv::face::pose::FSANet(conv_onnx_path); cv::Mat img_bgr = cv::imread(test_img_path); lite::types::EulerAngles var_euler_angles, conv_euler_angles; // 1. detect euler angles. var_fsanet->detect(img_bgr, var_euler_angles); conv_fsanet->detect(img_bgr, conv_euler_angles); lite::types::EulerAngles euler_angles; euler_angles.yaw = (var_euler_angles.yaw + conv_euler_angles.yaw) / 2.0f; euler_angles.pitch = (var_euler_angles.pitch + conv_euler_angles.pitch) / 2.0f; euler_angles.roll = (var_euler_angles.roll + conv_euler_angles.roll) / 2.0f; euler_angles.flag = var_euler_angles.flag && conv_euler_angles.flag; if (euler_angles.flag) { lite::utils::draw_axis_inplace(img_bgr, euler_angles); cv::imwrite(save_img_path, img_bgr); std::cout << "Default Version" << " yaw: " << euler_angles.yaw << " pitch: " << euler_angles.pitch << " roll: " << euler_angles.roll << std::endl; } delete var_fsanet; delete conv_fsanet; } static void test_onnxruntime() { #ifdef ENABLE_ONNXRUNTIME std::string var_onnx_path = "../../../hub/onnx/cv/fsanet-var.onnx"; std::string conv_onnx_path = "../../../hub/onnx/cv/fsanet-1x1.onnx"; std::string test_img_path = "../../../examples/lite/resources/test_lite_fsanet.jpg"; std::string save_img_path = "../../../logs/test_fsanet_onnx.jpg"; lite::onnxruntime::cv::face::pose::FSANet *var_fsanet = new lite::onnxruntime::cv::face::pose::FSANet(var_onnx_path); lite::onnxruntime::cv::face::pose::FSANet *conv_fsanet = new lite::onnxruntime::cv::face::pose::FSANet(conv_onnx_path); cv::Mat img_bgr = cv::imread(test_img_path); lite::types::EulerAngles var_euler_angles, conv_euler_angles; // 1. detect euler angles. var_fsanet->detect(img_bgr, var_euler_angles); conv_fsanet->detect(img_bgr, conv_euler_angles); lite::types::EulerAngles euler_angles; euler_angles.yaw = (var_euler_angles.yaw + conv_euler_angles.yaw) / 2.0f; euler_angles.pitch = (var_euler_angles.pitch + conv_euler_angles.pitch) / 2.0f; euler_angles.roll = (var_euler_angles.roll + conv_euler_angles.roll) / 2.0f; euler_angles.flag = var_euler_angles.flag && conv_euler_angles.flag; if (euler_angles.flag) { lite::utils::draw_axis_inplace(img_bgr, euler_angles); cv::imwrite(save_img_path, img_bgr); std::cout << "ONNXRuntime Version" << " yaw: " << euler_angles.yaw << " pitch: " << euler_angles.pitch << " roll: " << euler_angles.roll << std::endl; } delete var_fsanet; delete conv_fsanet; #endif } static void test_mnn() { #ifdef ENABLE_MNN std::string var_mnn_path = "../../../hub/mnn/cv/fsanet-var.mnn"; std::string conv_mnn_path = "../../../hub/mnn/cv/fsanet-1x1.mnn"; std::string test_img_path = "../../../examples/lite/resources/test_lite_fsanet.jpg"; std::string save_img_path = "../../../logs/test_fsanet_mnn.jpg"; lite::mnn::cv::face::pose::FSANet *var_fsanet = new lite::mnn::cv::face::pose::FSANet(var_mnn_path); lite::mnn::cv::face::pose::FSANet *conv_fsanet = new lite::mnn::cv::face::pose::FSANet(conv_mnn_path); cv::Mat img_bgr = cv::imread(test_img_path); lite::types::EulerAngles var_euler_angles, conv_euler_angles; // 1. detect euler angles. var_fsanet->detect(img_bgr, var_euler_angles); conv_fsanet->detect(img_bgr, conv_euler_angles); lite::types::EulerAngles euler_angles; euler_angles.yaw = (var_euler_angles.yaw + conv_euler_angles.yaw) / 2.0f; euler_angles.pitch = (var_euler_angles.pitch + conv_euler_angles.pitch) / 2.0f; euler_angles.roll = (var_euler_angles.roll + conv_euler_angles.roll) / 2.0f; euler_angles.flag = var_euler_angles.flag && conv_euler_angles.flag; if (euler_angles.flag) { lite::utils::draw_axis_inplace(img_bgr, euler_angles); cv::imwrite(save_img_path, img_bgr); std::cout << "MNN Version" << " yaw: " << euler_angles.yaw << " pitch: " << euler_angles.pitch << " roll: " << euler_angles.roll << std::endl; } delete var_fsanet; delete conv_fsanet; #endif } static void test_ncnn() { #ifdef ENABLE_NCNN #endif } static void test_tnn() { #ifdef ENABLE_TNN std::string var_proto_path = "../../../hub/tnn/cv/fsanet-var.opt.tnnproto"; std::string var_model_path = "../../../hub/tnn/cv/fsanet-var.opt.tnnmodel"; std::string conv_proto_path = "../../../hub/tnn/cv/fsanet-1x1.opt.tnnproto"; std::string conv_model_path = "../../../hub/tnn/cv/fsanet-1x1.opt.tnnmodel"; std::string test_img_path = "../../../examples/lite/resources/test_lite_fsanet.jpg"; std::string save_img_path = "../../../logs/test_fsanet_tnn.jpg"; lite::tnn::cv::face::pose::FSANet *var_fsanet = new lite::tnn::cv::face::pose::FSANet(var_proto_path, var_model_path); lite::tnn::cv::face::pose::FSANet *conv_fsanet = new lite::tnn::cv::face::pose::FSANet(conv_proto_path, conv_model_path); cv::Mat img_bgr = cv::imread(test_img_path); lite::types::EulerAngles var_euler_angles, conv_euler_angles; // 1. detect euler angles. var_fsanet->detect(img_bgr, var_euler_angles); conv_fsanet->detect(img_bgr, conv_euler_angles); lite::types::EulerAngles euler_angles; euler_angles.yaw = (var_euler_angles.yaw + conv_euler_angles.yaw) / 2.0f; euler_angles.pitch = (var_euler_angles.pitch + conv_euler_angles.pitch) / 2.0f; euler_angles.roll = (var_euler_angles.roll + conv_euler_angles.roll) / 2.0f; euler_angles.flag = var_euler_angles.flag && conv_euler_angles.flag; if (euler_angles.flag) { lite::utils::draw_axis_inplace(img_bgr, euler_angles); cv::imwrite(save_img_path, img_bgr); std::cout << "TNN Version" << " yaw: " << euler_angles.yaw << " pitch: " << euler_angles.pitch << " roll: " << euler_angles.roll << std::endl; } delete var_fsanet; delete conv_fsanet; #endif } static void test_lite() { test_default(); test_onnxruntime(); test_mnn(); test_ncnn(); test_tnn(); } int main(__unused int argc, __unused char *argv[]) { test_lite(); return 0; }
34.112821
95
0.683403
IgiArdiyanto
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
7bf8bdbb2422e2230a356459c9ca154c7515aae5
1,851
cc
C++
zircon/system/ulib/storage/operation/operation.cc
wwjiang007/fuchsia-1
0db66b52b5bcd3e27c8b8c2163925309e8522f94
[ "BSD-2-Clause" ]
210
2019-02-05T12:45:09.000Z
2022-03-28T07:59:06.000Z
zircon/system/ulib/storage/operation/operation.cc
wwjiang007/fuchsia-1
0db66b52b5bcd3e27c8b8c2163925309e8522f94
[ "BSD-2-Clause" ]
56
2021-06-03T03:16:25.000Z
2022-03-20T01:07:44.000Z
zircon/system/ulib/storage/operation/operation.cc
wwjiang007/fuchsia-1
0db66b52b5bcd3e27c8b8c2163925309e8522f94
[ "BSD-2-Clause" ]
73
2019-03-06T18:55:23.000Z
2022-03-26T12:04:51.000Z
// Copyright 2019 The Fuchsia Authors. All rights reserved. // Use of this source code is governed by a BSD-style license that can be // found in the LICENSE file. #include <safemath/checked_math.h> #include <storage/operation/operation.h> #ifdef __Fuchsia__ #include <storage/operation/unbuffered_operation.h> #endif #include <ostream> namespace storage { const char* OperationTypeToString(OperationType type) { switch (type) { case OperationType::kRead: return "kRead"; case OperationType::kWrite: return "kWrite"; case OperationType::kTrim: return "kTrim"; default: return "<unknown>"; } } template <typename T> uint64_t BlockCountImpl(fbl::Span<const T> operations) { safemath::CheckedNumeric<uint64_t> total_length = 0; for (const auto& operation : operations) { total_length += operation.op.length; } return total_length.ValueOrDie(); } uint64_t BlockCount(fbl::Span<const BufferedOperation> operations) { return BlockCountImpl(operations); } #ifdef __Fuchsia__ uint64_t BlockCount(fbl::Span<const UnbufferedOperation> operations) { return BlockCountImpl(operations); } #endif std::ostream& operator<<(std::ostream& stream, const BufferedOperation& operation) { stream << "BufferedOperation {type: " << OperationTypeToString(operation.op.type) << " vmo_offset: " << operation.op.vmo_offset << " dev_offset: " << operation.op.dev_offset << " length: " << operation.op.length << "}"; return stream; } std::ostream& operator<<(std::ostream& stream, const fbl::Span<const BufferedOperation>& operations) { stream << "["; for (size_t i = 0; i < operations.size(); ++i) { if (i < operations.size() - 1) { stream << ", "; } stream << operations[i]; } stream << "]"; return stream; } } // namespace storage
27.220588
100
0.680173
wwjiang007
7bfa4757f6bc63cc5625b6fd0d9ef1b0bb824b29
2,830
cc
C++
src/main/bandlog.cc
bandprotocol/bandprotocol
4a5861d14dba6a69af0e7ce9fc142beb9315dcb4
[ "Apache-2.0" ]
2
2020-02-13T17:50:46.000Z
2020-07-21T15:18:14.000Z
src/main/bandlog.cc
bandprotocol/bandchain-legacy
4a5861d14dba6a69af0e7ce9fc142beb9315dcb4
[ "Apache-2.0" ]
null
null
null
src/main/bandlog.cc
bandprotocol/bandchain-legacy
4a5861d14dba6a69af0e7ce9fc142beb9315dcb4
[ "Apache-2.0" ]
null
null
null
// Licensed to the Apache Software Foundation (ASF) under one // or more contributor license agreements. See the LICENSE file // distributed with this work for additional information // regarding copyright ownership. The ASF licenses this file // to you under the Apache License, Version 2.0 (the // "License"); you may not use this file except in compliance // with the License. You may obtain a copy of the License at // // http://www.apache.org/licenses/LICENSE-2.0 // // Unless required by applicable law or agreed to in writing, // software distributed under the License is distributed on an // "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY // KIND, either express or implied. See the License for the // specific language governing permissions and limitations // under the License. #include "listener/logging.h" #include "listener/manager.h" #include "listener/primary.h" #include "net/server.h" #include "net/tmapp.h" #include "store/storage.h" #include "store/storage_map.h" #include "util/cli.h" class BandLoggingApplication : public TendermintApplication { public: BandLoggingApplication(ListenerManager& _manager) : manager(_manager) { } std::string get_name() const final { return "band-logging"; } std::string get_version() const final { return "n/a"; } std::string get_current_app_hash() const final { return ""; } void init(const std::vector<std::pair<VerifyKey, uint64_t>>& _validators, const std::string& init_state) final { manager.initChain(gsl::as_bytes(gsl::make_span(init_state))); } std::string query(const std::string& path, const std::string& data) final { return ListenerManager::abi(); } void check(const std::string& msg_raw) final { manager.checkTransaction(gsl::as_bytes(gsl::make_span(msg_raw))); } std::string apply(const std::string& msg_raw) final { return manager.applyTransaction(gsl::as_bytes(gsl::make_span(msg_raw))); } void begin_block(uint64_t block_time, const Address& block_proposer) final { manager.beginBlock(block_time, block_proposer); } std::vector<std::pair<VerifyKey, uint64_t>> end_block() final { manager.endBlock(); return {}; } void commit_block() final { manager.commitBlock(); } private: ListenerManager& manager; }; CmdArg<int> port("p,port", "the port on which tmapp connects", "26658"); int main(int argc, char* argv[]) { Cmd cmd("Band ACBI application", argc, argv); boost::asio::io_service service; ListenerManager manager; StorageMap storage; manager.setPrimary(std::make_unique<PrimaryListener>(storage)); manager.addListener(std::make_unique<LoggingListener>()); BandLoggingApplication app(manager); Server server(service, app, +port); server.start(); service.run(); return 0; }
25.267857
76
0.711661
bandprotocol
7bfa51cd85ab7ce66cf0773192b7639a6a65b034
9,917
cc
C++
application/common/application_file_util.cc
shaochangbin/crosswalk
a4e189b2ab8ca33555a90601476d59c9c291942f
[ "BSD-3-Clause" ]
1
2019-01-16T06:49:57.000Z
2019-01-16T06:49:57.000Z
application/common/application_file_util.cc
shaochangbin/crosswalk
a4e189b2ab8ca33555a90601476d59c9c291942f
[ "BSD-3-Clause" ]
null
null
null
application/common/application_file_util.cc
shaochangbin/crosswalk
a4e189b2ab8ca33555a90601476d59c9c291942f
[ "BSD-3-Clause" ]
null
null
null
// Copyright (c) 2013 The Chromium Authors. All rights reserved. // Use of this source code is governed by a BSD-style license that can be // found in the LICENSE file. #include "xwalk/application/common/application_file_util.h" #include <algorithm> #include <map> #include <vector> #include "base/command_line.h" #include "base/files/file_path.h" #include "base/files/scoped_temp_dir.h" #include "base/file_util.h" #include "base/json/json_file_value_serializer.h" #include "base/logging.h" #include "base/metrics/histogram.h" #include "base/path_service.h" #include "base/strings/stringprintf.h" #include "base/strings/utf_string_conversions.h" #include "base/threading/thread_restrictions.h" #include "net/base/escape.h" #include "net/base/file_stream.h" #include "third_party/libxml/src/include/libxml/tree.h" #include "ui/base/l10n/l10n_util.h" #include "xwalk/application/common/application_data.h" #include "xwalk/application/common/application_manifest_constants.h" #include "xwalk/application/common/constants.h" #include "xwalk/application/common/install_warning.h" #include "xwalk/application/common/manifest.h" #include "xwalk/application/common/manifest_handler.h" namespace errors = xwalk::application_manifest_errors; namespace keys = xwalk::application_manifest_keys; namespace widget_keys = xwalk::application_widget_keys; namespace { const char kAttributePrefix[] = "@"; const char kNamespaceKey[] = "@namespace"; const char kTextKey[] = "#text"; } namespace xwalk { namespace application { inline char* ToCharPointer(void* ptr) { return reinterpret_cast<char *>(ptr); } inline const char* ToConstCharPointer(const void* ptr) { return reinterpret_cast<const char*>(ptr); } // Load XML node into Dictionary structure. // The keys for the XML node to Dictionary mapping are described below: // XML Dictionary // <e></e> "e":{"#text": ""} // <e>textA</e> "e":{"#text":"textA"} // <e attr="val">textA</e> "e":{ "@attr":"val", "#text": "textA"} // <e> <a>textA</a> <b>textB</b> </e> "e":{ // "a":{"#text":"textA"} // "b":{"#text":"textB"} // } // <e> <a>textX</a> <a>textY</a> </e> "e":{ // "a":[ {"#text":"textX"}, // {"#text":"textY"}] // } // <e> textX <a>textY</a> </e> "e":{ "#text":"textX", // "a":{"#text":"textY"} // } // // For elements that are specified under a namespace, the dictionary // will add '@namespace' key for them, e.g., // XML: // <e xmln="linkA" xmlns:N="LinkB"> // <sub-e1> text1 </sub-e> // <N:sub-e2 text2 /> // </e> // will be saved in Dictionary as, // "e":{ // "#text": "", // "@namespace": "linkA" // "sub-e1": { // "#text": "text1", // "@namespace": "linkA" // }, // "sub-e2": { // "#text":"text2" // "@namespace": "linkB" // } // } base::DictionaryValue* LoadXMLNode(xmlNode* root) { scoped_ptr<base::DictionaryValue> value(new base::DictionaryValue); if (root->type != XML_ELEMENT_NODE) return NULL; xmlAttr* prop = NULL; for (prop = root->properties; prop; prop = prop->next) { char* prop_value = ToCharPointer(xmlNodeListGetString( root->doc, prop->children, 1)); value->SetString( std::string(kAttributePrefix) + ToConstCharPointer(prop->name), prop_value); xmlFree(prop_value); } if (root->ns) value->SetString(kNamespaceKey, ToConstCharPointer(root->ns->href)); for (xmlNode* node = root->children; node; node = node->next) { std::string sub_node_name(ToConstCharPointer(node->name)); base::DictionaryValue* sub_value = LoadXMLNode(node); if (!sub_value) continue; if (!value->HasKey(sub_node_name)) { value->Set(sub_node_name, sub_value); continue; } base::Value* temp; value->Get(sub_node_name, &temp); DCHECK(temp); if (temp->IsType(base::Value::TYPE_LIST)) { base::ListValue* list; temp->GetAsList(&list); list->Append(sub_value); } else { DCHECK(temp->IsType(base::Value::TYPE_DICTIONARY)); base::DictionaryValue* dict; temp->GetAsDictionary(&dict); base::DictionaryValue* prev_value(new base::DictionaryValue()); prev_value = dict->DeepCopy(); base::ListValue* list = new base::ListValue(); list->Append(prev_value); list->Append(sub_value); value->Set(sub_node_name, list); } } char* text = ToCharPointer( xmlNodeListGetString(root->doc, root->children, 1)); if (!text) { value->SetString(kTextKey, std::string()); } else { value->SetString(kTextKey, text); } xmlFree(text); return value.release(); } scoped_refptr<ApplicationData> LoadApplication( const base::FilePath& application_path, Manifest::SourceType source_type, std::string* error) { return LoadApplication(application_path, std::string(), source_type, error); } scoped_refptr<ApplicationData> LoadApplication( const base::FilePath& application_path, const std::string& application_id, Manifest::SourceType source_type, std::string* error) { scoped_ptr<base::DictionaryValue> manifest( LoadManifest(application_path, error)); if (!manifest.get()) return NULL; scoped_refptr<ApplicationData> application = ApplicationData::Create( application_path, source_type, *manifest, application_id, error); if (!application.get()) return NULL; std::vector<InstallWarning> warnings; ManifestHandlerRegistry* registry = manifest->HasKey(widget_keys::kWidgetKey) ? ManifestHandlerRegistry::GetInstance(Manifest::TYPE_WGT) : ManifestHandlerRegistry::GetInstance(Manifest::TYPE_XPK); if (!registry->ValidateAppManifest(application, error, &warnings)) return NULL; if (!warnings.empty()) { LOG(WARNING) << "There are some warnings when validating the application " << application->ID(); } return application; } static base::DictionaryValue* LoadManifestXpk( const base::FilePath& manifest_path, std::string* error) { JSONFileValueSerializer serializer(manifest_path); scoped_ptr<base::Value> root(serializer.Deserialize(NULL, error)); if (!root.get()) { if (error->empty()) { // If |error| is empty, than the file could not be read. // It would be cleaner to have the JSON reader give a specific error // in this case, but other code tests for a file error with // error->empty(). For now, be consistent. *error = base::StringPrintf("%s", errors::kManifestUnreadable); } else { *error = base::StringPrintf("%s %s", errors::kManifestParseError, error->c_str()); } return NULL; } if (!root->IsType(base::Value::TYPE_DICTIONARY)) { *error = base::StringPrintf("%s", errors::kManifestUnreadable); return NULL; } base::DictionaryValue* dv = static_cast<base::DictionaryValue*>(root.release()); #if defined(OS_TIZEN) // Ignore any Tizen application ID, as this is automatically generated. dv->Remove(keys::kTizenAppIdKey, NULL); #endif return dv; } static base::DictionaryValue* LoadManifestWgt( const base::FilePath& manifest_path, std::string* error) { xmlDoc * doc = NULL; xmlNode* root_node = NULL; doc = xmlReadFile(manifest_path.MaybeAsASCII().c_str(), NULL, 0); if (doc == NULL) { *error = base::StringPrintf("%s", errors::kManifestUnreadable); return NULL; } root_node = xmlDocGetRootElement(doc); base::DictionaryValue* dv = LoadXMLNode(root_node); scoped_ptr<base::DictionaryValue> result(new base::DictionaryValue); if (dv) result->Set(ToConstCharPointer(root_node->name), dv); return result.release(); } base::DictionaryValue* LoadManifest(const base::FilePath& application_path, std::string* error) { base::FilePath manifest_path; manifest_path = application_path.Append(kManifestXpkFilename); if (base::PathExists(manifest_path)) return LoadManifestXpk(manifest_path, error); manifest_path = application_path.Append(kManifestWgtFilename); if (base::PathExists(manifest_path)) return LoadManifestWgt(manifest_path, error); *error = base::StringPrintf("%s", errors::kManifestUnreadable); return NULL; } base::FilePath ApplicationURLToRelativeFilePath(const GURL& url) { std::string url_path = url.path(); if (url_path.empty() || url_path[0] != '/') return base::FilePath(); // Drop the leading slashes and convert %-encoded UTF8 to regular UTF8. std::string file_path = net::UnescapeURLComponent(url_path, net::UnescapeRule::SPACES | net::UnescapeRule::URL_SPECIAL_CHARS); size_t skip = file_path.find_first_not_of("/\\"); if (skip != file_path.npos) file_path = file_path.substr(skip); base::FilePath path = #if defined(OS_POSIX) base::FilePath(file_path); #elif defined(OS_WIN) base::FilePath(base::UTF8ToWide(file_path)); #else base::FilePath(); NOTIMPLEMENTED(); #endif // It's still possible for someone to construct an annoying URL whose path // would still wind up not being considered relative at this point. // For example: app://id/c:////foo.html if (path.IsAbsolute()) return base::FilePath(); return path; } } // namespace application } // namespace xwalk
32.837748
78
0.628618
shaochangbin
7bfb31c23111aa6afa3fb5e2af8b708873ef2520
8,880
cpp
C++
Controller/Old versions/Controller_v3.0/Controller.cpp
RickVM/Trees_of_Life
382d23ed49edaafee923d1acc85e562fb7f12111
[ "Apache-2.0" ]
null
null
null
Controller/Old versions/Controller_v3.0/Controller.cpp
RickVM/Trees_of_Life
382d23ed49edaafee923d1acc85e562fb7f12111
[ "Apache-2.0" ]
null
null
null
Controller/Old versions/Controller_v3.0/Controller.cpp
RickVM/Trees_of_Life
382d23ed49edaafee923d1acc85e562fb7f12111
[ "Apache-2.0" ]
1
2018-06-21T13:12:44.000Z
2018-06-21T13:12:44.000Z
/* Main class for the logic of the program Cycle time for a loop with ultrasoon is ~500 millis Cycle time with buttons is ~75 millis */ #include "Controller.h" #define SYNC_DELAY 1000 #define PULSE_TIME 2500 #define CYCLES 5 /* Controller constructor Expects an Input object for acces to the value of the buttons/ultrasoons/etc.. Expects a number for selecting a communication methode with the slaves Expects the amount of animators (slaves) that it controlles And expect and id that is needed for communication over the I2C bus */ Controller::Controller(Input* input, int comMethod, int numAnimators, int id) { this->_input = input; this->communicationMethod = comMethod; this->numberAnimators = numAnimators; this->syncPreset = 15000; this->id = id; } /* This function always needs to be called when using this class it functions like the setup function in an ino file */ void Controller::Begin() { switch (communicationMethod) { case 1://Serial COM = new UART(BAUD_RATE); break; case 2://I2C COM = new I2C(this->id); break; default://Default is I2C COM = new I2C(this->id); break; }; COM->Begin();//Begin communication this->Reset();//Reset/init all the vars } /* Function that holds the logic/flow of the program */ void Controller::Logic(void) { //First check if syning has failed (somebody let go) if (syncingFailed) { this->syncingFailedLogic(); } else if (this->syncWait) //Check for syncing { this->waitSyncLogic(); } //Else check if syncing has started else if (syncing) { this->syncLogic(); } //If not syncing look if all inputs are high to start syncing else if (this->checkSync())//All active, do sync { //Start with the sync delay loop this->oldSyncTime = millis(); this->syncTime = millis(); Serial.println("Entering sync wait loop"); this->syncWait = true; } //Else check if one of the inputs is high else if (_input->getInputHigh(0) == true || _input->getInputHigh(1) == true || _input->getInputHigh(2) == true || _input->getInputHigh(3) == true || _input->getInputHigh(4) == true || _input->getInputHigh(5) == true) { this->Pulse(); } else { /* Idle, rest state To inplement */ } } /* Function that inplements the logic for when syncing fails. */ void Controller::syncingFailedLogic(void) { this->LetGo(); delay(10000); syncingFailed = false; this->Reset(); } /* */ void Controller::waitSyncLogic(void) { //Check if somebody let go if (this->checkLetGo()) { //Count until 5 cycles then, a cycle is 500 millis if (this->countLetGo == CYCLES) { this->syncing = false; this->syncingFailed = true; this->countLetGo = 0; } else { Serial.print("Cycle : "); Serial.println(countLetGo); this->countLetGo++; this->syncPreset += 500; } } else { this->syncTime = millis(); this->Pulse(); if (this->syncTime - this-> oldSyncTime > SYNC_DELAY) { this->syncing = true; this->Pulse();//Pulse to update old time values this->calculateAdjustments();//Calculate the difference here this->syncTime = millis(); this->oldSyncTime = millis(); this->syncWait = false; Serial.println("Exit sync wait loop"); } } } void Controller::syncLogic(void) { //Check if somebody let go if (this->checkLetGo()) { //Count until 5 cycles then if (this->countLetGo == CYCLES) { this->syncing = false; this->syncingFailed = true; this->countLetGo = 0; } else { Serial.print("Cycle : "); Serial.println(countLetGo); Serial.print("Millis : "); Serial.println(millis()); this->countLetGo++; switch (_input->getMethode()) { case 1://Buttons adjustime is the 75millis this->syncPreset += 75; break; case 2://Ultrasonic, adjusttime is than 500 millis this->syncPreset += 500; break; default: //Not inplemented break; }; } } else { //Execute sync this->countLetGo = 0; this->syncTime = millis(); //Check if sync is complete if (this->syncTime - this->oldSyncTime >= this->syncPreset) { //Sync completed this->Flash(); this->Reset(); delay(12000);//12 seconds } else { this->Pulse(); } } } void Controller::calculateAdjustments(void) { long average = 0; for (int i = 0; i < this->numberAnimators; i++) { average += oldTime[i]; } average /= this->numberAnimators; for (int k = 0; k < this->numberAnimators; k++) { adjustmentTimes[k] = average - oldTime[k]; adjustmentSteps[k] = adjustmentTimes[k] / 10; pulseTime[k] += adjustmentSteps[k]; } } bool Controller::checkLetGo() { bool rv = false; int temp = 0; for (int i = 0; i < this->numberAnimators; i++) { temp += _input->getInputHigh(i); } if (temp < numberAnimators) { delay(150); _input->readInputs();//Read the inputs again temp = 0; for (int i = 0; i < this->numberAnimators; i++) { temp += _input->getInputHigh(i); } if (temp < this->numberAnimators) { rv = true; } } return rv; } bool Controller::checkSync() { bool rv = false; int temp = 0; for (int i = 0; i < this->numberAnimators; i++) { temp += _input->getInputHigh(i); } if (temp == this->numberAnimators) { delay(25); _input->readInputs(); temp = 0; for (int i = 0; i < this->numberAnimators; i++) { temp += _input->getInputHigh(i); } if (temp == this->numberAnimators) { rv = true; } } return rv; } void Controller::syncStop(void) { this->currentTime = millis(); /* for (int i = 1; i < this->numberAnimators; i++) { finalAdjustment[i] = oldTime[0] - oldTime[i]; Serial.print("Time difference: "); Serial.print(finalAdjustment[i]); Serial.print(" of : "); Serial.println(i); } if (this->checkSyncStop()) { for (int i = 0; i < 6; i++) { pulseTime[i] = PULSE_TIME; } for (int k = 1; k < 6; k++) { pulseTime[k] += finalAdjustment[k]; finalSync[k] = true; } } */ long timeDifference = oldTime[0] - oldTime[1]; if (timeDifference < 20 && timeDifference > -20 && timeDifference != 0)//Stop adjusting whenever the difference between pulses is less than 20 { for (int i = 0; i < 6; i ++) { pulseTime[i] = PULSE_TIME; } //Add a final correction to get them perfectly synced. } } void Controller::Pulse(void)//Two inputs at the moment { this->syncStop(); for (int i = 0; i < this->numberAnimators; i++) { if (_input->getInputHigh(i)) { if (this->currentTime - this->oldTime[i] > this->pulseTime[i]) { switch (_input->getInputClassification(i)) { case 1: this->M = "pulse5"; break; case 2: this->M = "pulse6"; break; case 3: this->M = "pulse7"; break; case 4: this->M = "pulse8"; break; case 5: this->M = "pulse9"; break; case 6: this->M = "pulse10"; break; case 7: this->M = "pulse11"; break; }; COM->sendCommand((i + 1), M); this->oldTime[i] = this->currentTime; /*if (finalAdjustment[i] < 20 && finalAdjustment[i] > -20 && finalAdjustment[i] != 0)//Stop adjusting whenever the difference between pulses is less than 20 { for (int i = 0; i < 6; i ++) { pulseTime[i] = PULSE_TIME; } //Add a final correction to get them perfectly synced. }*/ } } } } void Controller::LetGo(void) { COM->sendCommand(1, "backward");//Teensy 1 COM->sendCommand(3, "backward");//Teensy 2 COM->sendCommand(5, "backward");//Teensy 3 /*for (int i = 1; i <= this->numberAnimators; i++) { COM->sendCommand(i, "backward"); }*/ } void Controller::Flash(void) { //Send to all three teensy's COM->sendCommand(1, "flash");//Teensy 1 COM->sendCommand(3, "flash");//Teensy 2 COM->sendCommand(5, "flash");//Teensy 3 /* for (int i = 1; i <= this->numberAnimators; i++) { COM->sendCommand(i, "flash"); }*/ } void Controller::Reset(void) { for (int i = 0; i < 6; i++) { this->pulseTime[i] = PULSE_TIME; this->oldTime[i] = 0; this->finalAdjustment[i] = 0; } this->syncing = false; this->syncingFailed = false; this->syncTime = 0; this->oldSyncTime = 0; this->syncWait = false; this->M = ""; this->countLetGo = 0; }
22.769231
164
0.574212
RickVM
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, &params); 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, &params); 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, &params); 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, &params); 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, &params); 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, &params); 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, &params); 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, &params); 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
d013345da77aeed792c509e8cbeb89bc35f8c658
26,314
cpp
C++
tests/test_metadata.cpp
ekg/gbwt
52229f7402467762e73a032f70614adc17c97392
[ "MIT" ]
null
null
null
tests/test_metadata.cpp
ekg/gbwt
52229f7402467762e73a032f70614adc17c97392
[ "MIT" ]
null
null
null
tests/test_metadata.cpp
ekg/gbwt
52229f7402467762e73a032f70614adc17c97392
[ "MIT" ]
null
null
null
/* Copyright (c) 2019 Jouni Siren Author: Jouni Siren <jouni.siren@iki.fi> 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 <gtest/gtest.h> #include <sstream> #include <gbwt/metadata.h> using namespace gbwt; namespace { //------------------------------------------------------------------------------ class MetadataTest : public ::testing::Test { public: std::vector<std::string> keys, first_keys, second_keys, third_keys; std::vector<PathName> paths; size_type path_samples, path_haplotypes, path_contigs; MetadataTest() { Verbosity::set(Verbosity::SILENT); } void SetUp() override { this->keys = { "first", "second", "third", "fourth", "fifth" }; this->first_keys = { "first", "second", "third" }; this->second_keys = { "fourth", "fifth", "sixth" }; this->third_keys = { "first", "fourth", "fifth" }; this->paths = { { static_cast<size_type>(0), static_cast<size_type>(0), static_cast<size_type>(0), static_cast<size_type>(0) }, { static_cast<size_type>(0), static_cast<size_type>(0), static_cast<size_type>(1), static_cast<size_type>(0) }, { static_cast<size_type>(1), static_cast<size_type>(0), static_cast<size_type>(0), static_cast<size_type>(0) }, { static_cast<size_type>(1), static_cast<size_type>(0), static_cast<size_type>(1), static_cast<size_type>(0) }, { static_cast<size_type>(1), static_cast<size_type>(1), static_cast<size_type>(0), static_cast<size_type>(0) }, { static_cast<size_type>(1), static_cast<size_type>(1), static_cast<size_type>(1), static_cast<size_type>(0) }, { static_cast<size_type>(2), static_cast<size_type>(0), static_cast<size_type>(0), static_cast<size_type>(0) }, { static_cast<size_type>(2), static_cast<size_type>(0), static_cast<size_type>(0), static_cast<size_type>(1) }, { static_cast<size_type>(2), static_cast<size_type>(0), static_cast<size_type>(1), static_cast<size_type>(0) }, { static_cast<size_type>(2), static_cast<size_type>(0), static_cast<size_type>(1), static_cast<size_type>(1) } }; this->path_samples = 3; this->path_haplotypes = 6; this->path_contigs = 2; } void testMergeConstructor(const Metadata& first, const Metadata& second, const Metadata& correct_result, bool same_samples, bool same_contigs, const std::string& test_name) const { std::vector<const Metadata*> sources { &first, &second }; Metadata constructed(sources, same_samples, same_contigs); EXPECT_EQ(constructed, correct_result) << "Merge constructor does not work correctly " << test_name; } // first[start, limit) should be equal to second. bool sameSamples(const Metadata& first, const Metadata& second, size_type start, size_type limit) const { for(size_type i = start; i < limit; i++) { if(first.sample(i) != second.sample(i - start)) { return false; } } return true; } void compareSamples(const Metadata& first, const Metadata& second, bool same_samples) const { std::stringstream stream; stream << "(" << (first.hasSampleNames() ? "names" : "nonames") << ", " << (second.hasSampleNames() ? "names" : "nonames") << ", " << (same_samples ? "same" : "not_same") << ")"; std::string test_name = stream.str(); bool merge_by_names = first.hasSampleNames() & second.hasSampleNames(); size_type correct_count = ((same_samples & !merge_by_names) ? first.samples() : first.samples() + second.samples()); Metadata merged = first; merged.merge(second, same_samples, false); ASSERT_TRUE(merged.check()) << "Merged metadata object is not in a valid state " << test_name; ASSERT_EQ(merged.samples(), correct_count) << "Expected " << correct_count << " samples, got " << merged.samples() << " " << test_name; testMergeConstructor(first, second, merged, same_samples, false, test_name); if(merge_by_names) { ASSERT_TRUE(merged.hasSampleNames()) << "Merged metadata object does not have sample names " << test_name; bool correct_samples = true; correct_samples &= sameSamples(merged, first, 0, first.samples()); correct_samples &= sameSamples(merged, second, first.samples(), first.samples() + second.samples()); EXPECT_TRUE(correct_samples) << "Sample names were not merged " << test_name; } else if(same_samples) { bool check_sample_names = false, correct_samples = true; if(first.hasSampleNames()) { correct_samples = sameSamples(merged, first, 0, merged.samples()); check_sample_names = true; } else if(second.hasSampleNames()) { correct_samples = sameSamples(merged, second, 0, merged.samples()); check_sample_names = true; } if(check_sample_names) { ASSERT_TRUE(merged.hasSampleNames()) << "Merged metadata object does not have sample names " << test_name; EXPECT_TRUE(correct_samples) << "Sample names were not merged " << test_name; } else { ASSERT_FALSE(merged.hasSampleNames()) << "Merged metadata object has sample names " << test_name; } } else { ASSERT_FALSE(merged.hasSampleNames()) << "Merged metadata object has sample names " << test_name; } } // first[start, limit) should be equal to second. bool sameContigs(const Metadata& first, const Metadata& second, size_type start, size_type limit) const { for(size_type i = start; i < limit; i++) { if(first.contig(i) != second.contig(i - start)) { return false; } } return true; } void compareContigs(const Metadata& first, const Metadata& second, bool same_contigs) const { std::stringstream stream; stream << "(" << (first.hasContigNames() ? "names" : "nonames") << ", " << (second.hasContigNames() ? "names" : "nonames") << ", " << (same_contigs ? "same" : "not_same") << ")"; std::string test_name = stream.str(); bool merge_by_names = first.hasContigNames() & second.hasContigNames(); size_type correct_count = ((same_contigs & !merge_by_names) ? first.contigs() : first.contigs() + second.contigs()); Metadata merged = first; merged.merge(second, false, same_contigs); ASSERT_TRUE(merged.check()) << "Merged metadata object is not in a valid state " << test_name; ASSERT_EQ(merged.contigs(), correct_count) << "Expected " << correct_count << " contigs, got " << merged.contigs() << " " << test_name; testMergeConstructor(first, second, merged, false, same_contigs, test_name); if(merge_by_names) { ASSERT_TRUE(merged.hasContigNames()) << "Merged metadata object does not have contig names " << test_name; bool correct_contigs = true; correct_contigs &= sameContigs(merged, first, 0, first.contigs()); correct_contigs &= sameContigs(merged, second, first.contigs(), first.contigs() + second.contigs()); EXPECT_TRUE(correct_contigs) << "Contig names were not merged " << test_name; } else if(same_contigs) { bool check_contig_names = false, correct_contigs = true; if(first.hasContigNames()) { correct_contigs = sameContigs(merged, first, 0, merged.contigs()); check_contig_names = true; } else if(second.hasContigNames()) { correct_contigs = sameContigs(merged, second, 0, merged.contigs()); check_contig_names = true; } if(check_contig_names) { ASSERT_TRUE(merged.hasContigNames()) << "Merged metadata object does not have contig names " << test_name; EXPECT_TRUE(correct_contigs) << "Contig names were not merged " << test_name; } else { ASSERT_FALSE(merged.hasContigNames()) << "Merged metadata object has contig names " << test_name; } } else { ASSERT_FALSE(merged.hasContigNames()) << "Merged metadata object has contig names " << test_name; } } void comparePaths(const Metadata& first, const Metadata& second, bool same) const { std::stringstream stream; stream << "(" << (first.hasSampleNames() ? "names" : "nonames") << ", " << (second.hasSampleNames() ? "names" : "nonames") << ", " << (same ? "same" : "not_same") << ")"; std::string test_name = stream.str(); bool merge_by_names = first.hasSampleNames() & second.hasSampleNames(); size_type correct_count = first.paths() + second.paths(); Metadata merged = first; merged.merge(second, same, same); ASSERT_TRUE(merged.check()) << "Merged metadata object is not in a valid state " << test_name; ASSERT_TRUE(merged.hasPathNames()) << "Merged metadata object does not have path names" << test_name; ASSERT_EQ(merged.paths(), correct_count) << "Expected " << correct_count << " paths, got " << merged.paths() << " " << test_name; testMergeConstructor(first, second, merged, same, same, test_name); if(merge_by_names) { bool correct_paths = true; for(size_type i = 0; i < first.paths(); i++) { PathName path = first.path(i); path.sample = merged.sample(first.sample(path.sample)); path.contig = merged.contig(first.contig(path.contig)); correct_paths &= (merged.path(i) == path); } for(size_type i = first.paths(); i < first.paths() + second.paths(); i++) { PathName path = second.path(i - first.paths()); path.sample = merged.sample(second.sample(path.sample)); path.contig = merged.contig(second.contig(path.contig)); correct_paths &= (merged.path(i) == path); } EXPECT_TRUE(correct_paths) << "Path names were not merged correctly " << test_name; } else if(same) { bool correct_paths = true; for(size_type i = 0; i < first.paths(); i++) { correct_paths &= (merged.path(i) == first.path(i)); } for(size_type i = first.paths(); i < first.paths() + second.paths(); i++) { correct_paths &= (merged.path(i) == second.path(i - first.paths())); } EXPECT_TRUE(correct_paths) << "Path names were not merged correctly " << test_name; } else { bool correct_paths = true; for(size_type i = 0; i < first.paths(); i++) { for(size_type i = 0; i < first.paths(); i++) { correct_paths &= (merged.path(i) == first.path(i)); } } for(size_type i = first.paths(); i < first.paths() + second.paths(); i++) { PathName path = second.path(i - first.paths()); path.sample += first.samples(); path.contig += first.contigs(); correct_paths &= (merged.path(i) == path); } EXPECT_TRUE(correct_paths) << "Path names were not merged correctly " << test_name; } } }; //------------------------------------------------------------------------------ TEST_F(MetadataTest, BasicTest) { // Empty metadata. Metadata empty; ASSERT_TRUE(empty.check()) << "Empty metadata object is not in a valid state"; EXPECT_EQ(empty.samples(), static_cast<size_type>(0)) << "Empty metadata object contains samples"; EXPECT_EQ(empty.haplotypes(), static_cast<size_type>(0)) << "Empty metadata object contains haplotypes"; EXPECT_EQ(empty.contigs(), static_cast<size_type>(0)) << "Empty metadata object contains contigs"; EXPECT_FALSE(empty.hasSampleNames()) << "Empty metadata object contains sample names"; EXPECT_FALSE(empty.hasContigNames()) << "Empty metadata object contains contig names"; EXPECT_FALSE(empty.hasPathNames()) << "Empty metadata object contains path names"; // Set counts. Metadata nonempty; size_type samples = 1, haplotypes = 2, contigs = 3; nonempty.setSamples(samples); nonempty.setHaplotypes(haplotypes); nonempty.setContigs(contigs); ASSERT_TRUE(nonempty.check()) << "Metadata object is not in a valid state"; EXPECT_EQ(nonempty.samples(), samples) << "Expected " << samples << " samples, got " << nonempty.samples(); EXPECT_EQ(nonempty.haplotypes(), haplotypes) << "Expected " << haplotypes << " haplotypes, got " << nonempty.haplotypes(); EXPECT_EQ(nonempty.contigs(), contigs) << "Expected " << contigs << " contigs, got " << nonempty.contigs(); // Comparisons and clear(). EXPECT_NE(empty, nonempty) << "Empty and nonempty metadata objects are equal"; nonempty.clear(); EXPECT_EQ(empty, nonempty) << "Cleared metadata object is not empty"; } //------------------------------------------------------------------------------ TEST_F(MetadataTest, Samples) { Metadata metadata; metadata.setSamples(keys); ASSERT_TRUE(metadata.check()) << "Metadata object with sample names is not in a valid state"; EXPECT_TRUE(metadata.hasSampleNames()) << "Metadata object does not contain sample names"; ASSERT_EQ(metadata.samples(), static_cast<size_type>(keys.size())) << "Sample count is incorrect"; bool ok = true; for(size_type i = 0; i < keys.size(); i++) { ok &= (metadata.sample(i) == keys[i]); ok &= (metadata.sample(keys[i]) == i); } EXPECT_TRUE(ok) << "Sample names are incorrect"; { std::vector<std::string> first_half(keys.begin(), keys.begin() + keys.size() / 2); std::vector<std::string> second_half(keys.begin() + keys.size() / 2, keys.end()); Metadata partial; partial.setSamples(first_half); partial.addSamples(second_half); EXPECT_EQ(metadata, partial) << "addSamples() does not work correctly"; } metadata.clearSampleNames(); ASSERT_TRUE(metadata.check()) << "Metadata object is not in a valid state after clearing sample names"; EXPECT_FALSE(metadata.hasSampleNames()) << "Metadata object contains sample names"; EXPECT_EQ(metadata.samples(), static_cast<size_type>(keys.size())) << "Clearing sample names also cleared sample count"; } TEST_F(MetadataTest, RemoveSample) { for(size_type removed_key = 0; removed_key <= keys.size(); removed_key++) { Metadata metadata; metadata.setSamples(keys); std::vector<size_type> removed = metadata.removeSample(removed_key); size_type correct_size = (removed_key >= keys.size() ? keys.size() : keys.size() - 1); EXPECT_TRUE(removed.empty()) << "Path names were removed from an object without path names"; ASSERT_EQ(metadata.samples(), correct_size) << "Expected " << correct_size << " samples after removing key " << removed_key << ", got " << metadata.samples(); bool ok = true; for(size_type i = 0; i < keys.size(); i++) { if(i < removed_key) { ok &= (metadata.sample(i) == keys[i]); ok &= (metadata.sample(keys[i]) == i); } else if(i == removed_key) { ok &= (metadata.sample(keys[i]) == metadata.samples()); } else { ok &= (metadata.sample(i - 1) == keys[i]); ok &= (metadata.sample(keys[i]) == i - 1); } } EXPECT_TRUE(ok) << "Metadata object does not contain the correct samples after removing sample " << removed_key; } } TEST_F(MetadataTest, SampleMerging) { Metadata first_names, first_nonames, second_names, second_nonames; first_names.setSamples(first_keys); first_nonames.setSamples(first_keys.size()); second_names.setSamples(second_keys); second_nonames.setSamples(second_keys.size()); compareSamples(first_nonames, second_nonames, false); compareSamples(first_nonames, second_nonames, true); compareSamples(first_names, second_nonames, false); compareSamples(first_names, second_nonames, true); compareSamples(first_nonames, second_names, false); compareSamples(first_nonames, second_names, true); compareSamples(first_names, second_names, false); compareSamples(first_names, second_names, true); } //------------------------------------------------------------------------------ TEST_F(MetadataTest, Contigs) { Metadata metadata; metadata.setContigs(keys); ASSERT_TRUE(metadata.check()) << "Metadata object with contig names is not in a valid state"; EXPECT_TRUE(metadata.hasContigNames()) << "Metadata object does not contain contig names"; ASSERT_EQ(metadata.contigs(), static_cast<size_type>(keys.size())) << "Contig count is incorrect"; bool ok = true; for(size_type i = 0; i < keys.size(); i++) { ok &= (metadata.contig(i) == keys[i]); ok &= (metadata.contig(keys[i]) == i); } EXPECT_TRUE(ok) << "Contig names are incorrect"; { std::vector<std::string> first_half(keys.begin(), keys.begin() + keys.size() / 2); std::vector<std::string> second_half(keys.begin() + keys.size() / 2, keys.end()); Metadata partial; partial.setContigs(first_half); partial.addContigs(second_half); EXPECT_EQ(metadata, partial) << "addContigs() does not work correctly"; } metadata.clearContigNames(); ASSERT_TRUE(metadata.check()) << "Metadata object is not in a valid state after clearing contig names"; EXPECT_FALSE(metadata.hasContigNames()) << "Metadata object contains contig names"; EXPECT_EQ(metadata.contigs(), static_cast<size_type>(keys.size())) << "Clearing contig names also cleared contig count"; } TEST_F(MetadataTest, RemoveContig) { for(size_type removed_key = 0; removed_key <= keys.size(); removed_key++) { Metadata metadata; metadata.setContigs(keys); std::vector<size_type> removed = metadata.removeContig(removed_key); size_type correct_size = (removed_key >= keys.size() ? keys.size() : keys.size() - 1); EXPECT_TRUE(removed.empty()) << "Path names were removed from an object without path names"; ASSERT_EQ(metadata.contigs(), correct_size) << "Expected " << correct_size << " contigs after removing key " << removed_key << ", got " << metadata.contigs(); bool ok = true; for(size_type i = 0; i < keys.size(); i++) { if(i < removed_key) { ok &= (metadata.contig(i) == keys[i]); ok &= (metadata.contig(keys[i]) == i); } else if(i == removed_key) { ok &= (metadata.contig(keys[i]) == metadata.contigs()); } else { ok &= (metadata.contig(i - 1) == keys[i]); ok &= (metadata.contig(keys[i]) == i - 1); } } EXPECT_TRUE(ok) << "Metadata object does not contain the correct contigs after removing contig " << removed_key; } } TEST_F(MetadataTest, ContigMerging) { Metadata first_names, first_nonames, second_names, second_nonames; first_names.setContigs(first_keys); first_nonames.setContigs(first_keys.size()); second_names.setContigs(second_keys); second_nonames.setContigs(second_keys.size()); compareContigs(first_nonames, second_nonames, false); compareContigs(first_nonames, second_nonames, true); compareContigs(first_names, second_nonames, false); compareContigs(first_names, second_nonames, true); compareContigs(first_nonames, second_names, false); compareContigs(first_nonames, second_names, true); compareContigs(first_names, second_names, false); compareContigs(first_names, second_names, true); } //------------------------------------------------------------------------------ TEST_F(MetadataTest, Paths) { Metadata metadata; for(const PathName& path : paths) { metadata.addPath(path); } ASSERT_TRUE(metadata.check()) << "Metadata object with path names is not in a valid state"; EXPECT_TRUE(metadata.hasPathNames()) << "Metadata object does not contain path names"; ASSERT_EQ(metadata.paths(), static_cast<size_type>(paths.size())) << "Path count is incorrect"; bool ok = true; for(size_type i = 0; i < keys.size(); i++) { ok &= (metadata.path(i) == paths[i]); } EXPECT_TRUE(ok) << "Path names are incorrect"; // Find paths by sample and contig. { std::vector<size_type> correct_paths; for(size_type i = 0; i < paths.size(); i++) { if(paths[i].sample == 1 && paths[i].contig == 0) { correct_paths.push_back(i); } } bool ok = (correct_paths == metadata.findPaths(1, 0)); EXPECT_TRUE(ok) << "Path selection by sample and contig failed"; } // Find paths by sample. { std::vector<size_type> correct_paths; for(size_type i = 0; i < paths.size(); i++) { if(paths[i].sample == 1) { correct_paths.push_back(i); } } bool ok = (correct_paths == metadata.pathsForSample(1)); EXPECT_TRUE(ok) << "Path selection by sample failed"; } // Find paths by contig. { std::vector<size_type> correct_paths; for(size_type i = 0; i < paths.size(); i++) { if(paths[i].contig == 1) { correct_paths.push_back(i); } } bool ok = (correct_paths == metadata.pathsForContig(1)); EXPECT_TRUE(ok) << "Path selection by contig failed"; } metadata.clearPathNames(); ASSERT_TRUE(metadata.check()) << "Metadata object is not in a valid state after clearing path names"; EXPECT_FALSE(metadata.hasPathNames()) << "Metadata object contains path names"; } TEST_F(MetadataTest, RemovePaths) { Metadata metadata; metadata.setSamples(path_samples); metadata.setHaplotypes(path_haplotypes); metadata.setContigs(path_contigs); for(const PathName& path : paths) { metadata.addPath(path); } for(size_type sample = 0; sample <= metadata.samples(); sample++) { Metadata curr = metadata; size_type correct_samples = (sample >= metadata.samples() ? path_samples : path_samples - 1); std::vector<size_type> removed = curr.removeSample(sample); ASSERT_EQ(curr.samples(), correct_samples) << "Expected " << correct_samples << " samples after removing sample " << sample << ", got " << curr.samples(); bool ok = true; size_type path_tail = 0, removed_tail = 0; for(size_type i = 0; i < paths.size(); i++) { if(paths[i].sample == sample) { if(removed_tail >= removed.size() || removed[removed_tail] != i) { ok = false; break; } removed_tail++; } else { PathName expected = paths[i]; if(expected.sample > sample) { expected.sample--; } if(path_tail >= curr.paths() || curr.path(path_tail) != expected) { ok = false; break; } path_tail++; } } ASSERT_TRUE(ok) << "Metadata object does not contain the correct contigs after removing sample " << sample; EXPECT_EQ(path_tail, curr.paths()) << "Expected " << path_tail << " paths after removing sample " << sample << ", got " << curr.paths(); EXPECT_EQ(removed_tail, removed.size()) << "Expected " << removed_tail << " removed paths after removing sample " << sample << ", got " << removed.size(); } for(size_type contig = 0; contig <= metadata.contigs(); contig++) { Metadata curr = metadata; size_type correct_contigs = (contig >= metadata.contigs() ? path_contigs : path_contigs - 1); std::vector<size_type> removed = curr.removeContig(contig); ASSERT_EQ(curr.contigs(), correct_contigs) << "Expected " << correct_contigs << " contigs after removing contig " << contig << ", got " << curr.contigs(); bool ok = true; size_type path_tail = 0, removed_tail = 0; for(size_type i = 0; i < paths.size(); i++) { if(paths[i].contig == contig) { if(removed_tail >= removed.size() || removed[removed_tail] != i) { ok = false; break; } removed_tail++; } else { PathName expected = paths[i]; if(expected.contig > contig) { expected.contig--; } if(path_tail >= curr.paths() || curr.path(path_tail) != expected) { ok = false; break; } path_tail++; } } ASSERT_TRUE(ok) << "Metadata object does not contain the correct contigs after removing contig " << contig; EXPECT_EQ(path_tail, curr.paths()) << "Expected " << path_tail << " paths after removing contig " << contig << ", got " << curr.paths(); EXPECT_EQ(removed_tail, removed.size()) << "Expected " << removed_tail << " removed paths after removing contig " << contig << ", got " << removed.size(); } } TEST_F(MetadataTest, PathMerging) { Metadata first_names, first_nonames, third_names, third_nonames; first_names.setSamples(first_keys); first_nonames.setSamples(first_keys.size()); first_names.setContigs(first_keys); first_nonames.setContigs(first_keys.size()); third_names.setSamples(third_keys); third_nonames.setSamples(third_keys.size()); third_names.setContigs(third_keys); third_nonames.setContigs(third_keys.size()); for(const PathName& path : paths) { first_names.addPath(path); first_nonames.addPath(path); third_names.addPath(path); third_nonames.addPath(path); } comparePaths(first_names, third_names, false); comparePaths(first_nonames, third_nonames, true); comparePaths(first_nonames, third_nonames, false); } TEST_F(MetadataTest, Serialization) { Metadata original; original.setSamples(std::vector<std::string>(keys.begin(), keys.begin() + path_samples)); original.setHaplotypes(path_haplotypes); original.setContigs(std::vector<std::string>(keys.begin(), keys.begin() + path_contigs)); for(const PathName& path : paths) { original.addPath(path); } std::string filename = TempFile::getName("Metadata"); sdsl::store_to_file(original, filename); Metadata copy; sdsl::load_from_file(copy, filename); TempFile::remove(filename); EXPECT_EQ(original, copy) << "Metadata serialization failed"; } //------------------------------------------------------------------------------ } // namespace
39.80938
180
0.650984
ekg
d01616fcd8ada5730cbf95a7701f9ee717d7d94f
779
cpp
C++
src/planner/binder/statement/bind_create_view.cpp
rainmaple/duckdb
d3df77ba6740b8b089bddbfef77e2b969245b5cf
[ "MIT" ]
null
null
null
src/planner/binder/statement/bind_create_view.cpp
rainmaple/duckdb
d3df77ba6740b8b089bddbfef77e2b969245b5cf
[ "MIT" ]
null
null
null
src/planner/binder/statement/bind_create_view.cpp
rainmaple/duckdb
d3df77ba6740b8b089bddbfef77e2b969245b5cf
[ "MIT" ]
null
null
null
#include "duckdb/planner/binder.hpp" #include "duckdb/parser/parsed_data/create_view_info.hpp" #include "duckdb/planner/parsed_data/bound_create_info.hpp" #include "duckdb/planner/bound_query_node.hpp" using namespace duckdb; using namespace std; unique_ptr<BoundCreateInfo> Binder::BindCreateViewInfo(unique_ptr<CreateInfo> info) { auto &base = (CreateViewInfo &)*info; auto result = make_unique<BoundCreateInfo>(move(info)); // bind the view as if it were a query so we can catch errors // note that we bind a copy and don't actually use the bind result auto copy = base.query->Copy(); auto query_node = Bind(*copy); if (base.aliases.size() > query_node->names.size()) { throw BinderException("More VIEW aliases than columns in query result"); } return result; }
35.409091
85
0.761232
rainmaple
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, &copy[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
d01ba605563cc5e9f1652e2bf91b435a0c79c0d7
93,629
cpp
C++
core.cpp
harshmittal2210/FPGA-Implementation-of-Handnumber-Recognition-Using-ANN
1533df8ab295da9295ba6551c7014e28d464b697
[ "MIT" ]
null
null
null
core.cpp
harshmittal2210/FPGA-Implementation-of-Handnumber-Recognition-Using-ANN
1533df8ab295da9295ba6551c7014e28d464b697
[ "MIT" ]
null
null
null
core.cpp
harshmittal2210/FPGA-Implementation-of-Handnumber-Recognition-Using-ANN
1533df8ab295da9295ba6551c7014e28d464b697
[ "MIT" ]
null
null
null
// Include HLS Math Lib to use calculate exponential function #include "hls_math.h" // This is the top function defined during project initialization int hand_num_nn(float X[401],int y){ /*Define PRAGMA * Input is taken form port X via BRAM * AXI_LITE Interface is used to control IP core */ #pragma HLS INTERFACE s_axilite port=return bundle=CRTL_BUS #pragma HLS INTERFACE s_axilite port=y bundle=CRTL_BUS #pragma HLS INTERFACE bram port=X // Weights of the trained Network float theta1[25][401] = {{0.79525,-0.013186,0.062409,-0.044509,-0.090421,-0.02066,0.028493,-0.035273,-0.010794,-0.079325,0.009332,-0.018573,-0.019726,-0.067484,-0.041991,0.0032306,0.048036,-0.071518,-0.012392,-0.053174,-0.015236,0.017315,-0.029389,0.053527,-0.08646,0.019188,-0.010101,-0.061025,-0.071432,-0.018168,-0.057551,-0.0051736,-0.064138,0.098295,0.027534,-0.03936,0.01671,0.045463,0.090493,-0.014183,0.032043,-0.047699,-0.071392,-0.014546,0.062656,0.047896,0.029028,0.051059,0.0032922,0.028078,-0.023712,0.038519,0.019693,0.048234,0.088918,-0.051981,-0.0050824,-0.067336,-0.057162,0.010397,-0.083534,-0.076339,-0.011453,0.034815,0.0535,0.037446,0.040143,0.1616,0.010158,0.085522,0.021715,-0.097327,-0.065661,0.038653,0.089062,0.081466,-0.086644,0.015739,-0.038422,0.070546,0.056457,0.07963,-0.080077,-0.060292,-0.041891,0.086748,0.058901,0.11221,0.069031,-0.034305,0.01036,-0.19853,-0.34325,-0.27183,-0.073561,0.13695,-0.25008,-0.21056,0.062413,0.15565,0.0058195,-0.068472,-0.045984,-0.069169,0.05337,0.028522,0.0929,0.20382,0.089495,0.06841,0.10896,-0.48333,-0.68843,-0.72852,-0.56128,-0.15184,-0.10204,-0.10075,0.14027,0.22497,0.076486,0.06948,-0.084076,-0.080026,-0.055344,-0.0084606,0.076688,0.22528,0.1314,0.39608,0.24129,-0.019929,-0.57697,-1.1267,-1.0255,-0.4406,-0.11897,-0.026791,0.10547,0.14978,0.058181,0.022098,0.016187,-0.17503,-0.13756,-0.1265,-0.0038878,0.077479,0.3963,0.42659,0.40016,0.12658,-0.38858,-1.3841,-1.2127,-0.73513,-0.24626,0.023168,0.13101,0.10594,-0.019002,-0.056809,-0.020144,-0.044452,-0.23096,-0.19179,0.073197,0.25522,0.067965,0.36733,0.31069,0.10404,-0.46787,-1.0409,-0.84109,-0.58018,-0.11749,0.14783,0.02605,0.13701,-0.042427,0.042893,0.0040329,-0.093264,-0.16548,-0.2408,0.05815,0.025463,0.0098919,0.2567,0.26068,0.4421,0.095577,-0.29793,-0.20364,-0.026988,0.04291,0.093591,0.22436,0.2062,0.082374,0.084333,-0.09075,-0.32449,-0.3992,-0.43678,-0.057613,-0.10633,0.14613,0.66289,0.89759,0.67396,0.37342,0.12038,0.16271,0.018659,0.17415,0.47558,0.33857,0.18968,-0.059562,0.025622,-0.1576,-0.30057,-0.45965,-0.36914,0.12865,0.37418,0.655,1.0004,0.98248,0.49509,0.29265,0.21747,-0.152,-0.29531,0.30227,0.61195,0.47889,0.23492,0.035965,0.097218,-0.021744,-0.32128,-0.3926,-0.48767,0.077369,0.26822,0.59197,0.79246,0.49261,0.16448,-0.065632,-0.072465,-0.40907,-0.37812,0.23796,0.43701,0.18464,0.11042,-0.015028,0.036171,-0.14638,-0.1521,-0.19869,-0.27114,0.13473,0.12607,0.1404,0.27792,-0.0072303,-0.1046,-0.17536,-0.45113,-0.7033,-0.48561,-0.055066,0.084471,0.077183,-0.03779,0.0023753,-0.028656,-0.048721,-0.070614,-0.094014,-0.047539,0.24441,0.25614,-0.020389,-0.23407,-0.24417,-0.08237,-0.20189,-0.44652,-0.30187,-0.25873,-0.26341,-0.054585,-0.07364,0.0014277,-0.076387,-0.054983,0.048588,-0.0051606,-0.0095027,0.071814,0.10349,0.12073,-0.18014,-0.45701,-0.35594,-0.24913,-0.20485,-0.36545,-0.32854,-0.20015,-0.1075,-0.12959,-0.026112,0.048408,0.093657,0.053527,0.044732,-0.019666,0.095447,0.17704,0.29468,0.063606,-0.12021,-0.33152,-0.27494,-0.26771,-0.30619,-0.36852,-0.31239,-0.23889,-0.084958,-0.026968,-0.045933,-0.039866,0.027309,0.033001,-0.089841,0.088802,0.030861,0.013998,0.094103,0.15197,0.015453,-0.086788,-0.22153,-0.044445,-0.054273,-0.16244,-0.16279,-0.046936,-0.066725,-0.037688,0.080976,0.0073714,-0.054964,-0.0046647,0.00081418,0.039037,-0.06522,-0.0089403,0.059828,0.14354,-0.055958,0.0053117,-0.034299,-0.058665,-0.14341,-0.11837,-0.10228,-0.089947,0.072219,0.066958,0.0088271,0.0050489,-0.069573,-0.057523,0.078738,-0.083921,-0.077982,-0.048029,0.086084,0.088282,0.044018,-0.034596,-0.029742,0.073053,-0.025389,0.0087582,-0.045372,0.029139,0.011723,0.044485,0.011023,0.0084699,0.0074441},{-1.0125,0.0085855,0.086709,-0.090986,0.029352,-0.065619,-0.01848,0.070487,-0.0089384,0.058043,0.055573,0.074885,0.071439,-0.074173,-0.090791,-0.064861,0.030095,-0.080179,0.028323,-0.022064,-0.0090628,-0.0018681,0.05848,-0.042779,0.02377,-0.0058049,-0.035314,-0.0033104,0.13509,-0.024865,0.072038,0.017727,0.077052,0.013314,-0.077044,0.0066796,0.0063225,-0.0034487,-0.06153,-0.059325,0.069287,0.051799,0.079317,0.050483,0.054112,-0.031764,-0.079516,0.035123,0.1454,0.12021,0.16143,0.039586,0.082304,-0.1597,-0.24089,-0.3443,-0.11488,0.044301,-0.16407,-0.06992,0.060498,-0.074494,0.032305,0.03282,0.0046227,-0.12168,-0.017404,0.032461,0.29549,0.29334,0.12315,0.13515,-0.0036873,-0.096051,-0.39866,-0.3239,-0.06485,-0.14394,-0.17459,-0.012136,0.040761,0.047785,0.025773,-0.068056,0.08689,-0.035646,0.10754,-0.0080679,-0.0050831,0.17083,0.023853,0.28278,0.45461,0.074027,-0.52161,-0.27704,0.17099,0.12739,-0.32387,-0.096084,-0.0036303,0.057797,-0.086533,-0.028562,-0.081323,-0.10659,0.12459,0.043781,0.11163,0.096376,-0.24411,0.18755,0.6255,0.2543,-0.46421,-0.67187,0.035807,0.088605,-0.39224,-0.096438,-0.013139,-0.080897,-0.022991,-0.076413,0.17008,-0.05729,0.033269,0.31521,0.46628,0.21325,-0.16095,-0.38082,0.1225,0.7872,0.40691,-0.35441,0.13838,0.019103,-0.30247,-0.041162,0.038509,-0.054375,-0.039067,-0.014587,0.19827,-0.24984,0.004762,0.1719,0.23992,-0.053899,-0.2062,-0.56091,-0.21227,1.2829,0.98884,0.058142,0.10886,0.070136,-0.0088823,0.1136,0.051382,0.036679,-0.034343,0.0108,-0.070679,-0.42679,-0.26497,0.12457,0.13532,-0.23379,-0.47751,-0.28925,0.18216,1.1431,0.54512,0.43677,0.30405,0.21173,-0.015044,0.14207,0.13004,0.016691,0.094566,-0.00060362,-0.10908,-0.078401,-0.022627,0.36122,0.27955,-0.29764,-0.43205,-0.20943,0.066353,0.4101,0.053068,0.30774,0.507,0.38905,0.019764,0.059161,0.19157,-0.021862,0.20785,0.24874,0.18082,-0.12683,-0.0020059,0.54538,0.16515,-0.35405,-0.26322,-0.041087,-0.032971,0.079187,-0.13554,0.095771,0.43108,0.1676,0.16287,0.26157,0.034271,0.021089,0.21536,0.24728,-0.044643,-0.27162,-0.08293,0.011616,-0.43489,-0.34814,-0.19954,-0.084775,-0.037086,-0.3345,-0.099847,0.17135,0.23056,0.19183,0.34901,0.3098,0.034062,-0.052034,0.10791,0.13692,-0.035931,-0.091603,-0.20352,-0.21625,0.0081519,-0.18039,-0.49603,-0.0055786,0.23857,-0.23235,-0.17657,-0.10313,-0.082752,-0.10611,0.028018,0.15906,0.14103,-0.058739,0.15304,0.21892,0.21026,0.075731,-0.46705,-0.057702,0.37732,0.22776,-0.22128,-0.18265,0.16512,-0.15108,-0.3946,-0.088247,-0.14719,-0.12603,-0.068661,-0.023155,-0.052361,-0.051838,0.15271,0.17412,0.1127,-0.18654,-0.46742,-0.20023,0.456,0.48007,0.13394,0.089618,0.08291,-0.040086,-0.2499,-0.34743,-0.19084,-0.16323,-0.05107,0.043431,-0.01036,-0.063239,0.021104,0.0097262,0.051489,-0.026644,-0.062164,-0.04864,0.46161,0.94754,0.61597,0.24313,0.21741,-0.18858,-0.18683,-0.14575,-0.087143,-0.071542,-0.10363,-0.072901,0.026815,0.034601,-0.025738,-0.15434,-0.14388,-0.031002,-0.178,0.013936,0.41988,0.82587,0.74478,0.44255,0.23838,0.067166,0.017355,0.017042,-0.062542,-0.17715,-0.080158,-0.030985,-0.022932,-0.077989,-0.041732,0.011767,-0.084348,-0.028975,-0.31255,-0.46429,-0.068804,0.17883,0.17952,0.056441,-0.097944,-0.062837,0.086959,-0.00093591,-0.10213,0.015469,-0.06828,-0.077986,-0.067974,-0.019285,0.0027959,0.077739,-0.067365,-0.064531,-0.2017,-0.34985,-0.2556,-0.1472,-0.085878,0.059523,0.062621,0.00757,0.027197,0.05033,0.067077,0.097869,-0.05018,0.032235,0.061305,-0.041104,-0.042847,-0.0058565,-0.055907,0.0071284,-0.041332,0.0069389,0.02908,0.080763,-0.076401,-0.077103,0.090687,0.10193,-0.090184,0.087875,0.022652,-0.028625,0.034145,-0.059818,-0.081842},{-0.40627,0.0031848,0.0049798,-0.089653,0.057638,-0.028575,0.090097,-0.058493,0.043877,-0.077573,0.0016013,-0.054326,-0.016754,-0.014593,0.066206,0.093251,-0.073847,-0.058704,-0.005976,0.031796,-0.08921,-0.08522,0.07285,-0.016245,-0.031858,-0.090222,-0.039156,-0.081738,-0.031126,0.059269,0.02902,0.04809,-0.016716,0.053794,0.021939,-0.065853,-0.085891,0.030981,0.0077058,0.029742,-0.054048,0.025648,0.077873,0.031941,0.0097972,0.038527,-0.030679,0.086057,0.04687,0.066088,-0.074788,-0.10686,-0.081438,-0.046235,0.050717,-0.051261,-0.091976,0.05654,0.02194,0.047178,-0.011176,0.020796,-0.083741,-0.015418,0.0059118,0.076497,0.1217,0.15298,0.20788,0.24842,0.10905,0.033286,-0.12017,-0.13142,-0.078699,0.035818,0.034728,-0.035768,-0.0025685,-0.048367,0.019659,-0.055744,-0.0471,0.083373,0.021457,0.13659,0.078226,0.1363,0.46302,0.44121,0.32889,0.024464,-0.096265,-0.57361,-0.48161,-0.25837,-0.056658,-0.042984,-0.0074751,0.0012684,0.015085,0.05161,0.025009,0.073495,0.06081,0.068866,0.10809,0.14597,0.49098,0.36034,0.32888,-0.1128,-0.23784,-0.51176,-0.87948,-0.58298,-0.25416,0.0012253,0.25252,0.046946,-0.018515,-0.041035,0.085763,0.048492,0.084984,0.079646,0.24465,0.23772,0.54582,0.42073,0.27396,-0.22325,-0.28362,-0.10726,-0.31875,-0.22793,0.049872,0.24108,0.36056,0.20307,0.025597,-0.087552,-0.017979,-0.10262,-0.10439,0.21791,0.11565,0.28199,0.50254,0.49062,0.13268,-0.21088,-0.18696,0.027593,-0.17406,-0.32733,-0.14747,0.31675,0.33011,0.17219,0.11991,0.026746,-0.0010744,-0.12715,-0.15733,-0.014086,0.013989,0.17368,0.25147,0.37074,0.20983,-0.36758,-0.36605,-0.022587,0.029569,0.010801,-0.001793,0.37086,0.47696,0.20565,0.11306,-0.090124,0.018704,-0.19236,-0.33945,0.031141,0.18934,0.27232,0.19038,0.39797,-0.16726,-0.75448,-0.56517,-0.34153,-0.36383,0.043995,0.27397,0.4034,0.34558,0.24123,0.013141,0.028009,0.0015526,-0.10826,-0.19917,0.18644,0.41341,0.039223,-0.22365,0.068003,-0.16309,-0.38372,-0.44502,-0.23003,-0.32113,0.26899,0.31864,0.16623,0.14273,0.22577,-0.0034985,-0.1036,0.11526,0.022409,-0.15826,0.062735,0.54525,0.1409,-0.23603,0.18191,0.46476,0.45713,0.41007,0.26701,0.31907,0.34747,0.35287,0.012126,0.1708,0.13751,0.025662,-0.085813,0.11999,0.17911,0.22545,0.24887,0.26605,-0.07891,0.10347,0.95886,0.86089,0.41588,0.27996,0.16225,0.039548,0.21798,0.17591,0.0022224,0.096104,0.0080182,-0.052838,-0.055045,-0.0005131,0.17352,0.20007,-0.075789,0.028133,-0.052082,0.43209,0.83736,0.44909,0.17735,0.12285,0.050247,-0.0059065,0.0019557,0.09562,-0.13184,-0.052803,0.11183,0.076594,0.081611,0.11356,0.18493,0.066618,-0.056476,-0.2708,-0.049908,0.27074,0.408,0.27786,0.26302,0.051625,0.054138,-0.062429,0.12141,0.066024,0.065088,0.029727,0.079981,0.057439,-0.01136,-0.053427,0.014293,0.026409,-0.25655,-0.40028,-0.31057,0.038005,0.13871,0.20382,0.46219,0.12524,-0.23734,-0.21284,-0.14044,-0.064177,0.0048226,0.020775,0.058313,-0.077833,0.050495,-0.076933,-0.074029,-0.012645,0.016365,-0.17932,-0.11037,0.17554,0.30132,0.28074,0.31528,0.22212,-0.13733,-0.33565,-0.22059,-0.093851,0.0043242,0.049254,0.07111,-0.065805,-0.051226,0.0028116,-0.067865,0.046782,-0.16138,-0.21767,-0.1693,-0.050857,0.010201,0.084997,0.071129,-0.023144,-0.17861,-0.12662,-0.10118,-0.096334,-0.036003,-0.02448,-0.040641,0.077024,-0.024399,0.0057067,0.057304,0.020358,-0.098434,-0.12588,-0.16597,-0.052539,-0.15147,-0.10506,-0.027009,-0.18364,-0.017424,0.015747,-0.021516,-0.00046606,-0.021192,0.058277,0.091082,-0.019817,-0.083413,-0.02422,-0.059556,-0.011228,0.015338,0.024603,-0.021507,0.085953,-0.093331,-0.077287,-0.073177,0.010486,-0.021421,-0.076621,0.070939,-0.064721,-0.010248,-0.040433,-0.066342,-0.079492},{-1.5541,-0.033613,-0.091377,0.074222,0.0043461,-0.01813,-0.059488,0.030801,-0.019652,-0.083313,0.075264,0.026808,-0.047895,-0.081649,0.013549,0.098677,0.078223,-0.059137,0.064497,0.0081492,-0.092075,0.0023114,-0.077342,-0.066767,-0.067949,0.012146,0.061096,-0.097163,0.035884,-0.093894,0.010491,0.0021386,0.038525,0.012751,0.011884,-0.16491,-0.0082901,0.058229,0.0080771,-0.0040536,-0.06247,-0.037646,0.043516,0.037706,0.09012,0.045569,0.027228,-0.00067036,-0.078455,0.0066976,-0.076049,0.0087899,0.0080651,-0.013993,-0.1428,-0.10081,0.029137,0.0545,-0.022148,-0.051997,0.041875,-0.035684,0.06707,-0.019128,0.014741,0.15715,0.072891,0.13658,0.026927,-0.030798,-0.28914,-0.091859,-0.022467,0.15909,0.35654,0.18763,0.067478,0.062959,-0.07848,0.0017723,-0.0030198,-0.083782,0.078281,0.074811,0.14233,0.229,0.034479,0.087163,-0.22916,-0.46404,-0.43913,0.096908,0.25751,0.33617,0.25627,0.28658,0.21739,0.28502,0.047355,-0.15659,-0.014986,-0.0073951,-0.016977,-0.024013,0.13766,0.06654,0.064217,-0.194,-0.51872,-0.47076,-0.29641,0.176,0.6739,0.26241,-0.0096435,-0.029649,0.0047417,0.018295,-0.095495,-0.24273,0.050465,-0.028869,-0.089839,0.064334,0.05753,-0.18078,-0.25652,-0.11903,-0.46625,-0.47578,0.0088707,0.096173,0.1726,0.43693,0.42721,0.29676,0.12421,0.057339,-0.094532,-0.23698,-0.020893,0.052186,0.069047,-0.0036438,0.056723,-0.15167,0.04284,0.047117,-0.55874,-0.39052,-0.061265,-0.022497,-0.34223,0.43486,0.47664,0.42269,0.35009,0.40153,-0.12884,-0.31302,-0.087383,-0.053959,0.077412,0.020214,0.02915,-0.12179,-0.29977,-0.53975,-0.81032,-0.48147,-0.13877,0.042211,0.24819,0.39627,0.33967,0.15979,-0.04917,0.23957,-0.097751,-0.25904,0.040345,-0.065514,0.051733,0.089352,0.26712,-0.0829,-0.47545,-0.25564,-0.5943,-0.25183,0.061918,0.37774,0.42518,0.16463,-0.26026,-0.24576,-0.0044667,0.43905,0.15855,-0.17771,-0.0069488,0.0077482,-0.068434,-0.0044183,0.34082,0.15697,-0.14885,0.10797,-0.18969,0.24912,0.45956,0.42142,-0.1382,-0.50902,-0.73183,-0.11301,0.077584,0.19101,0.11358,-0.14523,-0.012277,0.099809,-0.060647,-0.066039,0.46157,0.54977,0.32668,0.54129,0.35005,0.056105,0.00085795,-0.37872,-0.4027,-0.59832,-0.29194,0.081005,-0.064978,0.022635,0.050897,-0.24469,-0.097325,-0.0091792,-0.12018,-0.15903,0.39764,0.46116,0.67778,0.62011,0.44213,-0.12899,-0.44567,-0.80079,-0.49115,0.0086442,0.057408,-0.15841,-0.038137,0.05942,0.066763,-0.12882,-0.096377,0.093884,0.00033602,-0.16286,0.14348,0.2908,0.59527,0.43278,0.31545,0.34495,-0.32392,-0.55206,-0.16482,0.15408,0.035572,-0.020195,0.14458,0.088392,0.06798,-0.024038,0.014904,-0.068754,0.017527,-0.19784,0.036655,0.067848,0.046026,-0.042107,0.3903,0.54224,-0.19756,-0.47997,-0.2446,-0.056928,-0.17701,-0.13517,0.11585,-0.19183,-0.14997,-0.17318,0.0076954,-0.017364,-0.053344,-0.086671,-0.25237,0.090757,0.019776,-0.18892,0.54218,0.65005,0.26892,-0.059291,-0.14328,0.21756,0.048297,-0.0048733,-0.044314,-0.17522,-0.1886,-0.10702,-0.027727,-0.040955,0.04311,-0.044366,-0.09231,-0.29443,-0.13175,-0.018211,0.50814,0.72823,0.67369,0.24947,0.021898,0.31462,0.020145,-0.082234,-0.15702,-0.056571,-0.095995,0.053912,-0.0056012,-0.02305,-0.08728,0.032647,-4.5907e-006,-0.27603,-0.5581,-0.68412,-0.26704,0.15655,0.3762,0.18262,0.23501,0.22448,0.10865,-0.15117,-0.16796,0.029776,0.024046,0.037644,0.067852,-0.050412,-0.063201,0.0079094,0.038516,-0.030208,-0.26607,-0.4211,-0.35521,-0.081661,-0.042507,-0.090029,0.11551,0.089287,0.10615,0.080457,0.11242,0.022493,0.021347,0.060649,-0.0050248,0.047371,0.020262,0.004765,0.013488,0.020678,0.066158,-0.075342,-0.098027,0.026526,0.090221,0.064504,0.019035,-0.020655,-0.042734,0.074244,-0.087653,0.013268,0.057157,0.051006,0.017897},{0.56427,0.077971,-0.061596,0.091967,-0.087459,-0.087039,-0.045277,0.047369,-0.074904,-0.030084,-0.047137,-0.018173,0.013871,-0.071298,0.090234,0.017898,-0.0086689,-0.050893,-0.078526,-0.047414,0.0008194,0.031711,-0.079707,0.0025036,-0.0013716,0.0018364,0.084165,-0.098964,-0.022126,-0.072884,-0.026761,-0.013531,0.089954,0.044076,-0.034343,0.065934,0.070172,-0.022979,0.016649,-0.015496,0.086834,-0.066592,0.066275,-0.066256,0.064301,0.0139,-0.128,-0.030925,-0.11148,-0.068403,0.0058915,0.035627,-0.055568,-0.038439,0.019938,-0.0019596,-0.035567,0.0064525,-0.035846,0.020227,0.039936,-0.086196,-0.030989,0.032967,0.048516,-0.090876,-0.073201,-0.021669,-0.22117,-0.088775,-0.068438,0.20098,-0.051247,-0.30765,-0.15865,-0.14039,-0.071908,-0.060275,-0.087902,-0.095514,0.039197,-0.080678,-0.069948,-0.011557,0.048927,-0.20906,-0.10095,-0.22185,-0.34378,-0.20226,0.23389,0.47082,-0.032318,-0.07086,0.17233,-0.13632,-0.16772,-0.23146,-0.082221,-0.13902,0.045938,-0.052504,0.038566,0.044534,0.0049381,-0.0065232,-0.30769,-0.24649,-0.34876,0.13366,0.3992,0.5982,0.36077,0.45496,0.50892,0.31811,-0.18904,-0.23896,-0.37948,-0.22206,0.018464,0.048698,0.044048,0.14925,0.013223,0.20587,-0.17648,-0.41482,-0.17134,0.23204,0.426,0.50047,0.54156,0.14099,0.44694,0.301,-0.089235,-0.27168,-0.10204,-0.31581,-0.11553,-0.078627,0.068541,0.015283,0.2162,0.01649,-0.4396,-0.56971,-0.18382,0.094942,0.72652,0.71439,0.285,-0.013748,0.21466,0.27628,-0.0013375,-0.0081805,-0.19123,-0.29514,-0.0023906,0.014371,0.088034,0.052232,0.062189,-0.32524,-0.43875,-0.44973,-0.22932,0.042186,0.94722,0.88232,0.49503,0.24206,0.40562,0.43292,-0.053916,-0.21055,-0.074672,-0.43983,0.016478,-0.090847,-0.036088,0.10896,0.065313,-0.49195,-0.74027,-0.52051,-0.45956,-0.36532,0.54101,0.66414,0.44557,0.26026,0.37146,0.19842,-0.30208,-0.26569,-0.057894,-0.26767,-0.036785,-0.084811,-0.012985,0.19079,0.20296,-0.48191,-0.91135,-0.82141,-0.61199,-0.64715,-0.049113,0.14579,0.55823,0.12134,0.52103,0.16574,-0.33297,0.048557,0.15247,-0.12183,-0.088089,0.038019,0.12252,0.089398,0.079881,-0.4727,-0.79579,-0.51961,-0.42602,-0.62545,-0.2972,-0.0801,0.13091,0.46139,0.4495,-0.021113,-0.16042,-0.048286,-0.016342,-0.19877,-0.048367,0.061056,0.033242,0.18679,0.3424,-0.1512,-0.31405,-0.32283,-0.54239,-0.62235,-0.044703,0.077569,-0.020847,0.32544,0.13219,0.096568,-0.035553,0.12437,-0.10094,-0.34229,-0.11022,-0.088892,0.034646,0.094466,0.18277,-0.18395,-0.52554,-0.096552,-0.64235,-0.84395,0.025181,0.28368,0.17006,-0.18833,0.15902,-0.06439,0.052402,0.15074,-0.15274,-0.24631,-0.00026251,0.029222,0.068815,0.099316,0.25825,-0.091575,-0.25707,-0.18271,-0.67296,-1.1493,-0.066243,0.17418,0.08707,0.067086,-0.060228,-0.26521,-0.0044255,0.036964,0.017879,-0.25071,0.072683,-0.072214,0.063222,0.065919,0.23542,0.30528,0.40746,-0.096151,-0.78925,-0.74538,-0.40309,-0.092061,0.19629,0.30135,-0.049551,-0.030708,0.25283,0.24093,0.027885,-0.20234,-0.062413,-0.02108,0.055096,-0.040336,0.165,0.39441,0.7036,0.034218,-0.47159,-0.37074,-0.27235,0.0052036,0.10423,0.22477,0.090719,0.14634,0.067687,0.095934,-0.067736,0.019724,0.020913,0.0079125,-0.091341,0.062762,-0.011852,0.46906,0.6087,0.29461,-0.062198,0.029137,0.18329,0.17676,0.10742,0.064647,-0.034852,-0.12405,-0.028256,-0.041428,-0.032309,0.061799,0.076991,0.089918,-0.049147,0.077643,-0.0016138,0.19829,0.29311,0.30489,0.21538,0.09955,0.032072,0.016572,-0.077634,-0.06312,0.092464,0.072472,0.028167,0.074013,0.0078303,0.040943,0.062671,0.016341,0.087657,0.03945,-0.072499,-0.092891,-0.083748,-0.050343,0.067015,-0.0064469,-0.053638,-0.089233,-0.01733,-0.022648,-0.043936,0.064774,-0.071706,0.067491,-0.074436,0.041513,0.043203},{-0.24695,-0.057638,0.028346,-0.019954,-0.061256,0.067414,0.053816,-0.050926,0.039344,-0.05268,0.012194,0.013799,0.033411,-0.087952,0.046352,-0.0097047,0.079108,-0.019683,-0.068043,-0.050401,-0.049204,0.08979,-0.0050795,-0.08375,0.01572,-0.029712,0.087018,0.056822,0.0020186,-0.02845,-0.030157,0.089471,0.086395,-0.02328,-0.03162,0.033272,0.053051,0.051252,0.082267,0.045985,0.024887,0.061809,-0.01834,0.07739,-0.050357,0.012455,-0.035344,-0.030263,-0.039177,-0.12932,-0.11211,-0.085096,0.074459,-0.020394,0.15693,0.15792,0.021393,-0.052109,0.094129,0.015405,0.054597,0.069525,0.0056728,0.046242,0.0054763,-0.027629,-0.032822,-0.11123,-0.17462,-0.11253,-0.071184,-0.086351,0.0024957,0.12644,0.14329,0.35653,0.28885,0.21502,0.12868,-0.011867,-0.024595,-0.091054,0.073614,0.00062085,-0.047078,-0.028623,-0.066071,-0.15155,0.042507,0.22203,0.17717,0.064932,-0.024582,-0.081326,0.044046,0.33263,0.24166,0.2002,0.23164,0.040419,-0.03655,0.092433,-0.078386,-0.002895,-0.0098252,0.029562,-0.089311,-0.20586,-0.0252,0.10836,0.14764,0.20417,-0.20213,-0.036637,0.067393,0.091935,0.25543,0.23138,0.32797,0.074844,0.018971,0.0048093,0.016463,0.11048,0.0063696,-0.012247,-0.1352,-0.33538,-0.1854,-0.20755,0.27983,0.26285,0.19378,0.027326,0.048052,-0.014508,0.10817,0.10519,0.052949,0.14123,0.078356,-0.068924,0.12534,0.15517,0.10467,0.021402,0.019693,-0.19836,-0.16298,0.15041,0.27043,0.57253,0.19918,-0.13762,-0.046993,-0.12571,-0.062609,-0.082688,0.11519,0.17963,-0.054047,-0.071289,0.077737,0.068164,0.072249,0.1604,0.14581,-0.013922,-0.12881,0.23596,0.35502,0.33376,-0.15868,-0.35417,-0.20594,-0.028602,-0.048193,-0.38228,0.14143,0.22716,-0.0018757,-0.0074576,-0.013881,0.22048,-0.10145,-0.00057501,0.42691,0.10596,-0.17078,0.089434,0.43887,0.19364,-0.31856,-0.59501,-0.61919,-0.013978,0.015152,-0.22569,0.14818,0.26778,-0.099804,0.075964,0.013723,0.36882,-0.011228,0.26091,0.72092,0.15637,-0.13641,-0.062306,0.34041,0.19247,-0.66575,-0.76865,-0.5614,0.12963,0.1501,-0.21521,-0.18228,-0.018663,-0.08134,0.01871,0.14542,0.28015,-0.092745,0.24475,0.79058,0.078933,-0.55326,-0.33465,0.35578,0.088962,-0.43781,-0.16345,0.061834,0.33918,-0.14956,-0.50996,-0.22944,-0.026915,0.039381,-0.055063,0.047053,0.36112,0.11322,0.17543,0.5947,-0.18325,-0.42919,0.039599,0.29699,0.11122,-0.18697,0.2013,0.49559,0.45744,0.017342,-0.38987,-0.14844,0.15469,-0.087219,-0.0725,0.096386,0.26009,-0.05844,-0.011424,0.15354,-0.13503,-0.37214,0.033424,0.085911,0.11576,0.086075,0.54198,0.87061,0.46155,0.12577,-0.088867,0.10604,0.21675,0.01931,-0.017858,-0.017143,0.14345,-0.14891,-0.17802,0.22532,-0.036539,-0.20816,-0.056485,-0.074154,0.072058,0.13179,0.29603,0.55994,0.29528,0.051979,0.024471,0.10691,0.19676,0.088863,-0.060952,0.073824,0.047072,-0.16666,-0.1065,0.021152,0.074583,-0.11418,-0.08408,0.12801,0.11051,0.098469,0.20314,0.16352,0.16971,0.027117,-0.012298,0.054722,0.11996,-0.039784,-0.087295,0.08622,0.025635,-0.1235,-0.061299,0.063625,-0.13729,-0.27616,0.012923,0.080275,0.057302,0.01094,0.12552,0.073138,-0.034319,-0.073239,-0.061009,-0.020534,0.089456,0.05177,-0.073543,-0.035548,-0.07149,-0.08061,-0.071762,0.015213,0.08733,-0.010214,0.0027566,-0.023788,0.19385,0.080779,0.020332,0.064436,-0.056551,-0.045714,-0.091316,0.08162,-0.071591,0.077586,-0.063666,0.02193,0.059982,-0.080801,0.052955,-0.038269,-0.028598,-0.091191,-0.033047,0.085467,0.039424,-0.054771,0.074659,-0.046716,0.038656,0.046952,-0.071877,-0.0067939,-0.059534,-0.067541,-0.077541,0.014325,-0.025974,-0.0031099,0.03321,-0.05638,0.036989,0.044408,-0.03574,0.034755,0.024691,0.073164,0.02674,-0.090918,-0.013763,-0.036218,0.089316,-0.071509,0.079383,-0.074192},{0.13788,-0.089362,-0.082838,-0.053513,-0.064919,-0.024582,-0.045793,-0.022499,-0.042785,-0.027515,0.088397,0.057754,-0.058054,0.030084,-0.011537,0.08016,-0.0024853,0.072928,0.050871,0.087901,-0.085224,0.044164,0.046399,0.02691,0.051596,0.086087,0.0031984,0.037666,-0.11948,-0.018615,-0.097954,-0.067414,0.0016764,0.040422,-0.097132,-0.0067294,0.061622,0.074204,-0.048747,0.02677,-0.022742,-0.024323,0.04312,0.046455,-0.053877,-0.056606,-0.0017943,-0.060184,-0.070267,-0.11685,-0.056789,0.015589,-0.056518,0.0003752,-0.049475,-0.0029578,-0.12091,0.021958,0.076386,0.076492,-0.0057284,0.0061057,-0.014013,-0.027521,0.04861,-0.12279,-0.094866,-0.031151,0.036107,-0.02705,0.022105,-0.031675,-0.15656,-0.2826,-0.2732,-0.20501,-0.18965,-0.070931,0.022712,0.084984,0.078957,-0.071238,0.0094591,0.086979,-0.073949,-0.011886,-0.043299,-0.057511,0.11258,0.32577,0.17443,-0.022225,-0.18219,-0.50623,-0.35309,-0.17499,-0.27469,-0.060249,0.0071715,-0.080238,0.031398,-0.057642,0.090063,0.013161,-0.095463,-0.0088493,0.027437,-0.018699,0.17342,-0.0132,0.14374,0.014389,-0.12756,-0.17076,-0.43895,-0.29697,-0.15292,-0.26139,-0.17241,-0.15012,0.075065,-0.044007,-0.076496,-0.011823,-0.16779,-0.11861,0.095547,-0.046347,-0.044624,-0.13079,-0.080994,-0.030152,0.27928,0.054407,-0.24604,-0.29415,-0.29762,-0.25312,0.010369,-0.028427,-0.034115,-0.065284,0.0094186,0.045362,-0.18181,0.029545,0.080101,0.013118,-0.14559,-0.059564,-0.071415,0.33864,0.65495,0.56983,0.036816,-0.38347,-0.37292,-0.23472,0.042868,-0.10814,-0.003825,-0.0077513,-0.013849,-0.14336,-0.17022,0.11049,0.09245,-0.25649,-0.09883,0.11243,0.48718,0.86543,0.99481,0.65424,-0.025123,-0.58045,-0.56778,-0.024862,0.19357,-0.038158,-0.024521,0.053021,-0.020879,-0.12435,-0.23773,-0.11127,-0.14519,-0.15827,-0.14661,0.19177,0.6987,1.151,1.2514,0.65098,-0.16239,-0.41353,-0.36565,0.17706,0.28891,-0.041441,-0.0099103,0.011851,0.014044,-0.10192,-0.53527,-0.14846,-0.072834,-0.08293,-0.11097,0.23282,0.78654,1.121,0.98593,0.30365,-0.023274,-0.12928,-0.094754,0.0907,0.1976,-0.078809,0.010407,0.054557,0.01685,-0.29347,-0.50565,-0.27168,0.011039,0.00041586,0.00054818,0.071869,0.53013,0.76532,0.73619,0.41975,0.090081,-0.37296,-0.34676,0.061894,0.19978,-0.085508,-0.095869,0.091303,-0.055197,-0.20139,-0.3412,-0.018311,0.12659,-0.065857,-0.10573,-0.31546,-0.17341,0.16829,0.50157,0.17722,-0.29935,-0.47885,-0.082815,0.079388,0.16643,-0.057383,-0.090539,0.089772,0.061919,-0.13299,-0.20073,-0.045146,0.1698,-0.027089,-0.33704,-0.54049,-0.23649,-0.074636,0.0034415,-0.33478,-0.37632,-0.11648,0.15944,0.24091,0.25662,-0.011554,-0.10428,-0.031037,0.051495,-0.10794,-0.088881,0.19211,0.24269,-0.073437,-0.27198,-0.46634,-0.21559,-0.23025,-0.50424,-0.62365,-0.41969,-0.10262,0.14026,0.27827,0.3158,0.069759,0.0079247,0.02029,0.031189,0.00471,0.073694,0.18595,0.16425,-0.044106,-0.38564,-0.41131,-0.31203,-0.28642,-0.35273,-0.51849,-0.27802,0.030755,0.029006,0.11233,0.15331,0.003817,0.0071791,-0.0021237,0.048748,0.055862,0.072818,0.23665,0.3765,0.016049,-0.2223,-0.23294,-0.26072,-0.19815,-0.14733,-0.3478,-0.10792,-0.068075,0.0090126,0.11952,0.18295,0.061369,0.017402,0.016232,-0.063598,0.078276,0.076469,0.14967,0.25883,0.13056,0.020381,0.028741,-0.12349,-0.024078,-0.14363,-0.1286,-0.0031751,-0.10274,-0.11562,0.0041677,-0.048163,0.053952,0.080324,-0.03796,-0.035187,0.02549,-0.012358,0.10571,0.082246,0.14388,0.082679,-0.0067143,-0.066872,-0.063278,-0.10378,0.020521,-0.0041183,-0.014066,0.046693,-0.068198,-0.036304,0.091377,-0.025698,-0.0030177,0.0082492,-0.036146,-0.0057324,-0.017646,0.068693,0.020049,0.081435,-0.046401,0.085963,-0.053595,0.057001,0.0049311,0.051295,-0.013498,-0.085077,0.068659,-0.047615,0.07353,0.086946},{0.25608,0.013662,-0.023714,0.022957,-0.048551,-0.037866,-0.0075575,-0.087241,-0.010942,-0.025543,0.027013,-0.014273,-0.078125,0.083823,-0.043865,-0.088031,0.056381,0.019142,0.073674,-0.064508,0.091216,-0.07097,-0.087472,-0.055909,0.034906,-0.08147,-0.025828,-0.059802,-0.029215,-0.039363,0.090963,-0.061744,0.090343,-0.038373,0.073927,-0.031228,0.064168,-0.038047,-0.057084,0.015607,-0.033775,0.088839,0.074313,-0.071864,-0.047301,0.071296,-0.030486,-0.069924,0.091124,-0.054116,-0.079858,-0.066869,-0.032506,0.094982,0.11891,-0.045909,-0.014223,0.058449,-0.0067086,-0.067373,-0.031363,-0.020689,-0.089371,0.048813,0.10302,0.11894,0.024844,0.12019,0.054774,0.036221,-0.0021829,0.059619,0.12469,0.18532,0.20412,0.16548,0.071367,0.022672,0.11387,0.06797,-0.036037,-0.054442,0.032562,0.056901,0.025156,0.11193,0.28917,0.3206,0.065185,0.1471,0.17164,0.25482,0.29745,0.19597,0.21958,0.14996,0.07962,0.1824,0.21171,0.0058649,-0.062628,-0.023048,0.01766,0.09751,0.091924,0.40737,0.35641,0.38602,0.15187,-0.035184,0.15442,0.4709,0.58714,0.3396,0.29633,0.06748,-0.14552,0.053434,0.25031,-0.011019,0.0056093,0.014438,-0.071787,-0.040237,0.33088,0.59022,0.51335,0.22393,0.014708,-0.052034,0.19778,0.38922,0.42463,0.19067,0.22806,-0.098996,-0.18441,-0.23705,0.072006,0.13881,-0.032081,-0.058699,0.052592,0.13526,0.54602,0.86991,0.56322,-0.099725,-0.37816,-0.23124,0.18466,0.35433,0.40645,0.08553,0.042965,-0.17917,-0.045438,-0.24832,0.02238,0.17996,0.083231,0.016955,-0.046641,0.20562,0.57902,0.78232,0.15321,-0.39485,-0.53978,-0.44248,-0.23502,0.047089,0.33071,0.2116,-0.01028,0.14344,0.13207,-0.20018,0.030343,0.1547,0.02469,0.060821,-0.053908,0.21355,0.57209,0.29133,-0.01466,-0.33873,-0.76336,-0.83304,-0.58606,-0.39979,-0.25666,-0.18974,-0.25913,0.1663,0.2624,0.00082063,-0.036802,0.15768,0.070421,-0.016691,0.069617,0.1561,0.32764,0.33575,0.20252,-0.34652,-0.61006,-0.6375,-0.68432,-0.52984,-0.62912,-0.42349,-0.06208,0.084538,0.14176,-0.090665,-0.049184,0.015067,-0.050458,-0.050797,-0.025179,0.18049,0.055878,0.51822,0.37199,-0.084119,-0.020426,-0.13213,-0.31555,-0.15695,0.054481,0.13747,0.16699,0.24983,0.20315,-0.17131,-0.041854,0.10782,-0.048133,-0.072159,-0.058882,0.17282,-0.070255,0.23784,0.36336,0.086013,0.17417,0.27119,0.4029,0.50807,0.29031,0.088822,0.087065,0.13865,0.17547,-0.078792,-0.036184,0.037825,0.063324,-0.080171,-0.013472,0.1675,-0.19119,-0.0067291,0.015035,0.02549,0.22759,0.46946,0.61131,0.71227,0.58476,0.36954,0.25744,0.27338,0.32799,0.15792,0.025557,0.069401,-0.065185,-0.029589,0.088686,-0.037744,-0.062289,-0.14984,-0.28,-0.13783,0.22495,0.27722,0.52672,0.49146,0.65152,0.53172,0.36812,0.65629,0.4524,0.22756,0.15545,-0.014835,-0.084549,-0.0009487,-0.024679,-0.032931,-0.15476,-0.30079,-0.43668,-0.32373,0.0068035,0.25341,0.38629,0.30915,0.43101,0.51736,0.52147,0.54114,0.35612,0.22139,0.11108,0.056252,-0.018083,-0.014163,-0.070731,-0.038516,-0.11326,-0.26179,-0.50958,-0.53175,-0.1168,0.071575,0.19763,0.26196,0.35203,0.3467,0.46799,0.32457,0.14378,0.15485,0.027472,-0.044088,-0.0094617,0.057132,-0.012532,-0.063335,0.012913,-0.069347,-0.39898,-0.50735,-0.20086,0.021008,0.15625,0.17466,0.055658,0.23038,0.2691,0.17333,0.13827,-0.048099,-0.087623,0.060937,-0.065972,0.014886,-0.052673,0.046533,0.057604,-0.02057,-0.031248,-0.14257,-0.15217,0.068296,0.0016292,-0.0088008,0.070522,0.018172,-0.038153,0.0123,0.017015,0.035516,0.081624,0.038455,-0.0078803,0.035023,-0.0056893,0.07796,0.047065,-0.057033,0.027213,-0.0070218,0.062235,-0.080264,-0.0097014,-0.086799,-0.0025224,0.094237,0.014128,-0.0032819,-0.042605,0.0088242,0.0015519,0.05578,0.092101},{0.17801,0.05846,0.045336,0.026654,0.043497,-0.089749,-0.050764,-0.04095,0.049669,-0.025248,0.032996,-0.055362,-0.052478,0.058645,0.024832,-0.016135,0.036492,0.084957,0.044736,-0.037814,0.045323,-0.068931,-0.030242,-0.0363,0.015887,0.030198,0.059819,-0.092898,-0.053436,0.072938,-0.038875,-0.035996,0.033962,0.014323,-0.054995,0.041677,-0.020267,-0.029144,-0.028354,-0.072114,0.087792,-0.080617,-0.087644,0.028074,0.0035989,0.011817,-0.07382,-0.057113,-0.073325,0.050252,-0.027686,0.067363,-0.0075996,-0.064513,-0.11761,-0.10167,0.039313,-0.026522,0.010609,0.012119,0.04167,0.020942,-0.027243,-0.086807,0.036342,-0.10731,-0.12461,-0.2717,-0.065036,0.06675,0.035591,-0.13764,-0.01896,-0.052319,0.010998,0.022879,-0.034714,-0.14643,-0.16745,-0.058597,0.016661,0.063915,0.052062,-0.001579,0.029889,-0.20446,-0.34411,-0.28201,-0.05949,-0.1146,-0.23763,-0.26113,-0.28647,-0.15815,0.1806,0.13167,0.090596,-0.079628,-0.064887,0.036652,-0.031416,0.032427,0.069649,0.068767,-0.13879,-0.31424,-0.164,-0.047227,0.091361,-0.028801,-0.18171,-0.15576,-0.37437,-0.29481,0.121,0.16238,0.28867,0.16208,-0.1811,-0.038049,0.040715,-0.091134,0.029641,0.026756,-0.050379,-0.26903,-0.0057036,0.37146,0.35229,0.044033,-0.15928,-0.063142,-0.014852,-0.11441,0.34499,0.42063,0.32956,0.13584,-0.1691,-0.19689,-0.058748,-0.00069677,-0.046186,0.15665,-0.2416,-0.39711,-0.042813,0.27378,0.52597,0.13442,-0.17959,-0.027142,0.11227,0.11561,0.28853,0.46136,0.58112,0.070107,-0.26187,-0.12334,0.068067,4.4451e-005,0.051351,0.076612,-0.24416,-0.20836,0.05841,0.3145,0.30134,-0.070953,-0.13533,0.041077,0.28487,0.32331,0.5392,0.49504,0.2877,-0.19879,-0.26651,-0.21835,-0.094591,0.0085479,-0.016309,0.09986,-0.15604,-0.039511,-0.23513,0.12545,0.16315,0.069819,0.11016,0.40085,0.83707,0.88136,0.68381,0.28159,0.0041231,-0.46043,-0.20887,-0.20482,-0.051615,0.049563,-0.051473,0.024781,0.097536,0.067746,-0.43747,-0.15782,0.037042,0.42504,0.55237,0.70089,0.97146,0.53412,0.23294,-0.053819,-0.20529,-0.31671,0.038975,-0.049789,-0.080229,-0.015822,-0.028311,0.072496,0.19644,-0.011633,-0.48691,-0.31219,-0.14716,0.058615,0.19536,0.19114,-0.16869,-0.52064,-0.37771,-0.17911,-0.13662,-0.058182,0.0494,0.0037449,0.073552,-0.084534,0.05271,-0.032996,0.36211,0.016374,-0.37429,-0.094916,-0.57211,-0.6595,-0.41753,-0.11992,-0.40059,-0.58551,-0.47985,-0.049042,0.20904,0.078209,-0.032611,0.023371,-0.068793,0.0022258,-0.048291,0.14574,0.36759,0.16426,-0.074545,-0.1786,-0.68101,-0.63951,-0.2626,-0.039562,-0.10913,-0.23705,-0.014638,0.23201,0.17208,0.11063,0.053658,-0.08531,-0.018228,-0.084316,0.099962,0.011671,0.2181,0.17691,0.023778,-0.15746,-0.48987,-0.37304,-0.17633,-0.20919,-0.050024,0.027831,-0.056369,0.13575,0.023955,-0.055607,-0.027995,-0.062784,-0.013798,-0.042481,-0.086603,0.14037,0.11854,0.13864,0.21711,-0.16221,-0.47944,-0.33472,-0.2553,-0.18147,0.027893,0.0047769,0.08656,0.13412,0.017132,-0.012029,-0.011606,-0.0097399,-0.11348,0.011241,-0.00071717,0.067128,0.096618,0.063477,0.075306,-0.023702,-0.35423,-0.21785,-0.30918,-0.14295,-0.17157,0.15988,0.34589,0.15773,0.14193,0.0047742,0.067033,-0.022453,-0.029504,0.031239,0.082963,-0.024703,0.061964,0.031859,0.20734,0.18991,0.088658,-0.10446,-0.08891,-0.080523,-0.049987,0.21194,0.20197,0.050628,0.17935,-0.046604,0.024987,-0.064628,-0.088594,0.042965,-0.040073,0.053451,-0.073936,0.012323,0.092417,-0.041179,0.05699,0.0011105,0.079178,0.07388,0.11905,0.10552,0.086628,0.093571,-0.044994,0.058367,-0.0073078,-0.054485,-0.060859,-0.035556,0.012608,-0.091345,0.047514,0.069145,-0.04677,-0.081083,-0.078968,-0.034389,0.073696,0.041496,0.058287,-0.024333,-0.014856,-0.09009,-0.072719,0.065944,0.058508,-0.087526,-0.017411},{0.25499,0.088624,-0.089897,0.048502,0.067092,0.080743,0.078539,-0.03458,-0.037032,0.091889,-0.0094056,0.057528,-0.081843,-0.013834,0.034796,-0.016253,0.059219,-0.0020964,-0.083276,-0.0036543,-0.052355,-0.0043022,0.055501,-0.02246,-0.024142,0.0077642,0.079524,0.022407,-0.082268,0.089864,-0.033135,-0.085208,-0.0002642,0.096133,0.072633,-0.02224,-0.067167,-0.033121,-0.088557,-0.026282,0.031941,0.03779,-0.0099199,-0.028521,0.085722,0.098599,0.12326,0.13776,0.1228,0.11123,0.12635,0.0074393,-0.0091754,-0.026097,0.048855,0.033212,0.11095,0.079078,-0.010256,-0.087735,0.070078,0.067729,-0.027171,-0.063782,0.11058,0.104,0.19628,0.061129,0.14895,0.063124,-0.062301,0.063779,-0.0021551,0.11741,0.25987,0.13562,0.08529,0.032722,-0.032959,0.045718,0.01983,0.078186,0.04655,-0.052534,0.087222,0.10849,0.18762,0.073577,-0.21456,-0.6742,-0.49245,0.062632,0.24134,0.054477,0.16478,0.061597,0.022725,0.068199,0.025244,-0.055927,-0.071884,-0.04748,-0.083802,-0.011807,0.047211,0.23716,0.13814,-0.03097,-0.40837,-0.39098,0.058965,0.36997,0.57513,0.27585,-0.30607,-0.12623,-0.11512,-0.155,-0.11755,-0.11427,-0.083234,-0.023251,-0.0092004,-0.065835,0.24444,0.45875,0.049254,-0.40325,-0.46084,-0.045011,0.14264,0.13847,0.1774,-0.0089313,-0.39407,-0.39896,-0.49261,-0.13059,-0.015869,0.02704,-0.030522,0.017403,-0.037821,-0.045986,0.27433,0.2827,-0.4912,-0.51416,-0.40815,0.18294,0.24008,0.013054,-0.26999,-0.44302,-0.63558,-0.66209,-0.44753,-0.088086,0.14828,-0.065589,0.020248,-0.059033,0.027453,-0.10078,0.098261,-0.16906,-0.76458,-0.39517,-0.0072299,0.28744,0.49824,0.53004,-0.032132,-0.33126,-0.38276,-0.58366,-0.26,-0.026672,0.10709,-0.19605,0.10216,0.0055972,-0.13736,-0.10277,0.087875,-0.24343,-0.82395,-0.82558,-0.13639,0.24171,0.4346,0.32803,0.34224,0.41772,0.24928,-0.35934,-0.33952,0.061158,0.18167,-0.23503,0.0016699,0.024548,-0.044105,-0.27691,0.098255,-0.42218,-1.2102,-1.0478,-0.22961,0.18083,0.0064388,0.11562,0.45359,0.63449,0.12633,-0.22497,-0.082168,0.22815,0.16621,-0.14074,-0.039677,-0.044803,0.040821,-0.039101,0.24028,-0.22633,-1.3869,-0.3584,0.37165,0.1333,0.025002,0.16205,0.37474,0.40669,-0.059357,0.11666,0.20684,0.54372,0.042839,-0.21768,0.014532,-0.083846,-0.12797,0.032125,0.18214,-0.29123,-0.77111,-0.11496,0.46277,-0.021953,0.016683,0.21718,0.40273,0.20755,-0.021721,0.078774,0.18853,0.33132,-0.048127,-0.33921,-0.065054,0.061127,-0.025917,0.010104,0.095426,-0.1407,-0.15882,-0.085827,0.097251,0.052514,-0.051936,0.35354,0.54376,0.022746,-0.28612,-0.096132,0.011815,0.30191,-0.17884,-0.29004,-0.011368,0.068289,0.026181,-0.062072,0.1462,0.52383,0.17768,0.11772,0.032773,-0.15336,0.12145,0.40153,0.45024,-0.13591,-0.027657,0.14227,0.14146,0.1427,-0.25084,-0.077044,-0.00087985,-0.035373,0.018491,-0.021773,0.164,0.50314,0.45886,0.087136,0.017691,-0.23314,-0.079533,-0.015155,0.0013115,-0.19599,-0.068113,0.10706,0.068006,-0.035711,-0.16344,-0.15912,0.066324,-0.016655,0.033205,0.041165,0.11817,0.54617,0.44045,0.043297,-0.15114,-0.18514,-0.15272,-0.07888,-0.020814,-0.22799,-0.080807,-0.22006,-0.051863,-0.083546,-0.1598,-0.044739,-0.043762,0.041413,0.032455,0.080209,0.1258,0.15054,0.0043961,-0.098978,-0.18121,-0.20774,-0.24592,-0.095612,-0.10244,0.036694,-0.093823,-0.14749,0.037932,0.0081676,-0.066431,-0.066094,-0.089311,-0.029706,0.0079405,0.064042,0.065514,-0.06466,0.042989,-0.16252,-0.039,0.025423,-0.093256,-0.052511,0.010016,-0.036664,-0.0010524,-0.02566,0.045181,-0.054461,-0.064269,-0.087115,-0.023179,0.0002084,0.054752,0.038131,-0.01239,0.022622,-0.090378,0.024153,-0.089873,-0.021636,0.059581,-0.0084735,-0.041245,0.029236,0.033738,0.069141,-0.083186,-0.085347,0.041825,-0.033132,-0.001509},{-0.069779,0.060006,0.043434,-0.070593,-0.01043,-0.029786,-0.076061,-0.030319,0.075628,0.080707,-0.09008,0.00065288,-0.063593,0.0028076,0.0482,-0.030635,0.022265,0.067305,-0.026835,-0.080189,-0.03544,0.064178,0.067228,0.049741,-0.043275,-0.016986,0.054577,-0.050452,-0.046618,-0.078693,-0.066768,0.06219,0.032363,0.08882,-0.088972,0.037383,0.069233,-0.0296,-0.050043,-0.043799,-0.061334,-0.061731,0.04406,0.01322,-0.017279,-0.029237,0.068863,0.071335,0.0073707,-0.055763,-0.076986,0.0066254,0.071357,-0.051924,-0.092223,-0.096075,0.020608,0.061436,-0.064779,0.057855,-0.06245,-0.02517,0.038112,-0.068161,0.053625,-0.044534,-0.10654,-0.064833,-0.0087257,0.038159,-0.030003,-0.11288,-0.16117,-0.1671,-0.2584,-0.15658,-0.12151,-0.048173,0.041064,0.07515,-0.014449,0.028361,0.078119,-0.084131,0.0728,0.0056114,-0.06714,-0.032776,0.018988,-0.19124,-0.25659,-0.3307,-0.58421,-0.59801,-0.52393,-0.31158,-0.1399,-0.12717,0.11284,-0.053845,-0.024877,0.079777,-0.0018927,-0.064481,0.014069,-0.10834,-0.18982,-0.26824,-0.18108,-0.20969,-0.47722,-0.72595,-0.86328,-0.67266,-0.61718,-0.54965,-0.28694,-0.1175,0.00073679,0.15656,-0.035899,-0.057529,0.084187,0.08815,-0.05126,-0.077845,-0.33758,-0.38495,-0.2122,-0.23522,-0.43978,-0.68841,-0.64839,-0.55371,-0.51076,-0.43272,-0.18516,-0.064822,0.12679,0.13941,0.034488,-0.043994,0.033735,-0.076246,-0.055385,-0.35227,-0.45273,-0.28203,-0.10512,0.025854,-0.19573,-0.23304,-0.20891,-0.088286,-0.07053,-0.2259,-0.31595,-0.14735,0.068248,0.021306,0.038082,0.05843,-0.028974,0.042572,-0.060363,-0.23229,-0.19329,-0.012506,0.11479,-0.077925,-0.023972,-0.011946,0.27493,0.27695,-0.0061284,-0.19399,-0.33779,-0.25266,-0.1923,0.064362,-0.056397,0.048872,-0.013146,-0.12186,-0.1628,-0.11685,0.027474,0.064184,0.026268,0.027733,0.25146,0.41888,0.53652,0.68812,0.42077,-0.16367,-0.49815,-0.43394,-0.2819,-0.049115,0.099622,0.0060905,0.043746,-0.11198,-0.33344,-0.16196,-0.084134,0.045646,0.1556,0.33782,0.65011,0.74017,0.77189,0.58536,0.35616,-0.39841,-0.6107,-0.36932,-0.037609,0.031708,-0.010303,-0.032411,0.020485,-0.19286,-0.33174,-0.35082,-0.00031246,-0.14647,0.17102,0.37989,0.58211,0.43569,0.3313,-0.12328,-0.37271,-0.63402,-0.45317,0.0032355,0.13231,0.096686,-0.017278,0.084755,-0.095516,-0.20029,-0.50767,-0.4227,-0.10421,-0.1421,-0.15884,0.18809,0.24002,0.13044,-0.09155,-0.42002,-0.69632,-0.62631,-0.32785,0.19125,0.22652,0.020598,-0.0078067,0.023948,-0.011334,-0.10188,-0.19684,-0.13408,-0.10478,-0.24061,-0.19665,-0.12698,-0.098963,-0.35591,-0.50317,-0.79414,-0.85264,-0.50124,-0.19098,-0.10218,0.013018,-0.041396,0.013462,0.088242,-0.072994,-0.061493,-0.15743,0.021463,-0.072687,-0.4348,-0.48858,-0.32959,-0.5008,-0.69233,-0.66864,-0.84211,-0.59762,-0.36602,-0.033924,0.0012392,0.074474,-0.029288,-0.033403,-0.091073,-0.043061,-0.03143,-0.064369,-0.066177,-0.11384,-0.44932,-0.40179,-0.49304,-0.57461,-0.60794,-0.6358,-0.42925,-0.30604,-0.2252,0.049733,0.06353,0.068808,-0.014871,-0.082293,0.015553,0.04966,-0.038798,-0.019417,0.085193,-0.15514,-0.25412,-0.31882,-0.28435,-0.40114,-0.50594,-0.38399,-0.13232,-0.11633,0.010384,-0.09599,-0.072901,-0.010332,0.070312,-0.041834,-0.04367,-0.047242,0.082719,-0.0089429,-0.071481,-0.01041,0.0041844,-0.12484,-0.074422,-0.13902,-0.042142,-0.11956,-0.01963,0.03619,-0.058664,0.034947,-0.0094679,0.05464,-0.00020461,-0.072159,-0.015835,0.040422,-0.049489,0.029757,0.0057227,-0.033732,0.0037816,-0.018644,0.032786,0.0066938,-0.052017,-0.026131,-0.03647,-0.077763,0.054999,0.035678,0.030837,0.019843,-0.070101,0.05531,0.020382,-0.044012,0.0053927,-0.045202,0.065227,-0.092493,0.04374,0.08553,-0.071138,0.062101,0.051093,0.056658,0.0066184,0.015011,0.037324,-0.010876,-0.045671,0.020488,0.08526,0.025745},{0.28181,0.0095637,-0.08796,-0.0045427,0.0076213,-0.061518,-0.079803,-0.0043895,0.056424,0.086118,0.031821,-0.055064,0.0117,0.085969,0.013842,0.090407,-0.0045793,-0.063337,-0.0071934,-0.024138,0.059524,-0.077167,0.050553,-0.021499,-0.091766,0.020406,0.051671,0.072886,-0.027623,-0.054277,0.036055,0.03048,0.012183,0.071266,0.06773,0.054291,0.011411,-0.075258,-0.017612,-0.048262,-0.049128,0.056337,0.011828,0.037454,-0.021129,0.084104,-0.047402,0.069253,0.12432,0.061813,0.042957,0.036021,-0.082938,0.047927,-0.049663,0.066158,-0.028803,0.063992,-0.0061148,-0.03561,-0.053695,0.068048,-0.01339,0.050132,-0.0078661,0.076826,0.081368,0.057163,0.056429,0.059731,-0.047149,-0.022797,-0.041098,-0.23576,-0.21199,-0.11409,-0.046725,-0.0019712,-0.00014497,-0.069656,-0.01299,-0.0056739,-0.060722,-0.00040131,-0.089761,0.093645,-0.010891,-0.034573,0.19366,0.10511,0.034372,-0.2245,-0.36081,-0.61583,-0.83942,-0.6696,-0.36221,0.0066627,0.26147,0.099948,-0.068621,0.040599,-0.071044,0.058263,0.088033,-0.10117,-0.10919,-0.1322,0.011752,0.069756,0.14921,-0.1776,-0.37147,-0.604,-1.0611,-0.93781,-0.39069,0.10246,0.25172,0.14565,-0.051787,-0.034061,0.064981,-0.073977,-0.027435,-0.26803,-0.15314,-0.23172,-0.064518,0.078123,0.041445,-0.086634,-0.14783,-0.26658,-0.83529,-1.0136,-0.50153,-0.046052,0.12764,0.33461,0.10381,-0.043471,0.097545,-0.14552,-0.19602,-0.30254,-0.28365,-0.084993,-0.077328,0.094183,-0.27318,-0.35375,-0.13311,0.20393,-0.22696,-0.46719,-0.46719,-0.35416,-0.0094936,0.35877,0.038738,0.0040202,-0.021429,-0.080142,-0.084845,-0.43332,-0.2529,-0.16417,-0.10185,-0.31794,-0.45537,-0.31962,0.13783,0.2511,-0.085615,-0.28609,-0.4587,-0.60785,0.015609,0.38666,0.040313,-0.019431,0.042989,0.1152,-0.37657,-0.75037,0.089934,0.051876,-0.19004,-0.20982,0.10196,0.20233,0.44536,0.42031,0.11363,-0.29588,-0.49169,-0.67187,-0.17026,0.33973,0.097641,0.046732,-0.031193,0.11867,-0.65322,-0.67233,0.28981,0.16836,0.2842,0.63868,0.60287,0.59142,0.68779,0.43182,0.12465,0.041676,-0.47547,-0.40818,-0.087301,0.23301,-0.023065,-0.065168,0.096088,0.070982,-0.46909,-0.58713,0.0030161,0.21754,0.37086,0.37398,0.4198,0.49127,0.62243,0.04317,-0.18342,-0.23309,-0.47767,-0.36923,0.090641,0.23112,0.099728,-0.035024,0.0952,0.079777,-0.37428,-0.42559,0.089959,0.07339,0.077038,0.41655,0.64653,0.79454,0.70566,0.18731,-0.36328,-0.53415,-0.6158,-0.23148,0.0013228,0.24478,0.054802,0.031551,0.099043,0.1101,-0.10675,0.01617,0.14989,-0.25115,0.051853,0.34486,0.81557,0.71356,0.33228,-0.10695,-0.27477,-0.6027,-0.60856,-0.28038,0.049302,0.043629,0.014917,-0.0021531,-0.062587,-0.0085963,-0.0023692,-0.099841,-0.0078128,-0.31157,-0.12908,0.10604,0.34228,0.16038,-0.4044,-0.43984,-0.43432,-0.30514,-0.23053,-0.15999,0.060054,0.096039,-0.070286,-0.092359,0.028124,0.047512,0.12227,-0.181,-0.19821,-0.62835,-0.38963,-0.15383,-0.42532,-0.29514,-0.47428,-0.6015,-0.59383,-0.3607,-0.28402,-0.053158,0.15453,0.038726,-0.06279,-0.029032,-0.025872,0.037121,0.0094401,-0.232,-0.56324,-0.68366,-0.54607,-0.30629,-0.43038,-0.28359,-0.34671,-0.36747,-0.41546,-0.18375,-0.19182,0.0086666,0.054034,-0.066858,0.092895,0.060544,0.083951,0.091108,0.031496,-0.10689,-0.294,-0.40527,-0.14913,-0.085999,-0.21882,-0.065318,-0.21954,-0.23338,-0.086737,-0.11282,0.0068482,-0.080092,0.072894,0.065569,-0.092699,-0.02259,-0.084833,-0.004381,-0.060676,-0.026098,-0.06829,-0.14973,-0.069839,0.065851,-0.036535,0.039006,-0.0022155,0.012379,-0.067155,-0.022846,0.009574,-0.0058903,-0.007856,0.085721,-0.059883,0.00027304,0.034219,-0.083312,-0.04072,-0.10452,-0.0013685,0.027177,-0.0071129,0.05225,-0.0066197,-0.040128,-0.052005,-0.060504,0.029644,-0.051344,-0.061581,0.083733,-0.088678,-0.0035052,-0.029981},{-0.21768,-0.0019423,0.072987,-0.018415,-0.033231,-0.070967,-0.070033,-0.086257,-0.044135,-0.032537,0.013408,6.243e-005,-0.073787,0.0080327,0.017835,0.058721,0.030549,0.063334,-0.084367,0.072367,-0.074679,0.075862,-0.043371,-0.086732,0.088727,-0.031956,0.053509,0.033106,-0.013958,0.0041174,0.092242,0.084118,-0.043574,0.068585,0.08097,0.025055,0.053358,-0.0064573,-0.091018,0.082214,-0.0022448,-0.067006,0.0041762,0.074528,0.045679,-0.077795,0.04735,-0.055323,0.17507,0.19322,-0.080186,-0.16845,-0.040161,0.016734,-0.073127,-0.12781,-0.13536,0.0078214,0.070545,-0.025046,-0.06448,-0.085741,-0.00065138,-0.019318,-0.10436,-0.0042356,-0.022273,0.10354,0.25029,0.16131,-0.10892,-0.22131,-0.23595,-0.1207,-0.061952,-0.04226,0.0096242,-0.0051072,0.021211,0.022785,-0.025542,0.008733,-0.04273,0.050849,-0.19391,-0.16029,0.080197,0.33097,0.33235,-0.075444,-0.17917,-0.20755,-0.35926,-0.26815,-0.034974,0.30469,0.36883,0.25125,-0.093991,0.050239,-0.020848,-0.033212,-0.037437,0.034341,-0.19354,-0.085532,0.45467,0.64336,0.43186,-0.097934,-0.29713,-0.44985,-0.54196,-0.42133,0.047378,0.49268,0.69963,0.27334,0.062824,-0.11695,-0.062828,0.082768,-0.014357,0.022916,-0.19622,0.23025,0.61409,0.70941,0.53316,-0.19716,-0.41045,-0.3197,-0.56323,-0.65383,-0.16133,0.2887,0.49008,0.48349,0.22212,0.010149,-0.018232,-0.057863,0.062443,-0.099444,-0.14671,0.2142,0.39172,0.41834,0.45673,-0.0048802,-0.24874,-0.1436,-0.15345,-0.16233,-0.24031,0.15322,0.07881,0.86865,0.38118,0.021927,0.0079427,-0.066471,-0.031884,-0.062868,0.066947,0.24902,0.2515,0.3514,0.22107,0.21952,-0.19224,-0.40636,-0.20936,-0.17984,-0.21343,0.096136,0.561,1.0704,0.34927,-0.14294,0.14226,-0.029411,0.052666,-0.0066832,0.38059,0.44308,-0.0049579,-0.11784,0.20765,0.12508,-0.43438,-0.56598,-0.30091,-0.3533,-0.45294,-0.24109,0.50982,1.0836,0.24131,-0.0803,0.11351,0.083376,-0.032367,-0.11307,0.45236,0.36323,-0.37902,0.19012,0.40015,-0.17791,-0.22025,-0.56515,-0.26116,-0.29156,-0.40835,-0.52742,0.46021,0.87486,0.62546,-0.018473,0.03918,0.045071,-0.037737,-0.22505,0.42851,0.32887,-0.40008,0.27168,0.22993,-0.24769,-0.43227,-0.32338,-0.66657,-0.29892,-0.30034,-0.34411,0.31126,0.86393,0.64687,0.081815,0.10783,-0.0021759,-0.038275,-0.006371,0.36066,0.25922,-0.046291,0.35317,0.37642,-0.22839,-0.32946,-0.35525,-0.47698,-0.20913,-0.25573,0.12814,0.40811,0.51151,0.28752,-0.0061808,0.084458,-0.013413,-0.037706,-0.15107,0.16524,0.082616,0.24141,0.3893,0.29492,0.29349,-0.27142,-0.35342,-0.05355,-0.08921,0.0024388,-0.12717,-0.016755,0.31572,0.10554,-0.018008,0.044404,-0.074391,0.023887,-0.21882,-0.1219,0.28481,0.15151,0.25017,0.26821,-0.1053,-0.55135,-0.57411,0.1102,-0.024455,-0.23569,-0.25493,-0.082066,0.024753,-0.021702,-0.20213,0.0028053,0.0042536,0.016205,-0.15865,-0.051504,0.23658,0.1985,0.34697,0.24265,-0.097561,-0.23422,-0.51647,-0.10533,0.082364,0.12554,0.052407,0.12852,0.26987,0.027403,-0.055338,-0.067134,-0.01509,0.042918,-0.023163,-0.15255,0.095457,0.32612,0.80549,0.47174,0.096042,0.12929,0.16558,-0.087888,-0.046796,0.060734,-0.013052,0.1064,0.020343,-0.10196,-0.061545,0.013843,-0.010318,0.01471,0.070862,-0.077276,-0.073039,0.38543,0.64691,0.37031,-0.020994,0.022681,0.22103,0.1564,-0.05858,-0.10328,-0.14532,-0.061865,-0.010712,0.0080352,-0.030664,-0.088688,-0.040093,0.027284,0.065127,-0.0049291,0.0041123,0.052298,0.17373,-0.028011,-0.044613,-0.00086345,0.022847,-0.089754,0.016105,-0.10025,0.031823,0.057075,-0.018535,0.00050972,-0.09038,0.019502,0.049324,-0.036942,-0.042241,0.0014439,-0.031753,-0.027127,-0.040154,0.00081162,0.077136,0.030376,0.03545,0.085814,0.00051604,-0.030639,0.024911,-0.0078615,-0.038056,-0.034466,0.090571,-0.04041},{0.27753,-0.0855,0.00928,-0.040239,-0.059139,-0.0063405,0.022556,-0.023562,-0.014139,-0.076828,0.075442,-0.070276,-0.030886,0.083092,-0.05774,-0.0059548,-0.022707,0.017095,0.012613,-0.051579,-0.034132,-0.076571,-0.028844,0.032842,-0.017056,-0.04417,0.059235,0.074734,0.025618,-0.050176,0.032951,-0.0072256,-0.01595,-0.033653,-0.077255,-0.033287,-0.015542,0.015861,0.081225,-0.039685,0.032357,0.055862,0.044498,-0.030901,0.056122,0.069287,-0.054604,0.035218,-0.028616,0.14134,-0.012656,-0.024045,0.017206,0.068417,0.080979,0.083534,-0.093762,-0.026828,-0.029914,-0.071424,0.026063,-0.073431,0.064011,-0.0041099,-0.027393,-0.0053856,-0.0027067,0.0025101,0.1435,0.077091,0.11429,0.16073,0.19359,-0.01849,-0.18776,-0.20084,-0.15495,-0.014386,0.14552,-0.045861,0.049328,-0.058595,-0.049972,-0.06809,0.003446,-0.050362,-0.071093,0.21089,0.14143,0.073417,0.0017233,-0.01528,-0.11894,-0.078837,-0.17353,-0.30642,-0.48291,-0.094334,0.11597,0.03351,0.086359,-0.003189,-0.081975,-0.072657,-0.025583,-0.20741,-0.12671,0.16851,0.2138,0.18853,0.099903,0.026911,-0.099134,-0.029097,-0.16843,-0.48941,-0.56382,-0.1183,0.23198,0.19762,-0.056712,-0.015821,0.053706,-0.032051,-0.069707,-0.20395,0.034255,0.21359,0.1801,0.19679,0.11765,-0.032446,-0.082911,-0.030996,-0.316,-0.5768,-0.46428,-0.1601,0.12729,0.23706,0.051727,-0.044458,-0.12299,-0.11379,-0.062919,-0.28765,-0.0085987,0.23557,-0.029436,-0.15536,-0.12719,-0.10975,0.074387,-0.096687,-0.30383,-0.64247,-0.69598,-0.46952,0.039422,0.30141,0.03539,-0.068308,0.0546,-0.103,-0.29822,-0.36694,0.13646,0.18924,0.011174,-0.40874,-0.3674,-0.026831,0.4248,0.088188,-0.098359,-0.50653,-0.76822,-0.45106,0.27356,0.38016,-0.026242,-0.053403,-0.11034,-0.089218,-0.5716,-0.33701,0.42456,0.16804,-0.26121,-0.39644,-0.53408,-0.042544,0.2911,0.37032,0.068912,-0.34957,-0.55633,-0.43328,0.22115,0.2238,0.080064,-0.013754,-0.1308,-0.23116,-0.71382,-0.2829,0.30111,-0.046261,-0.44471,-0.40106,-0.59559,-0.22861,0.0034349,0.36273,0.24315,-0.20455,-0.61952,-0.35577,0.22003,0.31155,-0.0079486,-0.091726,0.050746,-0.29782,-0.59121,-0.30175,0.41173,0.29122,-0.078185,0.046303,0.2836,0.4675,0.53714,0.53904,0.22063,-0.38544,-0.62983,-0.10598,0.22558,0.16256,0.037328,0.019033,-0.13672,-0.32376,-0.63466,-0.28046,0.42576,0.40522,0.25241,0.49673,0.62251,0.54241,0.70268,0.47953,-0.14117,-0.44024,-0.30717,-0.2287,-0.0075161,0.10382,0.057365,0.0065571,-0.015274,-0.27127,-0.60979,-0.46862,-0.05736,0.18514,0.32582,0.44222,0.37195,0.40194,0.32286,0.08196,-0.33318,-0.38375,-0.19408,-0.27653,0.022518,0.025116,0.017322,-0.014579,-0.061376,-0.085147,-0.29232,-0.33925,-0.012561,0.30793,0.42901,0.1972,0.11831,0.084114,-0.18331,-0.43909,-0.41925,-0.22917,-0.2375,-0.037199,0.057539,0.18755,0.086181,-0.047229,0.078779,0.0097982,-0.11102,-0.19894,-0.061321,0.25842,0.32949,-0.058523,-0.179,-0.10553,-0.34751,-0.60142,-0.51438,-0.23234,-0.12502,-0.00081364,0.067441,0.091222,-0.036765,-0.036443,0.069662,-0.085948,0.016321,-0.12941,0.036624,0.097652,0.11754,-0.1176,-0.25156,-0.27392,-0.24058,-0.32521,-0.32257,0.05423,0.10255,0.075357,0.11352,0.035094,0.024838,-0.059499,0.039145,0.057554,-0.027437,0.028356,-0.042587,-0.095991,-0.031498,-0.062706,-0.20094,-0.13356,-0.25691,-0.040697,-0.0057204,0.014074,0.15297,0.0067856,0.096614,-0.00083566,0.020408,0.0087686,0.055096,-0.069475,0.062714,-0.041614,-0.0030441,0.05221,-0.030868,-0.099859,-0.043133,-0.059794,-0.011458,-0.12223,-0.0072366,0.061328,0.077222,0.01395,-0.012377,0.052817,-0.0091044,0.087421,0.036791,-0.089411,0.035588,-0.016184,0.032045,0.061138,-0.016654,0.090379,0.030282,0.047787,-0.029046,0.064064,0.033621,0.071104,-0.074428,0.059174,0.00085862,-0.085756,0.021578},{-0.29646,0.030138,-0.058153,0.056823,0.018198,-0.088807,0.052152,0.035448,0.0078446,0.087805,0.013454,-0.031039,-0.03735,0.0045206,-0.059717,-0.056809,0.087864,-0.021494,-0.058954,-0.025822,-0.047881,0.044623,-0.054413,-0.06812,-0.049128,-0.083985,-0.044469,-0.037313,0.092052,0.025477,-0.055086,0.087237,0.029144,0.10691,0.031962,-0.071391,-0.0013954,-0.047117,0.034064,-0.079246,-0.0115,-0.091419,0.082694,-0.03064,0.061371,0.041945,0.057035,0.0822,-0.043933,0.035644,-0.059633,-0.092251,-0.032439,0.095801,0.095358,0.24682,0.037863,0.13299,0.0050954,0.090391,-0.065909,0.049655,-0.059223,-0.031986,0.062693,0.11389,0.10895,0.15784,-0.083446,-0.12657,-0.090993,-0.17348,-0.0074943,0.017852,0.34494,0.40699,0.34124,0.19656,-0.025458,-0.055458,0.067035,0.062345,-0.046738,0.024804,0.086035,0.47935,0.30916,-0.0052462,-0.26803,-0.26089,-0.26151,-0.21728,-0.2287,-0.25093,-0.20849,0.18985,0.34903,0.25064,0.11749,0.035559,0.0083344,-0.0015676,-0.085201,-0.060708,0.29846,0.49952,-0.0167,-0.56925,-0.60664,-0.4378,-0.38733,-0.41481,-0.52974,-0.24677,-0.069525,0.076345,0.342,0.16362,-0.12665,-0.10202,-0.082818,0.031668,-0.032163,0.11385,0.16625,0.39365,-0.07008,-0.31316,-0.48104,-0.51201,-0.16552,0.086324,-0.11586,0.040374,0.53242,0.40021,0.2824,0.28242,-0.19512,-0.292,-0.051271,-0.064938,0.0093201,0.23671,0.20904,0.23605,-0.025663,-0.37376,-0.60654,-0.49058,-0.2654,-0.19275,-0.32473,-0.098381,0.48993,0.52603,0.54273,0.17203,-0.054238,-0.3328,-0.03801,0.016267,-0.029932,0.08929,0.14974,0.20204,0.06525,-0.34959,-0.80446,-0.55371,-0.38497,-0.35099,-0.41345,-0.095959,0.10783,0.39579,0.38203,-0.36022,-0.22484,-0.29403,0.0011183,0.085106,0.015119,0.22533,0.25166,0.090387,0.044013,-0.27674,-0.5058,-0.15495,0.13459,0.23504,0.38062,0.22986,0.23504,0.4274,0.078931,-0.51764,-0.2051,-0.078,-0.016305,-0.055324,0.16387,0.40545,-0.0042368,-0.1787,0.15512,-0.036306,0.18025,0.30692,0.65911,0.73587,0.53686,0.10165,0.096934,0.57148,0.36632,-0.3552,-0.28976,-0.16146,0.059196,-0.06729,0.14881,0.33254,0.15728,-0.32771,-0.2526,-0.15721,-0.1998,-0.025378,0.29052,0.20017,-0.11603,-0.12052,0.11745,0.47188,0.36122,-0.15962,-0.29931,-0.10999,-0.054643,0.081586,0.16117,0.42942,0.22354,-0.26606,-0.50619,-0.83189,-0.67463,0.0064984,0.26005,-0.039556,-0.062505,-0.028516,0.33872,0.39491,0.35567,-0.17104,-0.1471,0.061972,-0.047681,0.078976,0.15178,0.44405,0.419,0.18452,-0.58962,-0.90452,-0.51716,0.14563,-0.0561,-0.18301,-0.024822,0.3407,0.40473,0.51316,0.44187,-0.0016723,0.041586,0.083931,0.052126,0.047739,-0.02262,0.28143,0.33615,-0.20363,-0.46862,-0.5478,-0.17661,-0.036894,0.052963,0.075276,0.029702,0.32587,0.24146,0.43034,0.26101,0.0011339,0.073522,0.049129,0.07148,-0.077847,0.1092,0.27049,0.039984,-0.45006,-0.38705,-0.50462,-0.24818,-0.029543,-0.0095119,0.20973,0.3077,0.065111,0.043044,0.18634,-0.085548,-0.18698,-0.17248,-0.026155,-0.05135,0.076359,0.0043652,0.094819,-0.025739,-0.21606,-0.29177,-0.36314,-0.27466,-0.03483,0.095645,0.15427,0.15523,-0.032352,0.095659,0.19731,-0.065157,-0.16536,-0.032935,-0.076796,0.08464,0.024954,0.0028684,0.005241,-0.06726,-0.054028,-0.21198,-0.36155,-0.050214,0.13641,0.2072,0.24077,0.10139,0.032089,0.13163,0.20859,0.11061,-0.089611,0.027403,0.045673,-0.058047,-0.051007,0.072303,0.0494,-0.046137,-0.0050934,0.020277,-0.033381,0.032722,0.044526,-0.0013216,0.074657,-0.10552,-0.014459,-0.078753,0.088443,0.0012518,0.056379,-0.042024,-0.013041,0.091047,0.044132,-0.049076,-0.071979,0.0066396,0.113,0.041478,0.068822,-0.062013,-0.089078,-0.072435,0.0041704,0.010271,0.05227,0.054146,0.016873,0.0099695,0.011622,-0.017671,0.040844,-0.014067},{0.28923,0.079025,-0.0047764,-0.080374,-0.059326,0.0096227,0.023293,-0.024493,-0.074591,0.0089446,0.084853,-0.045119,-0.064574,0.048456,0.011396,0.039107,-0.036234,0.03895,0.080034,-0.075321,0.032396,0.070409,0.081606,0.060191,-0.080188,-0.067387,-0.055231,-0.039098,-0.058699,-0.017777,0.088781,-0.025995,0.055268,0.056754,0.04282,0.016886,0.064112,0.078535,0.022384,-0.059892,-0.047938,-0.078718,0.062998,-0.017275,-0.078632,-0.078736,0.031831,0.062609,0.079817,0.16687,0.010084,0.046866,0.068013,-0.018613,-0.075772,-0.020706,0.019297,-0.070612,-0.063817,0.069319,-0.075119,-0.042986,0.058617,-0.0043227,-0.038861,-0.0046035,0.11111,-0.03229,0.08886,0.035999,0.071945,0.10791,0.15463,0.029891,-0.15155,-0.1883,0.035494,0.040892,-0.03188,0.068434,-0.080698,0.012446,-0.064763,-0.061042,0.082365,0.044333,0.19174,0.086288,-0.062826,-0.051321,0.1978,0.42008,0.27425,0.0086208,0.010487,-0.083211,-0.10446,-0.04788,0.11839,0.098399,0.015172,-0.027171,-0.03613,0.085679,0.02239,0.18326,0.12958,-0.14378,-0.065418,0.035542,0.045499,0.30939,0.7171,0.30132,0.031233,-0.28051,-0.27203,0.045183,0.14511,0.063547,-0.085555,0.061555,0.027232,0.0062088,0.080094,0.097348,0.027624,-0.15314,0.044078,0.081535,-0.068276,0.20383,0.58317,0.46227,-0.033822,-0.16343,-0.046461,-0.0138,-0.050111,0.11669,0.031295,0.010437,0.063987,0.060494,0.085805,0.011533,0.012071,-0.01662,-0.11454,-0.10948,0.019325,-0.044105,-0.017106,0.21603,-0.067791,-0.038365,0.070198,-0.19797,-0.10168,0.13168,0.06997,0.019813,-0.0011473,0.04004,0.10554,-0.022246,0.0031061,-0.16433,-0.10055,-0.14084,-0.2519,-0.40933,-0.22215,0.083272,0.1403,0.13357,0.21241,-0.12461,0.07143,0.078812,0.088279,0.077431,-0.0018614,-0.097249,0.094585,-0.19383,-0.05497,-0.11718,-0.1468,-0.38177,-0.82118,-0.6785,-0.46941,0.11104,0.086152,0.26045,0.085751,-0.30962,-0.25294,0.051339,0.092549,-0.047007,0.072896,-0.034588,0.036943,-0.10565,-0.21645,-0.22754,-0.24814,-0.63878,-0.81118,-0.46706,-0.06721,0.36587,0.16243,0.12189,-0.26515,-0.28335,-0.18456,0.1284,0.014561,0.074329,0.015866,0.13816,-0.15248,-0.21316,-0.061469,0.018856,0.16838,0.058291,-0.27112,-0.13366,0.22795,0.2183,0.039972,0.12257,-0.2019,-0.30134,-0.20048,0.14258,0.051695,-0.085997,0.04816,0.20678,-0.058652,-0.1938,0.15627,0.17681,0.45208,0.35398,0.15196,0.029017,0.29739,0.19959,0.1433,0.072499,-0.15239,-0.52256,-0.25873,0.11029,0.093959,-0.074573,0.037997,0.1853,-0.057956,-0.26973,-0.31677,-0.023644,0.2186,0.035382,0.042155,0.31912,0.3465,0.30006,0.16191,0.041836,-0.24179,-0.45268,-0.17225,0.073386,-0.068815,-0.08017,0.093088,0.03623,0.099798,-0.069677,-0.27632,-0.16854,-0.0027136,0.11548,0.12156,0.5573,0.47091,0.24289,0.055844,-0.10441,-0.21107,-0.30626,-0.22052,0.0049318,0.0057881,0.024488,-0.037128,0.096033,-0.030751,0.10541,-0.0093389,-0.16153,0.0057268,0.23549,0.14279,0.44163,0.44193,0.12941,-0.031911,-0.12708,-0.086564,-0.25386,-0.022917,0.025383,0.0096457,0.081993,-0.063917,-0.055438,0.0088036,0.0096737,-0.16037,-0.30801,-0.012422,0.11168,0.34284,0.22947,0.31526,0.12276,-0.16137,-0.14867,-0.13376,-0.07491,-0.059446,-0.051817,0.040464,-0.047406,0.020094,-0.0884,-0.00049209,0.042408,-0.043032,-0.39221,-0.15454,-0.071168,0.035349,0.12842,0.017514,0.10695,-0.032347,-0.093679,-0.012394,0.011058,-0.0505,0.009609,-0.050689,0.033552,-0.014934,-0.0015766,-0.015915,-0.064973,-0.092334,-0.16334,-0.011481,-0.0591,0.044282,-0.011162,-0.04317,0.038642,-0.047496,0.080985,0.063993,0.036326,0.02427,0.03381,-0.075322,-0.042852,0.08502,-0.0074296,0.060455,-0.051116,-0.014542,0.02415,0.05387,0.026616,0.011049,0.0084869,0.039645,0.025176,0.062223,0.075118,0.016995,-0.080034,-0.0070817,-0.080556,-0.044672},{-0.79283,0.068319,0.013513,-0.057885,0.047749,0.043141,0.0054976,0.085092,0.028138,0.027079,-0.087522,0.076701,-0.062425,0.018677,0.0084456,-0.075859,-0.084044,-0.06561,0.017143,0.029794,0.07029,-0.011472,0.0018998,-0.014911,0.0066053,0.059941,0.090646,0.012196,-0.087633,0.015237,0.044196,0.066272,0.0121,0.071233,-0.037306,-0.029269,-0.096859,-0.054045,-0.057676,0.024341,0.060467,-0.08577,0.027457,-0.045481,0.056156,-0.10899,-0.058766,-0.055303,-0.21706,-0.072339,-0.037193,0.043735,-0.023882,-0.0076584,-0.19965,-0.15512,-0.098788,-0.00080209,0.025307,0.052052,0.035406,-0.036764,0.064128,-0.028853,0.00036765,-0.04948,-0.1256,-0.0048865,0.017712,0.28395,0.023544,-0.082469,0.055946,-0.206,-0.33789,-0.29688,-0.26129,-0.18601,-0.11513,-0.049692,-0.034682,0.046228,0.018095,-0.079696,-0.0299,-0.17754,-0.18833,-0.073799,0.18389,0.31051,0.091642,-0.044588,0.12059,-0.10243,-0.20978,-0.095869,-0.13364,-0.25321,-0.3578,-0.044906,-0.031468,0.048064,-0.029876,0.048973,0.10569,0.0093433,-0.10335,-0.26145,-0.067634,-0.10163,0.013086,0.42436,0.24211,0.24852,-0.021161,-0.38908,-0.38703,-0.28643,-0.44268,-0.22753,0.0096591,0.042152,-0.0053269,0.021649,0.21383,-0.1134,-0.19515,-0.26993,-0.16151,0.063856,0.22769,0.16612,0.39319,0.79018,0.58671,-0.36902,-0.39443,-0.42264,-0.46648,-0.20339,0.085651,-0.024403,0.089344,0.066325,0.085114,-0.028808,-0.13786,0.12629,0.37179,0.29577,0.29305,0.19562,0.66583,1.2748,0.75647,-0.14898,-0.25915,-0.37034,-0.27712,-0.35786,-0.088716,-0.089541,-0.079208,0.14476,0.32171,0.36924,0.085878,0.15957,0.2817,-0.08168,0.23882,0.55983,0.67107,0.64944,0.71596,0.31979,-0.096521,-0.22425,-0.4081,-0.094927,0.020765,-0.089424,0.10657,0.071522,0.47773,0.53875,-0.22316,0.0048775,-0.18476,-0.40166,-0.0089984,0.41269,0.33085,0.26669,0.30191,0.34839,0.18605,-0.071516,-0.32954,-0.063189,0.061381,0.014091,0.013157,0.025077,0.41642,0.16222,-0.68573,-0.41505,-0.7979,-0.68611,-0.1399,0.065651,0.080044,0.095834,0.078083,0.12643,-0.17189,-0.38396,-0.23484,-0.19303,0.031151,0.010323,0.11021,0.081273,0.27243,-0.0040077,-0.60407,-0.68788,-0.71613,-0.28505,0.058397,0.3557,0.53735,0.12043,0.48144,0.080642,-0.35241,-0.35871,0.09882,-0.14062,-0.016352,-0.041101,0.020968,0.10201,0.26547,0.28972,-0.38955,-0.57091,-0.35221,-0.25235,0.042689,0.44083,0.11761,0.10103,0.22829,0.10488,0.41142,0.18641,0.26897,-0.10088,-0.071852,-0.032884,0.016223,0.048704,-0.11477,-0.026628,-0.5265,-0.31486,-0.19646,-0.07525,0.18027,-0.11379,-0.42775,-0.58086,-0.56468,0.011551,0.40631,0.28963,0.2898,-0.059955,0.01124,-0.093217,0.029014,0.21117,-0.13156,-0.23863,-0.41025,-0.11089,0.22605,0.44482,0.35119,-0.12985,-0.48647,-0.59589,-0.32014,0.32769,0.16897,0.11449,0.29859,-0.065499,-0.061371,0.056084,0.01046,0.14175,0.0044166,-0.24016,-0.16954,-0.20579,0.19716,0.40812,0.084321,-0.20781,-0.23808,-0.090143,0.1735,0.27977,0.079055,0.23817,0.20638,-0.056318,0.021446,0.069082,-0.080153,0.047263,-0.093419,-0.020838,-0.28088,-0.14012,0.049843,0.098841,-0.061626,-0.27596,-0.31455,0.059841,0.31041,0.22496,0.156,0.15977,0.0031445,0.099423,-0.057744,-0.004849,-0.0466,0.054526,-0.12529,-0.081736,-0.18205,-0.15336,-0.039854,0.11191,-0.068659,-0.20025,-0.10802,0.039868,0.043917,0.039508,0.05585,-0.02133,-0.020116,-0.049785,-0.078188,-0.077266,0.021473,0.055452,0.080772,-0.015349,-0.067796,-0.25264,-0.044907,-0.058925,-0.042562,0.089177,0.053597,-0.0047739,-0.019134,-0.035706,-0.0023217,0.018975,0.064978,0.0047257,0.086761,-0.045759,0.037495,0.055009,0.0074372,-0.030631,0.053431,-0.059001,-0.037712,0.06222,-0.058627,0.01859,0.06207,0.089956,-0.00014264,0.090544,0.019503,-0.02375,0.019263,0.045977,0.024358},{0.37852,-0.010718,-0.050101,0.059154,-0.087122,0.014634,0.081152,-0.041706,0.056259,-0.069024,0.001467,0.014944,-0.038712,0.049982,-0.082702,-0.0063515,0.017169,-0.050217,-0.040707,0.02367,-0.034879,0.033161,0.024036,-0.019103,-0.079189,0.064607,-0.024697,-0.023891,0.0066164,0.075516,-0.030806,-0.046528,-0.084223,0.060106,-0.067134,0.003275,-0.073378,-0.0090639,0.010654,0.082721,0.073354,0.055878,0.0083921,0.0021433,0.034365,-0.024896,-0.12705,-0.15358,-0.19098,-0.20427,-0.083252,-0.12407,0.00059045,-0.071843,0.10668,0.023163,0.096293,0.068367,-0.022473,-0.0049105,0.0016941,-0.039776,0.012561,0.015435,0.015952,-0.04201,-0.23531,-0.32928,-0.27121,-0.27457,-0.069599,-0.17682,-0.14075,-0.20409,0.058629,0.17576,0.26298,0.25291,0.1689,0.056936,-0.078085,0.056512,-0.033298,-0.084193,-0.11756,-0.040603,-0.14526,-0.36018,-0.042792,-0.0010167,0.094746,0.013738,-0.25544,0.019789,0.17038,0.058833,0.057861,0.11414,-0.0039631,-0.057104,0.051152,-0.067983,0.042631,-0.083781,-0.093828,-0.10539,-0.47494,-0.50432,-0.096628,0.1392,0.25654,-0.17612,-0.31883,0.041096,0.59616,0.41555,0.10362,-0.10145,-0.064732,-0.04633,0.0088105,-0.0062421,-0.077918,-0.045225,-0.28189,-0.14321,-0.38106,-0.35141,0.0049306,0.11977,0.30692,0.50917,-0.11026,-0.038648,0.42894,0.5049,0.21919,0.30133,0.032671,-0.10132,-0.01045,-0.0030117,0.12488,0.009404,-0.06771,0.037961,-0.3563,-0.33085,-0.047499,0.34868,0.66135,1.0406,0.13603,-0.31728,0.31885,0.62454,0.36512,0.37281,0.29614,-0.1068,0.010034,0.022351,-0.025148,-0.048538,0.14038,0.13381,-0.28502,-0.013157,0.10345,0.37636,0.38373,0.41786,-0.62422,-0.80096,0.03167,0.61172,0.26957,0.29703,0.14767,0.038163,0.019247,0.078848,0.10491,0.21517,0.18178,0.14472,-0.12806,-0.015747,0.28186,0.32005,0.55654,0.12914,-0.51502,-0.70849,-0.16342,0.46426,0.24949,0.19779,0.068523,-0.053968,-0.048636,0.0042946,0.2636,0.42608,0.14728,-0.042419,0.12369,0.4067,0.56265,0.42752,0.33415,0.044554,-0.75281,-0.91076,-0.19494,0.33154,0.56004,0.29459,-0.10689,-0.066077,-0.026622,-0.01219,0.14023,0.45431,0.21995,-0.23513,0.25333,0.28748,-0.092672,-0.38401,-0.51626,-0.46659,-0.99695,-0.97567,-0.33775,0.18702,0.38244,0.026714,-0.10227,-0.079427,-0.058138,0.0080552,0.24504,0.45571,0.19906,0.1113,0.34711,0.19067,-0.44813,-0.73611,-0.58385,-0.26081,-0.65948,-0.83249,-0.051554,0.47999,-0.028737,-0.28806,-0.068777,-0.0057221,0.02627,-0.084548,0.077586,0.2121,0.13732,0.40267,0.35471,-0.04594,-0.59828,-1.0572,-0.5795,-0.48311,-0.56797,-0.066973,0.48026,0.24512,-0.03395,-0.19366,-0.038147,-0.043857,-0.0672,-0.053175,0.058415,0.042365,0.095671,0.10156,0.18595,-0.26189,-0.94291,-0.96173,-0.508,-0.021373,0.0038927,0.30525,0.48692,-0.00059106,-0.2632,-0.13946,0.033326,0.041486,-0.037393,-0.091943,0.099384,-0.036097,0.12251,-0.16682,0.063192,-0.050359,-0.43369,-0.25572,0.095465,0.54285,0.45654,0.46089,0.069144,-0.077925,-0.23695,-0.033845,-0.028699,0.016992,-0.12918,-0.03398,-0.016125,0.10275,0.053506,-0.0047987,0.2267,0.32547,-0.1018,0.020099,0.32168,0.5256,0.29338,0.09478,0.049174,0.082984,0.0046061,-0.093558,-0.024511,-0.0012431,-0.030958,0.019728,-0.029545,-0.01659,0.10545,0.064835,0.36702,0.47608,0.14394,0.02594,0.065713,0.13076,-0.042113,-0.058236,-0.079769,-0.075682,-0.021661,-0.066884,0.032168,0.013453,-0.0075879,-0.032851,0.064555,0.089808,-0.015826,0.068587,0.046836,0.2644,0.073403,-0.090295,0.093056,-0.070125,-0.12762,-0.15341,-0.035284,0.004392,-0.015359,-0.033433,-0.075737,-0.059798,-0.077358,0.052245,-0.058254,0.087913,0.078928,-0.040047,0.065598,-0.0091568,0.017807,0.092892,0.033907,-0.00017261,-0.0015207,0.060685,0.068958,-0.045401,0.040883,0.020562,-0.050844,-0.011615,-0.075446},{-0.61771,0.055735,0.054524,-0.043768,-0.027264,-0.045843,0.040039,0.061879,0.067478,-0.038724,-0.055906,0.01861,-0.065876,0.090204,0.055697,-0.0068873,-0.091376,-0.068488,0.043589,0.072278,0.078722,0.079611,0.018697,-0.0051464,-0.061153,-0.038612,-0.053759,-0.079738,-0.050219,0.048861,-0.086347,0.078893,0.024543,-0.075651,-0.089227,-0.075703,0.077437,0.080239,0.034394,0.078648,0.022166,0.0068409,0.046931,-0.031475,-0.020556,-0.043598,0.0043059,0.048958,0.07321,0.16325,0.032806,-0.044128,0.0013831,0.17199,0.19164,-0.013465,0.096775,0.08261,0.0071885,0.056059,0.075232,-0.025488,0.087708,0.080733,0.070354,0.12012,0.19815,0.24504,0.10458,-0.020471,-0.28974,-0.27395,-0.053548,0.21999,0.4304,0.47691,0.15192,0.08948,-0.0409,0.070389,-0.070126,0.016706,-0.0070723,0.07904,0.12097,0.11345,0.16242,0.22869,-0.082199,-0.4227,-0.78579,-0.63751,-0.39464,0.10263,0.41906,0.45779,0.40277,0.20352,0.017955,0.03282,-0.041124,-0.005544,0.031607,-0.0041752,0.14086,0.15373,0.07962,0.017289,-0.38809,-0.57557,-0.66548,-0.5249,-0.20431,-0.062191,0.26132,0.17515,0.24696,0.18944,-0.0035719,-0.0086442,-0.051476,-0.064826,-0.13435,-0.038987,0.28694,0.27265,-0.11237,-0.21932,-0.53427,-0.63239,-0.50545,-0.51026,-0.43754,-0.44067,0.18836,0.15084,0.15575,-0.14564,-0.13632,0.013388,0.1023,-0.046522,-0.1359,0.040087,0.32049,0.35696,0.077174,0.182,-0.41925,-0.74813,-0.93858,-0.69234,-0.51885,-0.57747,-0.15998,0.03886,-0.089703,-0.10438,0.047137,0.055995,-0.053929,-0.072856,0.040458,0.12029,0.45617,0.39241,0.47702,0.42599,-0.48609,-0.98421,-0.84417,-0.27701,-0.049401,-0.34573,-0.37018,-0.08645,-0.10037,-0.060396,0.038602,0.23172,-0.036969,0.037283,-0.033529,0.21256,0.77464,0.62026,0.79331,0.37737,-0.36937,-0.75966,-0.30632,0.46905,0.64629,0.19507,0.030721,-0.095294,-0.23918,0.02602,0.091388,0.22405,0.055044,-0.0092217,-0.092285,0.13562,0.55457,0.50809,0.75673,0.61361,0.30545,0.20994,0.55934,0.39668,0.28447,0.3837,-0.066636,-0.42311,-0.43753,-0.15729,0.11027,0.12308,-0.011966,0.025147,0.024045,0.067516,0.29932,0.38486,0.49946,0.55495,0.73907,0.38567,0.26746,0.18551,0.13733,0.074123,-0.23641,-0.67852,-0.31367,-0.064907,0.020332,0.1398,0.12584,0.048067,-0.1309,-0.20371,-0.15538,-0.12364,0.17528,0.71123,0.63686,0.13136,0.16837,0.27741,0.22308,-0.039133,-0.37022,-0.40758,-0.0028404,0.113,0.12502,0.10346,0.12838,-0.082697,-0.029302,-0.34144,-0.35558,-0.079621,0.40402,0.63565,0.60917,0.52983,0.36322,0.056568,0.0068301,-0.22622,-0.4262,-0.097785,-0.065453,-0.079731,0.033123,0.21446,0.040844,-0.016211,-0.014993,-0.33023,-0.49108,-0.057274,0.17663,0.4956,0.50806,0.62881,-0.056195,-0.51539,-0.5258,-0.38116,-0.18405,0.26091,0.14421,-0.063049,0.10592,0.1251,-0.00044971,0.053452,-0.064068,-0.14686,-0.34216,-0.33897,-0.18095,0.26359,0.48414,0.094975,-0.34252,-0.62632,-0.40397,0.006311,0.28452,0.41321,0.26129,0.04317,-0.067279,0.0048835,-0.052113,0.082443,0.0051341,-0.09409,-0.30683,-0.42925,-0.19954,0.12123,0.11938,-0.21199,-0.4532,-0.64965,-0.4951,-0.054826,0.35583,0.22585,0.17375,-0.077227,0.03075,-0.081569,0.031564,-0.057364,-0.017864,-0.087779,0.019812,-0.29057,-0.35932,-0.16096,-0.16492,-0.27141,-0.43388,-0.31361,-0.032168,0.25369,0.42915,0.26372,0.12549,-0.01916,-0.062469,-0.06503,-0.034003,0.034405,0.025288,-0.042546,-0.10452,-0.12475,-0.072559,-0.20378,-0.10984,0.0306,0.0509,0.021894,-0.079936,0.051912,0.043013,0.03803,0.0019381,0.074499,0.046129,-0.079106,0.064915,0.062655,0.087662,0.0061645,-0.066762,-0.020631,-0.012169,0.0041271,0.004682,0.052078,-0.020799,-0.025306,0.097054,0.049961,0.088202,-0.030858,-0.071629,-0.068085,0.0032152,-0.025882,0.062817},{0.39398,0.060716,-0.0020062,-0.090819,-0.077711,-0.039412,0.036512,0.039766,-0.06397,0.087127,-0.026748,0.047058,-0.073467,-0.017265,-0.069403,0.033923,0.044943,0.057098,-0.058455,-0.027189,0.013395,-0.021682,0.078233,0.049067,0.066446,0.0053884,0.048136,-0.035776,0.089718,0.057283,0.086282,-0.063455,0.075225,0.011359,0.088111,-0.0079362,0.061647,0.040866,0.035446,-0.07349,0.060305,-0.054484,-0.089448,0.026415,0.090542,0.079985,-0.028519,0.085641,-0.020574,-0.011658,-0.068372,-0.045072,0.060385,-0.036496,0.11216,-0.048854,0.033563,0.054499,0.043644,-0.021011,0.08852,0.074584,0.038081,0.035715,0.0048782,0.067723,0.10198,0.092984,0.17582,0.045945,-0.020183,-0.058224,-0.2074,-0.24243,-0.2074,-0.048232,0.0054087,0.068807,-0.023413,-0.084223,0.046645,-0.059086,0.045712,0.077833,0.11896,0.18612,0.2308,0.30604,0.12481,-0.14111,-0.46691,-0.51155,-0.61995,-0.49692,-0.64465,-0.48,-0.094793,0.024261,0.11163,-0.032345,-0.050841,-0.015412,0.082233,0.042176,0.25018,0.31179,0.28231,0.30124,0.055607,-0.50952,-0.83694,-1.0172,-0.71923,-0.45182,-0.63342,-0.52626,-0.1256,0.087297,0.07491,0.057939,0.056167,-0.0038187,-0.065385,0.02916,0.13135,0.21826,0.23594,0.25615,-0.21351,-0.84249,-1.2637,-1.1387,-0.49872,-0.2578,-0.14688,-0.3843,-0.36231,-0.22576,-0.15176,0.02282,0.053819,-0.018082,0.0057063,0.16123,0.21808,0.27359,0.24957,0.14333,-0.41926,-0.9503,-1.5333,-1.0452,-0.39535,0.21404,0.51781,0.24791,-0.38502,-0.6217,-0.27337,0.16221,0.013774,0.086645,0.050718,0.072945,0.3233,0.13504,-0.048538,0.20557,-0.24302,-0.89439,-1.3398,-1.0387,-0.014852,0.71706,0.95012,0.61292,-0.16274,-0.92573,-0.42581,0.20715,0.15229,0.057303,0.041775,0.2657,0.39266,-0.16316,-0.25287,0.12215,-0.2086,-0.60484,-0.72201,-0.0721,0.78533,1.0218,0.8681,0.57961,-0.38321,-0.89088,-0.28804,0.17095,0.13626,0.034048,0.14398,0.19864,0.28659,-0.52564,-0.39029,0.25198,0.43567,0.17239,0.15572,0.68845,0.8846,0.75034,0.61382,0.37177,-0.2363,-0.49758,-0.18756,0.15509,0.070715,-0.059876,0.056745,0.31533,0.23708,-0.55075,-0.4665,0.25473,0.52118,0.33309,0.40895,0.41831,0.15162,0.003148,0.07856,0.11014,-0.16769,-0.21783,-0.10937,0.12165,0.071968,-0.04664,0.12418,0.32519,0.022035,-0.7528,-0.37742,0.078785,0.27873,0.21225,0.29997,0.17135,0.1817,-0.22771,-0.029757,-0.045844,-0.20029,-0.13944,-0.18663,0.11845,0.022481,-0.056028,0.08236,0.20436,-0.012429,-0.61452,-0.4778,-0.31524,-0.19956,-0.081168,0.017511,-0.025064,-0.11803,-0.23979,-0.0036535,-0.040976,-0.053051,-0.071599,-0.19224,-0.069035,-0.028857,-0.066214,-0.060073,0.11319,-0.1142,-0.42285,-0.67607,-0.76511,-0.82747,-0.54554,-0.28818,-0.13079,-0.2035,-0.14538,0.044651,0.13549,0.076095,0.044152,-0.014655,-0.072931,-0.07146,-0.019622,0.051413,0.08272,0.0024733,-0.28939,-0.57737,-0.97181,-0.79625,-0.55721,-0.52345,-0.3603,-0.07293,-0.13661,-0.066372,0.045323,0.0071161,-0.037894,0.02476,-0.072392,-0.07792,-0.00089857,-0.022356,-0.0025586,-0.090544,-0.16328,-0.48595,-0.72723,-0.45179,-0.45974,-0.28374,-0.11482,-0.094527,-0.09717,0.01606,0.006128,0.10195,-0.003636,0.029278,0.061382,0.038117,0.075149,0.040457,0.045465,0.043375,-0.17258,-0.34674,-0.35737,-0.062515,-0.16059,0.04468,-0.068962,-0.065329,0.047584,0.13859,0.066616,0.075786,-0.099017,0.019522,0.037555,-0.012117,-0.048186,-0.0070806,-0.039687,-0.033366,-0.082182,0.0029751,-0.10447,0.041013,0.085627,0.065633,-0.029038,0.072973,0.072922,0.066927,0.054194,-0.07862,-0.030472,0.048914,0.077152,-0.011313,0.049281,0.081129,-0.020507,-0.041742,-0.034293,0.087662,-0.082355,-0.054886,0.023443,0.023019,0.008699,0.0089183,0.036525,0.030799,0.087607,-0.029099,-0.044406,0.080991,-0.0085467,-0.087317},{0.47357,0.00045992,-0.089895,-0.026476,-0.0021079,0.076951,0.086072,-0.077874,0.067618,-0.056927,0.038189,-0.016484,0.023303,0.080962,-0.0041462,0.079654,-0.034197,-0.01453,-0.042653,-0.036958,-0.0064873,-0.015613,-0.073039,0.045347,0.07771,-0.0054198,0.032684,-0.076614,-0.046683,-0.084151,-0.076922,0.066852,0.052213,-0.062783,0.01348,0.061915,-0.039543,0.038032,-0.064427,0.081837,0.043643,0.056969,0.082912,-0.0031771,-0.062947,0.0515,-0.086743,-0.048043,-0.024292,-0.068322,-0.041061,0.072202,0.080938,0.010883,0.029085,0.12477,0.11589,0.037873,0.050076,-0.051243,-0.04006,-0.059684,-0.018847,-0.013774,0.054491,0.019772,0.11358,0.0014996,-0.20416,-0.39798,-0.41793,-0.048428,-0.011059,0.31375,0.41955,0.43349,0.2351,0.14139,0.08153,0.053808,-0.01239,-0.071999,-0.028023,0.032344,0.030756,0.13345,0.19169,-0.0014056,-0.46624,-0.51182,-0.41814,-0.070769,0.15945,0.51161,0.7451,0.56823,0.31164,0.25687,0.056623,-0.11567,-0.086408,-0.001136,-0.050154,-0.084614,0.033488,0.29292,0.028395,-0.084079,-0.45272,-0.5905,-0.35073,0.1181,0.062199,-0.088417,0.44207,0.75809,0.34018,0.13897,-0.029878,-0.12089,-0.066152,-0.076333,-0.05343,0.067784,0.048559,0.084075,0.056743,-0.013859,-0.33822,-0.58605,-0.34831,0.084459,-0.017039,-0.85532,-0.18785,0.77856,0.33731,-0.011603,-0.12485,-0.031573,-0.07951,0.0073044,-0.088895,0.10514,0.022353,0.22483,0.24513,-0.085935,-0.35436,-0.47145,-0.090152,0.3123,0.10048,-0.54333,-0.52314,0.57908,0.53323,0.20982,-0.062741,-0.052711,-0.093403,0.07455,-0.038113,0.091446,0.047266,0.15752,0.49789,0.23231,-0.28106,-0.36088,-0.2194,-0.15398,-0.05767,-0.23001,-0.1544,0.50059,0.49261,0.26594,0.022496,-0.089479,-0.022216,-0.027668,-0.038973,0.12387,0.22257,-0.016932,0.48674,0.34492,-0.40963,-0.55401,-0.44624,-0.29358,-0.17994,-0.50792,-0.15028,0.51817,0.25857,0.15737,0.12388,-0.12128,-0.11564,0.029615,-0.12489,-0.023633,0.13578,0.090118,0.28486,0.27798,-0.13298,-0.73191,-0.69288,-0.53732,-0.252,-0.40939,0.0070201,0.32802,0.17068,0.15577,-0.0059971,-0.17464,-0.031449,0.016563,-0.052587,-0.066044,0.00026246,0.31775,0.21079,0.15713,-0.27491,-0.69029,-1.0082,-0.85742,-0.60411,-0.094544,0.18243,0.34596,0.26747,0.0064399,-0.17516,-0.044183,0.024609,0.081371,-0.051646,0.063838,0.13953,0.29745,0.18263,0.29205,-0.0076497,-0.4696,-0.45392,-0.52664,-0.41497,0.18488,0.54131,0.214,0.12408,0.042232,0.026577,-0.12901,-0.019076,0.070281,-0.065888,0.001159,0.070444,0.40822,-0.091658,0.22076,-0.077246,-0.37737,-0.18443,-0.54036,-0.091333,0.30747,0.22835,0.12352,0.31477,0.26045,0.18763,-0.092386,-0.0086694,0.040281,0.052399,0.079146,0.072959,0.13568,0.12339,-0.016256,-0.3149,-0.64537,-0.53049,-0.3931,-0.15594,-0.015232,-0.074579,0.27162,0.31141,0.20028,0.1385,-0.072329,-0.056684,0.037096,-0.10216,0.0096188,-0.049467,0.079987,0.37389,0.077602,-0.42811,-0.79393,-0.39118,-0.12074,0.15299,0.3426,0.53461,0.32549,0.21458,0.1253,0.017721,-0.011626,0.048889,-0.033581,0.041703,-0.019766,-0.032933,-0.043234,0.31291,0.032172,-0.50012,-0.36629,-0.093732,0.033156,0.21928,0.51144,0.50719,0.24097,-0.019487,0.029681,0.018169,-0.015841,-0.095748,-0.034283,-0.035279,0.011304,0.064829,0.12895,0.39261,0.20625,0.043641,-0.08958,-0.046201,0.107,0.13664,0.2061,0.29748,0.17117,-0.0062748,-0.10444,0.045121,0.033501,-0.028507,0.075673,-0.056832,-0.039562,0.026936,0.16651,0.14728,0.17316,0.033526,0.0036526,-0.030735,-0.026302,0.16946,0.023813,0.051846,-0.00080725,0.031778,0.063382,0.06754,0.068665,0.059792,-0.024574,0.071254,0.071047,-0.084911,0.025003,0.055179,-0.061131,0.02453,-0.078833,-0.080748,0.095789,-0.03304,-0.014021,-0.039783,0.044253,0.0077934,0.029464,0.040288,9.6298e-005,0.032589},{-0.2529,0.042953,-0.072224,0.061487,-0.044873,0.084804,0.077921,-0.06445,-0.07169,-0.080206,-0.042792,-0.085546,0.06928,0.093255,-0.067123,-0.058473,0.08532,0.051397,-0.01006,-0.079463,0.011667,0.035503,0.036178,0.019382,-0.0059044,0.0070121,-0.032256,-0.039939,-0.13944,-0.083798,0.051043,0.075071,-0.082471,-0.11529,-0.04515,-0.048768,0.061534,0.030097,0.082592,-0.042231,-0.0041741,-0.043206,-0.017996,0.01379,0.022486,-0.12347,-0.23769,-0.20589,-0.23667,-0.16962,-0.0015991,-0.040342,-0.029057,-0.12456,-0.17593,-0.14807,-0.078518,-0.14692,-0.083457,-0.083151,-0.055895,0.068814,-0.018368,-0.064941,-0.019329,-0.20342,-0.59988,-0.50923,-0.12148,0.31469,0.40907,0.37959,-0.057659,-0.40324,-0.34705,-0.22242,-0.21114,-0.25609,-0.30313,-0.034474,0.083502,-0.024938,0.02525,-0.04088,-0.1347,-0.79027,-0.80052,-0.56477,-0.034338,0.85953,1.1266,0.80858,0.17085,0.26478,0.38183,0.058911,0.085702,-0.24534,-0.46591,-0.15314,-0.033275,-0.03847,-0.036488,0.05258,-0.35033,-0.89916,-0.44525,-0.21162,0.14938,0.89781,1.0006,0.5753,0.13161,0.22411,0.38299,0.3834,0.093527,-0.34388,-0.46732,-0.2022,0.049703,0.027962,-0.022374,-0.084149,-0.39195,-0.55107,0.27054,0.12487,0.51465,0.78469,0.5721,-0.081536,0.15952,0.19247,0.31484,0.30109,0.0017292,-0.11444,-0.13518,-0.19849,-0.06802,0.062382,0.0061637,-0.061011,-0.44357,-0.18414,0.066676,0.090431,0.85651,0.81788,0.44208,0.065457,0.57691,0.7023,0.46248,0.052125,-0.036497,-0.016798,0.1091,-0.26472,-0.060162,-0.0061035,-0.029028,-0.26021,-0.38792,0.081525,-0.1694,0.049015,0.86036,0.66239,0.80194,0.50271,0.3209,0.33485,0.11302,0.14639,0.0084545,0.39032,-0.11491,-0.29413,-0.10439,0.081829,0.081136,-0.39625,-0.61705,0.09974,-0.30084,-0.28022,0.43122,0.48457,0.6329,0.18385,0.056563,0.023919,-0.13581,-0.24764,0.18519,0.30878,-0.32332,-0.079066,-0.09052,0.068295,0.081168,-0.09552,-0.445,0.19895,-0.043317,-0.51049,-0.73869,-0.25382,0.23762,-0.14421,-0.12341,-0.10623,-0.34557,-0.60397,-0.013351,-0.10113,-0.073898,0.064921,0.073615,-0.00072691,0.04984,-0.086632,-0.24114,-0.023745,0.27212,-0.60386,-1.0987,-0.13831,0.10431,-0.10534,0.089075,-0.053378,-0.33168,-0.33511,-0.10448,-0.29401,0.13454,0.043268,-0.14071,0.07939,-0.011603,-0.055457,0.0038764,0.13145,0.13957,-0.17449,-0.50188,-0.29745,-0.0648,0.40279,-0.080409,-0.071959,-0.22195,-0.19567,-0.064051,-0.0074603,0.18555,-0.01384,-0.073146,-0.023798,0.11141,0.087666,0.18216,0.019815,-0.29443,-0.42038,-0.31434,-0.2769,0.2554,0.10263,-0.47284,-0.58939,0.011374,-0.01179,0.020253,-0.083996,0.27037,0.02219,0.055652,0.019853,0.05447,0.16282,0.41876,0.18712,-0.45564,-0.51383,-0.34185,0.065451,0.15238,-0.29602,-0.54619,-0.057127,0.18519,-0.24657,-0.083884,0.16046,0.40992,0.069156,-0.10254,-0.0772,-0.086253,0.10968,0.62543,0.46629,-0.019013,-0.16894,-0.24513,0.2359,0.30292,-0.15963,-0.49131,-0.47347,-0.4014,-0.35307,-0.21819,0.24848,0.16761,0.068828,-0.003171,0.051062,-0.085373,0.0086674,0.1821,0.47007,0.63792,0.41853,0.10841,0.13534,0.3402,0.142,-0.17071,-0.39561,-0.046204,-0.049538,0.073875,0.02634,-0.0011314,0.050691,0.056085,0.082326,0.017959,-0.086094,-0.024994,0.40549,0.6377,0.60669,0.269,0.18153,0.10468,0.076835,-0.19014,-0.19352,-0.21865,-0.070227,0.038494,-0.083926,0.0063288,0.058885,-0.011629,-0.064072,-0.036003,0.083149,-0.0069428,0.11007,0.19317,0.13897,-0.05424,-0.10572,0.052056,-0.11482,-0.11613,-0.057902,-0.1257,-0.041452,-0.00013835,-0.033643,0.044471,-0.00047096,-0.041514,0.0029103,-0.063378,0.023872,-0.025097,-0.0059991,-0.052208,0.025408,0.080054,0.070297,0.044268,-0.08222,0.043859,-0.014509,0.080025,0.0597,0.020067,0.018663,-0.017957,0.068283,-0.071425},{0.86611,-0.086655,0.031617,0.085376,-0.023737,-0.073277,-0.0020996,0.046504,0.0062775,-0.079101,-0.057559,-0.079118,0.035858,-0.040385,-0.0054554,-0.089592,-0.082018,0.078418,0.07328,-0.018347,-0.030277,0.049941,-0.059721,-0.071945,-0.038962,-0.020992,-0.053663,-0.032722,0.03579,0.08705,-0.060141,0.014687,-0.060101,-0.059145,0.0050842,-0.0084435,0.04721,0.064016,0.0031611,0.034724,-0.010086,-0.0016323,0.089287,-0.034304,0.0038391,-0.051537,-0.1238,0.03497,0.26277,0.097218,0.13302,0.0019351,0.007841,-0.16271,-0.21981,-0.064531,-0.06913,0.042757,0.019067,-0.011288,0.0030592,-0.010148,0.0055062,-0.090294,-0.019409,-0.023671,-0.096955,-0.15176,0.16791,0.15392,0.21243,0.085654,0.13999,-0.027185,-0.30955,-0.52304,-0.21021,-0.039075,-0.080771,-0.0034838,-0.075001,-0.053739,-0.074871,0.038505,-0.17497,-0.26866,-0.2702,-0.072099,0.14021,0.6612,0.51735,0.13909,0.18169,0.26176,0.023829,-0.51501,-0.44201,-0.08484,0.028166,0.053149,-0.043241,0.069908,-0.019661,0.07855,-0.14519,-0.3379,-0.21443,-0.26575,0.19215,0.60449,0.4059,-0.11784,-0.22805,0.11159,0.33769,-0.081446,-0.3743,-0.14197,0.029927,0.17775,0.043218,-0.054065,-0.01225,-0.093988,-0.16082,-0.4097,-0.41987,-0.001017,0.3392,0.24405,0.19525,0.033346,-0.26931,-0.37337,-0.18864,-0.1384,0.054786,-0.1082,-0.25328,0.12386,0.091424,-0.011926,0.00042495,-0.14113,-0.30962,-0.51528,-0.25018,-0.0096895,0.32532,0.36267,0.35341,0.54561,-0.059331,-0.30513,-0.13447,0.14214,0.043654,-0.091426,-0.13852,0.23064,0.031533,0.051198,0.079372,-0.1554,-0.40487,-0.49476,0.0026895,0.039451,0.3592,0.18839,-0.28453,-0.42232,-0.48123,-0.39652,-0.29859,-0.081335,0.04254,0.026289,-0.027047,0.35314,0.023362,-0.067659,0.050111,-0.094073,-0.20411,-0.072787,0.49812,0.11253,0.21308,-0.077059,-0.37202,-0.3787,-0.75077,-0.71103,-0.20805,-0.21283,-0.10866,0.060081,-0.10751,0.27544,-0.065602,-0.052482,-0.094392,-0.12598,-0.39109,0.074148,0.80526,0.50667,0.66825,0.034382,-0.37676,-0.33636,-0.80839,-0.23269,-0.13133,-0.60345,-0.1489,0.045129,-0.051529,0.25908,-0.022078,0.048114,-0.0054789,-0.066822,-0.54154,0.014778,0.74197,0.15554,0.14425,-0.34341,-0.73442,-0.47603,-0.62712,-0.1001,-0.49478,-0.64737,-0.24446,-0.072071,0.33391,0.51633,0.056052,0.056931,0.022769,-0.21143,-0.62581,-0.0090917,0.64001,0.5766,0.60648,-0.080242,-0.51943,-0.094657,0.18255,0.083183,-0.20794,-0.36299,-0.42503,-0.31638,0.35379,0.52611,-0.037499,0.048793,0.049504,-0.18059,-0.31592,0.048288,0.34839,0.67454,0.68637,0.030906,-0.13401,0.018944,-0.215,-0.34135,-0.37158,-0.4243,-0.60957,-0.30475,0.16552,0.20288,-0.05358,-0.078092,0.017624,-0.30291,-0.31774,-0.009327,0.3482,0.15623,0.10246,-0.010068,-0.22788,-0.26864,-0.37042,-0.18875,-0.30952,-0.38306,-0.15915,-0.023343,0.099026,0.12803,0.10392,-0.033623,0.0004612,-0.12453,-0.23471,0.0036538,0.11712,0.22304,0.019804,0.13609,-0.03686,0.048419,-0.1015,-0.077969,-0.24336,-0.38631,-0.18072,-0.15012,0.075999,0.047001,-0.02429,0.046106,0.029541,-0.077027,-0.10646,-0.052353,0.05188,0.16969,-0.033347,0.10429,0.26374,0.23191,-0.011843,-0.1236,-0.23776,-0.143,-0.17229,-0.093412,0.07564,0.087365,0.012486,0.074218,0.022859,0.075905,0.1369,0.16257,0.26556,0.40362,0.095934,-0.0054884,-0.097946,0.016003,0.022208,-0.21719,-0.093631,-0.10336,-0.12281,0.05854,-0.049733,-0.053088,0.074565,-0.020193,0.0085718,-0.033841,0.038863,-0.0028735,0.0202,0.13314,0.093479,0.029906,0.05427,-0.0066098,-0.043455,0.05764,0.0071963,-0.087983,0.071396,-0.077946,0.055378,-0.082951,-0.038548,-0.0097564,-0.0082745,0.021441,-0.056839,0.018606,0.033684,0.054922,-0.073001,-0.0026041,-0.086254,-0.041586,-0.068064,-0.003394,-0.01965,0.012197,-0.046171,-0.062956,0.082697,-0.064839,-0.036698},{-0.040885,0.079048,0.003681,0.081809,-0.061779,0.06932,-0.0037978,-0.05438,0.022513,0.0060484,0.088264,0.04398,-0.077716,0.084238,-0.061528,-0.014837,-0.052873,0.052156,0.030669,-0.039752,-0.0069469,-0.051344,0.02363,-0.027122,0.0097823,0.058544,-0.050531,0.075226,0.0018973,-0.0169,-0.08504,0.078628,-0.031625,0.060104,-0.035329,0.056682,0.037883,-0.020263,-0.069258,0.046325,0.079284,-0.047923,-2.4966e-005,0.035886,0.030516,-0.047151,0.10451,-0.030721,0.081,-0.0072962,0.079306,-0.0011173,0.1111,-0.026838,0.050728,-0.0086159,0.053633,-0.076827,-0.054242,-0.077789,0.087008,0.05941,-0.054884,-0.00017867,-0.064634,-0.0048418,0.057709,0.011414,-0.011637,-0.073303,-0.093689,-0.075131,0.027127,0.080399,0.044019,0.16503,0.062549,0.024572,0.066587,-0.050503,0.024024,-0.0069525,-0.026002,-0.042763,0.0042895,0.029023,-0.033466,0.016203,-0.0053414,-0.15414,-0.054806,-0.07905,-0.030369,0.01629,0.23439,0.25144,0.26179,0.061928,0.027903,0.013786,-0.03475,-0.084622,0.025716,-0.094592,-0.11309,0.099339,0.24244,0.2398,-0.027562,0.0068901,-0.071962,0.031308,0.12389,0.066871,0.20539,0.35638,0.19944,0.23085,0.15387,-0.025276,0.063224,-0.068768,-0.069513,0.035921,0.022432,0.12895,0.15808,0.20801,0.027227,-0.052102,0.029304,-0.0029181,-0.094597,-0.047715,0.04604,0.13785,0.16706,0.19928,0.1548,0.043729,-0.077802,-0.016159,-0.093605,-0.10685,-0.038312,0.25638,0.19827,0.062881,0.14577,0.055467,-0.047509,-0.22215,-0.1766,0.082151,-0.11294,0.11235,0.23437,0.26103,0.12124,0.043884,0.02385,0.014316,0.00053764,0.010564,0.063197,0.27067,0.33505,0.25753,0.23919,0.051063,-0.0057573,-0.10992,0.015821,-0.093768,-0.28924,-0.1694,0.08816,0.31886,0.23962,0.10413,0.037557,0.059737,-0.02746,-0.076115,0.090909,0.1828,0.30988,0.24641,0.21002,0.12333,0.1086,0.094381,-0.02797,-0.074226,-0.31472,-0.23947,-0.037566,0.30573,0.23747,0.13784,0.024294,0.0019052,0.080876,-0.034357,0.13891,0.34742,0.23084,0.16959,0.037677,0.086546,0.056862,-0.20302,-0.22881,-0.16434,-0.18872,-0.26962,-0.044932,0.26142,0.17728,0.029971,0.10563,0.077152,0.043236,0.03909,0.098081,0.20282,0.31768,-0.036406,-0.00047036,-0.04344,-0.16507,-0.065329,-0.038772,0.086563,-0.055665,-0.16204,-0.053386,0.21029,0.1018,0.00054948,0.063828,0.079644,-0.059847,0.015292,0.16122,0.23031,0.14731,0.11693,-0.062972,-0.12689,-0.16386,0.016339,0.14089,0.10312,0.076265,-0.0012839,-0.0049927,0.0099535,0.13261,0.032803,-0.02471,-0.0025016,-0.03394,-0.067276,0.012798,0.14105,0.27867,0.088658,-0.0033466,-0.045427,-0.04851,0.020483,0.097698,0.17642,-0.0084546,0.15002,0.080861,-0.0058494,0.02552,0.045161,0.0070866,-0.065913,-0.044888,-0.070333,0.026,0.24672,0.40487,0.17137,0.13774,0.097947,-0.073827,-0.088228,-0.064794,-0.031276,-0.02448,0.12299,0.11431,0.097773,0.081612,0.0057216,0.017422,-0.043753,-0.085066,-0.071543,0.11936,0.12565,0.26427,0.27521,0.14788,0.041129,-0.018499,-0.0047803,-0.0052622,-0.071783,0.077141,0.19634,0.1684,0.066853,-0.033673,-0.0088678,0.036845,-0.088562,0.002747,-0.018845,0.015893,0.08088,0.19712,0.28304,0.092865,0.0096389,-0.15341,-0.15899,0.0018807,0.13414,0.047125,0.11511,0.048931,-0.0024717,-0.039186,0.007721,0.071189,-0.025532,-0.038546,-0.0070392,0.056251,0.10759,0.18737,0.083522,-0.067424,-0.029572,-0.12845,-0.08405,0.017466,0.1589,0.004823,0.030876,0.13434,-0.058151,-0.026955,-0.024731,0.067577,-0.0022981,-0.053912,0.0083069,0.055655,-0.053111,0.10222,0.0080094,-0.009691,0.06437,0.095152,0.067497,0.11725,-0.033041,0.053922,-0.065482,0.055151,0.044909,0.04696,0.037702,-0.02639,-0.083139,-0.028119,0.043742,-0.026073,-0.069187,-0.068597,0.020616,0.020971,0.013411,0.0077044,-0.024873,-0.011147,-0.075512,0.062975,0.090047,-0.028315,0.009633,0.049066,-0.017005,-0.036031},{0.40514,-0.063284,-0.075366,-0.0022825,-0.087601,-0.020545,-0.038576,-0.032053,-0.045819,-0.01074,0.026522,0.065787,0.038261,0.002842,-0.0092356,-0.091475,0.059839,0.011163,-0.072757,-0.031947,0.070538,0.03021,-0.072927,-0.082839,0.050821,-0.083055,-0.065401,-0.053982,-0.048507,0.013939,0.074242,-0.061101,0.028392,0.030554,-0.031819,0.089302,0.05187,0.07853,-0.014516,0.064501,0.060212,0.058173,0.0072905,0.064645,-0.061965,0.06909,0.0029338,0.0035367,0.052216,-0.024888,0.046331,-0.054862,-0.078386,0.033707,-0.069383,0.092523,0.017713,-0.016787,0.020459,-0.048944,-0.059351,0.088533,0.01513,-0.020564,-0.023221,0.057269,-0.011857,0.12855,0.0069239,0.11385,0.10986,-0.018396,0.11867,0.038088,0.10985,0.16617,0.024312,0.097579,0.029576,-0.077603,0.066869,0.048523,-0.018583,-0.047815,-0.015431,0.069094,0.025644,0.12872,0.11662,0.036446,0.11542,0.1611,0.13105,0.28948,0.37068,0.25976,0.11068,0.071157,-0.039737,-0.059296,-0.025761,0.082582,-0.015215,0.089917,-0.043341,0.049352,0.055804,0.32479,0.26502,0.11595,0.12922,0.1892,0.32045,0.30712,0.49587,0.41302,0.33187,0.21528,0.0073999,0.097257,0.028813,0.037756,0.067012,-0.058284,0.16577,0.20973,0.24039,0.39649,0.33949,0.27061,0.16522,0.28854,0.087921,0.032207,0.12942,0.28667,0.27968,0.065254,0.18552,-0.03296,0.035691,0.03885,0.049263,0.049393,0.13907,0.24558,0.37698,0.38371,0.1982,-0.04775,-0.011762,-0.077346,-0.031737,-0.16651,-0.32563,-0.18741,0.072058,0.06483,0.12972,0.037072,-0.042139,-0.041734,0.029821,0.059914,0.23267,0.37319,0.34105,0.30944,-0.037675,-0.068983,-0.14836,-0.14261,-0.24294,-0.35074,-0.26771,-0.26158,-0.1309,0.069921,0.054899,0.082239,-0.018599,-0.052996,0.071283,0.089012,0.20766,0.19264,0.13476,-0.022567,-0.1238,-0.19744,-0.29995,-0.37179,-0.073196,-0.012821,0.032158,-0.09775,-0.14042,-0.088176,0.18221,0.12823,0.060126,-0.061278,-0.11657,-0.081523,-0.013674,-0.063481,-0.13273,-0.19458,-0.16522,-0.31343,-0.45217,-0.21286,-0.041396,0.16321,0.16497,0.1088,-0.062012,-0.13621,0.18453,0.11132,0.081,0.069857,-0.073202,-0.059039,-0.038395,-0.038927,0.030024,0.0157,0.11522,0.036597,-0.24178,0.00094582,0.12795,0.31383,0.13938,0.0030052,0.065334,0.018715,0.058812,-0.016918,-0.03853,-0.030365,-0.028807,-0.19688,0.075468,0.018746,0.035645,0.16686,0.24348,-0.01616,0.006712,0.092194,0.17133,0.19882,0.012379,0.086917,0.051156,0.063117,-0.010222,-0.010496,-0.04433,0.036012,-0.11245,-0.19822,-0.091656,-0.0028365,0.22297,0.2827,0.26161,0.065206,0.05819,0.22311,0.13836,0.20528,0.098643,0.22748,0.076585,-0.10053,-0.082046,0.015273,-0.023431,0.067961,-0.1036,-0.066421,-0.054013,0.18734,0.27209,0.33871,0.40253,0.20984,0.22641,0.128,0.22394,0.059838,0.13087,0.15387,0.023058,-0.011333,-0.026795,-0.069796,0.024828,-0.056484,-0.070352,-0.045587,0.039274,0.11968,0.25328,0.27284,0.19049,0.04109,0.10996,0.099433,0.039051,0.097121,0.25882,0.19027,-0.0024803,0.064985,-0.076012,-0.028855,-0.066453,0.060296,-0.014099,-0.0019611,0.16309,0.12123,0.15099,0.23576,0.14064,0.1634,0.059018,0.12928,0.022093,0.11554,0.08001,0.17925,0.037457,0.022725,0.042616,-0.065731,-0.081183,-0.045397,-0.087298,-0.055409,0.09703,0.039377,0.073429,0.09833,0.0088049,0.10651,0.094,-0.037023,0.12245,0.054188,0.062499,-0.02875,0.072996,-0.068202,0.019979,0.072029,0.080894,-0.073493,-0.027748,-0.049023,-0.037955,0.048013,-0.031365,0.005584,0.0036259,0.071222,-0.074669,0.021505,-0.036625,-0.039825,0.059126,0.083732,-0.028855,-0.051958,-0.069964,-0.083126,-0.046695,-0.09204,-0.036749,-0.020421,-0.062523,-0.10928,0.00083975,-0.063154,-0.035826,-0.069117,0.030057,0.086797,0.079462,-0.014457,-0.055646,0.0007576,-0.0059909,0.0095413,-0.0049004,-0.023862,-0.0069884}}; float theta2[10][26] = {{1.2215,1.1279,-0.42843,-3.0932,0.14352,-1.6399,-1.2439,-2.4002,-3.6262,0.85534,1.1541,1.3883,1.019,-1.004,-2.1936,1.6224,-1.7697,-1.7175,0.57454,1.0563,2.9234,-1.5392,-1.0018,-0.89478,-1.2084,-0.53612},{-1.4423,-2.1078,0.05866,-2.826,1.1532,0.032075,-0.87852,-0.92615,2.0079,1.4834,-0.66015,-0.77221,-1.5608,-1.4902,-0.31935,-0.73975,0.10436,2.4692,-2.8977,2.7454,1.2421,3.3536,-2.5699,-0.96487,-0.65725,-0.25402},{-1.8845,1.7932,-3.0717,0.63079,1.1508,-0.81421,1.5577,0.27336,0.76842,-1.4064,0.50915,-2.2631,-0.8362,-0.3902,0.56114,1.1224,-1.6972,-2.0007,0.31008,1.1309,-1.46,-0.39652,-4.3507,-2.1855,-0.59192,-0.083352},{-0.45875,-0.023536,-1.9487,1.7402,-0.164,2.5325,-1.8336,0.33879,-0.76771,-0.92851,2.6017,1.2197,-0.070195,-2.5863,1.4016,-2.5485,0.69224,-0.35768,-1.626,-2.7357,-2.2788,-1.5471,0.44434,-3.1523,-0.87861,0.20837},{-0.51668,0.64819,-3.5052,-2.0086,-3.9409,1.6268,-0.77007,0.26104,-1.5029,0.91574,-0.47043,-0.61291,-2.5139,1.9997,0.2296,-0.81109,-1.7025,-1.2499,1.9067,-1.9206,-1.2425,1.7557,1.704,0.94143,-0.58843,0.69397},{-1.1127,-1.1075,2.5235,0.49168,-1.1865,1.5617,0.041393,-0.24006,-0.36603,0.31554,-2.3404,-0.26124,-0.73134,-1.6242,-1.3705,3.0842,0.021784,1.1329,0.96792,-4.1895,0.18507,-0.42785,1.1115,-1.7613,-2.8729,-2.4357},{-0.99877,1.0076,1.0493,0.62266,-1.1982,-3.1642,-1.4624,-2.2954,0.25048,-0.63285,0.97617,0.75781,0.24382,0.58044,1.0907,-1.6507,2.102,-2.3844,-1.8996,-1.1963,1.5592,-2.0046,-3.3764,1.3232,0.060719,0.60312},{-2.7064,-0.38211,0.067225,0.93756,1.0232,-1.6461,-0.67521,0.9662,-2.0888,1.4383,-0.47041,-0.95392,-3.2562,2.8768,-0.73988,-1.5499,-2.6255,2.2665,-1.5268,1.1626,-1.4588,-3.4896,2.3482,-2.0892,-0.69262,-0.28505},{-0.8762,-1.6195,-2.0916,0.93678,-1.7039,-4.442,0.84963,0.97816,-0.42344,-0.88363,-3.6065,1.5069,1.5605,-3.5811,1.1396,-1.0544,-0.4413,1.1048,-0.046322,0.48121,-1.3253,-2.4451,2.36,1.3419,0.069599,-0.53235},{-2.2003,-3.203,1.2796,-0.75908,1.4108,-0.1729,-0.36361,-1.5001,1.6733,-2.4471,-1.2483,-4.1725,-1.89,1.6089,-2.8517,-2.9627,0.7071,-0.39483,1.3218,-0.92507,-3.222,2.1221,1.0661,2.6448,-0.36446,-2.657}}; float h1[26]; float h2[10]; int i=0,j=0; // Feed Forward Network Implementation h1[0]=1.0; for(i=1;i<26;i++){ h1[i]=0.0; for(j=0;j<401;j++){ h1[i]+= (X[j]*theta1[i-1][j]); } h1[i] = 1.0/(1.0 + hls::exp(-1*h1[i])); } int num=0; float mm=-10.0; for(i=0;i<10;i++){ h2[i]=0.0; for(j=0;j<27;j++){ h2[i]+= (h1[j]*theta2[i][j]); } h2[i] = 1.0/(1.0 + hls::exp(-1*h2[i])); if(h2[i]>mm){ mm=h2[i]; num=i; } } return (num+1)%10; }
1,800.557692
90,562
0.720247
harshmittal2210
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
d039ca11426a50f4bee6054978cd1ce62fe85286
577
cpp
C++
sketches/libraries/AUnit/tests/FailingTest/ExternalTests.cpp
gtraines/Robot1
2dfd20dd574aa1ee53b37ce885769d7265d4934b
[ "MIT" ]
113
2018-04-25T12:42:28.000Z
2022-03-26T23:20:17.000Z
sketches/libraries/AUnit/tests/FailingTest/ExternalTests.cpp
gtraines/Robot1
2dfd20dd574aa1ee53b37ce885769d7265d4934b
[ "MIT" ]
47
2018-03-29T21:02:19.000Z
2022-01-10T15:22:40.000Z
sketches/libraries/AUnit/tests/FailingTest/ExternalTests.cpp
gtraines/Robot1
2dfd20dd574aa1ee53b37ce885769d7265d4934b
[ "MIT" ]
11
2018-07-16T16:42:42.000Z
2022-02-20T15:47:35.000Z
#line 2 "ExternalTests.cpp" #include "ExternalTests.h" testing(slow_fail) { static unsigned long start = millis(); if (millis() - start > 1000) fail(); } testing(slow_expire) { static unsigned long start = millis(); if (millis() - start > 1000) expire(); } testingF(CustomAgainFixture, fixture_slow_fail) { static unsigned long start = millis(); assertCommon(5); if (millis() - start > 1000) fail(); } testingF(CustomAgainFixture, fixture_slow_expire) { static unsigned long start = millis(); assertCommon(5); if (millis() - start > 1000) expire(); }
21.37037
51
0.682842
gtraines
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
d03d2b6fa92b70c9105d3bad279769bb501d12ba
3,519
cxx
C++
main/oox/source/ppt/customshowlistcontext.cxx
Grosskopf/openoffice
93df6e8a695d5e3eac16f3ad5e9ade1b963ab8d7
[ "Apache-2.0" ]
679
2015-01-06T06:34:58.000Z
2022-03-30T01:06:03.000Z
main/oox/source/ppt/customshowlistcontext.cxx
Grosskopf/openoffice
93df6e8a695d5e3eac16f3ad5e9ade1b963ab8d7
[ "Apache-2.0" ]
102
2017-11-07T08:51:31.000Z
2022-03-17T12:13:49.000Z
main/oox/source/ppt/customshowlistcontext.cxx
Grosskopf/openoffice
93df6e8a695d5e3eac16f3ad5e9ade1b963ab8d7
[ "Apache-2.0" ]
331
2015-01-06T11:40:55.000Z
2022-03-14T04:07:51.000Z
/************************************************************** * * Licensed to the Apache Software Foundation (ASF) under one * or more contributor license agreements. See the NOTICE file * distributed with this work for additional information * regarding copyright ownership. The ASF licenses this file * to you under the Apache License, Version 2.0 (the * "License"); you may not use this file except in compliance * with the License. You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, * software distributed under the License is distributed on an * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY * KIND, either express or implied. See the License for the * specific language governing permissions and limitations * under the License. * *************************************************************/ #include "customshowlistcontext.hxx" using namespace ::oox::core; using namespace ::com::sun::star::uno; using namespace ::com::sun::star::xml::sax; namespace oox { namespace ppt { class CustomShowContext : public ::oox::core::ContextHandler { CustomShow mrCustomShow; public: CustomShowContext( ::oox::core::ContextHandler& rParent, const ::com::sun::star::uno::Reference< ::com::sun::star::xml::sax::XFastAttributeList >& xAttribs, CustomShow& rCustomShow ); ~CustomShowContext( ); virtual ::com::sun::star::uno::Reference< ::com::sun::star::xml::sax::XFastContextHandler > SAL_CALL createFastChildContext( ::sal_Int32 aElementToken, const ::com::sun::star::uno::Reference< ::com::sun::star::xml::sax::XFastAttributeList >& /*xAttribs*/ ) throw ( ::com::sun::star::xml::sax::SAXException, ::com::sun::star::uno::RuntimeException ); }; CustomShowContext::CustomShowContext( ContextHandler& rParent, const Reference< XFastAttributeList >& rxAttribs, CustomShow& rCustomShow ) : ContextHandler( rParent ) , mrCustomShow( rCustomShow ) { mrCustomShow.maName = rxAttribs->getOptionalValue( XML_name ); mrCustomShow.mnId = rxAttribs->getOptionalValue( XML_id ); } CustomShowContext::~CustomShowContext( ) { } Reference< XFastContextHandler > SAL_CALL CustomShowContext::createFastChildContext( sal_Int32 aElementToken, const Reference< XFastAttributeList >& xAttribs ) throw ( SAXException, RuntimeException ) { Reference< XFastContextHandler > xRet; switch( aElementToken ) { case PPT_TOKEN( sld ) : mrCustomShow.maSldLst.push_back( xAttribs->getOptionalValue( R_TOKEN( id ) ) ); default: break; } if( !xRet.is() ) xRet.set( this ); return xRet; } //--------------------------------------------------------------------------- CustomShowListContext::CustomShowListContext( ContextHandler& rParent, std::vector< CustomShow >& rCustomShowList ) : ContextHandler( rParent ) , mrCustomShowList( rCustomShowList ) { } CustomShowListContext::~CustomShowListContext( ) { } Reference< XFastContextHandler > SAL_CALL CustomShowListContext::createFastChildContext( sal_Int32 aElementToken, const Reference< XFastAttributeList >& xAttribs ) throw ( SAXException, RuntimeException ) { Reference< XFastContextHandler > xRet; switch( aElementToken ) { case PPT_TOKEN( custShow ) : { CustomShow aCustomShow; mrCustomShowList.push_back( aCustomShow ); xRet = new CustomShowContext( *this, xAttribs, mrCustomShowList.back() ); } default: break; } if( !xRet.is() ) xRet.set( this ); return xRet; } } }
30.6
157
0.693379
Grosskopf
d03e365c096704d2170a00459cf6bb1fb6dde5d3
557
cpp
C++
Implementation/Project/src/AST/ASTSTMT/ASTWhileNode.cpp
migueldingli1997/CPS2000-Compiler-Theory-and-Practice-Assignment
6843fc5822d6faedb2970ebc260f1adaacb4b3c8
[ "MIT" ]
null
null
null
Implementation/Project/src/AST/ASTSTMT/ASTWhileNode.cpp
migueldingli1997/CPS2000-Compiler-Theory-and-Practice-Assignment
6843fc5822d6faedb2970ebc260f1adaacb4b3c8
[ "MIT" ]
null
null
null
Implementation/Project/src/AST/ASTSTMT/ASTWhileNode.cpp
migueldingli1997/CPS2000-Compiler-Theory-and-Practice-Assignment
6843fc5822d6faedb2970ebc260f1adaacb4b3c8
[ "MIT" ]
null
null
null
#include "ASTWhileNode.h" #include "../ASTExprNode.h" #include "ASTBlockNode.h" namespace AST { ASTWhileNode::ASTWhileNode(const ASTExprNode *expr, const ASTBlockNode *block) : expr(expr), block(block) {} const ASTExprNode *ASTWhileNode::getExpr() const { return expr; } const ASTBlockNode *ASTWhileNode::getBlock() const { return block; } void ASTWhileNode::Accept(VST::Visitor *v) const { v->visit(this); } ASTWhileNode::~ASTWhileNode(void) { delete expr; delete block; } }
22.28
112
0.637343
migueldingli1997
d03f76e910670f9995f26b62b4df01f19536b184
1,288
cpp
C++
src/test/current/source/NativeReplicatorStack/RCQNightWatchTXRService/RCQService.cpp
gridgentoo/ServiceFabricAzure
c3e7a07617e852322d73e6cc9819d266146866a4
[ "MIT" ]
2,542
2018-03-14T21:56:12.000Z
2019-05-06T01:18:20.000Z
src/test/current/source/NativeReplicatorStack/RCQNightWatchTXRService/RCQService.cpp
gridgentoo/ServiceFabricAzure
c3e7a07617e852322d73e6cc9819d266146866a4
[ "MIT" ]
994
2019-05-07T02:39:30.000Z
2022-03-31T13:23:04.000Z
src/test/current/source/NativeReplicatorStack/RCQNightWatchTXRService/RCQService.cpp
gridgentoo/ServiceFabricAzure
c3e7a07617e852322d73e6cc9819d266146866a4
[ "MIT" ]
300
2018-03-14T21:57:17.000Z
2019-05-06T20:07:00.000Z
//------------------------------------------------------------------------------ // Copyright (c) Microsoft Corporation. All rights reserved. //------------------------------------------------------------------------------ #include "stdafx.h" using namespace std; using namespace ktl; using namespace Common; using namespace TXRStatefulServiceBase; using namespace RCQNightWatchTXRService; using namespace TxnReplicator; StringLiteral const TraceComponent("RCQNightWatchTXRService"); RCQService::RCQService( __in FABRIC_PARTITION_ID partitionId, __in FABRIC_REPLICA_ID replicaId, __in Common::ComponentRootSPtr const & root) : NightWatchTXRService::Service(partitionId, replicaId, root) { } ComPointer<IFabricStateProvider2Factory> RCQService::GetStateProviderFactory() { KAllocator & allocator = this->KtlSystemValue->PagedAllocator(); return TestComStateProvider2Factory::Create(allocator); } NightWatchTXRService::ITestRunner::SPtr RCQService::CreateTestRunner( __in Common::ByteBufferUPtr const & testParametersJson, __in TxnReplicator::ITransactionalReplicator & txnReplicator, __in KAllocator & allocator) { RCQTestRunner::SPtr runner = RCQTestRunner::Create(testParametersJson, txnReplicator, allocator); return runner.RawPtr(); }
33.894737
101
0.696429
gridgentoo
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
d040714ae77a278f6f017b2acb45ef7ed008355e
546
cc
C++
src/prototools/commit.cc
imdea-software/legosnark
3f4a137c050371cf4dd51c3fe2d46a8eee60f8ee
[ "Apache-2.0", "MIT" ]
23
2019-09-09T15:11:48.000Z
2022-02-11T06:11:10.000Z
src/prototools/commit.cc
imdea-software/legosnark
3f4a137c050371cf4dd51c3fe2d46a8eee60f8ee
[ "Apache-2.0", "MIT" ]
1
2020-10-08T04:19:50.000Z
2020-10-08T20:37:13.000Z
src/prototools/commit.cc
imdea-software/legosnark
3f4a137c050371cf4dd51c3fe2d46a8eee60f8ee
[ "Apache-2.0", "MIT" ]
2
2021-05-29T09:13:29.000Z
2021-11-11T06:50:11.000Z
#include "commit.h" using namespace std; CommOut operator+(const CommOut& a, const CommOut& b) { if (a.lenXs != 1 || b.lenXs != 1) { throw runtime_error("Operations CommOut are only for commitments of single elements."); } return CommOut(a.c+b.c, a.r+b.r, a.xs[0]+b.xs[0]); } CommOut operator-(const CommOut& a, const CommOut& b) { if (a.lenXs != 1 || b.lenXs != 1) { throw runtime_error("Operations CommOut are only for commitments of single elements."); } return CommOut(a.c-b.c, a.r-b.r, a.xs[0]-b.xs[0]); }
28.736842
92
0.635531
imdea-software
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
d0496f8337a0e95da8a1d22831111358380bbbea
4,270
hpp
C++
third_party/omr/gc/base/standard/ConfigurationStandard.hpp
xiacijie/omr-wala-linkage
a1aff7aef9ed131a45555451abde4615a04412c1
[ "Apache-2.0" ]
null
null
null
third_party/omr/gc/base/standard/ConfigurationStandard.hpp
xiacijie/omr-wala-linkage
a1aff7aef9ed131a45555451abde4615a04412c1
[ "Apache-2.0" ]
null
null
null
third_party/omr/gc/base/standard/ConfigurationStandard.hpp
xiacijie/omr-wala-linkage
a1aff7aef9ed131a45555451abde4615a04412c1
[ "Apache-2.0" ]
null
null
null
/******************************************************************************* * Copyright (c) 1991, 2017 IBM Corp. and others * * This program and the accompanying materials are made available under * the terms of the Eclipse Public License 2.0 which accompanies this * distribution and is available at https://www.eclipse.org/legal/epl-2.0/ * or the Apache License, Version 2.0 which accompanies this distribution and * is available at https://www.apache.org/licenses/LICENSE-2.0. * * This Source Code may also be made available under the following * Secondary Licenses when the conditions for such availability set * forth in the Eclipse Public License, v. 2.0 are satisfied: GNU * General Public License, version 2 with the GNU Classpath * Exception [1] and GNU General Public License, version 2 with the * OpenJDK Assembly Exception [2]. * * [1] https://www.gnu.org/software/classpath/license.html * [2] http://openjdk.java.net/legal/assembly-exception.html * * SPDX-License-Identifier: EPL-2.0 OR Apache-2.0 OR GPL-2.0 WITH Classpath-exception-2.0 OR LicenseRef-GPL-2.0 WITH Assembly-exception *******************************************************************************/ /** * @file * @ingroup GC_Modron_Standard */ #if !defined(CONFIGURATIONSTANDARD_HPP_) #define CONFIGURATIONSTANDARD_HPP_ #include "omrcfg.h" #include "Configuration.hpp" #include "EnvironmentBase.hpp" #if defined(OMR_GC_MODRON_STANDARD) class MM_GlobalCollector; class MM_Heap; class MM_MemoryPool; class MM_ConfigurationStandard : public MM_Configuration { /* Data members / Types */ public: protected: /* Create Memory Pool(s) * @param appendCollectorLargeAllocateStats - if true, configure the pool to append Collector allocates to Mutator allocates (default is to gather only Mutator) */ virtual MM_MemoryPool* createMemoryPool(MM_EnvironmentBase* env, bool appendCollectorLargeAllocateStats); virtual void tearDown(MM_EnvironmentBase* env); bool createSweepPoolManagerAddressOrderedList(MM_EnvironmentBase* env); bool createSweepPoolManagerSplitAddressOrderedList(MM_EnvironmentBase* env); bool createSweepPoolManagerHybrid(MM_EnvironmentBase* env); static const uintptr_t STANDARD_REGION_SIZE_BYTES = 64 * 1024; static const uintptr_t STANDARD_ARRAYLET_LEAF_SIZE_BYTES = UDATA_MAX; private: /* Methods */ public: virtual MM_GlobalCollector* createGlobalCollector(MM_EnvironmentBase* env); virtual MM_Heap* createHeapWithManager(MM_EnvironmentBase* env, uintptr_t heapBytesRequested, MM_HeapRegionManager* regionManager); virtual MM_HeapRegionManager* createHeapRegionManager(MM_EnvironmentBase* env); virtual J9Pool* createEnvironmentPool(MM_EnvironmentBase* env); MM_ConfigurationStandard(MM_EnvironmentBase* env, MM_GCPolicy gcPolicy, uintptr_t regionSize) : MM_Configuration(env, gcPolicy, mm_regionAlignment, regionSize, STANDARD_ARRAYLET_LEAF_SIZE_BYTES, getWriteBarrierType(env), gc_modron_allocation_type_tlh) { _typeId = __FUNCTION__; }; protected: virtual bool initialize(MM_EnvironmentBase* env); virtual MM_EnvironmentBase* allocateNewEnvironment(MM_GCExtensionsBase* extensions, OMR_VMThread* omrVMThread); /** * Sets the number of gc threads * * @param env[in] - the current environment */ virtual void initializeGCThreadCount(MM_EnvironmentBase* env); private: static MM_GCWriteBarrierType getWriteBarrierType(MM_EnvironmentBase* env) { MM_GCWriteBarrierType writeBarrierType = gc_modron_wrtbar_none; MM_GCExtensionsBase* extensions = env->getExtensions(); if (extensions->isScavengerEnabled()) { if (extensions->isConcurrentMarkEnabled()) { if (extensions->configurationOptions._forceOptionWriteBarrierSATB) { writeBarrierType = gc_modron_wrtbar_satb_and_oldcheck; } else { writeBarrierType = gc_modron_wrtbar_cardmark_and_oldcheck; } } else { writeBarrierType = gc_modron_wrtbar_oldcheck; } } else if (extensions->isConcurrentMarkEnabled()) { if (extensions->configurationOptions._forceOptionWriteBarrierSATB) { writeBarrierType = gc_modron_wrtbar_satb; } else { writeBarrierType = gc_modron_wrtbar_cardmark; } } return writeBarrierType; } }; #endif /* OMR_GC_MODRON_STANDARD */ #endif /* CONFIGURATIONSTANDARD_HPP_ */
37.130435
161
0.759016
xiacijie
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
d0528e7cfae17c057ff549395fe11c7e5edfe1e2
7,274
cpp
C++
testing/Traffic_Map_Decomposition_Eclipse/mapdecompose.cpp
gusugusu1018/simmobility-prod
d30a5ba353673f8fd35f4868c26994a0206a40b6
[ "MIT" ]
50
2018-12-21T08:21:38.000Z
2022-01-24T09:47:59.000Z
testing/Traffic_Map_Decomposition_Eclipse/mapdecompose.cpp
gusugusu1018/simmobility-prod
d30a5ba353673f8fd35f4868c26994a0206a40b6
[ "MIT" ]
2
2018-12-19T13:42:47.000Z
2019-05-13T04:11:45.000Z
testing/Traffic_Map_Decomposition_Eclipse/mapdecompose.cpp
gusugusu1018/simmobility-prod
d30a5ba353673f8fd35f4868c26994a0206a40b6
[ "MIT" ]
27
2018-11-28T07:30:34.000Z
2022-02-05T02:22:26.000Z
/* Copyright Singapore-MIT Alliance for Research and Technology */ /** * argv[1] : node.weight * argv[2] : flow.data.size * argv[3] : infor.data.size * argv[4] : output folder * argv[5] : nparts (>=2) * argv[6] : load imbalance (>1) */ #include "all_includes.hpp" #include "algorithms/Configurations.hpp" #include "algorithms/MapDecompositionWithInformationFlow.hpp" #include "algorithms/MapDecompositionWithoutInformationFlow.hpp" #include "database/ChangeDatabasePartition.hpp" #include "database/DBConnection.hpp" //xuyan: add contiguous processing #include "algorithms/ContiguousProcessor.hpp" using namespace std; using namespace sim_mob_partitioning; /* * includes parameters that will change the behaviors of partitioning algorithm */ Configurations config; /** * supporting functions */ void show_menu(); bool is_file_or_folder_exist(const char* filename); bool check_user_inputs(char* argv[]); /** * start location */ int main(int argc, char* argv[]) { if (argc != 10) { show_menu(); cout << "Parameters in main function is not enough, program exit" << endl; return 1; } if (check_user_inputs(argv) == false) { show_menu(); cout << "Parameters setting not correct, program exit" << endl; return 1; } //load in road network from database config.node_sql = "get_node_bugis()"; config.section_sql = "get_section_bugis()"; config.network_node_file = "data/nodes.txt"; config.network_section_file = "data/sections.txt"; DBConnection connection; connection.loadInRoadNode(config); connection.loadInRoadSection(config); if (config.node_file.compare("NULL") == 0 || config.node_file.compare("null") == 0) connection.loadInRoadWeight(config); if (config.flow_file.compare("NULL") == 0 || config.flow_file.compare("null") == 0) connection.loadInRoadSectionWeight(config); std::cout << "Succeed to load in road network from DB for partitioning" << std::endl; /* *If there are information inputs, then use MapDecompositionWithInformationFlow *If not,use MapDecompositionWithoutInformationFlow */ if (config.infor_file.compare("NULL") == 0 || config.infor_file.compare("null") == 0) { MapDecompositionWithoutInformationFlow algorithm; algorithm.do_map_partitioning(config); } else { MapDecompositionWithInformationFlow algorithm; algorithm.do_map_partitioning(config); } //contiguous processing if(config.contiguous == true) { ContiguousProcessor processor; std::string partition_file = config.output_folder + "/hmetis.input.part."; partition_file += boost::lexical_cast<std::string>(config.nparts); config.partition_file = partition_file; processor.do_contiguous(config.network_node_file, config.network_section_file, partition_file); } //finally, output partition to DB if (config.database_config_file.compare("NULL") != 0 && config.database_config_file.compare("null") != 0) { ChangeDatabasePartition database_util; database_util.push_partitions_to_database(connection, config); std::cout << "You have updated the database!" << std::endl; } std::cout << "You have succeed to do partitioning!" << std::endl; return 0; } /* argv[1] : node.weight * argv[2] : flow.data.size * argv[3] : infor.data.size * argv[4] : output folder * argv[5] : nparts (>=2) * argv[6] : load imbalance (>1) */ void show_menu() { std::cout << "-------------------------------------------" << std::endl; std::cout << "Required Parameters" << std::endl; std::cout << "argv[1] : the input file describing CPU cost of each node (if you set NULL, means calculate default weight based on DB)" << std::endl; std::cout << "argv[2] : the input file describing Communication between nodes (if you set NULL, means calculate default weight based on DB)" << std::endl; std::cout << "argv[3] : the input file describing information exchange, if no such file, set NULL" << std::endl; std::cout << "argv[4] : the output folder, if you do not care medium results, set NULL" << std::endl; std::cout << "argv[5] : nparts: >= 2" << std::endl; std::cout << "argv[6] : load imbalance: >= 1, (suggestion: 1.05)" << std::endl; std::cout << "argv[7] : execute_speed: 0: fast; 1:medium; 2:slow, (suggestion: 2)" << std::endl; std::cout << "argv[8] : Contiguous (0: No Need; 1: Must Be)" << std::endl; std::cout << "argv[9] : database configuration: if you want to update Git database, specify the database configuration file, if not change database, set NULL" << std::endl; std::cout << "-------------------------------------------" << std::endl; } bool check_user_inputs(char* argv[]) { //input processing config.node_file = (argv[1]); config.flow_file = (argv[2]); config.infor_file = (argv[3]); config.output_folder = (argv[4]); config.nparts = boost::lexical_cast<int>(argv[5]); config.load_imbalance = boost::lexical_cast<double>(argv[6]); config.execute_speed = boost::lexical_cast<int>(argv[7]); config.contiguous = boost::lexical_cast<bool>(argv[8]); config.database_config_file = (argv[9]); if (config.nparts < 2) { std::cout << "nparts can not < 2" << std::endl; return false; } if (config.load_imbalance < 1) { std::cout << "load_imbalance can not < 1" << std::endl; return false; } if (config.execute_speed != 0 && config.execute_speed != 1 && config.execute_speed != 2) { std::cout << "execute_speed can only be 0,1,2" << std::endl; return false; } //file and folder check //if the node_file is NULL, it means algorithm will generate the file automatically, //based on length of lanes, from Database; if (config.node_file.compare("NULL") != 0 && config.node_file.compare("null") != 0) { if (is_file_or_folder_exist(config.node_file.c_str()) == false) { std::cout << "node_file not existing" << std::endl; return false; } } //if the flow_file is NULL, it means algorithm will generate the file automatically, //based on number of cut-lanes, from Database; if (config.flow_file.compare("NULL") != 0 && config.flow_file.compare("null") != 0) { if (is_file_or_folder_exist(config.flow_file.c_str()) == false) { std::cout << "flow_file not existing" << std::endl; return false; } } //if the infor_file is NULL, it means the data is not existing and not used in algorithm if (config.infor_file.compare("NULL") != 0 && config.infor_file.compare("null") != 0) { if (is_file_or_folder_exist(config.infor_file.c_str()) == false) { std::cout << "information_folder not existing" << std::endl; return false; } } if (config.output_folder.compare("NULL") == 0 || config.output_folder.compare("null") == 0) { config.output_folder = "temp_outputs"; } if (is_file_or_folder_exist(config.output_folder.c_str()) == false) { std::cout << "output_folder not existing" << std::endl; return false; } if (config.database_config_file.compare("NULL") != 0 && config.database_config_file.compare("null") != 0) { if (is_file_or_folder_exist(config.database_config_file.c_str()) == false) { std::cout << "database configuration file not existing" << std::endl; return false; } } return true; } /** * check the file exist */ bool is_file_or_folder_exist(const char* filename) { struct stat buffer; if (stat(filename, &buffer) == 0) return true; return false; }
30.822034
173
0.688617
gusugusu1018
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 <ndhist@martin-wolf.org> * * 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
d07022082e37b48f77f637b644b8a76809b71b91
5,284
hpp
C++
libahafront/aha/front/lexer.hpp
dlarudgus20/newly-aha
4d80bf992af3d8e7a6ddcca3c38d5959059ec66f
[ "MIT" ]
2
2017-08-12T11:23:37.000Z
2017-08-12T17:11:52.000Z
libahafront/aha/front/lexer.hpp
dlarudgus20/newly-aha
4d80bf992af3d8e7a6ddcca3c38d5959059ec66f
[ "MIT" ]
null
null
null
libahafront/aha/front/lexer.hpp
dlarudgus20/newly-aha
4d80bf992af3d8e7a6ddcca3c38d5959059ec66f
[ "MIT" ]
null
null
null
// The MIT License (MIT) // // Copyright (c) 2016 Im Kyeong-Hyeon (dlarudgus20@naver.com) // // 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. #pragma once #include <string> #include <string_view> #include <vector> #include <deque> #include <optional> #include <variant> #include <utility> #include "source.hpp" namespace aha::front { class lexer_error : public source_positional_error { public: lexer_error(source& src, source_position pos, const std::string& msg) : source_positional_error(src, pos, "lexer error: " + msg) { } }; enum class lex_result { done, exhausted, eof, error }; struct token_indent { unsigned level; }; struct token_newline { }; struct token_punct { std::u32string str; }; struct token_keyword { std::u32string str; }; struct token_contextual_keyword { std::u32string str; }; struct token_identifier { std::u32string str; }; struct token_normal_string { char32_t delimiter; std::u32string str; }; struct token_raw_string { char32_t delimiter; std::u32string str; }; struct token_interpol_string_start { std::u32string str; }; struct token_interpol_string_mid { std::u32string str; }; struct token_interpol_string_end { std::u32string str; }; struct token_number { unsigned radix; std::string integer, fraction, exponent, postfix; bool is_float; }; struct token { source* ptr_src; source_position beg; source_position end; std::variant< token_indent, token_newline, token_punct, token_keyword, token_contextual_keyword, token_identifier, token_normal_string, token_raw_string, token_interpol_string_start, token_interpol_string_mid, token_interpol_string_end, token_number > data; }; class lexer final { public: lexer(const lexer&) = delete; lexer& operator =(const lexer&) = delete; lexer(); ~lexer(); void clearBuffer(); void clearAll(); std::optional<token> lex(source& src); lex_result getLastResult() const; void enableInterpolatedBlockEnd(bool enable); void setContextualKeyword(std::vector<std::u32string> keywords); private: void init(); enum class state { indent, any, after_comment, error }; std::deque<char32_t> m_buf; source_position m_buf_beg; std::u32string m_str_token; source_position m_tok_beg; state m_state; std::u32string m_indent_str; std::vector<std::size_t> m_indent_pos; struct { bool identifier : 1; bool unknown_number : 1; bool binary : 1; bool octal : 1; bool heximal : 1; bool decimal : 1; bool punct : 1; bool normal_string : 1; bool raw_string : 1; bool interpol_string : 1; bool comment_line : 1; bool comment_block : 1; bool comment_block_contains_newline : 1; bool comment_block_might_closing : 1; bool commented_out : 1; bool interpol_string_after : 1; bool enable_interpol_block_end : 1; } m_flags; int m_idx_float_sep; int m_idx_float_exp; int m_idx_num_postfix; lex_result m_last_result; std::vector<std::u32string> m_contextual_keywords; static bool isSeperator(char32_t ch); static bool isIdentifierFirstChar(char32_t ch); static bool isIdentifierChar(char32_t ch); template <typename Exception> void throwError(Exception&& ex) { m_state = state::error; m_last_result = lex_result::error; throw std::forward<Exception>(ex); } }; }
25.282297
81
0.603331
dlarudgus20
d075e389e5d1cce583be41b567b3f6b92397a942
6,831
cc
C++
CalibCalorimetry/CastorCalib/plugins/CastorDbProducer.cc
Nik-Menendez/L1Trigger
5336631cc0a517495869279ed7d3a4cac8d4e5e5
[ "Apache-2.0" ]
3
2018-08-24T19:10:26.000Z
2019-02-19T11:45:32.000Z
CalibCalorimetry/CastorCalib/plugins/CastorDbProducer.cc
Nik-Menendez/L1Trigger
5336631cc0a517495869279ed7d3a4cac8d4e5e5
[ "Apache-2.0" ]
3
2018-08-23T13:40:24.000Z
2019-12-05T21:16:03.000Z
CalibCalorimetry/CastorCalib/plugins/CastorDbProducer.cc
Nik-Menendez/L1Trigger
5336631cc0a517495869279ed7d3a4cac8d4e5e5
[ "Apache-2.0" ]
5
2018-08-21T16:37:52.000Z
2020-01-09T13:33:17.000Z
// -*- C++ -*- // // Package: CastorDbProducer // Class: CastorDbProducer // /**\class CastorDbProducer CastorDbProducer.h CalibFormats/CastorDbProducer/interface/CastorDbProducer.h Description: <one line class summary> Implementation: <Notes on implementation> */ // // Original Author: Fedor Ratnikov // Created: Tue Aug 9 19:10:10 CDT 2005 // Adapted for CASTOR by L. Mundim // // // system include files #include <iostream> #include <fstream> #include "FWCore/Framework/interface/ESHandle.h" #include "CalibCalorimetry/CastorCalib/interface/CastorDbASCIIIO.h" #include "CalibFormats/CastorObjects/interface/CastorDbService.h" #include "CalibFormats/CastorObjects/interface/CastorDbRecord.h" #include "CondFormats/CastorObjects/interface/AllObjects.h" #include "CastorDbProducer.h" CastorDbProducer::CastorDbProducer(const edm::ParameterSet& fConfig) : ESProducer(), mDumpRequest(), mDumpStream(nullptr) { //the following line is needed to tell the framework what // data is being produced setWhatProduced(this); //now do what ever other initialization is needed mDumpRequest = fConfig.getUntrackedParameter<std::vector<std::string> >("dump", std::vector<std::string>()); if (!mDumpRequest.empty()) { std::string otputFile = fConfig.getUntrackedParameter<std::string>("file", ""); mDumpStream = otputFile.empty() ? &std::cout : new std::ofstream(otputFile.c_str()); } } CastorDbProducer::~CastorDbProducer() { // do anything here that needs to be done at desctruction time // (e.g. close files, deallocate resources etc.) if (mDumpStream != &std::cout) delete mDumpStream; } // // member functions // // ------------ method called to produce the data ------------ std::shared_ptr<CastorDbService> CastorDbProducer::produce(const CastorDbRecord& record) { auto host = holder_.makeOrGet([]() { return new HostType; }); bool needBuildCalibrations = false; bool needBuildCalibWidths = false; host->ifRecordChanges<CastorElectronicsMapRcd>( record, [this, h = host.get()](auto const& rec) { setupElectronicsMap(rec, h); }); host->ifRecordChanges<CastorChannelQualityRcd>( record, [this, h = host.get()](auto const& rec) { setupChannelQuality(rec, h); }); host->ifRecordChanges<CastorGainWidthsRcd>(record, [this, h = host.get(), &needBuildCalibWidths](auto const& rec) { setupGainWidths(rec, h); needBuildCalibWidths = true; }); host->ifRecordChanges<CastorQIEDataRcd>( record, [this, h = host.get(), &needBuildCalibrations, &needBuildCalibWidths](auto const& rec) { setupQIEData(rec, h); needBuildCalibrations = true; needBuildCalibWidths = true; }); host->ifRecordChanges<CastorPedestalWidthsRcd>(record, [this, h = host.get(), &needBuildCalibWidths](auto const& rec) { setupPedestalWidths(rec, h); needBuildCalibWidths = true; }); host->ifRecordChanges<CastorGainsRcd>(record, [this, h = host.get(), &needBuildCalibrations](auto const& rec) { setupGains(rec, h); needBuildCalibrations = true; }); host->ifRecordChanges<CastorPedestalsRcd>(record, [this, h = host.get(), &needBuildCalibrations](auto const& rec) { setupPedestals(rec, h); needBuildCalibrations = true; }); if (needBuildCalibWidths) { host->buildCalibWidths(); } if (needBuildCalibrations) { host->buildCalibrations(); } return host; // automatically converts to std::shared_ptr<CastorDbService> } void CastorDbProducer::setupPedestals(const CastorPedestalsRcd& fRecord, CastorDbService* service) { edm::ESHandle<CastorPedestals> item; fRecord.get(item); service->setData(item.product()); if (std::find(mDumpRequest.begin(), mDumpRequest.end(), std::string("Pedestals")) != mDumpRequest.end()) { *mDumpStream << "New HCAL/CASTOR Pedestals set" << std::endl; CastorDbASCIIIO::dumpObject(*mDumpStream, *(item.product())); } } void CastorDbProducer::setupPedestalWidths(const CastorPedestalWidthsRcd& fRecord, CastorDbService* service) { edm::ESHandle<CastorPedestalWidths> item; fRecord.get(item); service->setData(item.product()); if (std::find(mDumpRequest.begin(), mDumpRequest.end(), std::string("PedestalWidths")) != mDumpRequest.end()) { *mDumpStream << "New HCAL/CASTOR Pedestals set" << std::endl; CastorDbASCIIIO::dumpObject(*mDumpStream, *(item.product())); } } void CastorDbProducer::setupGains(const CastorGainsRcd& fRecord, CastorDbService* service) { edm::ESHandle<CastorGains> item; fRecord.get(item); service->setData(item.product()); if (std::find(mDumpRequest.begin(), mDumpRequest.end(), std::string("Gains")) != mDumpRequest.end()) { *mDumpStream << "New HCAL/CASTOR Gains set" << std::endl; CastorDbASCIIIO::dumpObject(*mDumpStream, *(item.product())); } } void CastorDbProducer::setupGainWidths(const CastorGainWidthsRcd& fRecord, CastorDbService* service) { edm::ESHandle<CastorGainWidths> item; fRecord.get(item); service->setData(item.product()); if (std::find(mDumpRequest.begin(), mDumpRequest.end(), std::string("GainWidths")) != mDumpRequest.end()) { *mDumpStream << "New HCAL/CASTOR GainWidths set" << std::endl; CastorDbASCIIIO::dumpObject(*mDumpStream, *(item.product())); } } void CastorDbProducer::setupQIEData(const CastorQIEDataRcd& fRecord, CastorDbService* service) { edm::ESHandle<CastorQIEData> item; fRecord.get(item); service->setData(item.product()); if (std::find(mDumpRequest.begin(), mDumpRequest.end(), std::string("QIEData")) != mDumpRequest.end()) { *mDumpStream << "New HCAL/CASTOR QIEData set" << std::endl; CastorDbASCIIIO::dumpObject(*mDumpStream, *(item.product())); } } void CastorDbProducer::setupChannelQuality(const CastorChannelQualityRcd& fRecord, CastorDbService* service) { edm::ESHandle<CastorChannelQuality> item; fRecord.get(item); service->setData(item.product()); if (std::find(mDumpRequest.begin(), mDumpRequest.end(), std::string("ChannelQuality")) != mDumpRequest.end()) { *mDumpStream << "New HCAL/CASTOR ChannelQuality set" << std::endl; CastorDbASCIIIO::dumpObject(*mDumpStream, *(item.product())); } } void CastorDbProducer::setupElectronicsMap(const CastorElectronicsMapRcd& fRecord, CastorDbService* service) { edm::ESHandle<CastorElectronicsMap> item; fRecord.get(item); service->setData(item.product()); if (std::find(mDumpRequest.begin(), mDumpRequest.end(), std::string("ElectronicsMap")) != mDumpRequest.end()) { *mDumpStream << "New HCAL/CASTOR Electronics Map set" << std::endl; CastorDbASCIIIO::dumpObject(*mDumpStream, *(item.product())); } }
38.8125
117
0.693456
Nik-Menendez
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
d07b45dc7241c183b2c63a07269928fb073f42e5
1,405
cpp
C++
libhext/src/ContainsWordsTest.cpp
brandonrobertz/hext
3b680096a7ab121bfd3cc728027e7fa9bcfae663
[ "Apache-2.0" ]
27
2019-06-23T21:31:44.000Z
2022-03-05T17:17:54.000Z
libhext/src/ContainsWordsTest.cpp
brandonrobertz/hext
3b680096a7ab121bfd3cc728027e7fa9bcfae663
[ "Apache-2.0" ]
15
2019-06-23T11:05:13.000Z
2021-12-29T12:51:48.000Z
libhext/src/ContainsWordsTest.cpp
brandonrobertz/hext
3b680096a7ab121bfd3cc728027e7fa9bcfae663
[ "Apache-2.0" ]
3
2021-03-20T10:08:25.000Z
2021-07-23T17:51:32.000Z
// Copyright 2015 Thomas Trapp // // 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 "hext/ContainsWordsTest.h" #include "StringUtil.h" #include <utility> #include <boost/algorithm/string.hpp> namespace hext { ContainsWordsTest::ContainsWordsTest(std::string words) : words_() { boost::trim_if(words, boost::is_any_of(" ")); boost::split(this->words_, words, boost::is_any_of(" "), boost::token_compress_on); } ContainsWordsTest::ContainsWordsTest(std::vector<std::string> words) noexcept : words_(std::move(words)) // noexcept { } bool ContainsWordsTest::test(const char * subject) const { if( !subject || this->words_.empty() ) return false; std::string str_subject = subject; for(const auto& w : this->words_) if( !hext::ContainsWord(str_subject, w) ) return false; return true; } } // namespace hext
23.813559
77
0.694662
brandonrobertz