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 |
|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|
f62d44c9ae61529633378a66943811cb0edbad84 | 1,239 | cpp | C++ | Sources/common/erm/rendering/data_structs/RenderConfigs.cpp | JALB91/ERM | 5d2c56db6330efc7d662c24796fdc49e43d26e40 | [
"MIT"
] | 5 | 2019-02-26T18:46:52.000Z | 2022-01-27T23:48:26.000Z | Sources/common/erm/rendering/data_structs/RenderConfigs.cpp | JALB91/ERM | 5d2c56db6330efc7d662c24796fdc49e43d26e40 | [
"MIT"
] | 1 | 2020-06-07T23:44:29.000Z | 2021-04-03T18:49:54.000Z | Sources/common/erm/rendering/data_structs/RenderConfigs.cpp | JALB91/ERM | 5d2c56db6330efc7d662c24796fdc49e43d26e40 | [
"MIT"
] | null | null | null | #include "erm/rendering/data_structs/RenderConfigs.h"
namespace erm {
const RenderConfigs RenderConfigs::DEFAULT_RENDER_CONFIGS {
SubpassData {
AttachmentData(
AttachmentLoadOp::CLEAR,
AttachmentStoreOp::STORE,
ImageLayout::UNDEFINED,
#ifdef ERM_RAY_TRACING_ENABLED
ImageLayout::GENERAL
#else
ImageLayout::COLOR_ATTACHMENT_OPTIMAL
#endif
),
AttachmentData(
AttachmentLoadOp::CLEAR,
#ifdef ERM_RAY_TRACING_ENABLED
AttachmentStoreOp::STORE,
#else
AttachmentStoreOp::DONT_CARE,
#endif
ImageLayout::UNDEFINED,
#ifdef ERM_RAY_TRACING_ENABLED
ImageLayout::GENERAL
#else
ImageLayout::DEPTH_STENCIL_ATTACHMENT_OPTIMAL
#endif
)}};
RenderConfigs::RenderConfigs(const SubpassData& subpassData)
: mSubpassData(subpassData)
{}
bool RenderConfigs::operator==(const RenderConfigs& other) const
{
return IsRenderPassLevelCompatible(other);
}
bool RenderConfigs::operator!=(const RenderConfigs& other) const
{
return !(*this == other);
}
bool RenderConfigs::IsRenderPassLevelCompatible(const RenderConfigs& other) const
{
return IsSubpassCompatible(other);
}
bool RenderConfigs::IsSubpassCompatible(const RenderConfigs& other) const
{
return mSubpassData == other.mSubpassData;
}
} // namespace erm
| 21.736842 | 81 | 0.786118 | JALB91 |
f62dbe57b051d83e747c9fba74632255747eb9a1 | 1,045 | cpp | C++ | Bit Manipulation/AND Product.cpp | StavrosChryselis/hackerrank | 42a3e393231e237a99a9e54522ce3ec954bf614f | [
"MIT"
] | null | null | null | Bit Manipulation/AND Product.cpp | StavrosChryselis/hackerrank | 42a3e393231e237a99a9e54522ce3ec954bf614f | [
"MIT"
] | null | null | null | Bit Manipulation/AND Product.cpp | StavrosChryselis/hackerrank | 42a3e393231e237a99a9e54522ce3ec954bf614f | [
"MIT"
] | null | null | null | /*
****************************************************************
****************************************************************
-> Coded by Stavros Chryselis
-> Visit my github for more solved problems over multiple sites
-> https://github.com/StavrosChryselis
-> Feel free to email me at stavrikios@gmail.com
****************************************************************
****************************************************************
*/
#include <cmath>
#include <cstdio>
#include <vector>
#include <iostream>
#include <algorithm>
using namespace std;
long long A, B;
inline long long solve()
{
long long sum = 0;
long long AA = A, BB = B;
long long val = 1;
while(A || B)
{
if(A % 2 && B % 2 && BB - AA < val)
sum += val;
val *= 2;
A /= 2;
B /= 2;
}
return sum;
}
int main()
{
int T;
scanf("%d", &T);
while(T--)
{
scanf("%lld %lld", &A, &B);
printf("%lld\n", solve());
}
return 0;
}
| 20.490196 | 64 | 0.378947 | StavrosChryselis |
f6301d5a4bed812c45991e5f220e2e92de000a7d | 1,663 | cpp | C++ | modules/params-triangle/test/test_params_triangle.cpp | gurylev-nikita/devtools-course-practice | bab6ba4e39f04940e27c9ac148505eb152c05d17 | [
"CC-BY-4.0"
] | null | null | null | modules/params-triangle/test/test_params_triangle.cpp | gurylev-nikita/devtools-course-practice | bab6ba4e39f04940e27c9ac148505eb152c05d17 | [
"CC-BY-4.0"
] | 3 | 2021-04-22T17:12:19.000Z | 2021-05-14T12:16:25.000Z | modules/params-triangle/test/test_params_triangle.cpp | taktaev-artyom/devtools-course-practice | 7cf19defe061c07cfb3ebb71579456e807430a5d | [
"CC-BY-4.0"
] | null | null | null | // Copyright 2021 Paranicheva Alyona
#include <gtest/gtest.h>
#include <cmath>
#include <iostream>
#include <utility>
#include "include/triangle.h"
TEST(Params_Triangle, Create_Triangle) {
std::pair<double, double> a(2.5, 0);
std::pair<double, double> b(0, 4.5);
std::pair<double, double> c(-1.5, 0);
ASSERT_NO_THROW(Triangle(a, b, c));
}
TEST(Params_Triangle, Calculate_SideAB) {
std::pair<double, double> a(0, 0);
std::pair<double, double> b(0, 4);
std::pair<double, double> c(3, 0);
Triangle tr(a, b, c);
double sideAB = tr.SideAB();
ASSERT_DOUBLE_EQ(4.0, sideAB);
}
TEST(Params_Triangle, Calculate_SideBC) {
std::pair<double, double> a(0, 0);
std::pair<double, double> b(0, 4);
std::pair<double, double> c(3, 0);
Triangle tr(a, b, c);
double sideBC = tr.SideBC();
ASSERT_DOUBLE_EQ(5.0, sideBC);
}
TEST(Params_Triangle, Calculate_SideAC) {
std::pair<double, double> a(0, 0);
std::pair<double, double> b(0, 4);
std::pair<double, double> c(3, 0);
Triangle tr(a, b, c);
double sideAC = tr.SideAC();
ASSERT_DOUBLE_EQ(3.0, sideAC);
}
TEST(Params_Triangle, Calculate_Perimeter) {
std::pair<double, double> a(0, 0);
std::pair<double, double> b(0, 4);
std::pair<double, double> c(3, 0);
Triangle tr(a, b, c);
double Perimeter = tr.Perimeter();
ASSERT_DOUBLE_EQ(12.0, Perimeter);
}
TEST(Params_Triangle, Calculate_Area) {
std::pair<double, double> a(0, 0);
std::pair<double, double> b(0, 4);
std::pair<double, double> c(3, 0);
Triangle tr(a, b, c);
double Area = tr.Area();
ASSERT_DOUBLE_EQ(6.0, Area);
}
| 26.396825 | 44 | 0.622971 | gurylev-nikita |
f63098e2ca87affc55081c3ae5b7011a1cf55a89 | 4,490 | cpp | C++ | HN_Path/HN_File.cpp | Jusdetalent/JT_Utility | 2dec8ff0e8a0263a589f0829d63cf01dcae46d79 | [
"MIT"
] | null | null | null | HN_Path/HN_File.cpp | Jusdetalent/JT_Utility | 2dec8ff0e8a0263a589f0829d63cf01dcae46d79 | [
"MIT"
] | null | null | null | HN_Path/HN_File.cpp | Jusdetalent/JT_Utility | 2dec8ff0e8a0263a589f0829d63cf01dcae46d79 | [
"MIT"
] | null | null | null | /*
* File source file
* By Henock @ Comedac
* 07/ 12/ 2016 :: 13:03
*/
#include "HN_File.hpp"
#include <cstring>
#include <cstdio>
#include <sys/stat.h>
using namespace hnapi::path;
// Static methods
bool hnapi::path::isFileExist(std::string &dirname)
{
// Obtain file statistics
struct stat fileStat;
int i = stat(dirname.c_str(), &fileStat);
/*
printf("%d %d %d %d %d %d %ld [%ld] %ld %ld %d\n",
fileStat.st_mode,
fileStat.st_ino,
fileStat.st_dev,
fileStat.st_nlink,
fileStat.st_uid,
fileStat.st_gid,
fileStat.st_size,
fileStat.st_atime,
fileStat.st_mtime,
fileStat.st_ctime,
i);
*/
if(i == -1 || !S_ISREG(fileStat.st_mode))
return false;
// Can arrive here only with success
return true;
}
bool hnapi::path::isFileAbsolutePath(std::string &path)
{
// Data pointers
const char *buffer = path.c_str();
int b_len = strlen(buffer), li = 0;
// Analyze if root
if(buffer[0] == '\\' || buffer[0] == '/')
return true;
// If driver
for(int i = 0; i < b_len; i++)
{
switch(buffer[i])
{
case '\\':
case '/':
{
if(li == ':'){return true;}
}
break;
}
li = buffer[i];
}
// Can not arrive here
return false;
}
bool hnapi::path::deleteFileFirstDirName(std::string &path)
{
return true;
}
bool hnapi::path::deleteFileFolderName(std::string &path)
{
return true;
}
bool hnapi::path::deleteFileFileName(std::string &path, int id)
{
return true;
}
std::string hnapi::path::getFileFileName(std::string &path)
{
// Generate pointers
const char *buffer = path.c_str();
int b_len = strlen(buffer), i_len = b_len;
bool breaked = false;
// Point on separator
for(; b_len >= 0; b_len--)
{
if(buffer[b_len] == '\\'
|| buffer[b_len] == '/')
{
breaked = true;
break;
}
}
if(b_len == 0 && !breaked)
return buffer;
// Build data to return
char filename[260];
int j = 0;
memset(filename, 0, 260 * sizeof(char));
for(b_len++; b_len < i_len; b_len++)
{
filename[j] = buffer[b_len];
j++;
}
// Return filename
return filename;
}
std::string hnapi::path::getFileFolderName(std::string &path)
{
// Generate pointers
const char *buffer = path.c_str();
int b_len = strlen(buffer);
bool breaked = false;
// Point on separator
for(; b_len >= 0; b_len--)
{
if(buffer[b_len] == '\\'
|| buffer[b_len] == '/')
{
breaked = true;
break;
}
}
if(b_len == 0 && !breaked)
return buffer;
// Build data to return
char filename[260];
int j = 0;
for(; j <= b_len; j++){
filename[j] = buffer[j];
}filename[j] = '\0';
// Return filename
return filename;
}
std::string hnapi::path::getFileExtension(std::string &path)
{
// Build data pointers
const char *buffer = path.c_str();
int b_len = strlen(buffer), i;
std::string extension;
// Place cursor
for(i = b_len; i >= 0; i--)
{
if(buffer[i] == '.')
{
break;
}
}
// Loop for getting file extension
for(i++; i < b_len; i++)
{
extension+= buffer[i];
}
return extension;
}
bool hnapi::path::isLocalFilePath(std::string &path)
{
// Verify if file exist
if(hnapi::path::isFileExist(path))
return true;
// Get file root
std::string root = hnapi::path::getFileRoot(path);
if(root == "file:")
return true;
// Unable to find it on local
return false;
}
std::string hnapi::path::getFileRoot(std::string &path)
{
// Build data pointers
const char *buffer = path.c_str();
int b_len = strlen(buffer), i;
std::string root;
// Loop for getting file root
for(i = 0; i < b_len; i++)
{
root+= buffer[i];
if(buffer[i] == ':')
break;
}
// Return root
return root;
}
| 20.883721 | 64 | 0.493318 | Jusdetalent |
f633bdf452f5afce93e3917645b0fcd09d5dde6d | 520 | cpp | C++ | project/src/Database.cpp | rushingvise/sqleicht | c9277896aceea60b5adddac61290034d547ab972 | [
"MIT"
] | null | null | null | project/src/Database.cpp | rushingvise/sqleicht | c9277896aceea60b5adddac61290034d547ab972 | [
"MIT"
] | null | null | null | project/src/Database.cpp | rushingvise/sqleicht | c9277896aceea60b5adddac61290034d547ab972 | [
"MIT"
] | null | null | null | #include "Database.h"
#include "Error.h"
using namespace sqleicht;
Database::Database(const std::string& filename, const Mode& mode) {
int rc = sqlite3_open_v2(filename.c_str(), &m_db, static_cast<int>(mode), nullptr);
if (Error::has_occurred(rc, m_db)) {
// Failure!
sqlite3_close(m_db);
m_db = nullptr;
}
}
Database::~Database() {
if (is_valid()) {
sqlite3_close(m_db);
m_db = nullptr;
}
}
bool Database::is_valid() const {
return m_db != nullptr;
}
| 20.8 | 87 | 0.615385 | rushingvise |
f6341801ae9d29d0e6d9cc0f105e1878ad239e9f | 9,079 | cpp | C++ | oaz/neural_network/nn_evaluator.cpp | ameroueh/oaz | 7cf192b02adaa373b7b93bedae3ef67886ea53af | [
"MIT"
] | 8 | 2021-03-18T16:06:42.000Z | 2022-03-09T10:42:44.000Z | oaz/neural_network/nn_evaluator.cpp | ameroueh/oaz | 7cf192b02adaa373b7b93bedae3ef67886ea53af | [
"MIT"
] | null | null | null | oaz/neural_network/nn_evaluator.cpp | ameroueh/oaz | 7cf192b02adaa373b7b93bedae3ef67886ea53af | [
"MIT"
] | null | null | null | #include "oaz/neural_network/nn_evaluator.hpp"
#include <stdint.h>
#include <functional>
#include <future>
#include <iostream>
#include <memory>
#include <queue>
#include <string>
#include <thread>
#include <utility>
#include "boost/multi_array.hpp"
#include "oaz/utils/time.hpp"
#include "tensorflow/core/framework/tensor.h"
oaz::nn::EvaluationBatch::EvaluationBatch(
const std::vector<int>& element_dimensions, size_t size)
: m_current_index(0),
m_n_reads(0),
m_size(size),
m_element_size(std::accumulate(element_dimensions.cbegin(),
element_dimensions.cend(), 1,
std::multiplies<int>())),
m_games(boost::extents[size]),
m_values(boost::extents[size]),
m_policies(boost::extents[size]),
m_tasks(boost::extents[size]),
m_statistics(std::make_unique<oaz::nn::EvaluationBatchStatistics>()) {
std::vector<tensorflow::int64> tensor_dimensions = {
static_cast<tensorflow::int64>(size)};
tensor_dimensions.insert(tensor_dimensions.end(), element_dimensions.begin(),
element_dimensions.end());
m_batch = tensorflow::Tensor(tensorflow::DT_FLOAT,
tensorflow::TensorShape(tensor_dimensions));
GetStatistics().time_created = oaz::utils::time_now_ns();
GetStatistics().size = GetSize();
}
oaz::nn::EvaluationBatchStatistics& oaz::nn::EvaluationBatch::GetStatistics() {
return *m_statistics;
}
void oaz::nn::EvaluationBatch::InitialiseElement(
size_t index, oaz::games::Game* game, float* value,
const boost::multi_array_ref<float, 1>& policy,
oaz::thread_pool::Task* task) {
float* destination = m_batch.flat<float>().data() + index * GetElementSize();
game->WriteCanonicalStateToTensorMemory(destination);
m_games[index] = game;
m_values[index] = value;
m_policies[index] =
std::move(std::make_unique<boost::multi_array_ref<float, 1>>(policy));
m_tasks[index] = task;
++m_n_reads;
}
bool oaz::nn::EvaluationBatch::IsAvailableForEvaluation() const {
return m_current_index == m_n_reads;
}
size_t oaz::nn::EvaluationBatch::AcquireIndex() {
size_t index = m_current_index;
++m_current_index;
return index;
}
boost::multi_array_ref<oaz::games::Game*, 1>
oaz::nn::EvaluationBatch::GetGames() {
return boost::multi_array_ref<oaz::games::Game*, 1>(
m_games.origin(), boost::extents[GetSize()]);
}
boost::multi_array_ref<float*, 1> oaz::nn::EvaluationBatch::GetValues() {
return boost::multi_array_ref<float*, 1>(m_values.origin(),
boost::extents[GetSize()]);
}
boost::multi_array_ref<std::unique_ptr<boost::multi_array_ref<float, 1>>, 1>
oaz::nn::EvaluationBatch::GetPolicies() {
return boost::multi_array_ref<
std::unique_ptr<boost::multi_array_ref<float, 1>>, 1>(
m_policies.origin(), boost::extents[GetSize()]);
}
size_t oaz::nn::EvaluationBatch::GetSize() const { return m_size; }
size_t oaz::nn::EvaluationBatch::GetElementSize() const {
return m_element_size;
}
tensorflow::Tensor& oaz::nn::EvaluationBatch::GetBatchTensor() {
return m_batch;
}
float* oaz::nn::EvaluationBatch::GetValue(size_t index) {
return m_values[index];
}
boost::multi_array_ref<float, 1> oaz::nn::EvaluationBatch::GetPolicy(
size_t index) {
return *(m_policies[index]);
}
void oaz::nn::EvaluationBatch::Lock() { m_lock.Lock(); }
void oaz::nn::EvaluationBatch::Unlock() { m_lock.Unlock(); }
bool oaz::nn::EvaluationBatch::IsFull() const {
return m_current_index >= GetSize();
}
size_t oaz::nn::EvaluationBatch::GetNumberOfElements() const {
return m_current_index;
}
oaz::thread_pool::Task* oaz::nn::EvaluationBatch::GetTask(size_t index) {
return m_tasks[index];
}
oaz::nn::NNEvaluator::NNEvaluator(
std::shared_ptr<Model> model, std::shared_ptr<oaz::cache::Cache> cache,
std::shared_ptr<oaz::thread_pool::ThreadPool> thread_pool,
const std::vector<int>& element_dimensions, size_t batch_size)
: m_batch_size(batch_size),
m_model(std::move(model)),
m_cache(std::move(cache)),
m_n_evaluation_requests(0),
m_n_evaluations(0),
m_thread_pool(std::move(thread_pool)),
m_element_dimensions(element_dimensions) {
StartMonitor();
}
oaz::nn::NNEvaluator::~NNEvaluator() {
m_exit_signal.set_value();
m_worker.join();
}
void oaz::nn::NNEvaluator::Monitor(std::future<void> future_exit_signal) {
while (future_exit_signal.wait_for(std::chrono::milliseconds(
WAIT_BEFORE_FORCED_EVAL_MS)) == std::future_status::timeout) {
ForceEvaluation();
}
}
void oaz::nn::NNEvaluator::StartMonitor() {
std::future<void> future_exit_signal = m_exit_signal.get_future();
m_worker = std::thread(&oaz::nn::NNEvaluator::Monitor, this,
std::move(future_exit_signal));
}
void oaz::nn::NNEvaluator::AddNewBatch() {
std::shared_ptr<oaz::nn::EvaluationBatch> batch =
std::make_shared<oaz::nn::EvaluationBatch>(GetElementDimensions(),
GetBatchSize());
m_batches.push_back(std::move(batch));
}
const std::vector<int>& oaz::nn::NNEvaluator::GetElementDimensions() const {
return m_element_dimensions;
}
size_t oaz::nn::NNEvaluator::GetBatchSize() const { return m_batch_size; }
void oaz::nn::NNEvaluator::RequestEvaluation(
oaz::games::Game* game, float* value,
boost::multi_array_ref<float, 1> policy, oaz::thread_pool::Task* task) {
if (m_cache && EvaluateFromCache(game, value, policy, task)) {
return;
}
EvaluateFromNN(game, value, policy, task);
}
bool oaz::nn::NNEvaluator::EvaluateFromCache(
oaz::games::Game* game, float* value,
const boost::multi_array_ref<float, 1>& policy,
oaz::thread_pool::Task* task) {
bool success = m_cache->Evaluate(*game, value, policy);
if (success) {
m_thread_pool->enqueue(task);
}
return success;
}
void oaz::nn::NNEvaluator::EvaluateFromNN(
oaz::games::Game* game, float* value,
const boost::multi_array_ref<float, 1>& policy,
oaz::thread_pool::Task* task) {
m_batches.Lock();
if (!m_batches.empty()) {
auto current_batch = m_batches.back();
current_batch->Lock();
size_t index = current_batch->AcquireIndex();
bool evaluate_batch = current_batch->IsFull();
if (evaluate_batch) {
m_batches.pop_back();
}
current_batch->Unlock();
m_batches.Unlock();
current_batch->InitialiseElement(index, game, value, policy, task);
if (evaluate_batch) {
while (!current_batch->IsAvailableForEvaluation()) {
}
EvaluateBatch(current_batch.get());
}
} else {
AddNewBatch();
m_batches.Unlock();
EvaluateFromNN(game, value, policy, task);
}
}
void oaz::nn::NNEvaluator::EvaluateBatch(oaz::nn::EvaluationBatch* batch) {
batch->GetStatistics().time_evaluation_start = oaz::utils::time_now_ns();
batch->GetStatistics().n_elements = batch->GetNumberOfElements();
std::vector<tensorflow::Tensor> outputs;
m_n_evaluation_requests++;
m_model->Run(
{{m_model->GetInputNodeName(),
batch->GetBatchTensor().Slice(0, batch->GetNumberOfElements())}},
{m_model->GetValueNodeName(), m_model->GetPolicyNodeName()}, {},
&outputs);
m_n_evaluations++;
auto values_map = outputs[0].template tensor<float, 2>();
auto policies_map = outputs[1].template tensor<float, 2>();
for (size_t i = 0; i != batch->GetNumberOfElements(); ++i) {
std::memcpy(batch->GetValue(i), &values_map(i, 0), 1 * sizeof(float));
auto policy = batch->GetPolicy(i);
std::memcpy(policy.origin(), &policies_map(i, 0),
policy.num_elements() * sizeof(float));
}
if (m_cache) {
m_cache->BatchInsert(batch->GetGames(), batch->GetValues(),
batch->GetPolicies(), batch->GetNumberOfElements());
}
for (size_t i = 0; i != batch->GetNumberOfElements(); ++i) {
m_thread_pool->enqueue(batch->GetTask(i));
}
batch->GetStatistics().time_evaluation_end = oaz::utils::time_now_ns();
ArchiveBatchStatistics(batch->GetStatistics());
}
void oaz::nn::NNEvaluator::ArchiveBatchStatistics(
const oaz::nn::EvaluationBatchStatistics& stats) {
m_archive_lock.Lock();
m_archive.push_back(stats);
m_archive_lock.Unlock();
}
std::vector<oaz::nn::EvaluationBatchStatistics>
oaz::nn::NNEvaluator::GetStatistics() {
m_archive_lock.Lock();
std::vector<oaz::nn::EvaluationBatchStatistics> archive(m_archive);
m_archive_lock.Unlock();
return archive;
}
void oaz::nn::NNEvaluator::ForceEvaluation() {
m_batches.Lock();
if (!m_batches.empty()) {
auto earliest_batch = m_batches.front();
earliest_batch->Lock();
if (earliest_batch->IsAvailableForEvaluation()) {
m_batches.pop_front();
earliest_batch->Unlock();
m_batches.Unlock();
earliest_batch->GetStatistics().evaluation_forced = true;
EvaluateBatch(earliest_batch.get());
} else {
earliest_batch->Unlock();
m_batches.Unlock();
}
} else {
m_batches.Unlock();
}
}
| 30.672297 | 79 | 0.677498 | ameroueh |
f635d45278e501fdec73c98f216e76c01eda55b0 | 564 | cc | C++ | code/foundation/math/xnamath/xna_plane.cc | gscept/nebula-trifid | e7c0a0acb05eedad9ed37a72c1bdf2d658511b42 | [
"BSD-2-Clause"
] | 67 | 2015-03-30T19:56:16.000Z | 2022-03-11T13:52:17.000Z | code/foundation/math/xnamath/xna_plane.cc | gscept/nebula-trifid | e7c0a0acb05eedad9ed37a72c1bdf2d658511b42 | [
"BSD-2-Clause"
] | 5 | 2015-04-15T17:17:33.000Z | 2016-02-11T00:40:17.000Z | code/foundation/math/xnamath/xna_plane.cc | gscept/nebula-trifid | e7c0a0acb05eedad9ed37a72c1bdf2d658511b42 | [
"BSD-2-Clause"
] | 34 | 2015-03-30T15:08:00.000Z | 2021-09-23T05:55:10.000Z | //------------------------------------------------------------------------------
// plane.cc
// (C) 2007 Radon Labs GmbH
// (C) 2013-2014 Individual contributors, see AUTHORS file
//------------------------------------------------------------------------------
#include "stdneb.h"
#include "math/plane.h"
#include "math/matrix44.h"
namespace Math
{
//------------------------------------------------------------------------------
/**
*/
plane
plane::transform(__PlaneArg p, const matrix44& m)
{
return XMPlaneTransform(p.vec, m.mx);
}
} // namespace Math | 25.636364 | 80 | 0.390071 | gscept |
f6360a9405234cc744e6a1e93bd3f75e5f6d1266 | 1,743 | cc | C++ | src/document_fragment.cc | knocknote/libhtml5 | 46e18a9122097b4d681c91f0747aa78a20611cab | [
"MIT"
] | 7 | 2019-08-29T05:22:05.000Z | 2020-07-07T15:35:50.000Z | src/document_fragment.cc | blastrain/libhtml5 | 46e18a9122097b4d681c91f0747aa78a20611cab | [
"MIT"
] | 3 | 2019-07-12T09:43:31.000Z | 2019-09-10T03:36:45.000Z | src/document_fragment.cc | blastrain/libhtml5 | 46e18a9122097b4d681c91f0747aa78a20611cab | [
"MIT"
] | 3 | 2019-10-25T05:35:30.000Z | 2020-07-21T21:40:52.000Z | #include "element.h"
#include "node_list.h"
#include "html_collection.h"
#include "document_fragment.h"
USING_NAMESPACE_HTML5;
DocumentFragment::DocumentFragment(emscripten::val v) :
Node(v)
{
}
DocumentFragment::~DocumentFragment()
{
}
DocumentFragment *DocumentFragment::create(emscripten::val v)
{
auto frag = new DocumentFragment(v);
frag->autorelease();
return frag;
}
void DocumentFragment::append(std::vector<Node *> nodes)
{
for (Node *node : nodes) {
HTML5_CALL(this->v, append, node->v);
}
}
Element *DocumentFragment::getElementById(std::string elementId)
{
return Element::create(HTML5_CALLv(this->v, getElementById, elementId));
}
void DocumentFragment::prepend(std::vector<Node *> nodes)
{
for (Node *node : nodes) {
HTML5_CALL(this->v, prepend, node->v);
}
}
Element *DocumentFragment::query(std::string relativeSelectors)
{
return Element::create(HTML5_CALLv(this->v, query, relativeSelectors));
}
std::vector<Element *> DocumentFragment::queryAll(std::string relativeSelectors)
{
return toObjectArray<Element>(HTML5_CALLv(this->v, queryAll, relativeSelectors));
}
Element *DocumentFragment::querySelector(std::string selectors)
{
return Element::create(HTML5_CALLv(this->v, querySelector, selectors));
}
NodeList *DocumentFragment::querySelectorAll(std::string selectors)
{
return NodeList::create(HTML5_CALLv(this->v, querySelectorAll, selectors));
}
HTML5_PROPERTY_IMPL(DocumentFragment, unsigned long, childElementCount);
HTML5_PROPERTY_OBJECT_IMPL(DocumentFragment, HTMLCollection, children);
HTML5_PROPERTY_OBJECT_IMPL(DocumentFragment, Element, firstElementChild);
HTML5_PROPERTY_OBJECT_IMPL(DocumentFragment, Element, lastElementChild);
| 25.26087 | 85 | 0.751004 | knocknote |
f63653480e4f570d7a3274c77308b46d5f20756a | 66 | cpp | C++ | Src/AppsDev/Logger/logger.cpp | zc110747/embed_manage_system | f7ec87277405ac380d5d5cb3e20240afcd505740 | [
"MIT"
] | null | null | null | Src/AppsDev/Logger/logger.cpp | zc110747/embed_manage_system | f7ec87277405ac380d5d5cb3e20240afcd505740 | [
"MIT"
] | null | null | null | Src/AppsDev/Logger/logger.cpp | zc110747/embed_manage_system | f7ec87277405ac380d5d5cb3e20240afcd505740 | [
"MIT"
] | null | null | null | /*
* logger.cpp
*
* Created on: 2021 Dec 11 15:08:05
*/
| 11 | 37 | 0.5 | zc110747 |
f636a43d1f6a3a83f344ac571b6f2310aa1df6b2 | 1,336 | cpp | C++ | test/containers/sequences/list/list.cons/size_type.pass.cpp | caiohamamura/libcxx | 27c836ff3a9c505deb9fd1616012924de8ff9279 | [
"MIT"
] | 187 | 2015-02-28T11:50:45.000Z | 2022-02-20T12:51:00.000Z | test/containers/sequences/list/list.cons/size_type.pass.cpp | caiohamamura/libcxx | 27c836ff3a9c505deb9fd1616012924de8ff9279 | [
"MIT"
] | 2 | 2019-06-24T20:44:59.000Z | 2020-06-17T18:41:35.000Z | test/containers/sequences/list/list.cons/size_type.pass.cpp | caiohamamura/libcxx | 27c836ff3a9c505deb9fd1616012924de8ff9279 | [
"MIT"
] | 80 | 2015-01-02T12:44:41.000Z | 2022-01-20T15:37:54.000Z | //===----------------------------------------------------------------------===//
//
// The LLVM Compiler Infrastructure
//
// This file is dual licensed under the MIT and the University of Illinois Open
// Source Licenses. See LICENSE.TXT for details.
//
//===----------------------------------------------------------------------===//
// <list>
// explicit list(size_type n);
#include <list>
#include <cassert>
#include "../../../DefaultOnly.h"
#include "../../../stack_allocator.h"
int main()
{
{
std::list<int> l(3);
assert(l.size() == 3);
assert(std::distance(l.begin(), l.end()) == 3);
std::list<int>::const_iterator i = l.begin();
assert(*i == 0);
++i;
assert(*i == 0);
++i;
assert(*i == 0);
}
{
std::list<int, stack_allocator<int, 3> > l(3);
assert(l.size() == 3);
assert(std::distance(l.begin(), l.end()) == 3);
std::list<int>::const_iterator i = l.begin();
assert(*i == 0);
++i;
assert(*i == 0);
++i;
assert(*i == 0);
}
#ifndef _LIBCPP_HAS_NO_RVALUE_REFERENCES
{
std::list<DefaultOnly> l(3);
assert(l.size() == 3);
assert(std::distance(l.begin(), l.end()) == 3);
}
#endif // _LIBCPP_HAS_NO_RVALUE_REFERENCES
}
| 26.196078 | 80 | 0.44985 | caiohamamura |
f636c7c1da27af93181463056702681022e30e6b | 2,706 | cpp | C++ | App/FeaturePyImp.cpp | haisenzhao/CarpentryCompiler | c9714310b7ce7523a25becd397265bfaa3ab7ea3 | [
"FSFAP"
] | 21 | 2019-12-06T09:57:10.000Z | 2021-09-22T12:58:09.000Z | App/FeaturePyImp.cpp | haisenzhao/CarpentryCompiler | c9714310b7ce7523a25becd397265bfaa3ab7ea3 | [
"FSFAP"
] | null | null | null | App/FeaturePyImp.cpp | haisenzhao/CarpentryCompiler | c9714310b7ce7523a25becd397265bfaa3ab7ea3 | [
"FSFAP"
] | 5 | 2020-11-18T00:09:30.000Z | 2021-01-13T04:40:47.000Z | /***************************************************************************
* Copyright (c) 2007 Werner Mayer <wmayer[at]users.sourceforge.net> *
* *
* This file is part of the FreeCAD CAx development system. *
* *
* This library is free software; you can redistribute it and/or *
* modify it under the terms of the GNU Library General Public *
* License as published by the Free Software Foundation; either *
* version 2 of the License, or (at your option) any later version. *
* *
* This library is distributed in the hope that it will be useful, *
* but WITHOUT ANY WARRANTY; without even the implied warranty of *
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the *
* GNU Library General Public License for more details. *
* *
* You should have received a copy of the GNU Library General Public *
* License along with this library; see the file COPYING.LIB. If not, *
* write to the Free Software Foundation, Inc., 59 Temple Place, *
* Suite 330, Boston, MA 02111-1307, USA *
* *
***************************************************************************/
#include "PreCompiled.h"
#include "Feature.h"
#include "Body.h"
// inclusion of the generated files (generated out of FeaturePy.xml)
#include "FeaturePy.h"
#include "FeaturePy.cpp"
using namespace PartDesign;
// returns a string which represent the object e.g. when printed in python
std::string FeaturePy::representation(void) const
{
App::DocumentObject* object = this->getFeaturePtr();
std::stringstream str;
str << "<" << object->getTypeId().getName() << ">";
return str.str();
}
PyObject *FeaturePy::getCustomAttributes(const char* ) const
{
return 0;
}
int FeaturePy::setCustomAttributes(const char* , PyObject *)
{
return 0;
}
PyObject* FeaturePy::getBaseObject(PyObject * /*args*/)
{
App::DocumentObject* base = getFeaturePtr()->getBaseObject();
if (base)
return base->getPyObject();
else
return Py::new_reference_to(Py::None());
}
Py::Object FeaturePy::getBody() const {
auto body = getFeaturePtr()->getFeatureBody();
if(body)
return Py::Object(body->getPyObject(),true);
return Py::Object();
}
| 38.657143 | 77 | 0.521064 | haisenzhao |
f638fa884ac0053430cba885932438be5e714864 | 4,639 | cpp | C++ | avogadro/qtgui/elementdetail_p.cpp | berquist/avogadrolibs | e169315d8f9527d6b8bee1b7426eabb8a188073b | [
"BSD-3-Clause"
] | 244 | 2015-09-09T15:08:54.000Z | 2022-03-30T17:44:21.000Z | avogadro/qtgui/elementdetail_p.cpp | berquist/avogadrolibs | e169315d8f9527d6b8bee1b7426eabb8a188073b | [
"BSD-3-Clause"
] | 670 | 2015-05-08T18:59:38.000Z | 2022-03-29T19:47:08.000Z | avogadro/qtgui/elementdetail_p.cpp | berquist/avogadrolibs | e169315d8f9527d6b8bee1b7426eabb8a188073b | [
"BSD-3-Clause"
] | 129 | 2015-01-28T01:18:36.000Z | 2022-03-17T08:50:25.000Z | /******************************************************************************
This source file is part of the Avogadro project.
Copyright 2007-2009 by Marcus D. Hanwell
Copyright 2012 Kitware, Inc.
This source code is released under the New BSD License, (the "License").
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 "elementdetail_p.h"
#include "elementtranslator.h"
#include <avogadro/core/elements.h>
#include <QtGui/QFont>
#include <QtGui/QFontMetrics>
#include <QtGui/QPainter>
#include <QtWidgets/QGraphicsSceneMouseEvent>
#include <QtWidgets/QStyleOption>
namespace Avogadro {
namespace QtGui {
using Core::Elements;
ElementDetail::ElementDetail(int elementNumber)
: m_width(100)
, m_height(70)
, m_element(elementNumber)
{}
QRectF ElementDetail::boundingRect() const
{
return QRectF(-m_width / 2, -m_height / 2, m_width, m_height);
}
QPainterPath ElementDetail::shape() const
{
QPainterPath path;
path.addRect(-m_width / 2, -m_height / 2, m_width, m_height);
return path;
}
void ElementDetail::paint(QPainter* painter, const QStyleOptionGraphicsItem*,
QWidget*)
{
// Set up a font object and get its height
QFont font(QStringLiteral("sans-serif"));
font.setPixelSize(12);
painter->setFont(font);
QFontMetrics fm(font);
int pixelHeight = fm.height();
QString symbol = Elements::symbol(static_cast<unsigned char>(m_element));
QString name(ElementTranslator::name(m_element));
QString mass = QStringLiteral("%L1").arg(
Elements::mass(static_cast<unsigned char>(m_element)), 0, 'f', 3);
const unsigned char* colorTmp =
Elements::color(static_cast<unsigned char>(m_element));
QColor color(Qt::white);
if (colorTmp) {
color.setRgb(static_cast<int>(colorTmp[0]), static_cast<int>(colorTmp[1]),
static_cast<int>(colorTmp[2]));
}
// Draw the element detail border and fill with the element colour
painter->setBrush(color);
painter->setPen(Qt::black);
QRectF rect(-m_width / 2, -m_height / 2, m_width, m_height);
painter->drawRect(rect);
// Draw the element symbol bigger than everything else
font.setPixelSize(24);
QFontMetrics fm2(font);
pixelHeight = fm2.height();
int pixelWidth = fm2.width(symbol);
painter->setFont(font);
QRectF symbolRect(-10, -m_height / 2 + 8, pixelWidth, pixelHeight);
painter->drawText(symbolRect, Qt::AlignCenter, symbol);
// Reduce the font size to draw the other parts
font.setPixelSize(12);
int pixelHeight2 = fm.height();
painter->setFont(font);
// I don't seem to be able to get a nice, cross platform layout working here
// I would really like to figure out how to make this more portable - ideas?
#ifdef Q_OS_MAC
// Draw the proton number
QRectF protonNumberRect(-m_width / 2 - 10, -m_height / 2 + 8, m_width / 2,
pixelHeight2);
painter->drawText(protonNumberRect, Qt::AlignRight,
QString::number(m_element));
// Draw the mass
QRectF massNumberRect(-m_width / 2, -m_height / 2 + 8 + pixelHeight * 1.1,
m_width, pixelHeight2);
painter->drawText(massNumberRect, Qt::AlignCenter, mass);
// Finally the full element name
QRectF nameRect(-m_width / 2,
-m_height / 2 + 4 + pixelHeight * 1.1 + pixelHeight2, m_width,
pixelHeight);
painter->drawText(nameRect, Qt::AlignCenter, name);
#else
// Draw the proton number
QRectF protonNumberRect(-m_width / 2 - 10, -m_height / 2 + 16, m_width / 2,
pixelHeight2);
painter->drawText(protonNumberRect, Qt::AlignRight,
QString::number(m_element));
// Draw the mass
QRectF massNumberRect(-m_width / 2, -m_height / 2 + 4 + pixelHeight, m_width,
pixelHeight2);
painter->drawText(massNumberRect, Qt::AlignCenter, mass);
// Finally the full element name
QRectF nameRect(-m_width / 2,
-m_height / 2 + pixelHeight + 0.8 * pixelHeight2, m_width,
pixelHeight);
painter->drawText(nameRect, Qt::AlignCenter, name);
#endif
}
void ElementDetail::setElement(int element)
{
if (m_element != element) {
m_element = element;
update(boundingRect());
}
}
} // End QtGui namespace
} // End Avogadro namespace
| 32.215278 | 80 | 0.660703 | berquist |
f639c0e1f43704acdb6e3a958d76153e65bb75f1 | 9,350 | cpp | C++ | src/clientcommands.cpp | burnedram/csgo-plugin-color-say | 64adc99eefa5edfd44c0716e3b0c0d5983a99ee8 | [
"MIT"
] | 5 | 2017-10-17T03:26:24.000Z | 2021-07-08T23:24:05.000Z | src/clientcommands.cpp | burnedram/csgo-plugin-color-say | 64adc99eefa5edfd44c0716e3b0c0d5983a99ee8 | [
"MIT"
] | 1 | 2016-10-29T12:59:12.000Z | 2017-04-23T18:45:07.000Z | src/clientcommands.cpp | burnedram/csgo-plugin-color-say | 64adc99eefa5edfd44c0716e3b0c0d5983a99ee8 | [
"MIT"
] | 5 | 2016-09-15T10:11:55.000Z | 2022-02-15T16:58:25.000Z | #include "clientcommands.h"
#include "globals.h"
#include "constants.h"
#include "chatcolor.h"
#include "chat.h"
#include "console.h"
#include <unordered_map>
#include <sstream>
#include <algorithm>
using namespace std;
namespace colorsay {
namespace clientcommands {
static unordered_map<string, ColorCommand *> _commands;
bool exists(const string &name) {
string lowername = name;
std::transform(lowername.begin(), lowername.end(), lowername.begin(), ::tolower);
return _commands.count(lowername);
}
PLUGIN_RESULT invoke(edict_t *pEdict, const string &name, const string &args, const vector<string> &argv) {
string lowername(name);
std::transform(lowername.begin(), lowername.end(), lowername.begin(), ::tolower);
return _commands.at(lowername)->invoke(pEdict, args, argv);
}
}
class HelpCommand : public ColorCommand {
public:
virtual const string get_name() const {
return "help";
}
virtual const string get_description() const {
return "Prints a list of available commands, or more specific help on a command";
}
virtual const string get_usage() const {
return "help <command>";
}
virtual const string get_help() const {
return "Prints a list of available commands, or more specific help on a command";
}
virtual PLUGIN_RESULT invoke(edict_t *pEdict, const string &args, const vector<string> &argv) const {
ostringstream ss;
if (argv.size() == 2) {
const string &name = argv[1];
if(!clientcommands::exists(name)) {
ss << "Unknown command \"" << name << "\"\n";
console::println(pEdict, ss.str());
} else {
const ColorCommand *cmd = clientcommands::_commands.at(name);
ss << "Usage: " << cmd->get_usage() << "\n\n" << cmd->get_help() << "\n";
console::println(pEdict, ss.str());
}
} else if (argv.size() == 1) {
console::println(pEdict, "GitHub: github.com/burnedram/csgo-plugin-color-say\nAvailable commands:\n");
for (auto &pair : clientcommands::_commands) {
auto &cc = pair.second;
console::print(pEdict, cc->get_usage());
console::print(pEdict, "\n\t");
console::println(pEdict, cc->get_description());
}
} else {
ss << "Usage: " << get_usage() << "\n";
console::println(pEdict, ss.str().c_str());
}
return PLUGIN_STOP;
}
};
class VersionCommand : public ColorCommand {
public:
virtual const string get_name() const {
return "version";
}
virtual const string get_description() const {
return "Prints the version of this plugin";
}
virtual const string get_usage() const {
return "version";
}
virtual const string get_help() const {
return "Prints the version of this plugin";
}
virtual PLUGIN_RESULT invoke(edict_t *pEdict, const string &args, const vector<string> &argv) const {
console::println(pEdict, "Plugin version " PLUGIN_VERSION);
ostringstream ss;
ss << "[" << chatcolor::random() << PLUGIN_NAME << chatcolor::ID::WHITE << "] Plugin version " PLUGIN_VERSION;
string str = ss.str();
chatcolor::parse_colors(str);
chat::say(pEdict, str);
return PLUGIN_STOP;
}
};
class AvailableColorsCommand : public ColorCommand {
public:
virtual const string get_name() const {
return "list";
}
virtual const string get_description() const {
return "Lists all available colors";
}
virtual const string get_usage() const {
return "list";
}
virtual const string get_help() const {
return "Lists all available colors";
}
virtual PLUGIN_RESULT invoke(edict_t *pEdict, const string &args, const vector<string> &argv) const {
ostringstream ss;
ostringstream ss2;
string chat_text, console_text;
chatcolor::RGB rgb;
chatcolor::ID color;
ss << "[" << chatcolor::random() << PLUGIN_NAME << "] Available colors";
chat_text = ss.str();
chatcolor::parse_colors(chat_text);
chat::say(pEdict, chat_text);
console::println(pEdict, "Available colors");
ss.str("");
for (color = chatcolor::min; color <= chatcolor::max; color++) {
ss2 << "(" << (int)color << ") {#" << (int)color << "}" << chatcolor::name(color);
if(color < chatcolor::max)
ss2 << "{#1}, ";
ss << ss2.str();
if(color == chatcolor::max)
ss2 << ", ";
rgb = chatcolor::rgb(color);
ss2 << "r" << (int)rgb.r;
ss2 << " g" << (int)rgb.g;
ss2 << " b" << (int)rgb.b;
console_text = ss2.str();
chatcolor::strip_colors(console_text);
console::println(pEdict, console_text);
ss2.str("");
if ((color - chatcolor::min) % 2 == 1 || color == chatcolor::max) {
chat_text = ss.str();
chatcolor::parse_colors(chat_text);
chat::say(pEdict, chat_text);
ss.str("");
}
}
return PLUGIN_STOP;
}
};
class EchoCommand : public ColorCommand {
public:
virtual const string get_name() const {
return "echo";
}
virtual const string get_description() const {
return "Prints colored text for you (and only you)";
}
virtual const string get_usage() const {
return "echo <message>";
}
virtual const string get_help() const {
return "Prints <message> in your chat window. Color tags are enabled.\nFor more info see \"list\"";
}
virtual PLUGIN_RESULT invoke(edict_t *pEdict, const string &args, const vector<string> &argv) const {
if(argv.size() < 2) {
console::println(pEdict, "Missing arg");
return PLUGIN_STOP;
}
string parsed(args);
if (!chatcolor::parse_colors(parsed))
console::println(pEdict, "Message contains bad tags");
chat::say(pEdict, parsed);
return PLUGIN_STOP;
}
};
class SayCommand : public ColorCommand {
public:
virtual const string get_name() const {
return "say";
}
virtual const string get_description() const {
return "Chat in color";
}
virtual const string get_usage() const {
return "say <message>";
}
virtual const string get_help() const {
return "Sends <message> to everyone in the server. Color tags are enabled.\nFor more info see \"list\"";
}
virtual PLUGIN_RESULT invoke(edict_t *pEdict, const string &args, const vector<string> &argv) const {
if(argv.size() < 2) {
console::println(pEdict, "Missing arg");
return PLUGIN_STOP;
}
string parsed(args);
if (!chatcolor::parse_colors(parsed))
console::println(pEdict, "Message contains bad tags");
chat::say_all(parsed);
return PLUGIN_STOP;
}
};
class SayTeamCommand : public ColorCommand {
virtual const string get_name() const {
return "say_team";
}
virtual const string get_description() const {
return "Teamchat in color";
}
virtual const string get_usage() const {
return "say_team <message>";
}
virtual const string get_help() const {
return "Sends <message> to everyone on your team. Color tags are enabled.\nFor more info see \"list\"";
}
virtual PLUGIN_RESULT invoke(edict_t *pEdict, const string &args, const vector<string> &argv) const {
if(argv.size() < 2) {
console::println(pEdict, "Missing arg");
return PLUGIN_STOP;
}
string parsed(args);
if (!chatcolor::parse_colors(parsed))
console::println(pEdict, "Message contains bad tags");
chat::say_team(pEdict, parsed);
return PLUGIN_STOP;
}
};
namespace clientcommands {
void register_commands() {
for (auto cc : initializer_list<ColorCommand *>({
new HelpCommand(), new VersionCommand(),
new AvailableColorsCommand(), new EchoCommand(),
new SayCommand(), new SayTeamCommand()}))
_commands[cc->get_name()] = cc;
}
}
}
| 34.249084 | 122 | 0.529198 | burnedram |
f63c529032238e129a5b3387c630e3340c75bc34 | 20,050 | hpp | C++ | externals/kokkos/core/src/impl/Kokkos_SimpleTaskScheduler.hpp | liranpeng/E3SM-2CRM | a15f0430555f4da7cd7189e8513c48fb6d896f3c | [
"zlib-acknowledgement",
"FTL",
"RSA-MD"
] | null | null | null | externals/kokkos/core/src/impl/Kokkos_SimpleTaskScheduler.hpp | liranpeng/E3SM-2CRM | a15f0430555f4da7cd7189e8513c48fb6d896f3c | [
"zlib-acknowledgement",
"FTL",
"RSA-MD"
] | null | null | null | externals/kokkos/core/src/impl/Kokkos_SimpleTaskScheduler.hpp | liranpeng/E3SM-2CRM | a15f0430555f4da7cd7189e8513c48fb6d896f3c | [
"zlib-acknowledgement",
"FTL",
"RSA-MD"
] | null | null | null | /*
//@HEADER
// ************************************************************************
//
// Kokkos v. 2.0
// Copyright (2014) Sandia Corporation
//
// Under the terms of Contract DE-AC04-94AL85000 with Sandia Corporation,
// the U.S. Government retains certain rights in this software.
//
// Redistribution and use in source and binary forms, with or without
// modification, are permitted provided that the following conditions are
// met:
//
// 1. Redistributions of source code must retain the above copyright
// notice, this list of conditions and the following disclaimer.
//
// 2. Redistributions in binary form must reproduce the above copyright
// notice, this list of conditions and the following disclaimer in the
// documentation and/or other materials provided with the distribution.
//
// 3. Neither the name of the Corporation nor the names of the
// contributors may be used to endorse or promote products derived from
// this software without specific prior written permission.
//
// THIS SOFTWARE IS PROVIDED BY SANDIA CORPORATION "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 SANDIA CORPORATION OR THE
// 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.
//
// Questions? Contact Christian R. Trott (crtrott@sandia.gov)
//
// ************************************************************************
//@HEADER
*/
#ifndef KOKKOS_SIMPLETASKSCHEDULER_HPP
#define KOKKOS_SIMPLETASKSCHEDULER_HPP
//----------------------------------------------------------------------------
#include <Kokkos_Macros.hpp>
#if defined( KOKKOS_ENABLE_TASKDAG )
#include <Kokkos_Core_fwd.hpp>
#include <Kokkos_TaskScheduler_fwd.hpp>
//----------------------------------------------------------------------------
#include <Kokkos_MemoryPool.hpp>
#include <impl/Kokkos_Tags.hpp>
#include <Kokkos_Future.hpp>
#include <impl/Kokkos_TaskQueue.hpp>
#include <impl/Kokkos_SingleTaskQueue.hpp>
#include <impl/Kokkos_MultipleTaskQueue.hpp>
#include <impl/Kokkos_TaskQueueMultiple.hpp>
#include <impl/Kokkos_TaskPolicyData.hpp>
#include <impl/Kokkos_TaskTeamMember.hpp>
#include <impl/Kokkos_EBO.hpp>
//----------------------------------------------------------------------------
//----------------------------------------------------------------------------
namespace Kokkos {
namespace Impl {
// TODO @tasking @cleanup move this
template <class T>
struct DefaultDestroy {
T* managed_object;
KOKKOS_FUNCTION
void destroy_shared_allocation() {
managed_object->~T();
}
};
template <class ExecutionSpace>
class ExecutionSpaceInstanceStorage
: private NoUniqueAddressMemberEmulation<ExecutionSpace>
{
private:
using base_t = NoUniqueAddressMemberEmulation<ExecutionSpace>;
protected:
KOKKOS_INLINE_FUNCTION
constexpr explicit
ExecutionSpaceInstanceStorage(ExecutionSpace const& arg_execution_space)
: base_t(arg_execution_space)
{ }
KOKKOS_INLINE_FUNCTION
constexpr explicit
ExecutionSpaceInstanceStorage(ExecutionSpace&& arg_execution_space)
: base_t(std::move(arg_execution_space))
{ }
KOKKOS_INLINE_FUNCTION
ExecutionSpace& execution_space_instance() &
{
return this->no_unique_address_data_member();
}
KOKKOS_INLINE_FUNCTION
ExecutionSpace const& execution_space_instance() const &
{
return this->no_unique_address_data_member();
}
KOKKOS_INLINE_FUNCTION
ExecutionSpace&& execution_space_instance() &&
{
return std::move(*this).no_unique_address_data_member();
}
};
template <class MemorySpace>
class MemorySpaceInstanceStorage
: private NoUniqueAddressMemberEmulation<MemorySpace>
{
private:
using base_t = NoUniqueAddressMemberEmulation<MemorySpace>;
protected:
KOKKOS_INLINE_FUNCTION
MemorySpaceInstanceStorage(MemorySpace const& arg_memory_space)
: base_t(arg_memory_space)
{ }
KOKKOS_INLINE_FUNCTION
constexpr explicit
MemorySpaceInstanceStorage(MemorySpace&& arg_memory_space)
: base_t(arg_memory_space)
{ }
KOKKOS_INLINE_FUNCTION
MemorySpace& memory_space_instance() &
{
return this->no_unique_address_data_member();
}
KOKKOS_INLINE_FUNCTION
MemorySpace const& memory_space_instance() const &
{
return this->no_unique_address_data_member();
}
KOKKOS_INLINE_FUNCTION
MemorySpace&& memory_space_instance() &&
{
return std::move(*this).no_unique_address_data_member();
}
};
} // end namespace Impl
//----------------------------------------------------------------------------
//----------------------------------------------------------------------------
template <class ExecSpace, class QueueType>
// requires ExecutionSpace<ExecSpace> && TaskQueue<QueueType>
class SimpleTaskScheduler
: public Impl::TaskSchedulerBase,
private Impl::ExecutionSpaceInstanceStorage<ExecSpace>,
private Impl::MemorySpaceInstanceStorage<typename QueueType::memory_space>,
private Impl::NoUniqueAddressMemberEmulation<typename QueueType::team_scheduler_info_type>
{
public:
// TODO @tasking @generalization (maybe?) don't force QueueType to be complete here
using scheduler_type = SimpleTaskScheduler; // tag as scheduler concept
using execution_space = ExecSpace;
using task_queue_type = QueueType;
using memory_space = typename task_queue_type::memory_space;
using memory_pool = typename task_queue_type::memory_pool;
using team_scheduler_info_type = typename task_queue_type::team_scheduler_info_type;
using task_scheduling_info_type = typename task_queue_type::task_scheduling_info_type;
using specialization = Impl::TaskQueueSpecialization<SimpleTaskScheduler>;
using member_type = typename specialization::member_type;
template <class Functor>
using runnable_task_type = typename QueueType::template runnable_task_type<Functor, SimpleTaskScheduler>;
using task_base_type = typename task_queue_type::task_base_type;
using runnable_task_base_type = typename task_queue_type::runnable_task_base_type;
using task_queue_traits = typename QueueType::task_queue_traits;
template <class ValueType>
using future_type = Kokkos::BasicFuture<ValueType, SimpleTaskScheduler>;
template <class FunctorType>
using future_type_for_functor = future_type<typename FunctorType::value_type>;
private:
template <typename, typename>
friend class BasicFuture;
using track_type = Kokkos::Impl::SharedAllocationTracker;
using execution_space_storage = Impl::ExecutionSpaceInstanceStorage<execution_space>;
using memory_space_storage = Impl::MemorySpaceInstanceStorage<memory_space>;
using team_scheduler_info_storage = Impl::NoUniqueAddressMemberEmulation<team_scheduler_info_type>;
track_type m_track;
task_queue_type* m_queue = nullptr;
KOKKOS_INLINE_FUNCTION
static constexpr task_base_type* _get_task_ptr(std::nullptr_t) { return nullptr; }
template <class ValueType>
KOKKOS_INLINE_FUNCTION
static constexpr task_base_type* _get_task_ptr(future_type<ValueType>&& f)
{
return f.m_task;
}
template <
int TaskEnum,
class DepTaskType,
class FunctorType
>
KOKKOS_FUNCTION
future_type_for_functor<typename std::decay<FunctorType>::type>
_spawn_impl(
DepTaskType arg_predecessor_task,
TaskPriority arg_priority,
typename runnable_task_base_type::function_type apply_function_ptr,
typename runnable_task_base_type::destroy_type destroy_function_ptr,
FunctorType&& functor
)
{
KOKKOS_EXPECTS(m_queue != nullptr);
using functor_future_type = future_type_for_functor<typename std::decay<FunctorType>::type>;
using task_type = typename task_queue_type::template runnable_task_type<
FunctorType, scheduler_type
>;
// Reference count starts at two:
// +1 for the matching decrement when task is complete
// +1 for the future
auto& runnable_task = *m_queue->template allocate_and_construct<task_type>(
/* functor = */ std::forward<FunctorType>(functor),
/* apply_function_ptr = */ apply_function_ptr,
/* task_type = */ static_cast<Impl::TaskType>(TaskEnum),
/* priority = */ arg_priority,
/* queue_base = */ m_queue,
/* initial_reference_count = */ 2
);
if(arg_predecessor_task != nullptr) {
m_queue->initialize_scheduling_info_from_predecessor(
runnable_task, *arg_predecessor_task
);
runnable_task.set_predecessor(*arg_predecessor_task);
}
else {
m_queue->initialize_scheduling_info_from_team_scheduler_info(
runnable_task, team_scheduler_info()
);
}
auto rv = functor_future_type(&runnable_task);
Kokkos::memory_fence(); // fence to ensure dependent stores are visible
m_queue->schedule_runnable(
std::move(runnable_task),
team_scheduler_info()
);
// note that task may be already completed even here, so don't touch it again
return rv;
}
public:
//----------------------------------------------------------------------------
// <editor-fold desc="Constructors, destructor, and assignment"> {{{2
SimpleTaskScheduler() = delete;
explicit
SimpleTaskScheduler(
execution_space const& arg_execution_space,
memory_space const& arg_memory_space,
memory_pool const& arg_memory_pool
) : execution_space_storage(arg_execution_space),
memory_space_storage(arg_memory_space)
{
// Ask the task queue how much space it needs (usually will just be
// sizeof(task_queue_type), but some queues may need additional storage
// dependent on runtime conditions or properties of the execution space)
auto const allocation_size = task_queue_type::task_queue_allocation_size(
arg_execution_space,
arg_memory_space,
arg_memory_pool
);
// TODO @tasking @generalization DSH better encapsulation of the SharedAllocationRecord pattern
using record_type = Impl::SharedAllocationRecord<
memory_space, Impl::DefaultDestroy<task_queue_type>
>;
// Allocate space for the task queue
auto* record = record_type::allocate(
memory_space(), "TaskQueue", allocation_size
);
m_queue = new (record->data()) task_queue_type(
arg_execution_space,
arg_memory_space,
arg_memory_pool
);
record->m_destroy.managed_object = m_queue;
m_track.assign_allocated_record_to_uninitialized(record);
}
explicit
SimpleTaskScheduler(
execution_space const& arg_execution_space,
memory_pool const& pool
) : SimpleTaskScheduler(arg_execution_space, memory_space{}, pool)
{ /* forwarding ctor, must be empty */ }
explicit
SimpleTaskScheduler(memory_pool const& pool)
: SimpleTaskScheduler(execution_space{}, memory_space{}, pool)
{ /* forwarding ctor, must be empty */ }
SimpleTaskScheduler(
memory_space const & arg_memory_space,
size_t const mempool_capacity,
unsigned const mempool_min_block_size, // = 1u << 6
unsigned const mempool_max_block_size, // = 1u << 10
unsigned const mempool_superblock_size // = 1u << 12
) : SimpleTaskScheduler(
execution_space{},
arg_memory_space,
memory_pool(
arg_memory_space, mempool_capacity, mempool_min_block_size,
mempool_max_block_size, mempool_superblock_size
)
)
{ /* forwarding ctor, must be empty */ }
// </editor-fold> end Constructors, destructor, and assignment }}}2
//----------------------------------------------------------------------------
// Note that this is an expression of shallow constness
KOKKOS_INLINE_FUNCTION
task_queue_type& queue() const
{
KOKKOS_EXPECTS(m_queue != nullptr);
return *m_queue;
}
KOKKOS_INLINE_FUNCTION
SimpleTaskScheduler
get_team_scheduler(int rank_in_league) const noexcept
{
KOKKOS_EXPECTS(m_queue != nullptr);
auto rv = SimpleTaskScheduler{ *this };
rv.team_scheduler_info() = m_queue->initial_team_scheduler_info(rank_in_league);
return rv;
}
KOKKOS_INLINE_FUNCTION
execution_space const& get_execution_space() const { return this->execution_space_instance(); }
KOKKOS_INLINE_FUNCTION
team_scheduler_info_type& team_scheduler_info() &
{
return this->team_scheduler_info_storage::no_unique_address_data_member();
}
KOKKOS_INLINE_FUNCTION
team_scheduler_info_type const& team_scheduler_info() const &
{
return this->team_scheduler_info_storage::no_unique_address_data_member();
}
template <int TaskEnum, typename DepFutureType, typename FunctorType>
KOKKOS_FUNCTION
static
Kokkos::BasicFuture<typename FunctorType::value_type, scheduler_type>
spawn(
Impl::TaskPolicyWithScheduler<TaskEnum, scheduler_type, DepFutureType>&& arg_policy,
typename runnable_task_base_type::function_type arg_function,
typename runnable_task_base_type::destroy_type arg_destroy,
FunctorType&& arg_functor
)
{
return std::move(arg_policy.scheduler()).template _spawn_impl<TaskEnum>(
_get_task_ptr(std::move(arg_policy.predecessor())),
arg_policy.priority(),
arg_function,
arg_destroy,
std::forward<FunctorType>(arg_functor)
);
}
template <int TaskEnum, typename DepFutureType, typename FunctorType>
KOKKOS_FUNCTION
Kokkos::BasicFuture<typename FunctorType::value_type, scheduler_type>
spawn(
Impl::TaskPolicyWithPredecessor<TaskEnum, DepFutureType>&& arg_policy,
FunctorType&& arg_functor
)
{
static_assert(
std::is_same<typename DepFutureType::scheduler_type, scheduler_type>::value,
"Can't create a task policy from a scheduler and a future from a different scheduler"
);
using task_type = runnable_task_type<FunctorType>;
typename task_type::function_type const ptr = task_type::apply;
typename task_type::destroy_type const dtor = task_type::destroy;
return _spawn_impl<TaskEnum>(
std::move(arg_policy).predecessor().m_task,
arg_policy.priority(),
ptr, dtor,
std::forward<FunctorType>(arg_functor)
);
}
template <class FunctorType, class ValueType, class Scheduler>
KOKKOS_FUNCTION
static void
respawn(
FunctorType* functor,
BasicFuture<ValueType, Scheduler> const& predecessor,
TaskPriority priority = TaskPriority::Regular
) {
using task_type = typename task_queue_type::template runnable_task_type<
FunctorType, scheduler_type
>;
auto& task = *static_cast<task_type*>(functor);
task.set_priority(priority);
task.set_predecessor(*predecessor.m_task);
task.set_respawn_flag(true);
}
template <class FunctorType, class ValueType, class Scheduler>
KOKKOS_FUNCTION
static void
respawn(
FunctorType* functor,
scheduler_type const&,
TaskPriority priority = TaskPriority::Regular
) {
using task_type = typename task_queue_type::template runnable_task_type<
FunctorType, scheduler_type
>;
auto& task = *static_cast<task_type*>(functor);
task.set_priority(priority);
KOKKOS_ASSERT(not task.has_predecessor());
task.set_respawn_flag(true);
}
template <class ValueType>
KOKKOS_FUNCTION
future_type<void>
when_all(BasicFuture<ValueType, scheduler_type> const predecessors[], int n_predecessors) {
// TODO @tasking @generalization DSH propagate scheduling info
using task_type = typename task_queue_type::aggregate_task_type;
future_type<void> rv;
if(n_predecessors > 0) {
task_queue_type* queue_ptr = nullptr;
// Loop over the predecessors to find the queue and increment the reference
// counts
for(int i_pred = 0; i_pred < n_predecessors; ++i_pred) {
auto* predecessor_task_ptr = predecessors[i_pred].m_task;
if(predecessor_task_ptr != nullptr) {
// TODO @tasking @cleanup DSH figure out when this is allowed to be nullptr (if at all anymore)
// Increment reference count to track subsequent assignment.
// TODO @tasking @optimization DSH figure out if this reference count increment is necessary
predecessor_task_ptr->increment_reference_count();
// TODO @tasking @cleanup DSH we should just set a boolean here instead to make this more readable
queue_ptr = m_queue;
}
} // end loop over predecessors
// This only represents a non-ready future if at least one of the predecessors
// has a task (and thus, a queue)
if(queue_ptr != nullptr) {
auto& q = *queue_ptr;
auto* aggregate_task_ptr = q.template allocate_and_construct_with_vla_emulation<
task_type, task_base_type*
>(
/* n_vla_entries = */ n_predecessors,
/* aggregate_predecessor_count = */ n_predecessors,
/* queue_base = */ &q,
/* initial_reference_count = */ 2
);
rv = future_type<void>(aggregate_task_ptr);
for(int i_pred = 0; i_pred < n_predecessors; ++i_pred) {
aggregate_task_ptr->vla_value_at(i_pred) = predecessors[i_pred].m_task;
}
Kokkos::memory_fence(); // we're touching very questionable memory, so be sure to fence
q.schedule_aggregate(std::move(*aggregate_task_ptr), team_scheduler_info());
// the aggregate may be processed at any time, so don't touch it after this
}
}
return rv;
}
template <class F>
KOKKOS_FUNCTION
future_type<void>
when_all(int n_calls, F&& func)
{
// TODO @tasking @generalization DSH propagate scheduling info?
// later this should be std::invoke_result_t
using generated_type = decltype(func(0));
using task_type = typename task_queue_type::aggregate_task_type;
static_assert(
is_future<generated_type>::value,
"when_all function must return a Kokkos future (an instance of Kokkos::BasicFuture)"
);
static_assert(
std::is_base_of<scheduler_type, typename generated_type::scheduler_type>::value,
"when_all function must return a Kokkos::BasicFuture of a compatible scheduler type"
);
auto* aggregate_task = m_queue->template allocate_and_construct_with_vla_emulation<
task_type, task_base_type*
>(
/* n_vla_entries = */ n_calls,
/* aggregate_predecessor_count = */ n_calls,
/* queue_base = */ m_queue,
/* initial_reference_count = */ 2
);
auto rv = future_type<void>(aggregate_task);
for(int i_call = 0; i_call < n_calls; ++i_call) {
auto generated_future = func(i_call);
if(generated_future.m_task != nullptr) {
generated_future.m_task->increment_reference_count();
aggregate_task->vla_value_at(i_call) = generated_future.m_task;
KOKKOS_ASSERT(m_queue == generated_future.m_task->ready_queue_base_ptr()
&& "Queue mismatch in when_all"
);
}
}
Kokkos::memory_fence();
m_queue->schedule_aggregate(std::move(*aggregate_task), team_scheduler_info());
// This could complete at any moment, so don't touch anything after this
return rv;
}
};
template<class ExecSpace, class QueueType>
inline
void wait(SimpleTaskScheduler<ExecSpace, QueueType> const& scheduler)
{
using scheduler_type = SimpleTaskScheduler<ExecSpace, QueueType>;
scheduler_type::specialization::execute(scheduler);
}
} // namespace Kokkos
//----------------------------------------------------------------------------
//---------------------------------------------------------------------------#endif /* #if defined( KOKKOS_ENABLE_TASKDAG ) */
#endif /* #if defined( KOKKOS_ENABLE_TASKDAG ) */
#endif /* #ifndef KOKKOS_SIMPLETASKSCHEDULER_HPP */
| 32.601626 | 126 | 0.701696 | liranpeng |
f63e7a16af6aac1e453b3f06341326570eee555b | 400 | cpp | C++ | Source/NetPhysSync/Private/NPSPrediction/FBufferInfo.cpp | i3oi3o/NetPhysSync | 267d1858d2f960933a699e725c14d8a4b4713f96 | [
"BSD-3-Clause"
] | 1 | 2018-09-22T20:35:49.000Z | 2018-09-22T20:35:49.000Z | Source/NetPhysSync/Private/NPSPrediction/FBufferInfo.cpp | i3oi3o/NetPhysSync | 267d1858d2f960933a699e725c14d8a4b4713f96 | [
"BSD-3-Clause"
] | null | null | null | Source/NetPhysSync/Private/NPSPrediction/FBufferInfo.cpp | i3oi3o/NetPhysSync | 267d1858d2f960933a699e725c14d8a4b4713f96 | [
"BSD-3-Clause"
] | 1 | 2019-04-17T05:37:51.000Z | 2019-04-17T05:37:51.000Z | // This is licensed under the BSD License 2.0 found in the LICENSE file in project's root directory.
#include "FBufferInfo.h"
FBufferInfo::FBufferInfo(uint32 BufferStartTickIndexParam, int32 BufferNumParam)
: BufferStartTickIndex(BufferStartTickIndexParam)
, BufferNum(BufferNumParam)
, BufferLastTickIndex(BufferStartTickIndexParam + BufferNumParam - 1)
{
}
FBufferInfo::~FBufferInfo()
{
}
| 22.222222 | 100 | 0.795 | i3oi3o |
f641c1cbefc7cb47cc8fb566c0540e14efaffc07 | 6,495 | hh | C++ | src/cxx/include/data/FileReader.hh | sbooeshaghi/bcl2fastq | 3f39a24cd743fa71fba9b7dcf62e5d33cea8272d | [
"BSD-3-Clause"
] | 5 | 2021-06-07T12:36:11.000Z | 2022-02-08T09:49:02.000Z | src/cxx/include/data/FileReader.hh | sbooeshaghi/bcl2fastq | 3f39a24cd743fa71fba9b7dcf62e5d33cea8272d | [
"BSD-3-Clause"
] | 1 | 2022-03-01T23:55:57.000Z | 2022-03-01T23:57:15.000Z | src/cxx/include/data/FileReader.hh | sbooeshaghi/bcl2fastq | 3f39a24cd743fa71fba9b7dcf62e5d33cea8272d | [
"BSD-3-Clause"
] | null | null | null | /**
* BCL to FASTQ file converter
* Copyright (c) 2007-2017 Illumina, Inc.
*
* This software is covered by the accompanying EULA
* and certain third party copyright/licenses, and any user of this
* source file is bound by the terms therein.
*
* \file FileReader.hh
*
* \brief Declaration of FileReader file.
*
* \author Aaron Day
*/
#ifndef BCL2FASTQ_DATA_FILEREADER_HH
#define BCL2FASTQ_DATA_FILEREADER_HH
#include "common/Types.hh"
#include "common/Exceptions.hh"
#include "io/SyncFile.hh"
#include <boost/noncopyable.hpp>
#include <boost/filesystem/path.hpp>
#include <boost/format.hpp>
#include <boost/iostreams/stream.hpp>
#include <boost/iostreams/device/array.hpp>
namespace bcl2fastq {
namespace data {
/// \brief Base class for all file readers
class FileReaderBase
{
public:
/// \brief Constructor
/// \param data Raw data from file.
/// \param ignoreErrors
/// \param defaultClustersCount Default number of clusters
FileReaderBase(const common::RawDataBuffer& data,
bool ignoreErrors,
common::ClustersCount defaultClustersCount = 0);
/// \brief Destructor
virtual ~FileReaderBase() = 0;
/// \brief Get file path.
/// \return File path.
/// \pre <tt>this->isOpen() == true</tt>
virtual const boost::filesystem::path& getPath() const;
/// \brief Get number of clusters.
/// \return Number of clusters in the file.
/// \pre <tt>this->isOpen() == true</tt>
virtual common::ClustersCount getClustersCount() const;
/// \brief Check whether the file is open.
/// \retval true File is open.
/// \retval false File is not open.
virtual bool isOpen() const { return !data_->path_.empty(); }
protected:
/// \brief Validate the condition is true.
/// \param warningMsg The warning message to use if condition is false
/// \retval condition
bool validateCondition(bool condition, const std::string& warningMsg) const;
/// \brief Raw data
const common::RawDataBuffer* data_;
/// \brief Ignore errors opening file and/or reading its header.
bool ignoreErrors_;
/// \brief Number of clusters.
common::ClustersCount clustersCount_;
boost::iostreams::basic_array_source<char> inputSrc_;
boost::iostreams::stream<boost::iostreams::basic_array_source<char>> istr_;
};
/// \brief File reading class. Virtual inheritance because of diamond inheritance.
class FileReader : public virtual FileReaderBase, private boost::noncopyable
{
public:
/// \brief Constructor. Resource acquisition is initialization.
/// \param data Raw data from file.
/// \param ignoreErrors Supress errors opening file and/or reading its header.
/// \param defaultClustersCount Number of clusters to assume in case of error opening the file
/// and/or reading its header.
FileReader(const common::RawDataBuffer& data,
bool ignoreErrors,
common::ClustersCount defaultClustersCount = 0);
/// \brief Destructor
virtual ~FileReader() = 0;
protected:
/// \brief Return the file type string. Used for logging message purposes.
virtual std::string getFileTypeStr() const = 0;
/// \brief Log an error message on file io failure.
/// \param bytesRead Number of bytes read from file.
/// \param bytesExpected Number of bytes expected to be read from file.
virtual void logError(std::streamsize bytesRead,
std::streamsize bytesExpected) const;
std::streamsize readBytes(char* buffer,
uint32_t bytes);
};
/// \brief Binary File Reader. Base class for reading binary files.
class BinaryFileReader : public FileReader
{
public:
/// \brief Constructor. Resource acquisition is initialization.
/// \param data Raw data from file.
/// \param ignoreErrors Supress errors opening file and/or reading its header.
/// \param defaultClustersCount Number of clusters to assume in case of error opening the file
/// and/or reading its header.
BinaryFileReader(const common::RawDataBuffer& data,
bool ignoreErrors,
common::ClustersCount defaultClustersCount =0);
/// \brief Destructor
virtual ~BinaryFileReader() = 0;
protected:
/// \brief Read bytes from file to buffer.
/// \param targetBuffer Target buffer to read to.
/// \param targetSize Maximum number of bytes to be read.
/// \return Number of bytes read.
virtual std::streamsize read(char* targetBuffer,
std::streamsize targetSize);
/// \brief Read the header. Template allows derived classes to implement their own header
/// class without inheritance, which would increase the size of an instance.
/// \param header Header to read.
template<typename HEADER>
bool readHeader(HEADER& header);
/// \brief Read the header. The template readHeader method only loads the data from file
/// into the HEADER instance. This method is implemented by derived classes to validate
/// and do something with the data.
virtual bool readHeader() { return true; }
};
/// \brief Binary file class that reads all clusters from the file on initialization.
class BinaryAllClustersFileReader : public BinaryFileReader
{
public:
/// \brief Constructor
/// \param data Raw data from file
/// \param ignoreErrors Supress errors opening file and/or reading its header.
BinaryAllClustersFileReader(const common::RawDataBuffer& data,
bool ignoreErrors);
protected:
/// \brief Read the clusters from file
/// \param buffer Buffer to read data into
/// \param clustersCount Number of clusters to read (size of buffer)
/// \retval true on success, false on failure.
virtual bool readClusters(std::vector<char>& buffer,
common::ClustersCount clustersCount);
/// \brief Validate the header. Throw an exception on failure.
virtual void validateHeader();
/// \brief Return the number of bytes in a record.
virtual std::size_t getRecordBytes() const = 0;
/// \brief Read all records in the file.
virtual void readRecords() { }
};
} // namespace data
} // namespace bcl2fastq
#include "data/FileReader.hpp"
#endif // BCL2FASTQ_DATA_FILEREADER_HH
| 33.828125 | 98 | 0.668668 | sbooeshaghi |
f6432f00dd84fdc63c993624b4fb8ae89272e701 | 3,274 | hpp | C++ | Firmware/Drivers/STM32/stm32_timer.hpp | deafloo/ODrive | bae459bb71b39c0169f4b8a322b7371eada58112 | [
"MIT"
] | 1,068 | 2016-05-31T22:39:08.000Z | 2020-12-20T22:13:01.000Z | Firmware/Drivers/STM32/stm32_timer.hpp | deafloo/ODrive | bae459bb71b39c0169f4b8a322b7371eada58112 | [
"MIT"
] | 389 | 2017-10-16T09:44:20.000Z | 2020-12-21T14:19:38.000Z | Firmware/Drivers/STM32/stm32_timer.hpp | deafloo/ODrive | bae459bb71b39c0169f4b8a322b7371eada58112 | [
"MIT"
] | 681 | 2016-06-12T01:41:00.000Z | 2020-12-21T12:49:32.000Z | #ifndef __STM32_TIMER_HPP
#define __STM32_TIMER_HPP
#include "stm32_system.h"
#include <tim.h>
#include <array>
class Stm32Timer {
public:
/**
* @brief Starts multiple timers deterministically and synchronously from the
* specified offset.
*
* All timers are atomically (*) put into the following state (regardless of
* their previous state/configuration):
* - TIMx_CNT will be initialized according to the corresponding counter[i] parameter.
* - If the timer is in center-aligned mode, it will be set to up-counting direction.
* - The update repetition counter is reset to TIMx_RCR (if applicable).
* - The prescaler counter is reset.
* - Update interrupts are disabled.
* - The counter put into running state.
*
* This function is implemented by generating an update event on all selected timers.
* That means as a side effect all things that are connected to the update event
* except the interrupt routine itself (i.e. ADCs, DMAs, slave timers, etc) will
* be triggered.
*
* Also you probably want to disable any connected PWM outputs to prevent glitches.
*
* (*) Best-effort atomically. There will be skew of a handful of clock cycles
* but it's always the same given the compiler version and configuration.
*/
template<size_t I>
static void start_synchronously(std::array<TIM_HandleTypeDef*, I> timers, std::array<size_t, I> counters) {
start_synchronously_impl(timers, counters, std::make_index_sequence<I>());
}
private:
#pragma GCC push_options
#pragma GCC optimize (3)
template<size_t I, size_t ... Is>
static void start_synchronously_impl(std::array<TIM_HandleTypeDef*, I> timers, std::array<size_t, I> counters, std::index_sequence<Is...>) {
for (size_t i = 0; i < I; ++i) {
TIM_HandleTypeDef* htim = timers[i];
// Stop the timer so we can start all of them later more atomically.
htim->Instance->CR1 &= ~TIM_CR1_CEN;
// Generate update event to force all of the timer's registers into
// a known state.
__HAL_TIM_DISABLE_IT(htim, TIM_IT_UPDATE);
htim->Instance->EGR |= TIM_EGR_UG;
__HAL_TIM_CLEAR_IT(htim, TIM_IT_UPDATE);
// Load counter with the desired value.
htim->Instance->CNT = counters[i];
}
register volatile uint32_t* cr_addr[I];
register uint32_t cr_val[I];
for (size_t i = 0; i < I; ++i) {
cr_addr[i] = &timers[i]->Instance->CR1;
cr_val[i] = timers[i]->Instance->CR1 | TIM_CR1_CEN;
}
// Restart all timers as atomically as possible.
// By inspection we find that this is compiled to the following code:
// f7ff faa0 bl 800bdd0 <cpu_enter_critical()>
// f8c9 6000 str.w r6, [r9]
// f8c8 5000 str.w r5, [r8]
// 603c str r4, [r7, #0]
// f7ff fa9d bl 800bdd8 <cpu_exit_critical(unsigned long)>
uint32_t mask = cpu_enter_critical();
int dummy[I] = {(*cr_addr[Is] = cr_val[Is], 0)...};
(void)dummy;
cpu_exit_critical(mask);
}
#pragma GCC pop_options
};
#endif // __STM32_TIMER_HPP | 39.445783 | 144 | 0.635919 | deafloo |
f64495f89a4b93117e666c31a395d42bcfa79438 | 490 | hpp | C++ | addons/#disabled/TBMod_liveMonitor/configs/CfgFunctions.hpp | Braincrushy/TBMod | 785f11cd9cd0defb0d01a6d2861beb6c207eb8a3 | [
"MIT"
] | null | null | null | addons/#disabled/TBMod_liveMonitor/configs/CfgFunctions.hpp | Braincrushy/TBMod | 785f11cd9cd0defb0d01a6d2861beb6c207eb8a3 | [
"MIT"
] | 4 | 2018-12-21T06:57:25.000Z | 2020-07-09T09:06:38.000Z | addons/#disabled/TBMod_liveMonitor/configs/CfgFunctions.hpp | Braincrushy/TBMod | 785f11cd9cd0defb0d01a6d2861beb6c207eb8a3 | [
"MIT"
] | null | null | null | /*
Part of the TBMod ( https://github.com/TacticalBaconDevs/TBMod )
Developed by http://tacticalbacon.de
Author: Chris 'Taranis'
*/
class CfgFunctions
{
class TBMod_liveMonitor
{
tag = "TB_liveMonitor";
class functions
{
file = "\TBMod_liveMonitor\functions";
class animated {};
class canShow {};
class initialize {};
class loop {};
class remove {};
};
};
};
| 19.6 | 68 | 0.526531 | Braincrushy |
f64649d1ef1b40f54a7f41d25fffb8f1fb893d42 | 47,431 | cpp | C++ | test/generated/grapheme_break_02.cpp | Ryan-rsm-McKenzie/text | 15aaea4297e00ec4c74295e7913ead79c90e1502 | [
"BSL-1.0"
] | 265 | 2017-07-09T23:23:48.000Z | 2022-03-24T10:14:19.000Z | test/generated/grapheme_break_02.cpp | Ryan-rsm-McKenzie/text | 15aaea4297e00ec4c74295e7913ead79c90e1502 | [
"BSL-1.0"
] | 185 | 2017-08-30T16:44:51.000Z | 2021-08-13T12:02:46.000Z | test/generated/grapheme_break_02.cpp | Ryan-rsm-McKenzie/text | 15aaea4297e00ec4c74295e7913ead79c90e1502 | [
"BSL-1.0"
] | 25 | 2017-08-29T23:07:23.000Z | 2021-09-03T06:31:29.000Z | // Copyright (C) 2020 T. Zachary Laine
//
// 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)
// Warning! This file is autogenerated.
#include <boost/text/grapheme_break.hpp>
#include <gtest/gtest.h>
#include <algorithm>
TEST(grapheme, breaks_2)
{
// ÷ 000A ÷ 000A ÷
// ÷ [0.2] <LINE FEED (LF)> (LF) ÷ [4.0] <LINE FEED (LF)> (LF) ÷ [0.3]
{
std::array<uint32_t, 2> cps = {{ 0xa, 0xa }};
EXPECT_EQ(boost::text::prev_grapheme_break(cps.begin(), cps.begin() + 0, cps.end()) - cps.begin(), 0);
EXPECT_EQ(boost::text::next_grapheme_break(cps.begin() + 0, cps.end()) - cps.begin(), 1);
EXPECT_EQ(boost::text::prev_grapheme_break(cps.begin(), cps.begin() + 1, cps.end()) - cps.begin(), 1);
EXPECT_EQ(boost::text::next_grapheme_break(cps.begin() + 1, cps.end()) - cps.begin(), 2);
EXPECT_EQ(boost::text::prev_grapheme_break(cps.begin(), cps.begin() + 2, cps.end()) - cps.begin(), 1);
EXPECT_EQ(boost::text::next_grapheme_break(cps.begin() + 1, cps.end()) - cps.begin(), 2);
}
// ÷ 000A ÷ 0308 ÷ 000A ÷
// ÷ [0.2] <LINE FEED (LF)> (LF) ÷ [4.0] COMBINING DIAERESIS (Extend_ExtCccZwj) ÷ [5.0] <LINE FEED (LF)> (LF) ÷ [0.3]
{
std::array<uint32_t, 3> cps = {{ 0xa, 0x308, 0xa }};
EXPECT_EQ(boost::text::prev_grapheme_break(cps.begin(), cps.begin() + 0, cps.end()) - cps.begin(), 0);
EXPECT_EQ(boost::text::next_grapheme_break(cps.begin() + 0, cps.end()) - cps.begin(), 1);
EXPECT_EQ(boost::text::prev_grapheme_break(cps.begin(), cps.begin() + 1, cps.end()) - cps.begin(), 1);
EXPECT_EQ(boost::text::next_grapheme_break(cps.begin() + 1, cps.end()) - cps.begin(), 2);
EXPECT_EQ(boost::text::prev_grapheme_break(cps.begin(), cps.begin() + 2, cps.end()) - cps.begin(), 2);
EXPECT_EQ(boost::text::next_grapheme_break(cps.begin() + 2, cps.end()) - cps.begin(), 3);
EXPECT_EQ(boost::text::prev_grapheme_break(cps.begin(), cps.begin() + 3, cps.end()) - cps.begin(), 2);
EXPECT_EQ(boost::text::next_grapheme_break(cps.begin() + 2, cps.end()) - cps.begin(), 3);
}
// ÷ 000A ÷ 0001 ÷
// ÷ [0.2] <LINE FEED (LF)> (LF) ÷ [4.0] <START OF HEADING> (Control) ÷ [0.3]
{
std::array<uint32_t, 2> cps = {{ 0xa, 0x1 }};
EXPECT_EQ(boost::text::prev_grapheme_break(cps.begin(), cps.begin() + 0, cps.end()) - cps.begin(), 0);
EXPECT_EQ(boost::text::next_grapheme_break(cps.begin() + 0, cps.end()) - cps.begin(), 1);
EXPECT_EQ(boost::text::prev_grapheme_break(cps.begin(), cps.begin() + 1, cps.end()) - cps.begin(), 1);
EXPECT_EQ(boost::text::next_grapheme_break(cps.begin() + 1, cps.end()) - cps.begin(), 2);
EXPECT_EQ(boost::text::prev_grapheme_break(cps.begin(), cps.begin() + 2, cps.end()) - cps.begin(), 1);
EXPECT_EQ(boost::text::next_grapheme_break(cps.begin() + 1, cps.end()) - cps.begin(), 2);
}
// ÷ 000A ÷ 0308 ÷ 0001 ÷
// ÷ [0.2] <LINE FEED (LF)> (LF) ÷ [4.0] COMBINING DIAERESIS (Extend_ExtCccZwj) ÷ [5.0] <START OF HEADING> (Control) ÷ [0.3]
{
std::array<uint32_t, 3> cps = {{ 0xa, 0x308, 0x1 }};
EXPECT_EQ(boost::text::prev_grapheme_break(cps.begin(), cps.begin() + 0, cps.end()) - cps.begin(), 0);
EXPECT_EQ(boost::text::next_grapheme_break(cps.begin() + 0, cps.end()) - cps.begin(), 1);
EXPECT_EQ(boost::text::prev_grapheme_break(cps.begin(), cps.begin() + 1, cps.end()) - cps.begin(), 1);
EXPECT_EQ(boost::text::next_grapheme_break(cps.begin() + 1, cps.end()) - cps.begin(), 2);
EXPECT_EQ(boost::text::prev_grapheme_break(cps.begin(), cps.begin() + 2, cps.end()) - cps.begin(), 2);
EXPECT_EQ(boost::text::next_grapheme_break(cps.begin() + 2, cps.end()) - cps.begin(), 3);
EXPECT_EQ(boost::text::prev_grapheme_break(cps.begin(), cps.begin() + 3, cps.end()) - cps.begin(), 2);
EXPECT_EQ(boost::text::next_grapheme_break(cps.begin() + 2, cps.end()) - cps.begin(), 3);
}
// ÷ 000A ÷ 034F ÷
// ÷ [0.2] <LINE FEED (LF)> (LF) ÷ [4.0] COMBINING GRAPHEME JOINER (Extend) ÷ [0.3]
{
std::array<uint32_t, 2> cps = {{ 0xa, 0x34f }};
EXPECT_EQ(boost::text::prev_grapheme_break(cps.begin(), cps.begin() + 0, cps.end()) - cps.begin(), 0);
EXPECT_EQ(boost::text::next_grapheme_break(cps.begin() + 0, cps.end()) - cps.begin(), 1);
EXPECT_EQ(boost::text::prev_grapheme_break(cps.begin(), cps.begin() + 1, cps.end()) - cps.begin(), 1);
EXPECT_EQ(boost::text::next_grapheme_break(cps.begin() + 1, cps.end()) - cps.begin(), 2);
EXPECT_EQ(boost::text::prev_grapheme_break(cps.begin(), cps.begin() + 2, cps.end()) - cps.begin(), 1);
EXPECT_EQ(boost::text::next_grapheme_break(cps.begin() + 1, cps.end()) - cps.begin(), 2);
}
// ÷ 000A ÷ 0308 × 034F ÷
// ÷ [0.2] <LINE FEED (LF)> (LF) ÷ [4.0] COMBINING DIAERESIS (Extend_ExtCccZwj) × [9.0] COMBINING GRAPHEME JOINER (Extend) ÷ [0.3]
{
std::array<uint32_t, 3> cps = {{ 0xa, 0x308, 0x34f }};
EXPECT_EQ(boost::text::prev_grapheme_break(cps.begin(), cps.begin() + 0, cps.end()) - cps.begin(), 0);
EXPECT_EQ(boost::text::next_grapheme_break(cps.begin() + 0, cps.end()) - cps.begin(), 1);
EXPECT_EQ(boost::text::prev_grapheme_break(cps.begin(), cps.begin() + 1, cps.end()) - cps.begin(), 1);
EXPECT_EQ(boost::text::next_grapheme_break(cps.begin() + 1, cps.end()) - cps.begin(), 3);
EXPECT_EQ(boost::text::prev_grapheme_break(cps.begin(), cps.begin() + 2, cps.end()) - cps.begin(), 1);
EXPECT_EQ(boost::text::next_grapheme_break(cps.begin() + 1, cps.end()) - cps.begin(), 3);
EXPECT_EQ(boost::text::prev_grapheme_break(cps.begin(), cps.begin() + 3, cps.end()) - cps.begin(), 1);
EXPECT_EQ(boost::text::next_grapheme_break(cps.begin() + 1, cps.end()) - cps.begin(), 3);
}
// ÷ 000A ÷ 1F1E6 ÷
// ÷ [0.2] <LINE FEED (LF)> (LF) ÷ [4.0] REGIONAL INDICATOR SYMBOL LETTER A (RI) ÷ [0.3]
{
std::array<uint32_t, 2> cps = {{ 0xa, 0x1f1e6 }};
EXPECT_EQ(boost::text::prev_grapheme_break(cps.begin(), cps.begin() + 0, cps.end()) - cps.begin(), 0);
EXPECT_EQ(boost::text::next_grapheme_break(cps.begin() + 0, cps.end()) - cps.begin(), 1);
EXPECT_EQ(boost::text::prev_grapheme_break(cps.begin(), cps.begin() + 1, cps.end()) - cps.begin(), 1);
EXPECT_EQ(boost::text::next_grapheme_break(cps.begin() + 1, cps.end()) - cps.begin(), 2);
EXPECT_EQ(boost::text::prev_grapheme_break(cps.begin(), cps.begin() + 2, cps.end()) - cps.begin(), 1);
EXPECT_EQ(boost::text::next_grapheme_break(cps.begin() + 1, cps.end()) - cps.begin(), 2);
}
// ÷ 000A ÷ 0308 ÷ 1F1E6 ÷
// ÷ [0.2] <LINE FEED (LF)> (LF) ÷ [4.0] COMBINING DIAERESIS (Extend_ExtCccZwj) ÷ [999.0] REGIONAL INDICATOR SYMBOL LETTER A (RI) ÷ [0.3]
{
std::array<uint32_t, 3> cps = {{ 0xa, 0x308, 0x1f1e6 }};
EXPECT_EQ(boost::text::prev_grapheme_break(cps.begin(), cps.begin() + 0, cps.end()) - cps.begin(), 0);
EXPECT_EQ(boost::text::next_grapheme_break(cps.begin() + 0, cps.end()) - cps.begin(), 1);
EXPECT_EQ(boost::text::prev_grapheme_break(cps.begin(), cps.begin() + 1, cps.end()) - cps.begin(), 1);
EXPECT_EQ(boost::text::next_grapheme_break(cps.begin() + 1, cps.end()) - cps.begin(), 2);
EXPECT_EQ(boost::text::prev_grapheme_break(cps.begin(), cps.begin() + 2, cps.end()) - cps.begin(), 2);
EXPECT_EQ(boost::text::next_grapheme_break(cps.begin() + 2, cps.end()) - cps.begin(), 3);
EXPECT_EQ(boost::text::prev_grapheme_break(cps.begin(), cps.begin() + 3, cps.end()) - cps.begin(), 2);
EXPECT_EQ(boost::text::next_grapheme_break(cps.begin() + 2, cps.end()) - cps.begin(), 3);
}
// ÷ 000A ÷ 0600 ÷
// ÷ [0.2] <LINE FEED (LF)> (LF) ÷ [4.0] ARABIC NUMBER SIGN (Prepend) ÷ [0.3]
{
std::array<uint32_t, 2> cps = {{ 0xa, 0x600 }};
EXPECT_EQ(boost::text::prev_grapheme_break(cps.begin(), cps.begin() + 0, cps.end()) - cps.begin(), 0);
EXPECT_EQ(boost::text::next_grapheme_break(cps.begin() + 0, cps.end()) - cps.begin(), 1);
EXPECT_EQ(boost::text::prev_grapheme_break(cps.begin(), cps.begin() + 1, cps.end()) - cps.begin(), 1);
EXPECT_EQ(boost::text::next_grapheme_break(cps.begin() + 1, cps.end()) - cps.begin(), 2);
EXPECT_EQ(boost::text::prev_grapheme_break(cps.begin(), cps.begin() + 2, cps.end()) - cps.begin(), 1);
EXPECT_EQ(boost::text::next_grapheme_break(cps.begin() + 1, cps.end()) - cps.begin(), 2);
}
// ÷ 000A ÷ 0308 ÷ 0600 ÷
// ÷ [0.2] <LINE FEED (LF)> (LF) ÷ [4.0] COMBINING DIAERESIS (Extend_ExtCccZwj) ÷ [999.0] ARABIC NUMBER SIGN (Prepend) ÷ [0.3]
{
std::array<uint32_t, 3> cps = {{ 0xa, 0x308, 0x600 }};
EXPECT_EQ(boost::text::prev_grapheme_break(cps.begin(), cps.begin() + 0, cps.end()) - cps.begin(), 0);
EXPECT_EQ(boost::text::next_grapheme_break(cps.begin() + 0, cps.end()) - cps.begin(), 1);
EXPECT_EQ(boost::text::prev_grapheme_break(cps.begin(), cps.begin() + 1, cps.end()) - cps.begin(), 1);
EXPECT_EQ(boost::text::next_grapheme_break(cps.begin() + 1, cps.end()) - cps.begin(), 2);
EXPECT_EQ(boost::text::prev_grapheme_break(cps.begin(), cps.begin() + 2, cps.end()) - cps.begin(), 2);
EXPECT_EQ(boost::text::next_grapheme_break(cps.begin() + 2, cps.end()) - cps.begin(), 3);
EXPECT_EQ(boost::text::prev_grapheme_break(cps.begin(), cps.begin() + 3, cps.end()) - cps.begin(), 2);
EXPECT_EQ(boost::text::next_grapheme_break(cps.begin() + 2, cps.end()) - cps.begin(), 3);
}
// ÷ 000A ÷ 0903 ÷
// ÷ [0.2] <LINE FEED (LF)> (LF) ÷ [4.0] DEVANAGARI SIGN VISARGA (SpacingMark) ÷ [0.3]
{
std::array<uint32_t, 2> cps = {{ 0xa, 0x903 }};
EXPECT_EQ(boost::text::prev_grapheme_break(cps.begin(), cps.begin() + 0, cps.end()) - cps.begin(), 0);
EXPECT_EQ(boost::text::next_grapheme_break(cps.begin() + 0, cps.end()) - cps.begin(), 1);
EXPECT_EQ(boost::text::prev_grapheme_break(cps.begin(), cps.begin() + 1, cps.end()) - cps.begin(), 1);
EXPECT_EQ(boost::text::next_grapheme_break(cps.begin() + 1, cps.end()) - cps.begin(), 2);
EXPECT_EQ(boost::text::prev_grapheme_break(cps.begin(), cps.begin() + 2, cps.end()) - cps.begin(), 1);
EXPECT_EQ(boost::text::next_grapheme_break(cps.begin() + 1, cps.end()) - cps.begin(), 2);
}
// ÷ 000A ÷ 0308 × 0903 ÷
// ÷ [0.2] <LINE FEED (LF)> (LF) ÷ [4.0] COMBINING DIAERESIS (Extend_ExtCccZwj) × [9.1] DEVANAGARI SIGN VISARGA (SpacingMark) ÷ [0.3]
{
std::array<uint32_t, 3> cps = {{ 0xa, 0x308, 0x903 }};
EXPECT_EQ(boost::text::prev_grapheme_break(cps.begin(), cps.begin() + 0, cps.end()) - cps.begin(), 0);
EXPECT_EQ(boost::text::next_grapheme_break(cps.begin() + 0, cps.end()) - cps.begin(), 1);
EXPECT_EQ(boost::text::prev_grapheme_break(cps.begin(), cps.begin() + 1, cps.end()) - cps.begin(), 1);
EXPECT_EQ(boost::text::next_grapheme_break(cps.begin() + 1, cps.end()) - cps.begin(), 3);
EXPECT_EQ(boost::text::prev_grapheme_break(cps.begin(), cps.begin() + 2, cps.end()) - cps.begin(), 1);
EXPECT_EQ(boost::text::next_grapheme_break(cps.begin() + 1, cps.end()) - cps.begin(), 3);
EXPECT_EQ(boost::text::prev_grapheme_break(cps.begin(), cps.begin() + 3, cps.end()) - cps.begin(), 1);
EXPECT_EQ(boost::text::next_grapheme_break(cps.begin() + 1, cps.end()) - cps.begin(), 3);
}
// ÷ 000A ÷ 1100 ÷
// ÷ [0.2] <LINE FEED (LF)> (LF) ÷ [4.0] HANGUL CHOSEONG KIYEOK (L) ÷ [0.3]
{
std::array<uint32_t, 2> cps = {{ 0xa, 0x1100 }};
EXPECT_EQ(boost::text::prev_grapheme_break(cps.begin(), cps.begin() + 0, cps.end()) - cps.begin(), 0);
EXPECT_EQ(boost::text::next_grapheme_break(cps.begin() + 0, cps.end()) - cps.begin(), 1);
EXPECT_EQ(boost::text::prev_grapheme_break(cps.begin(), cps.begin() + 1, cps.end()) - cps.begin(), 1);
EXPECT_EQ(boost::text::next_grapheme_break(cps.begin() + 1, cps.end()) - cps.begin(), 2);
EXPECT_EQ(boost::text::prev_grapheme_break(cps.begin(), cps.begin() + 2, cps.end()) - cps.begin(), 1);
EXPECT_EQ(boost::text::next_grapheme_break(cps.begin() + 1, cps.end()) - cps.begin(), 2);
}
// ÷ 000A ÷ 0308 ÷ 1100 ÷
// ÷ [0.2] <LINE FEED (LF)> (LF) ÷ [4.0] COMBINING DIAERESIS (Extend_ExtCccZwj) ÷ [999.0] HANGUL CHOSEONG KIYEOK (L) ÷ [0.3]
{
std::array<uint32_t, 3> cps = {{ 0xa, 0x308, 0x1100 }};
EXPECT_EQ(boost::text::prev_grapheme_break(cps.begin(), cps.begin() + 0, cps.end()) - cps.begin(), 0);
EXPECT_EQ(boost::text::next_grapheme_break(cps.begin() + 0, cps.end()) - cps.begin(), 1);
EXPECT_EQ(boost::text::prev_grapheme_break(cps.begin(), cps.begin() + 1, cps.end()) - cps.begin(), 1);
EXPECT_EQ(boost::text::next_grapheme_break(cps.begin() + 1, cps.end()) - cps.begin(), 2);
EXPECT_EQ(boost::text::prev_grapheme_break(cps.begin(), cps.begin() + 2, cps.end()) - cps.begin(), 2);
EXPECT_EQ(boost::text::next_grapheme_break(cps.begin() + 2, cps.end()) - cps.begin(), 3);
EXPECT_EQ(boost::text::prev_grapheme_break(cps.begin(), cps.begin() + 3, cps.end()) - cps.begin(), 2);
EXPECT_EQ(boost::text::next_grapheme_break(cps.begin() + 2, cps.end()) - cps.begin(), 3);
}
// ÷ 000A ÷ 1160 ÷
// ÷ [0.2] <LINE FEED (LF)> (LF) ÷ [4.0] HANGUL JUNGSEONG FILLER (V) ÷ [0.3]
{
std::array<uint32_t, 2> cps = {{ 0xa, 0x1160 }};
EXPECT_EQ(boost::text::prev_grapheme_break(cps.begin(), cps.begin() + 0, cps.end()) - cps.begin(), 0);
EXPECT_EQ(boost::text::next_grapheme_break(cps.begin() + 0, cps.end()) - cps.begin(), 1);
EXPECT_EQ(boost::text::prev_grapheme_break(cps.begin(), cps.begin() + 1, cps.end()) - cps.begin(), 1);
EXPECT_EQ(boost::text::next_grapheme_break(cps.begin() + 1, cps.end()) - cps.begin(), 2);
EXPECT_EQ(boost::text::prev_grapheme_break(cps.begin(), cps.begin() + 2, cps.end()) - cps.begin(), 1);
EXPECT_EQ(boost::text::next_grapheme_break(cps.begin() + 1, cps.end()) - cps.begin(), 2);
}
// ÷ 000A ÷ 0308 ÷ 1160 ÷
// ÷ [0.2] <LINE FEED (LF)> (LF) ÷ [4.0] COMBINING DIAERESIS (Extend_ExtCccZwj) ÷ [999.0] HANGUL JUNGSEONG FILLER (V) ÷ [0.3]
{
std::array<uint32_t, 3> cps = {{ 0xa, 0x308, 0x1160 }};
EXPECT_EQ(boost::text::prev_grapheme_break(cps.begin(), cps.begin() + 0, cps.end()) - cps.begin(), 0);
EXPECT_EQ(boost::text::next_grapheme_break(cps.begin() + 0, cps.end()) - cps.begin(), 1);
EXPECT_EQ(boost::text::prev_grapheme_break(cps.begin(), cps.begin() + 1, cps.end()) - cps.begin(), 1);
EXPECT_EQ(boost::text::next_grapheme_break(cps.begin() + 1, cps.end()) - cps.begin(), 2);
EXPECT_EQ(boost::text::prev_grapheme_break(cps.begin(), cps.begin() + 2, cps.end()) - cps.begin(), 2);
EXPECT_EQ(boost::text::next_grapheme_break(cps.begin() + 2, cps.end()) - cps.begin(), 3);
EXPECT_EQ(boost::text::prev_grapheme_break(cps.begin(), cps.begin() + 3, cps.end()) - cps.begin(), 2);
EXPECT_EQ(boost::text::next_grapheme_break(cps.begin() + 2, cps.end()) - cps.begin(), 3);
}
// ÷ 000A ÷ 11A8 ÷
// ÷ [0.2] <LINE FEED (LF)> (LF) ÷ [4.0] HANGUL JONGSEONG KIYEOK (T) ÷ [0.3]
{
std::array<uint32_t, 2> cps = {{ 0xa, 0x11a8 }};
EXPECT_EQ(boost::text::prev_grapheme_break(cps.begin(), cps.begin() + 0, cps.end()) - cps.begin(), 0);
EXPECT_EQ(boost::text::next_grapheme_break(cps.begin() + 0, cps.end()) - cps.begin(), 1);
EXPECT_EQ(boost::text::prev_grapheme_break(cps.begin(), cps.begin() + 1, cps.end()) - cps.begin(), 1);
EXPECT_EQ(boost::text::next_grapheme_break(cps.begin() + 1, cps.end()) - cps.begin(), 2);
EXPECT_EQ(boost::text::prev_grapheme_break(cps.begin(), cps.begin() + 2, cps.end()) - cps.begin(), 1);
EXPECT_EQ(boost::text::next_grapheme_break(cps.begin() + 1, cps.end()) - cps.begin(), 2);
}
// ÷ 000A ÷ 0308 ÷ 11A8 ÷
// ÷ [0.2] <LINE FEED (LF)> (LF) ÷ [4.0] COMBINING DIAERESIS (Extend_ExtCccZwj) ÷ [999.0] HANGUL JONGSEONG KIYEOK (T) ÷ [0.3]
{
std::array<uint32_t, 3> cps = {{ 0xa, 0x308, 0x11a8 }};
EXPECT_EQ(boost::text::prev_grapheme_break(cps.begin(), cps.begin() + 0, cps.end()) - cps.begin(), 0);
EXPECT_EQ(boost::text::next_grapheme_break(cps.begin() + 0, cps.end()) - cps.begin(), 1);
EXPECT_EQ(boost::text::prev_grapheme_break(cps.begin(), cps.begin() + 1, cps.end()) - cps.begin(), 1);
EXPECT_EQ(boost::text::next_grapheme_break(cps.begin() + 1, cps.end()) - cps.begin(), 2);
EXPECT_EQ(boost::text::prev_grapheme_break(cps.begin(), cps.begin() + 2, cps.end()) - cps.begin(), 2);
EXPECT_EQ(boost::text::next_grapheme_break(cps.begin() + 2, cps.end()) - cps.begin(), 3);
EXPECT_EQ(boost::text::prev_grapheme_break(cps.begin(), cps.begin() + 3, cps.end()) - cps.begin(), 2);
EXPECT_EQ(boost::text::next_grapheme_break(cps.begin() + 2, cps.end()) - cps.begin(), 3);
}
// ÷ 000A ÷ AC00 ÷
// ÷ [0.2] <LINE FEED (LF)> (LF) ÷ [4.0] HANGUL SYLLABLE GA (LV) ÷ [0.3]
{
std::array<uint32_t, 2> cps = {{ 0xa, 0xac00 }};
EXPECT_EQ(boost::text::prev_grapheme_break(cps.begin(), cps.begin() + 0, cps.end()) - cps.begin(), 0);
EXPECT_EQ(boost::text::next_grapheme_break(cps.begin() + 0, cps.end()) - cps.begin(), 1);
EXPECT_EQ(boost::text::prev_grapheme_break(cps.begin(), cps.begin() + 1, cps.end()) - cps.begin(), 1);
EXPECT_EQ(boost::text::next_grapheme_break(cps.begin() + 1, cps.end()) - cps.begin(), 2);
EXPECT_EQ(boost::text::prev_grapheme_break(cps.begin(), cps.begin() + 2, cps.end()) - cps.begin(), 1);
EXPECT_EQ(boost::text::next_grapheme_break(cps.begin() + 1, cps.end()) - cps.begin(), 2);
}
// ÷ 000A ÷ 0308 ÷ AC00 ÷
// ÷ [0.2] <LINE FEED (LF)> (LF) ÷ [4.0] COMBINING DIAERESIS (Extend_ExtCccZwj) ÷ [999.0] HANGUL SYLLABLE GA (LV) ÷ [0.3]
{
std::array<uint32_t, 3> cps = {{ 0xa, 0x308, 0xac00 }};
EXPECT_EQ(boost::text::prev_grapheme_break(cps.begin(), cps.begin() + 0, cps.end()) - cps.begin(), 0);
EXPECT_EQ(boost::text::next_grapheme_break(cps.begin() + 0, cps.end()) - cps.begin(), 1);
EXPECT_EQ(boost::text::prev_grapheme_break(cps.begin(), cps.begin() + 1, cps.end()) - cps.begin(), 1);
EXPECT_EQ(boost::text::next_grapheme_break(cps.begin() + 1, cps.end()) - cps.begin(), 2);
EXPECT_EQ(boost::text::prev_grapheme_break(cps.begin(), cps.begin() + 2, cps.end()) - cps.begin(), 2);
EXPECT_EQ(boost::text::next_grapheme_break(cps.begin() + 2, cps.end()) - cps.begin(), 3);
EXPECT_EQ(boost::text::prev_grapheme_break(cps.begin(), cps.begin() + 3, cps.end()) - cps.begin(), 2);
EXPECT_EQ(boost::text::next_grapheme_break(cps.begin() + 2, cps.end()) - cps.begin(), 3);
}
// ÷ 000A ÷ AC01 ÷
// ÷ [0.2] <LINE FEED (LF)> (LF) ÷ [4.0] HANGUL SYLLABLE GAG (LVT) ÷ [0.3]
{
std::array<uint32_t, 2> cps = {{ 0xa, 0xac01 }};
EXPECT_EQ(boost::text::prev_grapheme_break(cps.begin(), cps.begin() + 0, cps.end()) - cps.begin(), 0);
EXPECT_EQ(boost::text::next_grapheme_break(cps.begin() + 0, cps.end()) - cps.begin(), 1);
EXPECT_EQ(boost::text::prev_grapheme_break(cps.begin(), cps.begin() + 1, cps.end()) - cps.begin(), 1);
EXPECT_EQ(boost::text::next_grapheme_break(cps.begin() + 1, cps.end()) - cps.begin(), 2);
EXPECT_EQ(boost::text::prev_grapheme_break(cps.begin(), cps.begin() + 2, cps.end()) - cps.begin(), 1);
EXPECT_EQ(boost::text::next_grapheme_break(cps.begin() + 1, cps.end()) - cps.begin(), 2);
}
// ÷ 000A ÷ 0308 ÷ AC01 ÷
// ÷ [0.2] <LINE FEED (LF)> (LF) ÷ [4.0] COMBINING DIAERESIS (Extend_ExtCccZwj) ÷ [999.0] HANGUL SYLLABLE GAG (LVT) ÷ [0.3]
{
std::array<uint32_t, 3> cps = {{ 0xa, 0x308, 0xac01 }};
EXPECT_EQ(boost::text::prev_grapheme_break(cps.begin(), cps.begin() + 0, cps.end()) - cps.begin(), 0);
EXPECT_EQ(boost::text::next_grapheme_break(cps.begin() + 0, cps.end()) - cps.begin(), 1);
EXPECT_EQ(boost::text::prev_grapheme_break(cps.begin(), cps.begin() + 1, cps.end()) - cps.begin(), 1);
EXPECT_EQ(boost::text::next_grapheme_break(cps.begin() + 1, cps.end()) - cps.begin(), 2);
EXPECT_EQ(boost::text::prev_grapheme_break(cps.begin(), cps.begin() + 2, cps.end()) - cps.begin(), 2);
EXPECT_EQ(boost::text::next_grapheme_break(cps.begin() + 2, cps.end()) - cps.begin(), 3);
EXPECT_EQ(boost::text::prev_grapheme_break(cps.begin(), cps.begin() + 3, cps.end()) - cps.begin(), 2);
EXPECT_EQ(boost::text::next_grapheme_break(cps.begin() + 2, cps.end()) - cps.begin(), 3);
}
// ÷ 000A ÷ 231A ÷
// ÷ [0.2] <LINE FEED (LF)> (LF) ÷ [4.0] WATCH (ExtPict) ÷ [0.3]
{
std::array<uint32_t, 2> cps = {{ 0xa, 0x231a }};
EXPECT_EQ(boost::text::prev_grapheme_break(cps.begin(), cps.begin() + 0, cps.end()) - cps.begin(), 0);
EXPECT_EQ(boost::text::next_grapheme_break(cps.begin() + 0, cps.end()) - cps.begin(), 1);
EXPECT_EQ(boost::text::prev_grapheme_break(cps.begin(), cps.begin() + 1, cps.end()) - cps.begin(), 1);
EXPECT_EQ(boost::text::next_grapheme_break(cps.begin() + 1, cps.end()) - cps.begin(), 2);
EXPECT_EQ(boost::text::prev_grapheme_break(cps.begin(), cps.begin() + 2, cps.end()) - cps.begin(), 1);
EXPECT_EQ(boost::text::next_grapheme_break(cps.begin() + 1, cps.end()) - cps.begin(), 2);
}
// ÷ 000A ÷ 0308 ÷ 231A ÷
// ÷ [0.2] <LINE FEED (LF)> (LF) ÷ [4.0] COMBINING DIAERESIS (Extend_ExtCccZwj) ÷ [999.0] WATCH (ExtPict) ÷ [0.3]
{
std::array<uint32_t, 3> cps = {{ 0xa, 0x308, 0x231a }};
EXPECT_EQ(boost::text::prev_grapheme_break(cps.begin(), cps.begin() + 0, cps.end()) - cps.begin(), 0);
EXPECT_EQ(boost::text::next_grapheme_break(cps.begin() + 0, cps.end()) - cps.begin(), 1);
EXPECT_EQ(boost::text::prev_grapheme_break(cps.begin(), cps.begin() + 1, cps.end()) - cps.begin(), 1);
EXPECT_EQ(boost::text::next_grapheme_break(cps.begin() + 1, cps.end()) - cps.begin(), 2);
EXPECT_EQ(boost::text::prev_grapheme_break(cps.begin(), cps.begin() + 2, cps.end()) - cps.begin(), 2);
EXPECT_EQ(boost::text::next_grapheme_break(cps.begin() + 2, cps.end()) - cps.begin(), 3);
EXPECT_EQ(boost::text::prev_grapheme_break(cps.begin(), cps.begin() + 3, cps.end()) - cps.begin(), 2);
EXPECT_EQ(boost::text::next_grapheme_break(cps.begin() + 2, cps.end()) - cps.begin(), 3);
}
// ÷ 000A ÷ 0300 ÷
// ÷ [0.2] <LINE FEED (LF)> (LF) ÷ [4.0] COMBINING GRAVE ACCENT (Extend_ExtCccZwj) ÷ [0.3]
{
std::array<uint32_t, 2> cps = {{ 0xa, 0x300 }};
EXPECT_EQ(boost::text::prev_grapheme_break(cps.begin(), cps.begin() + 0, cps.end()) - cps.begin(), 0);
EXPECT_EQ(boost::text::next_grapheme_break(cps.begin() + 0, cps.end()) - cps.begin(), 1);
EXPECT_EQ(boost::text::prev_grapheme_break(cps.begin(), cps.begin() + 1, cps.end()) - cps.begin(), 1);
EXPECT_EQ(boost::text::next_grapheme_break(cps.begin() + 1, cps.end()) - cps.begin(), 2);
EXPECT_EQ(boost::text::prev_grapheme_break(cps.begin(), cps.begin() + 2, cps.end()) - cps.begin(), 1);
EXPECT_EQ(boost::text::next_grapheme_break(cps.begin() + 1, cps.end()) - cps.begin(), 2);
}
// ÷ 000A ÷ 0308 × 0300 ÷
// ÷ [0.2] <LINE FEED (LF)> (LF) ÷ [4.0] COMBINING DIAERESIS (Extend_ExtCccZwj) × [9.0] COMBINING GRAVE ACCENT (Extend_ExtCccZwj) ÷ [0.3]
{
std::array<uint32_t, 3> cps = {{ 0xa, 0x308, 0x300 }};
EXPECT_EQ(boost::text::prev_grapheme_break(cps.begin(), cps.begin() + 0, cps.end()) - cps.begin(), 0);
EXPECT_EQ(boost::text::next_grapheme_break(cps.begin() + 0, cps.end()) - cps.begin(), 1);
EXPECT_EQ(boost::text::prev_grapheme_break(cps.begin(), cps.begin() + 1, cps.end()) - cps.begin(), 1);
EXPECT_EQ(boost::text::next_grapheme_break(cps.begin() + 1, cps.end()) - cps.begin(), 3);
EXPECT_EQ(boost::text::prev_grapheme_break(cps.begin(), cps.begin() + 2, cps.end()) - cps.begin(), 1);
EXPECT_EQ(boost::text::next_grapheme_break(cps.begin() + 1, cps.end()) - cps.begin(), 3);
EXPECT_EQ(boost::text::prev_grapheme_break(cps.begin(), cps.begin() + 3, cps.end()) - cps.begin(), 1);
EXPECT_EQ(boost::text::next_grapheme_break(cps.begin() + 1, cps.end()) - cps.begin(), 3);
}
// ÷ 000A ÷ 200D ÷
// ÷ [0.2] <LINE FEED (LF)> (LF) ÷ [4.0] ZERO WIDTH JOINER (ZWJ_ExtCccZwj) ÷ [0.3]
{
std::array<uint32_t, 2> cps = {{ 0xa, 0x200d }};
EXPECT_EQ(boost::text::prev_grapheme_break(cps.begin(), cps.begin() + 0, cps.end()) - cps.begin(), 0);
EXPECT_EQ(boost::text::next_grapheme_break(cps.begin() + 0, cps.end()) - cps.begin(), 1);
EXPECT_EQ(boost::text::prev_grapheme_break(cps.begin(), cps.begin() + 1, cps.end()) - cps.begin(), 1);
EXPECT_EQ(boost::text::next_grapheme_break(cps.begin() + 1, cps.end()) - cps.begin(), 2);
EXPECT_EQ(boost::text::prev_grapheme_break(cps.begin(), cps.begin() + 2, cps.end()) - cps.begin(), 1);
EXPECT_EQ(boost::text::next_grapheme_break(cps.begin() + 1, cps.end()) - cps.begin(), 2);
}
// ÷ 000A ÷ 0308 × 200D ÷
// ÷ [0.2] <LINE FEED (LF)> (LF) ÷ [4.0] COMBINING DIAERESIS (Extend_ExtCccZwj) × [9.0] ZERO WIDTH JOINER (ZWJ_ExtCccZwj) ÷ [0.3]
{
std::array<uint32_t, 3> cps = {{ 0xa, 0x308, 0x200d }};
EXPECT_EQ(boost::text::prev_grapheme_break(cps.begin(), cps.begin() + 0, cps.end()) - cps.begin(), 0);
EXPECT_EQ(boost::text::next_grapheme_break(cps.begin() + 0, cps.end()) - cps.begin(), 1);
EXPECT_EQ(boost::text::prev_grapheme_break(cps.begin(), cps.begin() + 1, cps.end()) - cps.begin(), 1);
EXPECT_EQ(boost::text::next_grapheme_break(cps.begin() + 1, cps.end()) - cps.begin(), 3);
EXPECT_EQ(boost::text::prev_grapheme_break(cps.begin(), cps.begin() + 2, cps.end()) - cps.begin(), 1);
EXPECT_EQ(boost::text::next_grapheme_break(cps.begin() + 1, cps.end()) - cps.begin(), 3);
EXPECT_EQ(boost::text::prev_grapheme_break(cps.begin(), cps.begin() + 3, cps.end()) - cps.begin(), 1);
EXPECT_EQ(boost::text::next_grapheme_break(cps.begin() + 1, cps.end()) - cps.begin(), 3);
}
// ÷ 000A ÷ 0378 ÷
// ÷ [0.2] <LINE FEED (LF)> (LF) ÷ [4.0] <reserved-0378> (Other) ÷ [0.3]
{
std::array<uint32_t, 2> cps = {{ 0xa, 0x378 }};
EXPECT_EQ(boost::text::prev_grapheme_break(cps.begin(), cps.begin() + 0, cps.end()) - cps.begin(), 0);
EXPECT_EQ(boost::text::next_grapheme_break(cps.begin() + 0, cps.end()) - cps.begin(), 1);
EXPECT_EQ(boost::text::prev_grapheme_break(cps.begin(), cps.begin() + 1, cps.end()) - cps.begin(), 1);
EXPECT_EQ(boost::text::next_grapheme_break(cps.begin() + 1, cps.end()) - cps.begin(), 2);
EXPECT_EQ(boost::text::prev_grapheme_break(cps.begin(), cps.begin() + 2, cps.end()) - cps.begin(), 1);
EXPECT_EQ(boost::text::next_grapheme_break(cps.begin() + 1, cps.end()) - cps.begin(), 2);
}
// ÷ 000A ÷ 0308 ÷ 0378 ÷
// ÷ [0.2] <LINE FEED (LF)> (LF) ÷ [4.0] COMBINING DIAERESIS (Extend_ExtCccZwj) ÷ [999.0] <reserved-0378> (Other) ÷ [0.3]
{
std::array<uint32_t, 3> cps = {{ 0xa, 0x308, 0x378 }};
EXPECT_EQ(boost::text::prev_grapheme_break(cps.begin(), cps.begin() + 0, cps.end()) - cps.begin(), 0);
EXPECT_EQ(boost::text::next_grapheme_break(cps.begin() + 0, cps.end()) - cps.begin(), 1);
EXPECT_EQ(boost::text::prev_grapheme_break(cps.begin(), cps.begin() + 1, cps.end()) - cps.begin(), 1);
EXPECT_EQ(boost::text::next_grapheme_break(cps.begin() + 1, cps.end()) - cps.begin(), 2);
EXPECT_EQ(boost::text::prev_grapheme_break(cps.begin(), cps.begin() + 2, cps.end()) - cps.begin(), 2);
EXPECT_EQ(boost::text::next_grapheme_break(cps.begin() + 2, cps.end()) - cps.begin(), 3);
EXPECT_EQ(boost::text::prev_grapheme_break(cps.begin(), cps.begin() + 3, cps.end()) - cps.begin(), 2);
EXPECT_EQ(boost::text::next_grapheme_break(cps.begin() + 2, cps.end()) - cps.begin(), 3);
}
// ÷ 000A ÷ D800 ÷
// ÷ [0.2] <LINE FEED (LF)> (LF) ÷ [4.0] <surrogate-D800> (Control) ÷ [0.3]
{
std::array<uint32_t, 2> cps = {{ 0xa, 0xd800 }};
EXPECT_EQ(boost::text::prev_grapheme_break(cps.begin(), cps.begin() + 0, cps.end()) - cps.begin(), 0);
EXPECT_EQ(boost::text::next_grapheme_break(cps.begin() + 0, cps.end()) - cps.begin(), 1);
EXPECT_EQ(boost::text::prev_grapheme_break(cps.begin(), cps.begin() + 1, cps.end()) - cps.begin(), 1);
EXPECT_EQ(boost::text::next_grapheme_break(cps.begin() + 1, cps.end()) - cps.begin(), 2);
EXPECT_EQ(boost::text::prev_grapheme_break(cps.begin(), cps.begin() + 2, cps.end()) - cps.begin(), 1);
EXPECT_EQ(boost::text::next_grapheme_break(cps.begin() + 1, cps.end()) - cps.begin(), 2);
}
// ÷ 000A ÷ 0308 ÷ D800 ÷
// ÷ [0.2] <LINE FEED (LF)> (LF) ÷ [4.0] COMBINING DIAERESIS (Extend_ExtCccZwj) ÷ [5.0] <surrogate-D800> (Control) ÷ [0.3]
{
std::array<uint32_t, 3> cps = {{ 0xa, 0x308, 0xd800 }};
EXPECT_EQ(boost::text::prev_grapheme_break(cps.begin(), cps.begin() + 0, cps.end()) - cps.begin(), 0);
EXPECT_EQ(boost::text::next_grapheme_break(cps.begin() + 0, cps.end()) - cps.begin(), 1);
EXPECT_EQ(boost::text::prev_grapheme_break(cps.begin(), cps.begin() + 1, cps.end()) - cps.begin(), 1);
EXPECT_EQ(boost::text::next_grapheme_break(cps.begin() + 1, cps.end()) - cps.begin(), 2);
EXPECT_EQ(boost::text::prev_grapheme_break(cps.begin(), cps.begin() + 2, cps.end()) - cps.begin(), 2);
EXPECT_EQ(boost::text::next_grapheme_break(cps.begin() + 2, cps.end()) - cps.begin(), 3);
EXPECT_EQ(boost::text::prev_grapheme_break(cps.begin(), cps.begin() + 3, cps.end()) - cps.begin(), 2);
EXPECT_EQ(boost::text::next_grapheme_break(cps.begin() + 2, cps.end()) - cps.begin(), 3);
}
// ÷ 0001 ÷ 0020 ÷
// ÷ [0.2] <START OF HEADING> (Control) ÷ [4.0] SPACE (Other) ÷ [0.3]
{
std::array<uint32_t, 2> cps = {{ 0x1, 0x20 }};
EXPECT_EQ(boost::text::prev_grapheme_break(cps.begin(), cps.begin() + 0, cps.end()) - cps.begin(), 0);
EXPECT_EQ(boost::text::next_grapheme_break(cps.begin() + 0, cps.end()) - cps.begin(), 1);
EXPECT_EQ(boost::text::prev_grapheme_break(cps.begin(), cps.begin() + 1, cps.end()) - cps.begin(), 1);
EXPECT_EQ(boost::text::next_grapheme_break(cps.begin() + 1, cps.end()) - cps.begin(), 2);
EXPECT_EQ(boost::text::prev_grapheme_break(cps.begin(), cps.begin() + 2, cps.end()) - cps.begin(), 1);
EXPECT_EQ(boost::text::next_grapheme_break(cps.begin() + 1, cps.end()) - cps.begin(), 2);
}
// ÷ 0001 ÷ 0308 ÷ 0020 ÷
// ÷ [0.2] <START OF HEADING> (Control) ÷ [4.0] COMBINING DIAERESIS (Extend_ExtCccZwj) ÷ [999.0] SPACE (Other) ÷ [0.3]
{
std::array<uint32_t, 3> cps = {{ 0x1, 0x308, 0x20 }};
EXPECT_EQ(boost::text::prev_grapheme_break(cps.begin(), cps.begin() + 0, cps.end()) - cps.begin(), 0);
EXPECT_EQ(boost::text::next_grapheme_break(cps.begin() + 0, cps.end()) - cps.begin(), 1);
EXPECT_EQ(boost::text::prev_grapheme_break(cps.begin(), cps.begin() + 1, cps.end()) - cps.begin(), 1);
EXPECT_EQ(boost::text::next_grapheme_break(cps.begin() + 1, cps.end()) - cps.begin(), 2);
EXPECT_EQ(boost::text::prev_grapheme_break(cps.begin(), cps.begin() + 2, cps.end()) - cps.begin(), 2);
EXPECT_EQ(boost::text::next_grapheme_break(cps.begin() + 2, cps.end()) - cps.begin(), 3);
EXPECT_EQ(boost::text::prev_grapheme_break(cps.begin(), cps.begin() + 3, cps.end()) - cps.begin(), 2);
EXPECT_EQ(boost::text::next_grapheme_break(cps.begin() + 2, cps.end()) - cps.begin(), 3);
}
// ÷ 0001 ÷ 000D ÷
// ÷ [0.2] <START OF HEADING> (Control) ÷ [4.0] <CARRIAGE RETURN (CR)> (CR) ÷ [0.3]
{
std::array<uint32_t, 2> cps = {{ 0x1, 0xd }};
EXPECT_EQ(boost::text::prev_grapheme_break(cps.begin(), cps.begin() + 0, cps.end()) - cps.begin(), 0);
EXPECT_EQ(boost::text::next_grapheme_break(cps.begin() + 0, cps.end()) - cps.begin(), 1);
EXPECT_EQ(boost::text::prev_grapheme_break(cps.begin(), cps.begin() + 1, cps.end()) - cps.begin(), 1);
EXPECT_EQ(boost::text::next_grapheme_break(cps.begin() + 1, cps.end()) - cps.begin(), 2);
EXPECT_EQ(boost::text::prev_grapheme_break(cps.begin(), cps.begin() + 2, cps.end()) - cps.begin(), 1);
EXPECT_EQ(boost::text::next_grapheme_break(cps.begin() + 1, cps.end()) - cps.begin(), 2);
}
// ÷ 0001 ÷ 0308 ÷ 000D ÷
// ÷ [0.2] <START OF HEADING> (Control) ÷ [4.0] COMBINING DIAERESIS (Extend_ExtCccZwj) ÷ [5.0] <CARRIAGE RETURN (CR)> (CR) ÷ [0.3]
{
std::array<uint32_t, 3> cps = {{ 0x1, 0x308, 0xd }};
EXPECT_EQ(boost::text::prev_grapheme_break(cps.begin(), cps.begin() + 0, cps.end()) - cps.begin(), 0);
EXPECT_EQ(boost::text::next_grapheme_break(cps.begin() + 0, cps.end()) - cps.begin(), 1);
EXPECT_EQ(boost::text::prev_grapheme_break(cps.begin(), cps.begin() + 1, cps.end()) - cps.begin(), 1);
EXPECT_EQ(boost::text::next_grapheme_break(cps.begin() + 1, cps.end()) - cps.begin(), 2);
EXPECT_EQ(boost::text::prev_grapheme_break(cps.begin(), cps.begin() + 2, cps.end()) - cps.begin(), 2);
EXPECT_EQ(boost::text::next_grapheme_break(cps.begin() + 2, cps.end()) - cps.begin(), 3);
EXPECT_EQ(boost::text::prev_grapheme_break(cps.begin(), cps.begin() + 3, cps.end()) - cps.begin(), 2);
EXPECT_EQ(boost::text::next_grapheme_break(cps.begin() + 2, cps.end()) - cps.begin(), 3);
}
// ÷ 0001 ÷ 000A ÷
// ÷ [0.2] <START OF HEADING> (Control) ÷ [4.0] <LINE FEED (LF)> (LF) ÷ [0.3]
{
std::array<uint32_t, 2> cps = {{ 0x1, 0xa }};
EXPECT_EQ(boost::text::prev_grapheme_break(cps.begin(), cps.begin() + 0, cps.end()) - cps.begin(), 0);
EXPECT_EQ(boost::text::next_grapheme_break(cps.begin() + 0, cps.end()) - cps.begin(), 1);
EXPECT_EQ(boost::text::prev_grapheme_break(cps.begin(), cps.begin() + 1, cps.end()) - cps.begin(), 1);
EXPECT_EQ(boost::text::next_grapheme_break(cps.begin() + 1, cps.end()) - cps.begin(), 2);
EXPECT_EQ(boost::text::prev_grapheme_break(cps.begin(), cps.begin() + 2, cps.end()) - cps.begin(), 1);
EXPECT_EQ(boost::text::next_grapheme_break(cps.begin() + 1, cps.end()) - cps.begin(), 2);
}
// ÷ 0001 ÷ 0308 ÷ 000A ÷
// ÷ [0.2] <START OF HEADING> (Control) ÷ [4.0] COMBINING DIAERESIS (Extend_ExtCccZwj) ÷ [5.0] <LINE FEED (LF)> (LF) ÷ [0.3]
{
std::array<uint32_t, 3> cps = {{ 0x1, 0x308, 0xa }};
EXPECT_EQ(boost::text::prev_grapheme_break(cps.begin(), cps.begin() + 0, cps.end()) - cps.begin(), 0);
EXPECT_EQ(boost::text::next_grapheme_break(cps.begin() + 0, cps.end()) - cps.begin(), 1);
EXPECT_EQ(boost::text::prev_grapheme_break(cps.begin(), cps.begin() + 1, cps.end()) - cps.begin(), 1);
EXPECT_EQ(boost::text::next_grapheme_break(cps.begin() + 1, cps.end()) - cps.begin(), 2);
EXPECT_EQ(boost::text::prev_grapheme_break(cps.begin(), cps.begin() + 2, cps.end()) - cps.begin(), 2);
EXPECT_EQ(boost::text::next_grapheme_break(cps.begin() + 2, cps.end()) - cps.begin(), 3);
EXPECT_EQ(boost::text::prev_grapheme_break(cps.begin(), cps.begin() + 3, cps.end()) - cps.begin(), 2);
EXPECT_EQ(boost::text::next_grapheme_break(cps.begin() + 2, cps.end()) - cps.begin(), 3);
}
// ÷ 0001 ÷ 0001 ÷
// ÷ [0.2] <START OF HEADING> (Control) ÷ [4.0] <START OF HEADING> (Control) ÷ [0.3]
{
std::array<uint32_t, 2> cps = {{ 0x1, 0x1 }};
EXPECT_EQ(boost::text::prev_grapheme_break(cps.begin(), cps.begin() + 0, cps.end()) - cps.begin(), 0);
EXPECT_EQ(boost::text::next_grapheme_break(cps.begin() + 0, cps.end()) - cps.begin(), 1);
EXPECT_EQ(boost::text::prev_grapheme_break(cps.begin(), cps.begin() + 1, cps.end()) - cps.begin(), 1);
EXPECT_EQ(boost::text::next_grapheme_break(cps.begin() + 1, cps.end()) - cps.begin(), 2);
EXPECT_EQ(boost::text::prev_grapheme_break(cps.begin(), cps.begin() + 2, cps.end()) - cps.begin(), 1);
EXPECT_EQ(boost::text::next_grapheme_break(cps.begin() + 1, cps.end()) - cps.begin(), 2);
}
// ÷ 0001 ÷ 0308 ÷ 0001 ÷
// ÷ [0.2] <START OF HEADING> (Control) ÷ [4.0] COMBINING DIAERESIS (Extend_ExtCccZwj) ÷ [5.0] <START OF HEADING> (Control) ÷ [0.3]
{
std::array<uint32_t, 3> cps = {{ 0x1, 0x308, 0x1 }};
EXPECT_EQ(boost::text::prev_grapheme_break(cps.begin(), cps.begin() + 0, cps.end()) - cps.begin(), 0);
EXPECT_EQ(boost::text::next_grapheme_break(cps.begin() + 0, cps.end()) - cps.begin(), 1);
EXPECT_EQ(boost::text::prev_grapheme_break(cps.begin(), cps.begin() + 1, cps.end()) - cps.begin(), 1);
EXPECT_EQ(boost::text::next_grapheme_break(cps.begin() + 1, cps.end()) - cps.begin(), 2);
EXPECT_EQ(boost::text::prev_grapheme_break(cps.begin(), cps.begin() + 2, cps.end()) - cps.begin(), 2);
EXPECT_EQ(boost::text::next_grapheme_break(cps.begin() + 2, cps.end()) - cps.begin(), 3);
EXPECT_EQ(boost::text::prev_grapheme_break(cps.begin(), cps.begin() + 3, cps.end()) - cps.begin(), 2);
EXPECT_EQ(boost::text::next_grapheme_break(cps.begin() + 2, cps.end()) - cps.begin(), 3);
}
// ÷ 0001 ÷ 034F ÷
// ÷ [0.2] <START OF HEADING> (Control) ÷ [4.0] COMBINING GRAPHEME JOINER (Extend) ÷ [0.3]
{
std::array<uint32_t, 2> cps = {{ 0x1, 0x34f }};
EXPECT_EQ(boost::text::prev_grapheme_break(cps.begin(), cps.begin() + 0, cps.end()) - cps.begin(), 0);
EXPECT_EQ(boost::text::next_grapheme_break(cps.begin() + 0, cps.end()) - cps.begin(), 1);
EXPECT_EQ(boost::text::prev_grapheme_break(cps.begin(), cps.begin() + 1, cps.end()) - cps.begin(), 1);
EXPECT_EQ(boost::text::next_grapheme_break(cps.begin() + 1, cps.end()) - cps.begin(), 2);
EXPECT_EQ(boost::text::prev_grapheme_break(cps.begin(), cps.begin() + 2, cps.end()) - cps.begin(), 1);
EXPECT_EQ(boost::text::next_grapheme_break(cps.begin() + 1, cps.end()) - cps.begin(), 2);
}
// ÷ 0001 ÷ 0308 × 034F ÷
// ÷ [0.2] <START OF HEADING> (Control) ÷ [4.0] COMBINING DIAERESIS (Extend_ExtCccZwj) × [9.0] COMBINING GRAPHEME JOINER (Extend) ÷ [0.3]
{
std::array<uint32_t, 3> cps = {{ 0x1, 0x308, 0x34f }};
EXPECT_EQ(boost::text::prev_grapheme_break(cps.begin(), cps.begin() + 0, cps.end()) - cps.begin(), 0);
EXPECT_EQ(boost::text::next_grapheme_break(cps.begin() + 0, cps.end()) - cps.begin(), 1);
EXPECT_EQ(boost::text::prev_grapheme_break(cps.begin(), cps.begin() + 1, cps.end()) - cps.begin(), 1);
EXPECT_EQ(boost::text::next_grapheme_break(cps.begin() + 1, cps.end()) - cps.begin(), 3);
EXPECT_EQ(boost::text::prev_grapheme_break(cps.begin(), cps.begin() + 2, cps.end()) - cps.begin(), 1);
EXPECT_EQ(boost::text::next_grapheme_break(cps.begin() + 1, cps.end()) - cps.begin(), 3);
EXPECT_EQ(boost::text::prev_grapheme_break(cps.begin(), cps.begin() + 3, cps.end()) - cps.begin(), 1);
EXPECT_EQ(boost::text::next_grapheme_break(cps.begin() + 1, cps.end()) - cps.begin(), 3);
}
// ÷ 0001 ÷ 1F1E6 ÷
// ÷ [0.2] <START OF HEADING> (Control) ÷ [4.0] REGIONAL INDICATOR SYMBOL LETTER A (RI) ÷ [0.3]
{
std::array<uint32_t, 2> cps = {{ 0x1, 0x1f1e6 }};
EXPECT_EQ(boost::text::prev_grapheme_break(cps.begin(), cps.begin() + 0, cps.end()) - cps.begin(), 0);
EXPECT_EQ(boost::text::next_grapheme_break(cps.begin() + 0, cps.end()) - cps.begin(), 1);
EXPECT_EQ(boost::text::prev_grapheme_break(cps.begin(), cps.begin() + 1, cps.end()) - cps.begin(), 1);
EXPECT_EQ(boost::text::next_grapheme_break(cps.begin() + 1, cps.end()) - cps.begin(), 2);
EXPECT_EQ(boost::text::prev_grapheme_break(cps.begin(), cps.begin() + 2, cps.end()) - cps.begin(), 1);
EXPECT_EQ(boost::text::next_grapheme_break(cps.begin() + 1, cps.end()) - cps.begin(), 2);
}
// ÷ 0001 ÷ 0308 ÷ 1F1E6 ÷
// ÷ [0.2] <START OF HEADING> (Control) ÷ [4.0] COMBINING DIAERESIS (Extend_ExtCccZwj) ÷ [999.0] REGIONAL INDICATOR SYMBOL LETTER A (RI) ÷ [0.3]
{
std::array<uint32_t, 3> cps = {{ 0x1, 0x308, 0x1f1e6 }};
EXPECT_EQ(boost::text::prev_grapheme_break(cps.begin(), cps.begin() + 0, cps.end()) - cps.begin(), 0);
EXPECT_EQ(boost::text::next_grapheme_break(cps.begin() + 0, cps.end()) - cps.begin(), 1);
EXPECT_EQ(boost::text::prev_grapheme_break(cps.begin(), cps.begin() + 1, cps.end()) - cps.begin(), 1);
EXPECT_EQ(boost::text::next_grapheme_break(cps.begin() + 1, cps.end()) - cps.begin(), 2);
EXPECT_EQ(boost::text::prev_grapheme_break(cps.begin(), cps.begin() + 2, cps.end()) - cps.begin(), 2);
EXPECT_EQ(boost::text::next_grapheme_break(cps.begin() + 2, cps.end()) - cps.begin(), 3);
EXPECT_EQ(boost::text::prev_grapheme_break(cps.begin(), cps.begin() + 3, cps.end()) - cps.begin(), 2);
EXPECT_EQ(boost::text::next_grapheme_break(cps.begin() + 2, cps.end()) - cps.begin(), 3);
}
// ÷ 0001 ÷ 0600 ÷
// ÷ [0.2] <START OF HEADING> (Control) ÷ [4.0] ARABIC NUMBER SIGN (Prepend) ÷ [0.3]
{
std::array<uint32_t, 2> cps = {{ 0x1, 0x600 }};
EXPECT_EQ(boost::text::prev_grapheme_break(cps.begin(), cps.begin() + 0, cps.end()) - cps.begin(), 0);
EXPECT_EQ(boost::text::next_grapheme_break(cps.begin() + 0, cps.end()) - cps.begin(), 1);
EXPECT_EQ(boost::text::prev_grapheme_break(cps.begin(), cps.begin() + 1, cps.end()) - cps.begin(), 1);
EXPECT_EQ(boost::text::next_grapheme_break(cps.begin() + 1, cps.end()) - cps.begin(), 2);
EXPECT_EQ(boost::text::prev_grapheme_break(cps.begin(), cps.begin() + 2, cps.end()) - cps.begin(), 1);
EXPECT_EQ(boost::text::next_grapheme_break(cps.begin() + 1, cps.end()) - cps.begin(), 2);
}
// ÷ 0001 ÷ 0308 ÷ 0600 ÷
// ÷ [0.2] <START OF HEADING> (Control) ÷ [4.0] COMBINING DIAERESIS (Extend_ExtCccZwj) ÷ [999.0] ARABIC NUMBER SIGN (Prepend) ÷ [0.3]
{
std::array<uint32_t, 3> cps = {{ 0x1, 0x308, 0x600 }};
EXPECT_EQ(boost::text::prev_grapheme_break(cps.begin(), cps.begin() + 0, cps.end()) - cps.begin(), 0);
EXPECT_EQ(boost::text::next_grapheme_break(cps.begin() + 0, cps.end()) - cps.begin(), 1);
EXPECT_EQ(boost::text::prev_grapheme_break(cps.begin(), cps.begin() + 1, cps.end()) - cps.begin(), 1);
EXPECT_EQ(boost::text::next_grapheme_break(cps.begin() + 1, cps.end()) - cps.begin(), 2);
EXPECT_EQ(boost::text::prev_grapheme_break(cps.begin(), cps.begin() + 2, cps.end()) - cps.begin(), 2);
EXPECT_EQ(boost::text::next_grapheme_break(cps.begin() + 2, cps.end()) - cps.begin(), 3);
EXPECT_EQ(boost::text::prev_grapheme_break(cps.begin(), cps.begin() + 3, cps.end()) - cps.begin(), 2);
EXPECT_EQ(boost::text::next_grapheme_break(cps.begin() + 2, cps.end()) - cps.begin(), 3);
}
// ÷ 0001 ÷ 0903 ÷
// ÷ [0.2] <START OF HEADING> (Control) ÷ [4.0] DEVANAGARI SIGN VISARGA (SpacingMark) ÷ [0.3]
{
std::array<uint32_t, 2> cps = {{ 0x1, 0x903 }};
EXPECT_EQ(boost::text::prev_grapheme_break(cps.begin(), cps.begin() + 0, cps.end()) - cps.begin(), 0);
EXPECT_EQ(boost::text::next_grapheme_break(cps.begin() + 0, cps.end()) - cps.begin(), 1);
EXPECT_EQ(boost::text::prev_grapheme_break(cps.begin(), cps.begin() + 1, cps.end()) - cps.begin(), 1);
EXPECT_EQ(boost::text::next_grapheme_break(cps.begin() + 1, cps.end()) - cps.begin(), 2);
EXPECT_EQ(boost::text::prev_grapheme_break(cps.begin(), cps.begin() + 2, cps.end()) - cps.begin(), 1);
EXPECT_EQ(boost::text::next_grapheme_break(cps.begin() + 1, cps.end()) - cps.begin(), 2);
}
// ÷ 0001 ÷ 0308 × 0903 ÷
// ÷ [0.2] <START OF HEADING> (Control) ÷ [4.0] COMBINING DIAERESIS (Extend_ExtCccZwj) × [9.1] DEVANAGARI SIGN VISARGA (SpacingMark) ÷ [0.3]
{
std::array<uint32_t, 3> cps = {{ 0x1, 0x308, 0x903 }};
EXPECT_EQ(boost::text::prev_grapheme_break(cps.begin(), cps.begin() + 0, cps.end()) - cps.begin(), 0);
EXPECT_EQ(boost::text::next_grapheme_break(cps.begin() + 0, cps.end()) - cps.begin(), 1);
EXPECT_EQ(boost::text::prev_grapheme_break(cps.begin(), cps.begin() + 1, cps.end()) - cps.begin(), 1);
EXPECT_EQ(boost::text::next_grapheme_break(cps.begin() + 1, cps.end()) - cps.begin(), 3);
EXPECT_EQ(boost::text::prev_grapheme_break(cps.begin(), cps.begin() + 2, cps.end()) - cps.begin(), 1);
EXPECT_EQ(boost::text::next_grapheme_break(cps.begin() + 1, cps.end()) - cps.begin(), 3);
EXPECT_EQ(boost::text::prev_grapheme_break(cps.begin(), cps.begin() + 3, cps.end()) - cps.begin(), 1);
EXPECT_EQ(boost::text::next_grapheme_break(cps.begin() + 1, cps.end()) - cps.begin(), 3);
}
// ÷ 0001 ÷ 1100 ÷
// ÷ [0.2] <START OF HEADING> (Control) ÷ [4.0] HANGUL CHOSEONG KIYEOK (L) ÷ [0.3]
{
std::array<uint32_t, 2> cps = {{ 0x1, 0x1100 }};
EXPECT_EQ(boost::text::prev_grapheme_break(cps.begin(), cps.begin() + 0, cps.end()) - cps.begin(), 0);
EXPECT_EQ(boost::text::next_grapheme_break(cps.begin() + 0, cps.end()) - cps.begin(), 1);
EXPECT_EQ(boost::text::prev_grapheme_break(cps.begin(), cps.begin() + 1, cps.end()) - cps.begin(), 1);
EXPECT_EQ(boost::text::next_grapheme_break(cps.begin() + 1, cps.end()) - cps.begin(), 2);
EXPECT_EQ(boost::text::prev_grapheme_break(cps.begin(), cps.begin() + 2, cps.end()) - cps.begin(), 1);
EXPECT_EQ(boost::text::next_grapheme_break(cps.begin() + 1, cps.end()) - cps.begin(), 2);
}
// ÷ 0001 ÷ 0308 ÷ 1100 ÷
// ÷ [0.2] <START OF HEADING> (Control) ÷ [4.0] COMBINING DIAERESIS (Extend_ExtCccZwj) ÷ [999.0] HANGUL CHOSEONG KIYEOK (L) ÷ [0.3]
{
std::array<uint32_t, 3> cps = {{ 0x1, 0x308, 0x1100 }};
EXPECT_EQ(boost::text::prev_grapheme_break(cps.begin(), cps.begin() + 0, cps.end()) - cps.begin(), 0);
EXPECT_EQ(boost::text::next_grapheme_break(cps.begin() + 0, cps.end()) - cps.begin(), 1);
EXPECT_EQ(boost::text::prev_grapheme_break(cps.begin(), cps.begin() + 1, cps.end()) - cps.begin(), 1);
EXPECT_EQ(boost::text::next_grapheme_break(cps.begin() + 1, cps.end()) - cps.begin(), 2);
EXPECT_EQ(boost::text::prev_grapheme_break(cps.begin(), cps.begin() + 2, cps.end()) - cps.begin(), 2);
EXPECT_EQ(boost::text::next_grapheme_break(cps.begin() + 2, cps.end()) - cps.begin(), 3);
EXPECT_EQ(boost::text::prev_grapheme_break(cps.begin(), cps.begin() + 3, cps.end()) - cps.begin(), 2);
EXPECT_EQ(boost::text::next_grapheme_break(cps.begin() + 2, cps.end()) - cps.begin(), 3);
}
}
| 66.059889 | 148 | 0.593683 | Ryan-rsm-McKenzie |
f646c7099880bfe83fc9cae96c511f414d38634a | 15,397 | hpp | C++ | p1788/flavor/infsup/setbased/mpfr_bin_ieee754_flavor_class_impl.hpp | nehmeier/libieeep1788 | 1f10b896ff532e95818856614ab3073189e81199 | [
"Apache-2.0"
] | 41 | 2015-01-23T07:52:27.000Z | 2022-02-28T03:15:21.000Z | p1788/flavor/infsup/setbased/mpfr_bin_ieee754_flavor_class_impl.hpp | nehmeier/libieeep1788 | 1f10b896ff532e95818856614ab3073189e81199 | [
"Apache-2.0"
] | 25 | 2015-01-25T16:13:35.000Z | 2022-02-14T12:05:08.000Z | p1788/flavor/infsup/setbased/mpfr_bin_ieee754_flavor_class_impl.hpp | nehmeier/libieeep1788 | 1f10b896ff532e95818856614ab3073189e81199 | [
"Apache-2.0"
] | 8 | 2015-02-22T11:06:19.000Z | 2021-05-23T09:57:32.000Z | //
// libieeep1788
//
// An implementation of the preliminary IEEE P1788 standard for
// interval arithmetic
//
//
// Copyright 2013 - 2015
//
// Marco Nehmeier (nehmeier@informatik.uni-wuerzburg.de)
// Department of Computer Science,
// University of Wuerzburg, Germany
//
// Licensed under the Apache License, Version 2.0 (the "License");
// you may not use this file except in compliance with the License.
// You may obtain a copy of the License at
//
// http://www.apache.org/licenses/LICENSE-2.0
//
// Unless required by applicable law or agreed to in writing, software
// distributed under the License is distributed on an "AS IS" BASIS,
// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
// See the License for the specific language governing permissions and
// limitations under the License.
#ifndef LIBIEEEP1788_P1788_FLAVOR_INFSUP_SETBASED_MPFR_BIN_IEEE754_FLAVOR_CLASS_IMPL_HPP
#define LIBIEEEP1788_P1788_FLAVOR_INFSUP_SETBASED_MPFR_BIN_IEEE754_FLAVOR_CLASS_IMPL_HPP
namespace p1788
{
namespace flavor
{
namespace infsup
{
namespace setbased
{
// -----------------------------------------------------------------------------
// Interval constants
// -----------------------------------------------------------------------------
// empty bare interval
template<typename T>
typename mpfr_bin_ieee754_flavor<T>::representation
mpfr_bin_ieee754_flavor<T>::empty()
{
return representation(std::numeric_limits<T>::quiet_NaN(),
std::numeric_limits<T>::quiet_NaN());
}
// empty decorated interval
template<typename T>
typename mpfr_bin_ieee754_flavor<T>::representation_dec
mpfr_bin_ieee754_flavor<T>::empty_dec()
{
return representation_dec(representation(std::numeric_limits<T>::quiet_NaN(),
std::numeric_limits<T>::quiet_NaN()), p1788::decoration::decoration::trv);
}
// entire bare interval
template<typename T>
typename mpfr_bin_ieee754_flavor<T>::representation
mpfr_bin_ieee754_flavor<T>::entire()
{
return representation(-std::numeric_limits<T>::infinity(),
std::numeric_limits<T>::infinity());
}
// entire decorated interval
template<typename T>
typename mpfr_bin_ieee754_flavor<T>::representation_dec
mpfr_bin_ieee754_flavor<T>::entire_dec()
{
return representation_dec(representation(-std::numeric_limits<T>::infinity(),
std::numeric_limits<T>::infinity()), p1788::decoration::decoration::dac);
}
// nai decorated interval
template<typename T>
typename mpfr_bin_ieee754_flavor<T>::representation_dec
mpfr_bin_ieee754_flavor<T>::nai()
{
return representation_dec(representation(std::numeric_limits<T>::quiet_NaN(),
std::numeric_limits<T>::quiet_NaN()), p1788::decoration::decoration::ill);
}
// -----------------------------------------------------------------------------
// Constructors
// -----------------------------------------------------------------------------
// bare inf-sup interval
template<typename T>
typename mpfr_bin_ieee754_flavor<T>::representation
mpfr_bin_ieee754_flavor<T>::nums_to_interval(T lower, T upper)
{
// Comparison with NaN is always false!
if (lower <= upper
&& lower != std::numeric_limits<T>::infinity()
&& upper != -std::numeric_limits<T>::infinity())
{
return representation(lower, upper);
}
else
{
p1788::exception::signal_undefined_operation();
return empty();
}
}
// decorated inf-sup interval
template<typename T>
typename mpfr_bin_ieee754_flavor<T>::representation_dec
mpfr_bin_ieee754_flavor<T>::nums_to_decorated_interval(T lower, T upper)
{
// Comparison with NaN is always false!
if (lower <= upper
&& lower != std::numeric_limits<T>::infinity()
&& upper != -std::numeric_limits<T>::infinity())
{
return new_dec(representation(lower,upper));
}
else
{
p1788::exception::signal_undefined_operation();
return nai();
}
}
// bare inf-sup interval mixed type
template<typename T>
template<typename L_, typename U_>
typename mpfr_bin_ieee754_flavor<T>::representation
mpfr_bin_ieee754_flavor<T>::nums_to_interval(L_ lower, U_ upper)
{
static_assert(std::numeric_limits<L_>::is_iec559, "Only IEEE 754 binary compliant types are supported!");
static_assert(std::numeric_limits<U_>::is_iec559, "Only IEEE 754 binary compliant types are supported!");
// Comparison with NaN is always false!
if (lower <= upper
&& lower != std::numeric_limits<L_>::infinity()
&& upper != -std::numeric_limits<U_>::infinity())
{
return representation(convert_rndd(lower), convert_rndu(upper));
}
else
{
p1788::exception::signal_undefined_operation();
return empty();
}
}
// decorated inf-sup interval mixed type
template<typename T>
template<typename L_, typename U_>
typename mpfr_bin_ieee754_flavor<T>::representation_dec
mpfr_bin_ieee754_flavor<T>::nums_to_decorated_interval(L_ lower, U_ upper)
{
static_assert(std::numeric_limits<L_>::is_iec559, "Only IEEE 754 binary compliant types are supported!");
static_assert(std::numeric_limits<U_>::is_iec559, "Only IEEE 754 binary compliant types are supported!");
// Comparison with NaN is always false!
if (lower <= upper
&& lower != std::numeric_limits<L_>::infinity()
&& upper != -std::numeric_limits<U_>::infinity())
{
return new_dec(representation(convert_rndd(lower), convert_rndu(upper)));
}
else
{
p1788::exception::signal_undefined_operation();
return nai();
}
}
// decorated inf-sup-dec interval
template<typename T>
typename mpfr_bin_ieee754_flavor<T>::representation_dec
mpfr_bin_ieee754_flavor<T>::nums_dec_to_decorated_interval(T lower, T upper, p1788::decoration::decoration dec)
{
if (p1788::decoration::is_valid(dec))
{
// Comparison with NaN is always false!
if (dec != p1788::decoration::decoration::ill
&& (lower <= upper
&& lower != std::numeric_limits<T>::infinity()
&& upper != -std::numeric_limits<T>::infinity()
&& (dec != p1788::decoration::decoration::com
|| (lower != -std::numeric_limits<T>::infinity()
&& upper != std::numeric_limits<T>::infinity()))
)
)
{
return representation_dec(representation(lower,upper), dec);
}
else
{
p1788::exception::signal_undefined_operation();
}
}
return nai();
}
// decorated inf-sup-dec interval mixed type
template<typename T>
template<typename L_, typename U_>
typename mpfr_bin_ieee754_flavor<T>::representation_dec
mpfr_bin_ieee754_flavor<T>::nums_dec_to_decorated_interval(L_ lower, U_ upper, p1788::decoration::decoration dec)
{
static_assert(std::numeric_limits<L_>::is_iec559, "Only IEEE 754 binary compliant types are supported!");
static_assert(std::numeric_limits<U_>::is_iec559, "Only IEEE 754 binary compliant types are supported!");
if (p1788::decoration::is_valid(dec))
{
// Comparison with NaN is always false!
if (dec != p1788::decoration::decoration::ill
&& (lower <= upper
&& lower != std::numeric_limits<L_>::infinity()
&& upper != -std::numeric_limits<U_>::infinity()
&& (dec != p1788::decoration::decoration::com
|| (lower != -std::numeric_limits<L_>::infinity()
&& upper != std::numeric_limits<U_>::infinity()))
)
)
{
representation tmp(convert_rndd(lower), convert_rndu(upper));
return representation_dec(tmp,
std::min(dec,
std::isinf(tmp.first) || std::isinf(tmp.second)
? p1788::decoration::decoration::dac
: p1788::decoration::decoration::com ));
}
else
{
p1788::exception::signal_undefined_operation();
}
}
return nai();
}
// string literal bare interval
template<typename T>
typename mpfr_bin_ieee754_flavor<T>::representation
mpfr_bin_ieee754_flavor<T>::text_to_interval(std::string const& str)
{
representation rep;
std::istringstream s(str);
operator_text_to_interval(s, rep);
if (!s)
{
p1788::exception::signal_undefined_operation();
return empty();
}
char c;
while(s.get(c))
if (!std::isspace(c))
{
p1788::exception::signal_undefined_operation();
return empty();
}
return rep;
}
// string literal decorated interval
template<typename T>
typename mpfr_bin_ieee754_flavor<T>::representation_dec
mpfr_bin_ieee754_flavor<T>::text_to_decorated_interval(std::string const& str)
{
representation_dec rep;
std::istringstream s(str);
operator_text_to_interval(s, rep);
if (!s)
{
p1788::exception::signal_undefined_operation();
return nai();
}
char c;
while(s.get(c))
if (!std::isspace(c))
{
p1788::exception::signal_undefined_operation();
return nai();
}
return rep;
}
// copy constructor bare interval
template<typename T>
typename mpfr_bin_ieee754_flavor<T>::representation
mpfr_bin_ieee754_flavor<T>::copy(representation const& other)
{
if (!is_valid(other))
{
return empty();
}
return other;
}
// copy constructor decorated interval
template<typename T>
typename mpfr_bin_ieee754_flavor<T>::representation_dec
mpfr_bin_ieee754_flavor<T>::copy(representation_dec const& other)
{
if (!is_valid(other))
{
return nai();
}
return other;
}
// -----------------------------------------------------------------------------
// Convert
// -----------------------------------------------------------------------------
// convert bare interval mixed type
template<typename T>
template<typename T_>
typename mpfr_bin_ieee754_flavor<T>::representation
mpfr_bin_ieee754_flavor<T>::convert_type(representation_type<T_> const& other)
{
static_assert(std::numeric_limits<T_>::is_iec559, "Only IEEE 754 binary compliant types are supported!");
if (!mpfr_bin_ieee754_flavor<T_>::is_valid(other))
{
return empty();
}
return convert_hull(other);
}
// convert decorated interval mixed type
template<typename T>
template<typename T_>
typename mpfr_bin_ieee754_flavor<T>::representation_dec
mpfr_bin_ieee754_flavor<T>::convert_type(representation_dec_type<T_> const& other)
{
static_assert(std::numeric_limits<T_>::is_iec559, "Only IEEE 754 binary compliant types are supported!");
if (!mpfr_bin_ieee754_flavor<T_>::is_valid(other))
{
return nai();
}
return convert_hull(other);
}
// convert decorated interval -> bare interval
template<typename T>
typename mpfr_bin_ieee754_flavor<T>::representation
mpfr_bin_ieee754_flavor<T>::interval_part(representation_dec const& other)
{
if (!is_valid(other))
{
return empty();
}
else if (is_nai(other))
{
p1788::exception::signal_interval_part_of_nai();
return empty();
}
return other.first;
}
// convert decorated interval -> bare interval mixed type
template<typename T>
template<typename T_>
typename mpfr_bin_ieee754_flavor<T>::representation
mpfr_bin_ieee754_flavor<T>::interval_part(representation_dec_type<T_> const& other)
{
static_assert(std::numeric_limits<T_>::is_iec559, "Only IEEE 754 binary compliant types are supported!");
if (!mpfr_bin_ieee754_flavor<T_>::is_valid(other))
{
return empty();
}
else if (mpfr_bin_ieee754_flavor<T_>::is_nai(other))
{
p1788::exception::signal_interval_part_of_nai();
return empty();
}
return convert_hull(other.first);
}
// convert bare interval -> decorated interval
template<typename T>
typename mpfr_bin_ieee754_flavor<T>::representation_dec
mpfr_bin_ieee754_flavor<T>::new_dec(representation const& other)
{
if (!is_valid(other))
{
return nai();
}
else if (is_empty(other))
{
return representation_dec(other, p1788::decoration::decoration::trv);
}
else if (other.first == -std::numeric_limits<T>::infinity() || other.second == std::numeric_limits<T>::infinity())
{
return representation_dec(other, p1788::decoration::decoration::dac);
}
else
{
return representation_dec(other, p1788::decoration::decoration::com);
}
}
// convert bare interval -> decorated interval mixed type
template<typename T>
template<typename T_>
typename mpfr_bin_ieee754_flavor<T>::representation_dec
mpfr_bin_ieee754_flavor<T>::new_dec(representation_type<T_> const& other)
{
static_assert(std::numeric_limits<T_>::is_iec559, "Only IEEE 754 binary compliant types are supported!");
if (!mpfr_bin_ieee754_flavor<T_>::is_valid(other))
{
return nai();
}
representation r = convert_hull(other);
if (is_empty(r))
{
return representation_dec(r, p1788::decoration::decoration::trv);
}
else if (r.first == -std::numeric_limits<T>::infinity() || r.second == std::numeric_limits<T>::infinity())
{
return representation_dec(r, p1788::decoration::decoration::dac);
}
else
{
return representation_dec(r, p1788::decoration::decoration::com);
}
}
// set decoration constructor
template<typename T>
typename mpfr_bin_ieee754_flavor<T>::representation_dec
mpfr_bin_ieee754_flavor<T>::set_dec(representation const& other, p1788::decoration::decoration dec)
{
if (!p1788::decoration::is_valid(dec) || !is_valid(other) || dec == p1788::decoration::decoration::ill)
{
return nai();
}
if (is_empty(other))
{
return empty_dec();
}
if (dec == p1788::decoration::decoration::com
&& (other.first == -std::numeric_limits<T>::infinity() || other.second == +std::numeric_limits<T>::infinity()))
{
return representation_dec(other, p1788::decoration::decoration::dac);
}
return representation_dec(other, dec);
}
// set decoration constructor mixed type
template<typename T>
template<typename T_>
typename mpfr_bin_ieee754_flavor<T>::representation_dec
mpfr_bin_ieee754_flavor<T>::set_dec(representation_type<T_> const& other, p1788::decoration::decoration dec)
{
static_assert(std::numeric_limits<T_>::is_iec559, "Only IEEE 754 binary compliant types are supported!");
return convert_hull(mpfr_bin_ieee754_flavor<T_>::set_dec(other, dec));
}
// get decoration
template<typename T>
p1788::decoration::decoration
mpfr_bin_ieee754_flavor<T>::decoration_part(representation_dec const& other)
{
if (!is_valid(other))
{
return p1788::decoration::decoration::ill;
}
return other.second;
}
} // namespace setbased
} // namespace infsup
} // namespace flavor
} // namespace p1788
#endif // LIBIEEEP1788_P1788_FLAVOR_INFSUP_SETBASED_MPFR_BIN_IEEE754_FLAVOR_CLASS_IMPL_HPP
| 29.216319 | 123 | 0.644541 | nehmeier |
f646dce818a2567323190f6ea2bc22130e46745a | 1,725 | cc | C++ | elements/standard/checkpaint.cc | MacWR/Click-changed-for-ParaGraph | 18285e5da578fbb7285d10380836146e738dee6e | [
"Apache-2.0"
] | 129 | 2015-10-08T14:38:35.000Z | 2022-03-06T14:54:44.000Z | elements/standard/checkpaint.cc | MacWR/Click-changed-for-ParaGraph | 18285e5da578fbb7285d10380836146e738dee6e | [
"Apache-2.0"
] | 241 | 2016-02-17T16:17:58.000Z | 2022-03-15T09:08:33.000Z | elements/standard/checkpaint.cc | MacWR/Click-changed-for-ParaGraph | 18285e5da578fbb7285d10380836146e738dee6e | [
"Apache-2.0"
] | 61 | 2015-12-17T01:46:58.000Z | 2022-02-07T22:25:19.000Z | /*
* checkpaint.{cc,hh} -- element checks paint annotation
* Eddie Kohler, Robert Morris
*
* Copyright (c) 1999-2000 Massachusetts Institute of Technology
* Copyright (c) 2008 Meraki, Inc.
*
* 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, subject to the conditions
* listed in the Click LICENSE file. These conditions include: you must
* preserve this copyright notice, and you cannot mention the copyright
* holders in advertising related to the Software without their permission.
* The Software is provided WITHOUT ANY WARRANTY, EXPRESS OR IMPLIED. This
* notice is a summary of the Click LICENSE file; the license in that file is
* legally binding.
*/
#include <click/config.h>
#include "checkpaint.hh"
#include <click/args.hh>
#include <click/error.hh>
#include <click/packet_anno.hh>
CLICK_DECLS
CheckPaint::CheckPaint()
{
}
int
CheckPaint::configure(Vector<String> &conf, ErrorHandler *errh)
{
int anno = PAINT_ANNO_OFFSET;
if (Args(conf, this, errh)
.read_mp("COLOR", _color)
.read_p("ANNO", AnnoArg(1), anno)
.complete() < 0)
return -1;
_anno = anno;
return 0;
}
void
CheckPaint::push(int, Packet *p)
{
if (p->anno_u8(_anno) != _color)
checked_output_push(1, p);
else
output(0).push(p);
}
Packet *
CheckPaint::pull(int)
{
Packet *p = input(0).pull();
if (p && p->anno_u8(_anno) != _color) {
checked_output_push(1, p);
p = 0;
}
return p;
}
void
CheckPaint::add_handlers()
{
add_data_handlers("color", Handler::OP_READ | Handler::OP_WRITE, &_color);
}
CLICK_ENDDECLS
EXPORT_ELEMENT(CheckPaint)
| 24.295775 | 78 | 0.708986 | MacWR |
f64881ce8abc7d77b304e8aecf57be400d1fe452 | 1,153 | cpp | C++ | Effective STL/estl-examples/26-1.cpp | goodspeed24e/Programming | ae73fad022396ea03105aad83293facaeea561ae | [
"MIT"
] | 1 | 2021-03-12T19:29:33.000Z | 2021-03-12T19:29:33.000Z | Effective STL/estl-examples/26-1.cpp | goodspeed24e/Programming | ae73fad022396ea03105aad83293facaeea561ae | [
"MIT"
] | 1 | 2019-03-13T01:36:12.000Z | 2019-03-13T01:36:12.000Z | Effective STL/estl-examples/26-1.cpp | goodspeed24e/Programming | ae73fad022396ea03105aad83293facaeea561ae | [
"MIT"
] | null | null | null | //
// Example from Item 26
//
#include <iostream>
#include <deque>
#include "ESTLUtil.h"
int data[] = { -30, 102, 55, -19, 0, 222, -3000, 4000, 8, -2 };
const int numValues = sizeof data / sizeof(int);
int main()
{
using namespace std;
using namespace ESTLUtils;
typedef deque<int> IntDeque; // STL container and
typedef IntDeque::iterator Iter; // iterator types are easier
typedef IntDeque::const_iterator ConstIter; // to work with if you
// use some typedefs
Iter i;
ConstIter ci;
deque<int> d; // make i and ci point into
i = d.begin(); // the same container
ci = d.begin();
if (i == ci) // compare an iterator
cout << "Iterators are equal" << endl; // and a const_iterator
else
cout << "Iterators are not equal" << endl;
if (ci == i) // workaround for when the
cout << "Iterators are equal" << endl; // comparison above won't compile
else
cout << "Iterators are not equal" << endl;
if (ci + 3 <= i) // workaround for when the above
cout << "Iterators are equal" << endl; // won't compile
else
cout << "Iterators are not equal" << endl;
return 0;
}
| 23.530612 | 74 | 0.619254 | goodspeed24e |
f648900f3836270aafc74e829eed9d3565b0677d | 860 | cpp | C++ | Ch 05/5.14.cpp | Felon03/CppPrimer | 7dc2daf59f0ae7ec5670def15cb5fab174fe9780 | [
"Apache-2.0"
] | null | null | null | Ch 05/5.14.cpp | Felon03/CppPrimer | 7dc2daf59f0ae7ec5670def15cb5fab174fe9780 | [
"Apache-2.0"
] | null | null | null | Ch 05/5.14.cpp | Felon03/CppPrimer | 7dc2daf59f0ae7ec5670def15cb5fab174fe9780 | [
"Apache-2.0"
] | null | null | null | /*编写一段程序,从标准输入中读取若干string对象并查找连续重复出现的单词。*/
#include<iostream>
#include<string>
#include<vector>
using namespace std;
int main()
{
vector<string> st;
string st1, prestr;
unsigned int wordCnt = 1;
bool flag = false;
while (cin >> st1)
{
st.push_back(st1);
}
auto beg = st.begin();
while (beg != st.end())
{
if (prestr == *beg)
{
++wordCnt;
prestr = *beg;
++beg;
}
else
{
if (wordCnt > 1)
{
cout << prestr << " occurs " << wordCnt << " times" << endl;
wordCnt = 1;
flag = true;
}
prestr = *beg;
++beg;
}
if (beg == st.end()) // 统计最后可能连续的单词
if (wordCnt > 1)
{
cout << prestr << " occurs " << wordCnt << " times" << endl;
flag = true;
//wordCnt = 1; // 重置计数器
}
}
/*判断是否有重复的单词 flag 为 true即有重复的单词*/
if (!flag)
cout << "No word occurs more than 2 times." << endl;
return 0;
} | 16.538462 | 64 | 0.552326 | Felon03 |
f64a4a21f24b00080d2680d2251d39a4c4e14d67 | 598 | cpp | C++ | Classes/Log/AceLog.cpp | DahamChoi/cocos_mygui_debugSystem | f716d99b1babdc8dfe84535033505b936a84a055 | [
"MIT"
] | null | null | null | Classes/Log/AceLog.cpp | DahamChoi/cocos_mygui_debugSystem | f716d99b1babdc8dfe84535033505b936a84a055 | [
"MIT"
] | null | null | null | Classes/Log/AceLog.cpp | DahamChoi/cocos_mygui_debugSystem | f716d99b1babdc8dfe84535033505b936a84a055 | [
"MIT"
] | null | null | null | #include "AceLog.h"
#include "LogData.h"
#include <ctime>
USING_NS_ACE;
void AceLog::log(const std::string& msg, Type type)
{
AceLogPtr pAceLog = std::make_shared<AceLog>();
pAceLog->msg = msg;
pAceLog->type = type;
time_t curTime = std::time(NULL);
tm* pLocal = std::localtime(&curTime);
pAceLog->time = (long long)curTime;
char str[100];
sprintf(str, "%02d-%02d %02d:%02d:%02d", pLocal->tm_mon + 1, pLocal->tm_mday, pLocal->tm_hour, pLocal->tm_min, pLocal->tm_sec);
pAceLog->strTime = str;
LogData::getInstance()->addLog(pAceLog);
}
| 23.92 | 131 | 0.632107 | DahamChoi |
f64a5d74e963d282e50760d08b52ab7373d7705e | 1,959 | cpp | C++ | ojcpp/leetcode/000/031_m_nextpermutation.cpp | softarts/oj | 2f51f360a7a6c49e865461755aec2f3a7e721b9e | [
"Apache-2.0"
] | 3 | 2019-05-04T03:26:02.000Z | 2019-08-29T01:20:44.000Z | ojcpp/leetcode/000/031_m_nextpermutation.cpp | softarts/oj | 2f51f360a7a6c49e865461755aec2f3a7e721b9e | [
"Apache-2.0"
] | null | null | null | ojcpp/leetcode/000/031_m_nextpermutation.cpp | softarts/oj | 2f51f360a7a6c49e865461755aec2f3a7e721b9e | [
"Apache-2.0"
] | null | null | null | //
// Created by rui.zhou on 2/20/2019.
//
/*
* Implement next permutation, which rearranges numbers into the lexicographically next greater permutation of numbers.
If such arrangement is not possible, it must rearrange it as the lowest possible order (ie, sorted in ascending order).
The replacement must be in-place and use only constant extra memory.
Here are some examples. Inputs are in the left-hand column and its corresponding outputs are in the right-hand column.
1,2,3 → 1,3,2
3,2,1 → 1,2,3
1,1,5 → 1,5,1
next permutation实现
从右往左,找到第一个降序的位置(v[i]<v[i+1]),左边比右边小的数字,例如1,2,3中的2
然后从右往左到i位置,找到第一个大于v[i]的数字,swap之,1,2,3 中的3,交换=>1,3,2
再把i+1到end位置逆序,即左到右从小到达排列(原来是从大到小) 从2之后的数字逆序
此时返回
如果均找不到,表明从左到右已经完全降序排列,需要reverse
*/
#include <codech/codech_def.h>
using namespace std;
using namespace CODECH;
class Solution {
public:
void nextPermutation(vector<int>& nums) {
next_permutation(nums.begin(), nums.end());
}
template<class BidDirIt>
bool next_permutation(BidDirIt first, BidDirIt last) {
if (first==last) return false;
BidDirIt i = last;
if (first==--i) return false; // only 1 element return false
while (true) {
BidDirIt i1=i;
if (*(--i)<*i1) { // find first element < right of it.
BidDirIt i2=last;
while (*i>=*--i2); // at least [i+1]>=[i]
swap(*i,*i2); // found i2
reverse(i1,last);
return true;
}
if (i==first) {
reverse(first, last);
return false;
}
}
}
};
DEFINE_CODE_TEST(031_nextpermutation)
{
Solution obj;
{
vector<int> nums{1,2,3};
obj.nextPermutation(nums);
VERIFY_CASE(PRINT_VEC(std::move(nums)),"1 3 2");
}
{
vector<int> nums{1,5,1};
obj.nextPermutation(nums);
VERIFY_CASE(PRINT_VEC(std::move(nums)),"5 1 1");
}
}
| 27.208333 | 119 | 0.60439 | softarts |
f64da81defb3c247ef8d238ae61e13665484af93 | 1,607 | cc | C++ | FTPD_cmd.cc | shuLhan/libvos | 831491b197fa8f267fd94966d406596896e6f25c | [
"BSD-3-Clause"
] | 1 | 2017-09-14T13:31:16.000Z | 2017-09-14T13:31:16.000Z | FTPD_cmd.cc | shuLhan/libvos | 831491b197fa8f267fd94966d406596896e6f25c | [
"BSD-3-Clause"
] | null | null | null | FTPD_cmd.cc | shuLhan/libvos | 831491b197fa8f267fd94966d406596896e6f25c | [
"BSD-3-Clause"
] | 5 | 2015-04-11T02:59:06.000Z | 2021-03-03T19:45:39.000Z | //
// Copyright 2009-2016 M. Shulhan (ms@kilabit.info). All rights reserved.
// Use of this source code is governed by a BSD-style license that can be
// found in the LICENSE file.
//
#include "FTPD_cmd.hh"
namespace vos {
const char* FTPD_cmd::__cname = "FTPD_cmd";
FTPD_cmd::FTPD_cmd() :
_code(0)
, _name()
, _parm()
, _callback(NULL)
{}
FTPD_cmd::~FTPD_cmd()
{
reset();
}
/**
* @method : FTPD_cmd::reset
* @desc : reset all attribute.
*/
void FTPD_cmd::reset()
{
_code = 0;
_name.reset();
_parm.reset();
_callback = 0;
}
/**
* @method : FTPD_cmd::set
* @param :
* > cmd : pointer to FTPD_cmd object.
* @desc : set content of this object using data from 'cmd' object.
*/
void FTPD_cmd::set(FTPD_cmd *cmd)
{
_code = cmd->_code;
_name.copy(&cmd->_name);
_parm.copy(&cmd->_parm);
_callback = cmd->_callback;
}
/**
* @method : FTPD_cmd::dump
* @desc : Dump content of FTPD_cmd object.
*/
void FTPD_cmd::dump()
{
printf( "[vos::FTPD_cmd__] dump:\n"
" command : %s\n"
" parameter : %s\n", _name.chars(), _parm.chars());
}
/**
* @method : FTPD_cmd::INIT
* @param :
* > name : name of new command.
* @return : pointer to function.
* < !NULL : success, pointer to new FTPD_cmd object.
* < NULL : fail.
* @desc : Create and initialize a new FTPD_cmd object.
*/
FTPD_cmd* FTPD_cmd::INIT(const int code, const char* name
, void (*callback)(const void*, const void*))
{
FTPD_cmd* cmd = new FTPD_cmd();
if (cmd) {
cmd->_code = code;
cmd->_callback = callback;
cmd->_name.copy_raw(name);
}
return cmd;
}
} /* namespace::vos */
// vi: ts=8 sw=8 tw=78:
| 18.686047 | 73 | 0.6285 | shuLhan |
f650d145e363c90851335df1b00baa52aa0999bd | 1,622 | cpp | C++ | projects/generation/sculptor/source/sculptor/geometry/Edge.cpp | silentorb/mythic-cpp | 97319d158800d77e1a944c47c13523662bc07e08 | [
"MIT"
] | null | null | null | projects/generation/sculptor/source/sculptor/geometry/Edge.cpp | silentorb/mythic-cpp | 97319d158800d77e1a944c47c13523662bc07e08 | [
"MIT"
] | null | null | null | projects/generation/sculptor/source/sculptor/geometry/Edge.cpp | silentorb/mythic-cpp | 97319d158800d77e1a944c47c13523662bc07e08 | [
"MIT"
] | null | null | null | #include "sculptor/geometry.h"
namespace sculptor_old {
namespace geometry {
Edge::Edge(Vertex *first, Vertex *second) {
vertices[0] = first;
vertices[1] = second;
find_polygons();
first->edges.push_back(this);
second->edges.push_back(this);
}
}
void Edge::find_polygons() {
for (int i = 0; i < 2; ++i) {
auto vertex = vertices[i];
for (auto polygon: vertex->polygons) {
if ((polygons.size() == 0 || polygons[0] != polygon)
&& vector_contains(vertices[1 - i]->polygons, polygon)) {
// && !vector_contains(polygons, polygon)) {
polygons.push_back(polygon);
if (polygons.size() == 2)
return;
}
}
}
}
bool Edge::contains(Vertex *vertex) {
return vertices[0] == vertex || vertices[1] == vertex;
}
void Edge::get_ordered_points(Vertex *points[2]) {
auto other_polygon = polygons[0];
auto p = 0;
for (auto vertex: other_polygon->vertices) {
if (contains(vertex))
points[p++] = vertex;
}
if (points[0] == other_polygon->vertices[0]
&& points[1] == other_polygon->vertices[other_polygon->vertices.size() - 1]) {
// Reverse the points
auto temp = points[0];
points[0] = points[1];
points[1] = temp;
}
}
Vertex *Edge::get_other_vertex(Vertex *vertex) {
if (vertex == vertices[0])
return vertices[1];
if (vertex == vertices[1])
return vertices[0];
throw runtime_error("vertex does not exist in edge.");
}
}
| 25.34375 | 87 | 0.548705 | silentorb |
f651e7c2b998d73d94d9609835fcc40c7299cf37 | 1,556 | cpp | C++ | 6. Heaps/HeapSort.cpp | suraj0803/DSA | 6ea21e452d7662e2351ee2a7b0415722e1bbf094 | [
"MIT"
] | null | null | null | 6. Heaps/HeapSort.cpp | suraj0803/DSA | 6ea21e452d7662e2351ee2a7b0415722e1bbf094 | [
"MIT"
] | null | null | null | 6. Heaps/HeapSort.cpp | suraj0803/DSA | 6ea21e452d7662e2351ee2a7b0415722e1bbf094 | [
"MIT"
] | null | null | null | #include<iostream>
#include<vector>
using namespace std;
void print(vector<int> v){
for(int x:v){
cout<<x<<" ";
}
cout<<endl;
}
bool minHeap = false;
bool compare(int a, int b){
if(minHeap){
return a<b;
}
else{
return a>b;
}
}
void heapify(vector<int> &v, int index, int size)
{
int left = 2*index;
int right = 2*index+1;
int min_index = index;
int last = size-1;
if(left <= last and compare(v[left],v[index])){
min_index = left;
}
if(right <= last and compare(v[right],v[index])){
min_index = right;
}
if(min_index!=index){
swap(v[index],v[min_index]);
heapify(v,min_index,size);
}
}
void buildHeap(vector<int> &v)
{
for(int i=(v.size()-1/2); i>=1; i--){// start from 1st non leaves and then heapify
// root node is fixed
heapify(v,i,v.size());
}
}
void heapsort(vector<int> &arr){
buildHeap(arr);
int n = arr.size();
//remove n-1 elements from the top
while(n>1){
swap(arr[1],arr[n-1]);
// remove that element from the heap
n--;// here we are just shrinking the size and we actually popping the element.
heapify(arr,1,n);
}
}
int main()
{
vector<int> v;
v.push_back(-1);
int n;
cin>>n;
int temp;
for(int i=0; i<n; i++){
cin>>temp;
v.push_back(temp);
}
heapsort(v);
print(v);
return 0;
} | 18.093023 | 88 | 0.503856 | suraj0803 |
f654cefc5761d245701e3300ccf8a6ba5973615f | 3,990 | cpp | C++ | Source/ArgsPasserModule/Private/Views/SLauncherWidget.cpp | lpestl/ArgsPasser | e7dc26ccfccd160ca8ed2eee10633a89d88c066a | [
"MIT"
] | null | null | null | Source/ArgsPasserModule/Private/Views/SLauncherWidget.cpp | lpestl/ArgsPasser | e7dc26ccfccd160ca8ed2eee10633a89d88c066a | [
"MIT"
] | null | null | null | Source/ArgsPasserModule/Private/Views/SLauncherWidget.cpp | lpestl/ArgsPasser | e7dc26ccfccd160ca8ed2eee10633a89d88c066a | [
"MIT"
] | null | null | null | #include "SLauncherWidget.h"
#include "DesktopPlatform/Public/DesktopPlatformModule.h"
#include "DesktopPlatform/Public/IDesktopPlatform.h"
#include "Editor/MainFrame/Public/Interfaces/IMainFrameModule.h"
#define LOCTEXT_NAMESPACE "LauncherWidget"
void SLauncherWidget::Construct(const FArguments& InArgs)
{
ChildSlot
[
SNew( SVerticalBox )
+SVerticalBox::Slot()
.AutoHeight()
.Padding( 5.f )
[
SNew( SHorizontalBox )
+SHorizontalBox::Slot()
.AutoWidth()
.VAlign( VAlign_Center )
.Padding(FMargin(0.f, 0.f, 3.f, 0.f) )
[
SNew( STextBlock )
.Text( NSLOCTEXT( "Launcher", "ExecutableText", "Executable:" ) )
]
+SHorizontalBox::Slot()
.FillWidth( 1.f )
[
SNew( SEditableTextBox )
.HintText( NSLOCTEXT( "Launcher", "PleaseEnterPath", "Please enter the path to the file") )
.Text(this, &SLauncherWidget::GetExecutablePath)
.OnTextCommitted(this, &SLauncherWidget::OnExecutablePathCommited)
]
+SHorizontalBox::Slot()
.AutoWidth()
.Padding( FMargin( 0.f, -1.f ) )
[
SNew( SButton )
.Text( NSLOCTEXT( "Launcher", "Browse", "Browse...") )
.OnClicked(this, &SLauncherWidget::OnBrowseExecutableClicked)
.ContentPadding(FCoreStyle::Get().GetMargin("StandardDialog.ContentPadding"))
]
]
+SVerticalBox::Slot()
.FillHeight( 1.f )
.Padding( 5.f )
+SVerticalBox::Slot()
.AutoHeight()
.Padding( 5.f )
.HAlign( HAlign_Right )
[
SNew( SHorizontalBox )
+SHorizontalBox::Slot()
.Padding( FMargin( 3.f, 0.f, 0.f, 0.f ) )
[
SNew( SBox )
.WidthOverride( 100.f )
[
SNew( SButton )
.HAlign(HAlign_Center)
.Text( NSLOCTEXT( "Launcher", "ExecuteText", "Execute" ) )
.IsEnabled(this, &SLauncherWidget::IsExecutablePathExist)
]
]
]
];
}
bool SLauncherWidget::ShowOpenFileDialog(
const FString& DefaultFolder,
const FString& FileDescription,
const FString& FileExtension,
TArray<FString>& OutFileNames)
{
// Prompt the user for the filenames
IDesktopPlatform* DesktopPlatform = FDesktopPlatformModule::Get();
const FString FileTypes = FString::Printf( TEXT("%s (%s)|%s"), *FileDescription, *FileExtension, *FileExtension );
bool bOpened = false;
if ( DesktopPlatform )
{
void* ParentWindowWindowHandle = nullptr;
const TSharedPtr<SWindow>& MainFrameParentWindow = FSlateApplicationBase::Get().GetActiveTopLevelWindow();
if ( MainFrameParentWindow.IsValid() && MainFrameParentWindow->GetNativeWindow().IsValid() )
{
ParentWindowWindowHandle = MainFrameParentWindow->GetNativeWindow()->GetOSWindowHandle();
}
bOpened = DesktopPlatform->OpenFileDialog(
ParentWindowWindowHandle,
LOCTEXT("OpenProjectBrowseTitle", "Open Project").ToString(),
DefaultFolder,
TEXT(""),
FileTypes,
EFileDialogFlags::None,
OutFileNames
);
}
return bOpened;
}
FReply SLauncherWidget::OnBrowseExecutableClicked()
{
const FString FileDescription = LOCTEXT( "FileTypeDescription", "All files" ).ToString();
const FString FileExtension = FString::Printf(TEXT("*.*"));
const FString DefaultFolder = FString();
TArray< FString > FileNames;
if (ShowOpenFileDialog(DefaultFolder, FileDescription, FileExtension, FileNames))
{
if (FileNames.Num() > 0)
{
ExecutablePath = FPaths::ConvertRelativePathToFull(FileNames[0]);
bIsExecutablePathExist = CheckPathExist(ExecutablePath);
}
}
return FReply::Handled();
}
FText SLauncherWidget::GetExecutablePath() const
{
return FText::FromString( ExecutablePath );
}
void SLauncherWidget::OnExecutablePathCommited(const FText& InText, ETextCommit::Type Type)
{
ExecutablePath = InText.ToString();
bIsExecutablePathExist = CheckPathExist(ExecutablePath);
}
bool SLauncherWidget::IsExecutablePathExist() const
{
return bIsExecutablePathExist;
}
bool SLauncherWidget::CheckPathExist(const FString& InPath)
{
IPlatformFile& FileManager = FPlatformFileManager::Get().GetPlatformFile();
return FileManager.FileExists(*InPath);
}
#undef LOCTEXT_NAMESPACE
| 27.328767 | 115 | 0.717043 | lpestl |
f65514fe24b9611de9c0db63bf3553bb2c92f668 | 1,497 | cc | C++ | src/libmu/mu/mu-printer.cc | Software-Knife-and-Tool/mux | 19166e2efde01dd5dcab60f06fc5d9ec2740ac5a | [
"MIT"
] | null | null | null | src/libmu/mu/mu-printer.cc | Software-Knife-and-Tool/mux | 19166e2efde01dd5dcab60f06fc5d9ec2740ac5a | [
"MIT"
] | 105 | 2021-07-11T15:54:40.000Z | 2021-08-07T04:38:06.000Z | src/libmu/mu/mu-printer.cc | Software-Knife-and-Tool/xian | bd5c77a222bfa9c18379510e63930627cb2f028a | [
"MIT"
] | null | null | null | /********
**
** SPDX-License-Identifier: MIT
**
** Copyright (c) 2017-2022 James M. Putnam <putnamjm.design@gmail.com>
**
**/
/********
**
** mu-printer.cc: library print functions
**
**/
#include <bitset>
#include <cassert>
#include <functional>
#include <iomanip>
#include <map>
#include <sstream>
#include <utility>
#include "libmu/core/core.h"
#include "libmu/core/env.h"
#include "libmu/core/type.h"
#include "libmu/types/cons.h"
#include "libmu/types/exception.h"
#include "libmu/types/fixnum.h"
#include "libmu/types/float.h"
#include "libmu/types/function.h"
#include "libmu/types/stream.h"
#include "libmu/types/symbol.h"
#include "libmu/types/vector.h"
namespace libmu {
namespace mu {
using Exception = core::Exception;
using Frame = core::Env::Frame;
using Type = core::Type;
/** * (print object stream escape) => object **/
auto PrintWithEscape(Frame *fp) -> auto {
auto obj = fp->argv[0];
auto stream = fp->argv[1];
auto escape = fp->argv[2];
if (!core::Stream::IsStreamDesignator(stream))
Exception::Raise(fp->env, "print", "error", "type", stream);
core::Print(fp->env, obj, stream, !Type::Null(escape));
fp->value = obj;
}
/** * (terpri stream) => :nil **/
auto Terpri(Frame *fp) -> auto {
auto stream = fp->argv[0];
if (!core::Stream::IsStreamDesignator(stream))
Exception::Raise(fp->env, "terpri", "error", "type", stream);
core::Terpri(fp->env, stream);
fp->value = Type::NIL;
}
} /* namespace mu */
} /* namespace libmu */
| 22.014706 | 72 | 0.647295 | Software-Knife-and-Tool |
f6594f43202007fdc7e39dffb1d19a932b22fc4b | 10,272 | cc | C++ | libgav1/src/post_filter/super_res.cc | TinkerBoard-Android/external-libgav1 | b24cb9cd67a6fe6360d55af1225f885442c8abac | [
"Apache-2.0"
] | null | null | null | libgav1/src/post_filter/super_res.cc | TinkerBoard-Android/external-libgav1 | b24cb9cd67a6fe6360d55af1225f885442c8abac | [
"Apache-2.0"
] | null | null | null | libgav1/src/post_filter/super_res.cc | TinkerBoard-Android/external-libgav1 | b24cb9cd67a6fe6360d55af1225f885442c8abac | [
"Apache-2.0"
] | null | null | null | // Copyright 2020 The libgav1 Authors
//
// Licensed under the Apache License, Version 2.0 (the "License");
// you may not use this file except in compliance with the License.
// You may obtain a copy of the License at
//
// http://www.apache.org/licenses/LICENSE-2.0
//
// Unless required by applicable law or agreed to in writing, software
// distributed under the License is distributed on an "AS IS" BASIS,
// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
// See the License for the specific language governing permissions and
// limitations under the License.
#include "src/post_filter.h"
#include "src/utils/blocking_counter.h"
namespace libgav1 {
namespace {
template <typename Pixel>
void ExtendLine(uint8_t* const line_start, const int width, const int left,
const int right) {
auto* const start = reinterpret_cast<Pixel*>(line_start);
const Pixel* src = start;
Pixel* dst = start - left;
// Copy to left and right borders.
Memset(dst, src[0], left);
Memset(dst + (left + width), src[width - 1], right);
}
} // namespace
template <bool in_place>
void PostFilter::ApplySuperRes(const std::array<uint8_t*, kMaxPlanes>& buffers,
const std::array<int, kMaxPlanes>& strides,
const std::array<int, kMaxPlanes>& rows,
size_t line_buffer_offset) {
// Only used when |in_place| == false.
uint8_t* const line_buffer_start = superres_line_buffer_ +
line_buffer_offset +
kSuperResHorizontalBorder * pixel_size_;
for (int plane = kPlaneY; plane < planes_; ++plane) {
const int8_t subsampling_x = subsampling_x_[plane];
const int plane_width =
MultiplyBy4(frame_header_.columns4x4) >> subsampling_x;
uint8_t* input = buffers[plane];
const uint32_t input_stride = strides[plane];
#if LIBGAV1_MAX_BITDEPTH >= 10
if (bitdepth_ >= 10) {
for (int y = 0; y < rows[plane]; ++y, input += input_stride) {
if (!in_place) {
memcpy(line_buffer_start, input, plane_width * sizeof(uint16_t));
}
ExtendLine<uint16_t>(in_place ? input : line_buffer_start, plane_width,
kSuperResHorizontalBorder,
kSuperResHorizontalBorder);
dsp_.super_res_row(in_place ? input : line_buffer_start,
super_res_info_[plane].upscaled_width,
super_res_info_[plane].initial_subpixel_x,
super_res_info_[plane].step,
input - (in_place ? input_stride : 0));
}
continue;
}
#endif // LIBGAV1_MAX_BITDEPTH >= 10
for (int y = 0; y < rows[plane]; ++y, input += input_stride) {
if (!in_place) {
memcpy(line_buffer_start, input, plane_width);
}
ExtendLine<uint8_t>(in_place ? input : line_buffer_start, plane_width,
kSuperResHorizontalBorder, kSuperResHorizontalBorder);
dsp_.super_res_row(in_place ? input : line_buffer_start,
super_res_info_[plane].upscaled_width,
super_res_info_[plane].initial_subpixel_x,
super_res_info_[plane].step,
input - (in_place ? input_stride : 0));
}
}
}
// Used by post_filter_test.cc.
template void PostFilter::ApplySuperRes<false>(
const std::array<uint8_t*, kMaxPlanes>& buffers,
const std::array<int, kMaxPlanes>& strides,
const std::array<int, kMaxPlanes>& rows, size_t line_buffer_offset);
void PostFilter::ApplySuperResForOneSuperBlockRow(int row4x4_start, int sb4x4,
bool is_last_row) {
assert(row4x4_start >= 0);
assert(DoSuperRes());
// If not doing cdef, then LR needs two rows of border with superres applied.
const int num_rows_extra = (DoCdef() || !DoRestoration()) ? 0 : 2;
std::array<uint8_t*, kMaxPlanes> buffers;
std::array<int, kMaxPlanes> strides;
std::array<int, kMaxPlanes> rows;
// Apply superres for the last 8-num_rows_extra rows of the previous
// superblock.
if (row4x4_start > 0) {
const int row4x4 = row4x4_start - 2;
for (int plane = 0; plane < planes_; ++plane) {
const int row =
(MultiplyBy4(row4x4) >> subsampling_y_[plane]) + num_rows_extra;
const ptrdiff_t row_offset = row * frame_buffer_.stride(plane);
buffers[plane] = cdef_buffer_[plane] + row_offset;
strides[plane] = frame_buffer_.stride(plane);
// Note that the |num_rows_extra| subtraction is done after the value is
// subsampled since we always need to work on |num_rows_extra| extra rows
// irrespective of the plane subsampling.
rows[plane] = (8 >> subsampling_y_[plane]) - num_rows_extra;
}
ApplySuperRes<true>(buffers, strides, rows, /*line_buffer_offset=*/0);
}
// Apply superres for the current superblock row (except for the last
// 8-num_rows_extra rows).
const int num_rows4x4 =
std::min(sb4x4, frame_header_.rows4x4 - row4x4_start) -
(is_last_row ? 0 : 2);
for (int plane = 0; plane < planes_; ++plane) {
const ptrdiff_t row_offset =
(MultiplyBy4(row4x4_start) >> subsampling_y_[plane]) *
frame_buffer_.stride(plane);
buffers[plane] = cdef_buffer_[plane] + row_offset;
strides[plane] = frame_buffer_.stride(plane);
// Note that the |num_rows_extra| subtraction is done after the value is
// subsampled since we always need to work on |num_rows_extra| extra rows
// irrespective of the plane subsampling.
rows[plane] = (MultiplyBy4(num_rows4x4) >> subsampling_y_[plane]) +
(is_last_row ? 0 : num_rows_extra);
}
ApplySuperRes<true>(buffers, strides, rows, /*line_buffer_offset=*/0);
}
void PostFilter::ApplySuperResThreaded() {
const int num_threads = thread_pool_->num_threads() + 1;
// The number of rows4x4 that will be processed by each thread in the thread
// pool (other than the current thread).
const int thread_pool_rows4x4 = frame_header_.rows4x4 / num_threads;
// For the current thread, we round up to process all the remaining rows so
// that the current thread's job will potentially run the longest.
const int current_thread_rows4x4 =
frame_header_.rows4x4 - (thread_pool_rows4x4 * (num_threads - 1));
// The size of the line buffer required by each thread. In the multi-threaded
// case we are guaranteed to have a line buffer which can store |num_threads|
// rows at the same time.
const size_t line_buffer_size =
(MultiplyBy4(frame_header_.columns4x4) +
MultiplyBy2(kSuperResHorizontalBorder) + kSuperResHorizontalPadding) *
pixel_size_;
size_t line_buffer_offset = 0;
BlockingCounter pending_workers(num_threads - 1);
for (int i = 0, row4x4_start = 0; i < num_threads; ++i,
row4x4_start += thread_pool_rows4x4,
line_buffer_offset += line_buffer_size) {
std::array<uint8_t*, kMaxPlanes> buffers;
std::array<int, kMaxPlanes> strides;
std::array<int, kMaxPlanes> rows;
for (int plane = 0; plane < planes_; ++plane) {
strides[plane] = frame_buffer_.stride(plane);
buffers[plane] =
GetBufferOffset(cdef_buffer_[plane], strides[plane],
static_cast<Plane>(plane), row4x4_start, 0);
if (i < num_threads - 1) {
rows[plane] = MultiplyBy4(thread_pool_rows4x4) >> subsampling_y_[plane];
} else {
rows[plane] =
MultiplyBy4(current_thread_rows4x4) >> subsampling_y_[plane];
}
}
if (i < num_threads - 1) {
thread_pool_->Schedule([this, buffers, strides, rows, line_buffer_offset,
&pending_workers]() {
ApplySuperRes<false>(buffers, strides, rows, line_buffer_offset);
pending_workers.Decrement();
});
} else {
ApplySuperRes<false>(buffers, strides, rows, line_buffer_offset);
}
}
// Wait for the threadpool jobs to finish.
pending_workers.Wait();
}
// This function lives in this file so that it has access to ExtendLine<>.
void PostFilter::SetupDeblockBuffer(int row4x4_start, int sb4x4) {
assert(row4x4_start >= 0);
assert(DoCdef());
assert(DoRestoration());
for (int sb_y = 0; sb_y < sb4x4; sb_y += 16) {
const int row4x4 = row4x4_start + sb_y;
for (int plane = 0; plane < planes_; ++plane) {
CopyDeblockedPixels(static_cast<Plane>(plane), row4x4);
}
const int row_offset_start = DivideBy4(row4x4);
if (DoSuperRes()) {
std::array<uint8_t*, kMaxPlanes> buffers = {
deblock_buffer_.data(kPlaneY) +
row_offset_start * deblock_buffer_.stride(kPlaneY),
deblock_buffer_.data(kPlaneU) +
row_offset_start * deblock_buffer_.stride(kPlaneU),
deblock_buffer_.data(kPlaneV) +
row_offset_start * deblock_buffer_.stride(kPlaneV)};
std::array<int, kMaxPlanes> strides = {deblock_buffer_.stride(kPlaneY),
deblock_buffer_.stride(kPlaneU),
deblock_buffer_.stride(kPlaneV)};
std::array<int, kMaxPlanes> rows = {4, 4, 4};
ApplySuperRes<false>(buffers, strides, rows,
/*line_buffer_offset=*/0);
}
// Extend the left and right boundaries needed for loop restoration.
for (int plane = 0; plane < planes_; ++plane) {
uint8_t* src = deblock_buffer_.data(plane) +
row_offset_start * deblock_buffer_.stride(plane);
const int plane_width =
RightShiftWithRounding(upscaled_width_, subsampling_x_[plane]);
for (int i = 0; i < 4; ++i) {
#if LIBGAV1_MAX_BITDEPTH >= 10
if (bitdepth_ >= 10) {
ExtendLine<uint16_t>(src, plane_width, kRestorationHorizontalBorder,
kRestorationHorizontalBorder);
} else // NOLINT.
#endif
{
ExtendLine<uint8_t>(src, plane_width, kRestorationHorizontalBorder,
kRestorationHorizontalBorder);
}
src += deblock_buffer_.stride(plane);
}
}
}
}
} // namespace libgav1
| 44.085837 | 80 | 0.641355 | TinkerBoard-Android |
2cf1c405f8068029edc7f14e62ebb7f99aab97b3 | 2,712 | cpp | C++ | pausedialog.cpp | williamwu88/Flying-Stickman | d11c05e87bde481200ed1f3aaf5a0f4e4982d9ae | [
"MIT"
] | null | null | null | pausedialog.cpp | williamwu88/Flying-Stickman | d11c05e87bde481200ed1f3aaf5a0f4e4982d9ae | [
"MIT"
] | null | null | null | pausedialog.cpp | williamwu88/Flying-Stickman | d11c05e87bde481200ed1f3aaf5a0f4e4982d9ae | [
"MIT"
] | null | null | null | #include "pausedialog.h"
#include "ui_pausedialog.h"
PauseDialog::PauseDialog(bool *paused, QWidget *parent) :
QDialog(parent),
ui(new Ui::PauseDialog),
paused(paused) {
ui->setupUi(this);
//this->setStyleSheet("background-color: #FFFFFF;"); //White
this->setFixedSize(this->width(), this->height());
setUpUI();
}
PauseDialog::~PauseDialog() {
delete ui;
}
//Sets up the pause screen with the values from the config screen
void PauseDialog::setUpUI() {
std::string stickman_size = Config::config()->getStickman()->getSize();
int stickman_x_position = Config::config()->getStickman()->getXPosition();
if (stickman_size == "tiny") {
ui->tiny_radio->setChecked(true);
}
else if (stickman_size == "normal") {
ui->normal_radio->setChecked(true);
}
else if (stickman_size == "large") {
ui->large_radio->setChecked(true);
}
else if (stickman_size == "giant") {
ui->giant_radio->setChecked(true);
}
ui->position_slider->setMaximum(Config::config()->getWorldWidth());
ui->position_slider->setValue(stickman_x_position);
}
void PauseDialog::on_buttonBox_clicked(QAbstractButton *button) {
// See what radio button is pressed
if ((QPushButton *)button == ui->buttonBox->button(QDialogButtonBox::Close)) {
if (ui->tiny_radio->isChecked()) {
ui->tiny_radio->setChecked(true);
}
else if (ui->normal_radio->isChecked()) {
ui->normal_radio->setChecked(true);
}
else if (ui->large_radio->isChecked()) {
ui->large_radio->setChecked(true);
}
else if (ui->giant_radio->isChecked()) {
ui->giant_radio->setChecked(true);
}
*this->paused = false;
}
}
//Real-time update of the x position of the stickman
void PauseDialog::on_position_slider_actionTriggered(int /*action*/) {
Config::config()->getStickman()->changeXPosition(ui->position_slider->value());
}
//Following methods update in real-time the size of the stickman
void PauseDialog::on_tiny_radio_clicked() {
Config::config()->getStickman()->changeSize("tiny");
Config::config()->getStickman()->updateStickman();
}
void PauseDialog::on_normal_radio_clicked() {
Config::config()->getStickman()->changeSize("normal");
Config::config()->getStickman()->updateStickman();
}
void PauseDialog::on_large_radio_clicked() {
Config::config()->getStickman()->changeSize("large");
Config::config()->getStickman()->updateStickman();
}
void PauseDialog::on_giant_radio_clicked() {
Config::config()->getStickman()->changeSize("giant");
Config::config()->getStickman()->updateStickman();
}
| 27.673469 | 83 | 0.65118 | williamwu88 |
2cf217767ac1a4d3b1a36960dd44b5fbcf1f40c8 | 3,966 | cc | C++ | chrome/browser/privacy_budget/privacy_budget_ukm_entry_filter_unittest.cc | mghgroup/Glide-Browser | 6a4c1eaa6632ec55014fee87781c6bbbb92a2af5 | [
"BSD-3-Clause-No-Nuclear-License-2014",
"BSD-3-Clause"
] | null | null | null | chrome/browser/privacy_budget/privacy_budget_ukm_entry_filter_unittest.cc | mghgroup/Glide-Browser | 6a4c1eaa6632ec55014fee87781c6bbbb92a2af5 | [
"BSD-3-Clause-No-Nuclear-License-2014",
"BSD-3-Clause"
] | null | null | null | chrome/browser/privacy_budget/privacy_budget_ukm_entry_filter_unittest.cc | mghgroup/Glide-Browser | 6a4c1eaa6632ec55014fee87781c6bbbb92a2af5 | [
"BSD-3-Clause-No-Nuclear-License-2014",
"BSD-3-Clause"
] | 2 | 2021-01-05T23:43:46.000Z | 2021-01-07T23:36:34.000Z | // Copyright 2020 The Chromium Authors. All rights reserved.
// Use of this source code is governed by a BSD-style license that can be
// found in the LICENSE file.
#include "chrome/browser/privacy_budget/privacy_budget_ukm_entry_filter.h"
#include <cstdint>
#include "base/containers/flat_map.h"
#include "base/template_util.h"
#include "chrome/common/privacy_budget/scoped_privacy_budget_config.h"
#include "components/prefs/testing_pref_service.h"
#include "services/metrics/public/cpp/ukm_builders.h"
#include "services/metrics/public/mojom/ukm_interface.mojom.h"
#include "testing/gtest/include/gtest/gtest.h"
namespace {
class PrivacyBudgetUkmEntryFilterTest : public ::testing::Test {
public:
PrivacyBudgetUkmEntryFilterTest() {
// Uses FeatureLists. Hence needs to be initialized in the constructor lest
// we add any multithreading tests here.
auto parameters = test::ScopedPrivacyBudgetConfig::Parameters{};
config_.Apply(parameters);
prefs::RegisterPrivacyBudgetPrefs(pref_service_.registry());
}
TestingPrefServiceSimple* pref_service() { return &pref_service_; }
private:
TestingPrefServiceSimple pref_service_;
test::ScopedPrivacyBudgetConfig config_;
};
} // namespace
TEST(PrivacyBudgetUkmEntryFilterStandaloneTest,
BlocksIdentifiabilityMetricsByDefault) {
TestingPrefServiceSimple pref_service;
prefs::RegisterPrivacyBudgetPrefs(pref_service.registry());
auto settings = std::make_unique<IdentifiabilityStudyState>(&pref_service);
auto filter = std::make_unique<PrivacyBudgetUkmEntryFilter>(settings.get());
// By default the filter should reject all Identifiability events:
base::flat_map<uint64_t, int64_t> events = {{1, 1}, {2, 2}};
ukm::mojom::UkmEntryPtr x(base::in_place, 1,
ukm::builders::Identifiability::kEntryNameHash,
events);
base::flat_set<uint64_t> filtered;
EXPECT_FALSE(filter->FilterEntry(x.get(), &filtered));
EXPECT_TRUE(filtered.empty());
}
TEST(PrivacyBudgetUkmEntryFilterStandaloneTest, AllowsOtherMetricsByDefault) {
TestingPrefServiceSimple pref_service;
prefs::RegisterPrivacyBudgetPrefs(pref_service.registry());
auto settings = std::make_unique<IdentifiabilityStudyState>(&pref_service);
auto filter = std::make_unique<PrivacyBudgetUkmEntryFilter>(settings.get());
base::flat_map<uint64_t, int64_t> events = {{1, 1}, {2, 2}};
ukm::mojom::UkmEntryPtr x(base::in_place, 1,
ukm::builders::Blink_UseCounter::kEntryNameHash,
events);
base::flat_set<uint64_t> filtered;
EXPECT_TRUE(filter->FilterEntry(x.get(), &filtered));
EXPECT_TRUE(filtered.empty());
EXPECT_EQ(2u, x->metrics.size());
}
TEST(PrivacyBudgetUkmEntryFilterStandaloneTest, BlockListedMetrics) {
constexpr uint64_t kBlockedSurface = 1;
constexpr uint64_t kUnblockedSurface = 2;
test::ScopedPrivacyBudgetConfig::Parameters parameters;
parameters.blocked_surfaces.push_back(
blink::IdentifiableSurface::FromMetricHash(kBlockedSurface));
test::ScopedPrivacyBudgetConfig scoped_config;
scoped_config.Apply(parameters);
TestingPrefServiceSimple pref_service;
prefs::RegisterPrivacyBudgetPrefs(pref_service.registry());
auto settings = std::make_unique<IdentifiabilityStudyState>(&pref_service);
auto filter = std::make_unique<PrivacyBudgetUkmEntryFilter>(settings.get());
base::flat_map<uint64_t, int64_t> metrics = {{kBlockedSurface, 1},
{kUnblockedSurface, 2}};
ukm::mojom::UkmEntryPtr x(base::in_place, 1,
ukm::builders::Identifiability::kEntryNameHash,
metrics);
ASSERT_EQ(2u, x->metrics.size());
base::flat_set<uint64_t> filtered;
EXPECT_TRUE(filter->FilterEntry(x.get(), &filtered));
EXPECT_TRUE(filtered.empty());
ASSERT_EQ(1u, x->metrics.size());
EXPECT_EQ(kUnblockedSurface, x->metrics.begin()->first);
}
| 39.267327 | 79 | 0.734493 | mghgroup |
2cf4381bb3482283e4c2c84af071694678e219a1 | 203 | cpp | C++ | Fellz/RaknetGlobals.cpp | digitalhoax/fellz | cacf5cd57f00121bcb2a795021aed24c4164c418 | [
"Zlib",
"libtiff",
"BSD-2-Clause",
"Apache-2.0",
"MIT",
"Libpng",
"curl",
"BSD-3-Clause"
] | 1 | 2017-09-25T09:32:22.000Z | 2017-09-25T09:32:22.000Z | Fellz/RaknetGlobals.cpp | digitalhoax/fellz | cacf5cd57f00121bcb2a795021aed24c4164c418 | [
"Zlib",
"libtiff",
"BSD-2-Clause",
"Apache-2.0",
"MIT",
"Libpng",
"curl",
"BSD-3-Clause"
] | null | null | null | Fellz/RaknetGlobals.cpp | digitalhoax/fellz | cacf5cd57f00121bcb2a795021aed24c4164c418 | [
"Zlib",
"libtiff",
"BSD-2-Clause",
"Apache-2.0",
"MIT",
"Libpng",
"curl",
"BSD-3-Clause"
] | null | null | null | #include "RaknetGlobals.h"
// for documentation, see RaknetGlobals.h
RakNet::RakPeerInterface* player2;
RakNet::SystemAddress player2Adress;
bool isServer;
bool isConnected;
bool otherGameOver; | 22.555556 | 42 | 0.783251 | digitalhoax |
2cf898eb30b312384af57b0be63943dfc1e3cacc | 45 | hpp | C++ | src/boost_mpl_aux__config_has_xxx.hpp | miathedev/BoostForArduino | 919621dcd0c157094bed4df752b583ba6ea6409e | [
"BSL-1.0"
] | 10 | 2018-03-17T00:58:42.000Z | 2021-07-06T02:48:49.000Z | src/boost_mpl_aux__config_has_xxx.hpp | miathedev/BoostForArduino | 919621dcd0c157094bed4df752b583ba6ea6409e | [
"BSL-1.0"
] | 2 | 2021-03-26T15:17:35.000Z | 2021-05-20T23:55:08.000Z | src/boost_mpl_aux__config_has_xxx.hpp | miathedev/BoostForArduino | 919621dcd0c157094bed4df752b583ba6ea6409e | [
"BSL-1.0"
] | 4 | 2019-05-28T21:06:37.000Z | 2021-07-06T03:06:52.000Z | #include <boost/mpl/aux_/config/has_xxx.hpp>
| 22.5 | 44 | 0.777778 | miathedev |
2cf89ab55f7193b92900ab50122c466e126f0a5e | 9,234 | cpp | C++ | src/Daggy/CConsoleDaggy.cpp | milovidov/dataagregator | 1150f66fc2ef2bbcf62c0174ef147109185cad98 | [
"MIT"
] | 135 | 2019-06-23T20:32:33.000Z | 2022-02-06T15:41:41.000Z | src/Daggy/CConsoleDaggy.cpp | milovidov/dataagregator | 1150f66fc2ef2bbcf62c0174ef147109185cad98 | [
"MIT"
] | 2 | 2020-10-16T17:31:44.000Z | 2022-01-02T22:02:04.000Z | src/Daggy/CConsoleDaggy.cpp | milovidov/dataagregator | 1150f66fc2ef2bbcf62c0174ef147109185cad98 | [
"MIT"
] | 11 | 2019-12-26T14:36:44.000Z | 2022-02-23T02:14:41.000Z | /*
MIT License
Copyright (c) 2020 Mikhail Milovidov
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 "Precompiled.hpp"
#include "CConsoleDaggy.hpp"
#include <DaggyCore/Core.hpp>
#include <DaggyCore/aggregators/CConsole.hpp>
#include <DaggyCore/aggregators/CFile.hpp>
#include <DaggyCore/Types.hpp>
#include <DaggyCore/Errors.hpp>
using namespace daggy;
CConsoleDaggy::CConsoleDaggy(QObject* parent)
: QObject(parent)
, daggy_core_(nullptr)
, need_hard_stop_(false)
{
qApp->setApplicationName(DAGGY_NAME);
qApp->setApplicationVersion(DAGGY_VERSION_FULL);
qApp->setOrganizationName(DAGGY_VENDOR);
qApp->setOrganizationDomain(DAGGY_HOMEPAGE_URL);
connect(this, &CConsoleDaggy::interrupt, this, &CConsoleDaggy::stop, Qt::QueuedConnection);
}
std::error_code CConsoleDaggy::prepare()
{
if (daggy_core_)
return errors::success;
const auto settings = parse();
Sources sources;
switch (settings.data_source_text_type) {
case Json:
sources = std::move(*sources::convertors::json(settings.data_source_text));
break;
case Yaml:
sources = std::move(*sources::convertors::yaml(settings.data_source_text));
break;
}
const QString& session = QDateTime::currentDateTime().toString("dd-MM-yy_hh-mm-ss-zzz") + "_" + settings.data_sources_name;
daggy_core_ = new Core(session, std::move(sources), this);
connect(daggy_core_, &Core::stateChanged, this, &CConsoleDaggy::onDaggyCoreStateChanged);
auto file_aggregator = new aggregators::CFile(settings.output_folder);
file_aggregator->moveToThread(&file_thread_);
connect(this, &CConsoleDaggy::destroyed, file_aggregator, &aggregators::CFile::deleteLater);
auto console_aggregator = new aggregators::CConsole(session, daggy_core_);
daggy_core_->connectAggregator(file_aggregator);
daggy_core_->connectAggregator(console_aggregator);
return daggy_core_->prepare();;
}
std::error_code CConsoleDaggy::start()
{
file_thread_.start();
return daggy_core_->start();
}
void CConsoleDaggy::stop()
{
if (need_hard_stop_) {
qWarning() << "HARD STOP";
qApp->exit();
} else {
daggy_core_->stop();
need_hard_stop_ = true;
}
file_thread_.quit();
file_thread_.wait();
}
bool CConsoleDaggy::handleSystemSignal(const int signal)
{
if (signal & DEFAULT_SIGNALS) {
emit interrupt(signal);
return true;
}
return false;
}
const QVector<QString>& CConsoleDaggy::supportedConvertors() const
{
static thread_local QVector<QString> formats = {
"json",
#ifdef YAML_SUPPORT
"yaml"
#endif
};
return formats;
}
DaggySourcesTextTypes CConsoleDaggy::textFormatType(const QString& file_name) const
{
DaggySourcesTextTypes result = Json;
const QString& extension = QFileInfo(file_name).suffix();
if (extension == "yml" || extension == "yaml")
result = Yaml;
return result;
}
bool CConsoleDaggy::isError() const
{
return !error_message_.isEmpty();
}
const QString& CConsoleDaggy::errorMessage() const
{
return error_message_;
}
CConsoleDaggy::Settings CConsoleDaggy::parse() const
{
Settings result;
const QCommandLineOption output_folder_option({"o", "output"},
"Set output folder",
"folder", "");
const QCommandLineOption input_format_option({"f", "format"},
"Source format",
supportedConvertors().join("|"),
supportedConvertors()[0]);
const QCommandLineOption auto_complete_timeout({"t", "timeout"},
"Auto complete timeout",
"time in ms",
0
);
const QCommandLineOption input_from_stdin_option({"i", "stdin"},
"Read data aggregation sources from stdin");
QCommandLineParser command_line_parser;
command_line_parser.addOption(output_folder_option);
command_line_parser.addOption(input_format_option);
command_line_parser.addOption(input_from_stdin_option);
command_line_parser.addOption(auto_complete_timeout);
command_line_parser.addHelpOption();
command_line_parser.addVersionOption();
command_line_parser.addPositionalArgument("file", "data aggregation sources file", "*.yaml|*.yml|*.json");
command_line_parser.process(*qApp);
const QStringList positional_arguments = command_line_parser.positionalArguments();
if (positional_arguments.isEmpty()) {
command_line_parser.showHelp(-1);
}
const QString& source_file_name = positional_arguments.first();
if (command_line_parser.isSet(input_from_stdin_option)) {
result.data_source_text = QTextStream(stdin).readAll();
result.data_sources_name = "stdin";
}
else {
result.data_source_text = getTextFromFile(source_file_name);
result.data_sources_name = QFileInfo(source_file_name).baseName();
}
if (command_line_parser.isSet(output_folder_option))
result.output_folder = command_line_parser.value(output_folder_option);
else
result.output_folder = QString();
if (command_line_parser.isSet(input_format_option)) {
const QString& format = command_line_parser.value(input_format_option);
if (!supportedConvertors().contains(format.toLower()))
{
command_line_parser.showHelp(-1);
} else {
result.data_source_text_type = textFormatType(format);
}
} else {
result.data_source_text_type = textFormatType(source_file_name);
}
if (command_line_parser.isSet(auto_complete_timeout)) {
result.timeout = command_line_parser.value(auto_complete_timeout).toUInt();
}
if (result.output_folder.isEmpty())
result.output_folder = QDir::currentPath();
result.data_source_text = mustache(result.data_source_text, result.output_folder);
return result;
}
daggy::Core* CConsoleDaggy::daggyCore() const
{
return findChild<daggy::Core*>();
}
QCoreApplication* CConsoleDaggy::application() const
{
return qobject_cast<QCoreApplication*>(parent());
}
QString CConsoleDaggy::getTextFromFile(QString file_path) const
{
QString result;
if (!QFileInfo::exists(file_path)) {
file_path = homeFolder() + file_path;
}
QFile source_file(file_path);
if (source_file.open(QIODevice::ReadOnly | QIODevice::Text))
result = source_file.readAll();
else
throw std::invalid_argument(QString("Cann't open %1 file for read: %2")
.arg(file_path, source_file.errorString())
.toStdString());
if (result.isEmpty())
throw std::invalid_argument(QString("%1 file is empty")
.arg(file_path)
.toStdString());
return result;
}
QString CConsoleDaggy::homeFolder() const
{
return QStandardPaths::writableLocation(QStandardPaths::AppDataLocation);
}
QString CConsoleDaggy::mustache(const QString& text, const QString& output_folder) const
{
QProcessEnvironment process_environment = QProcessEnvironment::systemEnvironment();
kainjow::mustache::mustache tmpl(qUtf8Printable(text));
kainjow::mustache::data variables;
for (const auto& key : process_environment.keys()) {
variables.set(qPrintable(QString("env_%1").arg(key)),
qUtf8Printable(process_environment.value(key)));
}
variables.set("output_folder", qUtf8Printable(output_folder));
return QString::fromStdString(tmpl.render(variables));
}
void CConsoleDaggy::onDaggyCoreStateChanged(DaggyStates state)
{
switch (state) {
case DaggyNotStarted:
break;
case DaggyStarted:
break;
case DaggyFinishing:
break;
case DaggyFinished:
qApp->exit();
break;
}
}
| 33.33574 | 127 | 0.668075 | milovidov |
2cf95fa4d1af26fa57d13569b320577a31d79785 | 453 | cpp | C++ | src/armnn/Exceptions.cpp | KevinRodrigues05/armnn_caffe2_parser | c577f2c6a3b4ddb6ba87a882723c53a248afbeba | [
"MIT"
] | 1 | 2019-03-19T08:44:28.000Z | 2019-03-19T08:44:28.000Z | src/armnn/Exceptions.cpp | KevinRodrigues05/armnn_caffe2_parser | c577f2c6a3b4ddb6ba87a882723c53a248afbeba | [
"MIT"
] | null | null | null | src/armnn/Exceptions.cpp | KevinRodrigues05/armnn_caffe2_parser | c577f2c6a3b4ddb6ba87a882723c53a248afbeba | [
"MIT"
] | 1 | 2019-10-11T05:58:56.000Z | 2019-10-11T05:58:56.000Z | //
// Copyright © 2017 Arm Ltd. All rights reserved.
// See LICENSE file in the project root for full license information.
//
#include "armnn/Exceptions.hpp"
#include <string>
namespace armnn
{
Exception::Exception(const std::string& message)
: m_Message(message)
{
}
const char* Exception::what() const noexcept
{
return m_Message.c_str();
}
UnimplementedException::UnimplementedException()
: Exception("Function not yet implemented")
{
}
}
| 16.178571 | 69 | 0.730684 | KevinRodrigues05 |
2cfea314db777fdd1478eddb86659a125232716f | 2,083 | cpp | C++ | tests/nostdlib/llvm_passes/SimplifyCFG/MergeConditionalStores/mergecondstores.cpp | jmorse/dexter | 79cefa890d041dfc927aea2a84737aa704ddd35c | [
"MIT"
] | null | null | null | tests/nostdlib/llvm_passes/SimplifyCFG/MergeConditionalStores/mergecondstores.cpp | jmorse/dexter | 79cefa890d041dfc927aea2a84737aa704ddd35c | [
"MIT"
] | null | null | null | tests/nostdlib/llvm_passes/SimplifyCFG/MergeConditionalStores/mergecondstores.cpp | jmorse/dexter | 79cefa890d041dfc927aea2a84737aa704ddd35c | [
"MIT"
] | null | null | null | // RUN: %dexter
int global = 0;
int
foo(int bar) // DexWatch('bar', 'global')
{
int lolret = 0; // DexWatch('bar', 'global', 'lolret')
if (bar & 1) { // DexWatch('bar', 'global', 'lolret')
bar += 1; // DexUnreachable()
lolret += 1; // DexUnreachable()
} else { // DexWatch('bar', 'global', 'lolret')
global = 2; // DexWatch('bar', 'global', 'lolret')
lolret += 2; // DexWatch('bar', 'global', 'lolret')
} // DexWatch('bar', 'global', 'lolret')
if (bar & 2) { // DexWatch('bar', 'global', 'lolret')
bar += 2; // DexUnreachable()
lolret += 3; // DexUnreachable()
} else { // DexWatch('bar', 'global', 'lolret')
global = 5; // DexWatch('bar', 'global', 'lolret')
lolret += 4; // DexWatch('bar', 'global', 'lolret')
} // DexWatch('bar', 'global', 'lolret')
return lolret; // DexWatch('bar', 'global', 'lolret')
}
int
main()
{
volatile int baz = 4;
int read = baz; // DexWatch('global')
int lolret2 = foo(read); // DexWatch('global', 'read')
return global + lolret2; // DexWatch('global', 'read', 'lolret2')
}
// Here, mergeConditionalStores merges the two accesses to global into one,
// with some kind of select arrangement beforehand. Run in O2, we get a ton
// of backwards steps, stepping over unreachable lines, illegal values for
// lolret, amoungst other things.
// It gets even worse if you just run with opt -mem2reg -simplifycfg.
//
// Reported: https://bugs.llvm.org/show_bug.cgi?id=38756
// As of 2018-10-8, the illegal value is fixed, but we still step on
// unreachable lines.
// DexExpectWatchValue('bar', '4', from_line=1, to_line=50)
// DexExpectWatchValue('lolret', '0', '2', '6', from_line=1, to_line=50)
// DexExpectWatchValue('global', '0', '2', '5', from_line=1, to_line=50)
// DexExpectWatchValue('lolret2', '6', from_line=1, to_line=50)
// DexExpectWatchValue('read', '4', from_line=1, to_line=50)
// DexExpectStepKind('BACKWARD', 0)
// DexExpectStepKind('FUNC', 3)
// DexExpectStepKind('FUNC_EXTERNAL', 0)
| 38.574074 | 75 | 0.606337 | jmorse |
2cffd33eed22de0c010509c4afebb3fbd1612541 | 303 | hpp | C++ | development/CppDB/libCppDb/include/CppDb/ManagerFwd.hpp | AntonPoturaev/CppDB | 034d7feafc438fc585441742472bf4b5ef637eb2 | [
"Unlicense"
] | null | null | null | development/CppDB/libCppDb/include/CppDb/ManagerFwd.hpp | AntonPoturaev/CppDB | 034d7feafc438fc585441742472bf4b5ef637eb2 | [
"Unlicense"
] | null | null | null | development/CppDB/libCppDb/include/CppDb/ManagerFwd.hpp | AntonPoturaev/CppDB | 034d7feafc438fc585441742472bf4b5ef637eb2 | [
"Unlicense"
] | null | null | null | #if !defined(__CPP_ABSTRACT_DATA_BASE_MANAGER_FORWARD_DECLARATION_HPP__)
# define __CPP_ABSTRACT_DATA_BASE_MANAGER_FORWARD_DECLARATION_HPP__
namespace CppAbstractDataBase {
class Manager;
} /// end namespace CppAbstractDataBase
#endif /// !__CPP_ABSTRACT_DATA_BASE_MANAGER_FORWARD_DECLARATION_HPP__
| 33.666667 | 72 | 0.874587 | AntonPoturaev |
fa030575fb7c488e9ebb7f42102a5b68f07ced46 | 101 | cpp | C++ | src/algolib/graphs/vertex.cpp | ref-humbold/AlgoLib_CPlusPlus | 9c39138f4d4cd9a8a7db62a9e7495b63aefe069c | [
"Apache-2.0"
] | null | null | null | src/algolib/graphs/vertex.cpp | ref-humbold/AlgoLib_CPlusPlus | 9c39138f4d4cd9a8a7db62a9e7495b63aefe069c | [
"Apache-2.0"
] | null | null | null | src/algolib/graphs/vertex.cpp | ref-humbold/AlgoLib_CPlusPlus | 9c39138f4d4cd9a8a7db62a9e7495b63aefe069c | [
"Apache-2.0"
] | 1 | 2021-04-05T12:11:38.000Z | 2021-04-05T12:11:38.000Z | /*!
* \file vertex.cpp
* \brief Structure of graph vertex
*/
#include "algolib/graphs/vertex.hpp"
| 16.833333 | 36 | 0.683168 | ref-humbold |
fa07338eccfe31262314f8cc36876a4f175df8c7 | 1,498 | cpp | C++ | code-forces/657 Div 2/C2.cpp | ErickJoestar/competitive-programming | 76afb766dbc18e16315559c863fbff19a955a569 | [
"MIT"
] | 1 | 2020-04-23T00:35:38.000Z | 2020-04-23T00:35:38.000Z | code-forces/657 Div 2/C2.cpp | ErickJoestar/competitive-programming | 76afb766dbc18e16315559c863fbff19a955a569 | [
"MIT"
] | null | null | null | code-forces/657 Div 2/C2.cpp | ErickJoestar/competitive-programming | 76afb766dbc18e16315559c863fbff19a955a569 | [
"MIT"
] | null | null | null | #include <bits/stdc++.h>
#define ENDL '\n'
#define deb(u) cout << #u " : " << (u) << ENDL;
#define deba(alias, u) cout << alias << ": " << (u) << ENDL;
#define debp(u, v) cout << u << " : " << v << ENDL;
#define pb push_back
#define F first
#define S second
#define lli long long
#define pii pair<int, int>
#define pll pair<lli, lli>
#define ALL(a) (a).begin(), (a).end()
#define ALLR(a) (a).rbegin(), (a).rend()
#define FOR(i, a, n) for (int i = (a); i < (n); ++i)
#define FORN(i, a, n) for (int i = (a - 1); i >= n; --i)
#define IO \
ios_base::sync_with_stdio(false); \
cin.tie(0); \
cout.tie(0)
using namespace std;
int main()
{
IO;
int t;
cin >> t;
while (t--)
{
lli n, m;
cin >> n >> m;
pii best = {-1, -1};
vector<lli> v(m);
FOR(i, 0, m)
{
lli a, b;
cin >> a >> b;
v[i] = a;
lli bestVal = best.F + best.S * (n - 1);
lli val;
if (a >= b)
{
lli val = b * n;
if (val > bestVal)
best = {b, b};
}
else
{
lli val = a + b * (n - 1);
if (val > bestVal)
best = {a, b};
}
}
sort(v.rbegin(), v.rend());
lli ans = 0;
for (auto e : v)
{
lli val = best.F + best.S * (n - 1);
if (e * n > val)
{
ans += e;
}
else
break;
n--;
}
if (n > 0)
ans += best.F + best.S * (n - 1);
cout << ans << ENDL;
}
return 0;
} | 20.520548 | 60 | 0.417223 | ErickJoestar |
fa0a00bc000fb4492fa205ca3e76cf85f6117e00 | 1,499 | cpp | C++ | dynamic programming/70. Climbing Stairs.cpp | Constantine-L01/leetcode | 1f1e3a8226fcec036370e75c1d69e823d1323392 | [
"MIT"
] | 1 | 2021-04-08T10:33:48.000Z | 2021-04-08T10:33:48.000Z | dynamic programming/70. Climbing Stairs.cpp | Constantine-L01/leetcode | 1f1e3a8226fcec036370e75c1d69e823d1323392 | [
"MIT"
] | null | null | null | dynamic programming/70. Climbing Stairs.cpp | Constantine-L01/leetcode | 1f1e3a8226fcec036370e75c1d69e823d1323392 | [
"MIT"
] | 1 | 2021-02-23T05:58:58.000Z | 2021-02-23T05:58:58.000Z | You are climbing a staircase. It takes n steps to reach the top.
Each time you can either climb 1 or 2 steps. In how many distinct ways can you climb to the top?
Example 1:
Input: n = 2
Output: 2
Explanation: There are two ways to climb to the top.
1. 1 step + 1 step
2. 2 steps
//better solution with less space used
class Solution {
public:
int climbStairs(int n) {
// initially, the currentstep is first stair, oneStep means the move of climbing the stair, twoStep means the move of moving to right and climbing the stair. 1 for oneStep,
// 0 for twoStep because it is not possible
int oneStepToReachDest = 1;
int twoStepToReachDest = 0;
int currentStep = 0;
// At first iteration, currentStep is 1 because only action oneStep is possible. At second iteration, twoStep = oneStep and oneStep = first iteration's currentStep
for(int i = 1; i <= n; i++) {
currentStep = oneStepToReachDest + twoStepToReachDest;
twoStepToReachDest = oneStepToReachDest;
oneStepToReachDest = currentStep;
}
return currentStep;
}
};
class Solution {
public:
int climbStairs(int n) {
if(n == 1) return 1;
vector<int> steps(n, 0);
steps[0] = 1;
steps[1] = 2;
for(int i = 2; i < n; i++) {
steps[i] = steps[i-1] + steps[i-2];
}
return steps[n-1];
}
};
| 28.826923 | 181 | 0.596398 | Constantine-L01 |
fa0fc5014c590e38f905d7af0ab48bb4b7535324 | 4,083 | hpp | C++ | src/utils/timed_events.hpp | norayr/biboumi | 805671032d25ee6ce09ed75e8a385c04e9563cdd | [
"Zlib"
] | 68 | 2015-01-29T21:07:37.000Z | 2022-03-20T14:48:07.000Z | src/utils/timed_events.hpp | norayr/biboumi | 805671032d25ee6ce09ed75e8a385c04e9563cdd | [
"Zlib"
] | 5 | 2016-10-24T18:34:30.000Z | 2021-08-31T13:30:37.000Z | src/utils/timed_events.hpp | norayr/biboumi | 805671032d25ee6ce09ed75e8a385c04e9563cdd | [
"Zlib"
] | 13 | 2015-12-11T15:19:05.000Z | 2021-08-31T13:24:35.000Z | #pragma once
#include <functional>
#include <string>
#include <chrono>
#include <vector>
using namespace std::literals::chrono_literals;
namespace utils {
static constexpr std::chrono::milliseconds no_timeout = std::chrono::milliseconds(-1);
}
class TimedEventsManager;
/**
* A callback with an associated date.
*/
class TimedEvent
{
friend class TimedEventsManager;
public:
/**
* An event the occurs only once, at the given time_point
*/
explicit TimedEvent(std::chrono::steady_clock::time_point&& time_point,
std::function<void()> callback, std::string name="");
explicit TimedEvent(std::chrono::milliseconds&& duration,
std::function<void()> callback, std::string name="");
explicit TimedEvent(TimedEvent&&) = default;
TimedEvent& operator=(TimedEvent&&) = default;
~TimedEvent() = default;
TimedEvent(const TimedEvent&) = delete;
TimedEvent& operator=(const TimedEvent&) = delete;
/**
* Whether or not this event happens after the other one.
*/
bool is_after(const TimedEvent& other) const;
bool is_after(const std::chrono::steady_clock::time_point& time_point) const;
/**
* Return the duration difference between now and the event time point.
* If the difference would be negative (i.e. the event is expired), the
* returned value is 0 instead. The value cannot then be negative.
*/
std::chrono::milliseconds get_timeout() const;
void execute() const;
const std::string& get_name() const;
private:
/**
* The next time point at which the event is executed.
*/
std::chrono::steady_clock::time_point time_point;
/**
* The function to execute.
*/
std::function<void()> callback;
/**
* Whether or not this events repeats itself until it is destroyed.
*/
bool repeat;
/**
* This value is added to the time_point each time the event is executed,
* if repeat is true. Otherwise it is ignored.
*/
std::chrono::milliseconds repeat_delay;
/**
* A name that is used to identify that event. If you want to find your
* event (for example if you want to cancel it), the name should be
* unique.
*/
std::string name;
};
/**
* A class managing a list of TimedEvents.
* They are sorted, new events can be added, removed, fetch, etc.
*/
class TimedEventsManager
{
public:
~TimedEventsManager() = default;
TimedEventsManager(const TimedEventsManager&) = delete;
TimedEventsManager(TimedEventsManager&&) = delete;
TimedEventsManager& operator=(const TimedEventsManager&) = delete;
TimedEventsManager& operator=(TimedEventsManager&&) = delete;
/**
* Return the unique instance of this class
*/
static TimedEventsManager& instance();
/**
* Add an event to the list of managed events. The list is sorted after
* this call.
*/
void add_event(TimedEvent&& event);
/**
* Returns the duration, in milliseconds, between now and the next
* available event. If the event is already expired (the duration is
* negative), 0 is returned instead (as in “it's not too late, execute it
* now”)
* Returns a negative value if no event is available.
*/
std::chrono::milliseconds get_timeout() const;
/**
* Execute all the expired events (if their expiration time is exactly
* now, or before now). The event is then removed from the list. If the
* event does repeat, its expiration time is updated and it is reinserted
* in the list at the correct position.
* Returns the number of executed events.
*/
std::size_t execute_expired_events();
/**
* Remove (and thus cancel) all the timed events with the given name.
* Returns the number of canceled events.
*/
std::size_t cancel(const std::string& name);
/**
* Return the number of managed events.
*/
std::size_t size() const;
/**
* Return a pointer to the first event with the given name. If none
* is found, returns nullptr.
*/
const TimedEvent* find_event(const std::string& name) const;
private:
std::vector<TimedEvent> events;
explicit TimedEventsManager() = default;
};
| 29.586957 | 86 | 0.690914 | norayr |
fa14c0cd63a0c25a089f5434f3573441a843f9f6 | 362 | cpp | C++ | A/1031.cpp | chenjiajia9411/PATest | 061c961f5d7bf7b23c3a1b70d3d443cb57263700 | [
"Apache-2.0"
] | 1 | 2017-11-24T15:06:29.000Z | 2017-11-24T15:06:29.000Z | A/1031.cpp | chenjiajia9411/PAT | 061c961f5d7bf7b23c3a1b70d3d443cb57263700 | [
"Apache-2.0"
] | null | null | null | A/1031.cpp | chenjiajia9411/PAT | 061c961f5d7bf7b23c3a1b70d3d443cb57263700 | [
"Apache-2.0"
] | null | null | null | #include <iostream>
using namespace std;
int main()
{
string input;
cin>>input;
int is = input.size();
int n = (is + 2)/3;
for(int i = 0;i < n - 1;i++)
{
cout<<input.front();
input.erase(0,1);
for(int j = 0;j < (is - 2*n);j++) cout<<" ";
cout<<input.back()<<"\n";
input.pop_back();
}
cout<<input<<endl;
}
| 19.052632 | 52 | 0.486188 | chenjiajia9411 |
fa17a23c3ce2ce020cd09e3414631fa3e31da150 | 4,213 | cpp | C++ | utilities/msmonitor/gui/QMSMFormHeatmapAbstract.cpp | akiml/ampehre | 383a863442574ea2e6a6ac853a9b99e153daeccf | [
"BSD-2-Clause"
] | 3 | 2016-01-20T13:41:52.000Z | 2018-04-10T17:50:49.000Z | utilities/msmonitor/gui/QMSMFormHeatmapAbstract.cpp | akiml/ampehre | 383a863442574ea2e6a6ac853a9b99e153daeccf | [
"BSD-2-Clause"
] | null | null | null | utilities/msmonitor/gui/QMSMFormHeatmapAbstract.cpp | akiml/ampehre | 383a863442574ea2e6a6ac853a9b99e153daeccf | [
"BSD-2-Clause"
] | null | null | null | /*
* QMSMFormHeatmapAbstract.cpp
*
* Copyright (C) 2015, Achim Lösch <achim.loesch@upb.de>, Christoph Knorr <cknorr@mail.uni-paderborn.de>
* All rights reserved.
*
* This software may be modified and distributed under the terms
* of the BSD license. See the LICENSE file for details.
*
* encoding: UTF-8
* tab size: 4
*
* author: Christoph Knorr (cknorr@mail.uni-paderborn.de)
* created: 01/27/16
* version: 0.7.3 - add heatmaps to msmonitor and the enum ipmi_timeout_setting in libmeasure
*/
#include "QMSMFormHeatmapAbstract.hpp"
namespace Ui {
uint32_t QMSMFormHeatmapAbstract::sNumberOfImages = 0;
QMSMFormHeatmapAbstract::QMSMFormHeatmapAbstract(QWidget *pParent, NData::CDataHandler* pDataHandler) :
QMdiSubWindow(pParent),
FormHeatmap(),
mpFormHeatmapAbstract(new QWidget(pParent)),
mpDataHandler(pDataHandler),
mTimer(mpDataHandler->getSettings().mGUIRefreshRate, this),
mHeatmaps(),
mCurrentX(0),
mIndexCurrentX(0)
{
//setAttribute(Qt::WA_DeleteOnClose);
setWindowFlags(Qt::CustomizeWindowHint | Qt::WindowCloseButtonHint | Qt::WindowMinimizeButtonHint);
setupUi(mpFormHeatmapAbstract);
setWidget(mpFormHeatmapAbstract);
createActions();
}
QMSMFormHeatmapAbstract::~QMSMFormHeatmapAbstract(void) {
for(std::vector<Ui::QMSMHeatmap*>::iterator it = mHeatmaps.begin(); it != mHeatmaps.end(); ++it) {
delete (*it);
}
delete mpFormHeatmapAbstract;
}
void QMSMFormHeatmapAbstract::createActions(void) {
connect(pushButtonOK, SIGNAL(clicked(bool)), this, SLOT(close()));
connect(pushButtonSave, SIGNAL(clicked(bool)), this, SLOT(saveImage()));
connect(this, SIGNAL(signalRefreshGui(void)), this, SLOT(slotRefreshGui()));
}
QwtText QMSMFormHeatmapAbstract::createTitle(QString title) {
QwtText qTitle(title);
qTitle.setFont(QFont("Helvetica", 12));
return qTitle;
}
void QMSMFormHeatmapAbstract::updateCurrentX(void) {
uint32_t bufferedSamples = ((mpDataHandler->getSettings().mTimeToBufferData - mpDataHandler->getSettings().mTimeToShowData) /
mpDataHandler->getSettings().mDataSamplingRate)-1;
uint32_t showSamples = (mpDataHandler->getSettings().mTimeToShowData / mpDataHandler->getSettings().mDataSamplingRate) - 1;
double *x = mpDataHandler->getMeasurement().mpX->getDataPtr() + bufferedSamples;
//shift x axis every 10 s
if(x[showSamples] - mCurrentX > 10) {
mCurrentX += 10;
}
//reset x axis if necessary
if(x[showSamples] < mCurrentX) {
mCurrentX = 0;
}
//search the index corresponding to mCurrentX
mIndexCurrentX = 0;
for (int i = showSamples; i >= 0; i--) {
if(x[i] <= (mCurrentX + ((double) mpDataHandler->getSettings().mDataSamplingRate/1000/3))){
mIndexCurrentX = i;
break;
}
}
}
void QMSMFormHeatmapAbstract::close(void) {
hide();
}
void QMSMFormHeatmapAbstract::closeEvent(QCloseEvent *pEvent) {
hide();
}
bool QMSMFormHeatmapAbstract::event(QEvent *pEvent) {
if (pEvent->type() == QEvent::ToolTip) {
return true;
}
return QMdiSubWindow::event(pEvent);
}
void QMSMFormHeatmapAbstract::refreshGui(void) {
emit signalRefreshGui();
}
void QMSMFormHeatmapAbstract::slotRefreshGui(void) {
if(isVisible()) {
setupHeatmaps();
for(std::vector<Ui::QMSMHeatmap*>::iterator it = mHeatmaps.begin(); it != mHeatmaps.end(); ++it) {
(*it)->refresh();
}
} else {
updateCurrentX();
}
}
void QMSMFormHeatmapAbstract::saveImage(void) {
//TODO needs to be implemented
}
void QMSMFormHeatmapAbstract::startTimer(void) {
mTimer.startTimer();
}
void QMSMFormHeatmapAbstract::stopTimer(void) {
mTimer.stopTimer();
}
void QMSMFormHeatmapAbstract::joinTimer(void) {
mTimer.joinTimer();
}
QMSMHeatmap* QMSMFormHeatmapAbstract::addHeatmap(const QString &title) {
Ui::QMSMHeatmap *heatmap = new QMSMHeatmap(this);
heatmap->setObjectName(title);
heatmap->setFrameShape(QFrame::NoFrame);
heatmap->setFrameShadow(QFrame::Raised);
heatmap->setTitle(title.toStdString());
verticalLayoutMeasurement->insertWidget(mHeatmaps.size(), heatmap);
mHeatmaps.push_back(heatmap);
resize(650, 50 + 110 * mHeatmaps.size());
return heatmap;
}
}
| 27.357143 | 127 | 0.711844 | akiml |
fa18a3ae82592268a345f287ee0a23fec1355601 | 670 | hpp | C++ | source/Utilities/Point2D.hpp | hadryansalles/ray-tracing-from-the-ground-up | 4ca02fca2cdd458767b4ab3df15b6cd20cb1f413 | [
"MIT"
] | 5 | 2021-09-24T12:22:08.000Z | 2022-03-23T06:54:02.000Z | source/Utilities/Point2D.hpp | hadryans/ray-tracing-from-the-ground-up | 4ca02fca2cdd458767b4ab3df15b6cd20cb1f413 | [
"MIT"
] | null | null | null | source/Utilities/Point2D.hpp | hadryans/ray-tracing-from-the-ground-up | 4ca02fca2cdd458767b4ab3df15b6cd20cb1f413 | [
"MIT"
] | 5 | 2021-08-14T22:26:11.000Z | 2022-03-04T09:13:39.000Z | #pragma once
#include "Matrix.hpp"
#include <math.h>
class Point2D {
public:
double x, y;
Point2D();
Point2D(const double a);
Point2D(const double a, const double b);
Point2D(const Point2D &p);
~Point2D();
Point2D& operator= (const Point2D& p); // assignment operator
Point2D operator- (void) const; // unary minus
Point2D operator* (const double a) const; // multiplication by a double on the right
double d_squared(const Point2D& p) const; // square of distance bertween two points
double distance(const Point2D& p) const; // distance bewteen two points
};
Point2D operator* (double a, const Point2D& p); | 27.916667 | 89 | 0.671642 | hadryansalles |
fa1e92d86a4cfe6bcc31d1ffa3b36128579a55c9 | 1,401 | cpp | C++ | Stack & Heap/316. Remove Duplicate Letters/main.cpp | Minecodecraft/LeetCode-Minecode | 185fd6efe88d8ffcad94e581915c41502a0361a0 | [
"MIT"
] | 1 | 2021-11-19T19:58:33.000Z | 2021-11-19T19:58:33.000Z | Stack & Heap/316. Remove Duplicate Letters/main.cpp | Minecodecraft/LeetCode-Minecode | 185fd6efe88d8ffcad94e581915c41502a0361a0 | [
"MIT"
] | null | null | null | Stack & Heap/316. Remove Duplicate Letters/main.cpp | Minecodecraft/LeetCode-Minecode | 185fd6efe88d8ffcad94e581915c41502a0361a0 | [
"MIT"
] | 2 | 2021-11-26T12:47:27.000Z | 2022-01-13T16:14:46.000Z | //
// main.cpp
// 316. Remove Duplicate Letters
//
// Created by 边俊林 on 2019/10/3.
// Copyright © 2019 Minecode.Link. All rights reserved.
//
/* ------------------------------------------------------ *\
https://leetcode.com/problems/remove-duplicate-letters/
\* ------------------------------------------------------ */
#include <map>
#include <set>
#include <queue>
#include <string>
#include <stack>
#include <vector>
#include <cstdio>
#include <numeric>
#include <cstdlib>
#include <utility>
#include <iostream>
#include <algorithm>
#include <unordered_map>
#include <unordered_set>
using namespace std;
/// Solution:
//
class Solution {
public:
string removeDuplicateLetters(string s) {
vector<int> cnt (26, 0);
for (char &ch: s) cnt[ch-'a']++;
int idx = 0;
for (int i = 0; i < s.length(); ++i) {
if (s[i] < s[idx]) idx = i;
if (--cnt[s[i] - 'a'] == 0) break;
}
if (s.empty())
return "";
else {
string buffer = s.substr(idx+1);
buffer.erase(remove(buffer.begin(), buffer.end(), s[idx]), buffer.end());
return s[idx] + removeDuplicateLetters(buffer);
}
}
};
int main() {
Solution sol = Solution();
string s = "bcabc";
// string s = "cbacdcbc";
string res = sol.removeDuplicateLetters(s);
cout << res << endl;
return 0;
}
| 23.35 | 85 | 0.522484 | Minecodecraft |
fa20d8ef350e7bfb6e8eba60dd1ea9396c022859 | 5,352 | cc | C++ | utils/clock_cal.cc | fxd0h/moteus | e66ba9fb54ad0482a0bdf9a32420f5bf18677216 | [
"Apache-2.0"
] | 347 | 2019-03-16T12:00:35.000Z | 2022-03-29T05:19:42.000Z | utils/clock_cal.cc | fxd0h/moteus | e66ba9fb54ad0482a0bdf9a32420f5bf18677216 | [
"Apache-2.0"
] | 22 | 2020-04-20T20:37:12.000Z | 2022-03-16T18:13:59.000Z | utils/clock_cal.cc | fxd0h/moteus | e66ba9fb54ad0482a0bdf9a32420f5bf18677216 | [
"Apache-2.0"
] | 127 | 2019-03-23T16:06:18.000Z | 2022-03-28T21:33:27.000Z | // Copyright 2020 Josh Pieper, jjp@pobox.com.
//
// Licensed under the Apache License, Version 2.0 (the "License");
// you may not use this file except in compliance with the License.
// You may obtain a copy of the License at
//
// http://www.apache.org/licenses/LICENSE-2.0
//
// Unless required by applicable law or agreed to in writing, software
// distributed under the License is distributed on an "AS IS" BASIS,
// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
// See the License for the specific language governing permissions and
// limitations under the License.
#include <functional>
#include <boost/asio.hpp>
#include <boost/date_time/posix_time/posix_time.hpp>
#include <fmt/format.h>
#include <fmt/ostream.h>
#include "mjlib/base/clipp.h"
#include "mjlib/base/clipp_archive.h"
#include "mjlib/base/fail.h"
#include "mjlib/base/system_error.h"
#include "mjlib/base/time_conversions.h"
#include "mjlib/io/now.h"
#include "mjlib/io/selector.h"
#include "mjlib/io/stream_factory.h"
#include "mjlib/multiplex/asio_client.h"
#include "mjlib/multiplex/stream_asio_client_builder.h"
#include "utils/line_reader.h"
namespace pl = std::placeholders;
namespace {
struct Options {
std::string type;
int target = 1;
mjlib::io::StreamFactory::Options stream;
};
class ClockCal {
public:
ClockCal(const boost::asio::any_io_executor& executor,
mjlib::io::Selector<mjlib::multiplex::AsioClient>* selector,
const Options& options)
: executor_(executor),
selector_(selector),
options_(options),
factory_(executor_) {
}
void Start() {
if (options_.type == "stream") {
factory_.AsyncCreate(options_.stream,
std::bind(&ClockCal::HandleStream, this, pl::_1, pl::_2));
} else if (options_.type == "multiplex") {
selector_->AsyncStart(
std::bind(&ClockCal::HandleClient, this, pl::_1));
} else {
throw mjlib::base::system_error::einval("unknown type: " + options_.type);
}
}
private:
void HandleClient(const mjlib::base::error_code& ec) {
mjlib::base::FailIf(ec);
HandleStream(ec, selector_->selected()->MakeTunnel(options_.target, 1));
}
void HandleStream(const mjlib::base::error_code& ec, mjlib::io::SharedStream stream) {
mjlib::base::FailIf(ec);
stream_ = stream;
reader_.emplace(stream.get());
boost::asio::co_spawn(
executor_,
std::bind(&ClockCal::Calibrate, this),
[](std::exception_ptr ptr) {
if (ptr) {
std::rethrow_exception(ptr);
}
std::exit(0);
});
}
boost::asio::awaitable<void> Write(const std::string& message) {
co_await boost::asio::async_write(
*stream_,
boost::asio::buffer(message + "\n"),
boost::asio::use_awaitable);
co_return;
}
boost::asio::awaitable<void> Sleep(double seconds) {
boost::asio::deadline_timer timer(executor_);
timer.expires_from_now(mjlib::base::ConvertSecondsToDuration(seconds));
co_await timer.async_wait(boost::asio::use_awaitable);
}
boost::asio::awaitable<void> Calibrate() {
boost::posix_time::ptime last_time;
int64_t last_us = 0;
for (int i = 0; i < 5; i++) {
co_await Write("clock us");
const auto us = std::stoul((co_await reader_->ReadLine()).value());
const auto timestamp = mjlib::io::Now(executor_.context());
const double us_per_s = [&]() {
if (last_time.is_special()) { return 1000000.0; }
return (static_cast<double>(us - last_us) /
mjlib::base::ConvertDurationToSeconds(timestamp - last_time));
}();
fmt::print("{} {} {:.0f}\n", us, timestamp, us_per_s);
last_time = timestamp;
last_us = us;
co_await Sleep(1.0);
}
co_return;
}
boost::asio::any_io_executor executor_;
mjlib::io::Selector<mjlib::multiplex::AsioClient>* const selector_;
const Options options_;
mjlib::io::StreamFactory factory_;
mjlib::io::SharedStream stream_;
std::optional<moteus::tool::LineReader> reader_;
};
}
int main(int argc, char** argv) {
boost::asio::io_context context;
mjlib::io::Selector<mjlib::multiplex::AsioClient> default_client_selector{
context.get_executor(), "client_type"};
mjlib::multiplex::StreamAsioClientBuilder::Options default_stream_options;
default_stream_options.stream.type = mjlib::io::StreamFactory::Type::kSerial;
default_stream_options.stream.serial_port = "/dev/fdcanusb";
default_stream_options.stream.serial_baud = 3000000;
default_client_selector.Register<mjlib::multiplex::StreamAsioClientBuilder>(
"stream", default_stream_options);
default_client_selector.set_default("stream");
Options options;
auto group = clipp::group(
clipp::option("type") & clipp::value("TYPE", options.type).doc(
"one of [stream,multiplex]"),
clipp::option("target", "t") & clipp::value("ID", options.target)
);
group.merge(mjlib::base::ClippArchive("stream.").Accept(&options.stream).release());
group.merge(clipp::with_prefix("client.", default_client_selector.program_options()));
mjlib::base::ClippParse(argc, argv, group);
ClockCal app(context.get_executor(), &default_client_selector, options);
app.Start();
context.run();
return 0;
}
| 31.298246 | 88 | 0.670777 | fxd0h |
fa20f0977a131beeb5cb7df5031aeb76a3af4148 | 1,173 | hpp | C++ | Server Lib/Game Server/PANGYA_DB/cmd_update_quest_user.hpp | CCasusensa/SuperSS-Dev | 6c6253b0a56bce5dad150c807a9bbf310e8ff61b | [
"MIT"
] | 23 | 2021-10-31T00:20:21.000Z | 2022-03-26T07:24:40.000Z | Server Lib/Game Server/PANGYA_DB/cmd_update_quest_user.hpp | CCasusensa/SuperSS-Dev | 6c6253b0a56bce5dad150c807a9bbf310e8ff61b | [
"MIT"
] | 5 | 2021-10-31T18:44:51.000Z | 2022-03-25T18:04:26.000Z | Server Lib/Game Server/PANGYA_DB/cmd_update_quest_user.hpp | CCasusensa/SuperSS-Dev | 6c6253b0a56bce5dad150c807a9bbf310e8ff61b | [
"MIT"
] | 18 | 2021-10-20T02:31:56.000Z | 2022-02-01T11:44:36.000Z | // Arquivo cmd_update_quest_user.hpp
// Criado em 14/04/2018 as 15:57 por Acrisio
// Defini��o da classe CmdUpdateQuestUser
#pragma once
#ifndef _STDA_CMD_UPDATE_QUEST_USER_HPP
#define _STDA_CMD_UPDATE_QUEST_USER_HPP
#include "../../Projeto IOCP/PANGYA_DB/pangya_db.h"
#include "../TYPE/pangya_game_st.h"
namespace stdA {
class CmdUpdateQuestUser : public pangya_db {
public:
explicit CmdUpdateQuestUser(bool _waiter = false);
CmdUpdateQuestUser(uint32_t _uid, QuestStuffInfo& _qsi, bool _waiter = false);
virtual ~CmdUpdateQuestUser();
uint32_t getUID();
void setUID(uint32_t _uid);
QuestStuffInfo& getInfo();
void setInfo(QuestStuffInfo& _qsi);
protected:
void lineResult(result_set::ctx_res* _result, uint32_t _index_result) override;
response* prepareConsulta(database& _db) override;
// get Class name
virtual std::string _getName() override { return "CmdUpdateQuestUser"; };
virtual std::wstring _wgetName() override { return L"CmdUpdateQuestUser"; };
private:
uint32_t m_uid;
QuestStuffInfo m_qsi;
const char* m_szConsulta = "pangya.ProcUpdateQuestUser";
};
}
#endif // !_STDA_CMD_UPDATE_QUEST_USER_HPP
| 27.928571 | 82 | 0.752771 | CCasusensa |
fa22c48336169f2ac310c7fbd1dcb72053918c35 | 1,390 | cc | C++ | Modules/Numerics/src/Point.cc | lisurui6/MIRTK | 5a06041102d7205b5aac147ff768df6e9415bd03 | [
"Apache-2.0"
] | 146 | 2016-01-15T15:02:02.000Z | 2022-03-24T01:43:30.000Z | Modules/Numerics/src/Point.cc | aria-rui/MIRTK | 877917b1b3ec9e602f7395dbbb1270e4334fc311 | [
"Apache-2.0"
] | 196 | 2016-01-15T16:45:58.000Z | 2022-03-24T01:06:53.000Z | Modules/Numerics/src/Point.cc | aria-rui/MIRTK | 877917b1b3ec9e602f7395dbbb1270e4334fc311 | [
"Apache-2.0"
] | 72 | 2016-01-15T15:04:32.000Z | 2022-03-25T11:05:16.000Z | /*
* Medical Image Registration ToolKit (MIRTK)
*
* Copyright 2008-2016 Imperial College London
* Copyright 2008-2015 Daniel Rueckert, Julia Schnabel
* Copyright 2016 Andreas Schuh
*
* 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 <istream>
#include <ostream>
#include "mirtk/Point.h"
namespace mirtk {
// -----------------------------------------------------------------------------
ostream &operator <<(ostream &o, const Point &p)
{
return o << p._x << " " << p._y << " " << p._z;
}
// -----------------------------------------------------------------------------
istream &operator >>(istream &i, Point &p)
{
char c = i.peek();
while ((c == ',') || (c == ' ') || (c == '\t') || (c == '\n')) {
i.get();
if (!i.eof()) {
c = i.peek();
} else {
break;
}
}
return i >> p._x >> p._y >> p._z;
}
} // namespace mirtk
| 26.226415 | 80 | 0.556835 | lisurui6 |
fa2380682598c79bfaf0c3f3da04682a49f4ac03 | 10,020 | cpp | C++ | Modular Server/modulserv/my_parser.cpp | jancura/modular-server | ef97e7147edb33614d986a514c236f3dd020b513 | [
"MIT"
] | 1 | 2018-12-30T11:17:22.000Z | 2018-12-30T11:17:22.000Z | Modular Server/modulserv/my_parser.cpp | jancura/modular-server | ef97e7147edb33614d986a514c236f3dd020b513 | [
"MIT"
] | null | null | null | Modular Server/modulserv/my_parser.cpp | jancura/modular-server | ef97e7147edb33614d986a514c236f3dd020b513 | [
"MIT"
] | null | null | null | //20.05.2005 - implementacia my_parser.cpp
/*Pali Jancura - to jest ja :)
* 26.05.2005
* - ping prerobeny do dll
* - dalsie zmeny, pridany ping, este predtym bol pridany broadcast
* 20.05.2005
* add: bool my_parser()
*/
#include "stdafx.h"
#include "my_parser.h"
#include "server_thread.h"
#include "broadcast_thread.h"
#include <string>
#include <cctype>
#include <winsock.h>
#include <iostream>
#include <fstream>
#define SPRAVA_SIZE 20
using namespace std;
typedef string::size_type str_size;
typedef size_t (*broadadd_PTR)(char*, size_t, size_t);
typedef size_t (*broadcast_PTR)(char*, size_t);
typedef int (*GetTimeout_PTR)();
typedef bool (*ping_PTR)(struct in_addr, struct in_addr, DWORD, char *);
typedef bool (*newping_PTR)();
broadadd_PTR broadcastadd = NULL;
broadcast_PTR GetBroadcastMsg = NULL;
GetTimeout_PTR GetTimeOutBroadcast= NULL;
ping_PTR ping = NULL;
newping_PTR new_ping = NULL;
//cesta k suboru pre logovanie pingu
char PingLog[MAX_PATH];
/******************************************************************************
* string word(const string& s, str_size& i)
* - zo stringu s, vrati jedno slovo od pozicie i, a pozmeni i, tak ze ukazuje
* na zaciatok noveho slova alebo koniec stringu s, za predpokladu, ze kazde
* slovo je oddelene prave jednym bielym znakom
* - v inom pripade vrati prazdny retazec
* - v configu pouzivam '=',tento znak zatial preskakujem,mozne vyuzitie neskor
******************************************************************************/
string word(const string& s, str_size& i)
{
string vysledok = "";
str_size j;
if(i < s.size()){
j = i;
//dokial nenarazim na biely znak alebo koniec stringu
while(j != s.size() && !isspace(s[j])) ++j;
//bol tam aspon jeden nebiely znak
if(i != j){
vysledok = s.substr(i, j - i);
i = ++j; //posuniem sa dalej za biely znak
}
//preskocim znak '='
if(vysledok == "=") vysledok = word(s, i);
}
return vysledok;
}//string word(string& s, str_size& i)
/******************************************************************************
* bool my_parser(const string& conf)
* - rozobera konfiguracny string pomocou funkcie word a nastavi konfiguraciu
******************************************************************************/
bool my_parser(const string& conf)
{
CLog::WriteLog("parser" , "my_parser(): begin");
wchar_t pwcLibrary[MAX_PATH];
char * sprava = new char[SPRAVA_SIZE]; int iNewSize=0;
string spr = strcpy(sprava, "modular_server 1.0");
str_size i = 0;
string option;
int port1, port2;
DWORD timeOut = 0; DWORD timeOutBroad = 0; //default hodnoty
struct in_addr localhost, subnetmask, broadcastIP;
bool old = true, pingOLD = false, pingNEW = false; //pre broadcast a ping
bool bBroadcast=false;
while(i < conf.size()){
option = word(conf, i);
if(option == "port"){
option = word(conf, i);
if(option == "telnet"){
option = word(conf, i);
port1 = htons(atoi(option.c_str()));
}else{
if(option == "broadcast"){
option = word(conf, i);
port2 = htons(atoi(option.c_str()));
}else{
CLog::WriteLog("parser", "my_parser(): Chyba v nastaveni portov!");
return false;
}
}
}else{
if(option == "localhost"){
option = word(conf, i);
localhost.s_addr = inet_addr(option.c_str());
}else{
if(option == "subnetmask"){
option = word(conf, i);
subnetmask.s_addr = inet_addr(option.c_str());
}else{
if(option == "broadcast"){
option = word(conf, i);
if(option == "Default"){
bBroadcast = true;
option = word(conf, i);
timeOutBroad = atoi(option.c_str());
if(timeOutBroad<=0) {
CLog::WriteLog("parser", "my_parser(): Chyba v nastaveni: Nenastaveny timeout broadcastu!");
return false;
}
}else{
if(option == "NEW"){
bBroadcast = true;
swprintf(pwcLibrary, L"%sLibrary\\broadcast.dll", pwcProgramFolder);
HINSTANCE hDll = LoadLibrary(pwcLibrary);
if(hDll == NULL){
CLog::WriteLog("parser", "my_parser(): broadcast.dll nie je v library");
bBroadcast = false;
}else{
GetBroadcastMsg = (broadcast_PTR)GetProcAddress(hDll,"GetBroadcastMessage");
GetTimeOutBroadcast = (GetTimeout_PTR)GetProcAddress(hDll,"GetTimeOut");
if(GetBroadcastMsg == NULL || GetTimeOutBroadcast==NULL){
CLog::WriteLog("parser", "my_parser(): Nenacitana funkcia z broadcast.dll");
bBroadcast = false;
}else{
CLog::WriteLog("parser", "my_parser(): GetBroadcastMessage a GetTimeOutBroadcast uspesne importovane!");
iNewSize = GetBroadcastMsg(sprava, SPRAVA_SIZE);
if(iNewSize){
delete [] sprava; sprava = new char [iNewSize+1];
GetBroadcastMsg(sprava, iNewSize);
spr = sprava;
}else spr = sprava;
timeOutBroad = GetTimeOutBroadcast();
CLog::WriteLog("parser", "my_parser(): GetBroadcastMessage a GetTimeOutBroadcast uspesne prebehli!");
}
}//if(hDll == NULL)
}else{
broadcastIP.s_addr = inet_addr(option.c_str());
}}
}else{
if(option == "broadcastadd"){
if(!bBroadcast)
CLog::WriteLog("parser", "my_parser(): Broadcastadd neprebehne: Zle nadefinovany broadcast v dll!");
else {
swprintf(pwcLibrary, L"%sLibrary\\broadcastadd.dll", pwcProgramFolder);
HINSTANCE hDll = LoadLibrary(pwcLibrary);
if(hDll == NULL){
CLog::WriteLog("parser", "my_parser(): broadcastadd.dll nie v library!");
}else{
broadcastadd=(broadadd_PTR)GetProcAddress(hDll,"broadcastadd");
if(broadcastadd == NULL){
CLog::WriteLog("parser", "my_parser(): Nenacitana funkcia z broadcastadd.dll!");
}else{
CLog::WriteLog("parser", "my_parser(): Broadcastadd uspesne importovany!");
if(iNewSize)
iNewSize = broadcastadd(sprava, iNewSize, spr.size());
else
iNewSize = broadcastadd(sprava, SPRAVA_SIZE, spr.size());
if(iNewSize){
char * buf = new char[iNewSize+1];
strcpy(buf, sprava);
delete [] sprava; sprava = NULL;
broadcastadd(buf, iNewSize, spr.size());
spr = buf;
delete [] buf;
}else spr = sprava;
}
}//if(hDll == NULL)
}
}else{
if(option == "ping"){
option = word(conf, i);
if(option == "Default"){
option = word(conf, i);
timeOut = atoi(option.c_str());
if(timeOut<=0) {
CLog::WriteLog("parser", "my_parser(): Chyba v nastaveni: Nenastaveny timeout pingu!");
return false;
}
pingOLD = true;
}else
if(option == "NEW")
pingNEW = true;
}else{
CLog::WriteLog("parser", "my_parser(): Chyba v nastaveni");
return false;
}}}}}}
}//while
//broadcast
CLog::WriteLog("parser", "my_parser(): Inicializacia broadcastu!");
sendBroadcastThread * sendBroad = NULL;
recvBroadcastThread * recvBroad = NULL;
if(bBroadcast){
recvBroad = new recvBroadcastThread(port2,localhost);
sendBroad = new sendBroadcastThread(broadcastIP,port2,spr,timeOutBroad);
}else{
}
if(sprava) delete [] sprava;
//opingujem siet
if(pingOLD){
swprintf(pwcLibrary, L"%sLibrary\\ping.dll", pwcProgramFolder);
HINSTANCE hDll = LoadLibrary(pwcLibrary);
if(hDll == NULL){
CLog::WriteLog("parser", "my_parser(): ping.dll nie v library");
}else{
ping = (ping_PTR)GetProcAddress(hDll,"ping");
if(ping == NULL){
CLog::WriteLog("parser", "my_parser(): Nenacitana funkcia z ping.dll");
}else{
CLog::WriteLog("parser", "my_parser(): ping uspesne importovany!");
sprintf(PingLog, "%sLog\\ping.log", pcProgramFolder);
if ( ping(localhost, subnetmask, timeOut, PingLog) )
CLog::WriteLog("parser", "my_parser(): Ping celej siete uspesne prebehol");
else
CLog::WriteLog("parser", "my_parser(): Chyba v importovanom ping!");
}
}//if(hDll == NULL)
}
if(pingNEW){
swprintf(pwcLibrary, L"%sLibrary\\new_ping.dll", pwcProgramFolder);
HINSTANCE hDll = LoadLibrary(pwcLibrary);
if(hDll == NULL){
CLog::WriteLog("parser", "my_parser(): new_ping.dll nie v library");
}else{
new_ping = (newping_PTR)GetProcAddress(hDll,"ping");
if(new_ping == NULL){
CLog::WriteLog("parser", "my_parser(): Nenacitana funkcia z new_ping.dll");
}else{
CLog::WriteLog("parser", "my_parser(): new_ping uspesne importovany!");
if(new_ping())
CLog::WriteLog("parser", "my_parser(): Imporotvany new_ping uspesne prebehol");
else
CLog::WriteLog("parser", "my_parser(): Chyba v importovanom new_ping!");
}
}//if(hDll == NULL)
}
//instacionujem triedu pre klientov
//spustim vlakno pre prijem spojeni na zadanom porte (samotny server)
CLog::WriteLog("parser", "my_parser(): Allocing listenThread!");
listenThread * listen = new listenThread(port1, localhost, &Clients);
CLog::WriteLog("parser", "my_parser(): Alloced listenThread!");
//instacionujem triedu pre spracovanie fronty
CLog::WriteLog("parser", "my_parser(): Allocing ProcessQueqe!");
CProcessQueqe* ProcessQueqe = new CProcessQueqe(recvBroad, sendBroad, listen, &Clients);
CLog::WriteLog("parser", "my_parser(): Alloced ProcessQueqe!");
//vytvorim zamky pre vlakna pre pristup ku globalnym premennym
try{
CLog::WriteLog("parser", "my_parser(): ProcessQueqe & listen starting!");
ProcessQueqe->start();
CLog::WriteLog("parser", "my_parser(): ProcessQueqe started!");
listen->start();
CLog::WriteLog("parser", "my_parser(): listen started!");
//zacnem vysielat a prijmat broadcast
if(recvBroad) recvBroad->start();
if(sendBroad) sendBroad->start();
CLog::WriteLog("parser", "my_parser(): listen stoping!");
listen->stop();
CLog::WriteLog("parser", "my_parser(): listen stoped!");
if(recvBroad){
recvBroad->stop();
delete recvBroad;
CLog::WriteLog("parser", "parser: Uspesne zastaveny recvBroad");
}
if(sendBroad){
sendBroad->stop();
delete sendBroad;
CLog::WriteLog("parser","parser: Uspesne zastaveny sendBroad");
}
ProcessQueqe->stop();
}catch (ThreadException ex) {
CLog::WriteLog("parser", (ex.getMessage()).c_str());
}
delete listen;
delete ProcessQueqe;
return true;
} | 31.809524 | 110 | 0.646607 | jancura |
fa267557bc33f4869f70e21dfcbf5301c9d0d38c | 186 | hpp | C++ | util.hpp | Mnkai/libzku_unitconv | 04951b54c255001bceeb484e5ff5754828dfda38 | [
"Apache-2.0"
] | null | null | null | util.hpp | Mnkai/libzku_unitconv | 04951b54c255001bceeb484e5ff5754828dfda38 | [
"Apache-2.0"
] | 2 | 2017-05-29T13:57:39.000Z | 2017-06-05T02:21:42.000Z | util.hpp | Mnkai/libzku_unitconv | 04951b54c255001bceeb484e5ff5754828dfda38 | [
"Apache-2.0"
] | null | null | null | #include <algorithm>
#include <functional>
#include <cctype>
#include <locale>
std::string <rim(std::string &s);
std::string &rtrim(std::string &s);
std::string &trim(std::string &s); | 23.25 | 35 | 0.698925 | Mnkai |
fa28b20e7e464a27ea215c13f2f5b4e81cac8680 | 4,319 | hpp | C++ | esp/platform/espsecurecontext.hpp | miguelvazq/HPCC-Platform | 22ad8e5fcb59626abfd8febecbdfccb1e9fb0aa5 | [
"Apache-2.0"
] | 286 | 2015-01-03T12:45:17.000Z | 2022-03-25T18:12:57.000Z | esp/platform/espsecurecontext.hpp | miguelvazq/HPCC-Platform | 22ad8e5fcb59626abfd8febecbdfccb1e9fb0aa5 | [
"Apache-2.0"
] | 9,034 | 2015-01-02T08:49:19.000Z | 2022-03-31T20:34:44.000Z | esp/platform/espsecurecontext.hpp | cloLN/HPCC-Platform | 42ffb763a1cdcf611d3900831973d0a68e722bbe | [
"Apache-2.0"
] | 208 | 2015-01-02T03:27:28.000Z | 2022-02-11T05:54:52.000Z | /*##############################################################################
HPCC SYSTEMS software Copyright (C) 2016 HPCC Systems®.
Licensed under the Apache License, Version 2.0 (the "License");
you may not use this file except in compliance with the License.
You may obtain a copy of the License at
http://www.apache.org/licenses/LICENSE-2.0
Unless required by applicable law or agreed to in writing, software
distributed under the License is distributed on an "AS IS" BASIS,
WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
See the License for the specific language governing permissions and
limitations under the License.
############################################################################## */
#ifndef ESPSECURECONTEXT_HPP
#define ESPSECURECONTEXT_HPP
#include "jiface.hpp"
#include "tokenserialization.hpp"
class CTxSummary;
// Declares a protocol-independent interface to give security managers read
// access to protocol-dependent data values. Subclasses determine the types
// of data to which they will provide access. Callers are assumed to know
// which data types they may request.
//
// For example, consider an HTTP request. A caller may need access to HTTP
// cookies. In such a case, the caller may call getProtocol() to confirm that
// the supported protocol is "http" and then may assume that a property type
// of "cookie" will be supported.
interface IEspSecureContext : extends IInterface
{
// Return a protocol-specific identifier. Callers may use this value to
// confirm availability of required data types.
virtual const char* getProtocol() const = 0;
// Returns the TxSummary object to be used for a request.
virtual CTxSummary* queryTxSummary() const = 0;
// Fetches a data value based on a given type and name. If the requested
// value exists it is stored in the supplied value buffer and true is
// returned. If the requested value does not exist, the value buffer is
// unchanged and false is returned.
//
// Acceptable values of the 'type' parameter are defined by protocol-
// specific subclasses. E.g., an HTTP specific subclass might support
// cookie data.
//
// Acceptable values of the 'name' parameter are dependent on the caller.
virtual bool getProp(int type, const char* name, StringBuffer& value) = 0;
// Implementation-independent wrapper of the abstract getProp method
// providing convenient access to non-string values. Non-string means
// numeric (including Boolean) values by default, but callers do have
// the option to replace the default deserializer with one capable of
// supporting more complex types.
//
// True is returned if the requested property exists and its value is
// convertible to TValue. False is returned in all other cases. The
// caller may request the conversion result code to understand why a
// request failed.
//
// Template Parameters
// - TValue: a type supported by of TDeserializer
// - TDefault[TValue]: a type from which TValue can be initialized
// - TDeserializer[TokenDeserializer]: a callback function, lambda, or
// functor with signature:
// DeserializationResult (*pfn)(const char*, TValue&)
template <typename TValue, typename TDefault = TValue, class TDeserializer = TokenDeserializer>
bool getProp(int type, const char* name, TValue& value, const TDefault dflt = TDefault(), DeserializationResult* deserializationResult = NULL, TDeserializer& deserializer = TDeserializer());
};
template <typename TValue, typename TDefault, class TDeserializer>
inline bool IEspSecureContext::getProp(int type, const char* name, TValue& value, const TDefault dflt, DeserializationResult* deserializationResult, TDeserializer& deserializer)
{
DeserializationResult result = Deserialization_UNKNOWN;
StringBuffer prop;
bool found = getProp(type, name, prop);
if (found)
{
result = deserializer(prop, value);
found = (Deserialization_SUCCESS == result);
}
if (!found)
{
value = TValue(dflt);
}
if (deserializationResult)
{
*deserializationResult = result;
}
return found;
}
#endif // ESPSECURECONTEXT_HPP
| 41.133333 | 194 | 0.694837 | miguelvazq |
fa2a0a2e3df171051a1eec3a3a731f4b5d59962e | 131,825 | cpp | C++ | src/hotspot/share/jvmci/jvmciCompilerToVM.cpp | siweilxy/openjdkstudy | 8597674ec1d6809faf55cbee1f45f4e9149d670d | [
"Apache-2.0"
] | null | null | null | src/hotspot/share/jvmci/jvmciCompilerToVM.cpp | siweilxy/openjdkstudy | 8597674ec1d6809faf55cbee1f45f4e9149d670d | [
"Apache-2.0"
] | null | null | null | src/hotspot/share/jvmci/jvmciCompilerToVM.cpp | siweilxy/openjdkstudy | 8597674ec1d6809faf55cbee1f45f4e9149d670d | [
"Apache-2.0"
] | null | null | null | /*
* Copyright (c) 2011, 2019, Oracle and/or its affiliates. All rights reserved.
* DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS FILE HEADER.
*
* This code is free software; you can redistribute it and/or modify it
* under the terms of the GNU General Public License version 2 only, as
* published by the Free Software Foundation.
*
* This code 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
* version 2 for more details (a copy is included in the LICENSE file that
* accompanied this code).
*
* You should have received a copy of the GNU General Public License version
* 2 along with this work; if not, write to the Free Software Foundation,
* Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301 USA.
*
* Please contact Oracle, 500 Oracle Parkway, Redwood Shores, CA 94065 USA
* or visit www.oracle.com if you need additional information or have any
* questions.
*/
#include "precompiled.hpp"
#include "classfile/javaClasses.inline.hpp"
#include "classfile/stringTable.hpp"
#include "classfile/symbolTable.hpp"
#include "code/scopeDesc.hpp"
#include "compiler/compileBroker.hpp"
#include "compiler/disassembler.hpp"
#include "interpreter/linkResolver.hpp"
#include "interpreter/bytecodeStream.hpp"
#include "jvmci/jvmciCompilerToVM.hpp"
#include "jvmci/jvmciCodeInstaller.hpp"
#include "jvmci/jvmciRuntime.hpp"
#include "memory/oopFactory.hpp"
#include "memory/universe.hpp"
#include "oops/constantPool.inline.hpp"
#include "oops/method.inline.hpp"
#include "oops/typeArrayOop.inline.hpp"
#include "prims/nativeLookup.hpp"
#include "runtime/deoptimization.hpp"
#include "runtime/fieldDescriptor.inline.hpp"
#include "runtime/frame.inline.hpp"
#include "runtime/interfaceSupport.inline.hpp"
#include "runtime/jniHandles.inline.hpp"
#include "runtime/timerTrace.hpp"
#include "runtime/vframe_hp.hpp"
JVMCIKlassHandle::JVMCIKlassHandle(Thread* thread, Klass* klass) {
_thread = thread;
_klass = klass;
if (klass != NULL) {
_holder = Handle(_thread, klass->klass_holder());
}
}
JVMCIKlassHandle& JVMCIKlassHandle::operator=(Klass* klass) {
_klass = klass;
if (klass != NULL) {
_holder = Handle(_thread, klass->klass_holder());
}
return *this;
}
static void requireInHotSpot(const char* caller, JVMCI_TRAPS) {
if (!JVMCIENV->is_hotspot()) {
JVMCI_THROW_MSG(IllegalStateException, err_msg("Cannot call %s from JVMCI shared library", caller));
}
}
void JNIHandleMark::push_jni_handle_block(JavaThread* thread) {
if (thread != NULL) {
// Allocate a new block for JNI handles.
// Inlined code from jni_PushLocalFrame()
JNIHandleBlock* java_handles = thread->active_handles();
JNIHandleBlock* compile_handles = JNIHandleBlock::allocate_block(thread);
assert(compile_handles != NULL && java_handles != NULL, "should not be NULL");
compile_handles->set_pop_frame_link(java_handles);
thread->set_active_handles(compile_handles);
}
}
void JNIHandleMark::pop_jni_handle_block(JavaThread* thread) {
if (thread != NULL) {
// Release our JNI handle block
JNIHandleBlock* compile_handles = thread->active_handles();
JNIHandleBlock* java_handles = compile_handles->pop_frame_link();
thread->set_active_handles(java_handles);
compile_handles->set_pop_frame_link(NULL);
JNIHandleBlock::release_block(compile_handles, thread); // may block
}
}
class JVMCITraceMark : public StackObj {
const char* _msg;
public:
JVMCITraceMark(const char* msg) {
_msg = msg;
if (JVMCITraceLevel >= 1) {
tty->print_cr(PTR_FORMAT " JVMCITrace-1: Enter %s", p2i(JavaThread::current()), _msg);
}
}
~JVMCITraceMark() {
if (JVMCITraceLevel >= 1) {
tty->print_cr(PTR_FORMAT " JVMCITrace-1: Exit %s", p2i(JavaThread::current()), _msg);
}
}
};
Handle JavaArgumentUnboxer::next_arg(BasicType expectedType) {
assert(_index < _args->length(), "out of bounds");
oop arg=((objArrayOop) (_args))->obj_at(_index++);
assert(expectedType == T_OBJECT || java_lang_boxing_object::is_instance(arg, expectedType), "arg type mismatch");
return Handle(Thread::current(), arg);
}
// Bring the JVMCI compiler thread into the VM state.
#define JVMCI_VM_ENTRY_MARK \
ThreadInVMfromNative __tiv(thread); \
ResetNoHandleMark rnhm; \
HandleMarkCleaner __hm(thread); \
Thread* THREAD = thread; \
debug_only(VMNativeEntryWrapper __vew;)
// Native method block that transitions current thread to '_thread_in_vm'.
#define C2V_BLOCK(result_type, name, signature) \
TRACE_CALL(result_type, jvmci_ ## name signature) \
JVMCI_VM_ENTRY_MARK; \
ResourceMark rm; \
JNI_JVMCIENV(thread, env);
static Thread* get_current_thread() {
return Thread::current_or_null_safe();
}
// Entry to native method implementation that transitions
// current thread to '_thread_in_vm'.
#define C2V_VMENTRY(result_type, name, signature) \
JNIEXPORT result_type JNICALL c2v_ ## name signature { \
Thread* base_thread = get_current_thread(); \
if (base_thread == NULL) { \
env->ThrowNew(JNIJVMCI::InternalError::clazz(), \
err_msg("Cannot call into HotSpot from JVMCI shared library without attaching current thread")); \
return; \
} \
assert(base_thread->is_Java_thread(), "just checking");\
JavaThread* thread = (JavaThread*) base_thread; \
JVMCITraceMark jtm("CompilerToVM::" #name); \
C2V_BLOCK(result_type, name, signature)
#define C2V_VMENTRY_(result_type, name, signature, result) \
JNIEXPORT result_type JNICALL c2v_ ## name signature { \
Thread* base_thread = get_current_thread(); \
if (base_thread == NULL) { \
env->ThrowNew(JNIJVMCI::InternalError::clazz(), \
err_msg("Cannot call into HotSpot from JVMCI shared library without attaching current thread")); \
return result; \
} \
assert(base_thread->is_Java_thread(), "just checking");\
JavaThread* thread = (JavaThread*) base_thread; \
JVMCITraceMark jtm("CompilerToVM::" #name); \
C2V_BLOCK(result_type, name, signature)
#define C2V_VMENTRY_NULL(result_type, name, signature) C2V_VMENTRY_(result_type, name, signature, NULL)
#define C2V_VMENTRY_0(result_type, name, signature) C2V_VMENTRY_(result_type, name, signature, 0)
// Entry to native method implementation that does not transition
// current thread to '_thread_in_vm'.
#define C2V_VMENTRY_PREFIX(result_type, name, signature) \
JNIEXPORT result_type JNICALL c2v_ ## name signature { \
Thread* base_thread = get_current_thread();
#define C2V_END }
#define JNI_THROW(caller, name, msg) do { \
jint __throw_res = env->ThrowNew(JNIJVMCI::name::clazz(), msg); \
if (__throw_res != JNI_OK) { \
tty->print_cr("Throwing " #name " in " caller " returned %d", __throw_res); \
} \
return; \
} while (0);
#define JNI_THROW_(caller, name, msg, result) do { \
jint __throw_res = env->ThrowNew(JNIJVMCI::name::clazz(), msg); \
if (__throw_res != JNI_OK) { \
tty->print_cr("Throwing " #name " in " caller " returned %d", __throw_res); \
} \
return result; \
} while (0)
jobjectArray readConfiguration0(JNIEnv *env, JVMCI_TRAPS);
C2V_VMENTRY_NULL(jobjectArray, readConfiguration, (JNIEnv* env))
jobjectArray config = readConfiguration0(env, JVMCI_CHECK_NULL);
return config;
}
C2V_VMENTRY_NULL(jobject, getFlagValue, (JNIEnv* env, jobject c2vm, jobject name_handle))
#define RETURN_BOXED_LONG(value) jvalue p; p.j = (jlong) (value); JVMCIObject box = JVMCIENV->create_box(T_LONG, &p, JVMCI_CHECK_NULL); return box.as_jobject();
#define RETURN_BOXED_DOUBLE(value) jvalue p; p.d = (jdouble) (value); JVMCIObject box = JVMCIENV->create_box(T_DOUBLE, &p, JVMCI_CHECK_NULL); return box.as_jobject();
JVMCIObject name = JVMCIENV->wrap(name_handle);
if (name.is_null()) {
JVMCI_THROW_NULL(NullPointerException);
}
const char* cstring = JVMCIENV->as_utf8_string(name);
JVMFlag* flag = JVMFlag::find_flag(cstring, strlen(cstring), /* allow_locked */ true, /* return_flag */ true);
if (flag == NULL) {
return c2vm;
}
if (flag->is_bool()) {
jvalue prim;
prim.z = flag->get_bool();
JVMCIObject box = JVMCIENV->create_box(T_BOOLEAN, &prim, JVMCI_CHECK_NULL);
return JVMCIENV->get_jobject(box);
} else if (flag->is_ccstr()) {
JVMCIObject value = JVMCIENV->create_string(flag->get_ccstr(), JVMCI_CHECK_NULL);
return JVMCIENV->get_jobject(value);
} else if (flag->is_intx()) {
RETURN_BOXED_LONG(flag->get_intx());
} else if (flag->is_int()) {
RETURN_BOXED_LONG(flag->get_int());
} else if (flag->is_uint()) {
RETURN_BOXED_LONG(flag->get_uint());
} else if (flag->is_uint64_t()) {
RETURN_BOXED_LONG(flag->get_uint64_t());
} else if (flag->is_size_t()) {
RETURN_BOXED_LONG(flag->get_size_t());
} else if (flag->is_uintx()) {
RETURN_BOXED_LONG(flag->get_uintx());
} else if (flag->is_double()) {
RETURN_BOXED_DOUBLE(flag->get_double());
} else {
JVMCI_ERROR_NULL("VM flag %s has unsupported type %s", flag->_name, flag->_type);
}
#undef RETURN_BOXED_LONG
#undef RETURN_BOXED_DOUBLE
C2V_END
C2V_VMENTRY_NULL(jobject, getObjectAtAddress, (JNIEnv* env, jobject c2vm, jlong oop_address))
requireInHotSpot("getObjectAtAddress", JVMCI_CHECK_NULL);
if (oop_address == 0) {
JVMCI_THROW_MSG_NULL(InternalError, "Handle must be non-zero");
}
oop obj = *((oopDesc**) oop_address);
if (obj != NULL) {
oopDesc::verify(obj);
}
return JNIHandles::make_local(obj);
C2V_END
C2V_VMENTRY_NULL(jbyteArray, getBytecode, (JNIEnv* env, jobject, jobject jvmci_method))
methodHandle method = JVMCIENV->asMethod(jvmci_method);
int code_size = method->code_size();
jbyte* reconstituted_code = NEW_RESOURCE_ARRAY(jbyte, code_size);
guarantee(method->method_holder()->is_rewritten(), "Method's holder should be rewritten");
// iterate over all bytecodes and replace non-Java bytecodes
for (BytecodeStream s(method); s.next() != Bytecodes::_illegal; ) {
Bytecodes::Code code = s.code();
Bytecodes::Code raw_code = s.raw_code();
int bci = s.bci();
int len = s.instruction_size();
// Restore original byte code.
reconstituted_code[bci] = (jbyte) (s.is_wide()? Bytecodes::_wide : code);
if (len > 1) {
memcpy(reconstituted_code + (bci + 1), s.bcp()+1, len-1);
}
if (len > 1) {
// Restore the big-endian constant pool indexes.
// Cf. Rewriter::scan_method
switch (code) {
case Bytecodes::_getstatic:
case Bytecodes::_putstatic:
case Bytecodes::_getfield:
case Bytecodes::_putfield:
case Bytecodes::_invokevirtual:
case Bytecodes::_invokespecial:
case Bytecodes::_invokestatic:
case Bytecodes::_invokeinterface:
case Bytecodes::_invokehandle: {
int cp_index = Bytes::get_native_u2((address) reconstituted_code + (bci + 1));
Bytes::put_Java_u2((address) reconstituted_code + (bci + 1), (u2) cp_index);
break;
}
case Bytecodes::_invokedynamic: {
int cp_index = Bytes::get_native_u4((address) reconstituted_code + (bci + 1));
Bytes::put_Java_u4((address) reconstituted_code + (bci + 1), (u4) cp_index);
break;
}
default:
break;
}
// Not all ldc byte code are rewritten.
switch (raw_code) {
case Bytecodes::_fast_aldc: {
int cpc_index = reconstituted_code[bci + 1] & 0xff;
int cp_index = method->constants()->object_to_cp_index(cpc_index);
assert(cp_index < method->constants()->length(), "sanity check");
reconstituted_code[bci + 1] = (jbyte) cp_index;
break;
}
case Bytecodes::_fast_aldc_w: {
int cpc_index = Bytes::get_native_u2((address) reconstituted_code + (bci + 1));
int cp_index = method->constants()->object_to_cp_index(cpc_index);
assert(cp_index < method->constants()->length(), "sanity check");
Bytes::put_Java_u2((address) reconstituted_code + (bci + 1), (u2) cp_index);
break;
}
default:
break;
}
}
}
JVMCIPrimitiveArray result = JVMCIENV->new_byteArray(code_size, JVMCI_CHECK_NULL);
JVMCIENV->copy_bytes_from(reconstituted_code, result, 0, code_size);
return JVMCIENV->get_jbyteArray(result);
C2V_END
C2V_VMENTRY_0(jint, getExceptionTableLength, (JNIEnv* env, jobject, jobject jvmci_method))
methodHandle method = JVMCIENV->asMethod(jvmci_method);
return method->exception_table_length();
C2V_END
C2V_VMENTRY_0(jlong, getExceptionTableStart, (JNIEnv* env, jobject, jobject jvmci_method))
methodHandle method = JVMCIENV->asMethod(jvmci_method);
if (method->exception_table_length() == 0) {
return 0L;
}
return (jlong) (address) method->exception_table_start();
C2V_END
C2V_VMENTRY_NULL(jobject, asResolvedJavaMethod, (JNIEnv* env, jobject, jobject executable_handle))
requireInHotSpot("asResolvedJavaMethod", JVMCI_CHECK_NULL);
oop executable = JNIHandles::resolve(executable_handle);
oop mirror = NULL;
int slot = 0;
if (executable->klass() == SystemDictionary::reflect_Constructor_klass()) {
mirror = java_lang_reflect_Constructor::clazz(executable);
slot = java_lang_reflect_Constructor::slot(executable);
} else {
assert(executable->klass() == SystemDictionary::reflect_Method_klass(), "wrong type");
mirror = java_lang_reflect_Method::clazz(executable);
slot = java_lang_reflect_Method::slot(executable);
}
Klass* holder = java_lang_Class::as_Klass(mirror);
methodHandle method = InstanceKlass::cast(holder)->method_with_idnum(slot);
JVMCIObject result = JVMCIENV->get_jvmci_method(method, JVMCI_CHECK_NULL);
return JVMCIENV->get_jobject(result);
}
C2V_VMENTRY_NULL(jobject, getResolvedJavaMethod, (JNIEnv* env, jobject, jobject base, jlong offset))
methodHandle method;
JVMCIObject base_object = JVMCIENV->wrap(base);
if (base_object.is_null()) {
method = *((Method**)(offset));
} else if (JVMCIENV->isa_HotSpotObjectConstantImpl(base_object)) {
Handle obj = JVMCIENV->asConstant(base_object, JVMCI_CHECK_NULL);
if (obj->is_a(SystemDictionary::ResolvedMethodName_klass())) {
method = (Method*) (intptr_t) obj->long_field(offset);
} else {
JVMCI_THROW_MSG_NULL(IllegalArgumentException, err_msg("Unexpected type: %s", obj->klass()->external_name()));
}
} else if (JVMCIENV->isa_HotSpotResolvedJavaMethodImpl(base_object)) {
method = JVMCIENV->asMethod(base_object);
}
if (method.is_null()) {
JVMCI_THROW_MSG_NULL(IllegalArgumentException, err_msg("Unexpected type: %s", JVMCIENV->klass_name(base_object)));
}
assert (method.is_null() || method->is_method(), "invalid read");
JVMCIObject result = JVMCIENV->get_jvmci_method(method, JVMCI_CHECK_NULL);
return JVMCIENV->get_jobject(result);
}
C2V_VMENTRY_NULL(jobject, getConstantPool, (JNIEnv* env, jobject, jobject object_handle))
constantPoolHandle cp;
JVMCIObject object = JVMCIENV->wrap(object_handle);
if (object.is_null()) {
JVMCI_THROW_NULL(NullPointerException);
}
if (JVMCIENV->isa_HotSpotResolvedJavaMethodImpl(object)) {
cp = JVMCIENV->asMethod(object)->constMethod()->constants();
} else if (JVMCIENV->isa_HotSpotResolvedObjectTypeImpl(object)) {
cp = InstanceKlass::cast(JVMCIENV->asKlass(object))->constants();
} else {
JVMCI_THROW_MSG_NULL(IllegalArgumentException,
err_msg("Unexpected type: %s", JVMCIENV->klass_name(object)));
}
assert(!cp.is_null(), "npe");
JVMCIObject result = JVMCIENV->get_jvmci_constant_pool(cp, JVMCI_CHECK_NULL);
return JVMCIENV->get_jobject(result);
}
C2V_VMENTRY_NULL(jobject, getResolvedJavaType0, (JNIEnv* env, jobject, jobject base, jlong offset, jboolean compressed))
JVMCIKlassHandle klass(THREAD);
JVMCIObject base_object = JVMCIENV->wrap(base);
jlong base_address = 0;
if (base_object.is_non_null() && offset == oopDesc::klass_offset_in_bytes()) {
// klass = JVMCIENV->unhandle(base_object)->klass();
if (JVMCIENV->isa_HotSpotObjectConstantImpl(base_object)) {
Handle base_oop = JVMCIENV->asConstant(base_object, JVMCI_CHECK_NULL);
klass = base_oop->klass();
} else {
assert(false, "What types are we actually expecting here?");
}
} else if (!compressed) {
if (base_object.is_non_null()) {
if (JVMCIENV->isa_HotSpotResolvedJavaMethodImpl(base_object)) {
base_address = (intptr_t) JVMCIENV->asMethod(base_object);
} else if (JVMCIENV->isa_HotSpotConstantPool(base_object)) {
base_address = (intptr_t) JVMCIENV->asConstantPool(base_object);
} else if (JVMCIENV->isa_HotSpotResolvedObjectTypeImpl(base_object)) {
base_address = (intptr_t) JVMCIENV->asKlass(base_object);
} else if (JVMCIENV->isa_HotSpotObjectConstantImpl(base_object)) {
Handle base_oop = JVMCIENV->asConstant(base_object, JVMCI_CHECK_NULL);
if (base_oop->is_a(SystemDictionary::Class_klass())) {
base_address = (jlong) (address) base_oop();
}
}
if (base_address == 0) {
JVMCI_THROW_MSG_NULL(IllegalArgumentException,
err_msg("Unexpected arguments: %s " JLONG_FORMAT " %s", JVMCIENV->klass_name(base_object), offset, compressed ? "true" : "false"));
}
}
klass = *((Klass**) (intptr_t) (base_address + offset));
} else {
JVMCI_THROW_MSG_NULL(IllegalArgumentException,
err_msg("Unexpected arguments: %s " JLONG_FORMAT " %s",
base_object.is_non_null() ? JVMCIENV->klass_name(base_object) : "null",
offset, compressed ? "true" : "false"));
}
assert (klass == NULL || klass->is_klass(), "invalid read");
JVMCIObject result = JVMCIENV->get_jvmci_type(klass, JVMCI_CHECK_NULL);
return JVMCIENV->get_jobject(result);
}
C2V_VMENTRY_NULL(jobject, findUniqueConcreteMethod, (JNIEnv* env, jobject, jobject jvmci_type, jobject jvmci_method))
methodHandle method = JVMCIENV->asMethod(jvmci_method);
Klass* holder = JVMCIENV->asKlass(jvmci_type);
if (holder->is_interface()) {
JVMCI_THROW_MSG_NULL(InternalError, err_msg("Interface %s should be handled in Java code", holder->external_name()));
}
if (method->can_be_statically_bound()) {
JVMCI_THROW_MSG_NULL(InternalError, err_msg("Effectively static method %s.%s should be handled in Java code", method->method_holder()->external_name(), method->external_name()));
}
methodHandle ucm;
{
MutexLocker locker(Compile_lock);
ucm = Dependencies::find_unique_concrete_method(holder, method());
}
JVMCIObject result = JVMCIENV->get_jvmci_method(ucm, JVMCI_CHECK_NULL);
return JVMCIENV->get_jobject(result);
C2V_END
C2V_VMENTRY_NULL(jobject, getImplementor, (JNIEnv* env, jobject, jobject jvmci_type))
Klass* klass = JVMCIENV->asKlass(jvmci_type);
if (!klass->is_interface()) {
THROW_MSG_0(vmSymbols::java_lang_IllegalArgumentException(),
err_msg("Expected interface type, got %s", klass->external_name()));
}
InstanceKlass* iklass = InstanceKlass::cast(klass);
JVMCIKlassHandle handle(THREAD);
{
// Need Compile_lock around implementor()
MutexLocker locker(Compile_lock);
handle = iklass->implementor();
}
JVMCIObject implementor = JVMCIENV->get_jvmci_type(handle, JVMCI_CHECK_NULL);
return JVMCIENV->get_jobject(implementor);
C2V_END
C2V_VMENTRY_0(jboolean, methodIsIgnoredBySecurityStackWalk,(JNIEnv* env, jobject, jobject jvmci_method))
methodHandle method = JVMCIENV->asMethod(jvmci_method);
return method->is_ignored_by_security_stack_walk();
C2V_END
C2V_VMENTRY_0(jboolean, isCompilable,(JNIEnv* env, jobject, jobject jvmci_method))
methodHandle method = JVMCIENV->asMethod(jvmci_method);
constantPoolHandle cp = method->constMethod()->constants();
assert(!cp.is_null(), "npe");
// don't inline method when constant pool contains a CONSTANT_Dynamic
return !method->is_not_compilable(CompLevel_full_optimization) && !cp->has_dynamic_constant();
C2V_END
C2V_VMENTRY_0(jboolean, hasNeverInlineDirective,(JNIEnv* env, jobject, jobject jvmci_method))
methodHandle method = JVMCIENV->asMethod(jvmci_method);
return !Inline || CompilerOracle::should_not_inline(method) || method->dont_inline();
C2V_END
C2V_VMENTRY_0(jboolean, shouldInlineMethod,(JNIEnv* env, jobject, jobject jvmci_method))
methodHandle method = JVMCIENV->asMethod(jvmci_method);
return CompilerOracle::should_inline(method) || method->force_inline();
C2V_END
C2V_VMENTRY_NULL(jobject, lookupType, (JNIEnv* env, jobject, jstring jname, jclass accessing_class, jboolean resolve))
JVMCIObject name = JVMCIENV->wrap(jname);
const char* str = JVMCIENV->as_utf8_string(name);
TempNewSymbol class_name = SymbolTable::new_symbol(str);
if (class_name->utf8_length() <= 1) {
JVMCI_THROW_MSG_0(InternalError, err_msg("Primitive type %s should be handled in Java code", class_name->as_C_string()));
}
JVMCIKlassHandle resolved_klass(THREAD);
Klass* accessing_klass = NULL;
Handle class_loader;
Handle protection_domain;
if (accessing_class != NULL) {
accessing_klass = JVMCIENV->asKlass(accessing_class);
class_loader = Handle(THREAD, accessing_klass->class_loader());
protection_domain = Handle(THREAD, accessing_klass->protection_domain());
} else {
// Use the System class loader
class_loader = Handle(THREAD, SystemDictionary::java_system_loader());
JVMCIENV->runtime()->initialize(JVMCIENV);
}
if (resolve) {
resolved_klass = SystemDictionary::resolve_or_null(class_name, class_loader, protection_domain, CHECK_0);
if (resolved_klass == NULL) {
JVMCI_THROW_MSG_NULL(ClassNotFoundException, str);
}
} else {
if (class_name->char_at(0) == 'L' &&
class_name->char_at(class_name->utf8_length()-1) == ';') {
// This is a name from a signature. Strip off the trimmings.
// Call recursive to keep scope of strippedsym.
TempNewSymbol strippedsym = SymbolTable::new_symbol(class_name->as_utf8()+1,
class_name->utf8_length()-2);
resolved_klass = SystemDictionary::find(strippedsym, class_loader, protection_domain, CHECK_0);
} else if (FieldType::is_array(class_name)) {
FieldArrayInfo fd;
// dimension and object_key in FieldArrayInfo are assigned as a side-effect
// of this call
BasicType t = FieldType::get_array_info(class_name, fd, CHECK_0);
if (t == T_OBJECT) {
TempNewSymbol strippedsym = SymbolTable::new_symbol(class_name->as_utf8()+1+fd.dimension(),
class_name->utf8_length()-2-fd.dimension());
resolved_klass = SystemDictionary::find(strippedsym,
class_loader,
protection_domain,
CHECK_0);
if (!resolved_klass.is_null()) {
resolved_klass = resolved_klass->array_klass(fd.dimension(), CHECK_0);
}
} else {
resolved_klass = TypeArrayKlass::cast(Universe::typeArrayKlassObj(t))->array_klass(fd.dimension(), CHECK_0);
}
} else {
resolved_klass = SystemDictionary::find(class_name, class_loader, protection_domain, CHECK_0);
}
}
JVMCIObject result = JVMCIENV->get_jvmci_type(resolved_klass, JVMCI_CHECK_NULL);
return JVMCIENV->get_jobject(result);
C2V_END
C2V_VMENTRY_NULL(jobject, getArrayType, (JNIEnv* env, jobject, jobject jvmci_type))
if (jvmci_type == NULL) {
JVMCI_THROW_0(NullPointerException);
}
JVMCIObject jvmci_type_object = JVMCIENV->wrap(jvmci_type);
JVMCIKlassHandle array_klass(THREAD);
if (JVMCIENV->isa_HotSpotResolvedPrimitiveType(jvmci_type_object)) {
BasicType type = JVMCIENV->kindToBasicType(JVMCIENV->get_HotSpotResolvedPrimitiveType_kind(jvmci_type_object), JVMCI_CHECK_0);
if (type == T_VOID) {
return NULL;
}
array_klass = Universe::typeArrayKlassObj(type);
if (array_klass == NULL) {
JVMCI_THROW_MSG_NULL(InternalError, err_msg("No array klass for primitive type %s", type2name(type)));
}
} else {
Klass* klass = JVMCIENV->asKlass(jvmci_type);
if (klass == NULL) {
JVMCI_THROW_0(NullPointerException);
}
array_klass = klass->array_klass(CHECK_NULL);
}
JVMCIObject result = JVMCIENV->get_jvmci_type(array_klass, JVMCI_CHECK_NULL);
return JVMCIENV->get_jobject(result);
C2V_END
C2V_VMENTRY_NULL(jobject, lookupClass, (JNIEnv* env, jobject, jclass mirror))
requireInHotSpot("lookupClass", JVMCI_CHECK_NULL);
if (mirror == NULL) {
return NULL;
}
JVMCIKlassHandle klass(THREAD);
klass = java_lang_Class::as_Klass(JNIHandles::resolve(mirror));
if (klass == NULL) {
JVMCI_THROW_MSG_NULL(IllegalArgumentException, "Primitive classes are unsupported");
}
JVMCIObject result = JVMCIENV->get_jvmci_type(klass, JVMCI_CHECK_NULL);
return JVMCIENV->get_jobject(result);
}
C2V_VMENTRY_NULL(jobject, resolvePossiblyCachedConstantInPool, (JNIEnv* env, jobject, jobject jvmci_constant_pool, jint index))
constantPoolHandle cp = JVMCIENV->asConstantPool(jvmci_constant_pool);
oop result = cp->resolve_possibly_cached_constant_at(index, CHECK_NULL);
return JVMCIENV->get_jobject(JVMCIENV->get_object_constant(result));
C2V_END
C2V_VMENTRY_0(jint, lookupNameAndTypeRefIndexInPool, (JNIEnv* env, jobject, jobject jvmci_constant_pool, jint index))
constantPoolHandle cp = JVMCIENV->asConstantPool(jvmci_constant_pool);
return cp->name_and_type_ref_index_at(index);
C2V_END
C2V_VMENTRY_NULL(jobject, lookupNameInPool, (JNIEnv* env, jobject, jobject jvmci_constant_pool, jint which))
constantPoolHandle cp = JVMCIENV->asConstantPool(jvmci_constant_pool);
JVMCIObject sym = JVMCIENV->create_string(cp->name_ref_at(which), JVMCI_CHECK_NULL);
return JVMCIENV->get_jobject(sym);
C2V_END
C2V_VMENTRY_NULL(jobject, lookupSignatureInPool, (JNIEnv* env, jobject, jobject jvmci_constant_pool, jint which))
constantPoolHandle cp = JVMCIENV->asConstantPool(jvmci_constant_pool);
JVMCIObject sym = JVMCIENV->create_string(cp->signature_ref_at(which), JVMCI_CHECK_NULL);
return JVMCIENV->get_jobject(sym);
C2V_END
C2V_VMENTRY_0(jint, lookupKlassRefIndexInPool, (JNIEnv* env, jobject, jobject jvmci_constant_pool, jint index))
constantPoolHandle cp = JVMCIENV->asConstantPool(jvmci_constant_pool);
return cp->klass_ref_index_at(index);
C2V_END
C2V_VMENTRY_NULL(jobject, resolveTypeInPool, (JNIEnv* env, jobject, jobject jvmci_constant_pool, jint index))
constantPoolHandle cp = JVMCIENV->asConstantPool(jvmci_constant_pool);
Klass* klass = cp->klass_at(index, CHECK_NULL);
JVMCIKlassHandle resolved_klass(THREAD, klass);
if (resolved_klass->is_instance_klass()) {
InstanceKlass::cast(resolved_klass())->link_class(CHECK_NULL);
if (!InstanceKlass::cast(resolved_klass())->is_linked()) {
// link_class() should not return here if there is an issue.
JVMCI_THROW_MSG_NULL(InternalError, err_msg("Class %s must be linked", resolved_klass()->external_name()));
}
}
JVMCIObject klassObject = JVMCIENV->get_jvmci_type(resolved_klass, JVMCI_CHECK_NULL);
return JVMCIENV->get_jobject(klassObject);
C2V_END
C2V_VMENTRY_NULL(jobject, lookupKlassInPool, (JNIEnv* env, jobject, jobject jvmci_constant_pool, jint index, jbyte opcode))
constantPoolHandle cp = JVMCIENV->asConstantPool(jvmci_constant_pool);
Klass* loading_klass = cp->pool_holder();
bool is_accessible = false;
JVMCIKlassHandle klass(THREAD, JVMCIRuntime::get_klass_by_index(cp, index, is_accessible, loading_klass));
Symbol* symbol = NULL;
if (klass.is_null()) {
constantTag tag = cp->tag_at(index);
if (tag.is_klass()) {
// The klass has been inserted into the constant pool
// very recently.
klass = cp->resolved_klass_at(index);
} else if (tag.is_symbol()) {
symbol = cp->symbol_at(index);
} else {
assert(cp->tag_at(index).is_unresolved_klass(), "wrong tag");
symbol = cp->klass_name_at(index);
}
}
JVMCIObject result;
if (!klass.is_null()) {
result = JVMCIENV->get_jvmci_type(klass, JVMCI_CHECK_NULL);
} else {
result = JVMCIENV->create_string(symbol, JVMCI_CHECK_NULL);
}
return JVMCIENV->get_jobject(result);
C2V_END
C2V_VMENTRY_NULL(jobject, lookupAppendixInPool, (JNIEnv* env, jobject, jobject jvmci_constant_pool, jint index))
constantPoolHandle cp = JVMCIENV->asConstantPool(jvmci_constant_pool);
oop appendix_oop = ConstantPool::appendix_at_if_loaded(cp, index);
return JVMCIENV->get_jobject(JVMCIENV->get_object_constant(appendix_oop));
C2V_END
C2V_VMENTRY_NULL(jobject, lookupMethodInPool, (JNIEnv* env, jobject, jobject jvmci_constant_pool, jint index, jbyte opcode))
constantPoolHandle cp = JVMCIENV->asConstantPool(jvmci_constant_pool);
InstanceKlass* pool_holder = cp->pool_holder();
Bytecodes::Code bc = (Bytecodes::Code) (((int) opcode) & 0xFF);
methodHandle method = JVMCIRuntime::get_method_by_index(cp, index, bc, pool_holder);
JVMCIObject result = JVMCIENV->get_jvmci_method(method, JVMCI_CHECK_NULL);
return JVMCIENV->get_jobject(result);
C2V_END
C2V_VMENTRY_0(jint, constantPoolRemapInstructionOperandFromCache, (JNIEnv* env, jobject, jobject jvmci_constant_pool, jint index))
constantPoolHandle cp = JVMCIENV->asConstantPool(jvmci_constant_pool);
return cp->remap_instruction_operand_from_cache(index);
C2V_END
C2V_VMENTRY_NULL(jobject, resolveFieldInPool, (JNIEnv* env, jobject, jobject jvmci_constant_pool, jint index, jobject jvmci_method, jbyte opcode, jintArray info_handle))
constantPoolHandle cp = JVMCIENV->asConstantPool(jvmci_constant_pool);
Bytecodes::Code code = (Bytecodes::Code)(((int) opcode) & 0xFF);
fieldDescriptor fd;
LinkInfo link_info(cp, index, (jvmci_method != NULL) ? JVMCIENV->asMethod(jvmci_method) : NULL, CHECK_0);
LinkResolver::resolve_field(fd, link_info, Bytecodes::java_code(code), false, CHECK_0);
JVMCIPrimitiveArray info = JVMCIENV->wrap(info_handle);
if (info.is_null() || JVMCIENV->get_length(info) != 3) {
JVMCI_ERROR_NULL("info must not be null and have a length of 3");
}
JVMCIENV->put_int_at(info, 0, fd.access_flags().as_int());
JVMCIENV->put_int_at(info, 1, fd.offset());
JVMCIENV->put_int_at(info, 2, fd.index());
JVMCIKlassHandle handle(THREAD, fd.field_holder());
JVMCIObject field_holder = JVMCIENV->get_jvmci_type(handle, JVMCI_CHECK_NULL);
return JVMCIENV->get_jobject(field_holder);
C2V_END
C2V_VMENTRY_0(jint, getVtableIndexForInterfaceMethod, (JNIEnv* env, jobject, jobject jvmci_type, jobject jvmci_method))
Klass* klass = JVMCIENV->asKlass(jvmci_type);
Method* method = JVMCIENV->asMethod(jvmci_method);
if (klass->is_interface()) {
JVMCI_THROW_MSG_0(InternalError, err_msg("Interface %s should be handled in Java code", klass->external_name()));
}
if (!method->method_holder()->is_interface()) {
JVMCI_THROW_MSG_0(InternalError, err_msg("Method %s is not held by an interface, this case should be handled in Java code", method->name_and_sig_as_C_string()));
}
if (!klass->is_instance_klass()) {
JVMCI_THROW_MSG_0(InternalError, err_msg("Class %s must be instance klass", klass->external_name()));
}
if (!InstanceKlass::cast(klass)->is_linked()) {
JVMCI_THROW_MSG_0(InternalError, err_msg("Class %s must be linked", klass->external_name()));
}
return LinkResolver::vtable_index_of_interface_method(klass, method);
C2V_END
C2V_VMENTRY_NULL(jobject, resolveMethod, (JNIEnv* env, jobject, jobject receiver_jvmci_type, jobject jvmci_method, jobject caller_jvmci_type))
Klass* recv_klass = JVMCIENV->asKlass(receiver_jvmci_type);
Klass* caller_klass = JVMCIENV->asKlass(caller_jvmci_type);
methodHandle method = JVMCIENV->asMethod(jvmci_method);
Klass* resolved = method->method_holder();
Symbol* h_name = method->name();
Symbol* h_signature = method->signature();
if (MethodHandles::is_signature_polymorphic_method(method())) {
// Signature polymorphic methods are already resolved, JVMCI just returns NULL in this case.
return NULL;
}
if (method->name() == vmSymbols::clone_name() &&
resolved == SystemDictionary::Object_klass() &&
recv_klass->is_array_klass()) {
// Resolution of the clone method on arrays always returns Object.clone even though that method
// has protected access. There's some trickery in the access checking to make this all work out
// so it's necessary to pass in the array class as the resolved class to properly trigger this.
// Otherwise it's impossible to resolve the array clone methods through JVMCI. See
// LinkResolver::check_method_accessability for the matching logic.
resolved = recv_klass;
}
LinkInfo link_info(resolved, h_name, h_signature, caller_klass);
methodHandle m;
// Only do exact lookup if receiver klass has been linked. Otherwise,
// the vtable has not been setup, and the LinkResolver will fail.
if (recv_klass->is_array_klass() ||
(InstanceKlass::cast(recv_klass)->is_linked() && !recv_klass->is_interface())) {
if (resolved->is_interface()) {
m = LinkResolver::resolve_interface_call_or_null(recv_klass, link_info);
} else {
m = LinkResolver::resolve_virtual_call_or_null(recv_klass, link_info);
}
}
if (m.is_null()) {
// Return NULL if there was a problem with lookup (uninitialized class, etc.)
return NULL;
}
JVMCIObject result = JVMCIENV->get_jvmci_method(m, JVMCI_CHECK_NULL);
return JVMCIENV->get_jobject(result);
C2V_END
C2V_VMENTRY_0(jboolean, hasFinalizableSubclass,(JNIEnv* env, jobject, jobject jvmci_type))
Klass* klass = JVMCIENV->asKlass(jvmci_type);
assert(klass != NULL, "method must not be called for primitive types");
return Dependencies::find_finalizable_subclass(klass) != NULL;
C2V_END
C2V_VMENTRY_NULL(jobject, getClassInitializer, (JNIEnv* env, jobject, jobject jvmci_type))
Klass* klass = JVMCIENV->asKlass(jvmci_type);
if (!klass->is_instance_klass()) {
return NULL;
}
InstanceKlass* iklass = InstanceKlass::cast(klass);
JVMCIObject result = JVMCIENV->get_jvmci_method(iklass->class_initializer(), JVMCI_CHECK_NULL);
return JVMCIENV->get_jobject(result);
C2V_END
C2V_VMENTRY_0(jlong, getMaxCallTargetOffset, (JNIEnv* env, jobject, jlong addr))
address target_addr = (address) addr;
if (target_addr != 0x0) {
int64_t off_low = (int64_t)target_addr - ((int64_t)CodeCache::low_bound() + sizeof(int));
int64_t off_high = (int64_t)target_addr - ((int64_t)CodeCache::high_bound() + sizeof(int));
return MAX2(ABS(off_low), ABS(off_high));
}
return -1;
C2V_END
C2V_VMENTRY(void, setNotInlinableOrCompilable,(JNIEnv* env, jobject, jobject jvmci_method))
methodHandle method = JVMCIENV->asMethod(jvmci_method);
method->set_not_c1_compilable();
method->set_not_c2_compilable();
method->set_dont_inline(true);
C2V_END
C2V_VMENTRY_0(jint, installCode, (JNIEnv *env, jobject, jobject target, jobject compiled_code,
jobject installed_code, jlong failed_speculations_address, jbyteArray speculations_obj))
HandleMark hm;
JNIHandleMark jni_hm(thread);
JVMCIObject target_handle = JVMCIENV->wrap(target);
JVMCIObject compiled_code_handle = JVMCIENV->wrap(compiled_code);
CodeBlob* cb = NULL;
JVMCIObject installed_code_handle = JVMCIENV->wrap(installed_code);
JVMCIPrimitiveArray speculations_handle = JVMCIENV->wrap(speculations_obj);
int speculations_len = JVMCIENV->get_length(speculations_handle);
char* speculations = NEW_RESOURCE_ARRAY(char, speculations_len);
JVMCIENV->copy_bytes_to(speculations_handle, (jbyte*) speculations, 0, speculations_len);
JVMCICompiler* compiler = JVMCICompiler::instance(true, CHECK_JNI_ERR);
TraceTime install_time("installCode", JVMCICompiler::codeInstallTimer());
bool is_immutable_PIC = JVMCIENV->get_HotSpotCompiledCode_isImmutablePIC(compiled_code_handle) > 0;
CodeInstaller installer(JVMCIENV, is_immutable_PIC);
JVMCI::CodeInstallResult result = installer.install(compiler,
target_handle,
compiled_code_handle,
cb,
installed_code_handle,
(FailedSpeculation**)(address) failed_speculations_address,
speculations,
speculations_len,
JVMCI_CHECK_0);
if (PrintCodeCacheOnCompilation) {
stringStream s;
// Dump code cache into a buffer before locking the tty,
{
MutexLocker mu(CodeCache_lock, Mutex::_no_safepoint_check_flag);
CodeCache::print_summary(&s, false);
}
ttyLocker ttyl;
tty->print_raw_cr(s.as_string());
}
if (result != JVMCI::ok) {
assert(cb == NULL, "should be");
} else {
if (installed_code_handle.is_non_null()) {
if (cb->is_nmethod()) {
assert(JVMCIENV->isa_HotSpotNmethod(installed_code_handle), "wrong type");
// Clear the link to an old nmethod first
JVMCIObject nmethod_mirror = installed_code_handle;
JVMCIENV->invalidate_nmethod_mirror(nmethod_mirror, JVMCI_CHECK_0);
} else {
assert(JVMCIENV->isa_InstalledCode(installed_code_handle), "wrong type");
}
// Initialize the link to the new code blob
JVMCIENV->initialize_installed_code(installed_code_handle, cb, JVMCI_CHECK_0);
}
}
return result;
C2V_END
C2V_VMENTRY_0(jint, getMetadata, (JNIEnv *env, jobject, jobject target, jobject compiled_code, jobject metadata))
#if INCLUDE_AOT
HandleMark hm;
assert(JVMCIENV->is_hotspot(), "AOT code is executed only in HotSpot mode");
JVMCIObject target_handle = JVMCIENV->wrap(target);
JVMCIObject compiled_code_handle = JVMCIENV->wrap(compiled_code);
JVMCIObject metadata_handle = JVMCIENV->wrap(metadata);
CodeMetadata code_metadata;
CodeInstaller installer(JVMCIENV, true /* immutable PIC compilation */);
JVMCI::CodeInstallResult result = installer.gather_metadata(target_handle, compiled_code_handle, code_metadata, JVMCI_CHECK_0);
if (result != JVMCI::ok) {
return result;
}
if (code_metadata.get_nr_pc_desc() > 0) {
int size = sizeof(PcDesc) * code_metadata.get_nr_pc_desc();
JVMCIPrimitiveArray array = JVMCIENV->new_byteArray(size, JVMCI_CHECK_(JVMCI::cache_full));
JVMCIENV->copy_bytes_from((jbyte*) code_metadata.get_pc_desc(), array, 0, size);
HotSpotJVMCI::HotSpotMetaData::set_pcDescBytes(JVMCIENV, metadata_handle, array);
}
if (code_metadata.get_scopes_size() > 0) {
int size = code_metadata.get_scopes_size();
JVMCIPrimitiveArray array = JVMCIENV->new_byteArray(size, JVMCI_CHECK_(JVMCI::cache_full));
JVMCIENV->copy_bytes_from((jbyte*) code_metadata.get_scopes_desc(), array, 0, size);
HotSpotJVMCI::HotSpotMetaData::set_scopesDescBytes(JVMCIENV, metadata_handle, array);
}
RelocBuffer* reloc_buffer = code_metadata.get_reloc_buffer();
int size = (int) reloc_buffer->size();
JVMCIPrimitiveArray array = JVMCIENV->new_byteArray(size, JVMCI_CHECK_(JVMCI::cache_full));
JVMCIENV->copy_bytes_from((jbyte*) reloc_buffer->begin(), array, 0, size);
HotSpotJVMCI::HotSpotMetaData::set_relocBytes(JVMCIENV, metadata_handle, array);
const OopMapSet* oopMapSet = installer.oopMapSet();
{
ResourceMark mark;
ImmutableOopMapBuilder builder(oopMapSet);
int size = builder.heap_size();
JVMCIPrimitiveArray array = JVMCIENV->new_byteArray(size, JVMCI_CHECK_(JVMCI::cache_full));
builder.generate_into((address) HotSpotJVMCI::resolve(array)->byte_at_addr(0));
HotSpotJVMCI::HotSpotMetaData::set_oopMaps(JVMCIENV, metadata_handle, array);
}
AOTOopRecorder* recorder = code_metadata.get_oop_recorder();
int nr_meta_refs = recorder->nr_meta_refs();
JVMCIObjectArray metadataArray = JVMCIENV->new_Object_array(nr_meta_refs, JVMCI_CHECK_(JVMCI::cache_full));
for (int i = 0; i < nr_meta_refs; ++i) {
jobject element = recorder->meta_element(i);
if (element == NULL) {
return JVMCI::cache_full;
}
JVMCIENV->put_object_at(metadataArray, i, JVMCIENV->wrap(element));
}
HotSpotJVMCI::HotSpotMetaData::set_metadata(JVMCIENV, metadata_handle, metadataArray);
ExceptionHandlerTable* handler = code_metadata.get_exception_table();
int table_size = handler->size_in_bytes();
JVMCIPrimitiveArray exceptionArray = JVMCIENV->new_byteArray(table_size, JVMCI_CHECK_(JVMCI::cache_full));
if (table_size > 0) {
handler->copy_bytes_to((address) HotSpotJVMCI::resolve(exceptionArray)->byte_at_addr(0));
}
HotSpotJVMCI::HotSpotMetaData::set_exceptionBytes(JVMCIENV, metadata_handle, exceptionArray);
ImplicitExceptionTable* implicit = code_metadata.get_implicit_exception_table();
int implicit_table_size = implicit->size_in_bytes();
JVMCIPrimitiveArray implicitExceptionArray = JVMCIENV->new_byteArray(implicit_table_size, JVMCI_CHECK_(JVMCI::cache_full));
if (implicit_table_size > 0) {
implicit->copy_bytes_to((address) HotSpotJVMCI::resolve(implicitExceptionArray)->byte_at_addr(0), implicit_table_size);
}
HotSpotJVMCI::HotSpotMetaData::set_implicitExceptionBytes(JVMCIENV, metadata_handle, implicitExceptionArray);
return result;
#else
JVMCI_THROW_MSG_0(InternalError, "unimplemented");
#endif
C2V_END
C2V_VMENTRY(void, resetCompilationStatistics, (JNIEnv* env, jobject))
JVMCICompiler* compiler = JVMCICompiler::instance(true, CHECK);
CompilerStatistics* stats = compiler->stats();
stats->_standard.reset();
stats->_osr.reset();
C2V_END
C2V_VMENTRY_NULL(jobject, disassembleCodeBlob, (JNIEnv* env, jobject, jobject installedCode))
HandleMark hm;
if (installedCode == NULL) {
JVMCI_THROW_MSG_NULL(NullPointerException, "installedCode is null");
}
JVMCIObject installedCodeObject = JVMCIENV->wrap(installedCode);
CodeBlob* cb = JVMCIENV->asCodeBlob(installedCodeObject);
if (cb == NULL) {
return NULL;
}
// We don't want the stringStream buffer to resize during disassembly as it
// uses scoped resource memory. If a nested function called during disassembly uses
// a ResourceMark and the buffer expands within the scope of the mark,
// the buffer becomes garbage when that scope is exited. Experience shows that
// the disassembled code is typically about 10x the code size so a fixed buffer
// sized to 20x code size plus a fixed amount for header info should be sufficient.
int bufferSize = cb->code_size() * 20 + 1024;
char* buffer = NEW_RESOURCE_ARRAY(char, bufferSize);
stringStream st(buffer, bufferSize);
if (cb->is_nmethod()) {
nmethod* nm = (nmethod*) cb;
if (!nm->is_alive()) {
return NULL;
}
}
Disassembler::decode(cb, &st);
if (st.size() <= 0) {
return NULL;
}
JVMCIObject result = JVMCIENV->create_string(st.as_string(), JVMCI_CHECK_NULL);
return JVMCIENV->get_jobject(result);
C2V_END
C2V_VMENTRY_NULL(jobject, getStackTraceElement, (JNIEnv* env, jobject, jobject jvmci_method, int bci))
HandleMark hm;
methodHandle method = JVMCIENV->asMethod(jvmci_method);
JVMCIObject element = JVMCIENV->new_StackTraceElement(method, bci, JVMCI_CHECK_NULL);
return JVMCIENV->get_jobject(element);
C2V_END
C2V_VMENTRY_NULL(jobject, executeHotSpotNmethod, (JNIEnv* env, jobject, jobject args, jobject hs_nmethod))
// The incoming arguments array would have to contain JavaConstants instead of regular objects
// and the return value would have to be wrapped as a JavaConstant.
requireInHotSpot("executeHotSpotNmethod", JVMCI_CHECK_NULL);
HandleMark hm;
JVMCIObject nmethod_mirror = JVMCIENV->wrap(hs_nmethod);
nmethod* nm = JVMCIENV->asNmethod(nmethod_mirror);
if (nm == NULL) {
JVMCI_THROW_NULL(InvalidInstalledCodeException);
}
methodHandle mh = nm->method();
Symbol* signature = mh->signature();
JavaCallArguments jca(mh->size_of_parameters());
JavaArgumentUnboxer jap(signature, &jca, (arrayOop) JNIHandles::resolve(args), mh->is_static());
JavaValue result(jap.get_ret_type());
jca.set_alternative_target(nm);
JavaCalls::call(&result, mh, &jca, CHECK_NULL);
if (jap.get_ret_type() == T_VOID) {
return NULL;
} else if (jap.get_ret_type() == T_OBJECT || jap.get_ret_type() == T_ARRAY) {
return JNIHandles::make_local((oop) result.get_jobject());
} else {
jvalue *value = (jvalue *) result.get_value_addr();
// Narrow the value down if required (Important on big endian machines)
switch (jap.get_ret_type()) {
case T_BOOLEAN:
value->z = (jboolean) value->i;
break;
case T_BYTE:
value->b = (jbyte) value->i;
break;
case T_CHAR:
value->c = (jchar) value->i;
break;
case T_SHORT:
value->s = (jshort) value->i;
break;
default:
break;
}
JVMCIObject o = JVMCIENV->create_box(jap.get_ret_type(), value, JVMCI_CHECK_NULL);
return JVMCIENV->get_jobject(o);
}
C2V_END
C2V_VMENTRY_NULL(jlongArray, getLineNumberTable, (JNIEnv* env, jobject, jobject jvmci_method))
Method* method = JVMCIENV->asMethod(jvmci_method);
if (!method->has_linenumber_table()) {
return NULL;
}
u2 num_entries = 0;
CompressedLineNumberReadStream streamForSize(method->compressed_linenumber_table());
while (streamForSize.read_pair()) {
num_entries++;
}
CompressedLineNumberReadStream stream(method->compressed_linenumber_table());
JVMCIPrimitiveArray result = JVMCIENV->new_longArray(2 * num_entries, JVMCI_CHECK_NULL);
int i = 0;
jlong value;
while (stream.read_pair()) {
value = ((long) stream.bci());
JVMCIENV->put_long_at(result, i, value);
value = ((long) stream.line());
JVMCIENV->put_long_at(result, i + 1, value);
i += 2;
}
return (jlongArray) JVMCIENV->get_jobject(result);
C2V_END
C2V_VMENTRY_0(jlong, getLocalVariableTableStart, (JNIEnv* env, jobject, jobject jvmci_method))
Method* method = JVMCIENV->asMethod(jvmci_method);
if (!method->has_localvariable_table()) {
return 0;
}
return (jlong) (address) method->localvariable_table_start();
C2V_END
C2V_VMENTRY_0(jint, getLocalVariableTableLength, (JNIEnv* env, jobject, jobject jvmci_method))
Method* method = JVMCIENV->asMethod(jvmci_method);
return method->localvariable_table_length();
C2V_END
C2V_VMENTRY(void, reprofile, (JNIEnv* env, jobject, jobject jvmci_method))
Method* method = JVMCIENV->asMethod(jvmci_method);
MethodCounters* mcs = method->method_counters();
if (mcs != NULL) {
mcs->clear_counters();
}
NOT_PRODUCT(method->set_compiled_invocation_count(0));
CompiledMethod* code = method->code();
if (code != NULL) {
code->make_not_entrant();
}
MethodData* method_data = method->method_data();
if (method_data == NULL) {
ClassLoaderData* loader_data = method->method_holder()->class_loader_data();
method_data = MethodData::allocate(loader_data, method, CHECK);
method->set_method_data(method_data);
} else {
method_data->initialize();
}
C2V_END
C2V_VMENTRY(void, invalidateHotSpotNmethod, (JNIEnv* env, jobject, jobject hs_nmethod))
JVMCIObject nmethod_mirror = JVMCIENV->wrap(hs_nmethod);
JVMCIENV->invalidate_nmethod_mirror(nmethod_mirror, JVMCI_CHECK);
C2V_END
C2V_VMENTRY_NULL(jobject, readUncompressedOop, (JNIEnv* env, jobject, jlong addr))
oop ret = RawAccess<>::oop_load((oop*)(address)addr);
return JVMCIENV->get_jobject(JVMCIENV->get_object_constant(ret));
C2V_END
C2V_VMENTRY_NULL(jlongArray, collectCounters, (JNIEnv* env, jobject))
// Returns a zero length array if counters aren't enabled
JVMCIPrimitiveArray array = JVMCIENV->new_longArray(JVMCICounterSize, JVMCI_CHECK_NULL);
if (JVMCICounterSize > 0) {
jlong* temp_array = NEW_RESOURCE_ARRAY(jlong, JVMCICounterSize);
JavaThread::collect_counters(temp_array, JVMCICounterSize);
JVMCIENV->copy_longs_from(temp_array, array, 0, JVMCICounterSize);
}
return (jlongArray) JVMCIENV->get_jobject(array);
C2V_END
C2V_VMENTRY_0(jint, getCountersSize, (JNIEnv* env, jobject))
return (jint) JVMCICounterSize;
C2V_END
C2V_VMENTRY_0(jboolean, setCountersSize, (JNIEnv* env, jobject, jint new_size))
return JavaThread::resize_all_jvmci_counters(new_size);
C2V_END
C2V_VMENTRY_0(jint, allocateCompileId, (JNIEnv* env, jobject, jobject jvmci_method, int entry_bci))
HandleMark hm;
if (jvmci_method == NULL) {
JVMCI_THROW_0(NullPointerException);
}
Method* method = JVMCIENV->asMethod(jvmci_method);
if (entry_bci >= method->code_size() || entry_bci < -1) {
JVMCI_THROW_MSG_0(IllegalArgumentException, err_msg("Unexpected bci %d", entry_bci));
}
return CompileBroker::assign_compile_id_unlocked(THREAD, method, entry_bci);
C2V_END
C2V_VMENTRY_0(jboolean, isMature, (JNIEnv* env, jobject, jlong metaspace_method_data))
MethodData* mdo = JVMCIENV->asMethodData(metaspace_method_data);
return mdo != NULL && mdo->is_mature();
C2V_END
C2V_VMENTRY_0(jboolean, hasCompiledCodeForOSR, (JNIEnv* env, jobject, jobject jvmci_method, int entry_bci, int comp_level))
Method* method = JVMCIENV->asMethod(jvmci_method);
return method->lookup_osr_nmethod_for(entry_bci, comp_level, true) != NULL;
C2V_END
C2V_VMENTRY_NULL(jobject, getSymbol, (JNIEnv* env, jobject, jlong symbol))
JVMCIObject sym = JVMCIENV->create_string((Symbol*)(address)symbol, JVMCI_CHECK_NULL);
return JVMCIENV->get_jobject(sym);
C2V_END
bool matches(jobjectArray methods, Method* method, JVMCIEnv* JVMCIENV) {
objArrayOop methods_oop = (objArrayOop) JNIHandles::resolve(methods);
for (int i = 0; i < methods_oop->length(); i++) {
oop resolved = methods_oop->obj_at(i);
if ((resolved->klass() == HotSpotJVMCI::HotSpotResolvedJavaMethodImpl::klass()) && HotSpotJVMCI::asMethod(JVMCIENV, resolved) == method) {
return true;
}
}
return false;
}
void call_interface(JavaValue* result, Klass* spec_klass, Symbol* name, Symbol* signature, JavaCallArguments* args, TRAPS) {
CallInfo callinfo;
Handle receiver = args->receiver();
Klass* recvrKlass = receiver.is_null() ? (Klass*)NULL : receiver->klass();
LinkInfo link_info(spec_klass, name, signature);
LinkResolver::resolve_interface_call(
callinfo, receiver, recvrKlass, link_info, true, CHECK);
methodHandle method = callinfo.selected_method();
assert(method.not_null(), "should have thrown exception");
// Invoke the method
JavaCalls::call(result, method, args, CHECK);
}
C2V_VMENTRY_NULL(jobject, iterateFrames, (JNIEnv* env, jobject compilerToVM, jobjectArray initial_methods, jobjectArray match_methods, jint initialSkip, jobject visitor_handle))
if (!thread->has_last_Java_frame()) {
return NULL;
}
Handle visitor(THREAD, JNIHandles::resolve_non_null(visitor_handle));
requireInHotSpot("iterateFrames", JVMCI_CHECK_NULL);
HotSpotJVMCI::HotSpotStackFrameReference::klass()->initialize(CHECK_NULL);
Handle frame_reference = HotSpotJVMCI::HotSpotStackFrameReference::klass()->allocate_instance_handle(CHECK_NULL);
StackFrameStream fst(thread);
jobjectArray methods = initial_methods;
int frame_number = 0;
vframe* vf = vframe::new_vframe(fst.current(), fst.register_map(), thread);
while (true) {
// look for the given method
bool realloc_called = false;
while (true) {
StackValueCollection* locals = NULL;
if (vf->is_compiled_frame()) {
// compiled method frame
compiledVFrame* cvf = compiledVFrame::cast(vf);
if (methods == NULL || matches(methods, cvf->method(), JVMCIENV)) {
if (initialSkip > 0) {
initialSkip--;
} else {
ScopeDesc* scope = cvf->scope();
// native wrappers do not have a scope
if (scope != NULL && scope->objects() != NULL) {
GrowableArray<ScopeValue*>* objects;
if (!realloc_called) {
objects = scope->objects();
} else {
// some object might already have been re-allocated, only reallocate the non-allocated ones
objects = new GrowableArray<ScopeValue*>(scope->objects()->length());
for (int i = 0; i < scope->objects()->length(); i++) {
ObjectValue* sv = (ObjectValue*) scope->objects()->at(i);
if (sv->value().is_null()) {
objects->append(sv);
}
}
}
bool realloc_failures = Deoptimization::realloc_objects(thread, fst.current(), fst.register_map(), objects, CHECK_NULL);
Deoptimization::reassign_fields(fst.current(), fst.register_map(), objects, realloc_failures, false);
realloc_called = true;
GrowableArray<ScopeValue*>* local_values = scope->locals();
assert(local_values != NULL, "NULL locals");
typeArrayOop array_oop = oopFactory::new_boolArray(local_values->length(), CHECK_NULL);
typeArrayHandle array(THREAD, array_oop);
for (int i = 0; i < local_values->length(); i++) {
ScopeValue* value = local_values->at(i);
if (value->is_object()) {
array->bool_at_put(i, true);
}
}
HotSpotJVMCI::HotSpotStackFrameReference::set_localIsVirtual(JVMCIENV, frame_reference(), array());
} else {
HotSpotJVMCI::HotSpotStackFrameReference::set_localIsVirtual(JVMCIENV, frame_reference(), NULL);
}
locals = cvf->locals();
HotSpotJVMCI::HotSpotStackFrameReference::set_bci(JVMCIENV, frame_reference(), cvf->bci());
JVMCIObject method = JVMCIENV->get_jvmci_method(cvf->method(), JVMCI_CHECK_NULL);
HotSpotJVMCI::HotSpotStackFrameReference::set_method(JVMCIENV, frame_reference(), JNIHandles::resolve(method.as_jobject()));
}
}
} else if (vf->is_interpreted_frame()) {
// interpreted method frame
interpretedVFrame* ivf = interpretedVFrame::cast(vf);
if (methods == NULL || matches(methods, ivf->method(), JVMCIENV)) {
if (initialSkip > 0) {
initialSkip--;
} else {
locals = ivf->locals();
HotSpotJVMCI::HotSpotStackFrameReference::set_bci(JVMCIENV, frame_reference(), ivf->bci());
JVMCIObject method = JVMCIENV->get_jvmci_method(ivf->method(), JVMCI_CHECK_NULL);
HotSpotJVMCI::HotSpotStackFrameReference::set_method(JVMCIENV, frame_reference(), JNIHandles::resolve(method.as_jobject()));
HotSpotJVMCI::HotSpotStackFrameReference::set_localIsVirtual(JVMCIENV, frame_reference(), NULL);
}
}
}
// locals != NULL means that we found a matching frame and result is already partially initialized
if (locals != NULL) {
methods = match_methods;
HotSpotJVMCI::HotSpotStackFrameReference::set_compilerToVM(JVMCIENV, frame_reference(), JNIHandles::resolve(compilerToVM));
HotSpotJVMCI::HotSpotStackFrameReference::set_stackPointer(JVMCIENV, frame_reference(), (jlong) fst.current()->sp());
HotSpotJVMCI::HotSpotStackFrameReference::set_frameNumber(JVMCIENV, frame_reference(), frame_number);
// initialize the locals array
objArrayOop array_oop = oopFactory::new_objectArray(locals->size(), CHECK_NULL);
objArrayHandle array(THREAD, array_oop);
for (int i = 0; i < locals->size(); i++) {
StackValue* var = locals->at(i);
if (var->type() == T_OBJECT) {
array->obj_at_put(i, locals->at(i)->get_obj()());
}
}
HotSpotJVMCI::HotSpotStackFrameReference::set_locals(JVMCIENV, frame_reference(), array());
HotSpotJVMCI::HotSpotStackFrameReference::set_objectsMaterialized(JVMCIENV, frame_reference(), JNI_FALSE);
JavaValue result(T_OBJECT);
JavaCallArguments args(visitor);
args.push_oop(frame_reference);
call_interface(&result, HotSpotJVMCI::InspectedFrameVisitor::klass(), vmSymbols::visitFrame_name(), vmSymbols::visitFrame_signature(), &args, CHECK_NULL);
if (result.get_jobject() != NULL) {
return JNIHandles::make_local(thread, (oop) result.get_jobject());
}
assert(initialSkip == 0, "There should be no match before initialSkip == 0");
if (HotSpotJVMCI::HotSpotStackFrameReference::objectsMaterialized(JVMCIENV, frame_reference()) == JNI_TRUE) {
// the frame has been deoptimized, we need to re-synchronize the frame and vframe
intptr_t* stack_pointer = (intptr_t*) HotSpotJVMCI::HotSpotStackFrameReference::stackPointer(JVMCIENV, frame_reference());
fst = StackFrameStream(thread);
while (fst.current()->sp() != stack_pointer && !fst.is_done()) {
fst.next();
}
if (fst.current()->sp() != stack_pointer) {
THROW_MSG_NULL(vmSymbols::java_lang_IllegalStateException(), "stack frame not found after deopt")
}
vf = vframe::new_vframe(fst.current(), fst.register_map(), thread);
if (!vf->is_compiled_frame()) {
THROW_MSG_NULL(vmSymbols::java_lang_IllegalStateException(), "compiled stack frame expected")
}
for (int i = 0; i < frame_number; i++) {
if (vf->is_top()) {
THROW_MSG_NULL(vmSymbols::java_lang_IllegalStateException(), "vframe not found after deopt")
}
vf = vf->sender();
assert(vf->is_compiled_frame(), "Wrong frame type");
}
}
frame_reference = HotSpotJVMCI::HotSpotStackFrameReference::klass()->allocate_instance_handle(CHECK_NULL);
HotSpotJVMCI::HotSpotStackFrameReference::klass()->initialize(CHECK_NULL);
}
if (vf->is_top()) {
break;
}
frame_number++;
vf = vf->sender();
} // end of vframe loop
if (fst.is_done()) {
break;
}
fst.next();
vf = vframe::new_vframe(fst.current(), fst.register_map(), thread);
frame_number = 0;
} // end of frame loop
// the end was reached without finding a matching method
return NULL;
C2V_END
C2V_VMENTRY(void, resolveInvokeDynamicInPool, (JNIEnv* env, jobject, jobject jvmci_constant_pool, jint index))
constantPoolHandle cp = JVMCIENV->asConstantPool(jvmci_constant_pool);
CallInfo callInfo;
LinkResolver::resolve_invoke(callInfo, Handle(), cp, index, Bytecodes::_invokedynamic, CHECK);
ConstantPoolCacheEntry* cp_cache_entry = cp->invokedynamic_cp_cache_entry_at(index);
cp_cache_entry->set_dynamic_call(cp, callInfo);
C2V_END
C2V_VMENTRY(void, resolveInvokeHandleInPool, (JNIEnv* env, jobject, jobject jvmci_constant_pool, jint index))
constantPoolHandle cp = JVMCIENV->asConstantPool(jvmci_constant_pool);
Klass* holder = cp->klass_ref_at(index, CHECK);
Symbol* name = cp->name_ref_at(index);
if (MethodHandles::is_signature_polymorphic_name(holder, name)) {
CallInfo callInfo;
LinkResolver::resolve_invoke(callInfo, Handle(), cp, index, Bytecodes::_invokehandle, CHECK);
ConstantPoolCacheEntry* cp_cache_entry = cp->cache()->entry_at(cp->decode_cpcache_index(index));
cp_cache_entry->set_method_handle(cp, callInfo);
}
C2V_END
C2V_VMENTRY_0(jint, isResolvedInvokeHandleInPool, (JNIEnv* env, jobject, jobject jvmci_constant_pool, jint index))
constantPoolHandle cp = JVMCIENV->asConstantPool(jvmci_constant_pool);
ConstantPoolCacheEntry* cp_cache_entry = cp->cache()->entry_at(cp->decode_cpcache_index(index));
if (cp_cache_entry->is_resolved(Bytecodes::_invokehandle)) {
// MethodHandle.invoke* --> LambdaForm?
ResourceMark rm;
LinkInfo link_info(cp, index, CATCH);
Klass* resolved_klass = link_info.resolved_klass();
Symbol* name_sym = cp->name_ref_at(index);
vmassert(MethodHandles::is_method_handle_invoke_name(resolved_klass, name_sym), "!");
vmassert(MethodHandles::is_signature_polymorphic_name(resolved_klass, name_sym), "!");
methodHandle adapter_method(cp_cache_entry->f1_as_method());
methodHandle resolved_method(adapter_method);
// Can we treat it as a regular invokevirtual?
if (resolved_method->method_holder() == resolved_klass && resolved_method->name() == name_sym) {
vmassert(!resolved_method->is_static(),"!");
vmassert(MethodHandles::is_signature_polymorphic_method(resolved_method()),"!");
vmassert(!MethodHandles::is_signature_polymorphic_static(resolved_method->intrinsic_id()), "!");
vmassert(cp_cache_entry->appendix_if_resolved(cp) == NULL, "!");
methodHandle m(LinkResolver::linktime_resolve_virtual_method_or_null(link_info));
vmassert(m == resolved_method, "!!");
return -1;
}
return Bytecodes::_invokevirtual;
}
if (cp_cache_entry->is_resolved(Bytecodes::_invokedynamic)) {
return Bytecodes::_invokedynamic;
}
return -1;
C2V_END
C2V_VMENTRY_NULL(jobject, getSignaturePolymorphicHolders, (JNIEnv* env, jobject))
JVMCIObjectArray holders = JVMCIENV->new_String_array(2, JVMCI_CHECK_NULL);
JVMCIObject mh = JVMCIENV->create_string("Ljava/lang/invoke/MethodHandle;", JVMCI_CHECK_NULL);
JVMCIObject vh = JVMCIENV->create_string("Ljava/lang/invoke/VarHandle;", JVMCI_CHECK_NULL);
JVMCIENV->put_object_at(holders, 0, mh);
JVMCIENV->put_object_at(holders, 1, vh);
return JVMCIENV->get_jobject(holders);
C2V_END
C2V_VMENTRY_0(jboolean, shouldDebugNonSafepoints, (JNIEnv* env, jobject))
//see compute_recording_non_safepoints in debugInfroRec.cpp
if (JvmtiExport::should_post_compiled_method_load() && FLAG_IS_DEFAULT(DebugNonSafepoints)) {
return true;
}
return DebugNonSafepoints;
C2V_END
// public native void materializeVirtualObjects(HotSpotStackFrameReference stackFrame, boolean invalidate);
C2V_VMENTRY(void, materializeVirtualObjects, (JNIEnv* env, jobject, jobject _hs_frame, bool invalidate))
JVMCIObject hs_frame = JVMCIENV->wrap(_hs_frame);
if (hs_frame.is_null()) {
JVMCI_THROW_MSG(NullPointerException, "stack frame is null");
}
requireInHotSpot("materializeVirtualObjects", JVMCI_CHECK);
JVMCIENV->HotSpotStackFrameReference_initialize(JVMCI_CHECK);
// look for the given stack frame
StackFrameStream fst(thread);
intptr_t* stack_pointer = (intptr_t*) JVMCIENV->get_HotSpotStackFrameReference_stackPointer(hs_frame);
while (fst.current()->sp() != stack_pointer && !fst.is_done()) {
fst.next();
}
if (fst.current()->sp() != stack_pointer) {
JVMCI_THROW_MSG(IllegalStateException, "stack frame not found");
}
if (invalidate) {
if (!fst.current()->is_compiled_frame()) {
JVMCI_THROW_MSG(IllegalStateException, "compiled stack frame expected");
}
assert(fst.current()->cb()->is_nmethod(), "nmethod expected");
((nmethod*) fst.current()->cb())->make_not_entrant();
}
Deoptimization::deoptimize(thread, *fst.current(), fst.register_map(), Deoptimization::Reason_none);
// look for the frame again as it has been updated by deopt (pc, deopt state...)
StackFrameStream fstAfterDeopt(thread);
while (fstAfterDeopt.current()->sp() != stack_pointer && !fstAfterDeopt.is_done()) {
fstAfterDeopt.next();
}
if (fstAfterDeopt.current()->sp() != stack_pointer) {
JVMCI_THROW_MSG(IllegalStateException, "stack frame not found after deopt");
}
vframe* vf = vframe::new_vframe(fstAfterDeopt.current(), fstAfterDeopt.register_map(), thread);
if (!vf->is_compiled_frame()) {
JVMCI_THROW_MSG(IllegalStateException, "compiled stack frame expected");
}
GrowableArray<compiledVFrame*>* virtualFrames = new GrowableArray<compiledVFrame*>(10);
while (true) {
assert(vf->is_compiled_frame(), "Wrong frame type");
virtualFrames->push(compiledVFrame::cast(vf));
if (vf->is_top()) {
break;
}
vf = vf->sender();
}
int last_frame_number = JVMCIENV->get_HotSpotStackFrameReference_frameNumber(hs_frame);
if (last_frame_number >= virtualFrames->length()) {
JVMCI_THROW_MSG(IllegalStateException, "invalid frame number");
}
// Reallocate the non-escaping objects and restore their fields.
assert (virtualFrames->at(last_frame_number)->scope() != NULL,"invalid scope");
GrowableArray<ScopeValue*>* objects = virtualFrames->at(last_frame_number)->scope()->objects();
if (objects == NULL) {
// no objects to materialize
return;
}
bool realloc_failures = Deoptimization::realloc_objects(thread, fstAfterDeopt.current(), fstAfterDeopt.register_map(), objects, CHECK);
Deoptimization::reassign_fields(fstAfterDeopt.current(), fstAfterDeopt.register_map(), objects, realloc_failures, false);
for (int frame_index = 0; frame_index < virtualFrames->length(); frame_index++) {
compiledVFrame* cvf = virtualFrames->at(frame_index);
GrowableArray<ScopeValue*>* scopeLocals = cvf->scope()->locals();
StackValueCollection* locals = cvf->locals();
if (locals != NULL) {
for (int i2 = 0; i2 < locals->size(); i2++) {
StackValue* var = locals->at(i2);
if (var->type() == T_OBJECT && scopeLocals->at(i2)->is_object()) {
jvalue val;
val.l = (jobject) locals->at(i2)->get_obj()();
cvf->update_local(T_OBJECT, i2, val);
}
}
}
GrowableArray<ScopeValue*>* scopeExpressions = cvf->scope()->expressions();
StackValueCollection* expressions = cvf->expressions();
if (expressions != NULL) {
for (int i2 = 0; i2 < expressions->size(); i2++) {
StackValue* var = expressions->at(i2);
if (var->type() == T_OBJECT && scopeExpressions->at(i2)->is_object()) {
jvalue val;
val.l = (jobject) expressions->at(i2)->get_obj()();
cvf->update_stack(T_OBJECT, i2, val);
}
}
}
GrowableArray<MonitorValue*>* scopeMonitors = cvf->scope()->monitors();
GrowableArray<MonitorInfo*>* monitors = cvf->monitors();
if (monitors != NULL) {
for (int i2 = 0; i2 < monitors->length(); i2++) {
cvf->update_monitor(i2, monitors->at(i2));
}
}
}
// all locals are materialized by now
JVMCIENV->set_HotSpotStackFrameReference_localIsVirtual(hs_frame, NULL);
// update the locals array
JVMCIObjectArray array = JVMCIENV->get_HotSpotStackFrameReference_locals(hs_frame);
StackValueCollection* locals = virtualFrames->at(last_frame_number)->locals();
for (int i = 0; i < locals->size(); i++) {
StackValue* var = locals->at(i);
if (var->type() == T_OBJECT) {
JVMCIENV->put_object_at(array, i, HotSpotJVMCI::wrap(locals->at(i)->get_obj()()));
}
}
HotSpotJVMCI::HotSpotStackFrameReference::set_objectsMaterialized(JVMCIENV, hs_frame, JNI_TRUE);
C2V_END
// Creates a scope where the current thread is attached and detached
// from HotSpot if it wasn't already attached when entering the scope.
extern "C" void jio_printf(const char *fmt, ...);
class AttachDetach : public StackObj {
public:
bool _attached;
AttachDetach(JNIEnv* env, Thread* current_thread) {
if (current_thread == NULL) {
extern struct JavaVM_ main_vm;
JNIEnv* hotspotEnv;
jint res = main_vm.AttachCurrentThread((void**)&hotspotEnv, NULL);
_attached = res == JNI_OK;
static volatile int report_attach_error = 0;
if (res != JNI_OK && report_attach_error == 0 && Atomic::cmpxchg(1, &report_attach_error, 0) == 0) {
// Only report an attach error once
jio_printf("Warning: attaching current thread to VM failed with %d (future attach errors are suppressed)\n", res);
}
} else {
_attached = false;
}
}
~AttachDetach() {
if (_attached && get_current_thread() != NULL) {
extern struct JavaVM_ main_vm;
jint res = main_vm.DetachCurrentThread();
static volatile int report_detach_error = 0;
if (res != JNI_OK && report_detach_error == 0 && Atomic::cmpxchg(1, &report_detach_error, 0) == 0) {
// Only report an attach error once
jio_printf("Warning: detaching current thread from VM failed with %d (future attach errors are suppressed)\n", res);
}
}
}
};
C2V_VMENTRY_PREFIX(jint, writeDebugOutput, (JNIEnv* env, jobject, jbyteArray bytes, jint offset, jint length, bool flush, bool can_throw))
AttachDetach ad(env, base_thread);
bool use_tty = true;
if (base_thread == NULL) {
if (!ad._attached) {
// Can only use tty if the current thread is attached
return 0;
}
base_thread = get_current_thread();
}
JVMCITraceMark jtm("writeDebugOutput");
assert(base_thread->is_Java_thread(), "just checking");
JavaThread* thread = (JavaThread*) base_thread;
C2V_BLOCK(void, writeDebugOutput, (JNIEnv* env, jobject, jbyteArray bytes, jint offset, jint length))
if (bytes == NULL) {
if (can_throw) {
JVMCI_THROW_0(NullPointerException);
}
return -1;
}
JVMCIPrimitiveArray array = JVMCIENV->wrap(bytes);
// Check if offset and length are non negative.
if (offset < 0 || length < 0) {
if (can_throw) {
JVMCI_THROW_0(ArrayIndexOutOfBoundsException);
}
return -2;
}
// Check if the range is valid.
int array_length = JVMCIENV->get_length(array);
if ((((unsigned int) length + (unsigned int) offset) > (unsigned int) array_length)) {
if (can_throw) {
JVMCI_THROW_0(ArrayIndexOutOfBoundsException);
}
return -2;
}
jbyte buffer[O_BUFLEN];
while (length > 0) {
int copy_len = MIN2(length, (jint)O_BUFLEN);
JVMCIENV->copy_bytes_to(array, buffer, offset, copy_len);
tty->write((char*) buffer, copy_len);
length -= O_BUFLEN;
offset += O_BUFLEN;
}
if (flush) {
tty->flush();
}
return 0;
C2V_END
C2V_VMENTRY(void, flushDebugOutput, (JNIEnv* env, jobject))
tty->flush();
C2V_END
C2V_VMENTRY_0(jint, methodDataProfileDataSize, (JNIEnv* env, jobject, jlong metaspace_method_data, jint position))
MethodData* mdo = JVMCIENV->asMethodData(metaspace_method_data);
ProfileData* profile_data = mdo->data_at(position);
if (mdo->is_valid(profile_data)) {
return profile_data->size_in_bytes();
}
DataLayout* data = mdo->extra_data_base();
DataLayout* end = mdo->extra_data_limit();
for (;; data = mdo->next_extra(data)) {
assert(data < end, "moved past end of extra data");
profile_data = data->data_in();
if (mdo->dp_to_di(profile_data->dp()) == position) {
return profile_data->size_in_bytes();
}
}
JVMCI_THROW_MSG_0(IllegalArgumentException, err_msg("Invalid profile data position %d", position));
C2V_END
C2V_VMENTRY_0(jlong, getFingerprint, (JNIEnv* env, jobject, jlong metaspace_klass))
#if INCLUDE_AOT
Klass *k = (Klass*) (address) metaspace_klass;
if (k->is_instance_klass()) {
return InstanceKlass::cast(k)->get_stored_fingerprint();
} else {
return 0;
}
#else
JVMCI_THROW_MSG_0(InternalError, "unimplemented");
#endif
C2V_END
C2V_VMENTRY_NULL(jobject, getHostClass, (JNIEnv* env, jobject, jobject jvmci_type))
InstanceKlass* k = InstanceKlass::cast(JVMCIENV->asKlass(jvmci_type));
InstanceKlass* host = k->unsafe_anonymous_host();
JVMCIKlassHandle handle(THREAD, host);
JVMCIObject result = JVMCIENV->get_jvmci_type(handle, JVMCI_CHECK_NULL);
return JVMCIENV->get_jobject(result);
C2V_END
C2V_VMENTRY_NULL(jobject, getInterfaces, (JNIEnv* env, jobject, jobject jvmci_type))
if (jvmci_type == NULL) {
JVMCI_THROW_0(NullPointerException);
}
Klass* klass = JVMCIENV->asKlass(jvmci_type);
if (klass == NULL) {
JVMCI_THROW_0(NullPointerException);
}
if (!klass->is_instance_klass()) {
JVMCI_THROW_MSG_0(InternalError, err_msg("Class %s must be instance klass", klass->external_name()));
}
InstanceKlass* iklass = InstanceKlass::cast(klass);
// Regular instance klass, fill in all local interfaces
int size = iklass->local_interfaces()->length();
JVMCIObjectArray interfaces = JVMCIENV->new_HotSpotResolvedObjectTypeImpl_array(size, JVMCI_CHECK_NULL);
for (int index = 0; index < size; index++) {
JVMCIKlassHandle klass(THREAD);
Klass* k = iklass->local_interfaces()->at(index);
klass = k;
JVMCIObject type = JVMCIENV->get_jvmci_type(klass, JVMCI_CHECK_NULL);
JVMCIENV->put_object_at(interfaces, index, type);
}
return JVMCIENV->get_jobject(interfaces);
C2V_END
C2V_VMENTRY_NULL(jobject, getComponentType, (JNIEnv* env, jobject, jobject jvmci_type))
if (jvmci_type == NULL) {
JVMCI_THROW_0(NullPointerException);
}
Klass* klass = JVMCIENV->asKlass(jvmci_type);
oop mirror = klass->java_mirror();
if (java_lang_Class::is_primitive(mirror) ||
!java_lang_Class::as_Klass(mirror)->is_array_klass()) {
return NULL;
}
oop component_mirror = java_lang_Class::component_mirror(mirror);
if (component_mirror == NULL) {
return NULL;
}
Klass* component_klass = java_lang_Class::as_Klass(component_mirror);
if (component_klass != NULL) {
JVMCIKlassHandle klass_handle(THREAD);
klass_handle = component_klass;
JVMCIObject result = JVMCIENV->get_jvmci_type(klass_handle, JVMCI_CHECK_NULL);
return JVMCIENV->get_jobject(result);
}
BasicType type = java_lang_Class::primitive_type(component_mirror);
JVMCIObject result = JVMCIENV->get_jvmci_primitive_type(type);
return JVMCIENV->get_jobject(result);
C2V_END
C2V_VMENTRY(void, ensureInitialized, (JNIEnv* env, jobject, jobject jvmci_type))
if (jvmci_type == NULL) {
JVMCI_THROW(NullPointerException);
}
Klass* klass = JVMCIENV->asKlass(jvmci_type);
if (klass != NULL && klass->should_be_initialized()) {
InstanceKlass* k = InstanceKlass::cast(klass);
k->initialize(CHECK);
}
C2V_END
C2V_VMENTRY_0(jint, interpreterFrameSize, (JNIEnv* env, jobject, jobject bytecode_frame_handle))
if (bytecode_frame_handle == NULL) {
JVMCI_THROW_0(NullPointerException);
}
JVMCIObject top_bytecode_frame = JVMCIENV->wrap(bytecode_frame_handle);
JVMCIObject bytecode_frame = top_bytecode_frame;
int size = 0;
int callee_parameters = 0;
int callee_locals = 0;
Method* method = JVMCIENV->asMethod(JVMCIENV->get_BytecodePosition_method(bytecode_frame));
int extra_args = method->max_stack() - JVMCIENV->get_BytecodeFrame_numStack(bytecode_frame);
while (bytecode_frame.is_non_null()) {
int locks = JVMCIENV->get_BytecodeFrame_numLocks(bytecode_frame);
int temps = JVMCIENV->get_BytecodeFrame_numStack(bytecode_frame);
bool is_top_frame = (JVMCIENV->equals(bytecode_frame, top_bytecode_frame));
Method* method = JVMCIENV->asMethod(JVMCIENV->get_BytecodePosition_method(bytecode_frame));
int frame_size = BytesPerWord * Interpreter::size_activation(method->max_stack(),
temps + callee_parameters,
extra_args,
locks,
callee_parameters,
callee_locals,
is_top_frame);
size += frame_size;
callee_parameters = method->size_of_parameters();
callee_locals = method->max_locals();
extra_args = 0;
bytecode_frame = JVMCIENV->get_BytecodePosition_caller(bytecode_frame);
}
return size + Deoptimization::last_frame_adjust(0, callee_locals) * BytesPerWord;
C2V_END
C2V_VMENTRY(void, compileToBytecode, (JNIEnv* env, jobject, jobject lambda_form_handle))
Handle lambda_form = JVMCIENV->asConstant(JVMCIENV->wrap(lambda_form_handle), JVMCI_CHECK);
if (lambda_form->is_a(SystemDictionary::LambdaForm_klass())) {
TempNewSymbol compileToBytecode = SymbolTable::new_symbol("compileToBytecode");
JavaValue result(T_VOID);
JavaCalls::call_special(&result, lambda_form, SystemDictionary::LambdaForm_klass(), compileToBytecode, vmSymbols::void_method_signature(), CHECK);
} else {
JVMCI_THROW_MSG(IllegalArgumentException,
err_msg("Unexpected type: %s", lambda_form->klass()->external_name()))
}
C2V_END
C2V_VMENTRY_0(jint, getIdentityHashCode, (JNIEnv* env, jobject, jobject object))
Handle obj = JVMCIENV->asConstant(JVMCIENV->wrap(object), JVMCI_CHECK_0);
return obj->identity_hash();
C2V_END
C2V_VMENTRY_0(jboolean, isInternedString, (JNIEnv* env, jobject, jobject object))
Handle str = JVMCIENV->asConstant(JVMCIENV->wrap(object), JVMCI_CHECK_0);
if (!java_lang_String::is_instance(str())) {
return false;
}
int len;
jchar* name = java_lang_String::as_unicode_string(str(), len, CHECK_0);
return (StringTable::lookup(name, len) != NULL);
C2V_END
C2V_VMENTRY_NULL(jobject, unboxPrimitive, (JNIEnv* env, jobject, jobject object))
if (object == NULL) {
JVMCI_THROW_0(NullPointerException);
}
Handle box = JVMCIENV->asConstant(JVMCIENV->wrap(object), JVMCI_CHECK_NULL);
BasicType type = java_lang_boxing_object::basic_type(box());
jvalue result;
if (java_lang_boxing_object::get_value(box(), &result) == T_ILLEGAL) {
return NULL;
}
JVMCIObject boxResult = JVMCIENV->create_box(type, &result, JVMCI_CHECK_NULL);
return JVMCIENV->get_jobject(boxResult);
C2V_END
C2V_VMENTRY_NULL(jobject, boxPrimitive, (JNIEnv* env, jobject, jobject object))
if (object == NULL) {
JVMCI_THROW_0(NullPointerException);
}
JVMCIObject box = JVMCIENV->wrap(object);
BasicType type = JVMCIENV->get_box_type(box);
if (type == T_ILLEGAL) {
return NULL;
}
jvalue value = JVMCIENV->get_boxed_value(type, box);
JavaValue box_result(T_OBJECT);
JavaCallArguments jargs;
Klass* box_klass = NULL;
Symbol* box_signature = NULL;
#define BOX_CASE(bt, v, argtype, name) \
case bt: \
jargs.push_##argtype(value.v); \
box_klass = SystemDictionary::name##_klass(); \
box_signature = vmSymbols::name##_valueOf_signature(); \
break
switch (type) {
BOX_CASE(T_BOOLEAN, z, int, Boolean);
BOX_CASE(T_BYTE, b, int, Byte);
BOX_CASE(T_CHAR, c, int, Character);
BOX_CASE(T_SHORT, s, int, Short);
BOX_CASE(T_INT, i, int, Integer);
BOX_CASE(T_LONG, j, long, Long);
BOX_CASE(T_FLOAT, f, float, Float);
BOX_CASE(T_DOUBLE, d, double, Double);
default:
ShouldNotReachHere();
}
#undef BOX_CASE
JavaCalls::call_static(&box_result,
box_klass,
vmSymbols::valueOf_name(),
box_signature, &jargs, CHECK_NULL);
oop hotspot_box = (oop) box_result.get_jobject();
JVMCIObject result = JVMCIENV->get_object_constant(hotspot_box, false);
return JVMCIENV->get_jobject(result);
C2V_END
C2V_VMENTRY_NULL(jobjectArray, getDeclaredConstructors, (JNIEnv* env, jobject, jobject holder))
if (holder == NULL) {
JVMCI_THROW_0(NullPointerException);
}
Klass* klass = JVMCIENV->asKlass(holder);
if (!klass->is_instance_klass()) {
JVMCIObjectArray methods = JVMCIENV->new_ResolvedJavaMethod_array(0, JVMCI_CHECK_NULL);
return JVMCIENV->get_jobjectArray(methods);
}
InstanceKlass* iklass = InstanceKlass::cast(klass);
// Ensure class is linked
iklass->link_class(CHECK_NULL);
GrowableArray<Method*> constructors_array;
for (int i = 0; i < iklass->methods()->length(); i++) {
Method* m = iklass->methods()->at(i);
if (m->is_initializer() && !m->is_static()) {
constructors_array.append(m);
}
}
JVMCIObjectArray methods = JVMCIENV->new_ResolvedJavaMethod_array(constructors_array.length(), JVMCI_CHECK_NULL);
for (int i = 0; i < constructors_array.length(); i++) {
JVMCIObject method = JVMCIENV->get_jvmci_method(constructors_array.at(i), JVMCI_CHECK_NULL);
JVMCIENV->put_object_at(methods, i, method);
}
return JVMCIENV->get_jobjectArray(methods);
C2V_END
C2V_VMENTRY_NULL(jobjectArray, getDeclaredMethods, (JNIEnv* env, jobject, jobject holder))
if (holder == NULL) {
JVMCI_THROW_0(NullPointerException);
}
Klass* klass = JVMCIENV->asKlass(holder);
if (!klass->is_instance_klass()) {
JVMCIObjectArray methods = JVMCIENV->new_ResolvedJavaMethod_array(0, JVMCI_CHECK_NULL);
return JVMCIENV->get_jobjectArray(methods);
}
InstanceKlass* iklass = InstanceKlass::cast(klass);
// Ensure class is linked
iklass->link_class(CHECK_NULL);
GrowableArray<Method*> methods_array;
for (int i = 0; i < iklass->methods()->length(); i++) {
Method* m = iklass->methods()->at(i);
if (!m->is_initializer() && !m->is_overpass()) {
methods_array.append(m);
}
}
JVMCIObjectArray methods = JVMCIENV->new_ResolvedJavaMethod_array(methods_array.length(), JVMCI_CHECK_NULL);
for (int i = 0; i < methods_array.length(); i++) {
JVMCIObject method = JVMCIENV->get_jvmci_method(methods_array.at(i), JVMCI_CHECK_NULL);
JVMCIENV->put_object_at(methods, i, method);
}
return JVMCIENV->get_jobjectArray(methods);
C2V_END
C2V_VMENTRY_NULL(jobject, readFieldValue, (JNIEnv* env, jobject, jobject object, jobject field, jboolean is_volatile))
if (object == NULL || field == NULL) {
JVMCI_THROW_0(NullPointerException);
}
JVMCIObject field_object = JVMCIENV->wrap(field);
JVMCIObject java_type = JVMCIENV->get_HotSpotResolvedJavaFieldImpl_type(field_object);
int modifiers = JVMCIENV->get_HotSpotResolvedJavaFieldImpl_modifiers(field_object);
Klass* holder = JVMCIENV->asKlass(JVMCIENV->get_HotSpotResolvedJavaFieldImpl_holder(field_object));
if (!holder->is_instance_klass()) {
JVMCI_THROW_MSG_0(InternalError, err_msg("Holder %s must be instance klass", holder->external_name()));
}
InstanceKlass* ik = InstanceKlass::cast(holder);
BasicType constant_type;
if (JVMCIENV->isa_HotSpotResolvedPrimitiveType(java_type)) {
constant_type = JVMCIENV->kindToBasicType(JVMCIENV->get_HotSpotResolvedPrimitiveType_kind(java_type), JVMCI_CHECK_NULL);
} else {
constant_type = T_OBJECT;
}
int displacement = JVMCIENV->get_HotSpotResolvedJavaFieldImpl_offset(field_object);
fieldDescriptor fd;
if (!ik->find_local_field_from_offset(displacement, (modifiers & JVM_ACC_STATIC) != 0, &fd)) {
JVMCI_THROW_MSG_0(InternalError, err_msg("Can't find field with displacement %d", displacement));
}
JVMCIObject base = JVMCIENV->wrap(object);
Handle obj;
if (JVMCIENV->isa_HotSpotObjectConstantImpl(base)) {
obj = JVMCIENV->asConstant(base, JVMCI_CHECK_NULL);
} else if (JVMCIENV->isa_HotSpotResolvedObjectTypeImpl(base)) {
Klass* klass = JVMCIENV->asKlass(base);
obj = Handle(THREAD, klass->java_mirror());
} else {
JVMCI_THROW_MSG_NULL(IllegalArgumentException,
err_msg("Unexpected type: %s", JVMCIENV->klass_name(base)));
}
jlong value = 0;
JVMCIObject kind;
switch (constant_type) {
case T_OBJECT: {
oop object = is_volatile ? obj->obj_field_acquire(displacement) : obj->obj_field(displacement);
JVMCIObject result = JVMCIENV->get_object_constant(object);
if (result.is_null()) {
return JVMCIENV->get_jobject(JVMCIENV->get_JavaConstant_NULL_POINTER());
}
return JVMCIENV->get_jobject(result);
}
case T_FLOAT: {
float f = is_volatile ? obj->float_field_acquire(displacement) : obj->float_field(displacement);
JVMCIObject result = JVMCIENV->call_JavaConstant_forFloat(f, JVMCI_CHECK_NULL);
return JVMCIENV->get_jobject(result);
}
case T_DOUBLE: {
double f = is_volatile ? obj->double_field_acquire(displacement) : obj->double_field(displacement);
JVMCIObject result = JVMCIENV->call_JavaConstant_forDouble(f, JVMCI_CHECK_NULL);
return JVMCIENV->get_jobject(result);
}
case T_BOOLEAN: value = is_volatile ? obj->bool_field_acquire(displacement) : obj->bool_field(displacement); break;
case T_BYTE: value = is_volatile ? obj->byte_field_acquire(displacement) : obj->byte_field(displacement); break;
case T_SHORT: value = is_volatile ? obj->short_field_acquire(displacement) : obj->short_field(displacement); break;
case T_CHAR: value = is_volatile ? obj->char_field_acquire(displacement) : obj->char_field(displacement); break;
case T_INT: value = is_volatile ? obj->int_field_acquire(displacement) : obj->int_field(displacement); break;
case T_LONG: value = is_volatile ? obj->long_field_acquire(displacement) : obj->long_field(displacement); break;
default:
ShouldNotReachHere();
}
JVMCIObject result = JVMCIENV->call_PrimitiveConstant_forTypeChar(type2char(constant_type), value, JVMCI_CHECK_NULL);
return JVMCIENV->get_jobject(result);
C2V_END
C2V_VMENTRY_0(jboolean, isInstance, (JNIEnv* env, jobject, jobject holder, jobject object))
if (object == NULL || holder == NULL) {
JVMCI_THROW_0(NullPointerException);
}
Handle obj = JVMCIENV->asConstant(JVMCIENV->wrap(object), JVMCI_CHECK_0);
Klass* klass = JVMCIENV->asKlass(JVMCIENV->wrap(holder));
return obj->is_a(klass);
C2V_END
C2V_VMENTRY_0(jboolean, isAssignableFrom, (JNIEnv* env, jobject, jobject holder, jobject otherHolder))
if (holder == NULL || otherHolder == NULL) {
JVMCI_THROW_0(NullPointerException);
}
Klass* klass = JVMCIENV->asKlass(JVMCIENV->wrap(holder));
Klass* otherKlass = JVMCIENV->asKlass(JVMCIENV->wrap(otherHolder));
return otherKlass->is_subtype_of(klass);
C2V_END
C2V_VMENTRY_0(jboolean, isTrustedForIntrinsics, (JNIEnv* env, jobject, jobject holder))
if (holder == NULL) {
JVMCI_THROW_0(NullPointerException);
}
InstanceKlass* ik = InstanceKlass::cast(JVMCIENV->asKlass(JVMCIENV->wrap(holder)));
if (ik->class_loader_data()->is_builtin_class_loader_data()) {
return true;
}
return false;
C2V_END
C2V_VMENTRY_NULL(jobject, asJavaType, (JNIEnv* env, jobject, jobject object))
if (object == NULL) {
JVMCI_THROW_0(NullPointerException);
}
Handle obj = JVMCIENV->asConstant(JVMCIENV->wrap(object), JVMCI_CHECK_NULL);
if (java_lang_Class::is_instance(obj())) {
if (java_lang_Class::is_primitive(obj())) {
JVMCIObject type = JVMCIENV->get_jvmci_primitive_type(java_lang_Class::primitive_type(obj()));
return JVMCIENV->get_jobject(type);
}
Klass* klass = java_lang_Class::as_Klass(obj());
JVMCIKlassHandle klass_handle(THREAD);
klass_handle = klass;
JVMCIObject type = JVMCIENV->get_jvmci_type(klass_handle, JVMCI_CHECK_NULL);
return JVMCIENV->get_jobject(type);
}
return NULL;
C2V_END
C2V_VMENTRY_NULL(jobject, asString, (JNIEnv* env, jobject, jobject object))
if (object == NULL) {
JVMCI_THROW_0(NullPointerException);
}
Handle obj = JVMCIENV->asConstant(JVMCIENV->wrap(object), JVMCI_CHECK_NULL);
const char* str = java_lang_String::as_utf8_string(obj());
JVMCIObject result = JVMCIENV->create_string(str, JVMCI_CHECK_NULL);
return JVMCIENV->get_jobject(result);
C2V_END
C2V_VMENTRY_0(jboolean, equals, (JNIEnv* env, jobject, jobject x, jlong xHandle, jobject y, jlong yHandle))
if (x == NULL || y == NULL) {
JVMCI_THROW_0(NullPointerException);
}
return JVMCIENV->resolve_handle(xHandle) == JVMCIENV->resolve_handle(yHandle);
C2V_END
C2V_VMENTRY_NULL(jobject, getJavaMirror, (JNIEnv* env, jobject, jobject object))
if (object == NULL) {
JVMCI_THROW_0(NullPointerException);
}
JVMCIObject base_object = JVMCIENV->wrap(object);
Handle mirror;
if (JVMCIENV->isa_HotSpotResolvedObjectTypeImpl(base_object)) {
mirror = Handle(THREAD, JVMCIENV->asKlass(base_object)->java_mirror());
} else if (JVMCIENV->isa_HotSpotResolvedPrimitiveType(base_object)) {
mirror = JVMCIENV->asConstant(JVMCIENV->get_HotSpotResolvedPrimitiveType_mirror(base_object), JVMCI_CHECK_NULL);
} else {
JVMCI_THROW_MSG_NULL(IllegalArgumentException,
err_msg("Unexpected type: %s", JVMCIENV->klass_name(base_object)));
}
JVMCIObject result = JVMCIENV->get_object_constant(mirror());
return JVMCIENV->get_jobject(result);
C2V_END
C2V_VMENTRY_0(jint, getArrayLength, (JNIEnv* env, jobject, jobject x))
if (x == NULL) {
JVMCI_THROW_0(NullPointerException);
}
Handle xobj = JVMCIENV->asConstant(JVMCIENV->wrap(x), JVMCI_CHECK_0);
if (xobj->klass()->is_array_klass()) {
return arrayOop(xobj())->length();
}
return -1;
C2V_END
C2V_VMENTRY_NULL(jobject, readArrayElement, (JNIEnv* env, jobject, jobject x, int index))
if (x == NULL) {
JVMCI_THROW_0(NullPointerException);
}
Handle xobj = JVMCIENV->asConstant(JVMCIENV->wrap(x), JVMCI_CHECK_NULL);
if (xobj->klass()->is_array_klass()) {
arrayOop array = arrayOop(xobj());
BasicType element_type = ArrayKlass::cast(array->klass())->element_type();
if (index < 0 || index >= array->length()) {
return NULL;
}
JVMCIObject result;
if (element_type == T_OBJECT) {
result = JVMCIENV->get_object_constant(objArrayOop(xobj())->obj_at(index));
if (result.is_null()) {
result = JVMCIENV->get_JavaConstant_NULL_POINTER();
}
} else {
jvalue value;
switch (element_type) {
case T_DOUBLE: value.d = typeArrayOop(xobj())->double_at(index); break;
case T_FLOAT: value.f = typeArrayOop(xobj())->float_at(index); break;
case T_LONG: value.j = typeArrayOop(xobj())->long_at(index); break;
case T_INT: value.i = typeArrayOop(xobj())->int_at(index); break;
case T_SHORT: value.s = typeArrayOop(xobj())->short_at(index); break;
case T_CHAR: value.c = typeArrayOop(xobj())->char_at(index); break;
case T_BYTE: value.b = typeArrayOop(xobj())->byte_at(index); break;
case T_BOOLEAN: value.z = typeArrayOop(xobj())->byte_at(index) & 1; break;
default: ShouldNotReachHere();
}
result = JVMCIENV->create_box(element_type, &value, JVMCI_CHECK_NULL);
}
assert(!result.is_null(), "must have a value");
return JVMCIENV->get_jobject(result);
}
return NULL;;
C2V_END
C2V_VMENTRY_0(jint, arrayBaseOffset, (JNIEnv* env, jobject, jobject kind))
if (kind == NULL) {
JVMCI_THROW_0(NullPointerException);
}
BasicType type = JVMCIENV->kindToBasicType(JVMCIENV->wrap(kind), JVMCI_CHECK_0);
return arrayOopDesc::header_size(type) * HeapWordSize;
C2V_END
C2V_VMENTRY_0(jint, arrayIndexScale, (JNIEnv* env, jobject, jobject kind))
if (kind == NULL) {
JVMCI_THROW_0(NullPointerException);
}
BasicType type = JVMCIENV->kindToBasicType(JVMCIENV->wrap(kind), JVMCI_CHECK_0);
return type2aelembytes(type);
C2V_END
C2V_VMENTRY_0(jbyte, getByte, (JNIEnv* env, jobject, jobject x, long displacement))
if (x == NULL) {
JVMCI_THROW_0(NullPointerException);
}
Handle xobj = JVMCIENV->asConstant(JVMCIENV->wrap(x), JVMCI_CHECK_0);
return xobj->byte_field(displacement);
}
C2V_VMENTRY_0(jshort, getShort, (JNIEnv* env, jobject, jobject x, long displacement))
if (x == NULL) {
JVMCI_THROW_0(NullPointerException);
}
Handle xobj = JVMCIENV->asConstant(JVMCIENV->wrap(x), JVMCI_CHECK_0);
return xobj->short_field(displacement);
}
C2V_VMENTRY_0(jint, getInt, (JNIEnv* env, jobject, jobject x, long displacement))
if (x == NULL) {
JVMCI_THROW_0(NullPointerException);
}
Handle xobj = JVMCIENV->asConstant(JVMCIENV->wrap(x), JVMCI_CHECK_0);
return xobj->int_field(displacement);
}
C2V_VMENTRY_0(jlong, getLong, (JNIEnv* env, jobject, jobject x, long displacement))
if (x == NULL) {
JVMCI_THROW_0(NullPointerException);
}
Handle xobj = JVMCIENV->asConstant(JVMCIENV->wrap(x), JVMCI_CHECK_0);
return xobj->long_field(displacement);
}
C2V_VMENTRY_NULL(jobject, getObject, (JNIEnv* env, jobject, jobject x, long displacement))
if (x == NULL) {
JVMCI_THROW_0(NullPointerException);
}
Handle xobj = JVMCIENV->asConstant(JVMCIENV->wrap(x), JVMCI_CHECK_0);
oop res = xobj->obj_field(displacement);
JVMCIObject result = JVMCIENV->get_object_constant(res);
return JVMCIENV->get_jobject(result);
}
C2V_VMENTRY(void, deleteGlobalHandle, (JNIEnv* env, jobject, jlong h))
jobject handle = (jobject)(address)h;
if (handle != NULL) {
assert(JVMCI::is_global_handle(handle), "Invalid delete of global JNI handle");
*((oop*)handle) = NULL; // Mark the handle as deleted, allocate will reuse it
}
}
static void requireJVMCINativeLibrary(JVMCI_TRAPS) {
if (!UseJVMCINativeLibrary) {
JVMCI_THROW_MSG(UnsupportedOperationException, "JVMCI shared library is not enabled (requires -XX:+UseJVMCINativeLibrary)");
}
}
static JavaVM* requireNativeLibraryJavaVM(const char* caller, JVMCI_TRAPS) {
JavaVM* javaVM = JVMCIEnv::get_shared_library_javavm();
if (javaVM == NULL) {
JVMCI_THROW_MSG_NULL(IllegalStateException, err_msg("Require JVMCI shared library to be initialized in %s", caller));
}
return javaVM;
}
C2V_VMENTRY_NULL(jlongArray, registerNativeMethods, (JNIEnv* env, jobject, jclass mirror))
requireJVMCINativeLibrary(JVMCI_CHECK_NULL);
requireInHotSpot("registerNativeMethods", JVMCI_CHECK_NULL);
void* shared_library = JVMCIEnv::get_shared_library_handle();
if (shared_library == NULL) {
// Ensure the JVMCI shared library runtime is initialized.
JVMCIEnv __peer_jvmci_env__(thread, false, __FILE__, __LINE__);
JVMCIEnv* peerEnv = &__peer_jvmci_env__;
HandleMark hm;
JVMCIRuntime* runtime = JVMCI::compiler_runtime();
JVMCIObject receiver = runtime->get_HotSpotJVMCIRuntime(peerEnv);
if (peerEnv->has_pending_exception()) {
peerEnv->describe_pending_exception(true);
}
shared_library = JVMCIEnv::get_shared_library_handle();
if (shared_library == NULL) {
JVMCI_THROW_MSG_0(InternalError, "Error initializing JVMCI runtime");
}
}
if (mirror == NULL) {
JVMCI_THROW_0(NullPointerException);
}
Klass* klass = java_lang_Class::as_Klass(JNIHandles::resolve(mirror));
if (klass == NULL || !klass->is_instance_klass()) {
JVMCI_THROW_MSG_0(IllegalArgumentException, "clazz is for primitive type");
}
InstanceKlass* iklass = InstanceKlass::cast(klass);
for (int i = 0; i < iklass->methods()->length(); i++) {
Method* method = iklass->methods()->at(i);
if (method->is_native()) {
// Compute argument size
int args_size = 1 // JNIEnv
+ (method->is_static() ? 1 : 0) // class for static methods
+ method->size_of_parameters(); // actual parameters
// 1) Try JNI short style
stringStream st;
char* pure_name = NativeLookup::pure_jni_name(method);
os::print_jni_name_prefix_on(&st, args_size);
st.print_raw(pure_name);
os::print_jni_name_suffix_on(&st, args_size);
char* jni_name = st.as_string();
address entry = (address) os::dll_lookup(shared_library, jni_name);
if (entry == NULL) {
// 2) Try JNI long style
st.reset();
char* long_name = NativeLookup::long_jni_name(method);
os::print_jni_name_prefix_on(&st, args_size);
st.print_raw(pure_name);
st.print_raw(long_name);
os::print_jni_name_suffix_on(&st, args_size);
char* jni_long_name = st.as_string();
entry = (address) os::dll_lookup(shared_library, jni_long_name);
if (entry == NULL) {
JVMCI_THROW_MSG_0(UnsatisfiedLinkError, err_msg("%s [neither %s nor %s exist in %s]",
method->name_and_sig_as_C_string(),
jni_name, jni_long_name, JVMCIEnv::get_shared_library_path()));
}
}
if (method->has_native_function() && entry != method->native_function()) {
JVMCI_THROW_MSG_0(UnsatisfiedLinkError, err_msg("%s [cannot re-link from " PTR_FORMAT " to " PTR_FORMAT "]",
method->name_and_sig_as_C_string(), p2i(method->native_function()), p2i(entry)));
}
method->set_native_function(entry, Method::native_bind_event_is_interesting);
if (PrintJNIResolving) {
tty->print_cr("[Dynamic-linking native method %s.%s ... JNI]",
method->method_holder()->external_name(),
method->name()->as_C_string());
}
}
}
JavaVM* javaVM = JVMCIEnv::get_shared_library_javavm();
JVMCIPrimitiveArray result = JVMCIENV->new_longArray(4, JVMCI_CHECK_NULL);
JVMCIENV->put_long_at(result, 0, (jlong) (address) javaVM);
JVMCIENV->put_long_at(result, 1, (jlong) (address) javaVM->functions->reserved0);
JVMCIENV->put_long_at(result, 2, (jlong) (address) javaVM->functions->reserved1);
JVMCIENV->put_long_at(result, 3, (jlong) (address) javaVM->functions->reserved2);
return (jlongArray) JVMCIENV->get_jobject(result);
}
C2V_VMENTRY_PREFIX(jboolean, isCurrentThreadAttached, (JNIEnv* env, jobject c2vm))
if (base_thread == NULL) {
// Called from unattached JVMCI shared library thread
return false;
}
JVMCITraceMark jtm("isCurrentThreadAttached");
assert(base_thread->is_Java_thread(), "just checking");
JavaThread* thread = (JavaThread*) base_thread;
if (thread->jni_environment() == env) {
C2V_BLOCK(jboolean, isCurrentThreadAttached, (JNIEnv* env, jobject))
requireJVMCINativeLibrary(JVMCI_CHECK_0);
JavaVM* javaVM = requireNativeLibraryJavaVM("isCurrentThreadAttached", JVMCI_CHECK_0);
JNIEnv* peerEnv;
return javaVM->GetEnv((void**)&peerEnv, JNI_VERSION_1_2) == JNI_OK;
}
return true;
C2V_END
C2V_VMENTRY_PREFIX(jboolean, attachCurrentThread, (JNIEnv* env, jobject c2vm, jboolean as_daemon))
if (base_thread == NULL) {
// Called from unattached JVMCI shared library thread
extern struct JavaVM_ main_vm;
JNIEnv* hotspotEnv;
jint res = as_daemon ? main_vm.AttachCurrentThreadAsDaemon((void**)&hotspotEnv, NULL) :
main_vm.AttachCurrentThread((void**)&hotspotEnv, NULL);
if (res != JNI_OK) {
JNI_THROW_("attachCurrentThread", InternalError, err_msg("Trying to attach thread returned %d", res), false);
}
return true;
}
JVMCITraceMark jtm("attachCurrentThread");
assert(base_thread->is_Java_thread(), "just checking");\
JavaThread* thread = (JavaThread*) base_thread;
if (thread->jni_environment() == env) {
// Called from HotSpot
C2V_BLOCK(jboolean, attachCurrentThread, (JNIEnv* env, jobject, jboolean))
requireJVMCINativeLibrary(JVMCI_CHECK_0);
JavaVM* javaVM = requireNativeLibraryJavaVM("attachCurrentThread", JVMCI_CHECK_0);
JavaVMAttachArgs attach_args;
attach_args.version = JNI_VERSION_1_2;
attach_args.name = thread->name();
attach_args.group = NULL;
JNIEnv* peerEnv;
if (javaVM->GetEnv((void**)&peerEnv, JNI_VERSION_1_2) == JNI_OK) {
return false;
}
jint res = as_daemon ? javaVM->AttachCurrentThreadAsDaemon((void**)&peerEnv, &attach_args) :
javaVM->AttachCurrentThread((void**)&peerEnv, &attach_args);
if (res == JNI_OK) {
guarantee(peerEnv != NULL, "must be");
return true;
}
JVMCI_THROW_MSG_0(InternalError, err_msg("Error %d while attaching %s", res, attach_args.name));
}
// Called from JVMCI shared library
return false;
C2V_END
C2V_VMENTRY_PREFIX(void, detachCurrentThread, (JNIEnv* env, jobject c2vm))
if (base_thread == NULL) {
// Called from unattached JVMCI shared library thread
JNI_THROW("detachCurrentThread", IllegalStateException, err_msg("Cannot detach non-attached thread"));
}
JVMCITraceMark jtm("detachCurrentThread");
assert(base_thread->is_Java_thread(), "just checking");\
JavaThread* thread = (JavaThread*) base_thread;
if (thread->jni_environment() == env) {
// Called from HotSpot
C2V_BLOCK(void, detachCurrentThread, (JNIEnv* env, jobject))
requireJVMCINativeLibrary(JVMCI_CHECK);
requireInHotSpot("detachCurrentThread", JVMCI_CHECK);
JavaVM* javaVM = requireNativeLibraryJavaVM("detachCurrentThread", JVMCI_CHECK);
JNIEnv* peerEnv;
if (javaVM->GetEnv((void**)&peerEnv, JNI_VERSION_1_2) != JNI_OK) {
JVMCI_THROW_MSG(IllegalStateException, err_msg("Cannot detach non-attached thread: %s", thread->name()));
}
jint res = javaVM->DetachCurrentThread();
if (res != JNI_OK) {
JVMCI_THROW_MSG(InternalError, err_msg("Error %d while attaching %s", res, thread->name()));
}
} else {
// Called from attached JVMCI shared library thread
extern struct JavaVM_ main_vm;
jint res = main_vm.DetachCurrentThread();
if (res != JNI_OK) {
JNI_THROW("detachCurrentThread", InternalError, err_msg("Cannot detach non-attached thread"));
}
}
C2V_END
C2V_VMENTRY_0(jlong, translate, (JNIEnv* env, jobject, jobject obj_handle))
requireJVMCINativeLibrary(JVMCI_CHECK_0);
if (obj_handle == NULL) {
return 0L;
}
JVMCIEnv __peer_jvmci_env__(thread, !JVMCIENV->is_hotspot(), __FILE__, __LINE__);
JVMCIEnv* peerEnv = &__peer_jvmci_env__;
JVMCIEnv* thisEnv = JVMCIENV;
JVMCIObject obj = thisEnv->wrap(obj_handle);
JVMCIObject result;
if (thisEnv->isa_HotSpotResolvedJavaMethodImpl(obj)) {
Method* method = thisEnv->asMethod(obj);
result = peerEnv->get_jvmci_method(method, JVMCI_CHECK_0);
} else if (thisEnv->isa_HotSpotResolvedObjectTypeImpl(obj)) {
Klass* klass = thisEnv->asKlass(obj);
JVMCIKlassHandle klass_handle(THREAD);
klass_handle = klass;
result = peerEnv->get_jvmci_type(klass_handle, JVMCI_CHECK_0);
} else if (thisEnv->isa_HotSpotResolvedPrimitiveType(obj)) {
BasicType type = JVMCIENV->kindToBasicType(JVMCIENV->get_HotSpotResolvedPrimitiveType_kind(obj), JVMCI_CHECK_0);
result = peerEnv->get_jvmci_primitive_type(type);
} else if (thisEnv->isa_IndirectHotSpotObjectConstantImpl(obj) ||
thisEnv->isa_DirectHotSpotObjectConstantImpl(obj)) {
Handle constant = thisEnv->asConstant(obj, JVMCI_CHECK_0);
result = peerEnv->get_object_constant(constant());
} else if (thisEnv->isa_HotSpotNmethod(obj)) {
nmethod* nm = thisEnv->asNmethod(obj);
if (nm != NULL) {
JVMCINMethodData* data = nm->jvmci_nmethod_data();
if (data != NULL) {
if (peerEnv->is_hotspot()) {
// Only the mirror in the HotSpot heap is accessible
// through JVMCINMethodData
oop nmethod_mirror = data->get_nmethod_mirror(nm, /* phantom_ref */ true);
if (nmethod_mirror != NULL) {
result = HotSpotJVMCI::wrap(nmethod_mirror);
}
}
}
}
if (result.is_null()) {
JVMCIObject methodObject = thisEnv->get_HotSpotNmethod_method(obj);
methodHandle mh = thisEnv->asMethod(methodObject);
jboolean isDefault = thisEnv->get_HotSpotNmethod_isDefault(obj);
jlong compileIdSnapshot = thisEnv->get_HotSpotNmethod_compileIdSnapshot(obj);
JVMCIObject name_string = thisEnv->get_InstalledCode_name(obj);
const char* cstring = name_string.is_null() ? NULL : thisEnv->as_utf8_string(name_string);
// Create a new HotSpotNmethod instance in the peer runtime
result = peerEnv->new_HotSpotNmethod(mh(), cstring, isDefault, compileIdSnapshot, JVMCI_CHECK_0);
if (nm == NULL) {
// nmethod must have been unloaded
} else {
// Link the new HotSpotNmethod to the nmethod
peerEnv->initialize_installed_code(result, nm, JVMCI_CHECK_0);
// Only HotSpotNmethod instances in the HotSpot heap are tracked directly by the runtime.
if (peerEnv->is_hotspot()) {
JVMCINMethodData* data = nm->jvmci_nmethod_data();
if (data == NULL) {
JVMCI_THROW_MSG_0(IllegalArgumentException, "Cannot set HotSpotNmethod mirror for default nmethod");
}
if (data->get_nmethod_mirror(nm, /* phantom_ref */ false) != NULL) {
JVMCI_THROW_MSG_0(IllegalArgumentException, "Cannot overwrite existing HotSpotNmethod mirror for nmethod");
}
oop nmethod_mirror = HotSpotJVMCI::resolve(result);
data->set_nmethod_mirror(nm, nmethod_mirror);
}
}
}
} else {
JVMCI_THROW_MSG_0(IllegalArgumentException,
err_msg("Cannot translate object of type: %s", thisEnv->klass_name(obj)));
}
return (jlong) peerEnv->make_global(result).as_jobject();
}
C2V_VMENTRY_NULL(jobject, unhand, (JNIEnv* env, jobject, jlong obj_handle))
requireJVMCINativeLibrary(JVMCI_CHECK_NULL);
if (obj_handle == 0L) {
return NULL;
}
jobject global_handle = (jobject) obj_handle;
JVMCIObject global_handle_obj = JVMCIENV->wrap((jobject) obj_handle);
jobject result = JVMCIENV->make_local(global_handle_obj).as_jobject();
JVMCIENV->destroy_global(global_handle_obj);
return result;
}
C2V_VMENTRY(void, updateHotSpotNmethod, (JNIEnv* env, jobject, jobject code_handle))
JVMCIObject code = JVMCIENV->wrap(code_handle);
// Execute this operation for the side effect of updating the InstalledCode state
JVMCIENV->asNmethod(code);
}
C2V_VMENTRY_NULL(jbyteArray, getCode, (JNIEnv* env, jobject, jobject code_handle))
JVMCIObject code = JVMCIENV->wrap(code_handle);
CodeBlob* cb = JVMCIENV->asCodeBlob(code);
if (cb == NULL) {
return NULL;
}
int code_size = cb->code_size();
JVMCIPrimitiveArray result = JVMCIENV->new_byteArray(code_size, JVMCI_CHECK_NULL);
JVMCIENV->copy_bytes_from((jbyte*) cb->code_begin(), result, 0, code_size);
return JVMCIENV->get_jbyteArray(result);
}
C2V_VMENTRY_NULL(jobject, asReflectionExecutable, (JNIEnv* env, jobject, jobject jvmci_method))
requireInHotSpot("asReflectionExecutable", JVMCI_CHECK_NULL);
methodHandle m = JVMCIENV->asMethod(jvmci_method);
oop executable;
if (m->is_initializer()) {
if (m->is_static_initializer()) {
JVMCI_THROW_MSG_NULL(IllegalArgumentException,
"Cannot create java.lang.reflect.Method for class initializer");
}
executable = Reflection::new_constructor(m, CHECK_NULL);
} else {
executable = Reflection::new_method(m, false, CHECK_NULL);
}
return JNIHandles::make_local(THREAD, executable);
}
C2V_VMENTRY_NULL(jobject, asReflectionField, (JNIEnv* env, jobject, jobject jvmci_type, jint index))
requireInHotSpot("asReflectionField", JVMCI_CHECK_NULL);
Klass* klass = JVMCIENV->asKlass(jvmci_type);
if (!klass->is_instance_klass()) {
JVMCI_THROW_MSG_NULL(IllegalArgumentException,
err_msg("Expected non-primitive type, got %s", klass->external_name()));
}
InstanceKlass* iklass = InstanceKlass::cast(klass);
Array<u2>* fields = iklass->fields();
if (index < 0 ||index > fields->length()) {
JVMCI_THROW_MSG_NULL(IllegalArgumentException,
err_msg("Field index %d out of bounds for %s", index, klass->external_name()));
}
fieldDescriptor fd(iklass, index);
oop reflected = Reflection::new_field(&fd, CHECK_NULL);
return JNIHandles::make_local(env, reflected);
}
C2V_VMENTRY_NULL(jobjectArray, getFailedSpeculations, (JNIEnv* env, jobject, jlong failed_speculations_address, jobjectArray current))
FailedSpeculation* head = *((FailedSpeculation**)(address) failed_speculations_address);
int result_length = 0;
for (FailedSpeculation* fs = head; fs != NULL; fs = fs->next()) {
result_length++;
}
int current_length = 0;
JVMCIObjectArray current_array = NULL;
if (current != NULL) {
current_array = JVMCIENV->wrap(current);
current_length = JVMCIENV->get_length(current_array);
if (current_length == result_length) {
// No new failures
return current;
}
}
JVMCIObjectArray result = JVMCIENV->new_byte_array_array(result_length, JVMCI_CHECK_NULL);
int result_index = 0;
for (FailedSpeculation* fs = head; result_index < result_length; fs = fs->next()) {
assert(fs != NULL, "npe");
JVMCIPrimitiveArray entry;
if (result_index < current_length) {
entry = (JVMCIPrimitiveArray) JVMCIENV->get_object_at(current_array, result_index);
} else {
entry = JVMCIENV->new_byteArray(fs->data_len(), JVMCI_CHECK_NULL);
JVMCIENV->copy_bytes_from((jbyte*) fs->data(), entry, 0, fs->data_len());
}
JVMCIENV->put_object_at(result, result_index++, entry);
}
return JVMCIENV->get_jobjectArray(result);
}
C2V_VMENTRY_0(jlong, getFailedSpeculationsAddress, (JNIEnv* env, jobject, jobject jvmci_method))
methodHandle method = JVMCIENV->asMethod(jvmci_method);
MethodData* method_data = method->method_data();
if (method_data == NULL) {
ClassLoaderData* loader_data = method->method_holder()->class_loader_data();
method_data = MethodData::allocate(loader_data, method, CHECK_0);
method->set_method_data(method_data);
}
return (jlong) method_data->get_failed_speculations_address();
}
C2V_VMENTRY(void, releaseFailedSpeculations, (JNIEnv* env, jobject, jlong failed_speculations_address))
FailedSpeculation::free_failed_speculations((FailedSpeculation**)(address) failed_speculations_address);
}
C2V_VMENTRY_0(jboolean, addFailedSpeculation, (JNIEnv* env, jobject, jlong failed_speculations_address, jbyteArray speculation_obj))
JVMCIPrimitiveArray speculation_handle = JVMCIENV->wrap(speculation_obj);
int speculation_len = JVMCIENV->get_length(speculation_handle);
char* speculation = NEW_RESOURCE_ARRAY(char, speculation_len);
JVMCIENV->copy_bytes_to(speculation_handle, (jbyte*) speculation, 0, speculation_len);
return FailedSpeculation::add_failed_speculation(NULL, (FailedSpeculation**)(address) failed_speculations_address, (address) speculation, speculation_len);
}
C2V_VMENTRY(void, callSystemExit, (JNIEnv* env, jobject, jint status))
JavaValue result(T_VOID);
JavaCallArguments jargs(1);
jargs.push_int(status);
JavaCalls::call_static(&result,
SystemDictionary::System_klass(),
vmSymbols::exit_method_name(),
vmSymbols::int_void_signature(),
&jargs,
CHECK);
}
#define CC (char*) /*cast a literal from (const char*)*/
#define FN_PTR(f) CAST_FROM_FN_PTR(void*, &(c2v_ ## f))
#define STRING "Ljava/lang/String;"
#define OBJECT "Ljava/lang/Object;"
#define CLASS "Ljava/lang/Class;"
#define OBJECTCONSTANT "Ljdk/vm/ci/hotspot/HotSpotObjectConstantImpl;"
#define HANDLECONSTANT "Ljdk/vm/ci/hotspot/IndirectHotSpotObjectConstantImpl;"
#define EXECUTABLE "Ljava/lang/reflect/Executable;"
#define STACK_TRACE_ELEMENT "Ljava/lang/StackTraceElement;"
#define INSTALLED_CODE "Ljdk/vm/ci/code/InstalledCode;"
#define TARGET_DESCRIPTION "Ljdk/vm/ci/code/TargetDescription;"
#define BYTECODE_FRAME "Ljdk/vm/ci/code/BytecodeFrame;"
#define JAVACONSTANT "Ljdk/vm/ci/meta/JavaConstant;"
#define INSPECTED_FRAME_VISITOR "Ljdk/vm/ci/code/stack/InspectedFrameVisitor;"
#define RESOLVED_METHOD "Ljdk/vm/ci/meta/ResolvedJavaMethod;"
#define HS_RESOLVED_METHOD "Ljdk/vm/ci/hotspot/HotSpotResolvedJavaMethodImpl;"
#define HS_RESOLVED_KLASS "Ljdk/vm/ci/hotspot/HotSpotResolvedObjectTypeImpl;"
#define HS_RESOLVED_TYPE "Ljdk/vm/ci/hotspot/HotSpotResolvedJavaType;"
#define HS_RESOLVED_FIELD "Ljdk/vm/ci/hotspot/HotSpotResolvedJavaField;"
#define HS_INSTALLED_CODE "Ljdk/vm/ci/hotspot/HotSpotInstalledCode;"
#define HS_NMETHOD "Ljdk/vm/ci/hotspot/HotSpotNmethod;"
#define HS_CONSTANT_POOL "Ljdk/vm/ci/hotspot/HotSpotConstantPool;"
#define HS_COMPILED_CODE "Ljdk/vm/ci/hotspot/HotSpotCompiledCode;"
#define HS_CONFIG "Ljdk/vm/ci/hotspot/HotSpotVMConfig;"
#define HS_METADATA "Ljdk/vm/ci/hotspot/HotSpotMetaData;"
#define HS_STACK_FRAME_REF "Ljdk/vm/ci/hotspot/HotSpotStackFrameReference;"
#define HS_SPECULATION_LOG "Ljdk/vm/ci/hotspot/HotSpotSpeculationLog;"
#define METASPACE_OBJECT "Ljdk/vm/ci/hotspot/MetaspaceObject;"
#define REFLECTION_EXECUTABLE "Ljava/lang/reflect/Executable;"
#define REFLECTION_FIELD "Ljava/lang/reflect/Field;"
#define METASPACE_METHOD_DATA "J"
JNINativeMethod CompilerToVM::methods[] = {
{CC "getBytecode", CC "(" HS_RESOLVED_METHOD ")[B", FN_PTR(getBytecode)},
{CC "getExceptionTableStart", CC "(" HS_RESOLVED_METHOD ")J", FN_PTR(getExceptionTableStart)},
{CC "getExceptionTableLength", CC "(" HS_RESOLVED_METHOD ")I", FN_PTR(getExceptionTableLength)},
{CC "findUniqueConcreteMethod", CC "(" HS_RESOLVED_KLASS HS_RESOLVED_METHOD ")" HS_RESOLVED_METHOD, FN_PTR(findUniqueConcreteMethod)},
{CC "getImplementor", CC "(" HS_RESOLVED_KLASS ")" HS_RESOLVED_KLASS, FN_PTR(getImplementor)},
{CC "getStackTraceElement", CC "(" HS_RESOLVED_METHOD "I)" STACK_TRACE_ELEMENT, FN_PTR(getStackTraceElement)},
{CC "methodIsIgnoredBySecurityStackWalk", CC "(" HS_RESOLVED_METHOD ")Z", FN_PTR(methodIsIgnoredBySecurityStackWalk)},
{CC "setNotInlinableOrCompilable", CC "(" HS_RESOLVED_METHOD ")V", FN_PTR(setNotInlinableOrCompilable)},
{CC "isCompilable", CC "(" HS_RESOLVED_METHOD ")Z", FN_PTR(isCompilable)},
{CC "hasNeverInlineDirective", CC "(" HS_RESOLVED_METHOD ")Z", FN_PTR(hasNeverInlineDirective)},
{CC "shouldInlineMethod", CC "(" HS_RESOLVED_METHOD ")Z", FN_PTR(shouldInlineMethod)},
{CC "lookupType", CC "(" STRING HS_RESOLVED_KLASS "Z)" HS_RESOLVED_TYPE, FN_PTR(lookupType)},
{CC "getArrayType", CC "(" HS_RESOLVED_TYPE ")" HS_RESOLVED_KLASS, FN_PTR(getArrayType)},
{CC "lookupClass", CC "(" CLASS ")" HS_RESOLVED_TYPE, FN_PTR(lookupClass)},
{CC "lookupNameInPool", CC "(" HS_CONSTANT_POOL "I)" STRING, FN_PTR(lookupNameInPool)},
{CC "lookupNameAndTypeRefIndexInPool", CC "(" HS_CONSTANT_POOL "I)I", FN_PTR(lookupNameAndTypeRefIndexInPool)},
{CC "lookupSignatureInPool", CC "(" HS_CONSTANT_POOL "I)" STRING, FN_PTR(lookupSignatureInPool)},
{CC "lookupKlassRefIndexInPool", CC "(" HS_CONSTANT_POOL "I)I", FN_PTR(lookupKlassRefIndexInPool)},
{CC "lookupKlassInPool", CC "(" HS_CONSTANT_POOL "I)Ljava/lang/Object;", FN_PTR(lookupKlassInPool)},
{CC "lookupAppendixInPool", CC "(" HS_CONSTANT_POOL "I)" OBJECTCONSTANT, FN_PTR(lookupAppendixInPool)},
{CC "lookupMethodInPool", CC "(" HS_CONSTANT_POOL "IB)" HS_RESOLVED_METHOD, FN_PTR(lookupMethodInPool)},
{CC "constantPoolRemapInstructionOperandFromCache", CC "(" HS_CONSTANT_POOL "I)I", FN_PTR(constantPoolRemapInstructionOperandFromCache)},
{CC "resolvePossiblyCachedConstantInPool", CC "(" HS_CONSTANT_POOL "I)" OBJECTCONSTANT, FN_PTR(resolvePossiblyCachedConstantInPool)},
{CC "resolveTypeInPool", CC "(" HS_CONSTANT_POOL "I)" HS_RESOLVED_KLASS, FN_PTR(resolveTypeInPool)},
{CC "resolveFieldInPool", CC "(" HS_CONSTANT_POOL "I" HS_RESOLVED_METHOD "B[I)" HS_RESOLVED_KLASS, FN_PTR(resolveFieldInPool)},
{CC "resolveInvokeDynamicInPool", CC "(" HS_CONSTANT_POOL "I)V", FN_PTR(resolveInvokeDynamicInPool)},
{CC "resolveInvokeHandleInPool", CC "(" HS_CONSTANT_POOL "I)V", FN_PTR(resolveInvokeHandleInPool)},
{CC "isResolvedInvokeHandleInPool", CC "(" HS_CONSTANT_POOL "I)I", FN_PTR(isResolvedInvokeHandleInPool)},
{CC "resolveMethod", CC "(" HS_RESOLVED_KLASS HS_RESOLVED_METHOD HS_RESOLVED_KLASS ")" HS_RESOLVED_METHOD, FN_PTR(resolveMethod)},
{CC "getSignaturePolymorphicHolders", CC "()[" STRING, FN_PTR(getSignaturePolymorphicHolders)},
{CC "getVtableIndexForInterfaceMethod", CC "(" HS_RESOLVED_KLASS HS_RESOLVED_METHOD ")I", FN_PTR(getVtableIndexForInterfaceMethod)},
{CC "getClassInitializer", CC "(" HS_RESOLVED_KLASS ")" HS_RESOLVED_METHOD, FN_PTR(getClassInitializer)},
{CC "hasFinalizableSubclass", CC "(" HS_RESOLVED_KLASS ")Z", FN_PTR(hasFinalizableSubclass)},
{CC "getMaxCallTargetOffset", CC "(J)J", FN_PTR(getMaxCallTargetOffset)},
{CC "asResolvedJavaMethod", CC "(" EXECUTABLE ")" HS_RESOLVED_METHOD, FN_PTR(asResolvedJavaMethod)},
{CC "getResolvedJavaMethod", CC "(" OBJECTCONSTANT "J)" HS_RESOLVED_METHOD, FN_PTR(getResolvedJavaMethod)},
{CC "getConstantPool", CC "(" METASPACE_OBJECT ")" HS_CONSTANT_POOL, FN_PTR(getConstantPool)},
{CC "getResolvedJavaType0", CC "(Ljava/lang/Object;JZ)" HS_RESOLVED_KLASS, FN_PTR(getResolvedJavaType0)},
{CC "readConfiguration", CC "()[" OBJECT, FN_PTR(readConfiguration)},
{CC "installCode", CC "(" TARGET_DESCRIPTION HS_COMPILED_CODE INSTALLED_CODE "J[B)I", FN_PTR(installCode)},
{CC "getMetadata", CC "(" TARGET_DESCRIPTION HS_COMPILED_CODE HS_METADATA ")I", FN_PTR(getMetadata)},
{CC "resetCompilationStatistics", CC "()V", FN_PTR(resetCompilationStatistics)},
{CC "disassembleCodeBlob", CC "(" INSTALLED_CODE ")" STRING, FN_PTR(disassembleCodeBlob)},
{CC "executeHotSpotNmethod", CC "([" OBJECT HS_NMETHOD ")" OBJECT, FN_PTR(executeHotSpotNmethod)},
{CC "getLineNumberTable", CC "(" HS_RESOLVED_METHOD ")[J", FN_PTR(getLineNumberTable)},
{CC "getLocalVariableTableStart", CC "(" HS_RESOLVED_METHOD ")J", FN_PTR(getLocalVariableTableStart)},
{CC "getLocalVariableTableLength", CC "(" HS_RESOLVED_METHOD ")I", FN_PTR(getLocalVariableTableLength)},
{CC "reprofile", CC "(" HS_RESOLVED_METHOD ")V", FN_PTR(reprofile)},
{CC "invalidateHotSpotNmethod", CC "(" HS_NMETHOD ")V", FN_PTR(invalidateHotSpotNmethod)},
{CC "readUncompressedOop", CC "(J)" OBJECTCONSTANT, FN_PTR(readUncompressedOop)},
{CC "collectCounters", CC "()[J", FN_PTR(collectCounters)},
{CC "getCountersSize", CC "()I", FN_PTR(getCountersSize)},
{CC "setCountersSize", CC "(I)Z", FN_PTR(setCountersSize)},
{CC "allocateCompileId", CC "(" HS_RESOLVED_METHOD "I)I", FN_PTR(allocateCompileId)},
{CC "isMature", CC "(" METASPACE_METHOD_DATA ")Z", FN_PTR(isMature)},
{CC "hasCompiledCodeForOSR", CC "(" HS_RESOLVED_METHOD "II)Z", FN_PTR(hasCompiledCodeForOSR)},
{CC "getSymbol", CC "(J)" STRING, FN_PTR(getSymbol)},
{CC "iterateFrames", CC "([" RESOLVED_METHOD "[" RESOLVED_METHOD "I" INSPECTED_FRAME_VISITOR ")" OBJECT, FN_PTR(iterateFrames)},
{CC "materializeVirtualObjects", CC "(" HS_STACK_FRAME_REF "Z)V", FN_PTR(materializeVirtualObjects)},
{CC "shouldDebugNonSafepoints", CC "()Z", FN_PTR(shouldDebugNonSafepoints)},
{CC "writeDebugOutput", CC "([BIIZZ)I", FN_PTR(writeDebugOutput)},
{CC "flushDebugOutput", CC "()V", FN_PTR(flushDebugOutput)},
{CC "methodDataProfileDataSize", CC "(JI)I", FN_PTR(methodDataProfileDataSize)},
{CC "getFingerprint", CC "(J)J", FN_PTR(getFingerprint)},
{CC "getHostClass", CC "(" HS_RESOLVED_KLASS ")" HS_RESOLVED_KLASS, FN_PTR(getHostClass)},
{CC "interpreterFrameSize", CC "(" BYTECODE_FRAME ")I", FN_PTR(interpreterFrameSize)},
{CC "compileToBytecode", CC "(" OBJECTCONSTANT ")V", FN_PTR(compileToBytecode)},
{CC "getFlagValue", CC "(" STRING ")" OBJECT, FN_PTR(getFlagValue)},
{CC "getObjectAtAddress", CC "(J)" OBJECT, FN_PTR(getObjectAtAddress)},
{CC "getInterfaces", CC "(" HS_RESOLVED_KLASS ")[" HS_RESOLVED_KLASS, FN_PTR(getInterfaces)},
{CC "getComponentType", CC "(" HS_RESOLVED_KLASS ")" HS_RESOLVED_TYPE, FN_PTR(getComponentType)},
{CC "ensureInitialized", CC "(" HS_RESOLVED_KLASS ")V", FN_PTR(ensureInitialized)},
{CC "getIdentityHashCode", CC "(" OBJECTCONSTANT ")I", FN_PTR(getIdentityHashCode)},
{CC "isInternedString", CC "(" OBJECTCONSTANT ")Z", FN_PTR(isInternedString)},
{CC "unboxPrimitive", CC "(" OBJECTCONSTANT ")" OBJECT, FN_PTR(unboxPrimitive)},
{CC "boxPrimitive", CC "(" OBJECT ")" OBJECTCONSTANT, FN_PTR(boxPrimitive)},
{CC "getDeclaredConstructors", CC "(" HS_RESOLVED_KLASS ")[" RESOLVED_METHOD, FN_PTR(getDeclaredConstructors)},
{CC "getDeclaredMethods", CC "(" HS_RESOLVED_KLASS ")[" RESOLVED_METHOD, FN_PTR(getDeclaredMethods)},
{CC "readFieldValue", CC "(" HS_RESOLVED_KLASS HS_RESOLVED_FIELD "Z)" JAVACONSTANT, FN_PTR(readFieldValue)},
{CC "readFieldValue", CC "(" OBJECTCONSTANT HS_RESOLVED_FIELD "Z)" JAVACONSTANT, FN_PTR(readFieldValue)},
{CC "isInstance", CC "(" HS_RESOLVED_KLASS OBJECTCONSTANT ")Z", FN_PTR(isInstance)},
{CC "isAssignableFrom", CC "(" HS_RESOLVED_KLASS HS_RESOLVED_KLASS ")Z", FN_PTR(isAssignableFrom)},
{CC "isTrustedForIntrinsics", CC "(" HS_RESOLVED_KLASS ")Z", FN_PTR(isTrustedForIntrinsics)},
{CC "asJavaType", CC "(" OBJECTCONSTANT ")" HS_RESOLVED_TYPE, FN_PTR(asJavaType)},
{CC "asString", CC "(" OBJECTCONSTANT ")" STRING, FN_PTR(asString)},
{CC "equals", CC "(" OBJECTCONSTANT "J" OBJECTCONSTANT "J)Z", FN_PTR(equals)},
{CC "getJavaMirror", CC "(" HS_RESOLVED_TYPE ")" OBJECTCONSTANT, FN_PTR(getJavaMirror)},
{CC "getArrayLength", CC "(" OBJECTCONSTANT ")I", FN_PTR(getArrayLength)},
{CC "readArrayElement", CC "(" OBJECTCONSTANT "I)Ljava/lang/Object;", FN_PTR(readArrayElement)},
{CC "arrayBaseOffset", CC "(Ljdk/vm/ci/meta/JavaKind;)I", FN_PTR(arrayBaseOffset)},
{CC "arrayIndexScale", CC "(Ljdk/vm/ci/meta/JavaKind;)I", FN_PTR(arrayIndexScale)},
{CC "getByte", CC "(" OBJECTCONSTANT "J)B", FN_PTR(getByte)},
{CC "getShort", CC "(" OBJECTCONSTANT "J)S", FN_PTR(getShort)},
{CC "getInt", CC "(" OBJECTCONSTANT "J)I", FN_PTR(getInt)},
{CC "getLong", CC "(" OBJECTCONSTANT "J)J", FN_PTR(getLong)},
{CC "getObject", CC "(" OBJECTCONSTANT "J)" OBJECTCONSTANT, FN_PTR(getObject)},
{CC "deleteGlobalHandle", CC "(J)V", FN_PTR(deleteGlobalHandle)},
{CC "registerNativeMethods", CC "(" CLASS ")[J", FN_PTR(registerNativeMethods)},
{CC "isCurrentThreadAttached", CC "()Z", FN_PTR(isCurrentThreadAttached)},
{CC "attachCurrentThread", CC "(Z)Z", FN_PTR(attachCurrentThread)},
{CC "detachCurrentThread", CC "()V", FN_PTR(detachCurrentThread)},
{CC "translate", CC "(" OBJECT ")J", FN_PTR(translate)},
{CC "unhand", CC "(J)" OBJECT, FN_PTR(unhand)},
{CC "updateHotSpotNmethod", CC "(" HS_NMETHOD ")V", FN_PTR(updateHotSpotNmethod)},
{CC "getCode", CC "(" HS_INSTALLED_CODE ")[B", FN_PTR(getCode)},
{CC "asReflectionExecutable", CC "(" HS_RESOLVED_METHOD ")" REFLECTION_EXECUTABLE, FN_PTR(asReflectionExecutable)},
{CC "asReflectionField", CC "(" HS_RESOLVED_KLASS "I)" REFLECTION_FIELD, FN_PTR(asReflectionField)},
{CC "getFailedSpeculations", CC "(J[[B)[[B", FN_PTR(getFailedSpeculations)},
{CC "getFailedSpeculationsAddress", CC "(" HS_RESOLVED_METHOD ")J", FN_PTR(getFailedSpeculationsAddress)},
{CC "releaseFailedSpeculations", CC "(J)V", FN_PTR(releaseFailedSpeculations)},
{CC "addFailedSpeculation", CC "(J[B)Z", FN_PTR(addFailedSpeculation)},
{CC "callSystemExit", CC "(I)V", FN_PTR(callSystemExit)},
};
int CompilerToVM::methods_count() {
return sizeof(methods) / sizeof(JNINativeMethod);
}
| 47.676311 | 194 | 0.660474 | siweilxy |
fa2b1cd9c0e3ad13ff409683d37c865b8020b188 | 1,609 | cpp | C++ | breath/cryptography/test/digest_ordering_test.cpp | erez-o/breath | adf197b4e959beffce11e090c5e806d2ff4df38a | [
"BSD-3-Clause"
] | null | null | null | breath/cryptography/test/digest_ordering_test.cpp | erez-o/breath | adf197b4e959beffce11e090c5e806d2ff4df38a | [
"BSD-3-Clause"
] | null | null | null | breath/cryptography/test/digest_ordering_test.cpp | erez-o/breath | adf197b4e959beffce11e090c5e806d2ff4df38a | [
"BSD-3-Clause"
] | null | null | null | // ===========================================================================
// This is an open source non-commercial project.
// Dear PVS-Studio, please check it.
// PVS-Studio Static Code Analyzer for C, C++, C#, and Java:
// http://www.viva64.com
// ===========================================================================
// Copyright 2019 Gennaro Prota
//
// Licensed under the 3-Clause BSD License.
// (See accompanying file 3_CLAUSE_BSD_LICENSE.txt or
// <https://opensource.org/licenses/BSD-3-Clause>.)
// ___________________________________________________________________________
#include "breath/cryptography/digest.hpp"
#include "breath/cryptography/sha1_hasher.hpp"
#include "breath/testing/testing.hpp"
#include <map>
#include <string>
int test_digest_ordering() ;
namespace {
void
check_usability_with_map()
{
std::string const s = "test" ;
breath::sha1_hasher const
hasher( s.cbegin(), s.cend() ) ;
breath::sha1_digest const
digest( hasher ) ;
std::map< breath::sha1_digest, int, breath::sha1_digest::less >
m ;
m[ digest ] = 1 ;
}
}
int
test_digest_ordering()
{
using namespace breath ;
return test_runner::instance().run(
"Digest ordering",
{ check_usability_with_map } ) ;
}
// Local Variables:
// mode: c++
// indent-tabs-mode: nil
// c-basic-offset: 4
// End:
// vim: set ft=cpp et sts=4 sw=4:
| 28.732143 | 78 | 0.527657 | erez-o |
fa2b32d34a9ddae71b3b037a4c48e590b07ed49a | 525 | cpp | C++ | chef/aug2020/linchess.cpp | skmorningstar/Competitive-Programming | 05ba602d0fe1492d5c36267237980a9ac2f124d6 | [
"Apache-2.0"
] | null | null | null | chef/aug2020/linchess.cpp | skmorningstar/Competitive-Programming | 05ba602d0fe1492d5c36267237980a9ac2f124d6 | [
"Apache-2.0"
] | null | null | null | chef/aug2020/linchess.cpp | skmorningstar/Competitive-Programming | 05ba602d0fe1492d5c36267237980a9ac2f124d6 | [
"Apache-2.0"
] | null | null | null | #include <bits/stdc++.h>
#define ll long long int
using namespace std;
int main()
{
ios_base::sync_with_stdio(false);
cin.tie(NULL);
ll t;
cin>>t;
while(t--)
{
ll n,k;
cin>>n>>k;
bool found=false;
vector<ll> arr(n);
for(ll i{0};i<n;i++)
cin>>arr[i];
ll min=INT_MAX;
ll mini=0;
for(ll i{0};i<n;i++)
{
if(k%arr[i]==0)
{
if(k/arr[i]<min)
{
min=k/arr[i];
mini=arr[i];
}
found=true;
}
}
if(found)
cout<<mini<<endl;
else
cout<<-1<<endl;
}
return 0;
} | 12.804878 | 34 | 0.52 | skmorningstar |
fa3148e6c41374aa0763f0c4ca79a69d027d60ab | 4,245 | hpp | C++ | include/gem/dimensions_tuple.hpp | RomainBrault/Gem | 0eff3cb034a0faaca894316b72f4b005e72e0f5d | [
"MIT"
] | null | null | null | include/gem/dimensions_tuple.hpp | RomainBrault/Gem | 0eff3cb034a0faaca894316b72f4b005e72e0f5d | [
"MIT"
] | null | null | null | include/gem/dimensions_tuple.hpp | RomainBrault/Gem | 0eff3cb034a0faaca894316b72f4b005e72e0f5d | [
"MIT"
] | null | null | null | #ifndef GEM_DIMENSIONS_TUPLE_HPP_INCLUDED
#define GEM_DIMENSIONS_TUPLE_HPP_INCLUDED
#define BOOST_HANA_CONFIG_ENABLE_STRING_UDL
#include <type_traits>
#include <boost/hana/assert.hpp>
#include <boost/hana/integral_constant.hpp>
#include <boost/hana/minus.hpp>
#include <boost/hana/tuple.hpp>
#include <boost/hana/transform.hpp>
#include <boost/hana/fold.hpp>
#include <boost/hana/string.hpp>
#include <cereal/cereal.hpp>
#include <gem/litterals.hpp>
#include <gem/fwd/dimensions_tuple.hpp>
namespace gem {
gem::concepts::DimensionTuple {T_flag, n_con, n_cov, ...dims}
class DimensionTuple :
public boost::hana::tuple<dims...>
{
private:
template <gem::concepts::Dimension d1, gem::concepts::Dimension... rd>
struct gem_dim_common_type {
using type =
std::common_type_t<typename d1::dim_t,
typename gem_dim_common_type<rd...>::type>;
};
// template <gem::concepts::Dimension d1>
gem::concepts::Dimension {d1}
struct gem_dim_common_type<d1> {
using type = typename d1::dim_t;
};
public:
using type_t = DimensionTuple<T_flag, n_con, n_cov, dims...>;
using base_t = boost::hana::tuple<dims...>;
using common_t = typename gem_dim_common_type<dims...>::type;
friend class cereal::access;
public:
static constexpr BOOST_HANA_CONSTANT_CHECK_MSG(
(boost::hana::ullong_c<0> <
boost::hana::ullong_c<sizeof...(dims)>),
"At least one dimension must be specified.");
using base_t::tuple;
constexpr inline auto
value(void) const noexcept
{
constexpr auto _value = [](auto && d) {
return d.value();
};
return boost::hana::transform(*this, _value);
}
static constexpr inline auto
get_max(void) noexcept
{
constexpr auto _max = [](auto && d) {
return decltype(+d)::type::get_max();
};
return boost::hana::transform(boost::hana::tuple_t<dims...>, _max);
}
static constexpr inline auto
get_min(void) noexcept
{
constexpr auto _min = [](auto && d) {
return decltype(+d)::type::get_min();
};
return boost::hana::transform(boost::hana::tuple_t<dims...>, _min);
}
constexpr inline auto size(void) const noexcept {
constexpr auto _mult = [](auto && acc, auto && d) {
return acc * d;
};
return boost::hana::fold(*this, _mult);
}
constexpr inline auto operator [](const auto & idx) const noexcept
-> const std::enable_if_t<T_flag,
decltype(base_t::operator[] (
boost::hana::ullong_c<sizeof...(dims)> -
idx + GEM_START_IDX -
boost::hana::ullong_c<1>))> &
{
return base_t::operator[] (
boost::hana::ullong_c<sizeof...(dims)> -
idx + GEM_START_IDX -
boost::hana::ullong_c<1>);
}
constexpr inline auto operator [](const auto & idx) const noexcept
-> const std::enable_if_t<!T_flag,
decltype(base_t::operator[] (idx - GEM_START_IDX))> &
{
return base_t::operator[] (idx - GEM_START_IDX);
}
private:
template<class Archive>
auto save(Archive & archive) const -> void
{
// archive(cereal::make_size_tag(n_con));
boost::hana::ullong_c<n_con>.times.with_index(
[this, &archive](auto index) {
// TODO: make the string concatenation compile time.
archive(cereal::make_nvp("contravariant",
this->operator[] (GEM_START_IDX + index)));
});
boost::hana::ullong_c<n_cov>.times.with_index(
[this, &archive](auto index) {
// TODO: make the string concatenation compile time.
archive(cereal::make_nvp("covariant",
this->operator[] (GEM_START_IDX + boost::hana::ullong_c<n_con> + index)));
});
}
template<class Archive>
auto load(Archive & archive) -> void
{
}
};
} // namespage gem
#endif // !GEM_DIMENSIONS_TUPLE_HPP_INCLUDED
| 29.479167 | 115 | 0.582332 | RomainBrault |
fa33e807e04aa06de178bb105e4c1fbc7315ea66 | 12,601 | hpp | C++ | SPOT/Custom_Library/PhaseSpase_Cameras/PHASESPACE/include/owl.hpp | Kirkados/combined_experiment | ac502781d089a95a120f7a82317df99696842382 | [
"MIT"
] | null | null | null | SPOT/Custom_Library/PhaseSpase_Cameras/PHASESPACE/include/owl.hpp | Kirkados/combined_experiment | ac502781d089a95a120f7a82317df99696842382 | [
"MIT"
] | null | null | null | SPOT/Custom_Library/PhaseSpase_Cameras/PHASESPACE/include/owl.hpp | Kirkados/combined_experiment | ac502781d089a95a120f7a82317df99696842382 | [
"MIT"
] | 2 | 2022-03-09T07:21:17.000Z | 2022-03-10T13:20:01.000Z | /***
Copyright (c) PhaseSpace, Inc 2016
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 PHASESPACE, INC
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.
***/
// owl.hpp -*- C++ -*-
// OWL C++ API v2.0
#ifndef OWL_HPP
#define OWL_HPP
#include <cstdlib>
#include <string>
#include <vector>
#include <stdint.h>
#ifdef WIN32
#ifdef __DLL
#define OWLAPI __declspec(dllexport)
#else // !__DLL
#define OWLAPI __declspec(dllimport)
#endif // __DLL
#ifdef ERROR
#undef ERROR
#endif
#else // ! WIN32
#define OWLAPI
#endif // WIN32
#define OWL_MAX_FREQUENCY 960.0
// id is unsigned 32-bit
// time is signed 64-bit, 1 count per frame or to be specified
// pose: pos, rot -- [x y z], [s x y z]
// options format: [opt=value opt2=value1,value2 ...]
namespace OWL {
//// Data Types ////
struct Camera {
uint32_t id;
uint32_t flags;
float pose[7];
float cond;
};
struct Peak {
uint32_t id;
uint32_t flags;
int64_t time;
uint16_t camera;
uint16_t detector;
uint32_t width;
float pos;
float amp;
};
struct Plane {
uint32_t id;
uint32_t flags;
int64_t time;
uint16_t camera;
uint16_t detector;
float plane[4];
float offset;
};
struct Marker {
uint32_t id;
uint32_t flags;
int64_t time;
float x, y, z;
float cond;
};
struct Rigid {
uint32_t id;
uint32_t flags;
int64_t time;
float pose[7];
float cond;
};
struct Input {
uint64_t hw_id;
uint64_t flags;
int64_t time;
std::vector<uint8_t> data;
};
typedef std::vector<Camera> Cameras;
typedef std::vector<Peak> Peaks;
typedef std::vector<Plane> Planes;
typedef std::vector<Marker> Markers;
typedef std::vector<Rigid> Rigids;
typedef std::vector<Input> Inputs;
struct Type;
struct Variant;
struct Event;
//// Info Types ////
struct OWLAPI MarkerInfo {
uint32_t id;
uint32_t tracker_id;
std::string name;
std::string options;
MarkerInfo(uint32_t id=-1, uint32_t tracker_id=-1,
const std::string &name=std::string(),
const std::string &options=std::string());
};
struct OWLAPI TrackerInfo {
uint32_t id;
std::string type;
std::string name;
std::string options;
std::vector<uint32_t> marker_ids;
TrackerInfo(uint32_t id=-1,
const std::string &type=std::string(),
const std::string &name=std::string(),
const std::string &options=std::string(),
const std::vector<uint32_t> &marker_ids=std::vector<uint32_t>());
TrackerInfo(uint32_t id,
const std::string &type, const std::string &name,
const std::string &options, const std::string &marker_ids);
};
struct OWLAPI FilterInfo {
uint32_t period;
std::string name;
std::string options;
FilterInfo(uint32_t period=0,
const std::string &name=std::string(),
const std::string &options=std::string());
};
struct OWLAPI DeviceInfo {
uint64_t hw_id;
uint32_t id;
int64_t time;
std::string type;
std::string name;
std::string options;
std::string status;
DeviceInfo(uint64_t hw_id=0, uint32_t id=-1);
};
typedef std::vector<MarkerInfo> MarkerInfoTable;
typedef std::vector<TrackerInfo> TrackerInfoTable;
typedef std::vector<FilterInfo> FilterInfoTable;
typedef std::vector<DeviceInfo> DeviceInfoTable;
//// Context ////
class ContextData;
class OWLAPI Context {
public:
Context();
~Context();
// initialization //
int open(const std::string &name, const std::string &open_options=std::string());
bool close();
bool isOpen() const;
int initialize(const std::string &init_options=std::string());
int done(const std::string &done_options=std::string());
int streaming() const;
bool streaming(int enable);
float frequency() const;
bool frequency(float freq);
const int* timeBase() const;
bool timeBase(int num, int den);
float scale() const;
bool scale(float scale);
const float* pose() const;
bool pose(const float *pose);
std::string option(const std::string &option) const;
std::string options() const;
bool option(const std::string &option, const std::string &value);
bool options(const std::string &options);
std::string lastError() const;
// markers //
bool markerName(uint32_t marker_id, const std::string &marker_name);
bool markerOptions(uint32_t marker_id, const std::string &marker_options);
const MarkerInfo markerInfo(uint32_t marker_id) const;
// trackers //
bool createTracker(uint32_t tracker_id, const std::string &tracker_type,
const std::string &tracker_name=std::string(),
const std::string &tracker_options=std::string());
bool createTrackers(const TrackerInfo *first, const TrackerInfo *last);
bool destroyTracker(uint32_t tracker_id);
bool destroyTrackers(const uint32_t *first, const uint32_t *last);
bool assignMarker(uint32_t tracker_id, uint32_t marker_id,
const std::string &marker_name=std::string(),
const std::string &marker_options=std::string());
bool assignMarkers(const MarkerInfo *first, const MarkerInfo *last);
bool trackerName(uint32_t tracker_id, const std::string &tracker_name);
bool trackerOptions(uint32_t tracker_id, const std::string &tracker_options);
const TrackerInfo trackerInfo(uint32_t tracker_id) const;
// filters //
bool filter(uint32_t period, const std::string &name, const std::string &filter_options);
bool filters(const FilterInfo *first, const FilterInfo *last);
const FilterInfo filterInfo(const std::string &name) const;
// devices //
const DeviceInfo deviceInfo(uint64_t hw_id) const;
// events //
const Event* peekEvent(long timeout=0);
const Event* nextEvent(long timeout=0);
// property //
const Variant property(const std::string &name) const;
template <typename T> T property(const std::string &name) const;
protected:
ContextData *data;
Context(const Context &ctx); // disable copy constructor
};
//// Type ////
struct OWLAPI Type {
enum {
INVALID = 0, BYTE, STRING = BYTE, INT, FLOAT,
ERROR = 0x7F,
EVENT = 0x80, FRAME = EVENT, CAMERA, PEAK, PLANE,
MARKER, RIGID, INPUT,
MARKERINFO, TRACKERINFO, FILTERINFO, DEVICEINFO
};
Type(uint32_t id, const void *data);
template <typename T> operator const T*() const;
template <typename T> operator T() const;
template <typename T> struct ID {
bool operator==(uint32_t id) const;
};
protected:
const uint32_t id;
const void * const data;
};
//// Variant ////
struct OWLAPI Variant {
Variant();
Variant(const Variant &v);
~Variant();
Variant& operator=(const Variant &v);
uint16_t type_id() const;
uint32_t flags() const;
const char* type_name() const;
bool valid() const;
bool empty() const;
const Type begin() const;
const Type end() const;
template <typename T> operator T() const;
template <typename T> operator std::vector<T>() const;
template <typename T> size_t get(T &v) const;
std::string str() const;
protected:
uint32_t _id;
uint32_t _flags;
void *_data, *_data_end;
const char *_type_name;
};
//// Event ////
struct OWLAPI Event : public Variant {
Event();
uint16_t type_id() const;
uint16_t id() const;
uint32_t flags() const;
int64_t time() const;
const char* type_name() const;
const char* name() const;
template <typename T> size_t size() const;
std::string str() const;
const Event* find(uint16_t type_id, const std::string &name) const;
const Event* find(const std::string &name) const;
template <typename T> size_t find(const std::string &name, T &v) const;
protected:
const char *_name;
int64_t _time;
friend class ContextData;
};
//// Scanner ////
class OWLAPI Scan {
int fd;
public:
Scan();
~Scan();
bool send(const std::string &message);
std::vector<std::string> listen(long timeout=0);
};
//// Context ////
template <typename T> T Context::property(const std::string &name) const
{ return property(name); }
//// Type ////
template <typename T> Type::operator const T*() const
{ return ID<T>() == id ? (const T*)data : 0; }
template <typename T> Type::operator T() const
{ return ID<T>() == id && (const T*)data ? *(const T*)data : T(); }
template <typename T> bool Type::ID<T>::operator==(uint32_t id) const { return false; }
template <> inline bool Type::ID<void>::operator==(uint32_t id) const { return true; }
template <> inline bool Type::ID<char>::operator==(uint32_t id) const { return id == BYTE || id == ERROR; }
template <> inline bool Type::ID<int>::operator==(uint32_t id) const { return id == INT; }
template <> inline bool Type::ID<unsigned int>::operator==(uint32_t id) const { return id == INT; }
template <> inline bool Type::ID<float>::operator==(uint32_t id) const { return id == FLOAT; }
template <> inline bool Type::ID<Event>::operator==(uint32_t id) const { return id == EVENT; }
template <> inline bool Type::ID<Camera>::operator==(uint32_t id) const { return id == CAMERA; }
template <> inline bool Type::ID<Peak>::operator==(uint32_t id) const { return id == PEAK; }
template <> inline bool Type::ID<Plane>::operator==(uint32_t id) const { return id == PLANE; }
template <> inline bool Type::ID<Marker>::operator==(uint32_t id) const { return id == MARKER; }
template <> inline bool Type::ID<Rigid>::operator==(uint32_t id) const { return id == RIGID; }
template <> inline bool Type::ID<Input>::operator==(uint32_t id) const { return id == INPUT; }
template <> inline bool Type::ID<MarkerInfo>::operator==(uint32_t id) const { return id == MARKERINFO; }
template <> inline bool Type::ID<TrackerInfo>::operator==(uint32_t id) const { return id == TRACKERINFO; }
template <> inline bool Type::ID<FilterInfo>::operator==(uint32_t id) const { return id == FILTERINFO; }
template <> inline bool Type::ID<DeviceInfo>::operator==(uint32_t id) const { return id == DEVICEINFO; }
//// Variant ////
template <typename T> Variant::operator T() const { return begin(); }
template <> inline Variant::operator std::string() const
{ return std::string((const char*)begin(), (const char*)end()); }
template <typename T> Variant::operator std::vector<T>() const
{ return std::vector<T>((const T*)begin(), (const T*)end()); }
template <typename T> size_t Variant::get(T &v) const
{
return Type::ID<typename T::value_type>() == type_id() ?
(v = T((typename T::const_pointer)begin(), (typename T::const_pointer)end())).size() : 0;
}
//// Event ////
template <typename T> size_t Event::size() const
{ return Type::ID<T>() == type_id() ? ((const char*)_data_end - (const char*)_data) / sizeof(T) : 0; }
template <typename T> size_t Event::find(const std::string &name, T &v) const
{
if(type_id() == Type::FRAME)
for(const Event *e = begin(); e != end(); e++)
if(Type::ID<typename T::value_type>() == e->type_id() && name == e->name())
return (v = T((typename T::const_pointer)e->begin(), (typename T::const_pointer)e->end())).size();
return 0;
}
//// conversion specializations ////
#define OWL_TYPE_OPERATORS(T1, T2) \
template <> inline Type::operator T1() const \
{ return ID<T1>() == id && (const T1*)data ? *(const T1*)data : ID<T2>() == id && (const T2*)data ? *(const T2*)data : T1(); }
#define OWL_VARIANT_VECTOR_OPERATORS(V, T1, T2) \
template <> inline Variant::operator V<T1>() const \
{ return Type::ID<T2>() == type_id() ? V<T1>((const T2*)begin(), (const T2*)end()) : V<T1>((const T1*)begin(), (const T1*)end()); }
OWL_TYPE_OPERATORS(float, int);
OWL_TYPE_OPERATORS(int, float);
OWL_VARIANT_VECTOR_OPERATORS(std::vector, float, int);
OWL_VARIANT_VECTOR_OPERATORS(std::vector, int, float);
////
} // namespace OWL
////
#endif // OWL_HPP
| 28.444695 | 133 | 0.642568 | Kirkados |
fa391d733f33efd06589d2c559344661df533abf | 2,566 | cpp | C++ | PA2 - Recipe Manager/src/Backend/Recipe.cpp | JahodaPaul/FIT_CTU | 2d96f18c7787ddfe340a15a36da6eea910225461 | [
"MIT"
] | 17 | 2019-03-09T17:13:40.000Z | 2022-03-05T14:42:05.000Z | PA2 - Recipe Manager/src/Backend/Recipe.cpp | JahodaPaul/FIT_CTU | 2d96f18c7787ddfe340a15a36da6eea910225461 | [
"MIT"
] | 1 | 2018-06-23T15:57:32.000Z | 2018-06-23T15:57:32.000Z | PA2 - Recipe Manager/src/Backend/Recipe.cpp | JahodaPaul/FIT_CTU | 2d96f18c7787ddfe340a15a36da6eea910225461 | [
"MIT"
] | 16 | 2019-04-09T00:10:55.000Z | 2022-02-21T20:28:05.000Z | //
// Created by pjahoda on 5/6/17.
//
#include "Recipe.h"
/**
* calculates percentage of same ingredients
* @param recipe2
* \return integer percentage
*/
int Recipe::HowMuchAreRecipesSame(const Recipe &recipe2)
{
int percentage = 0, nOfSameIngredients = 0;
for(unsigned int i = 0; i < this->ingredients.size(); i++)
{
if(i == 4 || i == 8)
{
if(i == 4)
{
if(this->ingredients[4] == recipe2.ingredients[8] || this->ingredients[4] == recipe2.ingredients[4])
{
nOfSameIngredients++;
}
if(this->ingredients[8] == recipe2.ingredients[8] || this->ingredients[8] == recipe2.ingredients[4])
{
nOfSameIngredients++;
if(this->ingredients[4] == this->ingredients[8] && recipe2.ingredients[4] != recipe2.ingredients[8])
{
nOfSameIngredients--;
}
}
}
}
else
{
if(this->ingredients[i] == recipe2.ingredients[i])
{
nOfSameIngredients += 1;
}
}
}
percentage = (100 * nOfSameIngredients) / 9;
return percentage;
}
///converts vector of ingredients into string presented to user
string Recipe::ToString(const int &screenWidth)
{
string result = "";
unsigned int cnt = 0;
for(const string &ingredient : ingredients)
{
cnt++;
if(cnt > 4 || (int) (result.length() + 7 + ingredient.length()) >= screenWidth)
{
return result;
}
if(cnt > 2 && ingredient != "#")
{
result += "and ";
}
else if(cnt == 2 && ingredient != "#")
{
result += "with ";
}
if(ingredient != "#")
{
result += ingredient;
result += ' ';
}
else
{
cnt--;
}
}
return result;
}
/// \return ingredients
vector <string> &Recipe::GetIngredients()
{
return this->ingredients;
}
/// \return ingredientWeight
vector<int> &Recipe::GetIngredientWeights()
{
return this->ingredientWeight;
}
/// \return idRecipe
int Recipe::GetRecipeId() const
{
return this->idRecipe;
}
Recipe::Recipe(vector <string> ingredients, vector<int> ingredientWeight, int idRecipe)
{
this->ingredients = ingredients;
this->ingredientWeight = ingredientWeight;
this->idRecipe = idRecipe;
}
Recipe::~Recipe()
{
} | 22.910714 | 120 | 0.512081 | JahodaPaul |
fa3a35933500e9a4c0035de671ededdfc82f1a41 | 15,054 | inl | C++ | include/Utopia/Asset/details/Serializer.inl | Justin-sky/Utopia | 71912290155a469ad578234a1f5e1695804e04a3 | [
"MIT"
] | null | null | null | include/Utopia/Asset/details/Serializer.inl | Justin-sky/Utopia | 71912290155a469ad578234a1f5e1695804e04a3 | [
"MIT"
] | null | null | null | include/Utopia/Asset/details/Serializer.inl | Justin-sky/Utopia | 71912290155a469ad578234a1f5e1695804e04a3 | [
"MIT"
] | 1 | 2021-04-24T23:26:09.000Z | 2021-04-24T23:26:09.000Z | #pragma once
#include "../../Core/Traits.h"
#include "../AssetMngr.h"
#include "../../Core/Object.h"
#include <variant>
namespace Ubpa::Utopia::detail {
template<typename Value>
void WriteVar(const Value& var, Serializer::SerializeContext& ctx);
template<typename UserType>
void WriteUserType(const UserType* obj, Serializer::SerializeContext& ctx) {
if constexpr (HasTypeInfo<UserType>::value) {
ctx.writer.StartObject();
Ubpa::USRefl::TypeInfo<UserType>::ForEachVarOf(
*obj,
[&ctx](auto field, const auto& var) {
ctx.writer.Key(field.name.data());
detail::WriteVar(var, ctx);
}
);
ctx.writer.EndObject();
}
else {
if (ctx.serializer.IsRegistered(GetID<UserType>()))
ctx.serializer.Visit(GetID<UserType>(), obj, ctx);
else {
assert("not support" && false);
ctx.writer.String(Serializer::Key::NOT_SUPPORT);
}
}
}
template<size_t Idx, typename Variant>
bool WriteVariantAt(const Variant& var, size_t idx, Serializer::SerializeContext& ctx) {
if (idx != Idx)
return false;
ctx.writer.StartObject();
ctx.writer.Key(Serializer::Key::INDEX);
ctx.writer.Uint64(var.index());
ctx.writer.Key(Serializer::Key::CONTENT);
WriteVar(std::get<std::variant_alternative_t<Idx, Variant>>(var), ctx);
ctx.writer.EndObject();
return true;
}
// TODO : stop
template<typename Variant, size_t... Ns>
void WriteVariant(const Variant& var, std::index_sequence<Ns...>, Serializer::SerializeContext& ctx) {
(WriteVariantAt<Ns>(var, var.index(), ctx), ...);
}
template<typename Value>
void WriteVar(const Value& var, Serializer::SerializeContext& ctx) {
if constexpr (std::is_floating_point_v<Value>)
ctx.writer.Double(static_cast<double>(var));
else if constexpr (std::is_enum_v<Value>)
WriteVar(static_cast<std::underlying_type_t<Value>>(var), ctx);
else if constexpr (std::is_integral_v<Value>) {
if constexpr (std::is_same_v<Value, bool>)
ctx.writer.Bool(var);
else {
constexpr size_t size = sizeof(Value);
if constexpr (std::is_unsigned_v<Value>) {
if constexpr (size <= sizeof(unsigned int))
ctx.writer.Uint(static_cast<std::uint32_t>(var));
else
ctx.writer.Uint64(static_cast<std::uint64_t>(var));
}
else {
if constexpr (size <= sizeof(int))
ctx.writer.Int(static_cast<std::int32_t>(var));
else
ctx.writer.Int64(static_cast<std::int64_t>(var));
}
}
}
else if constexpr (std::is_same_v<Value, std::string>)
ctx.writer.String(var);
else if constexpr (std::is_pointer_v<Value>) {
if (var == nullptr)
ctx.writer.Null();
else {
assert("not support" && false);
ctx.writer.Null();
}
}
else if constexpr (is_instance_of_v<Value, std::shared_ptr>) {
using Element = typename Value::element_type;
if (var == nullptr)
ctx.writer.Null();
else {
if constexpr (std::is_base_of_v<Object, Element>) {
auto& assetMngr = AssetMngr::Instance();
const auto& path = assetMngr.GetAssetPath(*var);
if (path.empty()) {
ctx.writer.Null();
return;
}
ctx.writer.String(assetMngr.AssetPathToGUID(path).str());
}
else {
assert("not support" && false);
ctx.writer.Null();
}
}
}
else if constexpr (std::is_same_v<Value, UECS::Entity>)
ctx.writer.Uint64(var.Idx());
else if constexpr (ArrayTraits<Value>::isArray) {
ctx.writer.StartArray();
for (size_t i = 0; i < ArrayTraits<Value>::size; i++)
WriteVar(ArrayTraits_Get(var, i), ctx);
ctx.writer.EndArray();
}
else if constexpr (OrderContainerTraits<Value>::isOrderContainer) {
ctx.writer.StartArray();
auto iter_end = OrderContainerTraits_End(var);
for (auto iter = OrderContainerTraits_Begin(var); iter != iter_end; iter++)
WriteVar(*iter, ctx);
ctx.writer.EndArray();
}
else if constexpr (MapTraits<Value>::isMap) {
auto iter_end = MapTraits_End(var);
if constexpr (std::is_same_v<std::string, MapTraits_KeyType<Value>>) {
ctx.writer.StartObject();
for (auto iter = MapTraits_Begin(var); iter != iter_end; ++iter) {
const auto& key = MapTraits_Iterator_Key(iter);
const auto& mapped = MapTraits_Iterator_Mapped(iter);
ctx.writer.Key(key);
WriteVar(mapped, ctx);
}
ctx.writer.EndObject();
}
else {
ctx.writer.StartArray();
for (auto iter = MapTraits_Begin(var); iter != iter_end; ++iter) {
const auto& key = MapTraits_Iterator_Key(iter);
const auto& mapped = MapTraits_Iterator_Mapped(iter);
ctx.writer.StartObject();
ctx.writer.Key(Serializer::Key::KEY);
WriteVar(key, ctx);
ctx.writer.Key(Serializer::Key::MAPPED);
WriteVar(mapped, ctx);
ctx.writer.EndObject();
}
ctx.writer.EndArray();
}
}
else if constexpr (TupleTraits<Value>::isTuple) {
ctx.writer.StartArray();
std::apply([&](const auto& ... elements) {
(WriteVar(elements, ctx), ...);
}, var);
ctx.writer.EndArray();
}
else if constexpr (is_instance_of_v<Value, std::variant>) {
constexpr size_t N = std::variant_size_v<Value>;
WriteVariant(var, std::make_index_sequence<N>{}, ctx);
}
else
WriteUserType(&var, ctx);
}
template<typename Value>
void ReadVar(Value& var, const rapidjson::Value& jsonValueField, Serializer::DeserializeContext& ctx);
template<size_t Idx, typename Variant>
bool ReadVariantAt(Variant& var, size_t idx, const rapidjson::Value& jsonValueContent, Serializer::DeserializeContext& ctx) {
if (idx != Idx)
return false;
std::variant_alternative_t<Idx, Variant> element;
ReadVar(element, jsonValueContent, ctx);
var = std::move(element);
return true;
}
// TODO : stop
template<typename Variant, size_t... Ns>
void ReadVariant(Variant& var, std::index_sequence<Ns...>, const rapidjson::Value& jsonValueField, Serializer::DeserializeContext& ctx) {
const auto& jsonObject = jsonValueField.GetObject();
size_t idx = jsonObject[Serializer::Key::INDEX].GetUint64();
const auto& jsonValueVariantData = jsonObject[Serializer::Key::CONTENT];
(ReadVariantAt<Ns>(var, idx, jsonValueVariantData, ctx), ...);
}
template<typename UserType>
void ReadUserType(UserType* obj, const rapidjson::Value& jsonValueField, Serializer::DeserializeContext& ctx) {
if constexpr (HasTypeInfo<UserType>::value) {
const auto& jsonObject = jsonValueField.GetObject();
USRefl::TypeInfo<UserType>::ForEachVarOf(
*obj,
[&](auto field, auto& var) {
auto target = jsonObject.FindMember(field.name.data());
if (target == jsonObject.MemberEnd())
return;
ReadVar(var, target->value, ctx);
}
);
}
else {
if (ctx.deserializer.IsRegistered(GetID<UserType>()))
ctx.deserializer.Visit(GetID<UserType>(), obj, jsonValueField, ctx);
else
assert("not support" && false);
}
}
template<typename Value>
void ReadVar(Value& var, const rapidjson::Value& jsonValueField, Serializer::DeserializeContext& ctx) {
if constexpr (std::is_floating_point_v<Value>)
var = static_cast<Value>(jsonValueField.GetDouble());
else if constexpr (std::is_enum_v<Value>) {
std::underlying_type_t<Value> under;
ReadVar(under, jsonValueField, ctx);
var = static_cast<Value>(under);
}
else if constexpr (std::is_integral_v<Value>) {
if constexpr (std::is_same_v<Value, bool>)
var = jsonValueField.GetBool();
else {
constexpr size_t size = sizeof(Value);
if constexpr (std::is_unsigned_v<Value>) {
if constexpr (size <= sizeof(unsigned int))
var = static_cast<Value>(jsonValueField.GetUint());
else
var = static_cast<Value>(jsonValueField.GetUint64());
}
else {
if constexpr (size <= sizeof(int))
var = static_cast<Value>(jsonValueField.GetInt());
else
var = static_cast<Value>(jsonValueField.GetInt64());
}
}
}
else if constexpr (std::is_same_v<Value, std::string>)
var = jsonValueField.GetString();
else if constexpr (std::is_pointer_v<Value>) {
if (jsonValueField.IsNull())
var = nullptr;
else {
assert("not support" && false);
}
}
else if constexpr (is_instance_of_v<Value, std::shared_ptr>) {
if (jsonValueField.IsNull())
var = nullptr;
else if (jsonValueField.IsString()) {
using Asset = typename Value::element_type;
std::string guid_str = jsonValueField.GetString();
const auto& path = AssetMngr::Instance().GUIDToAssetPath(xg::Guid{ guid_str });
var = AssetMngr::Instance().LoadAsset<Asset>(path);
}
else
assert("not support" && false);
}
else if constexpr (std::is_same_v<Value, UECS::Entity>) {
auto index = jsonValueField.GetUint64();
var = ctx.entityIdxMap.at(index);
}
else if constexpr (ArrayTraits<Value>::isArray) {
const auto& arr = jsonValueField.GetArray();
size_t N = std::min<size_t>(arr.Size(), ArrayTraits<Value>::size);
for (size_t i = 0; i < N; i++)
ReadVar(ArrayTraits_Get(var, i), arr[static_cast<rapidjson::SizeType>(i)], ctx);
}
else if constexpr (OrderContainerTraits<Value>::isOrderContainer) {
const auto& arr = jsonValueField.GetArray();
for (const auto& jsonValueElement : arr) {
OrderContainerTraits_ValueType<Value> element;
ReadVar(element, jsonValueElement, ctx);
OrderContainerTraits_Add(var, std::move(element));
}
OrderContainerTraits_PostProcess(var);
}
else if constexpr (MapTraits<Value>::isMap) {
if constexpr (std::is_same_v<MapTraits_KeyType<Value>, std::string>) {
const auto& m = jsonValueField.GetObject();
for (const auto& [val_key, val_mapped] : m) {
MapTraits_MappedType<Value> mapped;
ReadVar(mapped, val_mapped, ctx);
MapTraits_Emplace(
var,
MapTraits_KeyType<Value>{val_key.GetString()},
std::move(mapped)
);
}
}
else {
const auto& m = jsonValueField.GetArray();
for (const auto& val_pair : m) {
const auto& pair = val_pair.GetObject();
MapTraits_KeyType<Value> key;
MapTraits_MappedType<Value> mapped;
ReadVar(key, pair[Serializer::Key::KEY], ctx);
ReadVar(mapped, pair[Serializer::Key::MAPPED], ctx);
MapTraits_Emplace(var, std::move(key), std::move(mapped));
}
}
}
else if constexpr (TupleTraits<Value>::isTuple) {
std::apply([&](auto& ... elements) {
const auto& arr = jsonValueField.GetArray();
rapidjson::SizeType i = 0;
(ReadVar(elements, arr[i++], ctx), ...);
}, var);
}
else if constexpr (is_instance_of_v<Value, std::variant>) {
constexpr size_t N = std::variant_size_v<Value>;
ReadVariant(var, std::make_index_sequence<N>{}, jsonValueField, ctx);
}
else
ReadUserType(&var, jsonValueField, ctx);
};
}
namespace Ubpa::Utopia {
template<typename Func>
void Serializer::RegisterComponentSerializeFunction(Func&& func) {
using ArgList = FuncTraits_ArgList<Func>;
static_assert(Length_v<ArgList> == 2);
static_assert(std::is_same_v<At_t<ArgList, 1>, SerializeContext&>);
using ConstCmptPtr = At_t<ArgList, 0>;
static_assert(std::is_pointer_v<ConstCmptPtr>);
using ConstCmpt = std::remove_pointer_t<ConstCmptPtr>;
static_assert(std::is_const_v<ConstCmpt>);
using Cmpt = std::remove_const_t<ConstCmpt>;
RegisterComponentSerializeFunction(
UECS::CmptType::Of<Cmpt>,
[f = std::forward<Func>(func)](const void* p, SerializeContext& ctx) {
f(reinterpret_cast<const Cmpt*>(p), ctx);
}
);
}
template<typename Func>
void Serializer::RegisterComponentDeserializeFunction(Func&& func) {
using ArgList = FuncTraits_ArgList<Func>;
static_assert(Length_v<ArgList> == 3);
static_assert(std::is_same_v<At_t<ArgList, 1>, const rapidjson::Value&>);
static_assert(std::is_same_v<At_t<ArgList, 2>, DeserializeContext&>);
using CmptPtr = At_t<ArgList, 0>;
static_assert(std::is_pointer_v<CmptPtr>);
using Cmpt = std::remove_pointer_t<CmptPtr>;
static_assert(!std::is_const_v<Cmpt>);
RegisterComponentDeserializeFunction(
UECS::CmptType::Of<Cmpt>,
[f = std::forward<Func>(func)](void* p, const rapidjson::Value& jsonValueCmpt, DeserializeContext& ctx) {
f(reinterpret_cast<Cmpt*>(p), jsonValueCmpt, ctx);
}
);
}
template<typename Func>
void Serializer::RegisterUserTypeSerializeFunction(Func&& func) {
using ArgList = FuncTraits_ArgList<Func>;
static_assert(Length_v<ArgList> == 2);
static_assert(std::is_same_v<At_t<ArgList, 1>, SerializeContext&>);
using ConstUserTypePtr = At_t<ArgList, 0>;
static_assert(std::is_pointer_v<ConstUserTypePtr>);
using ConstUserType = std::remove_pointer_t<ConstUserTypePtr>;
static_assert(std::is_const_v<ConstUserType>);
using UserType = std::remove_const_t<ConstUserType>;
RegisterUserTypeSerializeFunction(
GetID<UserType>(),
[f = std::forward<Func>(func)](const void* p, SerializeContext& ctx) {
f(reinterpret_cast<const UserType*>(p), ctx);
}
);
}
template<typename Func>
void Serializer::RegisterUserTypeDeserializeFunction(Func&& func) {
using ArgList = FuncTraits_ArgList<Func>;
static_assert(Length_v<ArgList> == 3);
static_assert(std::is_same_v<At_t<ArgList, 1>, const rapidjson::Value&>);
static_assert(std::is_same_v<At_t<ArgList, 2>, DeserializeContext&>);
using UserTypePtr = At_t<ArgList, 0>;
static_assert(std::is_pointer_v<UserTypePtr>);
using UserType = std::remove_pointer_t<UserTypePtr>;
static_assert(!std::is_const_v<UserType>);
RegisterUserTypeDeserializeFunction(
GetID<UserType>(),
[f = std::forward<Func>(func)](void* p, const rapidjson::Value& jsonValueCmpt, DeserializeContext& ctx) {
f(reinterpret_cast<UserType*>(p), jsonValueCmpt, ctx);
}
);
}
template<typename... Cmpts>
void Serializer::RegisterComponentSerializeFunction() {
(RegisterComponentSerializeFunction(&detail::WriteUserType<Cmpts>), ...);
}
template<typename... Cmpts>
void Serializer::RegisterComponentDeserializeFunction() {
(RegisterComponentDeserializeFunction(&detail::ReadUserType<Cmpts>), ...);
}
template<typename... UserTypes>
void Serializer::RegisterUserTypeSerializeFunction() {
(RegisterUserTypeSerializeFunction(&detail::WriteUserType<UserTypes>), ...);
}
template<typename... UserTypes>
void Serializer::RegisterUserTypeDeserializeFunction() {
(RegisterUserTypeDeserializeFunction(&detail::ReadUserType<UserTypes>), ...);
}
template<typename... Cmpts>
void Serializer::RegisterComponents() {
RegisterComponentSerializeFunction<Cmpts...>();
RegisterComponentDeserializeFunction<Cmpts...>();
}
// register UserTypes' serialize and deserialize function
template<typename... UserTypes>
void Serializer::RegisterUserTypes() {
RegisterUserTypeSerializeFunction<UserTypes...>();
RegisterUserTypeDeserializeFunction<UserTypes...>();
}
template<typename UserType>
std::string Serializer::ToJSON(const UserType* obj) {
static_assert(!std::is_void_v<UserType>);
return ToJSON(GetID<UserType>(), obj);
}
template<typename UserType>
bool Serializer::ToUserType(std::string_view json, UserType* obj) {
static_assert(!std::is_void_v<UserType>);
return ToUserType(json, GetID<UserType>(), obj);
}
}
| 33.905405 | 138 | 0.692906 | Justin-sky |
fa3dc17feac4ff12716e3254a9915d340fb8893f | 6,913 | cxx | C++ | test/core/communication/BeaconSendingCaptureOffStateTest.cxx | stefaneberl/openkit-native | 1dc042141f4990508742a89aacafda9b2a29aaaf | [
"Apache-2.0"
] | null | null | null | test/core/communication/BeaconSendingCaptureOffStateTest.cxx | stefaneberl/openkit-native | 1dc042141f4990508742a89aacafda9b2a29aaaf | [
"Apache-2.0"
] | null | null | null | test/core/communication/BeaconSendingCaptureOffStateTest.cxx | stefaneberl/openkit-native | 1dc042141f4990508742a89aacafda9b2a29aaaf | [
"Apache-2.0"
] | null | null | null | /**
* Copyright 2018-2020 Dynatrace 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 "CustomMatchers.h"
#include "mock/MockIBeaconSendingContext.h"
#include "../../protocol/mock/MockIHTTPClient.h"
#include "../../protocol/mock/MockIStatusResponse.h"
#include "core/communication/IBeaconSendingState.h"
#include "core/communication/BeaconSendingCaptureOffState.h"
#include "gtest/gtest.h"
#include "gmock/gmock.h"
using namespace test;
using BeaconSendingCaptureOffState_t = core::communication::BeaconSendingCaptureOffState;
using IBeaconSendingState_t = core::communication::IBeaconSendingState;
using IBeaconSendingState_sp = std::shared_ptr<IBeaconSendingState_t>;
using IStatusResponse_t = protocol::IStatusResponse;
using MockNiceIBeaconSendingContext_sp = std::shared_ptr<testing::NiceMock<MockIBeaconSendingContext>>;
using MockNiceIHttpClient_sp = std::shared_ptr<testing::NiceMock<MockIHTTPClient>>;
class BeaconSendingCaptureOffStateTest : public testing::Test
{
protected:
MockNiceIBeaconSendingContext_sp mockContext;
MockNiceIHttpClient_sp mockHTTPClient;
void SetUp() override
{
mockHTTPClient = MockIHTTPClient::createNice();
ON_CALL(*mockHTTPClient, sendStatusRequest())
.WillByDefault(testing::Return(MockIStatusResponse::createNice()));
mockContext = MockIBeaconSendingContext::createNice();
ON_CALL(*mockContext, getHTTPClient())
.WillByDefault(testing::Return(mockHTTPClient));
}
};
TEST_F(BeaconSendingCaptureOffStateTest, aBeaconSendingCaptureOffStateIsNotATerminalState)
{
// given
BeaconSendingCaptureOffState_t target;
// when
auto obtained = target.isTerminalState();
// then
ASSERT_THAT(obtained, testing::Eq(false));
}
TEST_F(BeaconSendingCaptureOffStateTest, getStateNameGivesStatesName)
{
// given
auto target = BeaconSendingCaptureOffState_t();
// when
auto obtained = target.getStateName();
// then
ASSERT_THAT(obtained, testing::StrEq("CaptureOff"));
}
TEST_F(BeaconSendingCaptureOffStateTest, aBeaconSendingCaptureOffStateHasTerminalStateBeaconSendingFlushSessions)
{
// given
BeaconSendingCaptureOffState_t target;
// when
auto obtained = target.getShutdownState();
// then
ASSERT_THAT(obtained, testing::NotNull());
ASSERT_THAT(obtained->getStateType(), testing::Eq(IBeaconSendingState_t::StateType::BEACON_SENDING_FLUSH_SESSIONS_STATE));
}
TEST_F(BeaconSendingCaptureOffStateTest, aBeaconSendingCaptureOffStateTransitionsToCaptureOnStateWhenCapturingActive)
{
// given
ON_CALL(*mockContext, isCaptureOn())
.WillByDefault(testing::Return(true));
auto target = BeaconSendingCaptureOffState_t();
// expect
EXPECT_CALL(*mockContext, disableCaptureAndClear())
.Times(::testing::Exactly(1));
EXPECT_CALL(*mockContext, setLastStatusCheckTime(testing::_))
.Times(testing::Exactly(1));
EXPECT_CALL(*mockContext, setNextState(IsABeaconSendingCaptureOnState()))
.Times(testing::Exactly(1));
// when
target.execute(*mockContext);
}
TEST_F(BeaconSendingCaptureOffStateTest, getSleepTimeInMillisecondsReturnsMinusOneForDefaultConstructor)
{
// given
auto target = BeaconSendingCaptureOffState_t();
// when
auto obtained = target.getSleepTimeInMilliseconds();
// then
ASSERT_EQ(int64_t(-1), obtained);
}
TEST_F(BeaconSendingCaptureOffStateTest, getSleepTimeInMillisecondsReturnsSleepTimeSetInConstructor)
{
// given
int64_t sleepTime = 654321;
auto target = BeaconSendingCaptureOffState_t(sleepTime);
// when
auto obtained = target.getSleepTimeInMilliseconds();
// then
ASSERT_THAT(obtained, testing::Eq(sleepTime));
}
TEST_F(BeaconSendingCaptureOffStateTest, aBeaconSendingCaptureOffStateWaitsForGivenTime)
{
// with
int64_t sleepTime = 1234;
ON_CALL(*mockContext, isCaptureOn())
.WillByDefault(testing::Return(true));
// expect
EXPECT_CALL(*mockContext, sleep(testing::Eq(sleepTime)))
.Times(testing::Exactly(1));
// given
BeaconSendingCaptureOffState_t target(sleepTime);
// when
target.execute(*mockContext);
}
TEST_F(BeaconSendingCaptureOffStateTest, aBeaconSendingCaptureOffStateStaysInOffStateWhenServerRespondsWithTooManyRequests)
{
// with
int64_t sleepTime = 1234;
auto statusResponse = MockIStatusResponse::createNice();
ON_CALL(*statusResponse, getResponseCode())
.WillByDefault(testing::Return(429));
ON_CALL(*statusResponse, isTooManyRequestsResponse())
.WillByDefault(testing::Return(true));
ON_CALL(*statusResponse, isErroneousResponse())
.WillByDefault(testing::Return(true));
ON_CALL(*statusResponse, getRetryAfterInMilliseconds())
.WillByDefault(testing::Return(sleepTime));
ON_CALL(*mockHTTPClient, sendStatusRequest())
.WillByDefault(testing::Return(statusResponse));
ON_CALL(*mockContext, isCaptureOn())
.WillByDefault(testing::Return(false));
// expect
IBeaconSendingState_sp savedNextState = nullptr;
EXPECT_CALL(*mockContext, setNextState(IsABeaconSendingCaptureOffState()))
.Times(testing::Exactly(1))
.WillOnce(testing::SaveArg<0>(&savedNextState));
// given
auto target = BeaconSendingCaptureOffState_t(int64_t(12345));
// when calling execute
target.execute(*mockContext);
// verify captured state
ASSERT_THAT(savedNextState, testing::NotNull());
ASSERT_THAT(
std::static_pointer_cast<BeaconSendingCaptureOffState_t>(savedNextState)->getSleepTimeInMilliseconds(),
testing::Eq(sleepTime)
);
}
TEST_F(BeaconSendingCaptureOffStateTest, aBeaconSendingCaptureOffStateDoesDoesNotExecuteStatusRequestWhenInterruptedDuringSleep)
{
// with
ON_CALL(*mockContext, isCaptureOn())
.WillByDefault(testing::Return(false));
EXPECT_CALL(*mockContext, isShutdownRequested())
.WillOnce(testing::Return(false))
.WillRepeatedly(testing::Return(true));
// expect
EXPECT_CALL(*mockContext, disableCaptureAndClear())
.Times(::testing::Exactly(1));
// also verify that lastStatusCheckTime was updated
EXPECT_CALL(*mockContext, setLastStatusCheckTime(testing::_))
.Times(testing::Exactly(0));
// verify the sleep - since this is not multi-threaded, the sleep time is still the full time
EXPECT_CALL(*mockContext, sleep(7200000L))
.Times(testing::Exactly(1));
// verify that after sleeping the transition to IsABeaconSendingFlushSessionsState works
EXPECT_CALL(*mockContext, setNextState(IsABeaconSendingFlushSessionsState()))
.Times(testing::Exactly(1));
// given
auto target = BeaconSendingCaptureOffState_t();
// when calling execute
target.execute(*mockContext);
} | 30.861607 | 128 | 0.789093 | stefaneberl |
fa3e29946fa64171c7ebbacb839e3ad604f64dcb | 394 | hpp | C++ | src/random/circle2d.hpp | degarashi/beat | 456cc4469067509f0746fbe4eca0d3a0879cb894 | [
"MIT"
] | null | null | null | src/random/circle2d.hpp | degarashi/beat | 456cc4469067509f0746fbe4eca0d3a0879cb894 | [
"MIT"
] | null | null | null | src/random/circle2d.hpp | degarashi/beat | 456cc4469067509f0746fbe4eca0d3a0879cb894 | [
"MIT"
] | null | null | null | #pragma once
#include "../circle2d.hpp"
#include "frea/src/random/vector.hpp"
namespace beat {
namespace g2 {
namespace random {
template <class RDP, class RDR>
Circle GenCircle(RDP&& rdp, RDR&& rdr) {
return {
frea::random::GenVec<Vec2>(rdp),
std::abs(rdr())
};
}
template <class RD>
Circle GenCircle(RD&& rd) {
return GenCircle(rd, rd);
}
}
}
}
| 17.909091 | 43 | 0.604061 | degarashi |
fa43ab64c98b7c2e439b47615d389ee1d927ff1e | 954 | cpp | C++ | leetcode/algorithms/Q56-merge-intervals.cpp | jatin69/Revision-cpp | 52742ea76ee2440d92b116252399360fef46e0c7 | [
"MIT"
] | 4 | 2020-01-16T14:49:46.000Z | 2021-08-23T12:45:19.000Z | leetcode/algorithms/Q56-merge-intervals.cpp | jatin69/coding-practice | 52742ea76ee2440d92b116252399360fef46e0c7 | [
"MIT"
] | 2 | 2018-06-06T13:08:11.000Z | 2018-10-02T19:07:32.000Z | leetcode/algorithms/Q56-merge-intervals.cpp | jatin69/coding-practice | 52742ea76ee2440d92b116252399360fef46e0c7 | [
"MIT"
] | 5 | 2018-10-02T13:49:16.000Z | 2021-08-11T07:29:50.000Z | /*
* Author : Jatin Rohilla
* Date : June-July-2019
*
* Compiler : g++ 5.1.0
* flags : -std=c++14
*/
#include<bits/stdc++.h>
using namespace std;
// source code here
class Solution {
public:
vector<vector<int>> merge(vector<vector<int>>& intervals) {
if(intervals.size() < 2){
return intervals;
}
sort(begin(intervals), end(intervals), [](auto a, auto b){
if(a[0]==b[0]){
return a[1] < b[1];
}
return a[0] < b[0];
});
vector<vector<int>> res;
res.push_back(intervals[0]);
for(int i=1; i<intervals.size(); ++i){
if(intervals[i][0] <= res.back()[1]){
res.back()[1] = max(res.back()[1], intervals[i][1]);
}
else{
res.push_back(intervals[i]);
}
}
return res;
}
};
int main(){
cout<<"Hello World";
return 0;
}
| 19.469388 | 68 | 0.462264 | jatin69 |
fa44568e520dfcf40a0e97b897d200be5d8b3606 | 2,781 | cpp | C++ | SCProjects/MetaBot/Source/Commander/Zerg/ZergMain.cpp | andertavares/OpprimoBot | da75bc0bf65b2b12d7184ffef88b2dbfa0d6110b | [
"MIT"
] | null | null | null | SCProjects/MetaBot/Source/Commander/Zerg/ZergMain.cpp | andertavares/OpprimoBot | da75bc0bf65b2b12d7184ffef88b2dbfa0d6110b | [
"MIT"
] | null | null | null | SCProjects/MetaBot/Source/Commander/Zerg/ZergMain.cpp | andertavares/OpprimoBot | da75bc0bf65b2b12d7184ffef88b2dbfa0d6110b | [
"MIT"
] | null | null | null | #include "ZergMain.h"
#include "../../Managers/BuildplanEntry.h"
#include "../../Managers/AgentManager.h"
#include "../RushSquad.h"
#include "../ExplorationSquad.h"
#include "../../Managers/ExplorationManager.h"
ZergMain::ZergMain()
{
buildplan.push_back(BuildplanEntry(UnitTypes::Zerg_Spawning_Pool, 5));
buildplan.push_back(BuildplanEntry(UnitTypes::Zerg_Extractor, 5));
buildplan.push_back(BuildplanEntry(UnitTypes::Zerg_Hydralisk_Den, 8));
buildplan.push_back(BuildplanEntry(UnitTypes::Zerg_Hatchery, 14));
mainSquad = new Squad(1, Squad::OFFENSIVE, "MainSquad", 10);
mainSquad->addSetup(UnitTypes::Zerg_Zergling, 16);
mainSquad->addSetup(UnitTypes::Zerg_Hydralisk, 10);
mainSquad->setRequired(true);
mainSquad->setBuildup(true);
squads.push_back(mainSquad);
sc1 = new ExplorationSquad(4, "ScoutingSquad", 8);
sc1->addSetup(UnitTypes::Zerg_Overlord, 1);
sc1->setRequired(false);
sc1->setBuildup(false);
sc1->setActivePriority(10);
squads.push_back(sc1);
sc2 = new RushSquad(5, "ScoutingSquad", 7);
sc2->addSetup(UnitTypes::Zerg_Zergling, 2);
sc2->setRequired(false);
sc2->setBuildup(false);
sc2->setActivePriority(1000);
noWorkers = 8;
noWorkersPerRefinery = 3;
}
ZergMain::~ZergMain()
{
for (Squad* s : squads)
{
delete s;
}
instance = NULL;
}
void ZergMain::computeActions()
{
computeActionsBase();
noWorkers = AgentManager::getInstance()->countNoBases() * 6 + AgentManager::getInstance()->countNoUnits(UnitTypes::Zerg_Extractor) * 3;
int cSupply = Broodwar->self()->supplyUsed() / 2;
int min = Broodwar->self()->minerals();
int gas = Broodwar->self()->gas();
if (stage == 0 && AgentManager::getInstance()->countNoFinishedUnits(UnitTypes::Zerg_Lair) > 0)
{
buildplan.push_back(BuildplanEntry(UnitTypes::Zerg_Spire, cSupply));
buildplan.push_back(BuildplanEntry(UnitTypes::Zerg_Creep_Colony, cSupply));
buildplan.push_back(BuildplanEntry(UnitTypes::Zerg_Creep_Colony, cSupply));
stage++;
}
if (stage == 1 && AgentManager::getInstance()->countNoFinishedUnits(UnitTypes::Zerg_Spire) > 0)
{
mainSquad->addSetup(UnitTypes::Zerg_Hydralisk, 14);
mainSquad->addSetup(UnitTypes::Zerg_Mutalisk, 16);
mainSquad->setBuildup(false);
buildplan.push_back(BuildplanEntry(UnitTypes::Zerg_Queens_Nest, cSupply));
stage++;
}
if (stage == 2 && min > 450)
{
buildplan.push_back(BuildplanEntry(UnitTypes::Zerg_Hatchery, cSupply));
stage++;
}
if (stage == 3 && AgentManager::getInstance()->countNoFinishedUnits(UnitTypes::Zerg_Hive) > 0)
{
buildplan.push_back(BuildplanEntry(UnitTypes::Zerg_Defiler_Mound, cSupply));
stage++;
}
if (stage == 4 && AgentManager::getInstance()->countNoFinishedUnits(UnitTypes::Zerg_Defiler_Mound) > 0)
{
mainSquad->addSetup(UnitTypes::Zerg_Defiler, 4);
stage++;
}
}
| 29.273684 | 136 | 0.729953 | andertavares |
fa46c8fff2cb0b267e223c7e0da5de4bb2d10b5b | 5,356 | cpp | C++ | xCode/OpenGL/MD2 animation/Classes/QR_Engine/QR_3D/QR_Renderer/QR_Renderer_OpenGL.cpp | Jeanmilost/Demos | 2b71f6edc85948540660d290183530fd846262ad | [
"MIT"
] | 1 | 2022-03-22T14:41:15.000Z | 2022-03-22T14:41:15.000Z | xCode/OpenGL/MD2 animation/Classes/QR_Engine/QR_3D/QR_Renderer/QR_Renderer_OpenGL.cpp | Jeanmilost/Demos | 2b71f6edc85948540660d290183530fd846262ad | [
"MIT"
] | null | null | null | xCode/OpenGL/MD2 animation/Classes/QR_Engine/QR_3D/QR_Renderer/QR_Renderer_OpenGL.cpp | Jeanmilost/Demos | 2b71f6edc85948540660d290183530fd846262ad | [
"MIT"
] | null | null | null | /******************************************************************************
* ==> QR_Renderer_OpenGL ----------------------------------------------------*
******************************************************************************
* Description : Specialized OpenGL renderer *
* Developer : Jean-Milost Reymond *
******************************************************************************/
#include "QR_Renderer_OpenGL.h"
// std
#include <sstream>
#include <cmath>
// qr engine
#include "QR_Exception.h"
// openGL
#ifdef _WIN32
#include <gl/gl.h>
#elif defined (__APPLE__)
#ifdef USE_OPENGL_DIRECT_MODE
#include </Applications/Xcode.app/Contents/Developer/Platforms/iPhoneOS.platform/Developer/SDKs/iPhoneOS9.3.sdk/System/Library/Frameworks/OpenGLES.framework/Headers/ES1/gl.h>
#else
#include <ES2/gl.h>
#include <ES2/glext.h>
#endif // USE_OPENGL_DIRECT_MODE
#endif // _WIN32 / __APPLE__
#ifdef USE_GLFW_LIBRARY
#include <gl/glfw.h>
#endif // USE_GLFW_LIBRARY
//------------------------------------------------------------------------------
// Class QR_Renderer_OpenGL - c++ cross-platform
//------------------------------------------------------------------------------
QR_Renderer_OpenGL::QR_Renderer_OpenGL() : QR_Renderer()
{}
//------------------------------------------------------------------------------
#ifdef _WIN32
QR_Renderer_OpenGL::QR_Renderer_OpenGL(HWND hWnd,
ITfOnConfigure fOnConfigure) :
QR_Renderer(),
m_hWnd(hWnd)
#ifndef USE_GLFW_LIBRARY
,
m_hDC(NULL),
m_hRC(NULL)
#endif // USE_GLFW_LIBRARY
{
Initialize(fOnConfigure);
}
#endif // defined(_WIN32)
//------------------------------------------------------------------------------
QR_Renderer_OpenGL::~QR_Renderer_OpenGL()
{
#if defined(_WIN32) && !defined(USE_GLFW_LIBRARY)
// release OpenGL context
::wglMakeCurrent(NULL, NULL);
// delete OpenGL context
if (m_hRC)
wglDeleteContext(m_hRC);
// delete device context
if (m_hWnd && m_hDC)
::ReleaseDC(m_hWnd, m_hDC);
#endif // defined(_WIN32) && !defined(USE_GLFW_LIBRARY)
}
//------------------------------------------------------------------------------
void QR_Renderer_OpenGL::BeginScene(const QR_Color& color, IESceneFlags flags) const
{
// begin post-processing effect
if (m_pPostProcessingEffect)
m_pPostProcessingEffect->Begin();
GLbitfield openGLSceneFlags = 0;
// clear background color, if needed
if (flags & IE_SF_ClearColor)
{
glClearColor((GLclampf)color.GetRedF(), (GLclampf)color.GetGreenF(),
(GLclampf)color.GetBlueF(), (GLclampf)color.GetAlphaF());
openGLSceneFlags |= GL_COLOR_BUFFER_BIT;
}
// clear Z buffer, if needed
if (flags & IE_SF_ClearDepth)
{
#ifdef __APPLE__
glClearDepthf(1.0f);
#else
glClearDepth(1.0f);
#endif
openGLSceneFlags |= GL_DEPTH_BUFFER_BIT;
}
// clear scene, fill with background color and set render flags
glClear(openGLSceneFlags);
}
//------------------------------------------------------------------------------
void QR_Renderer_OpenGL::EndScene() const
{
// end post-processing effect
if (m_pPostProcessingEffect)
m_pPostProcessingEffect->End();
#if defined(_WIN32)
#ifdef USE_GLFW_LIBRARY
// swap the display buffers (displays what was just drawn)
glfwSwapBuffers();
#else
// no device context?
if (!m_hDC)
return;
// present back buffer
::SwapBuffers(m_hDC);
#endif // USE_GLFW_LIBRARY
#elif defined(__APPLE__)
// nothing to do, Apple OpenGLES implementation does everything for us
#else
#error "Do implement EndScene() for this platform"
#endif
}
//------------------------------------------------------------------------------
void QR_Renderer_OpenGL::Initialize(ITfOnConfigure fOnConfigure)
{
#if defined(_WIN32) && !defined(USE_GLFW_LIBRARY)
::PIXELFORMATDESCRIPTOR pfd;
QR_Int32 iFormat;
// get device context
m_hDC = ::GetDC(m_hWnd);
// set device context pixel format
::ZeroMemory(&pfd, sizeof(pfd));
pfd.nSize = sizeof(pfd);
pfd.nVersion = 1;
pfd.dwFlags = PFD_DRAW_TO_WINDOW | PFD_SUPPORT_OPENGL | PFD_DOUBLEBUFFER;
pfd.iPixelType = PFD_TYPE_RGBA;
pfd.cColorBits = 32;
pfd.cDepthBits = 32;
pfd.cStencilBits = 32;
pfd.iLayerType = PFD_MAIN_PLANE;
iFormat = ::ChoosePixelFormat(m_hDC, &pfd);
::SetPixelFormat(m_hDC, iFormat, &pfd);
// create and enable OpenGL render context
m_hRC = ::wglCreateContext(m_hDC);
::wglMakeCurrent(m_hDC, m_hRC);
// notify that OpenGL can be configured
if (fOnConfigure)
fOnConfigure(this);
#endif // defined(_WIN32) && !defined(USE_GLFW_LIBRARY)
}
//------------------------------------------------------------------------------
| 33.475 | 182 | 0.504294 | Jeanmilost |
fa489af4f8db0e9a17c8f717b03531ecba92e495 | 5,549 | cxx | C++ | Plugins/VR/vtkVRActiveObjectManipulationStyle.cxx | XiaoboFu/ParaViewGeo | 0089927885fd67a3d70a22a28977a291bed3fcdd | [
"BSD-2-Clause",
"BSD-3-Clause"
] | 17 | 2015-02-17T00:30:26.000Z | 2022-03-17T06:13:02.000Z | Plugins/VR/vtkVRActiveObjectManipulationStyle.cxx | ObjectivitySRC/ParaViewGeo | 0089927885fd67a3d70a22a28977a291bed3fcdd | [
"BSD-2-Clause",
"BSD-3-Clause"
] | null | null | null | Plugins/VR/vtkVRActiveObjectManipulationStyle.cxx | ObjectivitySRC/ParaViewGeo | 0089927885fd67a3d70a22a28977a291bed3fcdd | [
"BSD-2-Clause",
"BSD-3-Clause"
] | 10 | 2015-08-31T18:20:17.000Z | 2022-02-02T15:16:21.000Z | #include "vtkVRActiveObjectManipulationStyle.h"
#include "pqActiveObjects.h"
#include "pqDataRepresentation.h"
#include "pqView.h"
#include "vtkCamera.h"
#include "vtkMath.h"
#include "vtkRenderer.h"
#include "vtkRenderWindow.h"
#include "vtkSMDoubleVectorProperty.h"
#include "vtkSMPropertyHelper.h"
#include "vtkSMRenderViewProxy.h"
#include "vtkSMRepresentationProxy.h"
#include "vtkVRQueue.h"
vtkVRActiveObjectManipulationStyle::vtkVRActiveObjectManipulationStyle(QObject* parentObject) :
Superclass(parentObject)
{
}
vtkVRActiveObjectManipulationStyle::~vtkVRActiveObjectManipulationStyle()
{
}
// ----------------------------------------------------------------------------
// This handler currently only get the
bool vtkVRActiveObjectManipulationStyle::handleEvent(const vtkVREventData& data)
{
switch( data.eventType )
{
case BUTTON_EVENT:
this->HandleButton( data );
break;
case ANALOG_EVENT:
this->HandleAnalog( data );
break;
case TRACKER_EVENT:
this->HandleTracker( data );
break;
}
return false;
}
// ----------------------------------------------------------------------------
void vtkVRActiveObjectManipulationStyle::HandleTracker( const vtkVREventData& data )
{
}
// ----------------------------------------------------------------------------
void vtkVRActiveObjectManipulationStyle::HandleButton( const vtkVREventData& data )
{
}
// ----------------------------------------------------------------------------
void vtkVRActiveObjectManipulationStyle::HandleAnalog( const vtkVREventData& data )
{
HandleSpaceNavigatorAnalog(data);
}
// -------------------------------------------------------------------------fun
vtkAnalog AugmentChannelsToRetainLargestMagnitude(const vtkAnalog t)
{
vtkAnalog at;
// Make a list of the magnitudes into at
for(int i=0;i<6;++i)
{
if(t.channel[i] < 0.0)
at.channel[i] = t.channel[i]*-1;
else
at.channel[i]= t.channel[i];
}
// Get the max value;
int max =0;
for(int i=1;i<6;++i)
{
if(at.channel[i] > at.channel[max])
max = i;
}
// copy the max value of t into at (rest are 0)
for (int i = 0; i < 6; ++i)
{
(i==max)?at.channel[i]=t.channel[i]:at.channel[i]=0.0;
}
return at;
}
void vtkVRActiveObjectManipulationStyle::HandleSpaceNavigatorAnalog( const vtkVREventData& data )
{
vtkAnalog at = AugmentChannelsToRetainLargestMagnitude(data.data.analog);
pqView *view = 0;
pqDataRepresentation *rep =0;
view = pqActiveObjects::instance().activeView();
rep = pqActiveObjects::instance().activeRepresentation();
if(rep)
{
vtkCamera* camera;
double pos[3], up[3], dir[3];
double orient[3];
vtkSMRenderViewProxy *viewProxy = 0;
vtkSMRepresentationProxy *repProxy = 0;
viewProxy = vtkSMRenderViewProxy::SafeDownCast( view->getViewProxy() );
repProxy = vtkSMRepresentationProxy::SafeDownCast(rep->getProxy());
if ( repProxy && viewProxy )
{
vtkSMPropertyHelper(repProxy,"Position").Get(pos,3);
vtkSMPropertyHelper(repProxy,"Orientation").Get(orient,3);
camera = viewProxy->GetActiveCamera();
camera->GetDirectionOfProjection(dir);
camera->OrthogonalizeViewUp();
camera->GetViewUp(up);
for (int i = 0; i < 3; i++)
{
double dx = -0.01*at.channel[2]*up[i];
pos[i] += dx;
}
double r[3];
vtkMath::Cross(dir, up, r);
for (int i = 0; i < 3; i++)
{
double dx = 0.01*at.channel[0]*r[i];
pos[i] += dx;
}
for(int i=0;i<3;++i)
{
double dx = -0.01*at.channel[1]*dir[i];
pos[i] +=dx;
}
// pos[0] += at.channel[0];
// pos[1] += at.channel[1];
// pos[2] += at.channel[2];
orient[0] += 4.0*at.channel[3];
orient[1] += 4.0*at.channel[5];
orient[2] += 4.0*at.channel[4];
vtkSMPropertyHelper(repProxy,"Position").Set(pos,3);
vtkSMPropertyHelper(repProxy,"Orientation").Set(orient,3);
repProxy->UpdateVTKObjects();
}
}
else if ( view )
{
vtkSMRenderViewProxy *viewProxy = 0;
viewProxy = vtkSMRenderViewProxy::SafeDownCast( view->getViewProxy() );
if ( viewProxy )
{
vtkCamera* camera;
double pos[3], fp[3], up[3], dir[3];
camera = viewProxy->GetActiveCamera();
camera->GetPosition(pos);
camera->GetFocalPoint(fp);
camera->GetDirectionOfProjection(dir);
camera->OrthogonalizeViewUp();
camera->GetViewUp(up);
for (int i = 0; i < 3; i++)
{
double dx = 0.01*at.channel[2]*up[i];
pos[i] += dx;
fp[i] += dx;
}
// Apply right-left motion
double r[3];
vtkMath::Cross(dir, up, r);
for (int i = 0; i < 3; i++)
{
double dx = -0.01*at.channel[0]*r[i];
pos[i] += dx;
fp[i] += dx;
}
camera->SetPosition(pos);
camera->SetFocalPoint(fp);
camera->Dolly(pow(1.01,at.channel[1]));
camera->Elevation( 4.0*at.channel[3]);
camera->Azimuth( 4.0*at.channel[5]);
camera->Roll( 4.0*at.channel[4]);
}
}
}
bool vtkVRActiveObjectManipulationStyle::update()
{
vtkSMRenderViewProxy *proxy =0;
pqView *view = 0;
view = pqActiveObjects::instance().activeView();
if ( view )
{
proxy = vtkSMRenderViewProxy::SafeDownCast( view->getViewProxy() );
if ( proxy )
{
proxy->UpdateVTKObjects();
proxy->StillRender();
}
}
return false;
}
| 25.809302 | 97 | 0.575419 | XiaoboFu |
fa4d36c4a7e221fbcc362d618b503c54efa5f56d | 14,096 | hpp | C++ | include/GlobalNamespace/StandardScoreSyncStateDeltaNetSerializable.hpp | RedBrumbler/BeatSaber-Quest-Codegen | 73dda50b5a3e51f10d86b766dcaa24b0c6226e25 | [
"Unlicense"
] | null | null | null | include/GlobalNamespace/StandardScoreSyncStateDeltaNetSerializable.hpp | RedBrumbler/BeatSaber-Quest-Codegen | 73dda50b5a3e51f10d86b766dcaa24b0c6226e25 | [
"Unlicense"
] | null | null | null | include/GlobalNamespace/StandardScoreSyncStateDeltaNetSerializable.hpp | RedBrumbler/BeatSaber-Quest-Codegen | 73dda50b5a3e51f10d86b766dcaa24b0c6226e25 | [
"Unlicense"
] | null | null | null | // Autogenerated from CppHeaderCreator
// Created by Sc2ad
// =========================================================================
#pragma once
// Begin includes
#include "beatsaber-hook/shared/utils/typedefs.h"
#include "beatsaber-hook/shared/utils/byref.hpp"
// Including type: LiteNetLib.Utils.INetSerializable
#include "LiteNetLib/Utils/INetSerializable.hpp"
// Including type: IPoolablePacket
#include "GlobalNamespace/IPoolablePacket.hpp"
// Including type: ISyncStateDeltaSerializable`1
#include "GlobalNamespace/ISyncStateDeltaSerializable_1.hpp"
// Including type: StandardScoreSyncState
#include "GlobalNamespace/StandardScoreSyncState.hpp"
#include "beatsaber-hook/shared/utils/il2cpp-utils-methods.hpp"
#include "beatsaber-hook/shared/utils/il2cpp-utils-properties.hpp"
#include "beatsaber-hook/shared/utils/il2cpp-utils-fields.hpp"
#include "beatsaber-hook/shared/utils/utils.h"
// Completed includes
// Begin forward declares
// Forward declaring namespace: GlobalNamespace
namespace GlobalNamespace {
// Forward declaring type: IPacketPool`1<T>
template<typename T>
class IPacketPool_1;
}
// Forward declaring namespace: LiteNetLib::Utils
namespace LiteNetLib::Utils {
// Forward declaring type: NetDataWriter
class NetDataWriter;
// Forward declaring type: NetDataReader
class NetDataReader;
}
// Completed forward declares
// Type namespace:
namespace GlobalNamespace {
// Forward declaring type: StandardScoreSyncStateDeltaNetSerializable
class StandardScoreSyncStateDeltaNetSerializable;
}
#include "beatsaber-hook/shared/utils/il2cpp-type-check.hpp"
NEED_NO_BOX(::GlobalNamespace::StandardScoreSyncStateDeltaNetSerializable);
DEFINE_IL2CPP_ARG_TYPE(::GlobalNamespace::StandardScoreSyncStateDeltaNetSerializable*, "", "StandardScoreSyncStateDeltaNetSerializable");
// Type namespace:
namespace GlobalNamespace {
// Size: 0x2C
#pragma pack(push, 1)
// Autogenerated type: StandardScoreSyncStateDeltaNetSerializable
// [TokenAttribute] Offset: FFFFFFFF
class StandardScoreSyncStateDeltaNetSerializable : public ::Il2CppObject/*, public ::LiteNetLib::Utils::INetSerializable, public ::GlobalNamespace::IPoolablePacket, public ::GlobalNamespace::ISyncStateDeltaSerializable_1<::GlobalNamespace::StandardScoreSyncState>*/ {
public:
#ifdef USE_CODEGEN_FIELDS
public:
#else
#ifdef CODEGEN_FIELD_ACCESSIBILITY
CODEGEN_FIELD_ACCESSIBILITY:
#else
protected:
#endif
#endif
// private StandardScoreSyncState _delta
// Size: 0x14
// Offset: 0x10
::GlobalNamespace::StandardScoreSyncState delta;
// Field size check
static_assert(sizeof(::GlobalNamespace::StandardScoreSyncState) == 0x14);
// private SyncStateId <baseId>k__BackingField
// Size: 0x1
// Offset: 0x24
::GlobalNamespace::SyncStateId baseId;
// Field size check
static_assert(sizeof(::GlobalNamespace::SyncStateId) == 0x1);
// Padding between fields: baseId and: timeOffsetMs
char __padding1[0x3] = {};
// private System.Int32 <timeOffsetMs>k__BackingField
// Size: 0x4
// Offset: 0x28
int timeOffsetMs;
// Field size check
static_assert(sizeof(int) == 0x4);
public:
// Creating interface conversion operator: operator ::LiteNetLib::Utils::INetSerializable
operator ::LiteNetLib::Utils::INetSerializable() noexcept {
return *reinterpret_cast<::LiteNetLib::Utils::INetSerializable*>(this);
}
// Creating interface conversion operator: operator ::GlobalNamespace::IPoolablePacket
operator ::GlobalNamespace::IPoolablePacket() noexcept {
return *reinterpret_cast<::GlobalNamespace::IPoolablePacket*>(this);
}
// Creating interface conversion operator: operator ::GlobalNamespace::ISyncStateDeltaSerializable_1<::GlobalNamespace::StandardScoreSyncState>
operator ::GlobalNamespace::ISyncStateDeltaSerializable_1<::GlobalNamespace::StandardScoreSyncState>() noexcept {
return *reinterpret_cast<::GlobalNamespace::ISyncStateDeltaSerializable_1<::GlobalNamespace::StandardScoreSyncState>*>(this);
}
// Get instance field reference: private StandardScoreSyncState _delta
::GlobalNamespace::StandardScoreSyncState& dyn__delta();
// Get instance field reference: private SyncStateId <baseId>k__BackingField
::GlobalNamespace::SyncStateId& dyn_$baseId$k__BackingField();
// Get instance field reference: private System.Int32 <timeOffsetMs>k__BackingField
int& dyn_$timeOffsetMs$k__BackingField();
// static public IPacketPool`1<StandardScoreSyncStateDeltaNetSerializable> get_pool()
// Offset: 0x25F09E4
static ::GlobalNamespace::IPacketPool_1<::GlobalNamespace::StandardScoreSyncStateDeltaNetSerializable*>* get_pool();
// public SyncStateId get_baseId()
// Offset: 0x25F0A2C
::GlobalNamespace::SyncStateId get_baseId();
// public System.Void set_baseId(SyncStateId value)
// Offset: 0x25F0A34
void set_baseId(::GlobalNamespace::SyncStateId value);
// public System.Int32 get_timeOffsetMs()
// Offset: 0x25F0A3C
int get_timeOffsetMs();
// public System.Void set_timeOffsetMs(System.Int32 value)
// Offset: 0x25F0A44
void set_timeOffsetMs(int value);
// public StandardScoreSyncState get_delta()
// Offset: 0x25F0A4C
::GlobalNamespace::StandardScoreSyncState get_delta();
// public System.Void set_delta(StandardScoreSyncState value)
// Offset: 0x25F0A60
void set_delta(::GlobalNamespace::StandardScoreSyncState value);
// public System.Void Serialize(LiteNetLib.Utils.NetDataWriter writer)
// Offset: 0x25F0A74
void Serialize(::LiteNetLib::Utils::NetDataWriter* writer);
// public System.Void Deserialize(LiteNetLib.Utils.NetDataReader reader)
// Offset: 0x25F0B5C
void Deserialize(::LiteNetLib::Utils::NetDataReader* reader);
// public System.Void Release()
// Offset: 0x25F0C00
void Release();
// public System.Void .ctor()
// Offset: 0x25F0CBC
// Implemented from: System.Object
// Base method: System.Void Object::.ctor()
template<::il2cpp_utils::CreationType creationType = ::il2cpp_utils::CreationType::Temporary>
static StandardScoreSyncStateDeltaNetSerializable* New_ctor() {
static auto ___internal__logger = ::Logger::get().WithContext("::GlobalNamespace::StandardScoreSyncStateDeltaNetSerializable::.ctor");
return THROW_UNLESS((::il2cpp_utils::New<StandardScoreSyncStateDeltaNetSerializable*, creationType>()));
}
}; // StandardScoreSyncStateDeltaNetSerializable
#pragma pack(pop)
static check_size<sizeof(StandardScoreSyncStateDeltaNetSerializable), 40 + sizeof(int)> __GlobalNamespace_StandardScoreSyncStateDeltaNetSerializableSizeCheck;
static_assert(sizeof(StandardScoreSyncStateDeltaNetSerializable) == 0x2C);
}
#include "beatsaber-hook/shared/utils/il2cpp-utils-methods.hpp"
// Writing MetadataGetter for method: GlobalNamespace::StandardScoreSyncStateDeltaNetSerializable::get_pool
// Il2CppName: get_pool
template<>
struct ::il2cpp_utils::il2cpp_type_check::MetadataGetter<static_cast<::GlobalNamespace::IPacketPool_1<::GlobalNamespace::StandardScoreSyncStateDeltaNetSerializable*>* (*)()>(&GlobalNamespace::StandardScoreSyncStateDeltaNetSerializable::get_pool)> {
static const MethodInfo* get() {
return ::il2cpp_utils::FindMethod(classof(GlobalNamespace::StandardScoreSyncStateDeltaNetSerializable*), "get_pool", std::vector<Il2CppClass*>(), ::std::vector<const Il2CppType*>{});
}
};
// Writing MetadataGetter for method: GlobalNamespace::StandardScoreSyncStateDeltaNetSerializable::get_baseId
// Il2CppName: get_baseId
template<>
struct ::il2cpp_utils::il2cpp_type_check::MetadataGetter<static_cast<::GlobalNamespace::SyncStateId (GlobalNamespace::StandardScoreSyncStateDeltaNetSerializable::*)()>(&GlobalNamespace::StandardScoreSyncStateDeltaNetSerializable::get_baseId)> {
static const MethodInfo* get() {
return ::il2cpp_utils::FindMethod(classof(GlobalNamespace::StandardScoreSyncStateDeltaNetSerializable*), "get_baseId", std::vector<Il2CppClass*>(), ::std::vector<const Il2CppType*>{});
}
};
// Writing MetadataGetter for method: GlobalNamespace::StandardScoreSyncStateDeltaNetSerializable::set_baseId
// Il2CppName: set_baseId
template<>
struct ::il2cpp_utils::il2cpp_type_check::MetadataGetter<static_cast<void (GlobalNamespace::StandardScoreSyncStateDeltaNetSerializable::*)(::GlobalNamespace::SyncStateId)>(&GlobalNamespace::StandardScoreSyncStateDeltaNetSerializable::set_baseId)> {
static const MethodInfo* get() {
static auto* value = &::il2cpp_utils::GetClassFromName("", "SyncStateId")->byval_arg;
return ::il2cpp_utils::FindMethod(classof(GlobalNamespace::StandardScoreSyncStateDeltaNetSerializable*), "set_baseId", std::vector<Il2CppClass*>(), ::std::vector<const Il2CppType*>{value});
}
};
// Writing MetadataGetter for method: GlobalNamespace::StandardScoreSyncStateDeltaNetSerializable::get_timeOffsetMs
// Il2CppName: get_timeOffsetMs
template<>
struct ::il2cpp_utils::il2cpp_type_check::MetadataGetter<static_cast<int (GlobalNamespace::StandardScoreSyncStateDeltaNetSerializable::*)()>(&GlobalNamespace::StandardScoreSyncStateDeltaNetSerializable::get_timeOffsetMs)> {
static const MethodInfo* get() {
return ::il2cpp_utils::FindMethod(classof(GlobalNamespace::StandardScoreSyncStateDeltaNetSerializable*), "get_timeOffsetMs", std::vector<Il2CppClass*>(), ::std::vector<const Il2CppType*>{});
}
};
// Writing MetadataGetter for method: GlobalNamespace::StandardScoreSyncStateDeltaNetSerializable::set_timeOffsetMs
// Il2CppName: set_timeOffsetMs
template<>
struct ::il2cpp_utils::il2cpp_type_check::MetadataGetter<static_cast<void (GlobalNamespace::StandardScoreSyncStateDeltaNetSerializable::*)(int)>(&GlobalNamespace::StandardScoreSyncStateDeltaNetSerializable::set_timeOffsetMs)> {
static const MethodInfo* get() {
static auto* value = &::il2cpp_utils::GetClassFromName("System", "Int32")->byval_arg;
return ::il2cpp_utils::FindMethod(classof(GlobalNamespace::StandardScoreSyncStateDeltaNetSerializable*), "set_timeOffsetMs", std::vector<Il2CppClass*>(), ::std::vector<const Il2CppType*>{value});
}
};
// Writing MetadataGetter for method: GlobalNamespace::StandardScoreSyncStateDeltaNetSerializable::get_delta
// Il2CppName: get_delta
template<>
struct ::il2cpp_utils::il2cpp_type_check::MetadataGetter<static_cast<::GlobalNamespace::StandardScoreSyncState (GlobalNamespace::StandardScoreSyncStateDeltaNetSerializable::*)()>(&GlobalNamespace::StandardScoreSyncStateDeltaNetSerializable::get_delta)> {
static const MethodInfo* get() {
return ::il2cpp_utils::FindMethod(classof(GlobalNamespace::StandardScoreSyncStateDeltaNetSerializable*), "get_delta", std::vector<Il2CppClass*>(), ::std::vector<const Il2CppType*>{});
}
};
// Writing MetadataGetter for method: GlobalNamespace::StandardScoreSyncStateDeltaNetSerializable::set_delta
// Il2CppName: set_delta
template<>
struct ::il2cpp_utils::il2cpp_type_check::MetadataGetter<static_cast<void (GlobalNamespace::StandardScoreSyncStateDeltaNetSerializable::*)(::GlobalNamespace::StandardScoreSyncState)>(&GlobalNamespace::StandardScoreSyncStateDeltaNetSerializable::set_delta)> {
static const MethodInfo* get() {
static auto* value = &::il2cpp_utils::GetClassFromName("", "StandardScoreSyncState")->byval_arg;
return ::il2cpp_utils::FindMethod(classof(GlobalNamespace::StandardScoreSyncStateDeltaNetSerializable*), "set_delta", std::vector<Il2CppClass*>(), ::std::vector<const Il2CppType*>{value});
}
};
// Writing MetadataGetter for method: GlobalNamespace::StandardScoreSyncStateDeltaNetSerializable::Serialize
// Il2CppName: Serialize
template<>
struct ::il2cpp_utils::il2cpp_type_check::MetadataGetter<static_cast<void (GlobalNamespace::StandardScoreSyncStateDeltaNetSerializable::*)(::LiteNetLib::Utils::NetDataWriter*)>(&GlobalNamespace::StandardScoreSyncStateDeltaNetSerializable::Serialize)> {
static const MethodInfo* get() {
static auto* writer = &::il2cpp_utils::GetClassFromName("LiteNetLib.Utils", "NetDataWriter")->byval_arg;
return ::il2cpp_utils::FindMethod(classof(GlobalNamespace::StandardScoreSyncStateDeltaNetSerializable*), "Serialize", std::vector<Il2CppClass*>(), ::std::vector<const Il2CppType*>{writer});
}
};
// Writing MetadataGetter for method: GlobalNamespace::StandardScoreSyncStateDeltaNetSerializable::Deserialize
// Il2CppName: Deserialize
template<>
struct ::il2cpp_utils::il2cpp_type_check::MetadataGetter<static_cast<void (GlobalNamespace::StandardScoreSyncStateDeltaNetSerializable::*)(::LiteNetLib::Utils::NetDataReader*)>(&GlobalNamespace::StandardScoreSyncStateDeltaNetSerializable::Deserialize)> {
static const MethodInfo* get() {
static auto* reader = &::il2cpp_utils::GetClassFromName("LiteNetLib.Utils", "NetDataReader")->byval_arg;
return ::il2cpp_utils::FindMethod(classof(GlobalNamespace::StandardScoreSyncStateDeltaNetSerializable*), "Deserialize", std::vector<Il2CppClass*>(), ::std::vector<const Il2CppType*>{reader});
}
};
// Writing MetadataGetter for method: GlobalNamespace::StandardScoreSyncStateDeltaNetSerializable::Release
// Il2CppName: Release
template<>
struct ::il2cpp_utils::il2cpp_type_check::MetadataGetter<static_cast<void (GlobalNamespace::StandardScoreSyncStateDeltaNetSerializable::*)()>(&GlobalNamespace::StandardScoreSyncStateDeltaNetSerializable::Release)> {
static const MethodInfo* get() {
return ::il2cpp_utils::FindMethod(classof(GlobalNamespace::StandardScoreSyncStateDeltaNetSerializable*), "Release", std::vector<Il2CppClass*>(), ::std::vector<const Il2CppType*>{});
}
};
// Writing MetadataGetter for method: GlobalNamespace::StandardScoreSyncStateDeltaNetSerializable::New_ctor
// Il2CppName: .ctor
// Cannot get method pointer of value based method overload from template for constructor!
// Try using FindMethod instead!
| 60.239316 | 270 | 0.769154 | RedBrumbler |
fa502910a6e0e028b3322a7c64f5f3c6ebe22dd2 | 56,168 | cpp | C++ | middleware/transaction/source/manager/handle.cpp | casualcore/casual | 047a4eaabbba52ad3ce63dc698a9325ad5fcec6d | [
"MIT"
] | null | null | null | middleware/transaction/source/manager/handle.cpp | casualcore/casual | 047a4eaabbba52ad3ce63dc698a9325ad5fcec6d | [
"MIT"
] | null | null | null | middleware/transaction/source/manager/handle.cpp | casualcore/casual | 047a4eaabbba52ad3ce63dc698a9325ad5fcec6d | [
"MIT"
] | 1 | 2022-02-21T18:30:25.000Z | 2022-02-21T18:30:25.000Z | //!
//! Copyright (c) 2015, The casual project
//!
//! This software is licensed under the MIT license, https://opensource.org/licenses/MIT
//!
#include "transaction/manager/handle.h"
#include "transaction/manager/action.h"
#include "transaction/common.h"
#include "transaction/manager/admin/server.h"
#include "casual/assert.h"
#include "common/message/handle.h"
#include "common/event/listen.h"
#include "common/server/handle/call.h"
#include "common/code/raise.h"
#include "common/code/convert.h"
#include "common/communication/instance.h"
#include "common/communication/ipc/flush/send.h"
#include "configuration/message.h"
#include "domain/pending/message/send.h"
namespace casual
{
namespace transaction
{
namespace manager
{
namespace ipc
{
common::communication::ipc::inbound::Device& device()
{
return common::communication::ipc::inbound::device();
}
} // ipc
namespace handle
{
namespace local
{
namespace
{
namespace detail
{
namespace transaction
{
template< typename M, typename I>
auto find_or_add_and_involve( State& state, M&& message, I&& involved)
{
// Find the transaction
auto transaction = common::algorithm::find( state.transactions, message.trid);
if( ! transaction)
{
state.transactions.emplace_back( message.trid);
auto end = std::end( state.transactions);
transaction = common::range::make( std::prev( end), end);
}
if( auto branch = common::algorithm::find( transaction->branches, message.trid))
branch->involve( involved);
else
transaction->branches.emplace_back( message.trid).involve( involved);
return transaction;
}
template< typename M>
auto find_or_add_and_involve( State& state, M&& message)
{
return find_or_add_and_involve( state, std::forward< M>( message), message.involved);
}
} // transaction
namespace branch
{
template< typename M>
state::transaction::Branch& find_or_add( State& state, M&& message)
{
// Find the transaction
if( auto transaction = common::algorithm::find( state.transactions, message.trid))
{
// try find the branch
auto branch = common::algorithm::find( transaction->branches, message.trid);
if( branch)
return *branch;
return transaction->branches.emplace_back( message.trid);
}
return state.transactions.emplace_back( message.trid).branches.back();
}
} // branch
namespace persist
{
void send( State& state)
{
// persist transaction log
state.persistent.log.persist();
// we'll consume every message either way
auto persistent = std::exchange( state.persistent.replies, {});
common::log::line( verbose::log, "persistent: ", persistent);
auto direct_send = []( auto& message)
{
return common::message::pending::non::blocking::send( message);
};
// try send directly
auto pending = common::algorithm::remove_if( persistent, direct_send);
common::log::line( verbose::log, "pending: ", pending);
auto pending_send = []( auto& message)
{
casual::domain::pending::message::send( message);
};
// send failed non-blocking sends to pending
common::algorithm::for_each( pending, pending_send);
}
namespace batch
{
void send( State& state)
{
// check if we've reach our "batch-limit", if so, persit and send replies
if( state.persistent.replies.size() >= platform::batch::transaction::persistence)
detail::persist::send( state);
}
} // batch
} // persist
namespace send::persist
{
template< typename M>
void reply( State& state, M&& message, const common::process::Handle& target)
{
state.persistent.replies.emplace_back( std::move( message), target);
detail::persist::batch::send( state);
}
} // send::persist
namespace accumulate
{
template< typename R, typename O>
auto code( R&& range, O&& outcome, common::code::xa code = common::code::xa::read_only)
{
// if there are 'failed' in outcome we have (??) to classify this as heuristic_hazard,
// since we don't know what could have happend...
auto is_failed = []( auto& outcome){ return outcome.state == decltype( outcome.state)::failed;};
code = common::algorithm::any_of( outcome, is_failed) ? common::code::xa::heuristic_hazard : code;
return state::code::priority::convert( common::algorithm::accumulate( range, state::code::priority::convert( code), []( auto result, auto& reply)
{
return std::min( result, state::code::priority::convert( reply.state));
}));
}
} // accumulate
namespace branch
{
template< typename M, typename I>
auto involved( State& state, const M& message, I&& involved)
{
auto transaction = common::algorithm::find( state.transactions, message.trid);
if( ! transaction)
{
state.transactions.emplace_back( message.trid);
auto end = std::end( state.transactions);
transaction = common::range::make( std::prev( end), end);
}
if( auto branch = common::algorithm::find( transaction->branches, message.trid))
branch->involve( involved);
else
transaction->branches.emplace_back( message.trid).involve( involved);
// remove all branches that is not associated with resources, if any.
transaction->purge();
return transaction;
}
template< typename M>
auto involved( State& state, const M& message)
{
return branch::involved( state, message, message.involved);
}
} // branch
namespace send
{
template< typename M, typename C>
bool reply( const M& message, C custom)
{
auto reply = common::message::reverse::type( message);
reply.trid = message.trid;
custom( reply);
return common::predicate::boolean( common::communication::ipc::flush::optional::send( message.process.ipc, reply));
}
namespace resource
{
template< typename M>
auto request( State& state, M&& request)
{
if( state::resource::id::local( request.resource))
{
if( auto found = state.idle( request.resource))
{
auto correlation = common::communication::ipc::flush::send( found->process.ipc, request);
found->state( state::resource::Proxy::Instance::State::busy);
found->metrics.requested = platform::time::clock::type::now();
return correlation;
}
common::log::line( log, "could not send to resource: ", request.resource, " - action: try later");
return state.pending.requests.emplace_back( request.resource, std::move( request)).message.correlation();
}
auto& resource = state.get_external( request.resource);
return common::communication::ipc::flush::send( resource.process.ipc, request);
}
} // resource
} // send
namespace coordinate
{
namespace pending
{
template< typename Request, typename Branches, typename P>
auto branches( State& state, const Branches& branches, P pending, common::flag::xa::Flags flags = common::flag::xa::Flag::no_flags)
{
return common::algorithm::accumulate( branches, std::move( pending), [ &state, flags]( auto result, const auto& branch)
{
for( auto& resource : branch.resources)
{
Request request{ common::process::handle()};
request.trid = branch.trid;
request.resource = resource.id;
request.flags = flags;
result.emplace_back( send::resource::request( state, request), resource.id);
}
return result;
});
}
template< typename Request, typename Replies, typename P>
auto replies( State& state, Replies&& replies, P pending, common::flag::xa::Flags flags = common::flag::xa::Flag::no_flags)
{
return common::algorithm::accumulate( replies, std::move( pending), [ &state, flags]( auto result, const auto& reply)
{
Request request{ common::process::handle()};
request.trid = reply.trid;
request.resource = reply.resource;
request.flags = flags;
result.emplace_back( send::resource::request( state, request), reply.resource);
return result;
});
}
} // pending
struct Destination
{
common::process::Handle process;
common::strong::correlation::id correlation;
common::strong::execution::id execution;
common::strong::resource::id resource;
};
template< typename M>
auto destination( const M& message)
{
if constexpr( common::traits::is::any_v< M, common::message::transaction::commit::Request, common::message::transaction::rollback::Request>)
// local "user" commit/rollback request has no specific resource (of course)
return Destination{ message.process, message.correlation, message.execution, common::strong::resource::id{}};
else
// We need to keep the _origin resource_ for the reply later
return Destination{ message.process, message.correlation, message.execution, message.resource};
}
namespace create
{
template< typename Reply>
auto reply( const common::transaction::ID& trid, const detail::coordinate::Destination& destination, common::code::xa code)
{
// casual (right now) classifies _invalid_xid_ (no-tran) as _not an error_, and set read_only.
// We don't really know (?) how rm:s respond if they have been associated with a trid, and no work from the
// user has been done.
if( code == decltype( code)::invalid_xid)
code = decltype( code)::read_only;
Reply result{ common::process::handle()};
result.trid = trid;
result.correlation = destination.correlation;
result.execution = destination.execution;
// local transaction instigator replies need to convert to tx state
if constexpr( common::traits::is::any_v< Reply, common::message::transaction::commit::Reply, common::message::transaction::rollback::Reply>)
result.state = common::code::convert::to::tx( code);
else
{
result.state = code;
result.resource = destination.resource;
}
return result;
}
} // create
namespace remove
{
void transaction( State& state, common::transaction::id::range::range_type global)
{
state.persistent.log.remove( global);
if( auto found = common::algorithm::find( state.transactions, global))
state.transactions.erase( std::begin( found));
}
} // remove
template< typename Reply, typename Pending>
auto commit( State& state, Pending pending, const common::transaction::ID& origin, detail::coordinate::Destination destination, common::code::xa code = common::code::xa::read_only)
{
// note: everything captured needs to by value (besides State if used)
state.coordinate.commit( std::move( pending), [ &state, origin, destination, code]( auto replies, auto outcome)
{
Trace trace{ "transaction::manager::handle::local::detail::coordinate::commit"};
common::log::line( verbose::log, "replies: ", replies, ", outcome: ", outcome);
auto reply = create::reply< Reply>( origin, destination, detail::accumulate::code( replies, outcome, code));
if constexpr( common::traits::is::any_v< Reply, common::message::transaction::commit::Reply>)
reply.stage = decltype( reply.stage)::commit;
common::communication::ipc::flush::optional::send( destination.process.ipc, reply);
remove::transaction( state, common::transaction::id::range::global( origin));
});
}
template< typename Reply, typename Pending>
auto rollback( State& state, Pending pending, const common::transaction::ID& origin, detail::coordinate::Destination destination, common::code::xa code = common::code::xa::read_only)
{
// note: everything captured needs to by value (besides State if used)
state.coordinate.rollback( std::move( pending), [ &state, origin, destination, code]( auto replies, auto outcome)
{
Trace trace{ "transaction::manager::handle::local::detail::coordinate::rollback"};
common::log::line( verbose::log, "replies: ", replies, ", outcome: ", outcome);
auto reply = create::reply< Reply>( origin, destination, detail::accumulate::code( replies, outcome, code));
if constexpr( common::traits::is::any_v< Reply, common::message::transaction::commit::Reply>)
reply.stage = decltype( reply.stage)::rollback;
common::communication::ipc::flush::optional::send( destination.process.ipc, reply);
remove::transaction( state, common::transaction::id::range::global( origin));
});
}
template< typename Reply, typename Pending>
auto prepare( State& state, Pending pending, const common::transaction::ID& origin, detail::coordinate::Destination destination)
{
// note: everything captured needs to be by value (besides State if used)
state.coordinate.prepare( std::move( pending), [ &state, origin, destination]( auto replies, auto outcome)
{
Trace trace{ "transaction::manager::handle::local::detail::coordinate::prepare"};
common::log::line( verbose::log, "replies: ", replies, ", outcome: ", outcome);
auto transaction = common::algorithm::find( state.transactions, origin);
casual::assertion( transaction, "failed to find transaction 'context' for: ", origin);
// filter away all read-only replies
auto [ active, read_only] = common::algorithm::partition( replies, []( auto& reply){ return reply.state != decltype( reply.state)::read_only;});
// purge all read_only resources for each branch, and if a branch has 0 resources, remove it.
transaction->purge( read_only);
auto code = detail::accumulate::code( active, outcome);
if( code == decltype( code)::read_only)
{
state.transactions.erase( std::begin( transaction));
// we can send the reply directly
auto reply = create::reply< Reply>( origin, destination, code);
if constexpr( common::traits::is::any_v< Reply, common::message::transaction::commit::Reply>)
reply.stage = decltype( reply.stage)::commit;
common::communication::ipc::flush::optional::send( destination.process.ipc, reply);
}
else if( code == decltype( code)::ok)
{
// Prepare has gone ok. Log persistant state
state.persistent.log.prepare( *transaction);
// add _commit-prepare_ message to persistent reply, if reply is the commit reply type
if constexpr( common::traits::is::any_v< Reply, common::message::transaction::commit::Reply>)
{
auto reply = create::reply< Reply>( origin, destination, code);
reply.stage = decltype( reply.stage)::prepare;
detail::send::persist::reply( state, std::move( reply), destination.process);
}
// we try to commit all active resources.
auto pending = detail::coordinate::pending::replies< common::message::transaction::resource::commit::Request>(
state, active, state.coordinate.commit.empty_pendings());
detail::coordinate::commit< Reply>( state, std::move( pending), origin, destination, code);
}
else
{
// we try to rollback all active resources, if any.
auto pending = detail::coordinate::pending::replies< common::message::transaction::resource::rollback::Request>(
state, active, state.coordinate.rollback.empty_pendings());
detail::coordinate::rollback< Reply>( state, std::move( pending), origin, destination, code);
}
});
}
} // coordinate
} // detail
namespace commit
{
auto request( State& state)
{
return [&state]( const common::message::transaction::commit::Request& message)
{
Trace trace{ "transaction::manager::handle::local::commit::request"};
common::log::line( log, "message: ", message);
auto transaction = detail::branch::involved( state, message);
common::log::line( verbose::log, "transaction: ", *transaction);
if( transaction->stage > decltype( transaction->stage())::involved)
{
// transaction is not in the correct 'stage'
detail::send::reply( message, []( auto& reply)
{
reply.state = decltype( reply.state)::protocol;
reply.stage = decltype( reply.stage)::commit;
});
return;
}
transaction->owner = message.process;
// Only the owner of the transaction can fiddle with the transaction ?
switch( transaction->resource_count())
{
case 0:
{
common::log::line( log, transaction->global, " no resources involved: ");
// We can remove this transaction
state.transactions.erase( std::begin( transaction));
detail::send::reply( message, []( auto& reply)
{
reply.state = decltype( reply.state)::ok;
reply.stage = decltype( reply.stage)::commit;
});
break;
}
case 1:
{
// Only one resource involved, we do a one-phase-commit optimization.
common::log::line( log, "global: ", transaction->global, " - only one resource involved");
transaction->stage = decltype( transaction->stage())::commit;
auto pending = detail::coordinate::pending::branches< common::message::transaction::resource::commit::Request>(
state, transaction->branches, state.coordinate.commit.empty_pendings(), common::flag::xa::Flag::one_phase);
detail::coordinate::commit< common::message::transaction::commit::Reply>(
state, std::move( pending), message.trid, detail::coordinate::destination( message));
break;
}
default:
{
// More than one resource involved, we do the prepare stage
common::log::line( log, "global: ", transaction->global, " more than one resource involved");
transaction->stage = decltype( transaction->stage())::prepare;
auto pending = detail::coordinate::pending::branches< common::message::transaction::resource::prepare::Request>(
state, transaction->branches, state.coordinate.prepare.empty_pendings());
detail::coordinate::prepare< common::message::transaction::commit::Reply>(
state, std::move( pending), message.trid, detail::coordinate::destination( message));
break;
}
}
};
}
} // commit
namespace rollback
{
auto request( State& state)
{
return [&state]( const common::message::transaction::rollback::Request& message)
{
Trace trace{ "transaction::manager::handle::local::rollback::request"};
common::log::line( verbose::log, "message: ", message);
auto transaction = detail::branch::involved( state, message);
common::log::line( verbose::log, "transaction: ", *transaction);
transaction->stage = decltype( transaction->stage())::rollback;
transaction->owner = message.process;
auto pending = detail::coordinate::pending::branches< common::message::transaction::resource::rollback::Request>(
state, transaction->branches, state.coordinate.rollback.empty_pendings());
detail::coordinate::rollback< common::message::transaction::rollback::Reply>(
state, std::move( pending), message.trid, detail::coordinate::destination( message));
};
}
} // rollback
namespace resource
{
namespace detail
{
namespace instance
{
void done( State& state, state::resource::Proxy::Instance& instance)
{
Trace trace{ "transaction::manager::handle::local::resource::detail::instance::done"};
instance.state( state::resource::Proxy::Instance::State::idle);
if( auto request = common::algorithm::find( state.pending.requests, instance.id))
{
// We got a pending request for this resource, let's oblige
if( common::communication::ipc::flush::optional::send( instance.process.ipc, request->message))
{
instance.state( state::resource::Proxy::Instance::State::busy);
state.pending.requests.erase( std::begin( request));
}
else
common::log::line( common::log::category::error, "the instance: ", instance , " - does not seem to be running");
}
}
template< typename M>
void replied( State& state, const M& message)
{
if( state::resource::id::local( message.resource))
{
// The resource is a local resource proxy, and it's done, and ready for more work
auto& instance = state.get_instance( message.resource, message.process.pid);
{
instance::done( state, instance);
instance.metrics.add( message);
}
}
}
} // instance
} // detail
namespace involved
{
auto request( State& state)
{
return [ &state]( common::message::transaction::resource::involved::Request& message)
{
Trace trace{ "transaction::manager::handle::local::resource::involved::request"};
common::log::line( verbose::log, "message: ", message);
auto& branch = local::detail::branch::find_or_add( state, message);
// prepare and send the reply
auto reply = common::message::reverse::type( message);
reply.involved = common::algorithm::transform( branch.resources, []( auto& resource){ return resource.id;});
common::communication::device::blocking::optional::send( message.process.ipc, reply);
// partition what we don't got since before
auto involved = std::get< 1>( common::algorithm::intersection( message.involved, reply.involved));
// partition the new involved based on which we've got configured resources for
auto [ known, unknown] = common::algorithm::partition( involved, [&]( auto& resource)
{
return common::predicate::boolean( common::algorithm::find( state.resources, resource));
});
// add new involved resources, if any.
branch.involve( known);
// if we've got some resources that we don't know about.
// TODO: should we set the transaction to rollback only?
if( unknown)
{
common::log::line( common::log::category::error, "unknown resources: ", unknown, " - action: discard");
common::log::line( common::log::category::verbose::error, "trid: ", message.trid);
}
};
}
} // involved
namespace prepare
{
auto reply( State& state)
{
return [&state]( const common::message::transaction::resource::prepare::Reply& message)
{
Trace trace{ "transaction::manager::handle::local::resource::prepare::reply"};
common::log::line( verbose::log, "message: ", message);
detail::instance::replied( state, message);
state.coordinate.prepare( message);
};
}
} // prepare
namespace commit
{
auto reply( State& state)
{
return [&state]( const common::message::transaction::resource::commit::Reply& message)
{
Trace trace{ "transaction::manager::handle::local::resource::commit::reply"};
common::log::line( verbose::log, "message: ", message);
detail::instance::replied( state, message);
state.coordinate.commit( message);
};
}
} // commit
namespace rollback
{
auto reply( State& state)
{
return [&state]( const common::message::transaction::resource::rollback::Reply& message)
{
Trace trace{ "transaction::manager::handle::local::resource::rollback::reply"};
common::log::line( verbose::log, "message: ", message);
detail::instance::replied( state, message);
state.coordinate.rollback( message);
};
}
} // rollback
namespace external
{
namespace detail
{
namespace send
{
template< typename M, typename C>
bool reply( const M& message, C custom)
{
auto reply = common::message::reverse::type( message);
reply.trid = message.trid;
reply.resource = message.resource;
custom( reply);
return common::predicate::boolean( common::communication::ipc::flush::optional::send( message.process.ipc, reply));
}
} // send
namespace prepare::commit
{
//! This phase are 'exactly' the same for external prepare and commit, except for the
//! reply message/type (of course), which we deduce from the request message.
template< typename M>
void phase( State& state, M&& message)
{
Trace trace{ "transaction::manager::handle::local::resource::external::detail::prepare::commit::phase"};
common::log::line( verbose::log, "message: ", message);
// reply type, will be different for prepare and commit
using Reply = decltype( common::message::reverse::type( message));
auto transaction = common::algorithm::find( state.transactions, message.trid);
if( ! transaction || transaction->stage > decltype( transaction->stage())::involved)
{
// Either the transaction is absent (???) or we're already in at least the prepare stage.
// Eitherway we reply with read_only
detail::send::reply( message, []( auto& reply)
{
reply.statistics.start = platform::time::clock::type::now();
reply.statistics.end = reply.statistics.start;
reply.state = decltype( reply.state)::read_only;
});
return;
}
// external TM is running the show, let's oblige
transaction->owner = message.process;
switch( transaction->resource_count())
{
case 0:
{
common::log::line( log, transaction->global, " no resources involved: ");
// We can remove this transaction
state.transactions.erase( std::begin( transaction));
detail::send::reply( message, [ transaction]( auto& reply)
{
reply.statistics.start = transaction->started;
reply.statistics.end = platform::time::clock::type::now();
reply.state = decltype( reply.state)::read_only;
});
break;
}
case 1:
{
// Only one resource involved, we do a one-phase-commit optimization.
common::log::line( log, "global: ", transaction->global, " - only one resource involved");
transaction->stage = decltype( transaction->stage())::commit;
auto pending = local::detail::coordinate::pending::branches< common::message::transaction::resource::commit::Request>(
state, transaction->branches, state.coordinate.commit.empty_pendings(), common::flag::xa::Flag::one_phase);
// different reply, depending on prepare or commit phase, below
local::detail::coordinate::commit< Reply>(
state, std::move( pending), message.trid, local::detail::coordinate::destination( message));
break;
}
default:
{
// More than one resource involved, we do the prepare stage
common::log::line( log, "global: ", transaction->global, " more than one resource involved");
transaction->stage = decltype( transaction->stage())::prepare;
auto pending = local::detail::coordinate::pending::branches< common::message::transaction::resource::prepare::Request>(
state, transaction->branches, state.coordinate.prepare.empty_pendings());
// different reply, depending on prepare or commit phase, below
local::detail::coordinate::prepare< Reply>(
state, std::move( pending), message.trid, local::detail::coordinate::destination( message));
break;
}
}
}
} // prepare::commit
} // detail
namespace involved
{
auto request( State& state)
{
return [ &state]( common::message::transaction::resource::external::Involved& message)
{
Trace trace{ "transaction::manager::handle::local::resource::external::involved::request"};
common::log::line( log, "message: ", message);
auto id = state::resource::external::proxy::id( state, message.process);
auto& transaction = *local::detail::transaction::find_or_add_and_involve( state, message, id);
common::log::line( verbose::log, "transaction: ", transaction);
};
}
} // involved
namespace prepare
{
auto request( State& state)
{
return [&state]( const common::message::transaction::resource::prepare::Request& message)
{
// we use the generic prepare/commit phase
detail::prepare::commit::phase( state, message);
};
}
} // prepare
namespace commit
{
auto request( State& state)
{
return [&state]( const common::message::transaction::resource::commit::Request& message)
{
// we use the generic prepare/commit phase
detail::prepare::commit::phase( state, message);
};
}
} // commit
namespace rollback
{
auto request( State& state)
{
return [&state]( const common::message::transaction::resource::rollback::Request& message)
{
Trace trace{ "transaction::manager::handle::local::resource::external::rollback::request"};
common::log::line( verbose::log, "message: ", message);
auto transaction = common::algorithm::find( state.transactions, message.trid);
if( ! transaction || transaction->stage > decltype( transaction->stage())::involved)
{
// Either the transaction is absent (???) or we're already in at least the prepare stage.
// Eitherway we reply with read_only
detail::send::reply( message, []( auto& reply)
{
reply.statistics.start = platform::time::clock::type::now();
reply.statistics.end = reply.statistics.start;
reply.state = decltype( reply.state)::read_only;
});
return;
}
// We dont 'optimize' the rollback phase. We could check if there are 0 resources involved and
// possible gain a few us.
transaction->stage = decltype( transaction->stage())::rollback;
transaction->owner = message.process;
auto pending = local::detail::coordinate::pending::branches< common::message::transaction::resource::rollback::Request>(
state, transaction->branches, state.coordinate.rollback.empty_pendings());
local::detail::coordinate::rollback< common::message::transaction::resource::rollback::Reply>(
state, std::move( pending), message.trid, local::detail::coordinate::destination( message));
};
}
} // rollback
} // external
namespace configuration
{
auto request( State& state)
{
return [&state]( const common::message::transaction::resource::configuration::Request& message)
{
Trace trace{ "transaction::manager::handle::local::resource::configuration::request"};
common::log::line( log, "message: ", message);
auto reply = common::message::reverse::type( message);
{
auto& resource = state.get_resource( message.id);
reply.resource.id = message.id;
reply.resource.key = resource.configuration.key;
reply.resource.openinfo = resource.configuration.openinfo;
reply.resource.closeinfo = resource.configuration.closeinfo;
}
common::communication::device::blocking::optional::send( message.process.ipc, reply);
};
}
} // configuration
auto ready( State& state)
{
return [&state]( const common::message::transaction::resource::Ready& message)
{
Trace trace{ "transaction::manager::handle::local::resource::ready"};
common::log::line( log, "message: ", message);
auto& instance = state.get_instance( message.id, message.process.pid);
instance.process = message.process;
detail::instance::done( state, instance);
};
}
} // resource
namespace process
{
auto exit( State& state)
{
return [ &state]( common::message::event::process::Exit& message)
{
Trace trace{ "transaction::manager::handle::local::process::exit"};
common::log::line( verbose::log, "message: ", message);
// Check if it's a resource proxy instance
if( state.remove_instance( message.state.pid))
{
common::communication::device::blocking::send(
common::communication::instance::outbound::domain::manager::device(), message);
return;
}
auto trids = common::algorithm::accumulate( state.transactions, std::vector< common::transaction::ID>{}, [ &message]( auto result, auto& transaction)
{
if( ! transaction.branches.empty() && transaction.branches.back().trid.owner().pid == message.state.pid)
result.push_back( transaction.branches.back().trid);
return result;
});
common::log::line( verbose::log, "trids: ", trids);
for( auto& trid : trids)
{
common::message::transaction::rollback::Request request;
request.process = common::process::handle();
request.trid = trid;
// This could change the state, that's why we don't do it directly in the loop above.
local::rollback::request( state)( request);
}
};
}
} // process
namespace configuration
{
namespace alias
{
auto request( State& state)
{
return [&state]( const common::message::transaction::configuration::alias::Request& message)
{
Trace trace{ "transaction::manager::handle::local::configuration::alias::request"};
common::log::line( verbose::log, "message: ", message);
auto reply = state.configuration( message);
common::log::line( verbose::log, "reply: ", reply);
common::communication::device::blocking::optional::send( message.process.ipc, reply);
};
}
} // alias
auto request( State& state)
{
return [&state]( const casual::configuration::message::Request& message)
{
Trace trace{ "transaction::manager::handle::local::configuration::request"};
common::log::line( verbose::log, "message: ", message);
auto reply = common::message::reverse::type( message);
reply.model.transaction = state.configuration();
common::communication::device::blocking::optional::send( message.process.ipc, reply);
};
}
} // configuration
} // <unnamed>
} // local
namespace process
{
void exit( const common::process::lifetime::Exit& exit)
{
Trace trace{ "transaction::manager::handle::process::exit"};
common::log::line( verbose::log, "exit: ", exit);
// push it to handle it later together with other process exit events
ipc::device().push( common::message::event::process::Exit{ exit});
}
}
namespace persist
{
void send( State& state)
{
Trace trace{ "transaction::manager::handle::persist:send"};
// if we don't have any persistent replies, we don't need to persist
if( ! state.persistent.replies.empty())
local::detail::persist::send( state);
}
} // persist
namespace startup
{
dispatch_type handlers( State& state)
{
return common::message::dispatch::handler( ipc::device(),
common::message::handle::defaults( ipc::device()),
local::process::exit( state),
local::resource::configuration::request( state),
local::resource::ready( state)
);
}
} // startup
dispatch_type handlers( State& state)
{
return common::message::dispatch::handler( ipc::device(),
common::message::handle::defaults( ipc::device()),
common::event::listener( local::process::exit( state)),
local::commit::request( state),
local::rollback::request( state),
local::resource::involved::request( state),
local::configuration::alias::request( state),
local::configuration::request( state),
local::resource::configuration::request( state),
local::resource::ready( state),
local::resource::prepare::reply( state),
local::resource::commit::reply( state),
local::resource::rollback::reply( state),
local::resource::external::involved::request( state),
local::resource::external::prepare::request( state),
local::resource::external::commit::request( state),
local::resource::external::rollback::request( state),
common::server::handle::admin::Call{
manager::admin::services( state)}
);
}
void abort( State& state)
{
Trace trace{ "transaction::manager::handle::abort"};
auto scale_down = [&]( auto& resource)
{
common::exception::guard( [&](){
resource.configuration.instances = 0;
manager::action::resource::scale::instances( state, resource);
});
};
common::algorithm::for_each( state.resources, scale_down);
auto processes = state.processes();
common::process::lifetime::wait( processes, std::chrono::milliseconds( processes.size() * 100));
}
} // handle
} // manager
} // transaction
} // casual
| 51.201459 | 206 | 0.420293 | casualcore |
fa516317ceb552f45ff177c73ba06212b5698ec4 | 8,309 | cpp | C++ | test/BondStereopermutator.cpp | Dom1L/molassembler | dafc656b1aa846b65b1fd1e06f3740ceedcf22db | [
"BSD-3-Clause"
] | 17 | 2020-11-27T14:59:34.000Z | 2022-03-28T10:31:25.000Z | test/BondStereopermutator.cpp | Dom1L/molassembler | dafc656b1aa846b65b1fd1e06f3740ceedcf22db | [
"BSD-3-Clause"
] | null | null | null | test/BondStereopermutator.cpp | Dom1L/molassembler | dafc656b1aa846b65b1fd1e06f3740ceedcf22db | [
"BSD-3-Clause"
] | 6 | 2020-12-09T09:21:53.000Z | 2021-08-22T15:42:21.000Z | /*!@file
* @copyright This code is licensed under the 3-clause BSD license.
* Copyright ETH Zurich, Laboratory of Physical Chemistry, Reiher Group.
* See LICENSE.txt for details.
*/
#define BOOST_FILESYSTEM_NO_DEPRECATED
#include "boost/filesystem.hpp"
#include "boost/test/unit_test.hpp"
#include "Molassembler/Conformers.h"
#include "Molassembler/IO.h"
#include "Molassembler/Molecule.h"
#include "Molassembler/Graph.h"
#include "Molassembler/AtomStereopermutator.h"
#include "Molassembler/BondStereopermutator.h"
#include "Molassembler/StereopermutatorList.h"
#include <iostream>
using namespace Scine;
using BondIndex = Molassembler::BondIndex;
struct Expectation {
BondIndex edge;
unsigned numAssignments;
unsigned fittedAssignment;
Expectation(
BondIndex passEdge,
unsigned assignments,
unsigned assignment
) : edge(passEdge),
numAssignments(assignments),
fittedAssignment(assignment)
{
assert(assignments > 1);
}
Expectation(
BondIndex passEdge,
unsigned assignments
) : edge(passEdge),
numAssignments(assignments)
{
assert(assignments == 1);
// Define the value, but no comparisons with it should be performed
fittedAssignment = std::numeric_limits<unsigned>::max();
}
};
/* This is the current interpretation of yielded indices of permutations of
* BondStereopermutator for all combinations of the shapes triangle and
* bent.
*/
constexpr unsigned Z = 1;
constexpr unsigned E = 0;
constexpr unsigned stereogenic = 2;
constexpr unsigned nonStereogenic = 1;
const std::map<std::string, Expectation> recognitionExpectations {
{
"but-2E-ene",
{{0, 1}, stereogenic, E}
},
{
"but-2Z-ene",
{{0, 1}, stereogenic, Z}
},
{
"E-diazene",
{{0, 1}, stereogenic, E}
},
{
"ethanimine",
{{0, 2}, stereogenic, E}
},
{
"ethene",
{{0, 1}, nonStereogenic}
},
{
"methanimine",
{{0, 1}, nonStereogenic}
}
// formaldehyde is omitted, since there cannot be a BondStereopermutator on it
};
void checkExpectations(const boost::filesystem::path& filePath) {
using namespace Molassembler;
using namespace std::string_literals;
std::string moleculeName = filePath.stem().string();
// Read the file
auto mol = IO::read(filePath.string());
// Check if expectations are met
auto findIter = recognitionExpectations.find(filePath.stem().string());
if(findIter == std::end(recognitionExpectations)) {
// There should be no BondStereopermutator in this molecule
auto bondStereopermutatorRange = mol.stereopermutators().bondStereopermutators();
BOOST_CHECK(
std::distance(
bondStereopermutatorRange.first,
bondStereopermutatorRange.second
) == 0
);
/* No DG work is needed since it doesn't involve BondStereopermutator (there
* are none in the molecule)
*/
} else {
const Expectation& expectation = findIter->second;
auto bondStereopermutatorOption = mol.stereopermutators().option(expectation.edge);
BOOST_REQUIRE_MESSAGE(
bondStereopermutatorOption,
"There is no BondStereopermutator on the expected edge for " << moleculeName
);
BOOST_REQUIRE_MESSAGE(
bondStereopermutatorOption->numAssignments() == expectation.numAssignments,
"The expected number of permutations was not met for " << moleculeName
<< ": expected " << expectation.numAssignments << ", got "
<< bondStereopermutatorOption->numAssignments()
);
if(expectation.numAssignments == stereogenic) {
auto assignmentOptional = bondStereopermutatorOption->assigned();
BOOST_REQUIRE(assignmentOptional);
BOOST_REQUIRE_MESSAGE(
assignmentOptional.value() == expectation.fittedAssignment,
"The stereopermutator is not assigned the expected value for "
<< moleculeName << ": Expected " << expectation.fittedAssignment
<< ", got " << *assignmentOptional << " instead"
);
}
// Generate a conformation
auto positionsResult = generateRandomConformation(mol);
// If DG fails, we're screwed
if(!positionsResult) {
BOOST_FAIL(positionsResult.error().message());
}
// Reinterpret the molecule from the existing graph and the generated positions
Molecule reinterpreted {
mol.graph(),
AngstromPositions {positionsResult.value()}
};
bool pass = reinterpreted == mol;
if(!pass) {
std::cout << "Initial molecule: " << mol << "\nReinterpreted:"
<< reinterpreted;
}
BOOST_CHECK_MESSAGE(
pass,
"The reinterpreted molecule does not equal the initial molecule for "
<< moleculeName
);
}
}
BOOST_AUTO_TEST_CASE(BondStereopermutatorConsistency, *boost::unit_test::label("Molassembler")) {
for(
const boost::filesystem::path& currentFilePath :
boost::filesystem::recursive_directory_iterator("ez_stereocenters")
) {
BOOST_CHECK_NO_THROW(
checkExpectations(currentFilePath)
);
}
}
BOOST_AUTO_TEST_CASE(BondStatePropagation, *boost::unit_test::label("Molassembler")) {
using namespace Molassembler;
auto mol = IO::read("ez_stereocenters/but-2E-ene.mol");
// Alter a hydrogen at the bond stereopermutator
const StereopermutatorList& stereopermutators = mol.stereopermutators();
auto bondStereopermutatorRange = stereopermutators.bondStereopermutators();
BOOST_REQUIRE(std::distance(bondStereopermutatorRange.first, bondStereopermutatorRange.second) > 0);
const BondStereopermutator& mainStereopermutator = *bondStereopermutatorRange.first;
BOOST_REQUIRE(mainStereopermutator.assigned());
unsigned priorAssignment = mainStereopermutator.assigned().value();
// Pick a side
const AtomIndex side = mainStereopermutator.placement().first;
// Find a hydrogen substituent
boost::optional<AtomIndex> hydrogenSubstituent;
for(const AtomIndex substituent : mol.graph().adjacents(side)) {
if(mol.graph().elementType(substituent) == Utils::ElementType::H) {
hydrogenSubstituent = substituent;
break;
}
}
BOOST_REQUIRE(hydrogenSubstituent);
// Replace the hydrogen substituent with a fluorine
mol.setElementType(*hydrogenSubstituent, Utils::ElementType::F);
// All references are, in principle, invalidated. Just being extra careful.
auto postPermutatorRange = stereopermutators.bondStereopermutators();
// The new stereopermutator must still be assigned, and have a different assignment
BOOST_REQUIRE(std::distance(postPermutatorRange.first, postPermutatorRange.second) > 0);
const BondStereopermutator& postPermutator = *postPermutatorRange.first;
BOOST_REQUIRE(postPermutator.assigned());
// In this particular case, we know that the final assignment has to be different
BOOST_CHECK(postPermutator.assigned().value() != priorAssignment);
}
BOOST_AUTO_TEST_CASE(StereocentersInSmallCycles, *boost::unit_test::label("Molassembler")) {
// Flat map from cycle size to number of assignments
const std::vector<unsigned> expectedAssignmentsMap {
0, 0, 0, 1, 1, 1, 1, 2, 2
};
using namespace Molassembler;
/* In small cycles, double bond stereopermutators should exclude the E
* stereopermutation and have only a single assignment
*/
for(unsigned cycleSize = 3; cycleSize <= 8; ++cycleSize) {
Molecule mol {
Utils::ElementType::C,
Utils::ElementType::C,
BondType::Double
};
// Add cycle atoms
AtomIndex last = 0;
for(unsigned i = 0; i < cycleSize - 2; ++i) {
last = mol.addAtom(Utils::ElementType::C, last);
}
// Close the cycle
mol.addBond(last, 1);
// Set geometries
for(unsigned i = 0; i < cycleSize; ++i) {
mol.setShapeAtAtom(i, Shapes::Shape::Bent);
}
auto bondStereopermutatorOption = mol.stereopermutators().option(BondIndex {0, 1});
BOOST_REQUIRE_MESSAGE(
bondStereopermutatorOption,
"Expected a BondStereopermutator on {0, 1}, got None"
);
BOOST_CHECK_MESSAGE(
bondStereopermutatorOption->numAssignments() == expectedAssignmentsMap.at(cycleSize),
"Expected " << expectedAssignmentsMap.at(cycleSize)
<< " assignments for cycle of size " << cycleSize
<< ", got " << bondStereopermutatorOption->numAssignments()
<< "instead."
);
}
}
| 30.435897 | 102 | 0.703213 | Dom1L |
fa55c8ca4ebbbcdc70f3a343783d271705b0c954 | 10,452 | cpp | C++ | VoiceBridge/VoiceBridge/kaldi-win/scr/util.cpp | sanyaade-teachings/VoiceBridge | 348b0931f2bfaf33b7e0d18c68c50f448ab3de5c | [
"Apache-2.0"
] | 18 | 2018-02-15T03:14:32.000Z | 2021-07-06T08:21:13.000Z | VoiceBridge/VoiceBridge/kaldi-win/scr/util.cpp | sanyaade-teachings/VoiceBridge | 348b0931f2bfaf33b7e0d18c68c50f448ab3de5c | [
"Apache-2.0"
] | 3 | 2020-10-25T16:35:55.000Z | 2020-10-26T04:59:46.000Z | VoiceBridge/VoiceBridge/kaldi-win/scr/util.cpp | sanyaade-teachings/VoiceBridge | 348b0931f2bfaf33b7e0d18c68c50f448ab3de5c | [
"Apache-2.0"
] | 7 | 2018-09-16T20:40:17.000Z | 2021-07-06T08:21:14.000Z | /*
Copyright 2017-present Zoltan Somogyi (AI-TOOLKIT), All Rights Reserved
You may use this file only if you agree to the software license:
AI-TOOLKIT Open Source Software License - Version 2.1 - February 22, 2018:
https://ai-toolkit.blogspot.com/p/ai-toolkit-open-source-software-license.html.
Also included with the source code distribution in AI-TOOLKIT-LICENSE.txt.
*/
#include "kaldi-win\scr\kaldi_scr.h"
//NOTE: these variables are used in several compilation units and therefore must be accessed with the below accessor functions
// call ReadSilenceAndNonSilencePhones() before using the variable and access them with the two pointer functions
static std::vector<std::string> _silencephones;
static std::vector<std::string> _nonsilencephones;
std::vector<std::string> * Get_silencephones() { return &_silencephones; }
std::vector<std::string> * Get_nonsilencephones() { return &_nonsilencephones; }
//returns -2 if error; -1 if it does not exist; returns 0 if everything is OK (exists and not empty)
int CheckFileExistsAndNotEmpty(fs::path file, bool bShowError)
{
try
{
if (!fs::exists(file) || fs::is_empty(file))
{
if(bShowError)
LOGTW_ERROR << " the file " << file.string() << " does not exist or empty.";
//else LOGTW_INFO << " the file " << file.string() << " does not exist or empty.";
//NOTE: removed info about missing file because it can be confusing. If bShowError=false then it does not matter.
return -1;
}
}
catch (std::exception const& e)
{
LOGTW_FATALERROR << " " << e.what() << ".";
return -2;
}
catch (...)
{
LOGTW_FATALERROR << " Unknown Error.";
return -2;
}
return 0;
}
//check if valid strings in text file
int CheckUTF8AndWhiteSpace(fs::path _path, bool check_last_char_is_nl)
{
try {
StringTable txt = readData(_path.string());
for (StringTable::const_iterator it(txt.begin()), it_end(txt.end()); it != it_end; ++it)
{
for (string_vec::const_iterator itc(it->begin()), itc_end(it->end()); itc != itc_end; ++itc)
{
std::string s = ConvertToUTF8(*itc);
if (s.empty() || !validate_utf8_whitespaces(s)) {
LOGTW_ERROR << " " << _path.string() << " contains disallowed UTF-8 whitespace character(s) or not UTF-8 compatible.";
return -1;
}
}
}
if (check_last_char_is_nl == true)
{
fs::ifstream ifs(_path);
if (ifs.is_open()) {
ifs.seekg(-1, std::ios::end);
char *t = new char[1];
ifs.read(t, 1);
if (*t != '\n') {
LOGTW_ERROR << " " << _path.string() << " does not end in newline.";
return -1;
}
}
}
}
catch (std::exception const& e)
{
LOGTW_FATALERROR << " " << e.what() << ".";
return -1;
}
catch (...)
{
LOGTW_FATALERROR << " Unknown Error.";
return -1;
}
return 0;
}
//checks if every string in the text file is unique and puts all strings in the _v vector
//if check_valid_ending == true it check for some special character endings
// (disambiguation symbols; phones ending in _B, _E, _S or _I will cause problems with word - position - dependent systems in silence_phones.txt)
int CheckDuplicates(fs::path _path, bool check_valid_ending, std::vector<std::string> & _v)
{
try
{
StringTable txt = readData(_path.string());
for (StringTable::const_iterator it(txt.begin()), it_end(txt.end()); it != it_end; ++it)
{
for (string_vec::const_iterator itc(it->begin()), itc_end(it->end()); itc != itc_end; ++itc)
{
std::string s(*itc);
if (check_valid_ending && s.length() > 1) {
std::string ss = s.substr(s.length() - 2);
if (ss == "_B" || ss == "_E" || ss == "_S" || ss == "_I")
{
LOGTW_ERROR << " the characters _B, _E, _S and _I are not allowed as last characters in " << _path.string() << ".";
return -1;
}
}
_v.push_back(s);
}
}
if (!is_unique(_v)) {
LOGTW_ERROR << " duplicates in " << _path.string() << ".";
return -1;
}
}
catch (std::exception const& e)
{
LOGTW_FATALERROR << " " << e.what() << ".";
return -1;
}
catch (...)
{
LOGTW_FATALERROR << " Unknown Error.";
return -1;
}
return 0;
}
//checks the lexicons for consistency
int CheckLexicon(fs::path lp, int num_prob_cols, int num_skipped_cols)
{
//NOTE: ValidateDict() or ReadSilenceAndNonSilencePhones() must be first called in order to read in _silencephones, _nonsilencephones!
if (_silencephones.size() < 1 || _nonsilencephones.size() < 1) {
#ifdef _DEBUG
LOGTW_ERROR << "***DEVELOPER NOTE: ValidateDict() or ReadSilenceAndNonSilencePhones() must be first called in order to read in _silencephones, _nonsilencephones!";
#endif // DEBUG
LOGTW_ERROR << " no silence and/or non-silence phones detected.";
return -1;
}
if (CheckUTF8AndWhiteSpace(lp, true) < 0) return -1;
std::ifstream ifs(lp.string());
if (!ifs) {
LOGTW_ERROR << " Error opening file: " << lp.string() << ".";
return -1;
}
std::string line;
std::vector<std::string> _vLines;
int nLine = 0, nextCol = 0;
while (std::getline(ifs, line)) {
nextCol = 0;
nLine++;
//duplicate:
if (std::find(_vLines.begin(), _vLines.end(), line) == _vLines.end()) {
_vLines.push_back(line);
}
else {
LOGTW_ERROR << " Duplicate lines in file: " << lp.string() << ".";
return -1;
}
//extract the columns with strtk and check each word
std::vector<std::string> _words;
strtk::parse(line, " \t", _words, strtk::split_options::compress_delimiters);
if (_words.size() < 1) {
LOGTW_ERROR << " empty lexicon line in file: " << lp.string() << ".";
return -1;
}
//forbidden word:
if (_words[0].find("<s>", 0) != std::string::npos ||
_words[0].find("</s>", 0) != std::string::npos ||
_words[0].find("<eps>", 0) != std::string::npos ||
_words[0].find("#0", 0) != std::string::npos)
{
LOGTW_ERROR << " Forbidden word in " << _words[0] << " (<s>, </s>, <eps>, #0) in file: " << lp.string() << ".";
return -1;
}
//the first column is the <> tag
nextCol++;
int __num_prob_cols = num_prob_cols + nextCol;
for (int n = nextCol; n < __num_prob_cols; n++) {
double d = std::stod(_words[n].c_str());
if (!(d > 0.0 && d <= 1.0)) {
LOGTW_ERROR << " bad pron-prob in lexicon-line " << nLine << "in file: " << lp.string() << ".";
return -1;
}
nextCol++;
}
int __num_skipped_cols = num_skipped_cols + nextCol;
for (int n = nextCol; n < __num_skipped_cols; n++) { nextCol++; }
if (_words.size() < nextCol + 1) {
LOGTW_ERROR << " " << lp.string() << " contains word " << _words[0] << " with empty pronunciation.";
return -1;
}
//check if the word is either in silence.txt or in nonsilence.txt
for (int n = nextCol; n < _words.size(); n++)
{
if (std::find(_silencephones.begin(), _silencephones.end(), _words[n]) == _silencephones.end() &&
std::find(_nonsilencephones.begin(), _nonsilencephones.end(), _words[n]) == _nonsilencephones.end())
{ //not found, add it
LOGTW_ERROR << " " << _words[n] << " is not in silence.txt and neither in nonsilence.txt.";
return -1;
}
}
}
return 0;
}
//checks silprob.txt for consistency
int CheckSilprob(fs::path lp)
{
//NOTE: not checking for Carriage Return (^M) characters in the C++ version
if (CheckUTF8AndWhiteSpace(lp, true) < 0) return -1;
std::ifstream ifs(lp.string());
if (!ifs) {
LOGTW_ERROR << " Error opening file: " << lp.string() << ".";
return -1;
}
std::string line;
//std::vector<std::string> _vLines;
int nLine = 0, nextCol = 0;
while (std::getline(ifs, line)) {
nextCol = 0;
nLine++;
//NOTE: duplicate checking - probably not needed and maybe would not be good
//duplicate:
//if (std::find(_vLines.begin(), _vLines.end(), line) == _vLines.end()) {
// _vLines.push_back(line);
//}
//else {
// LOGTW_ERROR << " Duplicate lines in file: " << lp.string() << ".";
// return -1;
//}
//extract the columns with strtk and check each word
std::vector<std::string> _words;
strtk::parse(line, " \t", _words, strtk::split_options::compress_delimiters);
if (_words.size() != 2) {
LOGTW_ERROR << " bad line (" << nLine << ") in file: " << lp.string() << ".";
return -1;
}
double d = std::stod(_words[1].c_str());
if (_words[0] == "<s>" || _words[0] == "overall") {
if (!(d > 0.0 && d <= 1.0)) {
LOGTW_ERROR << " bad probability at line " << nLine << " in file: " << lp.string() << ".";
return -1;
}
}
else if (_words[0] == "</s>_s" || _words[0] == "</s>_n") {
if (d <= 0.0) {
LOGTW_ERROR << " bad correction term at line " << nLine << " in file: " << lp.string() << ".";
return -1;
}
}
else {
LOGTW_ERROR << " unexpected line " << nLine << " in file: " << lp.string() << ".";
return -1;
}
}
return 0;
}
//Return the integer value from the second field of the StringTable if the first field matches the supplied key.
//The return value is placed into 'val' (pointer).
//return -1 when not found; display error message
int GetSecondFieldFromStringTable(StringTable table, std::string key, std::string path, int * val)
{
for (StringTable::const_iterator it(table.begin()), it_end(table.end()); it != it_end; ++it)
{
if ((*it)[0] == key)
{
*val = std::stoi((*it)[1]);
return 0;
}
}
LOGTW_ERROR << " key " << key << " not found in table in file: " << path << ".";
return -1;
}
int ReadSilenceAndNonSilencePhones(fs::path fSilencephones, fs::path fNonSilencephones)
{
//NOTE: these files have one word per line.
StringTable t_silencephones, t_nonsilencephones;
if (ReadStringTable(fSilencephones.string(), t_silencephones) < 0) {
LOGTW_ERROR << " could not read file: " << fSilencephones.string() << ".";
return -1;
}
if (ReadStringTable(fNonSilencephones.string(), t_nonsilencephones) < 0) {
LOGTW_ERROR << " could not read file: " << fNonSilencephones.string() << ".";
return -1;
}
_silencephones.clear();
_nonsilencephones.clear();
for (StringTable::const_iterator it(t_silencephones.begin()), it_end(t_silencephones.end()); it != it_end; ++it)
_silencephones.push_back((*it)[0]);
for (StringTable::const_iterator it(t_nonsilencephones.begin()), it_end(t_nonsilencephones.end()); it != it_end; ++it)
_nonsilencephones.push_back((*it)[0]);
if (_silencephones.size() < 1) {
LOGTW_ERROR << " no silence phones found in file: " << fSilencephones.string() << ".";
return -1;
}
if (_nonsilencephones.size() < 1) {
LOGTW_ERROR << " no non-silence phones found in file: " << fNonSilencephones.string() << ".";
return -1;
}
return 0;
}
| 32.06135 | 165 | 0.631649 | sanyaade-teachings |
fa560f221384189593c6d4e70dafe8cb08e627ca | 4,963 | hpp | C++ | ql/experimental/templatemodels/hullwhite/g2ppT.hpp | urgu00/QuantLib | fecce0abb0ff3d50da29c129f8f9e73176e20ab9 | [
"BSD-3-Clause"
] | null | null | null | ql/experimental/templatemodels/hullwhite/g2ppT.hpp | urgu00/QuantLib | fecce0abb0ff3d50da29c129f8f9e73176e20ab9 | [
"BSD-3-Clause"
] | 9 | 2021-05-17T06:40:39.000Z | 2022-03-28T08:08:46.000Z | ql/experimental/templatemodels/hullwhite/g2ppT.hpp | urgu00/QuantLib | fecce0abb0ff3d50da29c129f8f9e73176e20ab9 | [
"BSD-3-Clause"
] | 1 | 2020-11-23T09:16:13.000Z | 2020-11-23T09:16:13.000Z | /* -*- mode: c++; tab-width: 4; indent-tabs-mode: nil; c-basic-offset: 4 -*- */
/*
Copyright (C) 2018, Sebastian Schlenkrich
*/
#ifndef quantlib_templateg2pp_hpp
#define quantlib_templateg2pp_hpp
#include <ql/shared_ptr.hpp>
#include <ql/errors.hpp>
#include <ql/termstructures/yieldtermstructure.hpp>
#include <ql/experimental/templatemodels/stochasticprocessT.hpp>
#define _MIN_( a, b ) ( (a) < (b) ? (a) : (b) )
#define _MAX_( a, b ) ( (a) > (b) ? (a) : (b) )
namespace QuantLib {
// G2++ model
// r(t) = phi(t) + x(t) + y(t)
// dx(t) = -a x(t) dt + sigma dW_1(t)
// dy(t) = -b y(t) dt + eta dW_2(t)
// dB(t) = B(t) r(t) dt
// dW_1(t) dW_2(t) = rho dt
//
template <class DateType, class PassiveType, class ActiveType>
class G2ppT : public StochasticProcessT<DateType,PassiveType,ActiveType> {
private:
ActiveType sigma_, eta_, a_, b_, rho_;
Handle<YieldTermStructure> termStructure_; // the yield curve is
inline ActiveType V(DateType t) const {
ActiveType expat = exp(-a_*t);
ActiveType expbt = exp(-b_*t);
ActiveType cx = sigma_ / a_;
ActiveType cy = eta_ / b_;
ActiveType valuex = cx*cx*(t + (2.0*expat - 0.5*expat*expat - 1.5) / a_);
ActiveType valuey = cy*cy*(t + (2.0*expbt - 0.5*expbt*expbt - 1.5) / b_);
ActiveType value = 2.0*rho_*cx*cy* (t + (expat - 1.0) / a_
+ (expbt - 1.0) / b_
- (expat*expbt - 1.0) / (a_ + b_));
return valuex + valuey + value;
}
inline ActiveType A(DateType t, DateType T) const {
return termStructure_->discount(T) / termStructure_->discount(t) * exp(0.5*(V(T - t) - V(T) + V(t)));
}
inline ActiveType B(PassiveType x, DateType t) const {
return (1.0 - exp(-x*t)) / x;
}
public:
// constructor
G2ppT( const Handle<YieldTermStructure>& termStructure,
const ActiveType sigma,
const ActiveType eta,
const ActiveType a,
const ActiveType b,
const ActiveType rho )
: termStructure_(termStructure), sigma_(sigma), eta_(eta), a_(a), b_(b), rho_(rho) {
// check for valid parameter inputs
}
// stochastic process interface
// dimension of X = [ x, y, B ]
inline virtual size_t size() { return 3; }
// stochastic factors (x and y)
inline virtual size_t factors() { return 2; }
// initial values for simulation
inline virtual VecP initialValues() {
VecP X(3);
X[0] = 0.0; // x(t)
X[1] = 0.0; // y(t)
X[2] = 1.0; // B(t) bank account numeraire
return X;
}
// a[t,X(t)]
inline virtual VecA drift( const DateType t, const VecA& X) {
QL_FAIL("Drift is not implemented");
return VecA(0);
}
// b[t,X(t)]
inline virtual MatA diffusion( const DateType t, const VecA& X) {
QL_FAIL("Diffusion is not implemented");
return MatA(0);
}
// integrate X1 = X0 + drift()*dt + diffusion()*dW*sqrt(dt)
inline void evolve(const DateType t0, const VecA& X0, const DateType dt, const VecD& dW, VecA& X1) {
// ensure X1 has size of X0
ActiveType ExpX = X0[0] * exp(-a_*dt);
ActiveType ExpY = X0[1] * exp(-b_*dt);
ActiveType VarX = sigma_*sigma_ / 2.0 / a_*(1.0 - exp(-2.0*a_*dt));
ActiveType VarY = eta_ *eta_ / 2.0 / b_*(1.0 - exp(-2.0*b_*dt));
ActiveType CovXY = rho_*sigma_*eta_ / (a_ + b_)*(1.0 - exp(-(a_ + b_)*dt));
ActiveType corr = CovXY / sqrt(VarX) / sqrt(VarY);
ActiveType dZ = corr*dW[0] + sqrt(1 - corr*corr)*dW[1];
X1[0] = ExpX + sqrt(VarX)*dW[0];
X1[1] = ExpY + sqrt(VarY)*dZ;
// Brigo, Corollary 4.2.1
ActiveType expIntPhi = termStructure_->discount(t0) / termStructure_->discount(t0 + dt) * exp(0.5*(V(t0 + dt) - V(t0)));
ActiveType expIntX = exp(0.5*(X0[0] + X1[0])*dt); // numerical integration
ActiveType expIntY = exp(0.5*(X0[1] + X1[1])*dt); // numerical integration
X1[2] = X0[2] * expIntPhi * expIntX * expIntY; // using that r = phi + x + y
}
inline ActiveType zeroBond(const DateType t, const DateType T, const VecA& X) {
QL_REQUIRE(t <= T, "G2++ Model ZeroBond t <= T required");
if (t == T) return (ActiveType)1.0;
return A(t, T) * exp(-B(a_, (T - t))*X[0] - B(b_, (T - t))*X[1]); // assume X = [x, y, B]
}
inline ActiveType numeraire(const DateType t, const VecA& X) {
return X[2];
}
};
}
#undef _MIN_
#undef _MAX_
#endif /* ifndef quantlib_templateshiftedsabrmodel_hpp */
| 38.176923 | 132 | 0.531735 | urgu00 |
fa6230a7abbc3d9cdfd4bbb6640f84770454bedf | 125,788 | cpp | C++ | openstudiocore/src/sdd/MapGeometry.cpp | jasondegraw/OpenStudio | 2ab13f6e5e48940929041444e40ad9d36f80f552 | [
"blessing"
] | 1 | 2016-12-29T08:45:03.000Z | 2016-12-29T08:45:03.000Z | openstudiocore/src/sdd/MapGeometry.cpp | jasondegraw/OpenStudio | 2ab13f6e5e48940929041444e40ad9d36f80f552 | [
"blessing"
] | null | null | null | openstudiocore/src/sdd/MapGeometry.cpp | jasondegraw/OpenStudio | 2ab13f6e5e48940929041444e40ad9d36f80f552 | [
"blessing"
] | null | null | null | /**********************************************************************
* Copyright (c) 2008-2016, Alliance for Sustainable Energy.
* All rights reserved.
*
* This library is free software; you can redistribute it and/or
* modify it under the terms of the GNU Lesser General Public
* License as published by the Free Software Foundation; either
* version 2.1 of the License, or (at your option) any later version.
*
* This library is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
* Lesser General Public License for more details.
*
* You should have received a copy of the GNU Lesser General Public
* License along with this library; if not, write to the Free Software
* Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA
**********************************************************************/
#include "ReverseTranslator.hpp"
#include "ForwardTranslator.hpp"
#include "../model/Model.hpp"
#include "../model/ModelObject.hpp"
#include "../model/ModelObject_Impl.hpp"
#include "../model/ConstructionBase.hpp"
#include "../model/ConstructionBase_Impl.hpp"
#include "../model/Construction.hpp"
#include "../model/Construction_Impl.hpp"
#include "../model/MasslessOpaqueMaterial.hpp"
#include "../model/MasslessOpaqueMaterial_Impl.hpp"
#include "../model/StandardOpaqueMaterial.hpp"
#include "../model/StandardOpaqueMaterial_Impl.hpp"
#include "../model/FFactorGroundFloorConstruction.hpp"
#include "../model/FFactorGroundFloorConstruction_Impl.hpp"
#include "../model/CFactorUndergroundWallConstruction.hpp"
#include "../model/CFactorUndergroundWallConstruction_Impl.hpp"
#include "../model/Building.hpp"
#include "../model/Building_Impl.hpp"
#include "../model/ThermalZone.hpp"
#include "../model/ThermalZone_Impl.hpp"
#include "../model/BuildingStory.hpp"
#include "../model/BuildingStory_Impl.hpp"
#include "../model/Space.hpp"
#include "../model/Space_Impl.hpp"
#include "../model/Surface.hpp"
#include "../model/Surface_Impl.hpp"
#include "../model/SubSurface.hpp"
#include "../model/SubSurface_Impl.hpp"
#include "../model/ShadingSurface.hpp"
#include "../model/ShadingSurface_Impl.hpp"
#include "../model/ShadingSurfaceGroup.hpp"
#include "../model/ShadingSurfaceGroup_Impl.hpp"
#include "../model/PeopleDefinition.hpp"
#include "../model/People.hpp"
#include "../model/LightsDefinition.hpp"
#include "../model/Lights.hpp"
#include "../model/ElectricEquipmentDefinition.hpp"
#include "../model/ElectricEquipment.hpp"
#include "../model/GasEquipmentDefinition.hpp"
#include "../model/GasEquipment.hpp"
#include "../model/HotWaterEquipmentDefinition.hpp"
#include "../model/HotWaterEquipment.hpp"
#include "../model/DesignSpecificationOutdoorAir.hpp"
#include "../model/SpaceInfiltrationDesignFlowRate.hpp"
#include "../model/Schedule.hpp"
#include "../model/Schedule_Impl.hpp"
#include "../model/ScheduleDay.hpp"
#include "../model/ScheduleDay_Impl.hpp"
#include "../model/ScheduleConstant.hpp"
#include "../model/ScheduleConstant_Impl.hpp"
#include "../model/ScheduleRuleset.hpp"
#include "../model/ScheduleRuleset_Impl.hpp"
#include "../model/ScheduleTypeLimits.hpp"
#include "../model/ScheduleTypeLimits_Impl.hpp"
#include "../model/PlantLoop.hpp"
#include "../model/PlantLoop_Impl.hpp"
#include "../model/WaterUseConnections.hpp"
#include "../model/WaterUseConnections_Impl.hpp"
#include "../model/WaterUseEquipment.hpp"
#include "../model/WaterUseEquipment_Impl.hpp"
#include "../model/WaterUseEquipmentDefinition.hpp"
#include "../model/WaterUseEquipmentDefinition_Impl.hpp"
#include "../model/ThermostatSetpointDualSetpoint.hpp"
#include "../model/AirLoopHVAC.hpp"
#include "../model/AirLoopHVAC_Impl.hpp"
#include "../utilities/geometry/Transformation.hpp"
#include "../utilities/geometry/Geometry.hpp"
#include "../utilities/units/QuantityConverter.hpp"
#include "../utilities/units/IPUnit.hpp"
#include "../utilities/units/SIUnit.hpp"
#include "../utilities/units/BTUUnit.hpp"
#include "../utilities/units/MPHUnit.hpp"
#include "../utilities/units/WhUnit.hpp"
#include "../utilities/units/UnitFactory.hpp"
#include "../utilities/units/TemperatureUnit.hpp"
#include "../utilities/units/TemperatureUnit_Impl.hpp"
#include "../utilities/plot/ProgressBar.hpp"
#include "../utilities/core/Assert.hpp"
#include <QFile>
#include <QDomDocument>
#include <QDomElement>
#include <QStringList>
namespace openstudio {
namespace sdd {
const double footToMeter = 0.3048;
const double meterToFoot = 1.0/0.3048;
double fixAngle(double angle){
while (angle >= 360){
angle -= 360;
}
while (angle < 0){
angle += 360;
}
return angle;
}
QDomElement elementByTagNameAndIndex(const QDomElement & root, const QString & tagName, bool useIndex, const int & index){
QDomElement result;
if( useIndex ){
bool ok;
QDomNodeList nodes = root.elementsByTagName(tagName);
for(int i = 0; i < nodes.count(); i++){
QDomElement e = nodes.at(i).toElement();
int thisIndex = e.attribute("index").toInt(&ok);
if( ok && (thisIndex == index) ) {
result = e;
break;
}
}
}else{
result = root.firstChildElement(tagName);
}
return result;
}
boost::optional<model::ModelObject> ReverseTranslator::translateBuilding(const QDomElement& element, const QDomDocument& doc, openstudio::model::Model& model)
{
openstudio::model::Building building = model.getUniqueModelObject<openstudio::model::Building>();
QDomElement nameElement = element.firstChildElement("Name");
// http://code.google.com/p/cbecc/issues/detail?id=378
// The angle between the model Y-Axis and True North, measured clockwise from the model Y-Axis in Degrees.
QDomElement northAngleElement = element.firstChildElement("NAng");
// The angle between True North and the the model Y-Axis, measured clockwise from True North in Degrees.
QDomElement buildingAzimuthElement = element.firstChildElement("BldgAz"); // this corresponds to Building::North Axis
QDomNodeList spaceElements = element.elementsByTagName("Spc");
QDomNodeList thermalZoneElements = element.elementsByTagName("ThrmlZn");
QDomNodeList buildingStoryElements = element.elementsByTagName("Story");
if (nameElement.isNull()){
LOG(Error, "Bldg element 'Name' is empty.")
} else {
building.setName(escapeName(nameElement.text()));
}
if(!buildingAzimuthElement.isNull()){
double buildingAzimuth = fixAngle(buildingAzimuthElement.text().toDouble());
building.setNorthAxis(buildingAzimuth);
}else if(!northAngleElement.isNull()){
// use NAng for backwards compatibility with SDD's only having NAng
double northAngle = fixAngle(northAngleElement.text().toDouble());
double buildingAzimuth = 360.0 - northAngle;
building.setNorthAxis(buildingAzimuth);
}
// translate shadingSurfaces
QDomNodeList exteriorShadingElements = element.elementsByTagName("ExtShdgObj");
model::ShadingSurfaceGroup shadingSurfaceGroup(model);
shadingSurfaceGroup.setName("Building ShadingGroup");
shadingSurfaceGroup.setShadingSurfaceType("Building");
for (int i = 0; i < exteriorShadingElements.count(); ++i){
if (exteriorShadingElements.at(i).parentNode() == element){
boost::optional<model::ModelObject> exteriorShading = translateShadingSurface(exteriorShadingElements.at(i).toElement(), doc, shadingSurfaceGroup);
if (!exteriorShading){
LOG(Error, "Failed to translate 'ExtShdgObj' element " << i);
}
}
}
// create all spaces
for (int i = 0; i < spaceElements.count(); i++){
QDomElement spaceElement = spaceElements.at(i).toElement();
boost::optional<model::ModelObject> space = createSpace(spaceElement, doc, model);
if (!space){
LOG(Error, "Failed to translate 'Spc' element " << i);
}
}
// create all thermal zones
for (int i = 0; i < thermalZoneElements.count(); i++){
if (thermalZoneElements.at(i).firstChildElement("Name").isNull()){
LOG(Error, "ThrmlZn element 'Name' is empty, object will not be translated.")
continue;
}
QDomElement thermalZoneElement = thermalZoneElements.at(i).toElement();
boost::optional<model::ModelObject> thermalZone = createThermalZone(thermalZoneElement, doc, model);
if (!thermalZone){
LOG(Error, "Failed to translate 'ThrmlZn' element " << i);
}
}
// translate building stories
if (m_progressBar){
m_progressBar->setWindowTitle(toString("Translating Storys"));
m_progressBar->setMinimum(0);
m_progressBar->setMaximum(buildingStoryElements.count());
m_progressBar->setValue(0);
}
for (int i = 0; i < buildingStoryElements.count(); i++){
QDomElement buildingStoryElement = buildingStoryElements.at(i).toElement();
boost::optional<model::ModelObject> buildingStory = translateBuildingStory(buildingStoryElement, doc, model);
if (!buildingStory){
LOG(Error, "Failed to translate 'Story' element " << i);
}
if (m_progressBar){
m_progressBar->setValue(m_progressBar->value() + 1);
}
}
// remove unused CFactor constructions
for (model::CFactorUndergroundWallConstruction cFactorConstruction : model.getConcreteModelObjects<model::CFactorUndergroundWallConstruction>()){
if (cFactorConstruction.directUseCount(true) == 0){
cFactorConstruction.remove();
}
}
// remove unused FFactor constructions
for (model::FFactorGroundFloorConstruction fFactorConstruction : model.getConcreteModelObjects<model::FFactorGroundFloorConstruction>()){
if (fFactorConstruction.directUseCount(true) == 0){
fFactorConstruction.remove();
}
}
return building;
}
boost::optional<openstudio::model::ModelObject> ReverseTranslator::createThermalZone(const QDomElement& element, const QDomDocument& doc, openstudio::model::Model& model)
{
QDomElement nameElement = element.firstChildElement("Name");
model::ThermalZone thermalZone(model);
if (nameElement.isNull()){
LOG(Error, "ThrmlZn element 'Name' is empty.");
} else{
thermalZone.setName(escapeName(nameElement.text()));
}
return thermalZone;
}
boost::optional<openstudio::model::ModelObject> ReverseTranslator::translateBuildingStory(const QDomElement& element, const QDomDocument& doc, openstudio::model::Model& model)
{
QDomElement nameElement = element.firstChildElement("Name");
QDomNodeList spaceElements = element.elementsByTagName("Spc");
model::BuildingStory buildingStory(model);
std::string name;
if (nameElement.isNull()){
LOG(Error, "Story element 'Name' is empty.");
} else{
name = escapeName(nameElement.text());
}
buildingStory.setName(name);
for (int i = 0; i < spaceElements.count(); i++){
QDomElement spaceElement = spaceElements.at(i).toElement();
boost::optional<model::ModelObject> space = translateSpace(spaceElement, doc, buildingStory);
if (!space){
LOG(Error, "Failed to translate 'Spc' element " << i << " under Story '" << name << "'");
}
}
return buildingStory;
}
boost::optional<model::ModelObject> ReverseTranslator::createSpace(const QDomElement& element, const QDomDocument& doc, openstudio::model::Model& model)
{
QDomElement nameElement = element.firstChildElement("Name");
model::Space space(model);
if (nameElement.isNull()){
LOG(Error, "Spc element 'Name' is empty.")
} else{
space.setName(escapeName(nameElement.text()));
}
return space;
}
boost::optional<model::ModelObject> ReverseTranslator::translateSpace(const QDomElement& element, const QDomDocument& doc, openstudio::model::BuildingStory& buildingStory)
{
QDomElement nameElement = element.firstChildElement("Name");
QDomElement hotWtrHtgRtElement = element.firstChildElement("HotWtrHtgRtSim");
QDomElement hotWtrHtgSchRefElement = element.firstChildElement("HotWtrHtgSchRef");
QDomElement shwFluidSegRefElement = element.firstChildElement("SHWFluidSegRef");
QDomElement hotWtrSupTempElement = element.firstChildElement("HotWtrSupTemp");
QDomNodeList exteriorWallElements = element.elementsByTagName("ExtWall");
QDomNodeList exteriorFloorElements = element.elementsByTagName("ExtFlr");
QDomNodeList roofElements = element.elementsByTagName("Roof");
QDomNodeList undergroundFloorElements = element.elementsByTagName("UndgrFlr");
QDomNodeList undergroundWallElements = element.elementsByTagName("UndgrWall");
QDomNodeList ceilingElements = element.elementsByTagName("Ceiling");
QDomNodeList interiorWallElements = element.elementsByTagName("IntWall");
QDomNodeList interiorFloorElements = element.elementsByTagName("IntFlr");
std::string spaceName;
if (nameElement.isNull()){
LOG(Error, "Spc element 'Name' is empty.");
} else{
spaceName = escapeName(nameElement.text());
}
boost::optional<model::Space> space = buildingStory.model().getModelObjectByName<model::Space>(spaceName);
if (!space){
LOG(Error, "Could not retrieve Space named '" << spaceName << "'.");
return boost::none;
}
space->setBuildingStory(buildingStory);
QDomElement thermalZoneElement = element.firstChildElement("ThrmlZnRef");
std::string thermalZoneName;
if (thermalZoneElement.isNull()){
LOG(Error, "Spc element 'ThrmlZnRef' is empty for Space named '" << spaceName << "'.");
} else{
thermalZoneName = escapeName(thermalZoneElement.text());
}
boost::optional<model::ThermalZone> thermalZone = space->model().getModelObjectByName<model::ThermalZone>(thermalZoneName);
if (thermalZone){
space->setThermalZone(*thermalZone);
} else{
LOG(Error, "Could not retrieve ThermalZone named '" << thermalZoneName << "'.");
LOG(Error, "ThermalZone not set for Space named '" << spaceName << "'.");
}
translateLoads(element, doc, *space);
for (int i = 0; i < exteriorWallElements.count(); i++){
QDomElement exteriorWallElement = exteriorWallElements.at(i).toElement();
boost::optional<model::ModelObject> surface = translateSurface(exteriorWallElement, doc, *space);
if (!surface){
LOG(Error, "Failed to translate 'ExtWall' element " << i << " for Space named '" << spaceName << "'.");
}
}
for (int i = 0; i < exteriorFloorElements.count(); i++){
QDomElement exteriorFloorElement = exteriorFloorElements.at(i).toElement();
boost::optional<model::ModelObject> surface = translateSurface(exteriorFloorElement, doc, *space);
if (!surface){
LOG(Error, "Failed to translate 'ExtFlr' element " << i << " for Space named '" << spaceName << "'.");
}
}
for (int i = 0; i < roofElements.count(); i++){
QDomElement roofElement = roofElements.at(i).toElement();
boost::optional<model::ModelObject> surface = translateSurface(roofElement, doc, *space);
if (!surface){
LOG(Error, "Failed to translate 'Roof' element " << i << " for Space named '" << spaceName << "'.");
}
}
for (int i = 0; i < undergroundFloorElements.count(); i++){
QDomElement undergroundFloorElement = undergroundFloorElements.at(i).toElement();
boost::optional<model::ModelObject> surface = translateSurface(undergroundFloorElement, doc, *space);
if (!surface){
LOG(Error, "Failed to translate 'UndgrFlr' element " << i << " for Space named '" << spaceName << "'.");
}
}
for (int i = 0; i < undergroundWallElements.count(); i++){
QDomElement undergroundWallElement = undergroundWallElements.at(i).toElement();
boost::optional<model::ModelObject> surface = translateSurface(undergroundWallElement, doc, *space);
if (!surface){
LOG(Error, "Failed to translate 'UndgrWall' element " << i << " for Space named '" << spaceName << "'.");
}
}
for (int i = 0; i < ceilingElements.count(); i++){
QDomElement ceilingElement = ceilingElements.at(i).toElement();
boost::optional<model::ModelObject> surface = translateSurface(ceilingElement, doc, *space);
if (!surface){
LOG(Error, "Failed to translate 'Ceiling' element " << i << " for Space named '" << spaceName << "'.");
}
}
for (int i = 0; i < interiorWallElements.count(); i++){
QDomElement interiorWallElement = interiorWallElements.at(i).toElement();
boost::optional<model::ModelObject> surface = translateSurface(interiorWallElement, doc, *space);
if (!surface){
LOG(Error, "Failed to translate 'IntWall' element " << i << " for Space named '" << spaceName << "'.");
}
}
for (int i = 0; i < interiorFloorElements.count(); i++){
QDomElement interiorFloorElement = interiorFloorElements.at(i).toElement();
boost::optional<model::ModelObject> surface = translateSurface(interiorFloorElement, doc, *space);
if (!surface){
LOG(Error, "Failed to translate 'IntFlr' element " << i << " for Space named '" << spaceName << "'.");
}
}
// translate shadingSurfaces
QDomNodeList exteriorShadingElements = element.elementsByTagName("ExtShdgObj");
model::ShadingSurfaceGroup shadingSurfaceGroup(space->model());
shadingSurfaceGroup.setName(spaceName + " ShadingGroup");
shadingSurfaceGroup.setSpace(*space);
for (int i = 0; i < exteriorShadingElements.count(); ++i){
if (exteriorShadingElements.at(i).parentNode() == element){
boost::optional<model::ModelObject> exteriorShading = translateShadingSurface(exteriorShadingElements.at(i).toElement(), doc, shadingSurfaceGroup);
if (!exteriorShading){
LOG(Error, "Failed to translate 'ExtShdgObj' element " << i << " for Space named '" << spaceName << "'.");
}
}
}
// DLM: volume is now a property associated with Thermal Zone, http://code.google.com/p/cbecc/issues/detail?id=490
//// volume
//if (!volElement.isNull()){
// // sdd units = ft^3, os units = m^3
// Quantity spaceVolumeIP(volElement.text().toDouble(), BTUUnit(BTUExpnt(0,3,0,0)));
// OptionalQuantity spaceVolumeSI = QuantityConverter::instance().convert(spaceVolumeIP, UnitSystem(UnitSystem::Wh));
// OS_ASSERT(spaceVolumeSI);
// OS_ASSERT(spaceVolumeSI->units() == WhUnit(WhExpnt(0,0,3,0)));
//
// if (thermalZone->isVolumeDefaulted()){
// thermalZone->setVolume(spaceVolumeSI->value());
// }else{
// boost::optional<double> zoneVolume = thermalZone->volume();
// OS_ASSERT(zoneVolume);
// zoneVolume = *zoneVolume + spaceVolumeSI->value();
// thermalZone->setVolume(zoneVolume);
// }
//}
// Service Hot Water
bool ok;
double value = hotWtrHtgRtElement.text().toDouble(&ok);
model::Model model = buildingStory.model();
boost::optional<model::PlantLoop> shwSys = serviceHotWaterLoopForSupplySegment(shwFluidSegRefElement.text(),doc,model);
if( ok && shwSys )
{
model::WaterUseConnections connections(model);
connections.setName(spaceName + " Water Use Connection");
model::WaterUseEquipmentDefinition definition(model);
definition.setName(spaceName + " Water Use Definition");
definition.setPeakFlowRate(unitToUnit(value,"gal/h","m^3/s").get());
value = hotWtrSupTempElement.text().toDouble(&ok);
if( ok ) {
value = unitToUnit(value,"F","C").get();
model::ScheduleRuleset schedule(model);
schedule.setName(spaceName + " Target SHW Temp");
auto scheduleDay = schedule.defaultDaySchedule();
scheduleDay.addValue(Time(1.0),value);
definition.setTargetTemperatureSchedule(schedule);
}
model::WaterUseEquipment equipment(definition);
equipment.setName(spaceName + " Water Use Equipment");
if( boost::optional<model::Schedule> schedule = model.getModelObjectByName<model::Schedule>(hotWtrHtgSchRefElement.text().toStdString()) )
{
equipment.setFlowRateFractionSchedule(schedule.get());
}
connections.addWaterUseEquipment(equipment);
shwSys->addDemandBranchForComponent(connections);
}
return boost::optional<model::ModelObject>(space);
}
boost::optional<openstudio::model::ModelObject> ReverseTranslator::translateLoads(const QDomElement& element, const QDomDocument& doc, openstudio::model::Space& space)
{
UnitSystem siSys(UnitSystem::SI);
UnitSystem whSys(UnitSystem::Wh);
openstudio::model::Model model = space.model();
std::string name = space.name().get();
// DLM: what to do with these?
//<SpcOcc>Office - Open</SpcOcc>
//<SchOcc>Table G-I Office Occupancy</SchOcc>
//***** OCCUPANCY *****
{
//<OccDens>6.67</OccDens> - person per thousand ft2
//<OccSensHtRt>250</OccSensHtRt> - Btu per h person
//<OccLatHtRt>200</OccLatHtRt> - Btu per h person
//<OccSchRef>Office Occup Sched</OccSchRef>
QDomElement occDensElement = element.firstChildElement("OccDensSim");
QDomElement occSensHtRtElement = element.firstChildElement("OccSensHtRt");
QDomElement occLatHtRtElement = element.firstChildElement("OccLatHtRt");
QDomElement occSchRefElement = element.firstChildElement("OccSchRef");
if (!occDensElement.isNull() && (occDensElement.text().toDouble() > 0)){
if (!occSensHtRtElement.isNull() && !occLatHtRtElement.isNull()){
openstudio::Quantity peopleDensityIP(occDensElement.text().toDouble() / 1000.0, openstudio::createUnit("people/ft^2",UnitSystem::BTU).get());
OptionalQuantity peopleDensitySI = QuantityConverter::instance().convert(peopleDensityIP, whSys);
OS_ASSERT(peopleDensitySI);
OS_ASSERT(peopleDensitySI->units() == WhUnit(WhExpnt(0,0,-2,0,0,0,0,0,0,1)));
openstudio::model::PeopleDefinition peopleDefinition(model);
peopleDefinition.setName(name + " People Definition");
peopleDefinition.setPeopleperSpaceFloorArea(peopleDensitySI->value()); // people/m2
openstudio::Quantity sensibleHeatRateIP(occSensHtRtElement.text().toDouble(), openstudio::createUnit("Btu/h*person", UnitSystem::BTU).get());
OptionalQuantity sensibleHeatRateSI = QuantityConverter::instance().convert(sensibleHeatRateIP, whSys);
OS_ASSERT(sensibleHeatRateSI);
OS_ASSERT(sensibleHeatRateSI->units() == WhUnit(WhExpnt(1,0,0,0,0,0,0,0,0,-1)));
openstudio::Quantity latentHeatRateIP(occLatHtRtElement.text().toDouble(), openstudio::createUnit("Btu/h*person", UnitSystem::BTU).get());
OptionalQuantity latentHeatRateSI = QuantityConverter::instance().convert(latentHeatRateIP, whSys);
OS_ASSERT(latentHeatRateSI);
OS_ASSERT(latentHeatRateSI->units() == WhUnit(WhExpnt(1,0,0,0,0,0,0,0,0,-1)));
double totalHeatRateSI = sensibleHeatRateSI->value() + latentHeatRateSI->value();
if (totalHeatRateSI > 0){
double sensibleHeatFraction = sensibleHeatRateSI->value() / totalHeatRateSI;
peopleDefinition.setSensibleHeatFraction(sensibleHeatFraction);
}
openstudio::model::People people(peopleDefinition);
people.setName(name + " People");
people.setSpace(space);
// activity schedule
openstudio::model::ScheduleRuleset activitySchedule(model, totalHeatRateSI);
activitySchedule.setName(name + " People Activity Level");
//boost::optional<model::ScheduleTypeLimits> scheduleTypeLimits = model.getModelObjectByName<model::ScheduleTypeLimits>("Activity Level");
//if (!scheduleTypeLimits){
// scheduleTypeLimits = model::ScheduleTypeLimits(model);
// scheduleTypeLimits->setName("Activity Level");
// scheduleTypeLimits->setNumericType("Continuous");
// scheduleTypeLimits->setUnitType("ActivityLevel");
//}
//if (scheduleTypeLimits){
// activitySchedule.setScheduleTypeLimits(*scheduleTypeLimits);
//}
people.setActivityLevelSchedule(activitySchedule);
// number of people schedule
if (!occSchRefElement.isNull()){
std::string scheduleName = escapeName(occSchRefElement.text());
boost::optional<model::Schedule> schedule = model.getModelObjectByName<model::Schedule>(scheduleName);
if (schedule){
people.setNumberofPeopleSchedule(*schedule);
}else{
LOG(Error, "Could not find schedule '" << scheduleName << "'");
}
}
}else{
LOG(Error, "People density is non-zero but sensible and latent heat rates are not given");
}
}
}
//***** Infiltration *****
{
//<InfMthd>FlowExteriorWallArea</InfMthd>
//<DsgnInfRt>0.0448</DsgnInfRt>
//<InfSchRef>School Inf Sch</InfSchRef>
//<InfModelCoefA>0</InfModelCoefA>
//<InfModelCoefC>0.10016</InfModelCoefC>
//<InfModelCoefD>0</InfModelCoefD>
//InfMthd = {AirChangesPerHour, FlowArea, FlowExteriorArea, FlowExteriorWallArea, FlowSpace}
QDomNodeList infMthdNodes = element.elementsByTagName("InfMthd");
for (int i = 0; i < infMthdNodes.count(); i++){
QDomElement infMthdElement = infMthdNodes.at(i).toElement();
bool hasIndex;
int infIndex = infMthdElement.attribute("index").toInt(&hasIndex);
QDomElement dsgnInfRtElement = elementByTagNameAndIndex(element,"DsgnInfRt",hasIndex,infIndex);
if ((!infMthdElement.isNull()) && (!dsgnInfRtElement.isNull())){
if ((infMthdElement.text() == "AirChangesPerHour") ||
(infMthdElement.text() == "FlowArea") ||
(infMthdElement.text() == "FlowExteriorArea") ||
(infMthdElement.text() == "FlowExteriorWallArea") ||
(infMthdElement.text() == "FlowSpace")){
QDomElement infSchRefElement = elementByTagNameAndIndex(element,"InfSchRef",hasIndex,infIndex);
QDomElement infModelCoefAElement = elementByTagNameAndIndex(element,"InfModelCoefA",hasIndex,infIndex); // unitless
QDomElement infModelCoefBElement = elementByTagNameAndIndex(element,"InfModelCoefB",hasIndex,infIndex); // 1/deltaF
QDomElement infModelCoefCElement = elementByTagNameAndIndex(element,"InfModelCoefC",hasIndex,infIndex); // hr/mile
QDomElement infModelCoefDElement = elementByTagNameAndIndex(element,"InfModelCoefD",hasIndex,infIndex); // hr^2/mile^2
openstudio::model::SpaceInfiltrationDesignFlowRate spaceInfiltrationDesignFlowRate(model);
std::string infName;
if( hasIndex ) {
infName = name + " Space Infiltration Design Flow Rate " + QString::number(infIndex + 1).toStdString();
}
else
{
infName = name + " Space Infiltration Design Flow Rate";
}
spaceInfiltrationDesignFlowRate.setName(infName);
spaceInfiltrationDesignFlowRate.setSpace(space);
double dsnInfRt = dsgnInfRtElement.text().toDouble();
openstudio::Quantity dsgnInfRtIP(dsnInfRt, openstudio::createUnit("cfm", UnitSystem::BTU).get());
OptionalQuantity dsgnInfRtSI = QuantityConverter::instance().convert(dsgnInfRtIP, siSys);
OS_ASSERT(dsgnInfRtSI);
OS_ASSERT(dsgnInfRtSI->units() == SIUnit(SIExpnt(0, 3, -1)));
openstudio::Quantity dsgnInfRtAreaIP(dsnInfRt, openstudio::createUnit("cfm/ft^2", UnitSystem::BTU).get());
OptionalQuantity dsgnInfRtAreaSI = QuantityConverter::instance().convert(dsgnInfRtAreaIP, siSys);
OS_ASSERT(dsgnInfRtAreaSI);
OS_ASSERT(dsgnInfRtAreaSI->units() == SIUnit(SIExpnt(0, 1, -1)));
if (infMthdElement.text() == "AirChangesPerHour") {
spaceInfiltrationDesignFlowRate.setAirChangesperHour(dsnInfRt);
}else if (infMthdElement.text() == "FlowArea") {
spaceInfiltrationDesignFlowRate.setFlowperSpaceFloorArea(dsgnInfRtAreaSI->value());
}else if (infMthdElement.text() == "FlowExteriorArea") {
spaceInfiltrationDesignFlowRate.setFlowperExteriorSurfaceArea(dsgnInfRtAreaSI->value());
}else if(infMthdElement.text() == "FlowExteriorWallArea") {
spaceInfiltrationDesignFlowRate.setFlowperExteriorWallArea(dsgnInfRtAreaSI->value());
}else if (infMthdElement.text() == "FlowSpace") {
spaceInfiltrationDesignFlowRate.setDesignFlowRate(dsgnInfRtSI->value());
}
if (!infSchRefElement.isNull()){
std::string scheduleName = escapeName(infSchRefElement.text());
boost::optional<model::Schedule> schedule = model.getModelObjectByName<model::Schedule>(scheduleName);
if (schedule){
spaceInfiltrationDesignFlowRate.setSchedule(*schedule);
}else{
LOG(Error, "Could not find schedule '" << scheduleName << "'");
}
}
if (!infModelCoefAElement.isNull()){
// unitless
double infModelCoefA = infModelCoefAElement.text().toDouble();
spaceInfiltrationDesignFlowRate.setConstantTermCoefficient(infModelCoefA);
}
if (!infModelCoefBElement.isNull()){
// convert 1/deltaF to 1/detlaC
spaceInfiltrationDesignFlowRate.setTemperatureTermCoefficient(infModelCoefBElement.text().toDouble() * 5.0 / 9.0);
}
if (!infModelCoefCElement.isNull()){
// SDD: hr/mile, OpenStudio: s/m
openstudio::Quantity infModelCoefCIP(infModelCoefCElement.text().toDouble(), MPHUnit(MPHExpnt(0,-1,1)));
OptionalQuantity infModelCoefCSI = QuantityConverter::instance().convert(infModelCoefCIP, siSys);
OS_ASSERT(infModelCoefCSI);
OS_ASSERT(infModelCoefCSI->units() == SIUnit(SIExpnt(0,-1,1)));
spaceInfiltrationDesignFlowRate.setVelocityTermCoefficient(infModelCoefCSI->value());
}
if (!infModelCoefDElement.isNull()){
// SDD: hr^2/mile^2, OpenStudio: s^2/m^2
openstudio::Quantity infModelCoefDIP(infModelCoefDElement.text().toDouble(), MPHUnit(MPHExpnt(0,-2,2)));
OptionalQuantity infModelCoefDSI = QuantityConverter::instance().convert(infModelCoefDIP, siSys);
OS_ASSERT(infModelCoefDSI);
OS_ASSERT(infModelCoefDSI->units() == SIUnit(SIExpnt(0,-2,2)));
spaceInfiltrationDesignFlowRate.setVelocitySquaredTermCoefficient(infModelCoefDSI->value());
}
}
}
} // end for infMthdNodes
}
//***** Interior Lights *****
{
//<IntLPDReg>1.1</IntLPDReg> - W per ft2
//<IntLtgRegSchRef>Office Lighting Sched</IntLtgRegSchRef>
//<IntLtgRegHtGnSpcFrac>0.61</IntLtgRegHtGnSpcFrac> - fraction to space, 1-Return Air Fraction
//<IntLtgRegHtGnRadFrac>0.75</IntLtgRegHtGnRadFrac> - radiant fraction
//<IntLPDNonReg>0</IntLPDNonReg> - W per ft2
//<IntLtgNonRegSchRef>Office Lighting Sched</IntLtgNonRegSchRef>
//<IntLtgNonRegHtGnSpcFrac>0.5</IntLtgNonRegHtGnSpcFrac> - fraction to space, 1-Return Air Fraction
//<IntLtgNonRegHtGnRadFrac>0.55</IntLtgNonRegHtGnRadFrac> - radiant fraction
QDomElement intLPDRegSimElement = element.firstChildElement("IntLPDRegSim");
QDomElement intLtgRegSchRefElement = element.firstChildElement("IntLtgRegSchRef");
QDomElement intLtgRegHtGnSpcFracSimElement = element.firstChildElement("IntLtgRegHtGnSpcFracSim");
QDomElement intLtgRegHtGnRadFracSimElement = element.firstChildElement("IntLtgRegHtGnRadFracSim");
QDomElement intLtgRegEndUseElement = element.firstChildElement("IntLtgRegEndUseCat");
if (!intLPDRegSimElement.isNull() && (intLPDRegSimElement.text().toDouble() > 0)){
openstudio::Quantity lightingDensityIP(intLPDRegSimElement.text().toDouble(), openstudio::createUnit("W/ft^2").get());
OptionalQuantity lightingDensitySI = QuantityConverter::instance().convert(lightingDensityIP, whSys);
OS_ASSERT(lightingDensitySI);
OS_ASSERT(lightingDensitySI->units() == WhUnit(WhExpnt(1,0,-2)));
openstudio::model::LightsDefinition lightsDefinition(model);
lightsDefinition.setName(name + " Regulated Lights Definition");
lightsDefinition.setWattsperSpaceFloorArea(lightingDensitySI->value()); // W/m2
openstudio::model::Lights lights(lightsDefinition);
lights.setName(name + " Regulated Lights");
lights.setSpace(space);
std::string subCategory = "ComplianceLtg";
if (!intLtgRegEndUseElement.isNull()){
subCategory = intLtgRegEndUseElement.text().toStdString();
}
lights.setEndUseSubcategory(subCategory);
if (!intLtgRegSchRefElement.isNull()){
std::string scheduleName = escapeName(intLtgRegSchRefElement.text());
boost::optional<model::Schedule> schedule = model.getModelObjectByName<model::Schedule>(scheduleName);
if (schedule){
lights.setSchedule(*schedule);
}else{
LOG(Error, "Could not find schedule '" << scheduleName << "'");
}
}
if (!intLtgRegHtGnSpcFracSimElement.isNull()){
double spaceFraction = intLtgRegHtGnSpcFracSimElement.text().toDouble();
double returnAirFraction = 1.0 - spaceFraction;
lightsDefinition.setReturnAirFraction(returnAirFraction);
if (!intLtgRegHtGnRadFracSimElement.isNull()){
double fractionRadiant = intLtgRegHtGnRadFracSimElement.text().toDouble() * spaceFraction;
lightsDefinition.setFractionRadiant(fractionRadiant);
}
}else if (!intLtgRegHtGnRadFracSimElement.isNull()){
LOG(Warn, "IntLtgRegHtGnRadFracSimElement is specified for space '" << name << "' but IntLtgRegHtGnSpcFracSimElement is not, IntLtgNonRegHtGnRadFracSimElement will be ignored.");
}
}
QDomElement intLPDNonRegSimElement = element.firstChildElement("IntLPDNonRegSim");
QDomElement intLtgNonRegSchRefElement = element.firstChildElement("IntLtgNonRegSchRef");
QDomElement intLtgNonRegHtGnSpcFracSimElement = element.firstChildElement("IntLtgNonRegHtGnSpcFracSim");
QDomElement intLtgNonRegHtGnRadFracSimElement = element.firstChildElement("IntLtgNonRegHtGnRadFracSim");
QDomElement intLtgNonRegEndUseElement = element.firstChildElement("IntLtgNonRegEndUseCat");
if (!intLPDNonRegSimElement.isNull() && (intLPDNonRegSimElement.text().toDouble() > 0)){
openstudio::Quantity lightingDensityIP(intLPDNonRegSimElement.text().toDouble(), openstudio::createUnit("W/ft^2").get());
OptionalQuantity lightingDensitySI = QuantityConverter::instance().convert(lightingDensityIP, whSys);
OS_ASSERT(lightingDensitySI);
OS_ASSERT(lightingDensitySI->units() == WhUnit(WhExpnt(1,0,-2)));
openstudio::model::LightsDefinition lightsDefinition(model);
lightsDefinition.setName(name + " Non-Regulated Lights Definition");
lightsDefinition.setWattsperSpaceFloorArea(lightingDensitySI->value()); // W/m2
openstudio::model::Lights lights(lightsDefinition);
lights.setName(name + " Non-Regulated Lights");
lights.setSpace(space);
std::string subCategory = "NonComplianceLtg";
if (!intLtgRegEndUseElement.isNull()){
subCategory = intLtgNonRegEndUseElement.text().toStdString();
}
lights.setEndUseSubcategory(subCategory);
if (!intLtgNonRegSchRefElement.isNull()){
std::string scheduleName = escapeName(intLtgNonRegSchRefElement.text());
boost::optional<model::Schedule> schedule = model.getModelObjectByName<model::Schedule>(scheduleName);
if (schedule){
lights.setSchedule(*schedule);
}else{
LOG(Error, "Could not find schedule '" << scheduleName << "'");
}
}
if (!intLtgNonRegHtGnSpcFracSimElement.isNull()){
double spaceFraction = intLtgNonRegHtGnSpcFracSimElement.text().toDouble();
double returnAirFraction = 1.0 - spaceFraction;
lightsDefinition.setReturnAirFraction(returnAirFraction);
if (!intLtgNonRegHtGnRadFracSimElement.isNull()){
double fractionRadiant = intLtgNonRegHtGnRadFracSimElement.text().toDouble() * spaceFraction;
lightsDefinition.setFractionRadiant(fractionRadiant);
}
}else if (!intLtgNonRegHtGnRadFracSimElement.isNull()){
LOG(Warn, "IntLtgNonRegHtGnRadFracSimElement is specified for space '" << name << "' but IntLtgNonRegHtGnSpcFracSimElement is not, IntLtgNonRegHtGnRadFracSimElement will be ignored.");
}
}
}
//***** Recepticle Loads *****
{
//<RecptPwrDens>2.53</RecptPwrDens> - W per ft2
//<RecptSchRef>Office Plugs Sched</RecptSchRef>
//<RecptRadFrac>0.2</RecptRadFrac>
//<RecptLatFrac>0</RecptLatFrac>
//<RecptLostFrac>0</RecptLostFrac>
QDomElement recptPwrDensElement = element.firstChildElement("RecptPwrDens");
QDomElement recptPwrDensSchRefElement = element.firstChildElement("RecptSchRef");
QDomElement recptRadFracElement = element.firstChildElement("RecptRadFrac");
QDomElement recptLatFracElement = element.firstChildElement("RecptLatFrac");
QDomElement recptLostFracElement = element.firstChildElement("RecptLostFrac");
if (!recptPwrDensElement.isNull() && (recptPwrDensElement.text().toDouble() > 0)){
openstudio::Quantity electricalDensityIP(recptPwrDensElement.text().toDouble(), openstudio::createUnit("W/ft^2").get());
OptionalQuantity electricalDensitySI = QuantityConverter::instance().convert(electricalDensityIP, whSys);
OS_ASSERT(electricalDensitySI);
OS_ASSERT(electricalDensitySI->units() == WhUnit(WhExpnt(1,0,-2)));
openstudio::model::ElectricEquipmentDefinition electricEquipmentDefinition(model);
electricEquipmentDefinition.setName(name + " Recepticle Loads Definition");
electricEquipmentDefinition.setWattsperSpaceFloorArea(electricalDensitySI->value()); // W/m2
if (!recptRadFracElement.isNull()){
electricEquipmentDefinition.setFractionRadiant(recptRadFracElement.text().toDouble());
}
if (!recptLatFracElement.isNull()){
electricEquipmentDefinition.setFractionLatent(recptLatFracElement.text().toDouble());
}
if (!recptLostFracElement.isNull()){
electricEquipmentDefinition.setFractionLost(recptLostFracElement.text().toDouble());
}
openstudio::model::ElectricEquipment electricEquipment(electricEquipmentDefinition);
electricEquipment.setName(name + " Recepticle Loads");
electricEquipment.setSpace(space);
electricEquipment.setEndUseSubcategory("Receptacle");
if (!recptPwrDensSchRefElement.isNull()){
std::string scheduleName = escapeName(recptPwrDensSchRefElement.text());
boost::optional<model::Schedule> schedule = model.getModelObjectByName<model::Schedule>(scheduleName);
if (schedule){
electricEquipment.setSchedule(*schedule);
}else{
LOG(Error, "Could not find schedule '" << scheduleName << "'");
}
}
}
}
//***** Gas Equipment Loads *****
{
//<GasEqpPwrDens>17.5377</GasEqpPwrDens>
//<GasEqpSchRef>RestaurantReceptacle</GasEqpSchRef>
//<GasEqpRadFrac>0.2</GasEqpRadFrac>
//<GasEqpLatFrac>0.4</GasEqpLatFrac>
//<GasEqpLostFrac>0.2></GasEqpLostFrac>
QDomElement gasEqpPwrDensElement = element.firstChildElement("GasEqpPwrDens");
QDomElement gasEqpPwrDensSchRefElement = element.firstChildElement("GasEqpSchRef");
QDomElement gasEqpRadFracElement = element.firstChildElement("GasEqpRadFrac");
QDomElement gasEqpLatFracElement = element.firstChildElement("GasEqpLatFrac");
QDomElement gasEqpLostFracElement = element.firstChildElement("GasEqpLostFrac");
if (!gasEqpPwrDensElement.isNull() && (gasEqpPwrDensElement.text().toDouble() > 0)){
openstudio::Quantity gasDensityIP(gasEqpPwrDensElement.text().toDouble(), openstudio::createUnit("Btu/h*ft^2").get());
OptionalQuantity gasDensitySI = QuantityConverter::instance().convert(gasDensityIP, whSys);
OS_ASSERT(gasDensitySI);
OS_ASSERT(gasDensitySI->units() == WhUnit(WhExpnt(1,0,-2)));
openstudio::model::GasEquipmentDefinition gasEquipmentDefinition(model);
gasEquipmentDefinition.setName(name + " Gas Equipment Loads Definition");
gasEquipmentDefinition.setWattsperSpaceFloorArea(gasDensitySI->value()); // W/m2
if (!gasEqpRadFracElement.isNull()){
gasEquipmentDefinition.setFractionRadiant(gasEqpRadFracElement.text().toDouble());
}
if (!gasEqpLatFracElement.isNull()){
gasEquipmentDefinition.setFractionLatent(gasEqpLatFracElement.text().toDouble());
}
if (!gasEqpLostFracElement.isNull()){
gasEquipmentDefinition.setFractionLost(gasEqpLostFracElement.text().toDouble());
}
openstudio::model::GasEquipment gasEquipment(gasEquipmentDefinition);
gasEquipment.setName(name + " Gas Equipment Loads");
gasEquipment.setSpace(space);
gasEquipment.setEndUseSubcategory("Receptacle");
if (!gasEqpPwrDensSchRefElement.isNull()){
std::string scheduleName = escapeName(gasEqpPwrDensSchRefElement.text());
boost::optional<model::Schedule> schedule = model.getModelObjectByName<model::Schedule>(scheduleName);
if (schedule){
gasEquipment.setSchedule(*schedule);
}else{
LOG(Error, "Could not find schedule '" << scheduleName << "'");
}
}
}
}
//***** Process Electricity Loads *****
{
//<ProcElecPwrDens>0</ProcElecPwrDens> - W per ft2
//<ProcElecSchRef>Office Plugs Sched</ProcElecSchRef>
//<ProcElecRadFrac>0.2</ProcElecRadFrac>
//<ProcElecLatFrac>0</ProcElecLatFrac>
//<ProcElecLostFrac>0</ProcElecLostFrac>
QDomElement procElecPwrDensElement = element.firstChildElement("ProcElecPwrDens");
QDomElement procElecSchRefElement = element.firstChildElement("ProcElecSchRef");
QDomElement procElecRadFracElement = element.firstChildElement("ProcElecRadFrac");
QDomElement procElecLatFracElement = element.firstChildElement("ProcElecLatFrac");
QDomElement procElecLostFracElement = element.firstChildElement("ProcElecLostFrac");
if (!procElecPwrDensElement.isNull() && (procElecPwrDensElement.text().toDouble() > 0)){
openstudio::Quantity electricalDensityIP(procElecPwrDensElement.text().toDouble(), openstudio::createUnit("W/ft^2").get());
OptionalQuantity electricalDensitySI = QuantityConverter::instance().convert(electricalDensityIP, whSys);
OS_ASSERT(electricalDensitySI);
OS_ASSERT(electricalDensitySI->units() == WhUnit(WhExpnt(1,0,-2)));
openstudio::model::ElectricEquipmentDefinition electricEquipmentDefinition(model);
electricEquipmentDefinition.setName(name + " Process Electric Loads Definition");
electricEquipmentDefinition.setWattsperSpaceFloorArea(electricalDensitySI->value()); // W/m2
if (!procElecRadFracElement.isNull()){
electricEquipmentDefinition.setFractionRadiant(procElecRadFracElement.text().toDouble());
}
if (!procElecLatFracElement.isNull()){
electricEquipmentDefinition.setFractionLatent(procElecLatFracElement.text().toDouble());
}
if (!procElecLostFracElement.isNull()){
electricEquipmentDefinition.setFractionLost(procElecLostFracElement.text().toDouble());
}
openstudio::model::ElectricEquipment electricEquipment(electricEquipmentDefinition);
electricEquipment.setName(name + " Process Electric Loads");
electricEquipment.setSpace(space);
electricEquipment.setEndUseSubcategory("Process");
if (!procElecSchRefElement.isNull()){
std::string scheduleName = escapeName(procElecSchRefElement.text());
boost::optional<model::Schedule> schedule = model.getModelObjectByName<model::Schedule>(scheduleName);
if (schedule){
electricEquipment.setSchedule(*schedule);
}else{
LOG(Error, "Could not find schedule '" << scheduleName << "'");
}
}
}
}
//***** Refrigeration Loads *****
{
//<CommRfrgEPD>0.06</CommRfrgEPD> - W per ft2
//<CommRfrgEqpSchRef>Office Plugs Sched</CommRfrgEqpSchRef>
//<CommRfrgRadFrac>0.1</CommRfrgRadFrac>
//<CommRfrgLatFrac>0.1</CommRfrgLatFrac>
//<CommRfrgLostFrac>0.6</CommRfrgLostFrac>
QDomElement commRfrgEPDElement = element.firstChildElement("CommRfrgEPD");
QDomElement commRfrgEqpSchRefElement = element.firstChildElement("CommRfrgEqpSchRef");
QDomElement commRfrgRadFracElement = element.firstChildElement("CommRfrgRadFrac");
QDomElement commRfrgLatFracElement = element.firstChildElement("CommRfrgLatFrac");
QDomElement commRfrgLostFracElement = element.firstChildElement("CommRfrgLostFrac");
if (!commRfrgEPDElement.isNull() && (commRfrgEPDElement.text().toDouble() > 0)){
openstudio::Quantity electricalDensityIP(commRfrgEPDElement.text().toDouble(), openstudio::createUnit("W/ft^2").get());
OptionalQuantity electricalDensitySI = QuantityConverter::instance().convert(electricalDensityIP, whSys);
OS_ASSERT(electricalDensitySI);
OS_ASSERT(electricalDensitySI->units() == WhUnit(WhExpnt(1,0,-2)));
openstudio::model::ElectricEquipmentDefinition electricEquipmentDefinition(model);
electricEquipmentDefinition.setName(name + " Refrigeration Loads Definition");
electricEquipmentDefinition.setWattsperSpaceFloorArea(electricalDensitySI->value()); // W/m2
if (!commRfrgRadFracElement.isNull()){
electricEquipmentDefinition.setFractionRadiant(commRfrgRadFracElement.text().toDouble());
}
if (!commRfrgLatFracElement.isNull()){
electricEquipmentDefinition.setFractionLatent(commRfrgLatFracElement.text().toDouble());
}
if (!commRfrgLostFracElement.isNull()){
electricEquipmentDefinition.setFractionLost(commRfrgLostFracElement.text().toDouble());
}
openstudio::model::ElectricEquipment electricEquipment(electricEquipmentDefinition);
electricEquipment.setName(name + " Refrigeration Loads");
electricEquipment.setSpace(space);
electricEquipment.setEndUseSubcategory("Refrig");
if (!commRfrgEqpSchRefElement.isNull()){
std::string scheduleName = escapeName(commRfrgEqpSchRefElement.text());
boost::optional<model::Schedule> schedule = model.getModelObjectByName<model::Schedule>(scheduleName);
if (schedule){
electricEquipment.setSchedule(*schedule);
}else{
LOG(Error, "Could not find schedule '" << scheduleName << "'");
}
}
}
}
//***** Elevator Loads *****
{
//<ElevPwr>20000</ElevPwr>
//<ElevSchRef>OfficeElevator</ElevSchRef>
//<ElevRadFrac>0</ElevRadFrac>
//<ElevLatFrac>0</ElevLatFrac>
//<ElevLostFrac>0.8</ElevLostFrac>
QDomElement elevPwrElement = element.firstChildElement("ElevPwr");
QDomElement elevSchRefElement = element.firstChildElement("ElevSchRef");
QDomElement elevRadFracElement = element.firstChildElement("ElevRadFrac");
QDomElement elevLatFracElement = element.firstChildElement("ElevLatFrac");
QDomElement elevLostFracElement = element.firstChildElement("ElevLostFrac");
if (!elevPwrElement.isNull() && (elevPwrElement.text().toDouble() > 0)){
openstudio::model::ElectricEquipmentDefinition electricEquipmentDefinition(model);
electricEquipmentDefinition.setName(name + " Elevator Definition");
electricEquipmentDefinition.setDesignLevel(elevPwrElement.text().toDouble());
if (!elevRadFracElement.isNull()){
electricEquipmentDefinition.setFractionRadiant(elevRadFracElement.text().toDouble());
}
if (!elevLatFracElement.isNull()){
electricEquipmentDefinition.setFractionLatent(elevLatFracElement.text().toDouble());
}
if (!elevLostFracElement.isNull()){
electricEquipmentDefinition.setFractionLost(elevLostFracElement.text().toDouble());
}
openstudio::model::ElectricEquipment electricEquipment(electricEquipmentDefinition);
electricEquipment.setName(name + " Elevator");
electricEquipment.setSpace(space);
electricEquipment.setEndUseSubcategory("Internal Transport");
if (!elevSchRefElement.isNull()){
std::string scheduleName = escapeName(elevSchRefElement.text());
boost::optional<model::Schedule> schedule = model.getModelObjectByName<model::Schedule>(scheduleName);
if (schedule){
electricEquipment.setSchedule(*schedule);
}else{
LOG(Error, "Could not find schedule '" << scheduleName << "'");
}
}
}
}
//***** Escalator Loads *****
{
//<EscalPwr>7860</EscalPwr>
//<EscalSchRef>OfficeEscalator Sch</EscalSchRef>
//<EscalRadFrac>0</EscalRadFrac>
//<EscalLatFrac>0</EscalLatFrac>
//<EscalLostFrac>0.2</EscalLostFrac>
QDomElement escalPwrElement = element.firstChildElement("EscalPwr");
QDomElement escalSchRefElement = element.firstChildElement("EscalSchRef");
QDomElement escalRadFracElement = element.firstChildElement("EscalRadFrac");
QDomElement escalLatFracElement = element.firstChildElement("EscalLatFrac");
QDomElement escalLostFracElement = element.firstChildElement("EscalLostFrac");
if (!escalPwrElement.isNull() && (escalPwrElement.text().toDouble() > 0)){
openstudio::model::ElectricEquipmentDefinition electricEquipmentDefinition(model);
electricEquipmentDefinition.setName(name + " Escalator Definition");
electricEquipmentDefinition.setDesignLevel(escalPwrElement.text().toDouble());
if (!escalRadFracElement.isNull()){
electricEquipmentDefinition.setFractionRadiant(escalRadFracElement.text().toDouble());
}
if (!escalLatFracElement.isNull()){
electricEquipmentDefinition.setFractionLatent(escalLatFracElement.text().toDouble());
}
if (!escalLostFracElement.isNull()){
electricEquipmentDefinition.setFractionLost(escalLostFracElement.text().toDouble());
}
openstudio::model::ElectricEquipment electricEquipment(electricEquipmentDefinition);
electricEquipment.setName(name + " Escalator");
electricEquipment.setSpace(space);
electricEquipment.setEndUseSubcategory("Internal Transport");
if (!escalSchRefElement.isNull()){
std::string scheduleName = escapeName(escalSchRefElement.text());
boost::optional<model::Schedule> schedule = model.getModelObjectByName<model::Schedule>(scheduleName);
if (schedule){
electricEquipment.setSchedule(*schedule);
}else{
LOG(Error, "Could not find schedule '" << scheduleName << "'");
}
}
}
}
//***** Process Gas Loads *****
{
//<ProcGasPwrDens>0.04</ProcGasPwrDens> - Btu per h ft2
//<ProcGasSchRef>Office Plugs Sched</ProcGasSchRef>
//<ProcGasRadFrac>0.2</ProcGasRadFrac>
//<ProcGasLatFrac>0.4</ProcGasLatFrac>
//<ProcGasLostFrac>0.2</ProcGasLostFrac>
QDomElement procGasPwrDensElement = element.firstChildElement("ProcGasPwrDens");
QDomElement procGasSchRefElement = element.firstChildElement("ProcGasSchRef");
QDomElement procGasRadFracElement = element.firstChildElement("ProcGasRadFrac");
QDomElement procGasLatFracElement = element.firstChildElement("ProcGasLatFrac");
QDomElement procGasLostFracElement = element.firstChildElement("ProcGasLostFrac");
if (!procGasPwrDensElement.isNull() && (procGasPwrDensElement.text().toDouble() > 0)){
openstudio::Quantity gasDensityIP(procGasPwrDensElement.text().toDouble(), openstudio::createUnit("Btu/h*ft^2").get());
OptionalQuantity gasDensitySI = QuantityConverter::instance().convert(gasDensityIP, whSys);
OS_ASSERT(gasDensitySI);
OS_ASSERT(gasDensitySI->units() == WhUnit(WhExpnt(1,0,-2)));
openstudio::model::GasEquipmentDefinition gasEquipmentDefinition(model);
gasEquipmentDefinition.setName(name + " Gas Loads Definition");
gasEquipmentDefinition.setWattsperSpaceFloorArea(gasDensitySI->value()); // W/m2
if (!procGasRadFracElement.isNull()){
gasEquipmentDefinition.setFractionRadiant(procGasRadFracElement.text().toDouble());
}
if (!procGasLatFracElement.isNull()){
gasEquipmentDefinition.setFractionLatent(procGasLatFracElement.text().toDouble());
}
if (!procGasLostFracElement.isNull()){
gasEquipmentDefinition.setFractionLost(procGasLostFracElement.text().toDouble());
}
openstudio::model::GasEquipment gasEquipment(gasEquipmentDefinition);
gasEquipment.setName(name + " Gas Loads");
gasEquipment.setSpace(space);
gasEquipment.setEndUseSubcategory("Process");
if (!procGasSchRefElement.isNull()){
std::string scheduleName = escapeName(procGasSchRefElement.text());
boost::optional<model::Schedule> schedule = model.getModelObjectByName<model::Schedule>(scheduleName);
if (schedule){
gasEquipment.setSchedule(*schedule);
}else{
LOG(Error, "Could not find schedule '" << scheduleName << "'");
}
}
}
}
return space;
}
boost::optional<model::ModelObject> ReverseTranslator::translateSurface(const QDomElement& element, const QDomDocument& doc, openstudio::model::Space& space)
{
boost::optional<model::ModelObject> result;
UnitSystem siSys(UnitSystem::SI);
std::vector<openstudio::Point3d> vertices;
QDomElement polyLoopElement = element.firstChildElement("PolyLp");
if (polyLoopElement.isNull()){
LOG(Error, "Surface element 'PolyLp' is empty, cannot create Surface.");
return boost::none;
}
QDomNodeList cartesianPointElements = polyLoopElement.elementsByTagName("CartesianPt");
for (int i = 0; i < cartesianPointElements.count(); i++){
QDomNodeList coordinateElements = cartesianPointElements.at(i).toElement().elementsByTagName("Coord");
if (coordinateElements.size() != 3){
LOG(Error, "PolyLp element 'CartesianPt' does not have exactly 3 'Coord' elements, cannot create Surface.");
return boost::none;
}
/* DLM: these unit conversions are taking about 75% of the total time to translate a large model
// sdd units = ft, os units = m
Quantity xIP(coordinateElements.at(0).toElement().text().toDouble(), IPUnit(IPExpnt(0,1,0)));
Quantity yIP(coordinateElements.at(1).toElement().text().toDouble(), IPUnit(IPExpnt(0,1,0)));
Quantity zIP(coordinateElements.at(2).toElement().text().toDouble(), IPUnit(IPExpnt(0,1,0)));
OptionalQuantity xSI = QuantityConverter::instance().convert(xIP, siSys);
OS_ASSERT(xSI);
OS_ASSERT(xSI->units() == SIUnit(SIExpnt(0,1,0)));
OptionalQuantity ySI = QuantityConverter::instance().convert(yIP, siSys);
OS_ASSERT(ySI);
OS_ASSERT(ySI->units() == SIUnit(SIExpnt(0,1,0)));
OptionalQuantity zSI = QuantityConverter::instance().convert(zIP, siSys);
OS_ASSERT(zSI);
OS_ASSERT(zSI->units() == SIUnit(SIExpnt(0,1,0)));
vertices.push_back(openstudio::Point3d(xSI->value(), ySI->value(), zSI->value()));
*/
double x = footToMeter*coordinateElements.at(0).toElement().text().toDouble();
double y = footToMeter*coordinateElements.at(1).toElement().text().toDouble();
double z = footToMeter*coordinateElements.at(2).toElement().text().toDouble();
vertices.push_back(openstudio::Point3d(x,y,z));
}
openstudio::model::Surface surface(vertices, space.model());
surface.setSpace(space);
QDomElement nameElement = element.firstChildElement("Name");
std::string name;
if (nameElement.isNull()){
LOG(Error, "Surface element 'Name' is empty.")
} else{
name = escapeName(nameElement.text());
}
surface.setName(name);
result = surface;
QDomElement constructionReferenceElement = element.firstChildElement("ConsAssmRef");
if(!constructionReferenceElement.isNull()){
std::string constructionName = escapeName(constructionReferenceElement.text());
boost::optional<model::ConstructionBase> construction = space.model().getModelObjectByName<model::ConstructionBase>(constructionName);
if(construction){
surface.setConstruction(*construction);
}else{
LOG(Error, "Cannot find construction '" << constructionName << "'");
}
}
QString tagName = element.tagName();
if (tagName == "ExtWall"){
surface.setSurfaceType("Wall");
surface.setOutsideBoundaryCondition("Outdoors");
surface.setSunExposure("SunExposed");
surface.setWindExposure("WindExposed");
}else if (tagName == "ExtFlr"){
surface.setSurfaceType("Floor");
surface.setOutsideBoundaryCondition("Outdoors");
surface.setSunExposure("SunExposed");
surface.setWindExposure("WindExposed");
}else if (tagName == "Roof"){
surface.setSurfaceType("RoofCeiling");
surface.setOutsideBoundaryCondition("Outdoors");
surface.setSunExposure("SunExposed");
surface.setWindExposure("WindExposed");
}else if (tagName.contains("UndgrFlr")){
surface.setSurfaceType("Floor");
surface.setOutsideBoundaryCondition("Ground");
surface.setSunExposure("NoSun");
surface.setWindExposure("NoWind");
}else if (tagName.contains("UndgrWall")){
surface.setSurfaceType("Wall");
surface.setOutsideBoundaryCondition("Ground");
surface.setSunExposure("NoSun");
surface.setWindExposure("NoWind");
}else if (tagName.contains("Ceiling")){
surface.setSurfaceType("RoofCeiling");
surface.setOutsideBoundaryCondition("Adiabatic");
surface.setSunExposure("NoSun");
surface.setWindExposure("NoWind");
}else if (tagName.contains("IntWall")){
surface.setSurfaceType("Wall");
surface.setOutsideBoundaryCondition("Adiabatic");
surface.setSunExposure("NoSun");
surface.setWindExposure("NoWind");
}else if (tagName.contains("IntFlr")){
surface.setSurfaceType("Floor");
surface.setOutsideBoundaryCondition("Adiabatic");
surface.setSunExposure("NoSun");
surface.setWindExposure("NoWind");
}else{
LOG(Error, "Unknown surface type '" << toString(tagName) << "'");
}
QDomElement perimExposedElement = element.firstChildElement("PerimExposed");
if (!perimExposedElement.isNull()){
double perimeterExposedIP = perimExposedElement.text().toDouble();
double perimeterExposedSI = footToMeter*perimeterExposedIP;
boost::optional<model::ConstructionBase> construction = surface.construction();
if (construction && construction->optionalCast<model::FFactorGroundFloorConstruction>()){
// clone the existing FFactor construction, set perimeter, and assign to this surface
model::FFactorGroundFloorConstruction fFactorConstruction = construction->cast<model::FFactorGroundFloorConstruction>();
model::Model model = fFactorConstruction.model();
model::FFactorGroundFloorConstruction clone = fFactorConstruction.clone(model).cast<model::FFactorGroundFloorConstruction>();
std::string cloneName = name + " " + fFactorConstruction.name().get();
clone.setName(cloneName);
clone.setPerimeterExposed(perimeterExposedSI);
clone.setArea(surface.grossArea());
surface.setConstruction(clone);
surface.setOutsideBoundaryCondition("GroundFCfactorMethod");
}else{
LOG(Error, "Cannot set exposed perimeter for surface '" << name << "''s construction.");
}
}
QDomElement heightElement = element.firstChildElement("Hgt");
if (!heightElement.isNull()){
double heightIP = heightElement.text().toDouble();
double heightSI = footToMeter*heightIP;
boost::optional<model::ConstructionBase> construction = surface.construction();
if (construction && construction->optionalCast<model::CFactorUndergroundWallConstruction>()){
// clone the existing CFactorUndergroundWallConstruction, set height, and assign to this surface
model::CFactorUndergroundWallConstruction cFactorConstruction = construction->cast<model::CFactorUndergroundWallConstruction>();
model::Model model = cFactorConstruction.model();
model::CFactorUndergroundWallConstruction clone = cFactorConstruction.clone(model).cast<model::CFactorUndergroundWallConstruction>();
std::string cloneName = name + " " + cFactorConstruction.name().get();
clone.setName(cloneName);
clone.setHeight(heightSI);
surface.setConstruction(clone);
surface.setOutsideBoundaryCondition("GroundFCfactorMethod");
}else{
LOG(Error, "Cannot set height for surface '" << name << "''s construction.");
}
}
// translate subSurfaces
QDomNodeList windowElements = element.elementsByTagName("Win");
QDomNodeList doorElements = element.elementsByTagName("Dr");
QDomNodeList skylightElements = element.elementsByTagName("Skylt");
for (int i = 0; i < windowElements.count(); ++i){
boost::optional<model::ModelObject> subSurface = translateSubSurface(windowElements.at(i).toElement(), doc, surface);
if (!subSurface){
LOG(Error, "Failed to translate 'Win' element " << i << " for Surface named '" << name << "'");
}
}
for (int i = 0; i < doorElements.count(); ++i){
boost::optional<model::ModelObject> subSurface = translateSubSurface(doorElements.at(i).toElement(), doc, surface);
if (!subSurface){
LOG(Error, "Failed to translate 'Dr' element " << i << " for Surface named '" << name << "'");
}
}
for (int i = 0; i < skylightElements.count(); ++i){
boost::optional<model::ModelObject> subSurface = translateSubSurface(skylightElements.at(i).toElement(), doc, surface);
if (!subSurface){
LOG(Error, "Failed to translate 'Skylt' element " << i << " for Surface named '" << name << "'");
}
}
// check for adjacent surface
QDomElement adjacentSpaceElement = element.firstChildElement("AdjacentSpcRef");
if (!adjacentSpaceElement.isNull()){
std::string adjacentSpaceName = escapeName(adjacentSpaceElement.text());
boost::optional<model::Space> otherSpace = space.model().getModelObjectByName<model::Space>(adjacentSpaceName);
if (!otherSpace){
LOG(Error, "Cannot retrieve adjacent Space '" << adjacentSpaceName << "' for Surface named '" << name << "'");
// DLM: make adiabatic per David Reddy, 6/5/2015
//surface.remove();
//return boost::none;
surface.setOutsideBoundaryCondition("Adiabatic");
} else if (otherSpace->handle() == space.handle()){
LOG(Error, "Adjacent Space '" << adjacentSpaceName << "' is same as parent Space for Surface named '" << name << "'. Removing interior surface.");
// DLM: make adiabatic per David Reddy, 6/5/2015
//surface.remove();
//return boost::none;
surface.setOutsideBoundaryCondition("Adiabatic");
} else{
// clone the surface and sub surfaces with reverse vertices
boost::optional<model::Surface> otherSurface = surface.createAdjacentSurface(*otherSpace);
if (!otherSurface){
LOG(Error, "Failed to create surface in adjacent Space '" << adjacentSpaceName << "' for Surface named '" << name << "'. Removing surface.");
// DLM: make adiabatic per David Reddy, 6/5/2015
//surface.remove();
//return boost::none;
surface.setOutsideBoundaryCondition("Adiabatic");
}
}
}
return result;
}
boost::optional<openstudio::model::ModelObject> ReverseTranslator::translateSubSurface(const QDomElement& element, const QDomDocument& doc, openstudio::model::Surface& surface)
{
std::vector<openstudio::Point3d> vertices;
UnitSystem siSys(UnitSystem::SI);
QDomElement polyLoopElement = element.firstChildElement("PolyLp");
if (polyLoopElement.isNull()){
LOG(Error, "SubSurface element 'PolyLp' is empty, cannot create SubSurface.");
return boost::none;
}
QDomNodeList cartesianPointElements = polyLoopElement.elementsByTagName("CartesianPt");
for (int i = 0; i < cartesianPointElements.count(); i++){
QDomNodeList coordinateElements = cartesianPointElements.at(i).toElement().elementsByTagName("Coord");
if (coordinateElements.size() != 3){
LOG(Error, "PolyLp element 'CartesianPt' does not have exactly 3 'Coord' elements, cannot create SubSurface.");
return boost::none;
}
/* DLM: there conversions were taking about 75% of the time it takes to convert a large model
// sdd units = ft, os units = m
Quantity xIP(coordinateElements.at(0).toElement().text().toDouble(), IPUnit(IPExpnt(0,1,0)));
Quantity yIP(coordinateElements.at(1).toElement().text().toDouble(), IPUnit(IPExpnt(0,1,0)));
Quantity zIP(coordinateElements.at(2).toElement().text().toDouble(), IPUnit(IPExpnt(0,1,0)));
OptionalQuantity xSI = QuantityConverter::instance().convert(xIP, siSys);
OS_ASSERT(xSI);
OS_ASSERT(xSI->units() == SIUnit(SIExpnt(0,1,0)));
OptionalQuantity ySI = QuantityConverter::instance().convert(yIP, siSys);
OS_ASSERT(ySI);
OS_ASSERT(ySI->units() == SIUnit(SIExpnt(0,1,0)));
OptionalQuantity zSI = QuantityConverter::instance().convert(zIP, siSys);
OS_ASSERT(zSI);
OS_ASSERT(zSI->units() == SIUnit(SIExpnt(0,1,0)));
vertices.push_back(openstudio::Point3d(xSI->value(), ySI->value(), zSI->value()));
*/
double x = footToMeter*coordinateElements.at(0).toElement().text().toDouble();
double y = footToMeter*coordinateElements.at(1).toElement().text().toDouble();
double z = footToMeter*coordinateElements.at(2).toElement().text().toDouble();
vertices.push_back(openstudio::Point3d(x,y,z));
}
model::SubSurface subSurface(vertices, surface.model());
subSurface.setSurface(surface);
QDomElement nameElement = element.firstChildElement("Name");
std::string name;
if (nameElement.isNull()){
LOG(Error, "Surface element 'Name' is empty.")
} else{
name = escapeName(nameElement.text());
}
subSurface.setName(name);
QString tagName = element.tagName();
if (tagName == "Win"){
subSurface.setSubSurfaceType("FixedWindow");
QDomElement constructionReferenceElement = element.firstChildElement("FenConsRef");
if(!constructionReferenceElement.isNull()){
std::string constructionName = escapeName(constructionReferenceElement.text());
boost::optional<model::ConstructionBase> construction = surface.model().getModelObjectByName<model::ConstructionBase>(constructionName);
if(construction){
subSurface.setConstruction(*construction);
}else{
LOG(Error, "Cannot find construction '" << constructionName << "'");
}
}
}else if (tagName == "Dr"){
subSurface.setSubSurfaceType("Door");
QDomElement constructionReferenceElement = element.firstChildElement("DrConsRef");
if(!constructionReferenceElement.isNull()){
std::string constructionName = escapeName(constructionReferenceElement.text());
boost::optional<model::ConstructionBase> construction = surface.model().getModelObjectByName<model::ConstructionBase>(constructionName);
if(construction){
subSurface.setConstruction(*construction);
}else{
LOG(Error, "Cannot find construction '" << constructionName << "'");
}
}
}else if (tagName == "Skylt"){
subSurface.setSubSurfaceType("Skylight");
QDomElement constructionReferenceElement = element.firstChildElement("FenConsRef");
if(!constructionReferenceElement.isNull()){
std::string constructionName = escapeName(constructionReferenceElement.text());
boost::optional<model::ConstructionBase> construction = surface.model().getModelObjectByName<model::ConstructionBase>(constructionName);
if(construction){
subSurface.setConstruction(*construction);
}else{
LOG(Error, "Cannot find construction '" << constructionName << "'");
}
}
}else{
LOG(Error, "Unknown subsurface type '" << toString(tagName) << "'");
}
// DLM: currently unhandled
// InternalShadingDevice
return subSurface;
}
boost::optional<openstudio::model::ModelObject> ReverseTranslator::translateShadingSurface(const QDomElement& element, const QDomDocument& doc, openstudio::model::ShadingSurfaceGroup& shadingSurfaceGroup)
{
std::vector<openstudio::Point3d> vertices;
UnitSystem siSys(UnitSystem::SI);
QDomElement polyLoopElement = element.firstChildElement("PolyLp");
if (polyLoopElement.isNull()){
LOG(Error, "ShadingSurface element 'PolyLp' is empty, cannot create ShadingSurface.");
return boost::none;
}
QDomNodeList cartesianPointElements = polyLoopElement.elementsByTagName("CartesianPt");
for (int i = 0; i < cartesianPointElements.count(); i++){
QDomNodeList coordinateElements = cartesianPointElements.at(i).toElement().elementsByTagName("Coord");
if (coordinateElements.size() != 3){
LOG(Error, "PolyLp element 'CartesianPt' does not have exactly 3 'Coord' elements, cannot create ShadingSurface.");
return boost::none;
}
/* DLM: there conversions were taking about 75% of the time it takes to convert a large model
// sdd units = ft, os units = m
Quantity xIP(coordinateElements.at(0).toElement().text().toDouble(), IPUnit(IPExpnt(0,1,0)));
Quantity yIP(coordinateElements.at(1).toElement().text().toDouble(), IPUnit(IPExpnt(0,1,0)));
Quantity zIP(coordinateElements.at(2).toElement().text().toDouble(), IPUnit(IPExpnt(0,1,0)));
OptionalQuantity xSI = QuantityConverter::instance().convert(xIP, siSys);
OS_ASSERT(xSI);
OS_ASSERT(xSI->units() == SIUnit(SIExpnt(0,1,0)));
OptionalQuantity ySI = QuantityConverter::instance().convert(yIP, siSys);
OS_ASSERT(ySI);
OS_ASSERT(ySI->units() == SIUnit(SIExpnt(0,1,0)));
OptionalQuantity zSI = QuantityConverter::instance().convert(zIP, siSys);
OS_ASSERT(zSI);
OS_ASSERT(zSI->units() == SIUnit(SIExpnt(0,1,0)));
vertices.push_back(openstudio::Point3d(xSI->value(), ySI->value(), zSI->value()));
*/
double x = footToMeter*coordinateElements.at(0).toElement().text().toDouble();
double y = footToMeter*coordinateElements.at(1).toElement().text().toDouble();
double z = footToMeter*coordinateElements.at(2).toElement().text().toDouble();
vertices.push_back(openstudio::Point3d(x,y,z));
}
model::Model model = shadingSurfaceGroup.model();
model::ShadingSurface shadingSurface(vertices, model);
shadingSurface.setShadingSurfaceGroup(shadingSurfaceGroup);
QDomElement nameElement = element.firstChildElement("Name");
std::string name;
if (nameElement.isNull()){
LOG(Error, "ShadingSurface element 'Name' is empty.")
} else{
name = escapeName(nameElement.text());
}
shadingSurface.setName(name);
QString tagName = element.tagName();
if (tagName == "ExtShdgObj"){
// default to 0 reflectance
// http://code.google.com/p/cbecc/issues/detail?id=344#c16
double solRefl = 0.0;
QDomElement solReflElement = element.firstChildElement("SolRefl");
if(!solReflElement.isNull()){
solRefl = solReflElement.text().toDouble();
}
double visRefl = 0.0;
QDomElement visReflElement = element.firstChildElement("VisRefl");
if(!visReflElement.isNull()){
visRefl = visReflElement.text().toDouble();
}
model::ConstructionBase construction = shadingConstruction(model, solRefl, visRefl);
shadingSurface.setConstruction(construction);
QDomElement transOptionElement = element.firstChildElement("TransOption");
if (!transOptionElement.isNull()){
boost::optional<model::Schedule> schedule;
std::string scheduleName;
// constant transmittance
if (transOptionElement.text().compare("Constant", Qt::CaseInsensitive) == 0){
QDomElement transElement = element.firstChildElement("Trans");
if (!transElement.isNull()){
schedule = shadingSchedule(model, transElement.text().toDouble());
if (schedule){
scheduleName = schedule->name().get();
}
} else {
LOG(Error, "Cannot find shading transmittance for shading surface '" << name << "'");
}
// transmittance schedule
} else if (transOptionElement.text().compare("Scheduled", Qt::CaseInsensitive) == 0){
QDomElement scheduleReferenceElement = element.firstChildElement("TransSchRef");
if (!scheduleReferenceElement.isNull()){
scheduleName = escapeName(scheduleReferenceElement.text());
schedule = model.getModelObjectByName<model::Schedule>(scheduleName);
if (!schedule){
LOG(Error, "Cannot find shading schedule '" << scheduleName << "' for shading surface '" << name << "'");
}
} else{
LOG(Error, "Cannot find shading schedule for shading surface '" << name << "'");
}
} else{
LOG(Error, "Unknown TransOption value for shading surface '" << name << "'");
}
if (schedule){
bool test = shadingSurface.setTransmittanceSchedule(*schedule);
if (!test){
LOG(Error, "Failed to assign shading schedule '" << scheduleName << "' to shading surface '" << name << "'");
}
} else {
// DLM: could warn here
}
}
}else{
LOG(Error, "Unknown shading surface type '" << toString(tagName) << "'");
}
return shadingSurface;
}
model::ConstructionBase ReverseTranslator::shadingConstruction(openstudio::model::Model& model, double solRefl, double visRefl)
{
std::pair<double, double> key = std::make_pair(solRefl, visRefl);
auto it = m_shadingConstructionMap.find(key);
if (it != m_shadingConstructionMap.end()){
return it->second;
}
std::string description = boost::lexical_cast<std::string>(solRefl) + "-" + boost::lexical_cast<std::string>(visRefl);
std::string constructionName = "Shading Construction " + description;
std::string materialName = "Shading Material " + description;
// create a construction with these properties
model::Construction construction(model);
construction.setName(constructionName);
model::MasslessOpaqueMaterial material(model);
material.setName(materialName);
bool test = material.setSolarAbsorptance(1.0-solRefl);
if (!test){
LOG(Error, "Failed to assign solar absorptance '" << 1.0-solRefl << "' to material '" << materialName << "'");
}
test = material.setVisibleAbsorptance(1.0-visRefl);
if (!test){
LOG(Error, "Failed to assign visible absorptance '" << 1.0-visRefl << "' to material '" << materialName << "'");
}
std::vector<model::Material> materials;
materials.push_back(material);
test = construction.setLayers(materials);
if (!test){
LOG(Error, "Failed to assign material layers to Construction named '" << constructionName << "'");
}
m_shadingConstructionMap.insert(std::make_pair(key, construction));
return construction;
}
model::Schedule ReverseTranslator::shadingSchedule(openstudio::model::Model& model, double trans)
{
auto it = m_shadingScheduleMap.find(trans);
if (it != m_shadingScheduleMap.end()){
return it->second;
}
std::string description = boost::lexical_cast<std::string>(trans);
std::string scheduleName = "Shading Schedule " + description;
// create a schedule with these properties
model::ScheduleRuleset schedule(model, trans);
schedule.setName(scheduleName);
m_shadingScheduleMap.insert(std::make_pair(trans, schedule));
return schedule;
}
boost::optional<QDomElement> ForwardTranslator::translateBuilding(const openstudio::model::Building& building, QDomDocument& doc)
{
QDomElement result = doc.createElement("Bldg");
m_translatedObjects[building.handle()] = result;
// name
std::string name = building.name().get();
QDomElement nameElement = doc.createElement("Name");
result.appendChild(nameElement);
nameElement.appendChild(doc.createTextNode(escapeName(name)));
// SDD:
// FuncClassMthd - optional, ignore
// RelocPubSchoolBldg - optional, in progress
// WholeBldgModeled - required, need to add
// BldgAz - required, done
// TotStoryCnt - required, in progress
// TotStoryCntNew - optional, need to add?
// TotStoryCntExisting - optional, need to add?
// TotStoryCntAltered - optional, need to add?
// AboveGrdStoryCnt - required, in progress
// AboveGrdStoryCntNew - optional, need to add?
// AboveGrdStoryCntExisting - optional, need to add?
// AboveGrdStoryCntAltered - optional, need to add?
// LivingUnitCnt - defaulted, in progress
// LivingUnitCntNew - optional, need to add?
// LivingUnitCntExisting - optional, need to add?
// LivingUnitCntAltered - optional, need to add?
// TotFlrArea - defaulted, ignore
// NonResFlrArea - defaulted, ignore
// ResFlrArea - defaulted, ignore
// TotCondVol - defaulted, ignore
// PlantClgCap - defaulted, ignore
// PlantHtgCap - defaulted, ignore
// CoilClgCap - defaulted, ignore
// CoilHtgCap - defaulted, ignore
// building azimuth
double buildingAzimuth = fixAngle(building.northAxis());
QDomElement buildingAzimuthElement = doc.createElement("BldgAz");
result.appendChild(buildingAzimuthElement);
buildingAzimuthElement.appendChild(doc.createTextNode(QString::number(buildingAzimuth)));
// TotStoryCnt - required, Standards Number of Stories
// AboveGrdStoryCnt - required, Standards Number of Above Ground Stories
// LivingUnitCnt - defaulted, Standards Number of Living Units
// translate storys
std::vector<model::BuildingStory> buildingStories = building.model().getConcreteModelObjects<model::BuildingStory>();
std::sort(buildingStories.begin(), buildingStories.end(), WorkspaceObjectNameLess());
if (m_progressBar){
m_progressBar->setWindowTitle(toString("Translating Building Stories"));
m_progressBar->setMinimum(0);
m_progressBar->setMaximum((int)buildingStories.size());
m_progressBar->setValue(0);
}
// DLM: do not translate aboveGradeStoryCount, Issue 243: Forward Translator - AboveGrdStryCount
/*
// aboveGradeStoryCount
unsigned numAboveGroundStories = 0;
for (const model::BuildingStory& buildingStory : buildingStories){
boost::optional<double> nominalZCoordinate = buildingStory.nominalZCoordinate();
if (nominalZCoordinate && *nominalZCoordinate >= 0){
numAboveGroundStories += 1;
}
}
QDomElement aboveGradeStoryCountElement = doc.createElement("AboveGrdStoryCnt");
result.appendChild(aboveGradeStoryCountElement);
aboveGradeStoryCountElement.appendChild(doc.createTextNode(QString::number(numAboveGroundStories)));
*/
// translate building shading
std::vector<model::ShadingSurfaceGroup> shadingSurfaceGroups = building.model().getConcreteModelObjects<model::ShadingSurfaceGroup>();
std::sort(shadingSurfaceGroups.begin(), shadingSurfaceGroups.end(), WorkspaceObjectNameLess());
if (m_progressBar){
m_progressBar->setWindowTitle(toString("Translating Building Shading"));
m_progressBar->setMinimum(0);
m_progressBar->setMaximum((int)shadingSurfaceGroups.size());
m_progressBar->setValue(0);
}
for (const model::ShadingSurfaceGroup& shadingSurfaceGroup : shadingSurfaceGroups){
if (istringEqual(shadingSurfaceGroup.shadingSurfaceType(), "Building")){
Transformation transformation = shadingSurfaceGroup.siteTransformation();
for (const model::ShadingSurface& shadingSurface : shadingSurfaceGroup.shadingSurfaces()){
boost::optional<QDomElement> shadingSurfaceElement = translateShadingSurface(shadingSurface, transformation, doc);
if (shadingSurfaceElement){
result.appendChild(*shadingSurfaceElement);
}
}
}
if (m_progressBar){
m_progressBar->setValue(m_progressBar->value() + 1);
}
}
// translate building story
for (const model::BuildingStory& buildingStory : buildingStories){
boost::optional<QDomElement> buildingStoryElement = translateBuildingStory(buildingStory, doc);
if (buildingStoryElement){
result.appendChild(*buildingStoryElement);
}
if (m_progressBar){
m_progressBar->setValue(m_progressBar->value() + 1);
}
}
// issue warning if any spaces not assigned to building story
std::vector<model::Space> spaces = building.model().getConcreteModelObjects<model::Space>();
std::sort(spaces.begin(), spaces.end(), WorkspaceObjectNameLess());
std::string spacesWithoutStory;
std::string spacesWithoutZone;
for (const model::Space& space : spaces){
if (!space.buildingStory()){
spacesWithoutStory += " '" + space.name().get() + "',";
}
if (!space.thermalZone()){
spacesWithoutZone += " '" + space.name().get() + "',";
}
}
if (spacesWithoutStory.size() > 0){
spacesWithoutStory.pop_back();
LOG(Warn, "Model contains spaces which are not assigned to a building story, these have not been translated:" << spacesWithoutStory);
}
if (spacesWithoutZone.size() > 0){
// DLM: desired workflow is to assign thermal zones in cbecc
// DLM: Kyle, we will have to think about if we want to warn about this or not
//Do not want this logged, http://code.google.com/p/cbecc/issues/detail?id=695
//spacesWithoutZone.pop_back();
//LOG(Warn, "Model contains spaces which are not assigned to a thermal zone, these have not been translated:" << spacesWithoutZone);
}
// issue warning if any surfaces not assigned to space
std::vector<model::Surface> surfaces = building.model().getConcreteModelObjects<model::Surface>();
std::sort(surfaces.begin(), surfaces.end(), WorkspaceObjectNameLess());
std::string surfacesWithoutSpace;
for (const model::Surface& surface : surfaces){
if (!surface.space()){
surfacesWithoutSpace += " '" + surface.name().get() + "',";
}
}
if (surfacesWithoutSpace.size() > 0){
surfacesWithoutSpace.pop_back();
LOG(Warn, "Model contains surfaces which are not assigned to a space, these have not been translated:" << surfacesWithoutSpace);
}
// issue warning if any sub surfaces not assigned to surface
std::vector<model::SubSurface> subSurfaces = building.model().getConcreteModelObjects<model::SubSurface>();
std::sort(subSurfaces.begin(), subSurfaces.end(), WorkspaceObjectNameLess());
std::string subSurfacesWithoutSurface;
for (const model::SubSurface& subSurface : subSurfaces){
if (!subSurface.surface()){
subSurfacesWithoutSurface += " '" + subSurface.name().get() + "',";
}
}
if (subSurfacesWithoutSurface.size() > 0){
subSurfacesWithoutSurface.pop_back();
LOG(Warn, "Model contains sub surfaces which are not assigned to a surface, these have not been translated:" << subSurfacesWithoutSurface);
}
// translate thermal zones
std::vector<model::ThermalZone> thermalZones = building.model().getConcreteModelObjects<model::ThermalZone>();
std::sort(thermalZones.begin(), thermalZones.end(), WorkspaceObjectNameLess());
if (m_progressBar){
m_progressBar->setWindowTitle(toString("Translating Thermal Zones"));
m_progressBar->setMinimum(0);
m_progressBar->setMaximum((int)thermalZones.size());
m_progressBar->setValue(0);
}
for (const model::ThermalZone& thermalZone : thermalZones){
boost::optional<QDomElement> thermalZoneElement = translateThermalZone(thermalZone, doc);
if (thermalZoneElement){
result.appendChild(*thermalZoneElement);
}
if (m_progressBar){
m_progressBar->setValue(m_progressBar->value() + 1);
}
}
// translate AirLoopHVAC systems
auto airLoops = building.model().getConcreteModelObjects<model::AirLoopHVAC>();
std::sort(airLoops.begin(),airLoops.end(),WorkspaceObjectNameLess());
if (m_progressBar) {
m_progressBar->setWindowTitle(toString("Translating AirLoopHVAC Systems"));
m_progressBar->setMinimum(0);
m_progressBar->setMaximum((int)airLoops.size());
m_progressBar->setValue(0);
}
for (const auto & airLoop : airLoops) {
auto airLoopElement = translateAirLoopHVAC(airLoop,doc);
if (airLoopElement) {
result.appendChild(*airLoopElement);
}
if (m_progressBar){
m_progressBar->setValue(m_progressBar->value() + 1);
}
}
return result;
}
boost::optional<QDomElement> ForwardTranslator::translateBuildingStory(const openstudio::model::BuildingStory& buildingStory, QDomDocument& doc)
{
QDomElement result = doc.createElement("Story");
m_translatedObjects[buildingStory.handle()] = result;
// name
std::string name = buildingStory.name().get();
QDomElement nameElement = doc.createElement("Name");
result.appendChild(nameElement);
nameElement.appendChild(doc.createTextNode(escapeName(name)));
// SDD:
// Mult - defaulted, ignore (OS doesn't have this)
// Z - only for simple geometry, ignore
// FlrToFlrHgt - only for simple geometry, ignore
// FlrToCeilingHgt - only for simple geometry, ignore
// translate spaces
std::vector<model::Space> spaces = buildingStory.spaces();
std::sort(spaces.begin(), spaces.end(), WorkspaceObjectNameLess());
for (const model::Space& space : spaces){
boost::optional<QDomElement> spaceElement = translateSpace(space, doc);
if (spaceElement){
result.appendChild(*spaceElement);
}
}
return result;
}
boost::optional<QDomElement> ForwardTranslator::translateSpace(const openstudio::model::Space& space, QDomDocument& doc)
{
UnitSystem ipSys(UnitSystem::IP);
UnitSystem btuSys(UnitSystem::BTU);
QDomElement result = doc.createElement("Spc");
m_translatedObjects[space.handle()] = result;
// name
std::string name = space.name().get();
QDomElement nameElement = doc.createElement("Name");
result.appendChild(nameElement);
nameElement.appendChild(doc.createTextNode(escapeName(name)));
// SDD:
// Status - required, need to add
// CondgType - required, in progress
// SupPlenumSpcRef - optional, in progress
// RetPlenumSpcRef - optional, in progress
// ThrmlZnRef - required, done
// Area - only for simple geometry, done, can we remove?
// FlrArea - optional, do we need this?
// FlrZ - optional, do we need this?
// FlrToCeilingHgt - optional, do we need this?
// Vol - required, done, can we remove?
// SpcFuncDefaultsRef - optional, do with space types
// SpcFunc - compulsory, do with space types
// FuncSchGrp - optional, do with space types
// OccDensSim - optional, do with space types
// OccSensHtRt - optional, do with space types
// OccLatHtRt - optional, do with space types
// OccSchRef - optional, do with space types
// InfMthd - defaulted, do with space types
// DsgnInfRt - defaulted, do with space types
// InfSchRef - defaulted, do with space types
// InfModelCoefA - required, do with space types
// InfModelCoefB - required, do with space types
// InfModelCoefC - required, do with space types
// InfModelCoefD - required, do with space types
// EnvStatus - optional, do with space types
// LtgStatus - optional, do with space types
// IntLtgSpecMthd - required, do with space types
// IntLPDReg - optional, do with space types
// IntLtgRegSchRef - optional, do with space types
// IntLtgRegHtGnSpcFrac - optional, do with space types
// IntLtgRegHtGnRadFrac - optional, do with space types
// IntLPDNonReg - optional, do with space types
// IntLtgNonRegSchRef - optional, do with space types
// IntLtgNonRegHtGnSpcFrac - optional, do with space types
// IntLtgNonRegHtGnRadFrac - optional, do with space types
// SkylitDayltgInstalledLtgPwr - optional, do we need this?
// PriSideDayltgInstalledLtgPwr - optional, do we need this?
// SecSideDayltgInstalledLtgPwr - optional, do we need this?
// Skylit100PctControlled - optional, do we need this?
// PriSide100PctControlled - optional, do we need this?
// SecSide100PctControlled - optional, do we need this?
// SkylitDayltgRefPtCoord - optional, do we need this?
// SkylitDayltgCtrlLtgPwr - optional, do we need this?
// SkylitDayltgCtrlLtgFrac - optional, do we need this?
// SkylitDayltgIllumSetpt - optional, do we need this?
// PriSideDayltgRefPtCoord - optional, do we need this?
// PriSideDayltgCtrlLtgPwr - optional, do we need this?
// PriSideDayltgCtrlLtgFrac - optional, do we need this?
// PriSideDayltgIllumSetpt - optional, do we need this?
// SecSideDayltgRefPtCoord - optional, do we need this?
// SecSideDayltgCtrlLtgPwr - optional, do we need this?
// SecSideDayltgCtrlLtgFrac - optional, do we need this?
// SecSideDayltgIllumSetpt - optional, do we need this?
// DayltgCtrlType - optional, do we need this?
// MinDimLtgFrac - optional, do we need this?
// MinDimPwrFrac - optional, do we need this?
// NumOfCtrlSteps - optional, do we need this?
// GlrAz - optional, do we need this?
// MaxGlrIdx - optional, do we need this?
// SkyltReqExcpt - optional, do we need this?
// SkyltReqExcptArea - optional, do we need this?
// SkyltReqExcptFrac - optional, do we need this?
// RecptPwrDens - defaulted, do with space types
// RecptSchRef - defaulted, do with space types
// RecptRadFrac - defaulted, do with space types
// RecptLatFrac - defaulted, do with space types
// RecptLostFrac - defaulted, do with space types
// GasEqpPwrDens - defaulted, do with space types
// GasEqpSchRef - defaulted, do with space types
// GasEqpRadFrac - defaulted, do with space types
// GasEqpLatFrac - defaulted, do with space types
// GasEqpLostFrac - defaulted, do with space types
// ProcElecPwrDens - optional, do with space types
// ProcElecSchRef - optional, do with space types
// ProcElecRadFrac - optional, do with space types
// ProcElecLatFrac - optional, do with space types
// ProcElecLostFrac - optional, do with space types
// ProcGasPwrDens - optional, do with space types
// ProcGasSchRef - optional, do with space types
// ProcGasRadFrac - optional, do with space types
// ProcGasLatFrac - optional, do with space types
// ProcGasLostFrac - optional, do with space types
// CommRfrgEPD - defaulted, do with space types
// CommRfrgEqpSchRef - defaulted, do with space types
// CommRfrgRadFrac - defaulted, do with space types
// CommRfrgLatFrac - defaulted, do with space types
// CommRfrgLostFrac - defaulted, do with space types
// ElevCnt - optional, do with space types
// ElevPwr - optional, do with space types
// ElevSchRef - defaulted, do with space types
// ElevRadFrac - optional, do with space types
// ElevLatFrac - optional, do with space types
// ElevLostFrac - optional, do with space types
// EscalCnt - optional, do with space types
// EscalPwr - optional, do with space types
// EscalSchRef - defaulted, do with space types
// EscalRadFrac - optional, do with space types
// EscalLatFrac - optional, do with space types
// EscalLostFrac - optional, do with space types
// SHWFluidSegRef - optional, do with space types
// RecircDHWSysRef - optional, do with space types
// HotWtrHtgRt - defaulted, do with space types
// RecircHotWtrHtgRt - optional, do with space types
// HotWtrHtgSchRef - optional, do with space types
// VentPerPerson - defaulted, do with space types
// VentPerArea - defaulted, do with space types
// VentACH - optional, do with space types
// VentPerSpc - optional, do with space types
// ExhPerArea - optional, do we need this?
// ExhACH - optional, do we need this?
// ExhPerSpc - optional, do we need this?
// KitExhHoodLen - optional, do we need this?
// KitExhHoodStyle - optional, do we need this?
// KitExhHoodDuty - optional, do we need this?
// KitExhHoodFlow - optional, do we need this?
// LabExhRtType - optional, do we need this?
// IntLPDPrescrip - optional, do we need this?
// IsPlenumRet - optional, do we need this?
// HighRiseResInt - optional, do we need this?
// HighRiseResCondFlrArea - optional, do we need this?
// volume
double volume = space.volume();
Quantity volumeSI(volume, SIUnit(SIExpnt(0,3,0)));
OptionalQuantity volumeIP = QuantityConverter::instance().convert(volumeSI, ipSys);
OS_ASSERT(volumeIP);
OS_ASSERT(volumeIP->units() == IPUnit(IPExpnt(0,3,0)));
QDomElement volumeElement = doc.createElement("Vol");
result.appendChild(volumeElement);
volumeElement.appendChild(doc.createTextNode(QString::number(volumeIP->value())));
// log warning if volume is 0
if (volumeIP->value() < std::numeric_limits<double>::epsilon()){
LOG(Warn, "Space '" << name << "' has zero volume.");
}
// area
double floorArea = space.floorArea();
Quantity floorAreaSI(floorArea, SIUnit(SIExpnt(0,2,0)));
OptionalQuantity floorAreaIP = QuantityConverter::instance().convert(floorAreaSI, ipSys);
OS_ASSERT(floorAreaIP);
OS_ASSERT(floorAreaIP->units() == IPUnit(IPExpnt(0,2,0)));
QDomElement floorAreaElement = doc.createElement("Area"); // SAC 3/14/14
result.appendChild(floorAreaElement);
floorAreaElement.appendChild(doc.createTextNode(QString::number(floorAreaIP->value())));
// log warning if area is 0
if (floorAreaIP->value() < std::numeric_limits<double>::epsilon()){
LOG(Warn, "Space '" << name << "' has zero floor area.");
}
// translate floorPrint
Transformation transformation = space.siteTransformation();
Point3dVector vertices = transformation*space.floorPrint();
boost::optional<double> floorPrintArea = openstudio::getArea(vertices);
if (vertices.empty() || !floorPrintArea){
LOG(Warn, "Cannot compute floor print for space '" << name << "'.");
}else{
Quantity floorPrintAreaSI(*floorPrintArea, SIUnit(SIExpnt(0, 2, 0)));
OptionalQuantity floorPrintAreaIP = QuantityConverter::instance().convert(floorPrintAreaSI, ipSys);
OS_ASSERT(floorPrintAreaIP);
OS_ASSERT(floorPrintAreaIP->units() == IPUnit(IPExpnt(0, 2, 0)));
// log warning if floor print area is 0
if (floorPrintAreaIP->value() < std::numeric_limits<double>::epsilon()){
LOG(Warn, "Space '" << name << "' has zero floor print area.");
}
}
QDomElement polyLoopElement = doc.createElement("PolyLp");
result.appendChild(polyLoopElement);
for (const Point3d& vertex : vertices){
QDomElement cartesianPointElement = doc.createElement("CartesianPt");
polyLoopElement.appendChild(cartesianPointElement);
QDomElement coordinateXElement = doc.createElement("Coord");
cartesianPointElement.appendChild(coordinateXElement);
coordinateXElement.appendChild(doc.createTextNode(QString::number(meterToFoot*vertex.x())));
QDomElement coordinateYElement = doc.createElement("Coord");
cartesianPointElement.appendChild(coordinateYElement);
coordinateYElement.appendChild(doc.createTextNode(QString::number(meterToFoot*vertex.y())));
QDomElement coordinateZElement = doc.createElement("Coord");
cartesianPointElement.appendChild(coordinateZElement);
coordinateZElement.appendChild(doc.createTextNode(QString::number(meterToFoot*vertex.z())));
}
// thermal zone
boost::optional<model::ThermalZone> thermalZone = space.thermalZone();
if (thermalZone){
std::string thermalZoneName = thermalZone->name().get();
QDomElement thermalZoneElement = doc.createElement("ThrmlZnRef");
result.appendChild(thermalZoneElement);
thermalZoneElement.appendChild(doc.createTextNode(escapeName(thermalZoneName)));
// CondgType - required
// SupPlenumSpcRef - optional
// RetPlenumSpcRef - optional
// ThrmlZnRef - required
}
// translate space shading
std::vector<model::ShadingSurfaceGroup> shadingSurfaceGroups = space.shadingSurfaceGroups();
std::sort(shadingSurfaceGroups.begin(), shadingSurfaceGroups.end(), WorkspaceObjectNameLess());
for (const model::ShadingSurfaceGroup& shadingSurfaceGroup : shadingSurfaceGroups){
Transformation shadingTransformation = shadingSurfaceGroup.siteTransformation();
for (const model::ShadingSurface& shadingSurface : shadingSurfaceGroup.shadingSurfaces()){
boost::optional<QDomElement> shadingSurfaceElement = translateShadingSurface(shadingSurface, shadingTransformation, doc);
if (shadingSurfaceElement){
result.appendChild(*shadingSurfaceElement);
}
}
}
// translate surfaces
std::vector<model::Surface> surfaces = space.surfaces();
std::sort(surfaces.begin(), surfaces.end(), WorkspaceObjectNameLess());
unsigned numFloors = 0;
unsigned numWalls = 0;
unsigned numRoofCeilings = 0;
for (const model::Surface& surface : surfaces){
std::string surfaceType = surface.surfaceType();
if (istringEqual("Wall", surfaceType)){
++numWalls;
} else if (istringEqual("RoofCeiling", surfaceType)){
++numRoofCeilings;
} else if (istringEqual("Floor", surfaceType)){
++numFloors;
}
boost::optional<QDomElement> surfaceElement = translateSurface(surface, transformation, doc);
if (surfaceElement){
result.appendChild(*surfaceElement);
}
}
if (numFloors < 1){
LOG(Warn, "Space '" << name << "' has less than 1 floor surfaces.")
}
if (numWalls < 3){
LOG(Warn, "Space '" << name << "' has less than 3 wall surfaces.")
}
if (numRoofCeilings < 1){
LOG(Warn, "Space '" << name << "' has less than 1 roof or ceiling surfaces.")
}
return result;
}
boost::optional<QDomElement> ForwardTranslator::translateSurface(const openstudio::model::Surface& surface, const openstudio::Transformation& transformation, QDomDocument& doc)
{
UnitSystem ipSys(UnitSystem::IP);
boost::optional<QDomElement> result;
// return if already translated
if (m_translatedObjects.find(surface.handle()) != m_translatedObjects.end()){
return boost::none;
}
std::string surfaceType = surface.surfaceType();
std::string outsideBoundaryCondition = surface.outsideBoundaryCondition();
if (istringEqual("Wall", surfaceType)){
if (istringEqual("Outdoors", outsideBoundaryCondition)){
result = doc.createElement("ExtWall");
}else if (surface.isGroundSurface()){
result = doc.createElement("UndgrWall");
}else if (istringEqual("Surface", outsideBoundaryCondition) ||
istringEqual("Adiabatic", outsideBoundaryCondition)){
result = doc.createElement("IntWall");
}
}else if (istringEqual("RoofCeiling", surfaceType)){
if (istringEqual("Outdoors", outsideBoundaryCondition)){
result = doc.createElement("Roof");
}else if (surface.isGroundSurface()){
// DLM: what to do here?
}else if (istringEqual("Surface", outsideBoundaryCondition) ||
istringEqual("Adiabatic", outsideBoundaryCondition)){
// DLM: we are not translating interior ceiling surfaces, the paired interior floor will be written instead
//result = doc.createElement("Ceiling");
return boost::none;
}
}else if (istringEqual("Floor", surfaceType)){
if (surface.isGroundSurface()){
result = doc.createElement("UndgrFlr");
}else if (istringEqual("Surface", outsideBoundaryCondition) ||
istringEqual("Adiabatic", outsideBoundaryCondition)){
result = doc.createElement("IntFlr");
}else if (istringEqual("Outdoors", outsideBoundaryCondition)){
result = doc.createElement("ExtFlr");
}
}
if (!result){
LOG(Error, "Cannot map surface '" << surface.name().get() << "' to a known surfaceType");
return boost::none;
}
m_translatedObjects[surface.handle()] = *result;
// name
std::string name = surface.name().get();
QDomElement nameElement = doc.createElement("Name");
result->appendChild(nameElement);
nameElement.appendChild(doc.createTextNode(escapeName(name)));
// SDD:
// Status - required (ExtFlr, ExtWall, IntWall, Roof, UndgrFlr, UndgrWall), need to add
// ConsAssmRef - optional (Ceiling, ExtFlr, ExtWall, IntFlr, IntWall, Roof, UndgrFlr, UndgrWall), done
// AdjacentSpcRef - optional (Ceiling, IntFlr, IntWall), done
// Area - simplified geometry only (Ceiling, ExtFlr, ExtWall, IntFlr, IntWall, Roof, UndgrFlr, UndgrWall), ignore
// Hgt - optional (UndgrWall), done, requires unique CFactor construction per surface
// PerimExposed - optional (UndgrFlr), done requires unique FFactor construction per surface
// DisplayPerim - optional (ExtWall), need to add?
// Az - simplified geometry only (ExtWall, Roof), ignore
// Tilt - simplified geometry only (Roof), ignore
// ExtSolAbs - required (Ceiling, ExtFlr, ExtWall, IntWall), ignore, do at construction level
// ExtThrmlAbs - required (Ceiling, ExtFlr, ExtWall, IntWall), ignore, do at construction level
// ExtVisAbs - required (Ceiling, ExtFlr, ExtWall, IntWall), ignore, do at construction level
// IntSolAbs - optional (Ceiling, ExtFlr, ExtWall, IntFlr, IntWall, Roof, UndgrFlr, UndgrWall), ignore, do at construction level
// IntThrmlAbs - optional (Ceiling, ExtFlr, ExtWall, IntFlr, IntWall, Roof, UndgrFlr, UndgrWall), ignore, do at construction level
// IntVisAbs - optional (Ceiling, ExtFlr, ExtWall, IntFlr, IntWall, Roof, UndgrFlr, UndgrWall), ignore, do at construction level
// FieldAppliedCoating - optional (Roof), ignore, do at construction level
// CRRCInitialRefl - optional (Roof), ignore, do at construction level
// CRRCAgedRefl - optional (Roof), ignore, do at construction level
// CRRCInitialEmittance - optional (Roof)), ignore, do at construction level
// CRRCAgedEmittance - optional (Roof), ignore, do at construction level
// CRRCInitialSRI - optional (Roof), ignore, do at construction level
// CRRCAgedSRI - optional (Roof), ignore, do at construction level
// CRRCProdID - optional (Roof), ignore, do at construction level
// adjacent surface
boost::optional<model::Surface> adjacentSurface = surface.adjacentSurface();
if (adjacentSurface){
boost::optional<model::Space> adjacentSpace = adjacentSurface->space();
if (adjacentSpace){
std::string adjacentSpaceName = adjacentSpace->name().get();
QDomElement adjacentSpaceElement = doc.createElement("AdjacentSpcRef");
result->appendChild(adjacentSpaceElement);
adjacentSpaceElement.appendChild(doc.createTextNode(escapeName(adjacentSpaceName)));
// count adjacent surface as translated
m_translatedObjects[adjacentSurface->handle()] = *result;
}
}
// construction reference
boost::optional<model::ConstructionBase> construction = surface.construction();
if (construction){
std::string constructionName = construction->name().get();
// check that construction has been translated
if (m_translatedObjects.find(construction->handle()) != m_translatedObjects.end()){
QDomElement constructionReferenceElement = doc.createElement("ConsAssmRef");
result->appendChild(constructionReferenceElement);
constructionReferenceElement.appendChild(doc.createTextNode(escapeName(constructionName)));
}else{
//Do not want this logged, http://code.google.com/p/cbecc/issues/detail?id=695
//LOG(Error, "Surface '" << name << "' uses construction '" << constructionName << "' which has not been translated");
}
}
// if underground floor try to write out perimeter exposed
if (istringEqual("Floor", surfaceType) && surface.isGroundSurface()){
// DLM: for now we will get the exposed perimeter from the FFactor construction
// this assumes one construction per surface, I don't really like this, maybe we can do better later
if (construction && construction->optionalCast<model::FFactorGroundFloorConstruction>()){
model::FFactorGroundFloorConstruction fFactorConstruction = construction->cast<model::FFactorGroundFloorConstruction>();
// check assumption of one surface per FFactor construction
if (fFactorConstruction.getModelObjectSources<model::Surface>().size() == 1){
double perimeterExposedSI = fFactorConstruction.perimeterExposed();
double perimeterExposedIP = meterToFoot*perimeterExposedSI;
QDomElement perimExposedElement = doc.createElement("PerimExposed");
result->appendChild(perimExposedElement);
perimExposedElement.appendChild(doc.createTextNode(QString::number(perimeterExposedIP)));
}else{
//Do not want this logged, http://code.google.com/p/cbecc/issues/detail?id=695
//LOG(Error, "Cannot compute exposed perimeter for surface '" << name << "'.");
}
}else{
//Do not want this logged, http://code.google.com/p/cbecc/issues/detail?id=695
//LOG(Error, "Cannot compute exposed perimeter for surface '" << name << "'.");
}
}
// if underground wall try to write out height
if (istringEqual("Wall", surfaceType) && surface.isGroundSurface()){
// DLM: for now we will get the height from the CFactor construction
// this assumes one construction per surface, I don't really like this, maybe we can do better later
if (construction && construction->optionalCast<model::CFactorUndergroundWallConstruction>()){
model::CFactorUndergroundWallConstruction cFactorConstruction = construction->cast<model::CFactorUndergroundWallConstruction>();
// check assumption of one surface per CFactor construction
if (cFactorConstruction.getModelObjectSources<model::Surface>().size() == 1){
double heightSI = cFactorConstruction.height();
double heightIP = meterToFoot*heightSI;
QDomElement heightElement = doc.createElement("Hgt");
result->appendChild(heightElement);
heightElement.appendChild(doc.createTextNode(QString::number(heightIP)));
}else{
//Do not want this logged, http://code.google.com/p/cbecc/issues/detail?id=695
//LOG(Error, "Cannot compute height for surface '" << name << "'.");
}
}else{
//Do not want this logged, http://code.google.com/p/cbecc/issues/detail?id=695
//LOG(Error, "Cannot compute height for surface '" << name << "'.");
}
}
// check area
double grossArea = surface.grossArea();
Quantity grossAreaSI(grossArea, SIUnit(SIExpnt(0, 2, 0)));
OptionalQuantity grossAreaIP = QuantityConverter::instance().convert(grossAreaSI, ipSys);
OS_ASSERT(grossAreaIP);
OS_ASSERT(grossAreaIP->units() == IPUnit(IPExpnt(0, 2, 0)));
// log warning if area is 0
if (grossAreaIP->value() < std::numeric_limits<double>::epsilon()){
LOG(Warn, "Surface '" << name << "' has zero area.")
}
// translate vertices
Point3dVector vertices = transformation*surface.vertices();
QDomElement polyLoopElement = doc.createElement("PolyLp");
result->appendChild(polyLoopElement);
for (const Point3d& vertex : vertices){
QDomElement cartesianPointElement = doc.createElement("CartesianPt");
polyLoopElement.appendChild(cartesianPointElement);
/* DLM: these conversions were taking about 75% of the time to convert a large model
Quantity xSI(vertex.x(), SIUnit(SIExpnt(0,1,0)));
Quantity ySI(vertex.y(), SIUnit(SIExpnt(0,1,0)));
Quantity zSI(vertex.z(), SIUnit(SIExpnt(0,1,0)));
OptionalQuantity xIP = QuantityConverter::instance().convert(xSI, ipSys);
OS_ASSERT(xIP);
OS_ASSERT(xIP->units() == IPUnit(IPExpnt(0,1,0)));
OptionalQuantity yIP = QuantityConverter::instance().convert(ySI, ipSys);
OS_ASSERT(yIP);
OS_ASSERT(yIP->units() == IPUnit(IPExpnt(0,1,0)));
OptionalQuantity zIP = QuantityConverter::instance().convert(zSI, ipSys);
OS_ASSERT(zIP);
OS_ASSERT(zIP->units() == IPUnit(IPExpnt(0,1,0)));
QDomElement coordinateXElement = doc.createElement("Coord");
cartesianPointElement.appendChild(coordinateXElement);
coordinateXElement.appendChild(doc.createTextNode(QString::number(xIP->value())));
QDomElement coordinateYElement = doc.createElement("Coord");
cartesianPointElement.appendChild(coordinateYElement);
coordinateYElement.appendChild(doc.createTextNode(QString::number(yIP->value())));
QDomElement coordinateZElement = doc.createElement("Coord");
cartesianPointElement.appendChild(coordinateZElement);
coordinateZElement.appendChild(doc.createTextNode(QString::number(zIP->value())));
*/
QDomElement coordinateXElement = doc.createElement("Coord");
cartesianPointElement.appendChild(coordinateXElement);
coordinateXElement.appendChild(doc.createTextNode(QString::number(meterToFoot*vertex.x())));
QDomElement coordinateYElement = doc.createElement("Coord");
cartesianPointElement.appendChild(coordinateYElement);
coordinateYElement.appendChild(doc.createTextNode(QString::number(meterToFoot*vertex.y())));
QDomElement coordinateZElement = doc.createElement("Coord");
cartesianPointElement.appendChild(coordinateZElement);
coordinateZElement.appendChild(doc.createTextNode(QString::number(meterToFoot*vertex.z())));
}
// translate sub surfaces
std::vector<model::SubSurface> subSurfaces = surface.subSurfaces();
std::sort(subSurfaces.begin(), subSurfaces.end(), WorkspaceObjectNameLess());
for (const model::SubSurface& subSurface : subSurfaces){
boost::optional<QDomElement> subSurfaceElement = translateSubSurface(subSurface, transformation, doc);
if (subSurfaceElement){
result->appendChild(*subSurfaceElement);
}
}
return result;
}
boost::optional<QDomElement> ForwardTranslator::translateSubSurface(const openstudio::model::SubSurface& subSurface, const openstudio::Transformation& transformation, QDomDocument& doc)
{
UnitSystem ipSys(UnitSystem::IP);
boost::optional<QDomElement> result;
// return if already translated
if (m_translatedObjects.find(subSurface.handle()) != m_translatedObjects.end()){
return boost::none;
}
std::string subSurfaceType = subSurface.subSurfaceType();
QString consRefElementName;
if (istringEqual("FixedWindow", subSurfaceType) ||
istringEqual("OperableWindow", subSurfaceType) ||
istringEqual("GlassDoor", subSurfaceType)){
consRefElementName = "FenConsRef";
result = doc.createElement("Win");
}else if (istringEqual("Door", subSurfaceType) ||
istringEqual("OverheadDoor", subSurfaceType)){
consRefElementName = "DrConsRef";
result = doc.createElement("Dr");
}else if (istringEqual("Skylight", subSurfaceType)){
consRefElementName = "FenConsRef";
result = doc.createElement("Skylt");
}
if (!result){
LOG(Error, "Cannot map subsurface '" << subSurface.name().get() << "' to a known subsurfaceType");
return boost::none;
}
m_translatedObjects[subSurface.handle()] = *result;
// name
std::string name = subSurface.name().get();
QDomElement nameElement = doc.createElement("Name");
result->appendChild(nameElement);
nameElement.appendChild(doc.createTextNode(escapeName(name)));
// SDD:
// Status - required (Win, Skylt, Dr), need to add
// FenConsRef - optional (Win, Skylt), done
// DrConsRef - optional (Dr), done
// Oper - optional (Dr), in progress
// Area - simple geometry only (Win, Skylt, Dr), ignore
// construction
boost::optional<model::ConstructionBase> construction = subSurface.construction();
if (construction){
std::string constructionName = construction->name().get();
// check that construction has been translated
if (m_translatedObjects.find(construction->handle()) != m_translatedObjects.end()){
QDomElement constructionReferenceElement = doc.createElement(consRefElementName);
result->appendChild(constructionReferenceElement);
constructionReferenceElement.appendChild(doc.createTextNode(escapeName(constructionName)));
}else{
//Do not want this logged, http://code.google.com/p/cbecc/issues/detail?id=695
//LOG(Error, "SubSurface '" << name << "' uses construction '" << constructionName << "' which has not been translated");
}
}
// check area
double grossArea = subSurface.grossArea();
Quantity grossAreaSI(grossArea, SIUnit(SIExpnt(0, 2, 0)));
OptionalQuantity grossAreaIP = QuantityConverter::instance().convert(grossAreaSI, ipSys);
OS_ASSERT(grossAreaIP);
OS_ASSERT(grossAreaIP->units() == IPUnit(IPExpnt(0, 2, 0)));
// log warning if area is 0
if (grossAreaIP->value() < std::numeric_limits<double>::epsilon()){
LOG(Warn, "Sub Surface '" << name << "' has zero area.")
}
// translate vertices
Point3dVector vertices = transformation*subSurface.vertices();
QDomElement polyLoopElement = doc.createElement("PolyLp");
result->appendChild(polyLoopElement);
for (const Point3d& vertex : vertices){
QDomElement cartesianPointElement = doc.createElement("CartesianPt");
polyLoopElement.appendChild(cartesianPointElement);
/* DLM: these conversions were taking about 75% of the time it takes to convert a large model
Quantity xSI(vertex.x(), SIUnit(SIExpnt(0,1,0)));
Quantity ySI(vertex.y(), SIUnit(SIExpnt(0,1,0)));
Quantity zSI(vertex.z(), SIUnit(SIExpnt(0,1,0)));
OptionalQuantity xIP = QuantityConverter::instance().convert(xSI, ipSys);
OS_ASSERT(xIP);
OS_ASSERT(xIP->units() == IPUnit(IPExpnt(0,1,0)));
OptionalQuantity yIP = QuantityConverter::instance().convert(ySI, ipSys);
OS_ASSERT(yIP);
OS_ASSERT(yIP->units() == IPUnit(IPExpnt(0,1,0)));
OptionalQuantity zIP = QuantityConverter::instance().convert(zSI, ipSys);
OS_ASSERT(zIP);
OS_ASSERT(zIP->units() == IPUnit(IPExpnt(0,1,0)));
QDomElement coordinateXElement = doc.createElement("Coord");
cartesianPointElement.appendChild(coordinateXElement);
coordinateXElement.appendChild(doc.createTextNode(QString::number(xIP->value())));
QDomElement coordinateYElement = doc.createElement("Coord");
cartesianPointElement.appendChild(coordinateYElement);
coordinateYElement.appendChild(doc.createTextNode(QString::number(yIP->value())));
QDomElement coordinateZElement = doc.createElement("Coord");
cartesianPointElement.appendChild(coordinateZElement);
coordinateZElement.appendChild(doc.createTextNode(QString::number(zIP->value())));
*/
QDomElement coordinateXElement = doc.createElement("Coord");
cartesianPointElement.appendChild(coordinateXElement);
coordinateXElement.appendChild(doc.createTextNode(QString::number(meterToFoot*vertex.x())));
QDomElement coordinateYElement = doc.createElement("Coord");
cartesianPointElement.appendChild(coordinateYElement);
coordinateYElement.appendChild(doc.createTextNode(QString::number(meterToFoot*vertex.y())));
QDomElement coordinateZElement = doc.createElement("Coord");
cartesianPointElement.appendChild(coordinateZElement);
coordinateZElement.appendChild(doc.createTextNode(QString::number(meterToFoot*vertex.z())));
}
return result;
}
boost::optional<QDomElement> ForwardTranslator::translateShadingSurface(const openstudio::model::ShadingSurface& shadingSurface, const openstudio::Transformation& transformation, QDomDocument& doc)
{
UnitSystem ipSys(UnitSystem::IP);
boost::optional<QDomElement> result;
// return if already translated
if (m_translatedObjects.find(shadingSurface.handle()) != m_translatedObjects.end()){
return boost::none;
}
result = doc.createElement("ExtShdgObj");
m_translatedObjects[shadingSurface.handle()] = *result;
// name
std::string name = shadingSurface.name().get();
QDomElement nameElement = doc.createElement("Name");
result->appendChild(nameElement);
nameElement.appendChild(doc.createTextNode(escapeName(name)));
// SDD:
// Status - required, need to add
// TransSchRef - optional, in progress
// SolRefl - optional, done
// VisRefl - optional, done
// schedule
boost::optional<model::Schedule> transmittanceSchedule = shadingSurface.transmittanceSchedule();
if (transmittanceSchedule){
std::string transmittanceScheduleName = transmittanceSchedule->name().get();
// check that construction has been translated
if (m_translatedObjects.find(transmittanceSchedule->handle()) != m_translatedObjects.end()){
QDomElement transmittanceScheduleReferenceElement = doc.createElement("TransSchRef");
result->appendChild(transmittanceScheduleReferenceElement);
transmittanceScheduleReferenceElement.appendChild(doc.createTextNode(escapeName(transmittanceScheduleName)));
}else{
LOG(Error, "ShadingSurface '" << name << "' uses transmittance schedule '" << transmittanceScheduleName << "' which has not been translated");
}
}
// default to 0 reflectance
// http://code.google.com/p/cbecc/issues/detail?id=344#c16
double solRefl = 0.0;
double visRefl = 0.0;
boost::optional<model::ConstructionBase> constructionBase = shadingSurface.construction();
if (constructionBase){
boost::optional<model::Construction> construction = constructionBase->optionalCast<model::Construction>();
if (construction){
std::vector<model::Material> layers = construction->layers();
if (!layers.empty()){
if (layers[0].optionalCast<model::StandardOpaqueMaterial>()){
model::StandardOpaqueMaterial outerMaterial = layers[0].cast<model::StandardOpaqueMaterial>();
if (!outerMaterial.isSolarAbsorptanceDefaulted()){
boost::optional<double> test = outerMaterial.solarReflectance();
if (test){
solRefl = *test;
}
}
if (!outerMaterial.isVisibleAbsorptanceDefaulted()){
boost::optional<double> test = outerMaterial.visibleReflectance();
if (test){
visRefl = *test;
}
}
}
if (layers[0].optionalCast<model::MasslessOpaqueMaterial>()){
model::MasslessOpaqueMaterial outerMaterial = layers[0].cast<model::MasslessOpaqueMaterial>();
if (!outerMaterial.isSolarAbsorptanceDefaulted()){
boost::optional<double> test = outerMaterial.solarReflectance();
if (test){
solRefl = *test;
}
}
if (!outerMaterial.isVisibleAbsorptanceDefaulted()){
boost::optional<double> test = outerMaterial.visibleReflectance();
if (test){
visRefl = *test;
}
}
}
}
}
}
QDomElement solReflElement = doc.createElement("SolRefl");
result->appendChild(solReflElement);
solReflElement.appendChild(doc.createTextNode(QString::number(solRefl)));
QDomElement visReflElement = doc.createElement("VisRefl");
result->appendChild(visReflElement);
visReflElement.appendChild(doc.createTextNode(QString::number(visRefl)));
// translate vertices
Point3dVector vertices = transformation*shadingSurface.vertices();
QDomElement polyLoopElement = doc.createElement("PolyLp");
result->appendChild(polyLoopElement);
for (const Point3d& vertex : vertices){
QDomElement cartesianPointElement = doc.createElement("CartesianPt");
polyLoopElement.appendChild(cartesianPointElement);
/* DLM: these conversions were taking about 75% of the time it takes to convert a large model
Quantity xSI(vertex.x(), SIUnit(SIExpnt(0,1,0)));
Quantity ySI(vertex.y(), SIUnit(SIExpnt(0,1,0)));
Quantity zSI(vertex.z(), SIUnit(SIExpnt(0,1,0)));
OptionalQuantity xIP = QuantityConverter::instance().convert(xSI, ipSys);
OS_ASSERT(xIP);
OS_ASSERT(xIP->units() == IPUnit(IPExpnt(0,1,0)));
OptionalQuantity yIP = QuantityConverter::instance().convert(ySI, ipSys);
OS_ASSERT(yIP);
OS_ASSERT(yIP->units() == IPUnit(IPExpnt(0,1,0)));
OptionalQuantity zIP = QuantityConverter::instance().convert(zSI, ipSys);
OS_ASSERT(zIP);
OS_ASSERT(zIP->units() == IPUnit(IPExpnt(0,1,0)));
QDomElement coordinateXElement = doc.createElement("Coord");
cartesianPointElement.appendChild(coordinateXElement);
coordinateXElement.appendChild(doc.createTextNode(QString::number(xIP->value())));
QDomElement coordinateYElement = doc.createElement("Coord");
cartesianPointElement.appendChild(coordinateYElement);
coordinateYElement.appendChild(doc.createTextNode(QString::number(yIP->value())));
QDomElement coordinateZElement = doc.createElement("Coord");
cartesianPointElement.appendChild(coordinateZElement);
coordinateZElement.appendChild(doc.createTextNode(QString::number(zIP->value())));
*/
QDomElement coordinateXElement = doc.createElement("Coord");
cartesianPointElement.appendChild(coordinateXElement);
coordinateXElement.appendChild(doc.createTextNode(QString::number(meterToFoot*vertex.x())));
QDomElement coordinateYElement = doc.createElement("Coord");
cartesianPointElement.appendChild(coordinateYElement);
coordinateYElement.appendChild(doc.createTextNode(QString::number(meterToFoot*vertex.y())));
QDomElement coordinateZElement = doc.createElement("Coord");
cartesianPointElement.appendChild(coordinateZElement);
coordinateZElement.appendChild(doc.createTextNode(QString::number(meterToFoot*vertex.z())));
}
return result;
}
boost::optional<QDomElement> ForwardTranslator::translateThermalZone(const openstudio::model::ThermalZone& thermalZone, QDomDocument& doc)
{
QDomElement result = doc.createElement("ThrmlZn");
m_translatedObjects[thermalZone.handle()] = result;
// Name
std::string name = thermalZone.name().get();
QDomElement nameElement = doc.createElement("Name");
result.appendChild(nameElement);
nameElement.appendChild(doc.createTextNode(escapeName(name)));
// Type
std::string type; // Conditioned, Unconditioned, Plenum
if(thermalZone.thermostatSetpointDualSetpoint()){
type = "Conditioned";
}else {
type = "Unconditioned";
}
QDomElement typeElement = doc.createElement("Type");
result.appendChild(typeElement);
typeElement.appendChild(doc.createTextNode(toQString(type)));
// DLM: Not input
// Mult
//QDomElement multElement = doc.createElement("Mult");
//result.appendChild(multElement);
//multElement.appendChild(doc.createTextNode(QString::number(thermalZone.multiplier())));
return result;
}
} // sdd
} // openstudio
| 45.117647 | 206 | 0.685518 | jasondegraw |
fa65151de53dd926e548e07a19e1297d0b23a005 | 277 | cpp | C++ | testcases/tests/t0004.cpp | Vindaar/vitanim | eb43b712247f1411e5a82c6fe6c29b84647c6549 | [
"MIT"
] | 12 | 2018-10-19T11:45:27.000Z | 2021-04-23T13:12:14.000Z | testcases/tests/t0004.cpp | Vindaar/vitanim | eb43b712247f1411e5a82c6fe6c29b84647c6549 | [
"MIT"
] | 4 | 2018-10-18T10:03:31.000Z | 2021-01-14T08:35:53.000Z | testcases/tests/t0004.cpp | Vindaar/vitanim | eb43b712247f1411e5a82c6fe6c29b84647c6549 | [
"MIT"
] | 4 | 2019-01-25T19:50:39.000Z | 2020-01-05T06:39:36.000Z | /*
KEY gdb brew
D20181203T110212:here [gdb still unusable on mojave · Issue #34750 · Homebrew/homebrew-core](https://github.com/Homebrew/homebrew-core/issues/34750)
*/
#include <iostream>
#include <stdio.h>
int main (int argc, char *argv[]) {
printf("ok1\n");
return 0;
}
| 23.083333 | 148 | 0.707581 | Vindaar |
fa65e1d6ba2cb4e1da46ac34a9ccdf2fe40bc9ce | 1,560 | cpp | C++ | ProjectEuler/Problems/problem076_100/Solution077.cpp | ankitdixit/code-gems | bdb30ba5c714f416dbf54d479d055458bde36085 | [
"MIT"
] | null | null | null | ProjectEuler/Problems/problem076_100/Solution077.cpp | ankitdixit/code-gems | bdb30ba5c714f416dbf54d479d055458bde36085 | [
"MIT"
] | null | null | null | ProjectEuler/Problems/problem076_100/Solution077.cpp | ankitdixit/code-gems | bdb30ba5c714f416dbf54d479d055458bde36085 | [
"MIT"
] | 2 | 2017-09-30T06:26:02.000Z | 2020-08-20T14:41:55.000Z | // https://projecteuler.net/problem=77
/*
It is possible to write ten as the sum of primes in exactly five different ways:
7 + 3
5 + 5
5 + 3 + 2
3 + 3 + 2 + 2
2 + 2 + 2 + 2 + 2
What is the first value which can be written as the sum of primes in over five
thousand different ways?
Solution:
Similar to coin change problem.
*/
#include <iostream>
#include <vector>
#include <chrono>
using namespace std;
using natural = unsigned;
const vector<natural> primes = {
2, 3, 5, 7, 11, 13, 17, 19, 23, 29,
31, 37, 41, 43, 47, 53, 59, 61, 67, 71
};
auto compute() {
constexpr size_t lim = 71;
const size_t p = primes.size();
vector<vector<natural>> table(lim + 1, vector<natural>(p, 0));
for (size_t i = primes.front(); i <= lim; ++i) {
natural ways = 0;
for (size_t j = 0; j < p; ++j) {
if (i == primes[j])
ways++;
else if (i > primes[j])
ways += table[i - primes[j]][j];
table[i][j] = ways;
}
}
return table.back().back();
}
template<typename Function, class ... Types>
decltype(auto) timeit(Function f, Types ... args) {
using namespace chrono;
auto start = high_resolution_clock::now();
auto result = f(args...);
double duration = duration_cast<nanoseconds>(high_resolution_clock::now() - start).count() / 1e6;
return std::make_pair(result, duration);
}
int main() {
using namespace std;
auto[result, time] = timeit(compute);
cout << result << " Calculated in " << time << " miliseconds." << '\n';
return 0;
} | 25.57377 | 101 | 0.595513 | ankitdixit |
fa66ba6e7918fcfcb32ecb01a4874e6642d2f517 | 924 | cpp | C++ | pypcode_emu/native/harness.cpp | jevinskie/pypcode-emu | 49d62090df9b25a7c4e35eee3532c3763f4e4286 | [
"MIT"
] | 13 | 2022-02-27T03:35:24.000Z | 2022-03-21T10:39:16.000Z | pypcode_emu/native/harness.cpp | jevinskie/pypcode-emu | 49d62090df9b25a7c4e35eee3532c3763f4e4286 | [
"MIT"
] | null | null | null | pypcode_emu/native/harness.cpp | jevinskie/pypcode-emu | 49d62090df9b25a7c4e35eee3532c3763f4e4286 | [
"MIT"
] | 1 | 2022-03-21T01:24:00.000Z | 2022-03-21T01:24:00.000Z | #undef NDEBUG
#include <cassert>
#include <sys/fcntl.h>
#include <sys/mman.h>
#include <sys/stat.h>
#include <unistd.h>
#include <fmt/format.h>
#include "lifted.h"
extern "C" double fpadd(double a, double b);
// 0x4000'0000'0000 makes asan happy
u8 *setup_mem(size_t size = 0x1'0000'0000, void *preferred_addr = (void *)0x4000'0000'0000) {
#if __has_feature(memory_sanitizer)
preferred_addr = nullptr;
#endif
u8 *mem = (u8 *)mmap(preferred_addr, size, PROT_READ | PROT_WRITE,
MAP_ANONYMOUS | MAP_PRIVATE | (preferred_addr ? MAP_FIXED : 0), -1, 0);
assert(mem);
assert((uintptr_t)mem != UINTPTR_MAX);
return mem;
}
u8 *mem;
regs_t regs;
int main(int argc, const char **argv) {
(void)argc;
(void)argv;
mem = setup_mem();
lifted_init(mem, ®s);
lifted_run(mem, ®s);
fmt::print("pc: {:#010x} res: {:#010x}\n", regs.pc, regs.r3);
return 0;
}
| 22.536585 | 96 | 0.640693 | jevinskie |
fa66dcee1c507681a3ee361e1656ddfef366c021 | 3,242 | cpp | C++ | graph-source-code/445-C/7033658.cpp | AmrARaouf/algorithm-detection | 59f3028d2298804870b32729415d71eec6116557 | [
"MIT"
] | null | null | null | graph-source-code/445-C/7033658.cpp | AmrARaouf/algorithm-detection | 59f3028d2298804870b32729415d71eec6116557 | [
"MIT"
] | null | null | null | graph-source-code/445-C/7033658.cpp | AmrARaouf/algorithm-detection | 59f3028d2298804870b32729415d71eec6116557 | [
"MIT"
] | null | null | null | //Language: GNU C++0x
#include <iostream>
#include <iomanip>
#include <cstdio>
#include <algorithm>
#include <cmath>
#include <vector>
#include <stack>
#include <queue>
#include <string>
#include <cstdlib>
#include <set>
#include <map>
#include <fstream>
#define PI 3.14159265359
using namespace std;
typedef unsigned long long ull;
template <typename T>
void print2dvector(vector< vector<T> > v)
{
cout << "A 2d vector:" << endl;
int a = v.size();
int b = v[0].size();
if (a <= 15 && b <= 15)
{
for (int i=0; i<a; i++)
{
for (int j=0; j<b; j++)
{
cout << setw(4) << v[i][j];
}
cout << endl;
}
}
if (a > 15 && b > 15)
{
for (int i=0; i<9; i++)
{
for (int j = 0; j<9; j++)
{
cout << setw(4) << v[i][j];
}
cout << " " << ". . ." << setw(4) << v[i][b-3] << setw(4) << v[i][b-2] << setw(4) << v[i][b-1] << endl;
}
for (int i=0; i<15; i++)
{
cout << setw(4) << '.';
}
cout << endl;
for (int i=a-3; i<a; i++)
{
for (int j = 0; j<9; j++)
{
cout << setw(4) << v[i][j];
}
cout << " " << ". . ." << setw(4) << v[i][b-3] << setw(4) << v[i][b-2] << setw(4) << v[i][b-1] << endl;
}
}
if (a>15)
{
for (int i=0; i<9; i++)
{
for (int j=0; j<b; j++)
{
cout << setw(4) << v[i][j];
}
cout << endl;
}
for (int i=0; i<b; i++)
{
cout << setw(4) << '.';
}
cout << endl;
for (int i=a-3; i<a; i++)
{
for (int j = 0; j<b; j++)
{
cout << setw(4) << v[i][j];
}
cout << endl;
}
}
if (b>15)
{
for (int i=0; i<a; i++)
{
for (int j = 0; j<9; j++)
{
cout << setw(4) << v[i][j];
}
cout << " " << ". . ." << setw(4) << v[i][b-3] << setw(4) << v[i][b-2] << setw(4) << v[i][b-1] << endl;
}
}
}
template <typename T>
void printvector(vector<T> v)
{
cout << "A 1d vector:" << endl;
int a = v.size();
if (a <= 15)
{
for (int i=0; i<a; i++)
{
cout << setw(4) << v[i];
}
}
else
{
for (int i=0; i<9; i++)
{
cout << setw(4) << v[i];
}
cout << " " << ". . ." << setw(4) << v[a-3] << setw(4) << v[a-2] << setw(4) << v[a-1];
}
cout << endl;
}
int main()
{
int n, m;
scanf("%d %d", &n, &m);
vector<int> v(n, 0);
for(int i=0; i<n; i++)
{
scanf("%d", &v[i]);
}
double ans = 0;
int a, b, c;
for(int i=0; i<m; i++)
{
scanf("%d %d %d", &a, &b, &c);
ans = max(ans, 1.0*(v[a-1]+v[b-1])/c);
}
printf("%.12lf", ans);
return 0;
}
| 20.389937 | 122 | 0.317705 | AmrARaouf |
fa66ff8686a2df747c40c10059c7e66939b348ba | 5,380 | cpp | C++ | lib/dataset/test/data_view_test.cpp | nvaytet/scipp | f14f56ed19cccb4162d55b1123df7225eeedb395 | [
"BSD-3-Clause"
] | 43 | 2019-04-08T14:13:11.000Z | 2022-02-08T06:09:35.000Z | lib/dataset/test/data_view_test.cpp | nvaytet/scipp | f14f56ed19cccb4162d55b1123df7225eeedb395 | [
"BSD-3-Clause"
] | 1,342 | 2019-03-30T07:06:08.000Z | 2022-03-28T13:12:47.000Z | lib/dataset/test/data_view_test.cpp | nvaytet/scipp | f14f56ed19cccb4162d55b1123df7225eeedb395 | [
"BSD-3-Clause"
] | 12 | 2019-06-13T08:56:12.000Z | 2021-11-04T08:24:18.000Z | // SPDX-License-Identifier: BSD-3-Clause
// Copyright (c) 2021 Scipp contributors (https://github.com/scipp)
#include <gtest/gtest.h>
#include <numeric>
#include "scipp/core/dimensions.h"
#include "scipp/dataset/dataset.h"
#include "dataset_test_common.h"
#include "test_macros.h"
using namespace scipp;
using namespace scipp::dataset;
// Using typed tests for common functionality of DataArrayView and
// DataArrayConstView.
template <typename T> class DataArrayViewTest : public ::testing::Test {
protected:
using dataset_type =
std::conditional_t<std::is_same_v<T, DataArray>, Dataset, const Dataset>;
};
using DataArrayViewTypes = ::testing::Types<DataArray, const DataArray>;
TYPED_TEST_SUITE(DataArrayViewTest, DataArrayViewTypes);
TYPED_TEST(DataArrayViewTest, name_ignored_in_comparison) {
const auto var = makeVariable<double>(Values{1.0});
Dataset d;
d.setData("a", var);
d.setData("b", var);
typename TestFixture::dataset_type &d_ref(d);
EXPECT_EQ(d_ref["a"], d_ref["b"]);
}
TYPED_TEST(DataArrayViewTest, dims) {
Dataset d;
const auto dense = makeVariable<double>(Dims{Dim::X, Dim::Y}, Shape{1, 2});
typename TestFixture::dataset_type &d_ref(d);
d.setData("dense", dense);
ASSERT_EQ(d_ref["dense"].dims(), dense.dims());
}
TYPED_TEST(DataArrayViewTest, dims_with_extra_coords) {
Dataset d;
typename TestFixture::dataset_type &d_ref(d);
const auto x = makeVariable<double>(Dims{Dim::X}, Shape{3}, Values{1, 2, 3});
const auto y = makeVariable<double>(Dims{Dim::Y}, Shape{3}, Values{4, 5, 6});
const auto var = makeVariable<double>(Dims{Dim::X}, Shape{3});
d.setCoord(Dim::X, x);
d.setCoord(Dim::Y, y);
d.setData("a", var);
ASSERT_EQ(d_ref["a"].dims(), var.dims());
}
TYPED_TEST(DataArrayViewTest, dtype) {
Dataset d = testdata::make_dataset_x();
typename TestFixture::dataset_type &d_ref(d);
EXPECT_EQ(d_ref["a"].dtype(), dtype<double>);
EXPECT_EQ(d_ref["b"].dtype(), dtype<int32_t>);
}
TYPED_TEST(DataArrayViewTest, unit) {
Dataset d = testdata::make_dataset_x();
typename TestFixture::dataset_type &d_ref(d);
EXPECT_EQ(d_ref["a"].unit(), units::kg);
EXPECT_EQ(d_ref["b"].unit(), units::s);
}
TYPED_TEST(DataArrayViewTest, coords) {
Dataset d;
const auto var = makeVariable<double>(Dims{Dim::X}, Shape{3});
d.setData("a", var);
d.coords().set(Dim::X, var);
typename TestFixture::dataset_type &d_ref(d);
ASSERT_NO_THROW(d_ref["a"].coords());
ASSERT_EQ(d_ref["a"].coords(), d.coords());
}
TYPED_TEST(DataArrayViewTest, coords_contains_only_relevant) {
Dataset d;
typename TestFixture::dataset_type &d_ref(d);
const auto x = makeVariable<double>(Dims{Dim::X}, Shape{3}, Values{1, 2, 3});
const auto y = makeVariable<double>(Dims{Dim::Y}, Shape{3}, Values{4, 5, 6});
const auto var = makeVariable<double>(Dims{Dim::X}, Shape{3});
d.setCoord(Dim::X, x);
d.setCoord(Dim::Y, y);
d.setData("a", var);
const auto coords = d_ref["a"].coords();
ASSERT_NE(coords, d.coords());
ASSERT_EQ(coords.size(), 1);
ASSERT_NO_THROW(coords[Dim::X]);
ASSERT_EQ(coords[Dim::X], x);
}
TYPED_TEST(DataArrayViewTest, coords_contains_only_relevant_2d_dropped) {
Dataset d;
typename TestFixture::dataset_type &d_ref(d);
const auto x = makeVariable<double>(Dims{Dim::X}, Shape{3}, Values{1, 2, 3});
const auto y = makeVariable<double>(Dims{Dim::Y, Dim::X}, Shape{3, 3});
const auto var = makeVariable<double>(Dims{Dim::X}, Shape{3});
d.setCoord(Dim::X, x);
d.setCoord(Dim::Y, y);
d.setData("a", var);
const auto coords = d_ref["a"].coords();
ASSERT_NE(coords, d.coords());
ASSERT_EQ(coords.size(), 1);
ASSERT_NO_THROW(coords[Dim::X]);
ASSERT_EQ(coords[Dim::X], x);
}
TYPED_TEST(DataArrayViewTest, coords_contains_only_relevant_2d) {
Dataset d;
typename TestFixture::dataset_type &d_ref(d);
const auto x = makeVariable<double>(Dims{Dim::Y, Dim::X}, Shape{3, 3});
const auto y = makeVariable<double>(Dims{Dim::Y}, Shape{3});
const auto var = makeVariable<double>(Dims{Dim::X}, Shape{3});
d.setCoord(Dim::X, x);
d.setCoord(Dim::Y, y);
d.setData("a", var);
const auto coords = d_ref["a"].coords();
// This is a very special case which is probably unlikely to occur in
// practice. If the coordinate depends on extra dimensions and the data is
// not, it implies that the coordinate cannot be for this data item, so it
// is dropped.
ASSERT_NE(coords, d.coords());
ASSERT_EQ(coords.size(), 0);
ASSERT_FALSE(coords.contains(Dim::X));
}
TYPED_TEST(DataArrayViewTest, hasVariances) {
Dataset d;
typename TestFixture::dataset_type &d_ref(d);
d.setData("a", makeVariable<double>(Values{double{}}));
d.setData("b", makeVariable<double>(Values{1}, Variances{1}));
ASSERT_FALSE(d_ref["a"].hasVariances());
ASSERT_TRUE(d_ref["b"].hasVariances());
}
TYPED_TEST(DataArrayViewTest, values_variances) {
Dataset d;
typename TestFixture::dataset_type &d_ref(d);
const auto var = makeVariable<double>(Dims{Dim::X}, Shape{2}, Values{1, 2},
Variances{3, 4});
d.setData("a", var);
ASSERT_EQ(d_ref["a"].data(), var);
ASSERT_TRUE(equals(d_ref["a"].template values<double>(), {1, 2}));
ASSERT_TRUE(equals(d_ref["a"].template variances<double>(), {3, 4}));
ASSERT_ANY_THROW(d_ref["a"].template values<float>());
ASSERT_ANY_THROW(d_ref["a"].template variances<float>());
}
| 33.836478 | 79 | 0.689963 | nvaytet |
fa683ca863337fa6fe4e4863ce755b62cf7830a8 | 567 | cc | C++ | matlab/mexfiles/GenerateAdmixedIndividuals_.cc | VasLem/SNPLIB | aea1cb943a7db22faa592a53cf1132561ce50c4e | [
"BSD-3-Clause"
] | 2 | 2019-11-21T04:55:13.000Z | 2021-10-05T18:01:23.000Z | matlab/mexfiles/GenerateAdmixedIndividuals_.cc | VasLem/SNPLIB | aea1cb943a7db22faa592a53cf1132561ce50c4e | [
"BSD-3-Clause"
] | null | null | null | matlab/mexfiles/GenerateAdmixedIndividuals_.cc | VasLem/SNPLIB | aea1cb943a7db22faa592a53cf1132561ce50c4e | [
"BSD-3-Clause"
] | 1 | 2022-02-17T17:20:24.000Z | 2022-02-17T17:20:24.000Z | #include "../../src/simulations.h"
#include "mex.h"
void mexFunction(int nlhs, mxArray *plhs[], int nrhs, const mxArray *prhs[]) {
auto *af = mxGetPr(prhs[0]);
auto num_snps = static_cast<size_t>(mxGetN(prhs[0]));
auto num_samples = static_cast<size_t>(mxGetScalar(prhs[1]));
auto num_bytes = num_samples / 4 + (num_samples % 4 > 0u ? 1 : 0);
plhs[0] = mxCreateNumericMatrix(num_bytes, num_snps, mxUINT8_CLASS, mxREAL);
auto *geno = reinterpret_cast<uint8_t *>(mxGetData(plhs[0]));
snplib::GenerateAdmixedIndividuals(af, num_snps, num_samples, geno);
} | 47.25 | 78 | 0.705467 | VasLem |
fa6b0f8ca1e8ca70fadd339abc1dab370544b02a | 17,099 | cpp | C++ | WRK-V1.2/csharp/sccomp/bitset.cpp | intj-t/openvmsft | 0d17fbce8607ab2b880be976c2e86d8cfc3e83bb | [
"Intel"
] | null | null | null | WRK-V1.2/csharp/sccomp/bitset.cpp | intj-t/openvmsft | 0d17fbce8607ab2b880be976c2e86d8cfc3e83bb | [
"Intel"
] | null | null | null | WRK-V1.2/csharp/sccomp/bitset.cpp | intj-t/openvmsft | 0d17fbce8607ab2b880be976c2e86d8cfc3e83bb | [
"Intel"
] | null | null | null | // ==++==
//
//
// Copyright (c) 2006 Microsoft Corporation. All rights reserved.
//
// The use and distribution terms for this software are contained in the file
// named license.txt, which can be found in the root of this distribution.
// By using this software in any fashion, you are agreeing to be bound by the
// terms of this license.
//
// You must not remove this notice, or any other, from this software.
//
//
// ==--==
// ===========================================================================
// File: bitset.cpp
//
// BitSet implementation
// ===========================================================================
#include "stdafx.h"
/***************************************************************************************************
Initialize the bitset to all zeros. Make sure there is room for cbit bits. Uses the given
heap to allocate a BitSetImp (if needed).
***************************************************************************************************/
void BitSet::Init(int cbit, NRHEAP * heap)
{
// cbit should be non-negative and shouldn't overflow.
ASSERT(0 <= cbit && 0 <= (cbit + kcbitBlob - 1));
if (cbit <= kcbitSmall)
m_bits = 1;
else {
// Allocate at least kcbitBlob more bits than kcbitSmall.
// Then we'll always grow by at least kcbitBlob.
if (cbit < kcbitSmall + kcbitBlob)
cbit = kcbitSmall + kcbitBlob;
int cblob = (int)((uint)(cbit + kcbitBlob - 1) / kcbitBlob);
int cbTot = cblob * sizeof(Blob) + sizeof(BitSetImp);
BitSetImp * pbsi = (BitSetImp *)heap->AllocZero(cbTot);
pbsi->cblob = cblob;
m_bits = (Blob)pbsi;
ASSERT(!FSmall());
}
}
/***************************************************************************************************
Grow the bitset to accomodate at least cbit bits. This preserves any existing bits.
***************************************************************************************************/
void BitSet::Grow(int cbit, NRHEAP * heap)
{
if (!m_bits)
Init(cbit, heap);
else if (Cbit() >= cbit)
VSFAIL("Why is Grow being called?");
else if (FSmall()) {
Blob blob = m_bits >> 1;
Init(cbit, heap);
ASSERT(cbit <= Cbit());
// Preserve the previous bits.
Pbsi()->rgblob[0] = blob;
}
else {
BitSetImp * pbsi = Pbsi();
Init(cbit, heap);
ASSERT(cbit <= Cbit());
// Preserve the previous bits.
memcpy(Pbsi()->rgblob, pbsi->rgblob, pbsi->cblob * sizeof(Blob));
}
}
/***************************************************************************************************
Return true iff the given bit is set. If ibit >= Cbit(), returns false.
***************************************************************************************************/
bool BitSet::TestBit(int ibit)
{
ASSERT(0 <= ibit);
if (!m_bits)
return false;
if (FSmall())
return ibit < kcbitSmall && ((m_bits >> (ibit + 1)) & 1);
BitSetImp * pbsi = Pbsi();
int iblob = (uint)ibit / kcbitBlob;
return iblob < pbsi->cblob && ((pbsi->rgblob[iblob] >> ((uint)ibit % kcbitBlob)) & 1);
}
/***************************************************************************************************
Return true iff all the bits in the range [ibitMin, ibitLim) are set. If ibitLim > Cbit(),
returns false. If ibitMin == ibitLim, returns true (vacuous).
***************************************************************************************************/
bool BitSet::TestAllRange(int ibitMin, int ibitLim)
{
ASSERT(0 <= ibitMin && ibitMin <= ibitLim);
if (ibitLim - ibitMin <= 1) {
if (ibitLim - ibitMin == 1)
return TestBit(ibitMin);
return true; // Vacuous
}
if (!m_bits)
return false;
if (FSmall()) {
if (ibitLim > kcbitSmall)
return false;
Blob blobMask = MaskSmall(ibitMin, ibitLim);
return (m_bits & blobMask) == blobMask;
}
MaskData md(ibitMin, ibitLim);
BitSetImp * pbsi = Pbsi();
if (md.iblobLast >= pbsi->cblob)
return false;
if ((pbsi->rgblob[md.iblobMin] & md.blobMaskMin) != md.blobMaskMin)
return false;
if (md.iblobMin >= md.iblobLast)
return true;
return (pbsi->rgblob[md.iblobLast] & md.blobMaskLast) == md.blobMaskLast &&
AreBitsOne(pbsi->rgblob + md.iblobMin + 1, md.iblobLast - md.iblobMin - 1);
}
/***************************************************************************************************
Returns true iff any bits in the range [ibitMin, ibitLim) are set.
***************************************************************************************************/
bool BitSet::TestAnyRange(int ibitMin, int ibitLim)
{
ASSERT(0 <= ibitMin && ibitMin <= ibitLim);
if (ibitLim - ibitMin <= 1) {
if (ibitLim - ibitMin == 1)
return TestBit(ibitMin);
return false;
}
if (!m_bits)
return false;
if (FSmall()) {
if (ibitMin >= kcbitSmall)
return false;
if (ibitLim > kcbitSmall)
ibitLim = kcbitSmall;
Blob blobMask = MaskSmall(ibitMin, ibitLim);
return (m_bits & blobMask) != 0;
}
MaskData md(ibitMin, ibitLim);
BitSetImp * pbsi = Pbsi();
if (md.iblobMin >= pbsi->cblob)
return false;
if ((pbsi->rgblob[md.iblobMin] & md.blobMaskMin) != 0)
return true;
if (md.iblobLast >= pbsi->cblob)
md.iblobLast = pbsi->cblob;
else if ((pbsi->rgblob[md.iblobLast] & md.blobMaskLast) != 0)
return true;
return !AreBitsZero(pbsi->rgblob + md.iblobMin + 1, md.iblobLast - md.iblobMin - 1);
}
/***************************************************************************************************
Returns true iff any bits in the range [0, infinity) are set.
***************************************************************************************************/
bool BitSet::TestAnyBits()
{
if (!m_bits)
return false;
if (FSmall())
return m_bits != 1;
BitSetImp * pbsi = Pbsi();
return !AreBitsZero(pbsi->rgblob, pbsi->cblob);
}
/***************************************************************************************************
Returns true iff there are any bits that are set in both this bitset and bsetCheck.
***************************************************************************************************/
bool BitSet::TestAnyBits(BitSet & bsetCheck)
{
if (!m_bits || !bsetCheck.m_bits)
return false;
if (FSmall()) {
if (bsetCheck.FSmall())
return (m_bits & bsetCheck.m_bits) != 1;
ASSERT(bsetCheck.Pbsi()->cblob > 0);
return (bsetCheck.Pbsi()->rgblob[0] & (m_bits >> 1)) != 0;
}
BitSetImp * pbsi1 = Pbsi();
ASSERT(pbsi1->cblob > 0);
if (bsetCheck.FSmall())
return (pbsi1->rgblob[0] & (bsetCheck.m_bits >> 1)) != 0;
BitSetImp * pbsi2 = bsetCheck.Pbsi();
ASSERT(pbsi2->cblob > 0);
for (int iblob = min(pbsi1->cblob, pbsi2->cblob); --iblob >= 0; ) {
if (pbsi1->rgblob[iblob] & pbsi2->rgblob[iblob])
return true;
}
return false;
}
/***************************************************************************************************
Sets the bit at position ibit, ensuring that the bitset is large enough.
***************************************************************************************************/
void BitSet::SetBit(int ibit, NRHEAP * heap)
{
// ibit should be non-negative and shouldn't overflow.
ASSERT(0 <= ibit && 0 <= (ibit + kcbitBlob - 1));
if (ibit >= Cbit())
Grow(ibit + 1, heap);
if (FSmall())
m_bits |= MaskSmall(ibit);
else {
BitSetImp * pbsi = Pbsi();
pbsi->rgblob[(uint)ibit / kcbitBlob] |= ((Blob)1 << ((uint)ibit % kcbitBlob));
}
}
/***************************************************************************************************
Clear all the bits in the bitset, but don't discard any memory allocated.
***************************************************************************************************/
void BitSet::ClearAll()
{
if (FSmall())
m_bits = 1;
else if (m_bits) {
BitSetImp * pbsi = Pbsi();
SetBlobs(pbsi->rgblob, pbsi->cblob, 0);
}
}
/***************************************************************************************************
Clear the given bit. If the bit is out of the range of the bitset, it is already considered
cleared, so nothing is changed.
***************************************************************************************************/
void BitSet::ClearBit(int ibit)
{
ASSERT(0 <= ibit);
if (FSmall()) {
if (ibit < kcbitSmall)
m_bits &= ~MaskSmall(ibit);
}
else if (m_bits) {
BitSetImp * pbsi = Pbsi();
int iblob = (uint)ibit / kcbitBlob;
if (iblob < pbsi->cblob)
pbsi->rgblob[iblob] &= ~((Blob)1 << ((uint)ibit % kcbitBlob));
}
}
/***************************************************************************************************
Set the range of bits [ibitMin, ibitLim), growing the bitset if needed.
***************************************************************************************************/
void BitSet::SetBitRange(int ibitMin, int ibitLim, NRHEAP * heap)
{
ASSERT(0 <= ibitMin && ibitMin <= ibitLim);
if (ibitLim - ibitMin <= 1) {
if (1 == ibitLim - ibitMin)
SetBit(ibitMin, heap);
return;
}
if (ibitLim > Cbit())
Grow(ibitLim, heap);
ASSERT(ibitLim <= Cbit());
if (FSmall()) {
m_bits |= MaskSmall(ibitMin, ibitLim);
return;
}
BitSetImp * pbsi = Pbsi();
MaskData md(ibitMin, ibitLim);
pbsi->rgblob[md.iblobMin] |= md.blobMaskMin;
if (md.iblobMin >= md.iblobLast)
return;
SetBlobs(pbsi->rgblob + md.iblobMin + 1, md.iblobLast - md.iblobMin - 1, ~(Blob)0);
pbsi->rgblob[md.iblobLast] |= md.blobMaskLast;
}
/***************************************************************************************************
Clear the range of bits [ibitMin, ibitLim).
***************************************************************************************************/
void BitSet::ClearBitRange(int ibitMin, int ibitLim)
{
ASSERT(0 <= ibitMin && ibitMin <= ibitLim);
int cbit = Cbit();
if (ibitLim > cbit)
ibitLim = cbit;
if (ibitMin >= ibitLim)
return;
ASSERT(0 <= ibitMin && ibitMin < ibitLim && ibitLim <= Cbit());
if (1 == ibitLim - ibitMin) {
ClearBit(ibitMin);
return;
}
if (FSmall()) {
m_bits &= ~MaskSmall(ibitMin, ibitLim);
return;
}
BitSetImp * pbsi = Pbsi();
MaskData md(ibitMin, ibitLim);
pbsi->rgblob[md.iblobMin] &= ~md.blobMaskMin;
if (md.iblobMin >= md.iblobLast)
return;
SetBlobs(pbsi->rgblob + md.iblobMin + 1, md.iblobLast - md.iblobMin - 1, 0);
pbsi->rgblob[md.iblobLast] &= ~md.blobMaskLast;
}
/***************************************************************************************************
Set the bitset to a copy of bset.
***************************************************************************************************/
void BitSet::Set(BitSet & bset, NRHEAP * heap)
{
ASSERT(this != &bset);
if (!bset.m_bits) {
ClearAll();
return;
}
int cbit = bset.Cbit();
if (Cbit() < cbit)
Init(cbit, heap);
if (FSmall()) {
ASSERT(bset.FSmall());
m_bits = bset.m_bits;
return;
}
BitSetImp * pbsiDst = Pbsi();
if (bset.FSmall()) {
pbsiDst->rgblob[0] = bset.m_bits >> 1;
SetBlobs(pbsiDst->rgblob + 1, pbsiDst->cblob - 1, 0);
return;
}
BitSetImp * pbsiSrc = bset.Pbsi();
ASSERT(pbsiDst->cblob >= pbsiSrc->cblob);
memcpy(pbsiDst->rgblob, pbsiSrc->rgblob, SizeMul(pbsiSrc->cblob, sizeof(Blob)));
if (pbsiDst->cblob > pbsiSrc->cblob)
SetBlobs(pbsiDst->rgblob + pbsiSrc->cblob, pbsiDst->cblob - pbsiSrc->cblob, 0);
}
/***************************************************************************************************
Return true iff this bitset contains the same set as bset.
***************************************************************************************************/
bool BitSet::Equals(BitSet & bset)
{
if (m_bits == bset.m_bits)
return true;
if (!m_bits)
return !bset.TestAnyBits();
if (!bset.m_bits)
return !TestAnyBits();
BitSetImp * pbsi;
if (FSmall()) {
if (bset.FSmall())
return false;
pbsi = bset.Pbsi();
return (pbsi->rgblob[0] == (m_bits >> 1)) &&
AreBitsZero(pbsi->rgblob + 1, pbsi->cblob - 1);
}
if (bset.FSmall()) {
pbsi = Pbsi();
return (pbsi->rgblob[0] == (bset.m_bits >> 1)) &&
AreBitsZero(pbsi->rgblob + 1, pbsi->cblob - 1);
}
pbsi = Pbsi();
BitSetImp * pbsi2 = bset.Pbsi();
int cblob = min(pbsi->cblob, pbsi2->cblob);
if (memcmp(pbsi->rgblob, pbsi2->rgblob, SizeMul(cblob, sizeof(Blob))))
return false;
if (pbsi->cblob == pbsi2->cblob)
return true;
if (cblob < pbsi->cblob)
return AreBitsZero(pbsi->rgblob + cblob, pbsi->cblob - cblob);
ASSERT(cblob < pbsi2->cblob);
return AreBitsZero(pbsi2->rgblob + cblob, pbsi2->cblob - cblob);
}
/***************************************************************************************************
Ensures that any bits that are set in bset are also set in this bitset.
***************************************************************************************************/
void BitSet::Union(BitSet & bset, NRHEAP * heap)
{
int cbitSrc = bset.Cbit();
if (!cbitSrc)
return;
if (Cbit() < cbitSrc)
Grow(cbitSrc, heap);
ASSERT(Cbit() >= cbitSrc);
if (FSmall()) {
ASSERT(bset.FSmall());
m_bits |= bset.m_bits;
}
else if (bset.FSmall())
Pbsi()->rgblob[0] |= bset.m_bits >> 1;
else {
BitSetImp * pbsiDst = Pbsi();
BitSetImp * pbsiSrc = bset.Pbsi();
for (int iblob = pbsiSrc->cblob; --iblob >= 0; )
pbsiDst->rgblob[iblob] |= pbsiSrc->rgblob[iblob];
}
}
/***************************************************************************************************
Ensures that any bits that are clear in bset are also clear in this bitset. Returns true iff
this bitset changes as a result (ie, if this bitset "shrunk").
***************************************************************************************************/
bool BitSet::FIntersectChanged(BitSet & bset)
{
BitSetImp * pbsiDst;
if (m_bits <= 1)
return false;
if (bset.m_bits <= 1) {
if (FSmall())
m_bits = 1;
else {
pbsiDst = Pbsi();
if (AreBitsZero(pbsiDst->rgblob, pbsiDst->cblob))
return false;
ClearAll();
}
return true;
}
if (FSmall()) {
Blob blob = bset.FSmall() ? bset.m_bits : ((bset.Pbsi()->rgblob[0] << 1) | 1);
return AndBlobChanged(m_bits, blob);
}
bool fChanged;
int cblob;
pbsiDst = Pbsi();
if (bset.FSmall()) {
fChanged = AndBlobChanged(pbsiDst->rgblob[0], bset.m_bits >> 1);
cblob = 1;
}
else {
BitSetImp * pbsiSrc = bset.Pbsi();
cblob = min(pbsiDst->cblob, pbsiSrc->cblob);
fChanged = false;
for (int iblob = cblob; --iblob >= 0; )
fChanged |= AndBlobChanged(pbsiDst->rgblob[iblob], pbsiSrc->rgblob[iblob]);
}
if (pbsiDst->cblob == cblob || AreBitsZero(pbsiDst->rgblob + cblob, pbsiDst->cblob - cblob))
return fChanged;
SetBlobs(pbsiDst->rgblob + cblob, pbsiDst->cblob - cblob, 0);
return true;
}
/***************************************************************************************************
Ensures that any bits that are clear in bset are also clear in this bitset.
***************************************************************************************************/
void BitSet::Intersect(BitSet & bset)
{
if (m_bits <= 1)
return;
if (bset.m_bits <= 1) {
ClearAll();
return;
}
if (FSmall()) {
Blob blob = bset.FSmall() ? bset.m_bits : ((bset.Pbsi()->rgblob[0] << 1) | 1);
m_bits &= blob;
return;
}
BitSetImp * pbsiDst = Pbsi();
int cblob;
if (bset.FSmall()) {
pbsiDst->rgblob[0] &= bset.m_bits >> 1;
cblob = 1;
}
else {
BitSetImp * pbsiSrc = bset.Pbsi();
cblob = min(pbsiDst->cblob, pbsiSrc->cblob);
for (int iblob = cblob; --iblob >= 0; )
pbsiDst->rgblob[iblob] &= pbsiSrc->rgblob[iblob];
}
if (pbsiDst->cblob > cblob)
SetBlobs(pbsiDst->rgblob + cblob, pbsiDst->cblob - cblob, 0);
}
| 32.140977 | 100 | 0.450494 | intj-t |
fa6bd5644e35a88353a7ad9f2729b6e6ce9d2b14 | 1,075 | cpp | C++ | third_party/WebKit/Source/platform/testing/FuzzedDataProvider.cpp | metux/chromium-deb | 3c08e9b89a1b6f95f103a61ff4f528dbcd57fc42 | [
"BSD-3-Clause-No-Nuclear-License-2014",
"BSD-3-Clause"
] | null | null | null | third_party/WebKit/Source/platform/testing/FuzzedDataProvider.cpp | metux/chromium-deb | 3c08e9b89a1b6f95f103a61ff4f528dbcd57fc42 | [
"BSD-3-Clause-No-Nuclear-License-2014",
"BSD-3-Clause"
] | null | null | null | third_party/WebKit/Source/platform/testing/FuzzedDataProvider.cpp | metux/chromium-deb | 3c08e9b89a1b6f95f103a61ff4f528dbcd57fc42 | [
"BSD-3-Clause-No-Nuclear-License-2014",
"BSD-3-Clause"
] | null | null | null | // Copyright 2016 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 "platform/testing/FuzzedDataProvider.h"
namespace blink {
FuzzedDataProvider::FuzzedDataProvider(const uint8_t* bytes, size_t num_bytes)
: provider_(bytes, num_bytes) {}
CString FuzzedDataProvider::ConsumeBytesInRange(uint32_t min_bytes,
uint32_t max_bytes) {
size_t num_bytes =
static_cast<size_t>(provider_.ConsumeUint32InRange(min_bytes, max_bytes));
std::string bytes = provider_.ConsumeBytes(num_bytes);
return CString(bytes.data(), bytes.size());
}
CString FuzzedDataProvider::ConsumeRemainingBytes() {
std::string bytes = provider_.ConsumeRemainingBytes();
return CString(bytes.data(), bytes.size());
}
bool FuzzedDataProvider::ConsumeBool() {
return provider_.ConsumeBool();
}
int FuzzedDataProvider::ConsumeInt32InRange(int min, int max) {
return provider_.ConsumeInt32InRange(min, max);
}
} // namespace blink
| 31.617647 | 80 | 0.733953 | metux |
fa6c012b93520ec881141c8547bc1337327463da | 3,633 | hpp | C++ | include/UnityEngine/U2D/SpriteAtlasManager.hpp | darknight1050/BeatSaber-Quest-Codegen | a6eeecc3f0e8f6079630f9a9a72b3121ac7b2032 | [
"Unlicense"
] | null | null | null | include/UnityEngine/U2D/SpriteAtlasManager.hpp | darknight1050/BeatSaber-Quest-Codegen | a6eeecc3f0e8f6079630f9a9a72b3121ac7b2032 | [
"Unlicense"
] | null | null | null | include/UnityEngine/U2D/SpriteAtlasManager.hpp | darknight1050/BeatSaber-Quest-Codegen | a6eeecc3f0e8f6079630f9a9a72b3121ac7b2032 | [
"Unlicense"
] | null | null | null | // Autogenerated from CppHeaderCreator
// Created by Sc2ad
// =========================================================================
#pragma once
// Begin includes
#include "extern/beatsaber-hook/shared/utils/typedefs.h"
// Completed includes
// Begin forward declares
// Forward declaring namespace: System
namespace System {
// Forward declaring type: Action`2<T1, T2>
template<typename T1, typename T2>
class Action_2;
// Forward declaring type: Action`1<T>
template<typename T>
class Action_1;
}
// Forward declaring namespace: UnityEngine::U2D
namespace UnityEngine::U2D {
// Forward declaring type: SpriteAtlas
class SpriteAtlas;
}
// Completed forward declares
// Type namespace: UnityEngine.U2D
namespace UnityEngine::U2D {
// Size: 0x10
#pragma pack(push, 1)
// Autogenerated type: UnityEngine.U2D.SpriteAtlasManager
// [NativeHeaderAttribute] Offset: D90E44
// [StaticAccessorAttribute] Offset: D90E44
// [NativeHeaderAttribute] Offset: D90E44
class SpriteAtlasManager : public ::Il2CppObject {
public:
// Creating value type constructor for type: SpriteAtlasManager
SpriteAtlasManager() noexcept {}
// [CompilerGeneratedAttribute] Offset: 0xD93EC8
// [DebuggerBrowsableAttribute] Offset: 0xD93EC8
// Get static field: static private System.Action`2<System.String,System.Action`1<UnityEngine.U2D.SpriteAtlas>> atlasRequested
static System::Action_2<::Il2CppString*, System::Action_1<UnityEngine::U2D::SpriteAtlas*>*>* _get_atlasRequested();
// Set static field: static private System.Action`2<System.String,System.Action`1<UnityEngine.U2D.SpriteAtlas>> atlasRequested
static void _set_atlasRequested(System::Action_2<::Il2CppString*, System::Action_1<UnityEngine::U2D::SpriteAtlas*>*>* value);
// [CompilerGeneratedAttribute] Offset: 0xD93F04
// [DebuggerBrowsableAttribute] Offset: 0xD93F04
// Get static field: static private System.Action`1<UnityEngine.U2D.SpriteAtlas> atlasRegistered
static System::Action_1<UnityEngine::U2D::SpriteAtlas*>* _get_atlasRegistered();
// Set static field: static private System.Action`1<UnityEngine.U2D.SpriteAtlas> atlasRegistered
static void _set_atlasRegistered(System::Action_1<UnityEngine::U2D::SpriteAtlas*>* value);
// static private System.Boolean RequestAtlas(System.String tag)
// Offset: 0x2306B98
static bool RequestAtlas(::Il2CppString* tag);
// static public System.Void add_atlasRegistered(System.Action`1<UnityEngine.U2D.SpriteAtlas> value)
// Offset: 0x2306C94
static void add_atlasRegistered(System::Action_1<UnityEngine::U2D::SpriteAtlas*>* value);
// static public System.Void remove_atlasRegistered(System.Action`1<UnityEngine.U2D.SpriteAtlas> value)
// Offset: 0x2306D84
static void remove_atlasRegistered(System::Action_1<UnityEngine::U2D::SpriteAtlas*>* value);
// static private System.Void PostRegisteredAtlas(UnityEngine.U2D.SpriteAtlas spriteAtlas)
// Offset: 0x2306E74
static void PostRegisteredAtlas(UnityEngine::U2D::SpriteAtlas* spriteAtlas);
// static System.Void Register(UnityEngine.U2D.SpriteAtlas spriteAtlas)
// Offset: 0x2306F00
static void Register(UnityEngine::U2D::SpriteAtlas* spriteAtlas);
// static private System.Void .cctor()
// Offset: 0x2306F40
static void _cctor();
}; // UnityEngine.U2D.SpriteAtlasManager
#pragma pack(pop)
}
#include "extern/beatsaber-hook/shared/utils/il2cpp-type-check.hpp"
DEFINE_IL2CPP_ARG_TYPE(UnityEngine::U2D::SpriteAtlasManager*, "UnityEngine.U2D", "SpriteAtlasManager");
| 51.169014 | 131 | 0.730526 | darknight1050 |
fa73bc930dbdce149f3b39567c17ef2558ba1e20 | 5,230 | cc | C++ | src/atlas/grid/detail/spacing/gaussian/N256.cc | mlange05/atlas | d8198435a9e39fbf67bfc467fe734203414af608 | [
"Apache-2.0"
] | null | null | null | src/atlas/grid/detail/spacing/gaussian/N256.cc | mlange05/atlas | d8198435a9e39fbf67bfc467fe734203414af608 | [
"Apache-2.0"
] | null | null | null | src/atlas/grid/detail/spacing/gaussian/N256.cc | mlange05/atlas | d8198435a9e39fbf67bfc467fe734203414af608 | [
"Apache-2.0"
] | null | null | null | // TL511
#include "atlas/grid/detail/spacing/gaussian/N.h"
namespace atlas {
namespace grid {
namespace spacing {
namespace gaussian {
DEFINE_GAUSSIAN_LATITUDES(
256, LIST( 89.731148618413, 89.382873896334, 89.032542423790, 88.681746243591, 88.330773788807, 87.979716034326,
87.628610609484, 87.277475867224, 86.926321817646, 86.575154382095, 86.223977286346, 85.872792991467,
85.521603188281, 85.170409076734, 84.819211531931, 84.468011207066, 84.116808599553, 83.765604094844,
83.414397996248, 83.063190545702, 82.711981938543, 82.360772334213, 82.009561864138, 81.658350637624,
81.307138746324, 80.955926267657, 80.604713267476, 80.253499802142, 79.902285920181, 79.551071663595,
79.199857068926, 78.848642168112, 78.497426989195, 78.146211556892, 77.794995893075, 77.443780017172,
77.092563946496, 76.741347696526, 76.390131281143, 76.038914712832, 75.687698002854, 75.336481161390,
74.985264197669, 74.634047120076, 74.282829936248, 73.931612653153, 73.580395277164, 73.229177814120,
72.877960269381, 72.526742647876, 72.175524954146, 71.824307192381, 71.473089366452, 71.121871479946,
70.770653536183, 70.419435538248, 70.068217489009, 69.716999391133, 69.365781247107, 69.014563059252,
68.663344829736, 68.312126560585, 67.960908253699, 67.609689910856, 67.258471533726, 66.907253123876,
66.556034682780, 66.204816211827, 65.853597712321, 65.502379185494, 65.151160632510, 64.799942054463,
64.448723452393, 64.097504827279, 63.746286180050, 63.395067511586, 63.043848822719, 62.692630114242,
62.341411386903, 61.990192641418, 61.638973878463, 61.287755098684, 60.936536302693, 60.585317491076,
60.234098664389, 59.882879823163, 59.531660967905, 59.180442099098, 58.829223217203, 58.478004322663,
58.126785415899, 57.775566497315, 57.424347567296, 57.073128626212, 56.721909674418, 56.370690712253,
56.019471740043, 55.668252758099, 55.317033766721, 54.965814766198, 54.614595756804, 54.263376738806,
53.912157712459, 53.560938678008, 53.209719635690, 52.858500585731, 52.507281528350, 52.156062463759,
51.804843392159, 51.453624313747, 51.102405228712, 50.751186137234, 50.399967039491, 50.048747935650,
49.697528825877, 49.346309710328, 48.995090589156, 48.643871462509, 48.292652330530, 47.941433193356,
47.590214051120, 47.238994903953, 46.887775751977, 46.536556595315, 46.185337434084, 45.834118268396,
45.482899098363, 45.131679924089, 44.780460745679, 44.429241563233, 44.078022376847, 43.726803186616,
43.375583992632, 43.024364794983, 42.673145593755, 42.321926389033, 41.970707180896, 41.619487969425,
41.268268754697, 40.917049536785, 40.565830315762, 40.214611091700, 39.863391864666, 39.512172634728,
39.160953401950, 38.809734166396, 38.458514928128, 38.107295687205, 37.756076443686, 37.404857197628,
37.053637949087, 36.702418698117, 36.351199444770, 35.999980189098, 35.648760931151, 35.297541670979,
34.946322408628, 34.595103144147, 34.243883877579, 33.892664608970, 33.541445338363, 33.190226065800,
32.839006791323, 32.487787514973, 32.136568236789, 31.785348956809, 31.434129675072, 31.082910391614,
30.731691106472, 30.380471819681, 30.029252531276, 29.678033241291, 29.326813949758, 28.975594656711,
28.624375362181, 28.273156066200, 27.921936768798, 27.570717470004, 27.219498169849, 26.868278868361,
26.517059565568, 26.165840261498, 25.814620956179, 25.463401649636, 25.112182341895, 24.760963032984,
24.409743722926, 24.058524411747, 23.707305099470, 23.356085786120, 23.004866471720, 22.653647156293,
22.302427839862, 21.951208522449, 21.599989204076, 21.248769884764, 20.897550564535, 20.546331243409,
20.195111921408, 19.843892598551, 19.492673274857, 19.141453950348, 18.790234625041, 18.439015298957,
18.087795972114, 17.736576644529, 17.385357316222, 17.034137987211, 16.682918657513, 16.331699327146,
15.980479996126, 15.629260664472, 15.278041332199, 14.926821999325, 14.575602665866, 14.224383331838,
13.873163997257, 13.521944662139, 13.170725326500, 12.819505990355, 12.468286653719, 12.117067316609,
11.765847979038, 11.414628641021, 11.063409302574, 10.712189963711, 10.360970624447, 10.009751284795,
9.658531944770, 9.307312604387, 8.956093263659, 8.604873922599, 8.253654581223, 7.902435239543,
7.551215897573, 7.199996555326, 6.848777212817, 6.497557870058, 6.146338527062, 5.795119183843,
5.443899840414, 5.092680496788, 4.741461152978, 4.390241808997, 4.039022464858, 3.687803120573,
3.336583776155, 2.985364431618, 2.634145086974, 2.282925742235, 1.931706397414, 1.580487052524,
1.229267707577, 0.878048362586, 0.526829017564, 0.175609672524 ) )
} // namespace gaussian
} // namespace spacing
} // namespace grid
} // namespace atlas
| 88.644068 | 116 | 0.7174 | mlange05 |
fa767dffcfd85faec8c76169b414c96c96c625ea | 28,938 | cpp | C++ | src/resolver/sleefResolver.cpp | sx-aurora-test/rv | 5d546958b155d7349b20a8cbbeff1b4c65589fd7 | [
"Apache-2.0"
] | null | null | null | src/resolver/sleefResolver.cpp | sx-aurora-test/rv | 5d546958b155d7349b20a8cbbeff1b4c65589fd7 | [
"Apache-2.0"
] | null | null | null | src/resolver/sleefResolver.cpp | sx-aurora-test/rv | 5d546958b155d7349b20a8cbbeff1b4c65589fd7 | [
"Apache-2.0"
] | null | null | null | //===- sleefLibrary.cpp -----------------------------===//
//
// The Region Vectorizer
//
// This file is distributed under the University of Illinois Open Source
// License. See LICENSE.TXT for details.
#include <llvm/Support/SourceMgr.h>
#include <llvm/IRReader/IRReader.h>
#include <llvm/Transforms/Utils/Cloning.h>
#include <llvm/IR/InstIterator.h>
#include <llvm/IR/Constants.h>
#include <llvm/IR/Module.h>
#include <llvm/IR/Dominators.h>
#include <llvm/Analysis/PostDominators.h>
#include <llvm/Analysis/LoopInfo.h>
#include <llvm/Analysis/ScalarEvolution.h>
#include <llvm/Analysis/MemoryDependenceAnalysis.h>
#include <llvm/Analysis/BranchProbabilityInfo.h>
#include <llvm/Passes/PassBuilder.h>
#include "llvm/Transforms/Utils/LCSSA.h"
#include "rv/PlatformInfo.h"
#include "utils/rvTools.h"
#include "utils/rvLinking.h"
#include "rvConfig.h"
#include "rv/rv.h"
#include "rv/utils.h"
#include "rv/region/FunctionRegion.h"
#include "rv/transform/singleReturnTrans.h"
#include "rv/transform/loopExitCanonicalizer.h"
#include "report.h"
#include <llvm/IR/Verifier.h>
#include <vector>
#include <sstream>
#if 1
#define IF_DEBUG_SLEEF IF_DEBUG
#else
#define IF_DEBUG_SLEEF if (true)
#endif
// used for on-demand mappings
//
using namespace llvm;
// vector-length agnostic
extern "C" {
#define EXTERNAL_GENBC_BUFFER(NAME) \
extern const unsigned char * NAME##_Buffer; \
extern const size_t NAME##_BufferLen;
#define EMPTY_GENBC_BUFFER(NAME) \
const unsigned char * NAME##_Buffer = nullptr; \
const size_t NAME##_BufferLen = 0;
#ifdef RV_ENABLE_SLEEF
EXTERNAL_GENBC_BUFFER(rempitab)
EXTERNAL_GENBC_BUFFER(vla_sp)
EXTERNAL_GENBC_BUFFER(vla_dp)
#else
EMPTY_GENBC_BUFFER(rempitab)
EMPTY_GENBC_BUFFER(vla_sp)
EMPTY_GENBC_BUFFER(vla_dp)
#endif
#ifdef RV_ENABLE_ADVSIMD
EXTERNAL_GENBC_BUFFER(advsimd_extras)
EXTERNAL_GENBC_BUFFER(advsimd_sp)
EXTERNAL_GENBC_BUFFER(advsimd_dp)
#else
EMPTY_GENBC_BUFFER(advsimd_extras)
EMPTY_GENBC_BUFFER(advsimd_sp)
EMPTY_GENBC_BUFFER(advsimd_dp)
#endif
#ifdef RV_ENABLE_X86
EXTERNAL_GENBC_BUFFER(avx512_extras)
EXTERNAL_GENBC_BUFFER(avx512_sp)
EXTERNAL_GENBC_BUFFER(avx512_dp)
EXTERNAL_GENBC_BUFFER(avx2_extras)
EXTERNAL_GENBC_BUFFER(avx2_sp)
EXTERNAL_GENBC_BUFFER(avx2_dp)
EXTERNAL_GENBC_BUFFER(avx_sp)
EXTERNAL_GENBC_BUFFER(avx_dp)
EXTERNAL_GENBC_BUFFER(sse_sp)
EXTERNAL_GENBC_BUFFER(sse_dp)
#else
EMPTY_GENBC_BUFFER(avx512_extras)
EMPTY_GENBC_BUFFER(avx512_sp)
EMPTY_GENBC_BUFFER(avx512_dp)
EMPTY_GENBC_BUFFER(avx2_extras)
EMPTY_GENBC_BUFFER(avx2_sp)
EMPTY_GENBC_BUFFER(avx2_dp)
EMPTY_GENBC_BUFFER(avx_sp)
EMPTY_GENBC_BUFFER(avx_dp)
EMPTY_GENBC_BUFFER(sse_sp)
EMPTY_GENBC_BUFFER(sse_dp)
#endif
} // extern "C"
#undef EMPTY_GENBC_BUFFER
#undef EXTERNAL_GENBC_BUFFER
namespace rv {
// internal structures for named mappings (without fancily shaped arguments)
struct PlainVecDesc {
std::string scalarFnName;
std::string vectorFnName;
int vectorWidth;
PlainVecDesc(std::string _scalarName, std::string _vectorName, int _width)
: scalarFnName(_scalarName), vectorFnName(_vectorName), vectorWidth(_width)
{}
PlainVecDesc()
: scalarFnName()
, vectorFnName()
, vectorWidth(0)
{}
};
using PlainVecDescVector = std::vector<PlainVecDesc>;
using AddToListFuncType = std::function<void(const PlainVecDescVector&, bool)>;
enum SleefISA {
SLEEF_VLA = 0,
SLEEF_SSE = 1,
SLEEF_AVX = 2,
SLEEF_AVX2 = 3,
SLEEF_AVX512 = 4,
SLEEF_ADVSIMD = 5,
SLEEF_Enum_Entries = 6
};
inline int sleefModuleIndex(SleefISA isa, bool doublePrecision) {
return int(isa) + (doublePrecision ? (int) SLEEF_Enum_Entries : 0);
}
static const size_t sleefModuleBufferLens[] = {
vla_sp_BufferLen,
sse_sp_BufferLen,
avx_sp_BufferLen,
avx2_sp_BufferLen,
avx512_sp_BufferLen,
advsimd_sp_BufferLen,
vla_dp_BufferLen,
sse_dp_BufferLen,
avx_dp_BufferLen,
avx2_dp_BufferLen,
avx512_dp_BufferLen,
advsimd_dp_BufferLen,
};
static const unsigned char** sleefModuleBuffers[] = {
&vla_sp_Buffer,
&sse_sp_Buffer,
&avx_sp_Buffer,
&avx2_sp_Buffer,
&avx512_sp_Buffer,
&advsimd_sp_Buffer,
&vla_dp_Buffer,
&sse_dp_Buffer,
&avx_dp_Buffer,
&avx2_dp_Buffer,
&avx512_dp_Buffer,
&advsimd_dp_Buffer,
};
static const size_t extraModuleBufferLens[] = {
0, // VLA
0, // SSE
0, // AVX
avx2_extras_BufferLen,
avx512_extras_BufferLen,
advsimd_extras_BufferLen,
};
static const unsigned char** extraModuleBuffers[] = {
nullptr, // VLA
nullptr, // SSE
nullptr, // AVX
&avx2_extras_Buffer,
&avx512_extras_Buffer,
&advsimd_extras_Buffer,
};
static Module *sleefModules[SLEEF_Enum_Entries * 2];
static Module *extraModules[SLEEF_Enum_Entries * 2];
static Module &requestSharedModule(LLVMContext &Ctx) {
static Module *SharedModule = nullptr;
if (!SharedModule)
SharedModule =
createModuleFromBuffer(reinterpret_cast<const char *>(&rempitab_Buffer),
rempitab_BufferLen, Ctx);
assert(SharedModule);
return *SharedModule;
}
const LinkerCallback SharedModuleLookup = [](GlobalValue& GV, Module& M) -> Value * {
IF_DEBUG_SLEEF {
errs() << "SharedModuleLookup: " << GV.getName() << "\n";
}
// Definition available
if (!GV.isDeclaration())
return &GV;
// Ignore intrinsic decls
auto *F = dyn_cast<Function>(&GV);
if (F && F->getIntrinsicID() != Intrinsic::not_intrinsic)
return nullptr;
// Lookup symbol in shared 'rempitab' module
auto &SharedMod = requestSharedModule(M.getContext());
auto *SharedGV = SharedMod.getNamedValue(GV.getName());
// N/a in the shared module -> back to the original source.
if (!SharedGV)
return nullptr;
IF_DEBUG_SLEEF {
errs() << "Pulling shared global: " << SharedGV->getName() << "\n";
}
// Don't recurse into lookup
GlobalVariable * ClonedGV = cast<GlobalVariable>(&cloneGlobalIntoModule(*SharedGV, M, nullptr));
// Uniquify the 'rempitab' constant globals.
ClonedGV->setLinkage(GlobalVariable::LinkOnceODRLinkage);
return ClonedGV;
};
static
void
InitSleefMappings(PlainVecDescVector & archMappings, int floatWidth, int doubleWidth) {
PlainVecDescVector VecFuncs = {
{"ilogbf", "xilogbf", floatWidth},
{"fmaf", "xfmaf", floatWidth},
{"fabsf", "xfabsf", floatWidth},
{"copysignf", "xcopysignf", floatWidth},
{"fmaxf", "xfmaxf", floatWidth},
{"fminf", "xfminf", floatWidth},
{"fdimf", "xfdimf", floatWidth},
{"truncf", "xtruncf", floatWidth},
{"floorf", "xfloorf", floatWidth},
{"ceilf", "xceilf", floatWidth},
{"roundf", "xroundf", floatWidth},
{"rintf", "xrintf", floatWidth},
{"nextafterf", "xnextafterf", floatWidth},
{"frfrexpf", "xfrfrexpf", floatWidth},
{"expfrexpf", "xexpfrexpf", floatWidth},
{"fmodf", "xfmodf", floatWidth},
{"modff", "xmodff", floatWidth},
{"ilogb", "xilogb", doubleWidth},
{"fma", "xfma", doubleWidth},
{"fabs", "xfabs", doubleWidth},
{"copysign", "xcopysign", doubleWidth},
{"fmax", "xfmax", doubleWidth},
{"fmin", "xfmin", doubleWidth},
{"fdim", "xfdim", doubleWidth},
{"trunc", "xtrunc", doubleWidth},
{"floor", "xfloor", doubleWidth},
{"ceil", "xceil", doubleWidth},
{"round", "xround", doubleWidth},
{"rint", "xrint", doubleWidth},
{"nextafter", "xnextafter", doubleWidth},
{"frfrexp", "xfrfrexp", doubleWidth},
{"expfrexp", "xexpfrexp", doubleWidth},
{"fmod", "xfmod", doubleWidth},
{"modf", "xmodf", floatWidth},
{"llvm.floor.f32", "xfloorf", floatWidth},
{"llvm.fabs.f32", "xfabsf", floatWidth},
{"llvm.copysign.f32", "xcopysignf", floatWidth},
{"llvm.minnum.f32", "xfminf", floatWidth},
{"llvm.maxnum.f32", "xfmaxf", floatWidth},
{"llvm.floor.f64", "xfloor", doubleWidth},
{"llvm.fabs.f64", "xfabs", doubleWidth},
{"llvm.copysign.f64", "xcopysign", doubleWidth},
{"llvm.minnum.f64", "xfmin", doubleWidth},
{"llvm.maxnum.f64", "xfmax", doubleWidth},
#if 0
// TODO VLA random number generator
// extras
{"drand48", "vrand_extra_vla", 2},
{"frand48", "vrand_extra_vla", 4}
#endif
#define ALSO_FINITE(IRNAME, SLEEFNAME, WIDTH) \
{#IRNAME, #SLEEFNAME, WIDTH}, \
{"__" #IRNAME "_finite", #SLEEFNAME, floatWidth}
#define ALSO_FINITE_ULP(IRNAME, ULP, SLEEFNAME, WIDTH) \
{#IRNAME, #SLEEFNAME, WIDTH}, \
{"__" #IRNAME "_" #ULP "_finite", #SLEEFNAME, floatWidth}
// EXPORT CONST vfloat __atan2f_finite (vfloat, vfloat) __attribute__((weak, alias(str_xatan2f_u1 )));
// EXPORT CONST vfloat __fmodf_finite (vfloat, vfloat) __attribute__((weak, alias(str_xfmodf )));
// EXPORT CONST vfloat __modff_finite (vfloat, vfloat *) __attribute__((weak, alias(str_xmodff )));
// EXPORT CONST vfloat __hypotf_u05_finite(vfloat, vfloat) __attribute__((weak, alias(str_xhypotf_u05)));
// TODO: Auto-generate this from some API header/description file.
ALSO_FINITE(acosf,xacosf, floatWidth),
ALSO_FINITE(acoshf,xacoshf, floatWidth),
ALSO_FINITE(acoshf,xacoshf,floatWidth),
ALSO_FINITE(asinf,xasinf, floatWidth),
ALSO_FINITE(asinhf, xasinhf, floatWidth),
ALSO_FINITE(atan2f,xatan2f, floatWidth),
ALSO_FINITE(atanf,xatanf, floatWidth),
ALSO_FINITE(atanhf,xatanhf,floatWidth),
ALSO_FINITE(cbrtf,xcbrtf, floatWidth),
ALSO_FINITE(cosf,xcosf, floatWidth),
ALSO_FINITE(coshf, xcoshf, floatWidth),
ALSO_FINITE(erfcf,xerfcf, floatWidth),
ALSO_FINITE(erff,xerff, floatWidth),
ALSO_FINITE(exp10f,xexp10f, floatWidth),
ALSO_FINITE(exp2f,xexp2f, floatWidth),
ALSO_FINITE(expf,xexpf,floatWidth),
ALSO_FINITE(expm1f,xexpm1f, floatWidth),
ALSO_FINITE(log10f,xlog10f,floatWidth),
ALSO_FINITE(log1pf,xlog1pf,floatWidth),
ALSO_FINITE(logf,xlogf, floatWidth),
ALSO_FINITE(powf,xpowf,floatWidth),
ALSO_FINITE(sinf,xsinf, floatWidth),
ALSO_FINITE(sinhf,xsinhf, floatWidth),
ALSO_FINITE(sqrtf,xsqrtf,floatWidth),
ALSO_FINITE(tanf,xtanf, floatWidth),
ALSO_FINITE(tanhf, xtanhf, floatWidth),
ALSO_FINITE_ULP(hypotf,u05,xhypotf,floatWidth),
ALSO_FINITE_ULP(lgammaf,u1,xlgammaf, floatWidth),
ALSO_FINITE_ULP(tgammaf,u1,xtgammaf, floatWidth),
#undef ALSO_FINITE
#undef ALSO_FINITE_ULP
{"sin", "xsin", doubleWidth},
{"cos", "xcos", doubleWidth},
{"tan", "xtan", doubleWidth},
{"asin", "xasin", doubleWidth},
{"acos", "xacos", doubleWidth},
{"atan", "xatan", doubleWidth},
{"atan2", "xatan2", doubleWidth},
{"log", "xlog", doubleWidth},
{"cbrt", "xcbrt", doubleWidth},
{"exp", "xexp", doubleWidth},
{"pow", "xpow", doubleWidth},
{"sinh", "xsinh", doubleWidth},
{"cosh", "xcosh", doubleWidth},
{"tanh", "xtanh", doubleWidth},
{"asinh", "xasinh", doubleWidth},
{"acosh", "xacosh", doubleWidth},
{"atanh", "xatanh", doubleWidth},
{"exp2", "xexp2", doubleWidth},
{"exp10", "xexp10", doubleWidth},
{"expm1", "xexpm1", doubleWidth},
{"log10", "xlog10", doubleWidth},
{"log1p", "xlog1p", doubleWidth},
{"sqrt", "xsqrt", doubleWidth},
{"hypot", "xhypot", doubleWidth},
{"lgamma", "xlgamma", doubleWidth},
{"tgamma", "xtgamma", doubleWidth},
{"erf", "xerf", doubleWidth},
{"erfc", "xerfc", doubleWidth},
{"llvm.sin.f32", "xsinf", floatWidth},
{"llvm.cos.f32", "xcosf", floatWidth},
{"llvm.log.f32", "xlogf", floatWidth},
{"llvm.exp.f32", "xexpf", floatWidth},
{"llvm.pow.f32", "xpowf", floatWidth},
{"llvm.sqrt.f32", "xsqrtf", floatWidth},
{"llvm.exp2.f32", "xexp2f", floatWidth},
{"llvm.log10.f32", "xlog10f", floatWidth},
{"llvm.sin.f64", "xsin", doubleWidth},
{"llvm.cos.f64", "xcos", doubleWidth},
{"llvm.log.f64", "xlog", doubleWidth},
{"llvm.exp.f64", "xexp", doubleWidth},
{"llvm.pow.f64", "xpow", doubleWidth},
{"llvm.sqrt.f64", "xsqrt", doubleWidth},
{"llvm.exp2.f64", "xexp2", doubleWidth},
{"llvm.log10.f64", "xlog10", doubleWidth}
};
archMappings.insert(archMappings.end(), VecFuncs.begin(), VecFuncs.end());
}
class SleefResolverService : public ResolverService {
PlatformInfo & platInfo;
struct ArchFunctionList {
SleefISA isaIndex;
std::string archSuffix;
PlainVecDescVector commonVectorMappings;
void addNamedMappings(const PlainVecDescVector & funcs, bool givePrecedence) {
auto itInsert = givePrecedence ? commonVectorMappings.begin() : commonVectorMappings.end();
commonVectorMappings.insert(itInsert, funcs.begin(), funcs.end());
}
ArchFunctionList(SleefISA _isaIndex, std::string _archSuffix)
: isaIndex(_isaIndex)
, archSuffix(_archSuffix)
{}
};
std::vector<ArchFunctionList*> archLists;
Config config;
public:
void
print(llvm::raw_ostream & out) const override {
out << "SLEEFResolver:\n"
<< "\tarch order: ";
bool later = false;
for (const auto * archList : archLists) {
if (later) { out << ","; }
later = true;
out << archList->archSuffix;
}
}
SleefResolverService(PlatformInfo & _platInfo, const Config & _config)
: platInfo(_platInfo)
, config(_config)
{
// ARM
#ifdef RV_ENABLE_ADVSIMD
if (config.useADVSIMD) {
auto * advSimdArch = new ArchFunctionList(SleefISA::SLEEF_ADVSIMD, "advsimd");
InitSleefMappings(advSimdArch->commonVectorMappings, 4, 2);
archLists.push_back(advSimdArch);
}
#endif
// x86
#ifdef RV_ENABLE_X86
if (config.useAVX512) {
auto * avx512Arch = new ArchFunctionList(SleefISA::SLEEF_AVX512, "avx512");
InitSleefMappings(avx512Arch->commonVectorMappings, 16, 8);
archLists.push_back(avx512Arch);
}
if (config.useAVX2 || config.useAVX512) {
auto * avx2Arch = new ArchFunctionList(SleefISA::SLEEF_AVX2, "avx2");
InitSleefMappings(avx2Arch->commonVectorMappings, 8, 4);
archLists.push_back(avx2Arch);
}
if (config.useAVX) {
auto * avxArch = new ArchFunctionList(SleefISA::SLEEF_AVX, "avx");
InitSleefMappings(avxArch->commonVectorMappings, 8, 4);
archLists.push_back(avxArch);
}
if (config.useSSE || config.useAVX || config.useAVX2 || config.useAVX512) {
auto * sseArch = new ArchFunctionList(SleefISA::SLEEF_SSE, "sse");
InitSleefMappings(sseArch->commonVectorMappings, 4, 2);
archLists.push_back(sseArch);
}
#endif
// generic
// fall back to automatic vectorization of scalar implementations (baseline)
auto * vlaArch = new ArchFunctionList(SleefISA::SLEEF_VLA, "vla");
InitSleefMappings(vlaArch->commonVectorMappings, -1, -1);
vlaArch->commonVectorMappings.emplace_back("ldexpf", "xldexpf", -1);
vlaArch->commonVectorMappings.emplace_back("ldexp", "xldexp", -1);
archLists.push_back(vlaArch);
}
~SleefResolverService() {
for (auto * archList : archLists) delete archList;
}
std::unique_ptr<FunctionResolver> resolve(llvm::StringRef funcName, llvm::FunctionType & scaFuncTy, const VectorShapeVec & argShapes, int vectorWidth, bool hasPredicate, llvm::Module & destModule) override;
};
// simply links-in the pre-vectorized SLEEF function
class SleefLookupResolver : public FunctionResolver {
VectorShape resShape;
Function & vecFunc;
std::string destFuncName;
public:
SleefLookupResolver(Module & _targetModule, VectorShape resShape, Function & _vecFunc, std::string _destFuncName)
: FunctionResolver(_targetModule)
, resShape(resShape)
, vecFunc(_vecFunc)
, destFuncName(_destFuncName)
{}
CallPredicateMode getCallSitePredicateMode() override {
// FIXME this is not entirely true for vector math
return CallPredicateMode::SafeWithoutPredicate;
}
// mask position (if any)
int getMaskPos() override {
return -1; // FIXME vector math is unpredicated
}
llvm::Function&
requestVectorized() override {
auto * existingFunc = targetModule.getFunction(destFuncName);
if (existingFunc) {
return *existingFunc;
}
// Picks 'Sleef_rempitab' from the shared module.
Function &clonedVecFunc = cloneFunctionIntoModule(
vecFunc, targetModule, destFuncName, SharedModuleLookup);
clonedVecFunc.setDoesNotRecurse(); // SLEEF math does not recurse
return clonedVecFunc;
}
// result shape of function @funcName in target module @module
VectorShape requestResultShape() override { return resShape; }
};
// on-the-fly vectorizing resolver
struct SleefVLAResolver : public FunctionResolver {
VectorizerInterface vectorizer;
std::unique_ptr<VectorizationInfo> vecInfo;
Function & scaFunc;
Function * clonedFunc;
Function * vecFunc;
VectorShapeVec argShapes;
VectorShape resShape;
int vectorWidth;
std::string vecFuncName;
SleefVLAResolver(PlatformInfo & platInfo, std::string baseName, Config config, Function & _scaFunc, const VectorShapeVec & _argShapes, int _vectorWidth)
: FunctionResolver(platInfo.getModule())
, vectorizer(platInfo, config)
, vecInfo(nullptr)
, scaFunc(_scaFunc)
, clonedFunc(nullptr)
, vecFunc(nullptr)
, argShapes(_argShapes)
, resShape(VectorShape::undef())
, vectorWidth(_vectorWidth)
, vecFuncName(platInfo.createMangledVectorName(baseName, argShapes, vectorWidth, -1))
{
IF_DEBUG_SLEEF { errs() << "VLA: " << vecFuncName << "\n"; }
}
CallPredicateMode getCallSitePredicateMode() override {
// FIXME this is not entirely true for vector math
return CallPredicateMode::SafeWithoutPredicate;
}
// mask position (if any)
int getMaskPos() override {
return -1; // FIXME vector math is unpredicated
}
// materialized the vectorized function in the module @insertInto and returns a reference to it
llvm::Function& requestVectorized() override {
if (vecFunc) return *vecFunc;
vecFunc = targetModule.getFunction(vecFuncName);
if (vecFunc) return *vecFunc;
// FIXME this is a hacky workaround for sqrt
if (scaFunc.getName().startswith("xsqrt")) {
auto funcTy = scaFunc.getFunctionType();
auto vecTy = FixedVectorType::get(funcTy->getReturnType(), vectorWidth);
vecFunc = Intrinsic::getDeclaration(&targetModule, Intrinsic::sqrt, {vecTy});
return *vecFunc;
}
requestResultShape();
// prepare scalar copy for transforming
clonedFunc = &cloneFunctionIntoModule(
scaFunc, targetModule, vecFuncName + ".tmp", SharedModuleLookup);
assert(clonedFunc);
// create SIMD declaration
const int maskPos = -1; // TODO add support for masking
vecFunc = createVectorDeclaration(*clonedFunc, resShape, argShapes, vectorWidth, maskPos);
vecFunc->setName(vecFuncName);
// override with no-recurse flag (so we won't get guards in the vector code)
vecFunc->copyAttributesFrom(&scaFunc);
vecFunc->setDoesNotRecurse();
// Use fastest possible CC.
vecFunc->setCallingConv(CallingConv::Fast);
vecFunc->setLinkage(GlobalValue::LinkOnceAnyLinkage);
VectorMapping mapping(clonedFunc, vecFunc, vectorWidth, maskPos, resShape, argShapes, CallPredicateMode::SafeWithoutPredicate);
vectorizer.getPlatformInfo().addMapping(mapping); // prevent recursive vectorization
// set-up vecInfo
FunctionRegion funcWrapper(*clonedFunc);
Region funcRegion(funcWrapper);
VectorizationInfo vecInfo(funcRegion, mapping);
// unify returns (if necessary)
SingleReturnTrans::run(funcRegion);
// compute anlaysis results
PassBuilder PB;
FunctionAnalysisManager FAM;
PB.registerFunctionAnalyses(FAM);
// compute DT, PDT, LI
FAM.getResult<DominatorTreeAnalysis>(*clonedFunc);
FAM.getResult<PostDominatorTreeAnalysis>(*clonedFunc);
FAM.getResult<LoopAnalysis>(*clonedFunc);
FAM.getResult<ScalarEvolutionAnalysis>(*clonedFunc);
FAM.getResult<MemoryDependenceAnalysis>(*clonedFunc);
FAM.getResult<BranchProbabilityAnalysis>(*clonedFunc);
// re-establish LCSSA
FunctionPassManager FPM;
FPM.addPass<LCSSAPass>(LCSSAPass());
FPM.run(*clonedFunc, FAM);
// normalize loop exits (TODO make divLoopTrans work without this)
{
LoopInfo &LI = FAM.getResult<LoopAnalysis>(*clonedFunc);
LoopExitCanonicalizer canonicalizer(LI);
canonicalizer.canonicalize(*clonedFunc);
FAM.invalidate<DominatorTreeAnalysis>(*clonedFunc);
FAM.invalidate<PostDominatorTreeAnalysis>(*clonedFunc);
// invalidate & recompute LI
FAM.invalidate<LoopAnalysis>(*clonedFunc);
FAM.getResult<LoopAnalysis>(*clonedFunc);
}
// run pipeline
vectorizer.analyze(vecInfo, FAM);
vectorizer.linearize(vecInfo, FAM);
vectorizer.vectorize(vecInfo, FAM, nullptr);
vectorizer.finalize();
// discard temporary mapping
vectorizer.getPlatformInfo().forgetAllMappingsFor(*clonedFunc);
// can dispose of temporary function now
clonedFunc->eraseFromParent();
return *vecFunc;
}
// result shape of function @funcName in target module @module
VectorShape requestResultShape() override {
if (resShape.isDefined()) return resShape;
// TODO run VA
for (const auto & argShape : argShapes) {
if (!argShape.isUniform()) {
resShape = VectorShape::varying();
return resShape;
}
}
resShape = VectorShape::uni();
return resShape;
}
// whether this resolver can provide a vectorized version ofthis function
bool isVectorizable(const VectorShapeVec & argShapes, int vectorWidth) {
return true;
}
};
// used for shape-based call mappings
using VecMappingShortVec = llvm::SmallVector<VectorMapping, 4>;
using VectorFuncMap = std::map<const llvm::Function *, VecMappingShortVec*>;
// parse ULP error bound from mangled SLEEF name
static unsigned
ReadULPBound(StringRef sleefName) {
auto itStart = sleefName.find_last_of("_u");
if (itStart == StringRef::npos) return 0; // unspecified -> perfect rounding
StringRef ulpPart = sleefName.substr(itStart + 1);
// single digit ULP value
unsigned ulpBound;
if (ulpPart.size() == 1) {
ulpBound = 10 * (ulpPart[0] - '0');
// lsc is tenth of ULP
} else {
bool parseError = ulpPart.consumeInteger<unsigned>(10, ulpBound);
(void) parseError; assert(!parseError);
}
return ulpBound;
}
static Function*
GetLeastPreciseImpl(Module & mod, const std::string & funcPrefix, const unsigned maxULPBound) {
Function * currBest = nullptr;
unsigned bestBound = 0;
IF_DEBUG_SLEEF { errs() << "SLEEF: impl: " << funcPrefix << "\n"; }
for (auto & func : mod) {
if (func.isDeclaration()) continue;
if (!func.getName().startswith(funcPrefix)) continue;
// not a complete funcname match (ie "xlog" would otw match "xlog1p")
if ((func.getName().size() > funcPrefix.size()) &&
(func.getName()[funcPrefix.size()] != '_'))
{
continue;
}
IF_DEBUG_SLEEF { errs() << "\t candidate: " << func.getName() << "\n"; }
unsigned funcBound = ReadULPBound(func.getName());
// dismiss too imprecise functions
if (funcBound > maxULPBound) {
IF_DEBUG_SLEEF { errs() << "discard, ulp was: " << funcBound << "\n"; }
continue;
// accept functions with higher ULP error within maxUPLBound
} else if (!currBest || (funcBound > bestBound)) {
IF_DEBUG_SLEEF { errs() << "\tOK! " << func.getName() << " with ulp bound: " << funcBound << "\n"; }
bestBound = funcBound;
currBest = &func;
}
}
return currBest;
}
std::unique_ptr<FunctionResolver>
SleefResolverService::resolve(llvm::StringRef funcName, llvm::FunctionType & scaFuncTy, const VectorShapeVec & argShapes, int vectorWidth, bool hasPredicate, llvm::Module & destModule) {
IF_DEBUG_SLEEF { errs() << "SLEEFResolverService: " << funcName << " for width " << vectorWidth << "\n"; }
(void) hasPredicate; // FIXME use predicated versions
// Otw, start looking for a SIMD-ized implementation
ArchFunctionList * archList = nullptr;
PlainVecDesc funcDesc;
for (auto * candList : archLists) {
// query custom mappings with precedence
std::string funcNameStr = funcName.str();
for (const auto & vd : candList->commonVectorMappings) {
if (vd.scalarFnName == funcNameStr &&
((vd.vectorWidth <= 0) || (vd.vectorWidth == vectorWidth)))
{
funcDesc = vd;
archList = candList;
break;
}
};
if (archList) break;
}
IF_DEBUG_SLEEF { errs() << "\tsleef: n/a\n"; }
if (!archList) return nullptr;
// Make sure the shared module is available
auto & Ctx = destModule.getContext();
// decode bitwidth (for module lookup)
bool doublePrecision = false;
for (const auto * argTy : scaFuncTy.params()) {
doublePrecision |= argTy->isDoubleTy();
}
// remove the trailing isa specifier (_avx2/_avx/_sse/..)
SleefISA isa = archList->isaIndex;
std::string sleefName = funcDesc.vectorFnName;
// TODO factor out
bool isExtraFunc = funcDesc.vectorFnName.find("_extra") != std::string::npos;
if (isExtraFunc) {
int modIdx = (int) isa;
auto *& mod = extraModules[modIdx];
if (!mod) mod = createModuleFromBuffer(reinterpret_cast<const char*>(extraModuleBuffers[modIdx]), extraModuleBufferLens[modIdx], Ctx);
Function *vecFunc = mod->getFunction(sleefName);
assert(vecFunc && "mapped extra function not found in module!");
return std::make_unique<SleefLookupResolver>(destModule, /* RNG result */ VectorShape::varying(), *vecFunc, funcDesc.vectorFnName);
}
// Skip for fast builtin functions // FIXME should be in its own target-dependent resolver
if (StringRef(sleefName).startswith("xsqrt")) {
// "every" target has a sqrt instruction of sorts
auto vecTy = FixedVectorType::get(scaFuncTy.getReturnType(), vectorWidth);
auto vecFunc = Intrinsic::getDeclaration(&destModule, Intrinsic::sqrt, {vecTy});
// FIXME abusing the SleefLookupResolver to retrieve an existing declaration...
return std::make_unique<SleefLookupResolver>(destModule, VectorShape::varying(), *vecFunc, vecFunc->getName().str());
}
// Look in SLEEF module
auto modIndex = sleefModuleIndex(isa, doublePrecision);
llvm::Module*& mod = sleefModules[modIndex]; // TODO const Module
if (!mod) {
mod = createModuleFromBuffer(reinterpret_cast<const char*>(sleefModuleBuffers[modIndex]), sleefModuleBufferLens[modIndex], Ctx);
IF_DEBUG {
bool brokenMod = verifyModule(*mod, &errs());
if (brokenMod) abort();
}
}
if (isa == SLEEF_VLA) {
// on-the-fly vectorization module
Function *vlaFunc = GetLeastPreciseImpl(*mod, sleefName, config.maxULPErrorBound);
if (!vlaFunc) {
IF_DEBUG_SLEEF { errs() << "sleef: " << sleefName << " n/a with maxULPError: " << config.maxULPErrorBound << "\n"; }
return nullptr;
}
return std::make_unique<SleefVLAResolver>(platInfo, vlaFunc->getName().str(), config, *vlaFunc, argShapes, vectorWidth);
} else {
// these are pure functions
VectorShape resShape = VectorShape::uni();
for (const auto argShape : argShapes) {
if (!argShape.isUniform()) {
resShape = VectorShape::varying();
break;
}
}
// we'll have to link in the function
Function *vecFunc = GetLeastPreciseImpl(*mod, sleefName, config.maxULPErrorBound);
if (!vecFunc) {
IF_DEBUG_SLEEF { errs() << "sleef: " << sleefName << " n/a with maxULPError: " << config.maxULPErrorBound << "\n"; }
return nullptr;
}
std::string vecFuncName = vecFunc->getName().str() + "_" + archList->archSuffix;
return std::make_unique<SleefLookupResolver>(destModule, resShape, *vecFunc, vecFuncName);
}
}
void
addSleefResolver(const Config & config, PlatformInfo & platInfo) {
#ifdef RV_ENABLE_SLEEF
auto sleefRes = std::make_unique<SleefResolverService>(platInfo, config);
platInfo.addResolverService(std::move(sleefRes), false); // give precedence to VectorABI
#else
Report() << " build w/o SLEEF (tried to add SleefResolver)!\n";
#endif
}
} // namespace rv
| 33.33871 | 208 | 0.670952 | sx-aurora-test |
fa77c3022865e3f92693358145303215345ca6a1 | 631 | cpp | C++ | Vic2ToHoI4Tests/HoI4WorldTests/OperativeNames/OperativeNamesTests.cpp | gawquon/Vic2ToHoI4 | 8371cfb1fd57cf81d854077963135d8037e754eb | [
"MIT"
] | 25 | 2018-12-10T03:41:49.000Z | 2021-10-04T10:42:36.000Z | Vic2ToHoI4Tests/HoI4WorldTests/OperativeNames/OperativeNamesTests.cpp | gawquon/Vic2ToHoI4 | 8371cfb1fd57cf81d854077963135d8037e754eb | [
"MIT"
] | 739 | 2018-12-13T02:01:20.000Z | 2022-03-28T02:57:13.000Z | Vic2ToHoI4Tests/HoI4WorldTests/OperativeNames/OperativeNamesTests.cpp | Osariusz/Vic2ToHoI4 | 9738b52c7602b1fe187c3820660c58a8d010d87e | [
"MIT"
] | 43 | 2018-12-10T03:41:58.000Z | 2022-03-22T23:55:41.000Z | #include "HOI4World/OperativeNames/OperativeNames.h"
#include "HOI4World/OperativeNames/OperativeNamesFactory.h"
#include "gtest/gtest.h"
#include <sstream>
TEST(HoI4World_OperativeNames_OperativeNamesTests, OperativeNamesDefaultsToEmpty)
{
const auto operativeNames = HoI4::OperativeNames::Factory::getOperativeNames("bad_path");
ASSERT_TRUE(operativeNames->getOperativeNamesSets().empty());
}
TEST(HoI4World_OperativeNames_OperativeNamesTests, OperativeNamesCanBeAdded)
{
const auto operativeNames = HoI4::OperativeNames::Factory::getOperativeNames(".");
ASSERT_EQ(2, operativeNames->getOperativeNamesSets().size());
} | 30.047619 | 90 | 0.81775 | gawquon |
fa78add51b4e41dcc8b8ff9fc82ca69b143115e3 | 154 | cpp | C++ | stat.cpp | sagar-sam/codechef-solutions | ea414d17435f0cfbc84b0c6b172ead0b22f32a23 | [
"MIT"
] | null | null | null | stat.cpp | sagar-sam/codechef-solutions | ea414d17435f0cfbc84b0c6b172ead0b22f32a23 | [
"MIT"
] | null | null | null | stat.cpp | sagar-sam/codechef-solutions | ea414d17435f0cfbc84b0c6b172ead0b22f32a23 | [
"MIT"
] | null | null | null | #include <iostream>
using namespace std;
int main()
{
int t;
scanf("%d",&t);
while(t--)
{
int n;
scanf("%d",&n);
int i=0;
int j=n-1;
}
} | 9.058824 | 20 | 0.506494 | sagar-sam |
fa79764ed3fe4e562a1bf37035b400745cd61fd1 | 2,267 | cpp | C++ | BetaEngine/Comp/Lab1/Source/Level1.cpp | PowerUser64/dP-2 | 98e5edc2dca4ed629e2bbf222c5b764e166e7193 | [
"MIT"
] | null | null | null | BetaEngine/Comp/Lab1/Source/Level1.cpp | PowerUser64/dP-2 | 98e5edc2dca4ed629e2bbf222c5b764e166e7193 | [
"MIT"
] | null | null | null | BetaEngine/Comp/Lab1/Source/Level1.cpp | PowerUser64/dP-2 | 98e5edc2dca4ed629e2bbf222c5b764e166e7193 | [
"MIT"
] | null | null | null | #include "stdafx.h"
#include "Level1.h"
#include "MonkeyMovement.h"
using namespace Beta;
Level1::Level1() : Level("Leve1")
{
}
void Level1::Load()
{
// Create a sprite component and set its mesh and sprite source
textureMonkey = ResourceGetTexture("Monkey.png");
spriteSourceMonkey = std::make_shared<SpriteSource>(textureMonkey, "Monkey", 3, 5);
// animations
//"MonkeyWalk" (8 frames, starts from frame 0, frame duration of 0.15f seconds)
animationWalk = std::make_shared<Animation>("MonkeyWalk", spriteSourceMonkey, 8, 0, 0.01f);
//"MonkeyJump" (1 frame, starts from frame 9)
animationJump = std::make_shared<Animation>("MonkeyJump", spriteSourceMonkey, 1, 9, 0.0f);
//"MonkeyIdle" (1 frame, starts from frame 12)
animationIdle = std::make_shared<Animation>("MonkeyIdle", spriteSourceMonkey, 1, 12, 0.0f);
}
void Level1::Initialize()
{
std::cout << "Level1::Initialize" << std::endl;
// set bkgnd color
GraphicsEngine *graphix = EngineGetModule(GraphicsEngine);
graphix->SetBackgroundColor(Colors::Blue);
GetSpace()->GetObjectManager().AddObject(*CreateMonkey());
}
void Level1::Update(float dt)
{
UNREFERENCED_PARAMETER(dt);
Input *input = EngineGetModule(Input);
// If the user presses the '1' key, restart the current level
if (input->CheckTriggered('1'))
GetSpace()->RestartLevel();
}
void Level1::Shutdown()
{
std::cout << "Level1::Shutdown\n";
}
void Level1::Unload()
{
std::cout << "Level1::Unload\n";
}
Beta::GameObject *Level1::CreateMonkey(void)
{
GameObject *Monkey = new GameObject("Monkey");
Transform *transform = new Transform(0.0f, 0.0f);
transform->SetScale(Vector2D(2.0f, 2.0f));
Sprite *sprite = new Sprite();
sprite->SetColor(Colors::Green);
sprite->SetSpriteSource(spriteSourceMonkey);
Monkey->AddComponent(sprite);
Monkey->AddComponent(transform);
Animator *animator = new Animator();
Monkey->AddComponent(animator);
animator->AddAnimation(animationWalk);
animator->AddAnimation(animationJump);
animator->AddAnimation(animationIdle);
RigidBody *rigidBody = new RigidBody();
Monkey->AddComponent(rigidBody);
MonkeyMovement *movement = new MonkeyMovement();
Monkey->AddComponent(movement);
return Monkey;
}
| 27.987654 | 93 | 0.703573 | PowerUser64 |
fa79dd4dd51eb42bc905ff3a6089e66f0857fdd2 | 14,005 | cc | C++ | hybridse/examples/toydb/src/storage/table_test.cc | jasleon/OpenMLDB | 2f85d12cd8dadd3a1ec822e1f591632341f3b23f | [
"Apache-2.0"
] | 2,659 | 2021-06-07T12:59:15.000Z | 2022-03-30T15:29:37.000Z | hybridse/examples/toydb/src/storage/table_test.cc | jasleon/OpenMLDB | 2f85d12cd8dadd3a1ec822e1f591632341f3b23f | [
"Apache-2.0"
] | 1,396 | 2021-05-28T09:50:13.000Z | 2022-03-31T16:37:49.000Z | hybridse/examples/toydb/src/storage/table_test.cc | jasleon/OpenMLDB | 2f85d12cd8dadd3a1ec822e1f591632341f3b23f | [
"Apache-2.0"
] | 499 | 2021-05-31T07:36:48.000Z | 2022-03-31T15:10:12.000Z | /*
* Copyright 2021 4Paradigm
*
* 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 <sys/time.h>
#include <string>
#include "codec/fe_row_codec.h"
#include "gtest/gtest.h"
#include "storage/table_impl.h"
namespace hybridse {
namespace storage {
using codec::RowBuilder;
using codec::RowView;
class TableTest : public ::testing::Test {
public:
TableTest() {}
~TableTest() {}
};
TEST_F(TableTest, SingleIndexIterator) {
::hybridse::type::TableDef def;
::hybridse::type::ColumnDef* col = def.add_columns();
col->set_name("col1");
col->set_type(::hybridse::type::kVarchar);
col = def.add_columns();
col->set_name("col2");
col->set_type(::hybridse::type::kInt64);
col = def.add_columns();
col->set_name("col3");
col->set_type(::hybridse::type::kVarchar);
::hybridse::type::IndexDef* index = def.add_indexes();
index->set_name("index1");
index->add_first_keys("col1");
index->set_second_key("col2");
Table table(1, 1, def);
table.Init();
RowBuilder builder(def.columns());
uint32_t size = builder.CalTotalLength(10);
// test empty table
std::unique_ptr<TableIterator> iter = table.NewIterator("key2");
iter->SeekToFirst();
ASSERT_FALSE(iter->Valid());
std::string row;
row.resize(size);
builder.SetBuffer(reinterpret_cast<int8_t*>(&(row[0])), size);
builder.AppendString("key1", 4);
builder.AppendInt64(11);
builder.AppendString("value1", 6);
table.Put(row.c_str(), row.length());
row.clear();
row.resize(size);
builder.SetBuffer(reinterpret_cast<int8_t*>(&(row[0])), size);
builder.AppendString("key1", 4);
builder.AppendInt64(22);
builder.AppendString("value1", 6);
table.Put(row.c_str(), row.length());
row.clear();
row.resize(size);
builder.SetBuffer(reinterpret_cast<int8_t*>(&(row[0])), size);
builder.AppendString("key1", 4);
builder.AppendInt64(33);
builder.AppendString("value2", 6);
table.Put(row.c_str(), row.length());
row.clear();
row.resize(size);
builder.SetBuffer(reinterpret_cast<int8_t*>(&(row[0])), size);
builder.AppendString("key2", 4);
builder.AppendInt64(11);
builder.AppendString("value2", 6);
table.Put(row.c_str(), row.length());
row.clear();
row.resize(size);
builder.SetBuffer(reinterpret_cast<int8_t*>(&(row[0])), size);
builder.AppendString("key2", 4);
builder.AppendInt64(22);
builder.AppendString("value2", 6);
table.Put(row.c_str(), row.length());
// test NewIterator(key)
iter = table.NewIterator("key2");
int count = 0;
RowView view(def.columns());
iter->SeekToFirst();
ASSERT_TRUE(iter->Valid());
while (iter->Valid()) {
const char* ch = nullptr;
uint32_t length = 0;
view.GetValue(reinterpret_cast<const int8_t*>(iter->GetValue().data()),
2, &ch, &length);
ASSERT_STREQ("value2", std::string(ch, length).c_str());
iter->Next();
count++;
}
ASSERT_EQ(count, 2);
// test NewIterator(key)
iter = table.NewIterator("key2", "index1");
count = 0;
iter->SeekToFirst();
ASSERT_TRUE(iter->Valid());
while (iter->Valid()) {
const char* ch = nullptr;
uint32_t length = 0;
view.GetValue(reinterpret_cast<const int8_t*>(iter->GetValue().data()),
2, &ch, &length);
ASSERT_STREQ("value2", std::string(ch, length).c_str());
iter->Next();
count++;
}
ASSERT_EQ(count, 2);
// test NewTraverseIterator()
iter = table.NewTraverseIterator();
count = 0;
iter->SeekToFirst();
while (iter->Valid()) {
iter->Next();
count++;
}
ASSERT_EQ(count, 5);
// test NewTraverseIterator(index_name)
iter = table.NewTraverseIterator("index1");
count = 0;
iter->SeekToFirst();
while (iter->Valid()) {
iter->Next();
count++;
}
ASSERT_EQ(count, 5);
// test NewIterator(key, ts)
iter = table.NewIterator("key2", 30);
count = 0;
while (iter->Valid()) {
iter->Next();
count++;
}
ASSERT_EQ(count, 2);
iter = table.NewIterator("key2", 11);
count = 0;
while (iter->Valid()) {
iter->Next();
count++;
}
ASSERT_EQ(count, 1);
iter = table.NewIterator("key2", 0);
count = 0;
ASSERT_FALSE(iter->Valid());
// test NewTraverseIterator(index_name) with current Ts valid
iter = table.NewTraverseIterator("index1");
std::map<std::string, int32_t> key_counters;
iter->SeekToFirst();
// iterator 1st segment of pk key1
while (iter->CurrentTsValid()) {
iter->NextTs();
count++;
}
ASSERT_EQ(count, 3);
ASSERT_EQ(iter->GetPK().ToString(), "key1");
// iterator 2nd segment of pk key1
count = 0;
iter->NextTsInPks();
ASSERT_TRUE(iter->Valid());
ASSERT_TRUE(iter->CurrentTsValid());
while (iter->CurrentTsValid()) {
iter->NextTs();
count++;
}
ASSERT_EQ(count, 2);
ASSERT_EQ(iter->GetPK().ToString(), "key2");
}
TEST_F(TableTest, MultiIndexIterator) {
::hybridse::type::TableDef def;
::hybridse::type::ColumnDef* col = def.add_columns();
col->set_name("col1");
col->set_type(::hybridse::type::kVarchar);
col = def.add_columns();
col->set_name("col2");
col->set_type(::hybridse::type::kInt64);
col = def.add_columns();
col->set_name("col3");
col->set_type(::hybridse::type::kVarchar);
col = def.add_columns();
col->set_name("col4");
col->set_type(::hybridse::type::kInt64);
::hybridse::type::IndexDef* index = def.add_indexes();
index->set_name("index1");
index->add_first_keys("col1");
index->set_second_key("col2");
index = def.add_indexes();
index->set_name("index2");
index->add_first_keys("col3");
index->set_second_key("col4");
Table table(1, 1, def);
table.Init();
RowBuilder builder(def.columns());
uint32_t size = builder.CalTotalLength(10);
// test empty table
std::unique_ptr<TableIterator> iter = table.NewIterator("i1_k2");
iter->SeekToFirst();
ASSERT_FALSE(iter->Valid());
std::string row;
row.resize(size);
builder.SetBuffer(reinterpret_cast<int8_t*>(&(row[0])), size);
builder.AppendString("i1_k1", 5);
builder.AppendInt64(11);
builder.AppendString("i2_k1", 5);
builder.AppendInt64(21);
table.Put(row.c_str(), row.length());
row.clear();
row.resize(size);
builder.SetBuffer(reinterpret_cast<int8_t*>(&(row[0])), size);
builder.AppendString("i1_k1", 5);
builder.AppendInt64(1);
builder.AppendString("i2_k2", 5);
builder.AppendInt64(11);
table.Put(row.c_str(), row.length());
row.clear();
row.resize(size);
builder.SetBuffer(reinterpret_cast<int8_t*>(&(row[0])), size);
builder.AppendString("i1_k2", 5);
builder.AppendInt64(12);
builder.AppendString("i2_k1", 5);
builder.AppendInt64(22);
table.Put(row.c_str(), row.length());
row.clear();
row.resize(size);
builder.SetBuffer(reinterpret_cast<int8_t*>(&(row[0])), size);
builder.AppendString("i1_k1", 5);
builder.AppendInt64(2);
builder.AppendString("i2_k2", 5);
builder.AppendInt64(32);
table.Put(row.c_str(), row.length());
RowView view(def.columns());
// test NewIterator(key, index_name)
iter = table.NewIterator("i2_k2", "index2");
int count = 0;
iter->SeekToFirst();
ASSERT_TRUE(iter->Valid());
while (iter->Valid()) {
const char* ch = nullptr;
uint32_t length = 0;
view.GetValue(reinterpret_cast<const int8_t*>(iter->GetValue().data()),
0, &ch, &length);
ASSERT_STREQ("i1_k1", std::string(ch, length).c_str());
iter->Next();
count++;
}
ASSERT_EQ(count, 2);
iter = table.NewIterator("i1_k2", "index1");
count = 0;
iter->SeekToFirst();
while (iter->Valid()) {
const char* ch = nullptr;
uint32_t length = 0;
view.GetValue(reinterpret_cast<const int8_t*>(iter->GetValue().data()),
2, &ch, &length);
ASSERT_STREQ("i2_k1", std::string(ch, length).c_str());
iter->Next();
count++;
}
ASSERT_EQ(count, 1);
// test NewIterator(key)
iter = table.NewIterator("i1_k2");
count = 0;
iter->SeekToFirst();
while (iter->Valid()) {
const char* ch = nullptr;
uint32_t length = 0;
view.GetValue(reinterpret_cast<const int8_t*>(iter->GetValue().data()),
2, &ch, &length);
ASSERT_STREQ("i2_k1", std::string(ch, length).c_str());
iter->Next();
count++;
}
ASSERT_EQ(count, 1);
// test NewTraverseIterator()
count = 0;
iter = table.NewTraverseIterator();
iter->SeekToFirst();
while (iter->Valid()) {
iter->Next();
count++;
}
ASSERT_EQ(count, 4);
// test NewTraverseIterator(index_name)
count = 0;
iter = table.NewTraverseIterator("index1");
iter->SeekToFirst();
while (iter->Valid()) {
iter->Next();
count++;
}
ASSERT_EQ(count, 4);
// test NewTraverseIterator(index_name)
count = 0;
iter = table.NewTraverseIterator("index1");
iter->SeekToFirst();
ASSERT_EQ(iter->GetPK().ToString(), "i1_k2");
while (iter->CurrentTsValid()) {
iter->NextTs();
count++;
}
ASSERT_EQ(count, 1);
count = 0;
iter->NextTsInPks();
ASSERT_EQ(iter->GetPK().ToString(), "i1_k1");
while (iter->CurrentTsValid()) {
iter->NextTs();
count++;
}
ASSERT_EQ(count, 3);
// test NewIterator(key, ts)
iter = table.NewIterator("i1_k1", 30);
count = 0;
while (iter->Valid()) {
iter->Next();
count++;
}
ASSERT_EQ(count, 3);
iter = table.NewIterator("i1_k1", 2);
count = 0;
while (iter->Valid()) {
iter->Next();
count++;
}
ASSERT_EQ(count, 2);
iter = table.NewIterator("key2", 0);
count = 0;
ASSERT_FALSE(iter->Valid());
}
TEST_F(TableTest, FullTableTest) {
::hybridse::type::TableDef def;
::hybridse::type::ColumnDef* col = def.add_columns();
col->set_name("col1");
col->set_type(::hybridse::type::kVarchar);
col = def.add_columns();
col->set_name("col2");
col->set_type(::hybridse::type::kInt64);
col = def.add_columns();
col->set_name("col3");
col->set_type(::hybridse::type::kVarchar);
::hybridse::type::IndexDef* index = def.add_indexes();
index->set_name("index1");
index->add_first_keys("col1");
index->set_second_key("col2");
Table table(1, 1, def);
table.Init();
// test empty table
std::unique_ptr<TableIterator> iter = table.NewIterator("key2");
int count = 0;
RowView view(def.columns());
iter->SeekToFirst();
ASSERT_FALSE(iter->Valid());
// test full table
RowBuilder builder(def.columns());
uint32_t size = builder.CalTotalLength(14);
std::string row;
int entry_count = 1000;
char key[12];
char value[12];
for (int i = 0; i < entry_count; ++i) {
row.resize(size);
sprintf(key, "key%03d", i % 10); // NOLINT
sprintf(value, "value%03d", i % 100); // NOLINT
builder.SetBuffer(reinterpret_cast<int8_t*>(&(row[0])), size);
builder.AppendString(key, 6);
builder.AppendInt64(i % 10);
builder.AppendString(value, 8);
table.Put(row.c_str(), row.length());
}
iter = table.NewTraverseIterator();
iter->SeekToFirst();
count = 0;
while (iter->Valid()) {
iter->Next();
count++;
}
ASSERT_EQ(count, 1000);
}
TEST_F(TableTest, DecodeKeysAndTsTest) {
::hybridse::type::TableDef def;
::hybridse::type::ColumnDef* col = def.add_columns();
col->set_name("col1");
col->set_type(::hybridse::type::kVarchar);
col = def.add_columns();
col->set_name("col2");
col->set_type(::hybridse::type::kInt64);
col = def.add_columns();
col->set_name("col3");
col->set_type(::hybridse::type::kVarchar);
col = def.add_columns();
col->set_name("col4");
col->set_type(::hybridse::type::kInt64);
::hybridse::type::IndexDef* index = def.add_indexes();
index->set_name("index1");
index->add_first_keys("col1");
index->add_first_keys("col4");
index->set_second_key("col2");
Table table(1, 1, def);
table.Init();
RowBuilder builder(def.columns());
uint32_t size = builder.CalTotalLength(10);
// test empty table
std::unique_ptr<TableIterator> iter = table.NewIterator("i1_k2");
iter->SeekToFirst();
ASSERT_FALSE(iter->Valid());
std::string row;
{
row.resize(size);
builder.SetBuffer(reinterpret_cast<int8_t*>(&(row[0])), size);
builder.AppendString("i1_k1", 5);
builder.AppendInt64(11);
builder.AppendString("i2_k1", 5);
builder.AppendInt64(21);
}
auto index_map = table.GetIndexMap();
int64_t time = 1;
std::string key;
ASSERT_TRUE(table.DecodeKeysAndTs(index_map["index1"], row.c_str(),
row.length(), key, &time));
ASSERT_EQ("i1_k1|21", key);
ASSERT_EQ(11L, time);
}
} // namespace storage
} // namespace hybridse
int main(int argc, char** argv) {
::testing::InitGoogleTest(&argc, argv);
return RUN_ALL_TESTS();
}
| 29.422269 | 79 | 0.602713 | jasleon |
fa7c8e73799feb7707f1f90d68a0f5cfb6678d50 | 2,118 | hh | C++ | include/WCSimDetectorZone.hh | chipsneutrino/chips-sim | 19d3f2d75c674c06d2f27b9a344b70ca53e672c5 | [
"MIT"
] | null | null | null | include/WCSimDetectorZone.hh | chipsneutrino/chips-sim | 19d3f2d75c674c06d2f27b9a344b70ca53e672c5 | [
"MIT"
] | null | null | null | include/WCSimDetectorZone.hh | chipsneutrino/chips-sim | 19d3f2d75c674c06d2f27b9a344b70ca53e672c5 | [
"MIT"
] | null | null | null | /*
* WCSimDetectorZone.hh
*
* Created on: 24 Nov 2014
* Author: ajperch
*/
#pragma once
#include "G4ThreeVector.hh"
#include "WCSimGeometryEnums.hh"
#include <map>
#include <vector>
class WCSimDetectorZone
{
public:
WCSimDetectorZone();
virtual ~WCSimDetectorZone();
void AddCellPMTName(std::string name);
std::string GetCellPMTName(unsigned int pmt) const;
std::vector<std::string> GetCellPMTName() const;
void AddCellPMTX(double x);
double GetCellPMTX(unsigned int pmt) const;
std::vector<double> GetCellPMTX() const;
void AddCellPMTY(double y);
double GetCellPMTY(unsigned int pmt) const;
std::vector<double> GetCellPMTY() const;
void AddCellPMTFaceType(WCSimGeometryEnums::PMTDirection_t face);
WCSimGeometryEnums::PMTDirection_t GetCellPMTFaceType(unsigned int pmt) const;
std::vector<WCSimGeometryEnums::PMTDirection_t> GetCellPMTFaceType() const;
void AddCellPMTFaceTheta(double theta);
double GetCellPMTFaceTheta(unsigned int pmt) const;
std::vector<double> GetCellPMTFaceTheta() const;
void AddCellPMTFacePhi(double phi);
double GetCellPMTFacePhi(unsigned int pmt) const;
std::vector<double> GetCellPMTPhi() const;
void SetPMTLimit(std::string name, int limit);
int GetPMTLimit(std::string name) const;
int GetMaxNumCells() const;
bool IsGood(WCSimGeometryEnums::DetectorRegion_t region) const;
double GetCoverage() const
{
return fCoverage;
}
void SetCoverage(double coverage)
{
this->fCoverage = coverage;
}
void Print() const;
double GetThetaEnd() const
{
return fThetaEnd;
}
void SetThetaEnd(double thetaEnd)
{
this->fThetaEnd = thetaEnd;
}
double GetThetaStart() const
{
return fThetaStart;
}
void SetThetaStart(double thetaStart)
{
this->fThetaStart = thetaStart;
}
private:
double fCoverage;
std::vector<std::string> fCellPMTName;
std::map<std::string, int> fPMTLimit;
std::vector<double> fCellPMTX;
std::vector<double> fCellPMTY;
std::vector<WCSimGeometryEnums::PMTDirection_t> fDirectionType;
std::vector<double> fCellDirTheta;
std::vector<double> fCellDirPhi;
double fThetaStart;
double fThetaEnd;
};
| 21.612245 | 79 | 0.756374 | chipsneutrino |
fa7fee538418403a33c936d0a173b574b7a03de0 | 976 | cpp | C++ | examples/grover/general_grover.cpp | ausbin/qcor | e9e0624a0e14b1b980ce9265b71c9b394abc60a8 | [
"BSD-3-Clause"
] | 59 | 2019-08-22T18:40:38.000Z | 2022-03-09T04:12:42.000Z | examples/grover/general_grover.cpp | ausbin/qcor | e9e0624a0e14b1b980ce9265b71c9b394abc60a8 | [
"BSD-3-Clause"
] | 137 | 2019-09-13T15:50:18.000Z | 2021-12-06T14:19:46.000Z | examples/grover/general_grover.cpp | ausbin/qcor | e9e0624a0e14b1b980ce9265b71c9b394abc60a8 | [
"BSD-3-Clause"
] | 26 | 2019-07-08T17:30:35.000Z | 2021-12-03T16:24:12.000Z | using GroverPhaseOracle = KernelSignature<qreg>;
__qpu__ void reflect_about_uniform(qreg q) {
compute {
H(q);
X(q);
} action {
// we have N qubits, get the first N-1 as the
// ctrl qubits, and the last one for the
// ctrl-ctrl-...-ctrl-z operation qubit
auto ctrl_qubits = q.head(q.size()-1);
auto last_qubit = q.tail();
Z::ctrl(ctrl_qubits, last_qubit);
}
}
__qpu__ void run_grover(qreg q, GroverPhaseOracle oracle,
const int iterations) {
// Put them all in a superposition
H(q);
// Iteratively apply the oracle then reflect
for (int i = 0; i < iterations; i++) {
oracle(q);
reflect_about_uniform(q);
}
// Measure all qubits
Measure(q);
}
__qpu__ void oracle(qreg q) {
CZ(q[0], q[2]);
CZ(q[1], q[2]);
}
int main(int argc, char** argv) {
auto q = qalloc(3);
run_grover(q, oracle, 1);
for (auto [bits, count] : q.counts()) {
print(bits, ":", count);
}
}
| 22.181818 | 57 | 0.594262 | ausbin |
fa817f8b0dd229fd2d71bbcd788ff35c5df0a81d | 1,435 | cpp | C++ | WonderMake/Collision/ColliderDebug.cpp | nicolasgustafsson/WonderMake | 9661d5dab17cf98e06daf6ea77c5927db54d62f9 | [
"MIT"
] | 3 | 2020-03-27T15:25:19.000Z | 2022-01-18T14:12:25.000Z | WonderMake/Collision/ColliderDebug.cpp | nicolasgustafsson/WonderMake | 9661d5dab17cf98e06daf6ea77c5927db54d62f9 | [
"MIT"
] | null | null | null | WonderMake/Collision/ColliderDebug.cpp | nicolasgustafsson/WonderMake | 9661d5dab17cf98e06daf6ea77c5927db54d62f9 | [
"MIT"
] | null | null | null | #include "pch.h"
#include "ColliderDebug.h"
#include "Colliders.h"
void DrawSphere(const Colliders::SSphere& aCollider, const SColor& aColor)
{
constexpr u32 points = 16;
SVector2f positions[points];
for (u32 i = 0; i < points; ++i)
{
positions[i].X = std::cosf((Constants::Pi * 2.f) / points * i);
positions[i].Y = std::sinf((Constants::Pi * 2.f) / points * i);
positions[i] *= aCollider.Radius;
positions[i] += aCollider.Position;
}
SDebugLine line;
line.Color = aColor;
for (u32 i = 0; i < points - 1; ++i)
{
line.Start = positions[i];
line.End = positions[i + 1];
WmDrawDebugLine(line);
}
line.Start = positions[points - 1];
line.End = positions[0];
//WmDrawDebugLine(line);
}
void DrawLine(const Colliders::SCollisionLine& aCollider, const SColor& aColor)
{
SDebugLine line;
line.Color = aColor;
line.Start = aCollider.Position;
line.End = aCollider.GetLineEnd();
//WmDrawDebugLine(line);
}
void DrawCollider(const Colliders::Shape& aCollider, const SColor& aColor)
{
std::visit([aColor](const auto& aCollider)
{
using T = std::decay_t<decltype(aCollider)>;
if constexpr (std::is_same_v<T, Colliders::SSphere>)
{
DrawSphere(aCollider, aColor);
}
else if constexpr (std::is_same_v<T, Colliders::SCollisionLine>)
{
DrawLine(aCollider, aColor);
}
else
{
static_assert(std::false_type::value, "Collider not implemented!");
}
}, aCollider);
}
| 21.41791 | 79 | 0.667596 | nicolasgustafsson |
fa836b9da81e50a6e7a7fa097ac97bd5cb0c6bd4 | 11,001 | cpp | C++ | [Lib]__Engine/Sources/Common/profile.cpp | yexiuph/RanOnline | 7f7be07ef740c8e4cc9c7bef1790b8d099034114 | [
"Apache-2.0"
] | null | null | null | [Lib]__Engine/Sources/Common/profile.cpp | yexiuph/RanOnline | 7f7be07ef740c8e4cc9c7bef1790b8d099034114 | [
"Apache-2.0"
] | null | null | null | [Lib]__Engine/Sources/Common/profile.cpp | yexiuph/RanOnline | 7f7be07ef740c8e4cc9c7bef1790b8d099034114 | [
"Apache-2.0"
] | null | null | null | // "Portions Copyright (C) Steve Rabin, 2000"
// Edit by Jung DH, 2002.
//
#include "pch.h"
#include "./profile.h"
#include "./DebugSet.h"
#include "./DxInputDevice.h"
#ifdef _DEBUG
#define new DEBUG_NEW
#endif
CPROFILE g_profile_1;
CPROFILE g_profile_2;
BOOL g_bProfile = FALSE;
namespace
{
#define _HISTORY_RATE_ ( 5000.0f )
#define _GETCURTIME_ ( timeGetTime() )
#define _GETELAPSEDTIME_ ( (float)( m_endProfile - m_startProfile ) )
};
CPROFILE::CPROFILE ()
: m_startProfile(0)
, m_endProfile(0)
{
}
CPROFILE::~CPROFILE ()
{
}
void CPROFILE::Init (void)
{
unsigned int i;
for( i=0; i<NUM_PROFILE_SAMPLES; i++ )
{
m_samples[i].bValid = false;
m_history[i].bValid = false;
}
m_startProfile = _GETCURTIME_;
}
void CPROFILE::BlockStart ()
{
if ( m_startProfile==0 ) return;
unsigned int i; // Reset samples for next frame
for (i=0; i<NUM_PROFILE_SAMPLES; ++i)
{
m_samples[i].bValid = false;
}
DxInputDevice &IDev = DxInputDevice::GetInstance();
if (IDev.GetKeyState(DIK_LCONTROL)&DXKEY_PRESSED)
{
if (IDev.GetKeyState(DIK_F12)&DXKEY_UP)
{
for (i=0; i<NUM_PROFILE_SAMPLES; ++i)
{
m_history[i].bValid = false;
}
}
}
m_startProfile = _GETCURTIME_;
}
void CPROFILE::BlockEnd ()
{
if (m_startProfile==0)
{
return;
}
else
{
m_endProfile = _GETCURTIME_;
}
}
void CPROFILE::Begin(char* name)
{
if (m_startProfile==0)
{
return;
}
unsigned int i = 0;
while ( i < NUM_PROFILE_SAMPLES && m_samples[i].bValid == true )
{
if( strcmp( m_samples[i].szName, name ) == 0 ) //Found the sample
{
m_samples[i].iOpenProfiles++;
m_samples[i].iProfileInstances++;
m_samples[i].fStartTime = _GETCURTIME_;
GASSERT( m_samples[i].iOpenProfiles == 1 ); //max 1 open at once
return;
}
i++;
}
if( i >= NUM_PROFILE_SAMPLES )
{
GASSERT( !"Exceeded Max Available Profile Samples" );
return;
}
StringCchCopy( m_samples[i].szName, 256, name );
m_samples[i].bValid = true;
m_samples[i].iOpenProfiles = 1;
m_samples[i].iProfileInstances = 1;
m_samples[i].fAccumulator = 0;
m_samples[i].fStartTime = _GETCURTIME_;
m_samples[i].fChildrenSampleTime = 0;
}
void CPROFILE::End ( char* name )
{
if (m_startProfile==0)
{
return;
}
unsigned int i = 0;
unsigned int numParents = 0;
while (i < NUM_PROFILE_SAMPLES && m_samples[i].bValid == true)
{
if (strcmp(m_samples[i].szName, name) == 0) //Found the sample
{
unsigned int inner = 0;
int parent = -1;
unsigned long fEndTime = _GETCURTIME_;
m_samples[i].iOpenProfiles--;
while (m_samples[inner].bValid == true) //Count all parents and find the immediate parent
{
if (m_samples[inner].iOpenProfiles > 0) //Found a parent (any open profiles are parents)
{
numParents++;
if (parent < 0) //Replace invalid parent (index)
{
parent = inner;
}
else if (m_samples[inner].fStartTime >= m_samples[parent].fStartTime) //Replace with more immediate parent
{
parent = inner;
}
}
inner++;
}
m_samples[i].iNumParents = numParents; //Remember the current number of parents of the sample
if (parent >= 0)
{
m_samples[parent].fChildrenSampleTime += fEndTime - m_samples[i].fStartTime; //Record this time in fChildrenSampleTime (add it in)
}
m_samples[i].fAccumulator += fEndTime - m_samples[i].fStartTime; //Save sample time in accumulator
return;
} // if
i++;
} // while
}
void CPROFILE::DumpOutputToView (int _OUTCHANNEL)
{
if ( m_startProfile==0 ) return;
unsigned int i=0;
float fDxTIME = _GETELAPSEDTIME_;
if (fDxTIME <= 0.0f)
return;
CDebugSet::ToView ( _OUTCHANNEL, 0, " Ave : Min : Max : # : Profile Name" );
CDebugSet::ToView ( _OUTCHANNEL, 1, "--------------------------------------------" );
while (i < NUM_PROFILE_SAMPLES && m_samples[i].bValid == true)
{
unsigned int indent = 0;
float sampleTime = 0;
float percentTime = 0;
float aveTime = 0;
float minTime = 0;
float maxTime = 0;
char name[256] = "";
char indentedName[256] = "";
char ave[16] = "";
char min[16] = "";
char max[16] = "";
char num[16] = "";
if (m_samples[i].iOpenProfiles < 0)
{
char szDump[256] = "";
StringCchPrintf(szDump, 256, "%s, ProfileEnd() called without a ProfileBegin()", m_samples[i].szName);
GASSERT (!szDump);
}
else if (m_samples[i].iOpenProfiles > 0)
{
char szDump[256] = "";
StringCchPrintf(szDump, 256, "%s, ProfileBegin() called without a ProfileEnd()", m_samples[i].szName);
GASSERT (!szDump);
}
sampleTime = (float)( m_samples[i].fAccumulator - m_samples[i].fChildrenSampleTime );
if (sampleTime < 0)
{
sampleTime = 0;
}
percentTime = ( ( sampleTime / fDxTIME ) * 100.0f );
if (percentTime < 0)
{
percentTime = 0;
}
aveTime = minTime = maxTime = percentTime;
//Add new measurement into the history and get the ave, min, and max
StoreInHistory ( m_samples[i].szName, percentTime );
GetFromHistory ( m_samples[i].szName, &aveTime, &minTime, &maxTime );
//Format the data
StringCchPrintf( ave, 16, "%3.1f", aveTime );
StringCchPrintf( min, 16, "%3.1f", minTime );
StringCchPrintf( max, 16, "%3.1f", maxTime );
StringCchPrintf( num, 16, "%3d", m_samples[i].iProfileInstances );
StringCchCopy (indentedName, 256, m_samples[i].szName);
for (indent=0; indent<m_samples[i].iNumParents; ++indent)
{
StringCchPrintf(name, 256, " %s", indentedName);
StringCchCopy(indentedName, 256, name);
}
CDebugSet::ToView( _OUTCHANNEL, 2+i, "%5s : %5s : %5s : %3s : %s", ave, min, max, num, indentedName );
i++;
} // while
CDebugSet::ToView(_OUTCHANNEL, 2+i+0, "--------------------------------------------");
CDebugSet::ToView(_OUTCHANNEL, 2+i+1, "Reset Stats : Ctrl + F12");
}
void CPROFILE::DumpOutputToFile ()
{
if (m_startProfile==0)
{
return;
}
unsigned int i=0;
float fDxTIME = _GETELAPSEDTIME_;
if (fDxTIME <= 0.0f)
return;
CDebugSet::ToLogFile ( " Ave : Min : Max : # : Profile Name" );
CDebugSet::ToLogFile ( "--------------------------------------------" );
while (i < NUM_PROFILE_SAMPLES && m_samples[i].bValid == true)
{
unsigned int indent = 0;
float sampleTime = 0;
float percentTime = 0;
float aveTime = 0;
float minTime = 0;
float maxTime = 0;
char name[256] = "";
char indentedName[256] = "";
char ave[16] = "";
char min[16] = "";
char max[16] = "";
char num[16] = "";
if (m_samples[i].iOpenProfiles < 0)
{
char szDump[256] = "";
StringCchPrintf(szDump,
256,
_T("%s, ProfileEnd() called without a ProfileBegin()"),
m_samples[i].szName);
GASSERT(!szDump);
}
else if (m_samples[i].iOpenProfiles > 0)
{
char szDump[256] = "";
StringCchPrintf (szDump,
256,
_T("%s, ProfileBegin() called without a ProfileEnd()"),
m_samples[i].szName);
GASSERT ( !szDump );
}
sampleTime = (float)( m_samples[i].fAccumulator - m_samples[i].fChildrenSampleTime );
if (sampleTime < 0)
{
sampleTime = 0;
}
percentTime = ( ( sampleTime / fDxTIME ) * 100.0f );
if (percentTime < 0)
{
percentTime = 0;
}
aveTime = minTime = maxTime = percentTime;
//Add new measurement into the history and get the ave, min, and max
StoreInHistory ( m_samples[i].szName, percentTime );
GetFromHistory ( m_samples[i].szName, &aveTime, &minTime, &maxTime );
//Format the data
StringCchPrintf( ave, 16, "%3.1f", aveTime );
StringCchPrintf( min, 16, "%3.1f", minTime );
StringCchPrintf( max, 16, "%3.1f", maxTime );
StringCchPrintf( num, 16, "%3d", m_samples[i].iProfileInstances );
StringCchCopy( indentedName, 256, m_samples[i].szName );
for( indent=0; indent<m_samples[i].iNumParents; indent++ )
{
StringCchPrintf ( name, 256, " %s", indentedName );
StringCchCopy( indentedName, 256, name );
}
CDebugSet::ToLogFile( "%5s : %5s : %5s : %3s : %s", ave, min, max, num, indentedName );
i++;
} // while
CDebugSet::ToLogFile ( "--------------------------------------------" );
}
void CPROFILE::DumpOutputToNon ()
{
if (m_startProfile==0)
{
return;
}
unsigned int i=0;
float fDxTIME = _GETELAPSEDTIME_;
if (fDxTIME <= 0.0f)
return;
while (i < NUM_PROFILE_SAMPLES && m_samples[i].bValid == true)
{
unsigned int indent = 0;
float sampleTime = 0;
float percentTime = 0;
float aveTime = 0;
float minTime = 0;
float maxTime = 0;
if ( m_samples[i].iOpenProfiles < 0 )
{
char szDump[256] = "";
StringCchPrintf( szDump, 256, "%s, ProfileEnd() called without a ProfileBegin()", m_samples[i].szName );
GASSERT ( !szDump );
}
else if ( m_samples[i].iOpenProfiles > 0 )
{
char szDump[256] = "";
StringCchPrintf( szDump, 256, "%s, ProfileBegin() called without a ProfileEnd()", m_samples[i].szName );
GASSERT ( !szDump );
}
sampleTime = (float)( m_samples[i].fAccumulator - m_samples[i].fChildrenSampleTime );
if (sampleTime < 0)
{
sampleTime = 0;
}
percentTime = ( ( sampleTime / fDxTIME ) * 100.0f );
if (percentTime < 0)
{
percentTime = 0;
}
aveTime = minTime = maxTime = percentTime;
//Add new measurement into the history and get the ave, min, and max
StoreInHistory(m_samples[i].szName, percentTime);
GetFromHistory(m_samples[i].szName, &aveTime, &minTime, &maxTime);
i++;
} // while
}
void CPROFILE::StoreInHistory ( char* name, float percent )
{
if (m_startProfile==0)
{
return;
}
unsigned int i = 0;
float oldRatio = 0;
float newRatio = _GETELAPSEDTIME_ / _HISTORY_RATE_;
if ( newRatio > 1.0f )
{
newRatio = 1.0f;
}
oldRatio = 1.0f - newRatio;
while (i < NUM_PROFILE_SAMPLES && m_history[i].bValid == true)
{
if (strcmp(m_history[i].szName, name) == 0) //Found the sample
{
m_history[i].fAve = (m_history[i].fAve*oldRatio) + (percent*newRatio);
if ( percent < m_history[i].fMin )
{
m_history[i].fMin = percent;
}
else
{
m_history[i].fMin = (m_history[i].fMin*oldRatio) + (percent*newRatio);
}
if ( m_history[i].fMin < 0.0f )
{
m_history[i].fMin = 0.0f;
}
if ( percent > m_history[i].fMax )
{
m_history[i].fMax = percent;
}
else
{
m_history[i].fMax = (m_history[i].fMax*oldRatio) + (percent*newRatio);
}
return;
} // if
i++;
} // while
if (i < NUM_PROFILE_SAMPLES) //Add to history
{
StringCchCopy( m_history[i].szName, 256, name );
m_history[i].bValid = true;
m_history[i].fAve = m_history[i].fMin = m_history[i].fMax = percent;
}
else
{
GASSERT ( !"Exceeded Max Available Profile Samples!");
}
}
void CPROFILE::GetFromHistory ( char* name, float* ave, float* min, float* max )
{
if (m_startProfile==0)
{
return;
}
unsigned int i = 0;
while (i < NUM_PROFILE_SAMPLES && m_history[i].bValid == true)
{
if (strcmp(m_history[i].szName, name) == 0)
{ //Found the sample
*ave = m_history[i].fAve;
*min = m_history[i].fMin;
*max = m_history[i].fMax;
return;
}
i++;
}
*ave = *min = *max = 0.0f;
} | 22.871102 | 134 | 0.624852 | yexiuph |
fa83f675d9c884b76ce3bb0d43c0c11312df07f7 | 1,646 | cpp | C++ | fnelem/model/restraints/restraint.cpp | mfkiwl/FNELEM-GPU | 7f035e065f7fcaf98df9b3e40cfa0ef782b55931 | [
"MIT"
] | 7 | 2019-05-25T04:43:55.000Z | 2022-02-14T09:14:28.000Z | fnelem/model/restraints/restraint.cpp | mfkiwl/FNELEM-GPU | 7f035e065f7fcaf98df9b3e40cfa0ef782b55931 | [
"MIT"
] | 2 | 2018-12-06T15:23:10.000Z | 2021-04-14T15:07:33.000Z | fnelem/model/restraints/restraint.cpp | mfkiwl/FNELEM-GPU | 7f035e065f7fcaf98df9b3e40cfa0ef782b55931 | [
"MIT"
] | 5 | 2019-05-25T09:32:28.000Z | 2021-03-15T08:14:52.000Z | #include <utility>
/**
FNELEM-GPU RESTRAINTS - RESTRAINT.
Abstract restraint class.
@package fnelem.model.restraints
@author ppizarror
@date 01/12/2018
@license
MIT License
Copyright (c) 2018 Pablo Pizarro R.
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 header
#include "restraint.h"
/**
* Constructor.
*
* @param tag Restraint tag
*/
Restraint::Restraint(std::string tag) : ModelComponent(std::move(tag)) {
}
/**
* Destructor.
*/
Restraint::~Restraint() = default;;
/**
* Apply restraint
*/
void Restraint::apply() {
}
/**
* Display restraint information
*/
void Restraint::disp() const {
ModelComponent::disp();
} | 27.433333 | 79 | 0.752126 | mfkiwl |
fa8513b9b1598a97d7e11ea82cb932f68a07efaa | 544 | cpp | C++ | GameEngine/Sources/IndexBufferSegment.cpp | GPUWorks/OpenGL-Mini-CAD-2D | fedb903302f82a1d1ff0ca6776687a60a237008a | [
"MIT"
] | 1 | 2021-08-10T02:48:57.000Z | 2021-08-10T02:48:57.000Z | GameEngine/Sources/IndexBufferSegment.cpp | GPUWorks/OpenGL-Mini-CAD-2D | fedb903302f82a1d1ff0ca6776687a60a237008a | [
"MIT"
] | null | null | null | GameEngine/Sources/IndexBufferSegment.cpp | GPUWorks/OpenGL-Mini-CAD-2D | fedb903302f82a1d1ff0ca6776687a60a237008a | [
"MIT"
] | null | null | null | #include "IndexBufferSegment.h"
//------------------------------ Constructors
storage::IndexBufferSegment::IndexBufferSegment()
{
}
storage::IndexBufferSegment::IndexBufferSegment(GLuint start, GLuint end)
{
this->start = start;
this->end = end;
}
//------------------------------ Secondary Functions (Provide Data)
void storage::IndexBufferSegment::update(GLuint start, GLuint end)
{
this->start = start;
this->end = end;
}
void storage::IndexBufferSegment::update(GLuint end)
{
this->end = end;
} | 17.548387 | 74 | 0.606618 | GPUWorks |
fa862e6bccb7fae496c3d8819b8bf739ad5f4f72 | 1,621 | cpp | C++ | qt_ai_network/ai2_pathfinding/code/Breadth_First.cpp | marwac-9/labs | 343c19db16d702b7af392d0325e69aa575ad04c1 | [
"Apache-2.0"
] | 1 | 2019-10-05T04:06:50.000Z | 2019-10-05T04:06:50.000Z | qt_ai_network/ai2_pathfinding/code/Breadth_First.cpp | marwac-9/LTU-labs | 343c19db16d702b7af392d0325e69aa575ad04c1 | [
"Apache-2.0"
] | null | null | null | qt_ai_network/ai2_pathfinding/code/Breadth_First.cpp | marwac-9/LTU-labs | 343c19db16d702b7af392d0325e69aa575ad04c1 | [
"Apache-2.0"
] | null | null | null | #include "Breadth_First.h"
#include "Face.h"
#include "Edge.h"
#include <unordered_map>
BreadthFirst::BreadthFirst()
{
}
BreadthFirst::~BreadthFirst()
{
}
void BreadthFirst::BFS(Face* start, Face* goal, int mapSize, std::vector<Face*>& nodePath)
{
Face** Queue = new Face*[mapSize];
std::unordered_map<Face*, bool> discoveryMap;
discoveryMap.reserve(mapSize);
int Front = 0;
int Back = 0;
Queue[Back++] = start;
discoveryMap[start] = true;
//start->visited = true;
Face* currentNode;
Face* pairNode = nullptr;
while (Front < Back)
{
currentNode = Queue[Front];
Edge* currentEdge = currentNode->edge;
do
{
//returns the path if we have come to our goal
if (goal == currentNode)
{
if (currentNode == start)
{
delete[] Queue;
return;
}
nodePath.push_back(goal);
Face* currentPathNode = goal;
Face* nextNode = nullptr;
while ((nextNode = currentPathNode->previousFace) != start)
{
nodePath.push_back(nextNode);
currentPathNode = nextNode;
}
delete[] Queue;
return;
}
pairNode = nullptr;
//checks if the edges are connected
if (currentEdge->pair != nullptr) {
pairNode = currentEdge->pair->face;
//if pairnode has not been visited, add it to the nodes we want to visit
//if (!pairNode->visited)
if (!discoveryMap[pairNode]) {
Queue[Back++] = pairNode;
pairNode->previousFace = currentNode;
//pairNode->visited = true;
discoveryMap[pairNode] = true;
}
}
currentEdge = currentEdge->next;
} while (currentEdge != currentNode->edge);
Front++;
}
delete[] Queue;
} | 21.051948 | 90 | 0.645281 | marwac-9 |
fa87955f9a6f32cc158faeaa7263440951aa935b | 2,821 | cpp | C++ | src/main.cpp | cbeck88/flashcards | dc3a517c1bb527645358db0229075b4a1692c3c6 | [
"WTFPL"
] | null | null | null | src/main.cpp | cbeck88/flashcards | dc3a517c1bb527645358db0229075b4a1692c3c6 | [
"WTFPL"
] | null | null | null | src/main.cpp | cbeck88/flashcards | dc3a517c1bb527645358db0229075b4a1692c3c6 | [
"WTFPL"
] | null | null | null | #include <algorithm>
#include <fstream>
#include <iostream>
#include <random>
#include <string>
#include <vector>
#include "catalog.hpp"
namespace flash {
struct controller {
catalog cards;
std::mt19937 rng;
static void prompt_impl(const std::string & query, const std::string & answer) {
std::cout << '"' << query << "\":" << std::endl;
std::string result;
std::getline(std::cin, result);
std::cout << answer << std::endl << std::endl;
}
static void prompt_forward(const spair & card) {
prompt_impl(card.first, card.second);
}
static void prompt_backward(const spair & card) {
prompt_impl(card.second, card.first);
}
std::vector<int> get_cards_permutation() {
std::vector<int> result(cards.size());
for (unsigned int i = 0; i < result.size(); ++i) {
result[i] = i;
}
std::shuffle(result.begin(), result.end(), rng);
return result;
}
template <typename V>
void for_each_card(V && v) {
std::vector<int> perm{ this->get_cards_permutation() };
for (int idx : perm) {
v(cards[idx]);
}
}
// Main interface
void do_each_forward() {
this->for_each_card(controller::prompt_forward);
}
void do_each_backward() {
this->for_each_card(controller::prompt_backward);
}
// ctor
controller(catalog && cat)
: cards(std::move(cat))
, rng()
{
std::random_device rdev;
rng = std::mt19937(rdev());
}
};
} // end namespace flash
int main(int argc, char * argv[]) {
if (argc != 2) { std::cerr << "Expected: [catalog file]\n"; return 1; }
std::string fname{argv[1]};
std::ifstream ifs{fname};
if (!ifs) { std::cerr << "Could not read file: " << fname << std::endl; return 1; }
flash::catalog cat{ flash::parse_catalog(ifs) };
std::cout << "Read: " << cat.size() << " flash cards." << std::endl;
if (!cat.size()) { return 0; }
else {
std::cout << std::endl;
for (const auto & card : cat) {
std::cout << card.first << " -- " << card.second << std::endl;
}
std::cout << std::endl;
std::cout << std::endl;
}
// Load cards into the controller
flash::controller ctrl{std::move(cat)};
// Main loop
int option = 0;
do {
std::cout << "\nOptions:\n"
<< "[1] Read flash cards forwards\n"
<< "[2] Read flash cards backwards\n"
<< "[0] Exit\n"
<< std::endl;
option = 0;
if (std::cin >> option) {
std::string temp;
std::getline(std::cin, temp);
switch (option) {
case 1:
ctrl.do_each_forward();
break;
case 2:
ctrl.do_each_backward();
break;
default:
option = 0;
break;
}
}
} while(option);
std::cout << "Goodbye!" << std::endl;
}
| 20.442029 | 85 | 0.556186 | cbeck88 |
fa88d7eba6f8e9eaf50ecb4b4df86f9b212bed51 | 6,340 | cc | C++ | tasks/process_metabuf_task.cc | smukil/cachemover | 159ae10072f23b7d4168a804b672e1e810d4df19 | [
"Apache-2.0"
] | 27 | 2021-11-27T06:11:54.000Z | 2022-03-31T18:53:51.000Z | tasks/process_metabuf_task.cc | Netflix/cachemover | 236998c442eed704cc9cf9df9be4f299e7f3b6e1 | [
"Apache-2.0"
] | null | null | null | tasks/process_metabuf_task.cc | Netflix/cachemover | 236998c442eed704cc9cf9df9be4f299e7f3b6e1 | [
"Apache-2.0"
] | null | null | null | /**
*
* Copyright 2021 Netflix, Inc.
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*
*/
#include "common/logger.h"
#include "dumper/dumper.h"
#include "tasks/process_metabuf_task.h"
#include "tasks/s3_upload_task.h"
#include "tasks/task_scheduler.h"
#include "tasks/task_thread.h"
#include "utils/mem_mgr.h"
#include "utils/memcache_utils.h"
#include "utils/socket.h"
#include <fstream>
#include <sstream>
namespace memcachedumper {
ProcessMetabufTask::ProcessMetabufTask(const std::string& filename, bool is_s3_dump)
: filename_(filename),
is_s3_dump_(is_s3_dump) {
}
std::string ProcessMetabufTask::UrlDecode(std::string& str){
std::ostringstream oss;
char ch;
int i, ii, len = str.length();
for (i=0; i < len; i++){
if(str[i] != '%'){
if(str[i] == '+')
oss << ' ';
else
oss << str[i];
}else{
sscanf(str.substr(i + 1, 2).c_str(), "%x", &ii);
ch = static_cast<char>(ii);
oss << ch;
i = i + 2;
}
}
return oss.str();
}
void ProcessMetabufTask::ProcessMetaBuffer(MetaBufferSlice* mslice) {
time_t now = std::time(0);
char* newline_pos = nullptr;
do {
const char *key_pos = mslice->next_key_pos();
if (key_pos == nullptr) {
if (newline_pos != nullptr) {
mslice->CopyRemainingToStart(newline_pos);
}
break;
}
const char *exp_pos = mslice->next_exp_pos();
if (exp_pos == nullptr) {
if (newline_pos != nullptr) {
mslice->CopyRemainingToStart(newline_pos);
}
break;
}
const char *la_pos = mslice->next_la_pos();
if (la_pos == nullptr) {
if (newline_pos != nullptr) {
mslice->CopyRemainingToStart(newline_pos);
}
break;
}
char *unused;
int32_t expiry = strtol(exp_pos + 4, &unused, 10);
std::string encoded_key(
const_cast<char*>(key_pos) + 4, static_cast<int>(
exp_pos - key_pos - 4 - 1));
std::string decoded_key = UrlDecode(encoded_key);
if (expiry != -1 && MemcachedUtils::KeyExpiresSoon(now,
static_cast<uint32_t>(expiry))) {
owning_thread()->increment_keys_ignored();
continue;
}
// Filter the key out if required.
if (MemcachedUtils::FilterKey(decoded_key) == true) {
owning_thread()->increment_keys_filtered();
continue;
}
// Track the key and queue it for processing.
McData *new_key = new McData(decoded_key, expiry);
data_writer_->QueueForProcessing(new_key);
} while ((newline_pos = const_cast<char*>(mslice->next_newline())) != nullptr);
}
void ProcessMetabufTask::MarkCheckpoint() {
std::ofstream checkpoint_file;
std::string chkpt_file_path =
MemcachedUtils::GetKeyFilePath() + "CHECKPOINTS_" + owning_thread()->thread_name();
checkpoint_file.open(chkpt_file_path, std::ofstream::app);
// Omit the path while writing the file name.
// Also add a new line after every file name.
std::string file_sans_path = filename_.substr(filename_.rfind("/") + 1) + "\n";
checkpoint_file.write(file_sans_path.c_str(), file_sans_path.length());
checkpoint_file.close();
}
void ProcessMetabufTask::Execute() {
Socket *mc_sock = owning_thread()->task_scheduler()->GetMemcachedSocket();
assert(mc_sock != nullptr);
uint8_t* data_writer_buf = owning_thread()->mem_mgr()->GetBuffer();
assert(data_writer_buf != nullptr);
// Extract the key file's index from its name, so that we can use the same index
// for data files.
std::string keyfile_idx_str = filename_.substr(filename_.rfind("_") + 1);
data_writer_.reset(new KeyValueWriter(
MemcachedUtils::DataFilePrefix() + "_" + keyfile_idx_str,
owning_thread()->thread_name(),
data_writer_buf, owning_thread()->mem_mgr()->chunk_size(),
MemcachedUtils::MaxDataFileSize(), mc_sock));
// TODO: Check return status
Status init_status = data_writer_->Init();
if (!init_status.ok()) {
LOG_ERROR("FAILED TO INITIALIZE KeyValueWriter. (Status: {0})", init_status.ToString());
owning_thread()->task_scheduler()->ReleaseMemcachedSocket(mc_sock);
owning_thread()->mem_mgr()->ReturnBuffer(data_writer_buf);
return;
}
std::ifstream metafile;
metafile.open(filename_);
LOG("Processing file: {0}", filename_);
char *metabuf = reinterpret_cast<char*>(owning_thread()->mem_mgr()->GetBuffer());
uint64_t buf_size = owning_thread()->mem_mgr()->chunk_size();
int32_t bytes_read = metafile.readsome(metabuf, buf_size);
size_t mslice_size = bytes_read;
char *buf_begin_fill = metabuf;
while (bytes_read > 0) {
MetaBufferSlice mslice(metabuf, mslice_size);
ProcessMetaBuffer(&mslice);
// Find number of bytes free in the buffer. Usually should be the entire 'buf_size',
// but in some cases, we can have a little leftover unparsed bytes at the end of the
// buffer which 'ProcessMetaBuffer()' would have copied to the start of the buffer.
size_t free_bytes = mslice.free_bytes();
size_t size_remaining = mslice.size() - free_bytes;
// Start filling the buffer from after the unparsed bytes.
buf_begin_fill = mslice.buf_begin_fill();
bytes_read = metafile.readsome(buf_begin_fill, free_bytes);
mslice_size = size_remaining + bytes_read;
}
data_writer_->Finalize();
owning_thread()->account_keys_processed(data_writer_->num_processed_keys());
owning_thread()->account_keys_missing(data_writer_->num_missing_keys());
metafile.close();
owning_thread()->task_scheduler()->ReleaseMemcachedSocket(mc_sock);
owning_thread()->mem_mgr()->ReturnBuffer(reinterpret_cast<uint8_t*>(metabuf));
owning_thread()->mem_mgr()->ReturnBuffer(data_writer_buf);
MarkCheckpoint();
}
} // namespace memcachedumper
| 31.078431 | 92 | 0.672871 | smukil |
fa8a431ac27f66c322f134372c2d59cc6876d0b4 | 3,263 | inl | C++ | owCore/RefManager1DimAssync.inl | adan830/OpenWow | 9b6e9c248bd185b1677fe616d2a3a81a35ca8894 | [
"Apache-2.0"
] | null | null | null | owCore/RefManager1DimAssync.inl | adan830/OpenWow | 9b6e9c248bd185b1677fe616d2a3a81a35ca8894 | [
"Apache-2.0"
] | null | null | null | owCore/RefManager1DimAssync.inl | adan830/OpenWow | 9b6e9c248bd185b1677fe616d2a3a81a35ca8894 | [
"Apache-2.0"
] | 1 | 2020-05-11T13:32:49.000Z | 2020-05-11T13:32:49.000Z | #pragma once
#include "RefManager1DimAssync.h"
template <class T>
CRefManager1DimAssync<T>::CRefManager1DimAssync()
{
#ifndef DISABLE_ASSYNC
if (m_Event_Add == nullptr && m_Thread_Loader == nullptr)
{
m_Event_Add = CreateEvent(NULL, TRUE, TRUE, NULL);
m_Thread_Loader = CreateThread(NULL, 0, &ThreadProc, this, NULL, NULL);
SetThreadPriority(m_Thread_Loader, THREAD_PRIORITY_BELOW_NORMAL);
}
#endif
}
template <class T>
CRefManager1DimAssync<T>::~CRefManager1DimAssync()
{
for (auto it = objects.begin(); it != objects.end(); )
{
SharedTexturePtr item = it->second;
string name = GetNameByItem(item);
this->DeleteAction(name);
//delete item;
it = objects.erase(it);
//item = nullptr;
}
#ifndef DISABLE_ASSYNC
ResetEvent(m_Event_Add);
CloseHandle(m_Event_Add);
TerminateThread(m_Thread_Loader, 1);
CloseHandle(m_Thread_Loader);
#endif
}
template <class T>
inline shared_ptr<T> CRefManager1DimAssync<T>::Add(cstring name)
{
SharedTexturePtr item = GetItemByName(name);
if (item != nullptr)
{
return item;
}
item = CreateAction(name);
#ifndef DISABLE_ASSYNC
// Add to load list
m_ObjectsToLoad.add(name, item);
// Start thread if stopped
if (m_ObjectsToLoad.size() > 0)
{
SetEvent(m_Event_Add);
}
#else
LoadAction(name, item);
#endif
if (item != nullptr)
{
objects[name] = item;
}
return item;
}
template <class T>
bool CRefManager1DimAssync<T>::Exists(cstring name) const
{
return objects.find(name) != objects.end();
}
template <class T>
inline void CRefManager1DimAssync<T>::Delete(cstring name)
{
shared_ptr<T> item = GetItemByName(name);
if (item != nullptr)
{
auto it = objects.find(name);
this->DeleteAction(name);
//delete item;
objects.erase(name);
//item = nullptr;
}
}
template <class T>
inline void CRefManager1DimAssync<T>::Delete(shared_ptr<T> item)
{
for (auto it = objects.begin(); it != objects.end(); ++it)
{
if (it->second == item)
{
this->Delete(it->first);
return;
}
}
// If not found
//delete item;
//item = nullptr;
}
template <class T>
inline shared_ptr<T> CRefManager1DimAssync<T>::GetItemByName(cstring name) const
{
auto name_item = objects.find(name);
if (name_item != objects.end())
{
return name_item->second;
}
return nullptr;
}
template <class T>
inline std::string CRefManager1DimAssync<T>::GetNameByItem(shared_ptr<T> item) const
{
for (auto it = objects.begin(); it != objects.end(); ++it)
{
if (it->second == item)
{
return it->first;
}
}
return "";
}
// Log
template <class T>
inline void CRefManager1DimAssync<T>::PrintAllInfo()
{
uint32 refsCnt = 0;
for (auto it = objects.begin(); it != objects.end(); ++it)
{
refsCnt += it->second.use_count();
Log::Info("Item (%d) [%s]", it->second.use_count(), it->first.c_str());
}
Log::Info("Item's count [%d], items refs [%d]", objects.size(), refsCnt);
}
template<class T>
inline shared_ptr<T> CRefManager1DimAssync<T>::CreateAction(cstring name)
{
return NULL;
}
template<class T>
inline void CRefManager1DimAssync<T>::LoadAction(string name, shared_ptr<T>& item)
{
}
template<class T>
inline bool CRefManager1DimAssync<T>::DeleteAction(cstring name)
{
return false;
}
template<class T>
inline void CRefManager1DimAssync<T>::MakeContext()
{
}
| 18.861272 | 84 | 0.694146 | adan830 |
fa8c15f2e16ba4777ea1417d021e2af3df6b2e70 | 5,157 | cpp | C++ | Source/src/components/ComponentObstacle.cpp | Akita-Interactive/Hachiko-Engine | 0e3e0377ac5c8f5b15c525c8fcff384e9c92c14b | [
"MIT"
] | 5 | 2022-02-10T23:31:11.000Z | 2022-02-11T19:32:38.000Z | Source/src/components/ComponentObstacle.cpp | Akita-Interactive/Hachiko-Engine | 0e3e0377ac5c8f5b15c525c8fcff384e9c92c14b | [
"MIT"
] | null | null | null | Source/src/components/ComponentObstacle.cpp | Akita-Interactive/Hachiko-Engine | 0e3e0377ac5c8f5b15c525c8fcff384e9c92c14b | [
"MIT"
] | null | null | null | #include "core/hepch.h"
#include "ComponentObstacle.h"
#include "ComponentTransform.h"
#include "Application.h"
#include "modules/ModuleNavigation.h"
#include "resources/ResourceNavMesh.h"
#include "DetourTileCache/DetourTileCache.h"
Hachiko::ComponentObstacle::ComponentObstacle(GameObject* container) : Component(Type::OBSTACLE, container)
{}
Hachiko::ComponentObstacle::~ComponentObstacle()
{
RemoveObstacle();
}
void Hachiko::ComponentObstacle::Start()
{
AddObstacle();
}
void Hachiko::ComponentObstacle::Stop()
{
RemoveObstacle();
}
void Hachiko::ComponentObstacle::Update()
{
if (dirty)
{
++count_since_update;
if (count_since_update > update_freq)
{
RefreshObstacle();
dirty = false;
count_since_update = 0;
}
}
}
void Hachiko::ComponentObstacle::OnTransformUpdated()
{
Invalidate();
}
void Hachiko::ComponentObstacle::SetType(ObstacleType new_type)
{
obstacle_type = new_type;
Invalidate();
}
void Hachiko::ComponentObstacle::SetSize(const float3& new_size)
{
size = new_size;
Invalidate();
}
void Hachiko::ComponentObstacle::DrawGui()
{
ImGui::PushID(this);
if (ImGui::CollapsingHeader("Obstacle", ImGuiTreeNodeFlags_DefaultOpen))
{
if (!obstacle && ImGui::Button("Add to navmesh"))
{
AddObstacle();
}
if (obstacle && ImGui::Button("Remove from navmesh"))
{
RemoveObstacle();
}
if (obstacle_type == ObstacleType::DT_OBSTACLE_CYLINDER)
{
if (ImGui::DragFloat2("Radius, Height", size.ptr()))
{
SetSize(size);
}
}
else
{
if (ImGui::DragFloat3("Size", size.ptr()))
{
SetSize(size);
}
}
bool changed_type = false;
ImGui::Text("Type");
changed_type |= ImGui::RadioButton("Cylinder", (int*) &obstacle_type, static_cast<int>(ObstacleType::DT_OBSTACLE_CYLINDER));
ImGui::SameLine();
changed_type |= ImGui::RadioButton("Box", (int*)&obstacle_type, static_cast<int>(ObstacleType::DT_OBSTACLE_BOX));
ImGui::SameLine();
changed_type |= ImGui::RadioButton("Oriented Box", (int*)&obstacle_type, static_cast<int>(ObstacleType::DT_OBSTACLE_ORIENTED_BOX));
if (changed_type)
{
SetType(obstacle_type); // Changes the obstacle type
}
ImGui::Text("Exists: %d", obstacle != nullptr);
}
ImGui::PopID();
}
void Hachiko::ComponentObstacle::AddObstacle()
{
dtTileCache* tile_cache = App->navigation->GetTileCache();
if (!tile_cache)
{
HE_LOG("Failed to add obstacle on unexisting tile cache");
return;
}
// If obstacle is already set remove it before adding it again
// Remove already contains the check
RemoveObstacle();
obstacle = new dtObstacleRef;
ComponentTransform* transform = game_object->GetTransform();
switch (obstacle_type)
{
case ObstacleType::DT_OBSTACLE_CYLINDER:
// In this case we dont use size z, we only need height and radius
// Look for draw gizmo option that seems to be used on some examples
tile_cache->addObstacle(transform->GetGlobalPosition().ptr(), size.x, size.y, obstacle);
break;
case ObstacleType::DT_OBSTACLE_BOX:
{
// This case needs a scope for initializing
AABB aabb;
aabb.SetFromCenterAndSize(transform->GetGlobalPosition(), size);
tile_cache->addBoxObstacle(aabb.minPoint.ptr(), aabb.maxPoint.ptr(), obstacle);
break;
}
case ObstacleType::DT_OBSTACLE_ORIENTED_BOX:
// Method expects half the desired size of the box to be passed
// Expects y rotation in radians and says box cant be rotated in y
tile_cache->addBoxObstacle(transform->GetGlobalPosition().ptr(), (size / 2.f).ptr(), transform->GetGlobalRotation().ToEulerXYX().y, obstacle);
break;
}
if (!obstacle)
{
HE_LOG("Failed to add obstacle with existing navmesh and tile cache");
}
}
void Hachiko::ComponentObstacle::RemoveObstacle()
{
if (!obstacle)
{
// No need to remove an obstacle that is already not being used
return;
}
dtTileCache* tile_cache = App->navigation->GetTileCache();
if (!tile_cache)
{
HE_LOG("Failed to remove obstacle from unexisting tile cache");
return;
}
tile_cache->removeObstacle(*obstacle);
RELEASE(obstacle);
}
void Hachiko::ComponentObstacle::RefreshObstacle()
{
if (obstacle)
{
// Refesh the obstacle position if it exists
AddObstacle();
}
}
void Hachiko::ComponentObstacle::Save(YAML::Node& node) const
{
node[OBSTACLE_TYPE] = static_cast<unsigned int>(obstacle_type);
node[OBSTACLE_SIZE] = size;
}
void Hachiko::ComponentObstacle::Load(const YAML::Node& node)
{
SetType(static_cast<ObstacleType>(node[OBSTACLE_TYPE].as<unsigned int>()));
SetSize(node[OBSTACLE_SIZE].as<float3>());
}
| 27 | 150 | 0.631181 | Akita-Interactive |
fa8f88a378d4544dd3eaa8a898ad096b199e97d9 | 3,219 | cpp | C++ | client/Camera.cpp | fvazquezf/7542_TpFinal | 1699d9cf97794186f7e41d3bb2d33ba9239eaa3f | [
"MIT"
] | null | null | null | client/Camera.cpp | fvazquezf/7542_TpFinal | 1699d9cf97794186f7e41d3bb2d33ba9239eaa3f | [
"MIT"
] | null | null | null | client/Camera.cpp | fvazquezf/7542_TpFinal | 1699d9cf97794186f7e41d3bb2d33ba9239eaa3f | [
"MIT"
] | null | null | null | #include "Camera.h"
#include <iostream>
#include "Renderizable.h"
#include <cmath>
#define PI 3.141593f
Camera::Camera(SdlWindow& window)
: window(window),
logicalCenterX(0),
logicalCenterY(0) {
centerPix = window.getCenter();
width = 2*centerPix.x;
height = 2*centerPix.y;
}
void Camera::render(Renderizable &renderizable, size_t iteration) {
// renderizable.render(this) -> double dispatch
// cada textura se debe renderizar segun su tipo
// si no usamos double dispatch tenemos todos getters
renderizable.render(*this, iteration);
}
// logical coordinates
// should only render if visible to player
void Camera::renderInSight(SdlTexture& texture,
Area& src,
float posX,
float posY,
float angle) {
if (!isVisible(posX, posY)) {
return;
}
auto rect = src.buildRectangle();
int newX = centerPix.x - (logicalCenterX - posX) * M_TO_P;
int newY = centerPix.y - (logicalCenterY - posY) * M_TO_P;
Area dst(newX - (rect.w / 2),
newY - (rect.h / 2),
rect.w, rect.h);
texture.render(src, dst, angle, SDL_FLIP_NONE);
}
bool Camera::isVisibleInX(float x) {
auto pixelX = abs(logicalCenterX - x) / M_TO_P;
return (pixelX >= 0 && pixelX <= width);
}
bool Camera::isVisibleInY(float y) {
auto pixelY = abs(logicalCenterY - y) / M_TO_P;
return (pixelY >= 0 && pixelY <= height);
}
bool Camera::isVisible(float x, float y) {
return isVisibleInX(x) && isVisibleInY(y);
}
void Camera::setLogicalCenter(float x, float y) {
logicalCenterX = x;
logicalCenterY = y;
}
Camera::~Camera() {
}
int16_t Camera::angleFromMouse() {
int x, y = 0;
SDL_GetMouseState(&x, &y);
float angle = SDL_atan2(y - centerPix.y, x - centerPix.x) * (180.000f / PI) + 90;
if (angle < 0) {
angle = 360 + angle;
}
return angle;
}
void
Camera::renderWeapon(float playerX,
float playerY,
int16_t playerAngle,
int sizeX,
int sizeY,
SdlTexture &texture) {
if (isVisibleInX(playerX) && isVisibleInY(playerY)) {
Area src(0, 0, sizeX, sizeY);
int newX = centerPix.x - (logicalCenterX - playerX) * M_TO_P;
int newY = centerPix.y - (logicalCenterY - playerY) * M_TO_P;
Area dst(newX - (sizeX / 2),
newY - (sizeY / 2),
sizeX, sizeY);
SDL_Point center{sizeX/2, sizeY};
texture.render(src, dst, playerAngle,center,SDL_FLIP_NONE);
}
}
void Camera::renderWithAlpha(SdlTexture &texture, Area &source, float x, float y, uint8_t alpha) {
auto rect = source.buildRectangle();
int newX = centerPix.x - (logicalCenterX - x) * M_TO_P;
int newY = centerPix.y - (logicalCenterY - y) * M_TO_P;
Area dst(newX - rect.w/2,
newY - rect.h/2,
rect.w,
rect.h);
texture.render(source, dst, alpha);
}
float Camera::calculateDistanceToCenter(float posX, float posY) const {
return std::sqrt(pow(abs(logicalCenterX - posX), 2) + pow(abs(logicalCenterY - posY), 2));
}
| 29.805556 | 98 | 0.593973 | fvazquezf |
fa8faa3a10d43824e6cca0cee3f02a341a6cd088 | 519 | cpp | C++ | leetcode2/countprime.cpp | WIZARD-CXY/pl | 22b7f5d81804f4e333d3cff6433364ba1a0ac7ef | [
"Apache-2.0"
] | 1 | 2016-01-20T08:26:34.000Z | 2016-01-20T08:26:34.000Z | leetcode2/countprime.cpp | WIZARD-CXY/pl | 22b7f5d81804f4e333d3cff6433364ba1a0ac7ef | [
"Apache-2.0"
] | 1 | 2015-10-21T05:38:17.000Z | 2015-11-02T07:42:55.000Z | leetcode2/countprime.cpp | WIZARD-CXY/pl | 22b7f5d81804f4e333d3cff6433364ba1a0ac7ef | [
"Apache-2.0"
] | null | null | null | class Solution {
public:
int countPrimes(int n) {
vector<bool> vis(n,0);
for(int i=2; i<sqrt(n); i++){
if(!vis[i]){
// j*i may overflow when n is large near INT_MAX
for(int j=i; j*i<n; j++){
vis[j*i]=1;
}
}
}
int cnt=0;
for(int i=2; i<n; i++){
if(!vis[i]){
cnt++;
}
}
return cnt;
}
}; | 20.76 | 64 | 0.314066 | WIZARD-CXY |