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 |
|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|
4ee10cf2ef4edf67df6d4bc3679dec9fabbefee4 | 2,112 | cpp | C++ | Vulkan/jni/bor.vulkan.structs.VkMemoryType.cpp | AlessandroBorges/Bor_Vulkan | 3847e6f44ce7f14dfc1e671a6cc51eb4788e4e4b | [
"MIT"
] | 14 | 2016-02-29T12:30:05.000Z | 2020-09-17T11:30:50.000Z | Vulkan/jni/bor.vulkan.structs.VkMemoryType.cpp | AlessandroBorges/Bor_Vulkan | 3847e6f44ce7f14dfc1e671a6cc51eb4788e4e4b | [
"MIT"
] | 2 | 2016-09-13T18:02:55.000Z | 2019-11-03T01:54:20.000Z | Vulkan/jni/bor.vulkan.structs.VkMemoryType.cpp | AlessandroBorges/Bor_Vulkan | 3847e6f44ce7f14dfc1e671a6cc51eb4788e4e4b | [
"MIT"
] | 5 | 2017-09-19T03:09:06.000Z | 2021-11-23T20:20:52.000Z | #include <bor.vulkan.structs.VkMemoryType.h>
//@line:39
#include <BorVulkan.hpp>
JNIEXPORT void JNICALL Java_bor_vulkan_structs_VkMemoryType_setPropertyFlags0(JNIEnv* env, jclass clazz, jobject obj_ptr, jint _propertyFlags) {
unsigned char* ptr = (unsigned char*)(obj_ptr?env->GetDirectBufferAddress(obj_ptr) : NULL);
//@line:191
VkMemoryType* vkObj = (VkMemoryType*)(ptr);
// code for simple past value
vkObj->propertyFlags = (VkMemoryPropertyFlags) (_propertyFlags);
}
static inline jint wrapped_Java_bor_vulkan_structs_VkMemoryType_getPropertyFlags0
(JNIEnv* env, jclass clazz, jobject obj_ptr, unsigned char* ptr) {
//@line:201
VkMemoryType* vkObj = (VkMemoryType*)(ptr);
return (jint) (vkObj->propertyFlags);
}
JNIEXPORT jint JNICALL Java_bor_vulkan_structs_VkMemoryType_getPropertyFlags0(JNIEnv* env, jclass clazz, jobject obj_ptr) {
unsigned char* ptr = (unsigned char*)(obj_ptr?env->GetDirectBufferAddress(obj_ptr) : NULL);
jint JNI_returnValue = wrapped_Java_bor_vulkan_structs_VkMemoryType_getPropertyFlags0(env, clazz, obj_ptr, ptr);
return JNI_returnValue;
}
JNIEXPORT void JNICALL Java_bor_vulkan_structs_VkMemoryType_setHeapIndex0(JNIEnv* env, jclass clazz, jobject obj_ptr, jint _heapIndex) {
unsigned char* ptr = (unsigned char*)(obj_ptr?env->GetDirectBufferAddress(obj_ptr) : NULL);
//@line:210
VkMemoryType* vkObj = (VkMemoryType*)(ptr);
// code for simple past value
vkObj->heapIndex = (uint32_t) (_heapIndex);
}
static inline jint wrapped_Java_bor_vulkan_structs_VkMemoryType_getHeapIndex0
(JNIEnv* env, jclass clazz, jobject obj_ptr, unsigned char* ptr) {
//@line:220
VkMemoryType* vkObj = (VkMemoryType*)(ptr);
return (jint) (vkObj->heapIndex);
}
JNIEXPORT jint JNICALL Java_bor_vulkan_structs_VkMemoryType_getHeapIndex0(JNIEnv* env, jclass clazz, jobject obj_ptr) {
unsigned char* ptr = (unsigned char*)(obj_ptr?env->GetDirectBufferAddress(obj_ptr) : NULL);
jint JNI_returnValue = wrapped_Java_bor_vulkan_structs_VkMemoryType_getHeapIndex0(env, clazz, obj_ptr, ptr);
return JNI_returnValue;
}
| 30.171429 | 148 | 0.767045 | AlessandroBorges |
4ee1a8522f2f5b0f19dc50c1663d47148182d0fb | 3,492 | cc | C++ | unit_test/operators/maxpool2d.cc | shi510/mlfe | aec8d52ddb54ce6f6e00a6515d7023ffba9d02f0 | [
"MIT"
] | 13 | 2019-01-23T11:21:01.000Z | 2021-06-20T18:25:11.000Z | unit_test/operators/maxpool2d.cc | shi510/mlfe | aec8d52ddb54ce6f6e00a6515d7023ffba9d02f0 | [
"MIT"
] | null | null | null | unit_test/operators/maxpool2d.cc | shi510/mlfe | aec8d52ddb54ce6f6e00a6515d7023ffba9d02f0 | [
"MIT"
] | 4 | 2018-01-08T12:40:22.000Z | 2021-12-02T05:23:36.000Z | #include <gtest/gtest.h>
#include <mlfe/operators/maxpool2d.h>
#include <mlfe/utils/gradient_checker.h>
#include <random>
using namespace mlfe;
using namespace mlfe::operators;
namespace fn = mlfe::functional;
TEST(operator, maxpool2d_k2_s2){
using T = float;
constexpr int B = 1;
constexpr int C = 2;
constexpr int H = 4;
constexpr int W = 4;
auto x = fn::create_variable({B, H, W, C});
// x =
// [ 1 2 3 4 [ 1 5 9 13
// 5 6 7 8 2 6 10 14
// 9 10 11 12 3 7 11 15
// 13 14 15 16 ] 4 8 12 16 ]
for(int h = 0; h < H; ++h){
for(int w = 0; w < W; ++w){
int idx = h * W * C + w * C + 0;
x.mutable_data<T>()[idx] = h * W + w + 1;
}
}
for(int w = 0; w < W; ++w){
for(int h = 0; h < H; ++h){
int idx = h * W * C + w * C + 1;
x.mutable_data<T>()[idx] = w * H + h + 1;
}
}
auto y = maxpool2d(x, {2, 2}, {2, 2});
auto y_ptr = y.data<T>();
//y(0, 0, 0) = max(1, 2, 5, 6) = 6
EXPECT_EQ(y_ptr[0], 6);
//y(0, 0, 1) = max(1, 5, 2, 6) = 6
EXPECT_EQ(y_ptr[1], 6);
//y(0, 1, 0) = max(3, 4, 7, 8) = 8
EXPECT_EQ(y_ptr[2], 8);
//y(0, 1, 1) = max(9, 10, 13, 14) = 14
EXPECT_EQ(y_ptr[3], 14);
//y(1, 0, 0) = max(9, 13, 10, 14) = 14
EXPECT_EQ(y_ptr[4], 14);
//y(1, 0, 1) = max(3, 7, 4, 8) = 8
EXPECT_EQ(y_ptr[5], 8);
//y(1, 1, 0) = max(11, 12, 15, 16) = 16
EXPECT_EQ(y_ptr[6], 16);
//y(1, 1, 1) = max(11, 15, 12, 16) = 16
EXPECT_EQ(y_ptr[7], 16);
}
TEST(operator, maxpool2d_grad_manual_k2_s2){
using T = float;
constexpr int B = 1;
constexpr int C = 2;
constexpr int H = 4;
constexpr int W = 4;
auto x = fn::create_variable({B, H, W, C});
// x =
// [ 1 2 3 4 [ 1 5 9 13
// 5 6 7 8 2 6 10 14
// 9 10 11 12 3 7 11 15
// 13 14 15 16 ] 4 8 12 16 ]
for(int h = 0; h < H; ++h){
for(int w = 0; w < W; ++w){
int idx = h * W * C + w * C + 0;
x.mutable_data<T>()[idx] = h * W + w + 1;
}
}
for(int w = 0; w < W; ++w){
for(int h = 0; h < H; ++h){
int idx = h * W * C + w * C + 1;
x.mutable_data<T>()[idx] = w * H + h + 1;
}
}
auto y = maxpool2d(x, {2, 2}, {2, 2});
y.backprop();
auto dx_ptr = x.grad().data<T>();
EXPECT_EQ(dx_ptr[0], 0);
EXPECT_EQ(dx_ptr[1], 0);
EXPECT_EQ(dx_ptr[2], 0);
EXPECT_EQ(dx_ptr[3], 0);
EXPECT_EQ(dx_ptr[4], 0);
EXPECT_EQ(dx_ptr[5], 0);
EXPECT_EQ(dx_ptr[6], 0);
EXPECT_EQ(dx_ptr[7], 0);
EXPECT_EQ(dx_ptr[8], 0);
EXPECT_EQ(dx_ptr[9], 0);
EXPECT_EQ(dx_ptr[10], 1);
EXPECT_EQ(dx_ptr[11], 1);
EXPECT_EQ(dx_ptr[12], 0);
EXPECT_EQ(dx_ptr[13], 0);
EXPECT_EQ(dx_ptr[14], 1);
EXPECT_EQ(dx_ptr[15], 1);
EXPECT_EQ(dx_ptr[16 + 0], 0);
EXPECT_EQ(dx_ptr[16 + 1], 0);
EXPECT_EQ(dx_ptr[16 + 2], 0);
EXPECT_EQ(dx_ptr[16 + 3], 0);
EXPECT_EQ(dx_ptr[16 + 4], 0);
EXPECT_EQ(dx_ptr[16 + 5], 0);
EXPECT_EQ(dx_ptr[16 + 6], 0);
EXPECT_EQ(dx_ptr[16 + 7], 0);
EXPECT_EQ(dx_ptr[16 + 8], 0);
EXPECT_EQ(dx_ptr[16 + 9], 0);
EXPECT_EQ(dx_ptr[16 + 10], 1);
EXPECT_EQ(dx_ptr[16 + 11], 1);
EXPECT_EQ(dx_ptr[16 + 12], 0);
EXPECT_EQ(dx_ptr[16 + 13], 0);
EXPECT_EQ(dx_ptr[16 + 14], 1);
EXPECT_EQ(dx_ptr[16 + 15], 1);
} | 25.489051 | 53 | 0.471363 | shi510 |
4ee29d5c6af77bc3a98271fac17a1572e89c63c0 | 1,160 | cpp | C++ | catboost/libs/helpers/ut/sample_ut.cpp | jochenater/catboost | de2786fbc633b0d6ea6a23b3862496c6151b95c2 | [
"Apache-2.0"
] | 6,989 | 2017-07-18T06:23:18.000Z | 2022-03-31T15:58:36.000Z | catboost/libs/helpers/ut/sample_ut.cpp | birichie/catboost | de75c6af12cf490700e76c22072fbdc15b35d679 | [
"Apache-2.0"
] | 1,978 | 2017-07-18T09:17:58.000Z | 2022-03-31T14:28:43.000Z | catboost/libs/helpers/ut/sample_ut.cpp | birichie/catboost | de75c6af12cf490700e76c22072fbdc15b35d679 | [
"Apache-2.0"
] | 1,228 | 2017-07-18T09:03:13.000Z | 2022-03-29T05:57:40.000Z | #include <catboost/libs/helpers/sample.h>
#include <util/generic/hash_set.h>
#include <library/cpp/testing/unittest/registar.h>
using namespace NCB;
Y_UNIT_TEST_SUITE(TSampleIndicesTest) {
template<class T>
void CheckOneCase(size_t n, size_t k) {
TRestorableFastRng64 rand(0);
const TVector<T> sampledIndices = SampleIndices<T>(n, k, &rand);
UNIT_ASSERT_VALUES_EQUAL(sampledIndices.size(), k);
THashSet<T> sampledIndicesSet;
for (auto index : sampledIndices) {
UNIT_ASSERT((size_t)index >= (T)0);
UNIT_ASSERT((size_t)index < n);
UNIT_ASSERT(!sampledIndicesSet.contains(index));
sampledIndicesSet.insert(index);
}
}
Y_UNIT_TEST(Simple) {
CheckOneCase<int>(0, 0);
CheckOneCase<int>(1, 0);
CheckOneCase<int>(1, 1);
CheckOneCase<int>(2, 2);
CheckOneCase<ui32>(100, 100);
CheckOneCase<ui32>(100, 0);
CheckOneCase<ui32>(100, 1);
CheckOneCase<ui64>(1000, 20);
CheckOneCase<ui64>(935, 34);
CheckOneCase<ui64>(935, 623);
CheckOneCase<ui64>(935, 935);
}
}
| 26.976744 | 72 | 0.615517 | jochenater |
4ee3fdadfd9b232f59bcc391252582692619b014 | 735 | cpp | C++ | 3. Longest Substring Without Repeating Characters.cpp | TIAN-2001/leetcode | 90374b976a1db24c0cb4ebf25593aad0207e3706 | [
"Apache-2.0"
] | null | null | null | 3. Longest Substring Without Repeating Characters.cpp | TIAN-2001/leetcode | 90374b976a1db24c0cb4ebf25593aad0207e3706 | [
"Apache-2.0"
] | null | null | null | 3. Longest Substring Without Repeating Characters.cpp | TIAN-2001/leetcode | 90374b976a1db24c0cb4ebf25593aad0207e3706 | [
"Apache-2.0"
] | null | null | null | // sliding window / two pointers
class Solution {
public:
int lengthOfLongestSubstring(string s) {
int res = 0;
if(s.length() == 0)
return res;
int left = 0;
int right = 0;
unordered_map<char,int> mp;
char c;
while(right < s.length()){
c = s[right];
mp[c] += 1;
if(mp[c] == 1){
res = max(res, right - left + 1);
} else {
while(mp[c] > 1){
char cl = s[left];
--mp[cl];
++left;
}
}
++right;
}
return res;
}
}; | 22.96875 | 62 | 0.334694 | TIAN-2001 |
4ee47dc1579a574eed49824fe47fd23fbd770b78 | 6,376 | cc | C++ | components/variations/field_trial_config/field_trial_util.cc | zipated/src | 2b8388091c71e442910a21ada3d97ae8bc1845d3 | [
"BSD-3-Clause"
] | 2,151 | 2020-04-18T07:31:17.000Z | 2022-03-31T08:39:18.000Z | components/variations/field_trial_config/field_trial_util.cc | cangulcan/src | 2b8388091c71e442910a21ada3d97ae8bc1845d3 | [
"BSD-3-Clause"
] | 395 | 2020-04-18T08:22:18.000Z | 2021-12-08T13:04:49.000Z | components/variations/field_trial_config/field_trial_util.cc | cangulcan/src | 2b8388091c71e442910a21ada3d97ae8bc1845d3 | [
"BSD-3-Clause"
] | 338 | 2020-04-18T08:03:10.000Z | 2022-03-29T12:33:22.000Z | // Copyright 2014 The Chromium Authors. All rights reserved.
// Use of this source code is governed by a BSD-style license that can be
// found in the LICENSE file.
#include "components/variations/field_trial_config/field_trial_util.h"
#include <stddef.h>
#include <string>
#include <vector>
#include "base/command_line.h"
#include "base/feature_list.h"
#include "base/metrics/field_trial.h"
#include "base/strings/string_split.h"
#include "base/strings/stringprintf.h"
#include "components/variations/field_trial_config/fieldtrial_testing_config.h"
#include "components/variations/variations_associated_data.h"
#include "net/base/escape.h"
namespace variations {
namespace {
void AssociateParamsFromExperiment(
const std::string& study_name,
const FieldTrialTestingExperiment& experiment,
base::FeatureList* feature_list) {
if (experiment.params_size != 0) {
std::map<std::string, std::string> params;
for (size_t i = 0; i < experiment.params_size; ++i) {
const FieldTrialTestingExperimentParams& param = experiment.params[i];
params[param.key] = param.value;
}
AssociateVariationParams(study_name, experiment.name, params);
}
base::FieldTrial* trial =
base::FieldTrialList::CreateFieldTrial(study_name, experiment.name);
if (!trial) {
DLOG(WARNING) << "Field trial config study skipped: " << study_name
<< "." << experiment.name
<< " (it is overridden from chrome://flags)";
return;
}
for (size_t i = 0; i < experiment.enable_features_size; ++i) {
feature_list->RegisterFieldTrialOverride(
experiment.enable_features[i],
base::FeatureList::OVERRIDE_ENABLE_FEATURE, trial);
}
for (size_t i = 0; i < experiment.disable_features_size; ++i) {
feature_list->RegisterFieldTrialOverride(
experiment.disable_features[i],
base::FeatureList::OVERRIDE_DISABLE_FEATURE, trial);
}
}
// Chooses an experiment taking into account the command line. Defaults to
// picking the first experiment.
const FieldTrialTestingExperiment& ChooseExperiment(
const FieldTrialTestingExperiment experiments[],
size_t experiment_size) {
DCHECK_GT(experiment_size, 0ul);
const auto& command_line = *base::CommandLine::ForCurrentProcess();
size_t chosen_index = 0;
for (size_t i = 1; i < experiment_size && chosen_index == 0; ++i) {
const auto& experiment = experiments[i];
if (experiment.forcing_flag &&
command_line.HasSwitch(experiment.forcing_flag)) {
chosen_index = i;
break;
}
}
DCHECK_GT(experiment_size, chosen_index);
return experiments[chosen_index];
}
} // namespace
std::string UnescapeValue(const std::string& value) {
return net::UnescapeURLComponent(
value, net::UnescapeRule::PATH_SEPARATORS |
net::UnescapeRule::URL_SPECIAL_CHARS_EXCEPT_PATH_SEPARATORS);
}
std::string EscapeValue(const std::string& value) {
// This needs to be the inverse of UnescapeValue in the anonymous namespace
// above.
std::string net_escaped_str =
net::EscapeQueryParamValue(value, true /* use_plus */);
// net doesn't escape '.' and '*' but UnescapeValue() covers those cases.
std::string escaped_str;
escaped_str.reserve(net_escaped_str.length());
for (const char ch : net_escaped_str) {
if (ch == '.')
escaped_str.append("%2E");
else if (ch == '*')
escaped_str.append("%2A");
else
escaped_str.push_back(ch);
}
return escaped_str;
}
bool AssociateParamsFromString(const std::string& varations_string) {
// Format: Trial1.Group1:k1/v1/k2/v2,Trial2.Group2:k1/v1/k2/v2
std::set<std::pair<std::string, std::string>> trial_groups;
for (const base::StringPiece& experiment_group : base::SplitStringPiece(
varations_string, ",",
base::TRIM_WHITESPACE, base::SPLIT_WANT_ALL)) {
std::vector<base::StringPiece> experiment = base::SplitStringPiece(
experiment_group, ":", base::TRIM_WHITESPACE, base::SPLIT_WANT_ALL);
if (experiment.size() != 2) {
DLOG(ERROR) << "Experiment and params should be separated by ':'";
return false;
}
std::vector<std::string> group_parts = base::SplitString(
experiment[0], ".", base::TRIM_WHITESPACE, base::SPLIT_WANT_ALL);
if (group_parts.size() != 2) {
DLOG(ERROR) << "Trial and group name should be separated by '.'";
return false;
}
std::vector<std::string> key_values = base::SplitString(
experiment[1], "/", base::TRIM_WHITESPACE, base::SPLIT_WANT_ALL);
if (key_values.size() % 2 != 0) {
DLOG(ERROR) << "Param name and param value should be separated by '/'";
return false;
}
std::string trial = UnescapeValue(group_parts[0]);
std::string group = UnescapeValue(group_parts[1]);
auto trial_group = std::make_pair(trial, group);
if (trial_groups.find(trial_group) != trial_groups.end()) {
DLOG(ERROR) << base::StringPrintf(
"A (trial, group) pair listed more than once. (%s, %s)",
trial.c_str(), group.c_str());
return false;
}
trial_groups.insert(trial_group);
std::map<std::string, std::string> params;
for (size_t i = 0; i < key_values.size(); i += 2) {
std::string key = UnescapeValue(key_values[i]);
std::string value = UnescapeValue(key_values[i + 1]);
params[key] = value;
}
bool result = AssociateVariationParams(trial, group, params);
if (!result) {
DLOG(ERROR) << "Failed to associate variation params for group \""
<< group << "\" in trial \"" << trial << "\"";
return false;
}
}
return true;
}
void AssociateParamsFromFieldTrialConfig(const FieldTrialTestingConfig& config,
base::FeatureList* feature_list) {
for (size_t i = 0; i < config.studies_size; ++i) {
const FieldTrialTestingStudy& study = config.studies[i];
if (study.experiments_size > 0) {
AssociateParamsFromExperiment(
study.name,
ChooseExperiment(study.experiments, study.experiments_size),
feature_list);
} else {
DLOG(ERROR) << "Unexpected empty study: " << study.name;
}
}
}
void AssociateDefaultFieldTrialConfig(base::FeatureList* feature_list) {
AssociateParamsFromFieldTrialConfig(kFieldTrialConfig, feature_list);
}
} // namespace variations
| 35.820225 | 79 | 0.675502 | zipated |
4ee600fac45e55d775f4ed0e974b4dafa265f1c4 | 2,216 | cc | C++ | src/logkafka/file_position_entry.cc | Qihoo360/logkafka | f329b5a9806e0b0f716884759edbe54e72e4dec0 | [
"MIT"
] | 568 | 2015-06-23T07:41:50.000Z | 2022-03-30T11:32:05.000Z | src/logkafka/file_position_entry.cc | Qihoo360/logkafka | f329b5a9806e0b0f716884759edbe54e72e4dec0 | [
"MIT"
] | 26 | 2015-09-27T07:25:31.000Z | 2021-07-25T13:30:09.000Z | src/logkafka/file_position_entry.cc | Qihoo360/logkafka | f329b5a9806e0b0f716884759edbe54e72e4dec0 | [
"MIT"
] | 138 | 2015-06-23T07:41:50.000Z | 2021-12-13T02:31:40.000Z | ///////////////////////////////////////////////////////////////////////////
//
// logkafka - Collect logs and send lines to Apache Kafka v0.8+
//
///////////////////////////////////////////////////////////////////////////
//
// Copyright (c) 2015 Qihoo 360 Technology Co., Ltd. All rights reserved.
//
// Licensed under the MIT License, Version 2.0 (the "License");
// you may not use this file except in compliance with the License.
// You may obtain a copy of the License at
//
// http://opensource.org/licenses/MIT
//
// Unless required by applicable law or agreed to in writing, software
// distributed under the License is distributed on an "AS IS" BASIS,
// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
// See the License for the specific language governing permissions and
// limitations under the License.
//
///////////////////////////////////////////////////////////////////////////
#include "logkafka/file_position_entry.h"
namespace logkafka {
const size_t FilePositionEntry::POS_SIZE = 16;
const size_t FilePositionEntry::INO_OFFSET = 17;
const size_t FilePositionEntry::INO_SIZE = 8;
const int FilePositionEntry::LN_OFFSET = 25;
const int FilePositionEntry::SIZE = 26;
FilePositionEntry::FilePositionEntry(FILE *file, off_t seek)
{/*{{{*/
m_file = file;
m_seek = seek;
}/*}}}*/
bool FilePositionEntry::update(ino_t inode, off_t pos)
{/*{{{*/
fseek(m_file, m_seek, SEEK_SET);
fprintf(m_file, "%016llx\t%08x",
(unsigned long long)pos, (unsigned int)inode);
return true;
}/*}}}*/
bool FilePositionEntry::updatePos(off_t pos)
{/*{{{*/
fseek(m_file, m_seek, SEEK_SET);
fprintf(m_file, "%016llx", (unsigned long long)pos);
return true;
}/*}}}*/
off_t FilePositionEntry::readPos()
{/*{{{*/
fseek(m_file, m_seek, SEEK_SET);
char buf[POS_SIZE + 1] = {'\0'};
return (1 == fread(buf, POS_SIZE, 1, m_file)) ?
hexstr2num(buf, -1): -1;
}/*}}}*/
ino_t FilePositionEntry::readInode()
{/*{{{*/
fseek(m_file, m_seek + INO_OFFSET, SEEK_SET);
char buf[INO_SIZE + 1] = {'\0'};
return (1 == fread(buf, INO_SIZE, 1, m_file)) ?
hexstr2num(buf, INO_NONE): INO_NONE;
}/*}}}*/
} // namespace logkafka
| 30.777778 | 75 | 0.603791 | Qihoo360 |
4ee9a23806391c6723a2a998e4565d221823d456 | 337 | hpp | C++ | src/graphics/TestWindow.hpp | TobiasNienhaus/npp | ff6023ad5c160240cbaa029dce065b2cdf58ae74 | [
"MIT"
] | null | null | null | src/graphics/TestWindow.hpp | TobiasNienhaus/npp | ff6023ad5c160240cbaa029dce065b2cdf58ae74 | [
"MIT"
] | null | null | null | src/graphics/TestWindow.hpp | TobiasNienhaus/npp | ff6023ad5c160240cbaa029dce065b2cdf58ae74 | [
"MIT"
] | null | null | null | //
// Created by Tobias on 1/5/2021.
//
#ifndef NPP_TESTWINDOW_HPP
#define NPP_TESTWINDOW_HPP
#include "Win32Context.hpp"
class TestWindow : public Win32Context<TestWindow> {
public:
[[nodiscard]] LPCWSTR class_name() const override;
LRESULT handle_message(UINT msg, WPARAM wp, LPARAM lp) override;
};
#endif // NPP_TESTWINDOW_HPP
| 19.823529 | 65 | 0.759644 | TobiasNienhaus |
4eea6555b105295ce9dad341ada76a386bc7f836 | 2,539 | cpp | C++ | src/anytime.cpp | erdos-project/frenet-optimal-trajectory-planner | ba0cb5662a0e2ea668b1c2b2951c0f6b84f44f5b | [
"Apache-2.0"
] | null | null | null | src/anytime.cpp | erdos-project/frenet-optimal-trajectory-planner | ba0cb5662a0e2ea668b1c2b2951c0f6b84f44f5b | [
"Apache-2.0"
] | null | null | null | src/anytime.cpp | erdos-project/frenet-optimal-trajectory-planner | ba0cb5662a0e2ea668b1c2b2951c0f6b84f44f5b | [
"Apache-2.0"
] | 1 | 2020-03-07T01:49:50.000Z | 2020-03-07T01:49:50.000Z | #include "AnytimeFrenetOptimalTrajectory.h"
#include "FrenetPath.h"
#include "py_cpp_struct.h"
#include <iostream>
#include <assert.h>
#include <unistd.h>
using namespace std;
int main() {
double wx [25] = {132.67, 128.67, 124.67, 120.67, 116.67, 112.67, 108.67,
104.67, 101.43, 97.77, 94.84, 92.89, 92.4 , 92.4 ,
92.4 , 92.4 , 92.4 , 92.4 , 92.4 , 92.39, 92.39,
92.39, 92.39, 92.39, 92.39};
double wy [25] = {195.14, 195.14, 195.14, 195.14, 195.14, 195.14, 195.14,
195.14, 195.14, 195.03, 193.88, 191.75, 188.72, 185.32,
181.32, 177.32, 173.32, 169.32, 165.32, 161.32, 157.32,
153.32, 149.32, 145.32, 141.84};
double o_llx[1] = {92.89};
double o_lly[1] = {191.75};
double o_urx[1] = {92.89};
double o_ury[1] = {191.75};
// set up experiment
FrenetInitialConditions fot_ic = {
34.6,
7.10964962,
-1.35277168,
-1.86,
0.0,
10,
wx,
wy,
25,
o_llx,
o_lly,
o_urx,
o_ury,
1
};
FrenetHyperparameters fot_hp = {
25.0,
15.0,
15.0,
5.0,
5.0,
0.5,
0.2,
5.0,
2.0,
0.5,
2.0,
0.1,
1.0,
0.1,
0.1,
0.1,
0.1,
0.1,
1.0,
1.0,
2 // num thread
};
// run experiment
AnytimeFrenetOptimalTrajectory fot = AnytimeFrenetOptimalTrajectory(&fot_ic, &fot_hp);
fot.asyncPlan(); // start planning
const int NUM_ITER = 50;
const int TEST_INTERVAL_TIME = 2; // in microseconds
double prev_final_cf = INFINITY;
double curr_cf;
for (int i = 0; i < NUM_ITER; i ++) {
FrenetPath* curr_frenet_path = fot.getBestPath();
if (curr_frenet_path) {
curr_cf = curr_frenet_path->cf;
cout << "Found Valid Path with Cost: " << curr_cf << "\n";
} else {
curr_cf = INFINITY;
cout << "No Valid Path Found\n";
}
// anytime algo consistency test, cost should only reduce or stay unchanged
// assert(curr_cf > prev_final_cf);
if (prev_final_cf < curr_cf) {
cout << "Not Consistent\n";
return -1;
}
prev_final_cf = curr_cf;
usleep(TEST_INTERVAL_TIME);
}
cout << "All iterations are consistent\n";
fot.stopPlanning();
return 0;
} | 24.413462 | 90 | 0.493895 | erdos-project |
4eeb627169bedae2d2155591f0d9cbfc63e7cb55 | 2,824 | cpp | C++ | vm/external_libs/llvm/tools/llvmc2/llvmc.cpp | marnen/rubinius | 05b3f9789d01bada0604a7f09921c956bc9487e7 | [
"BSD-3-Clause"
] | 1 | 2016-05-08T16:58:14.000Z | 2016-05-08T16:58:14.000Z | vm/external_libs/llvm/tools/llvmc2/llvmc.cpp | taf2/rubinius | 493bfa2351fc509ca33d3bb03991c2e9c2b6dafa | [
"BSD-3-Clause"
] | null | null | null | vm/external_libs/llvm/tools/llvmc2/llvmc.cpp | taf2/rubinius | 493bfa2351fc509ca33d3bb03991c2e9c2b6dafa | [
"BSD-3-Clause"
] | null | null | null | //===--- llvmc.cpp - The LLVM Compiler Driver ------------------*- C++ -*-===//
//
// The LLVM Compiler Infrastructure
//
// This file is distributed under the University of Illinois Open
// Source License. See LICENSE.TXT for details.
//
//===----------------------------------------------------------------------===//
//
// This tool provides a single point of access to the LLVM
// compilation tools. It has many options. To discover the options
// supported please refer to the tools' manual page or run the tool
// with the --help option.
//
//===----------------------------------------------------------------------===//
#include "CompilationGraph.h"
#include "Tool.h"
#include "llvm/System/Path.h"
#include "llvm/Support/CommandLine.h"
#include <iostream>
#include <stdexcept>
#include <string>
namespace cl = llvm::cl;
namespace sys = llvm::sys;
using namespace llvmc;
// Built-in command-line options.
// External linkage here is intentional.
cl::list<std::string> InputFilenames(cl::Positional, cl::desc("<input file>"),
cl::ZeroOrMore);
cl::opt<std::string> OutputFilename("o", cl::desc("Output file name"),
cl::value_desc("file"));
cl::list<std::string> Languages("x",
cl::desc("Specify the language of the following input files"),
cl::ZeroOrMore);
cl::opt<bool> VerboseMode("v",
cl::desc("Enable verbose mode"));
cl::opt<bool> WriteGraph("write-graph",
cl::desc("Write compilation-graph.dot file"),
cl::Hidden);
cl::opt<bool> ViewGraph("view-graph",
cl::desc("Show compilation graph in GhostView"),
cl::Hidden);
namespace {
/// BuildTargets - A small wrapper for CompilationGraph::Build.
int BuildTargets(CompilationGraph& graph) {
int ret;
sys::Path tempDir(sys::Path::GetTemporaryDirectory());
try {
ret = graph.Build(tempDir);
}
catch(...) {
tempDir.eraseFromDisk(true);
throw;
}
tempDir.eraseFromDisk(true);
return ret;
}
}
int main(int argc, char** argv) {
try {
CompilationGraph graph;
cl::ParseCommandLineOptions(argc, argv,
"LLVM Compiler Driver (Work In Progress)");
PopulateCompilationGraph(graph);
if (WriteGraph) {
graph.writeGraph();
if (!ViewGraph)
return 0;
}
if (ViewGraph) {
graph.viewGraph();
return 0;
}
if (InputFilenames.empty()) {
std::cerr << "No input files.\n";
return 1;
}
return BuildTargets(graph);
}
catch(const std::exception& ex) {
std::cerr << ex.what() << '\n';
}
catch(...) {
std::cerr << "Unknown error!\n";
}
return 1;
}
| 27.417476 | 80 | 0.549929 | marnen |
4ef2b7d19d0802d49f65ebbc5eddc3e341ee57eb | 717 | cpp | C++ | src/propagation/types/value_context_ordering.cpp | RMGiroux/clangmetatool | 38071867d56a9c5dfa4fac1eb298b8058a026acd | [
"Apache-2.0"
] | null | null | null | src/propagation/types/value_context_ordering.cpp | RMGiroux/clangmetatool | 38071867d56a9c5dfa4fac1eb298b8058a026acd | [
"Apache-2.0"
] | null | null | null | src/propagation/types/value_context_ordering.cpp | RMGiroux/clangmetatool | 38071867d56a9c5dfa4fac1eb298b8058a026acd | [
"Apache-2.0"
] | null | null | null | #include "value_context_ordering.h"
namespace clangmetatool {
namespace propagation {
namespace types {
void ValueContextOrdering::print(std::ostream &stream, Value value) {
switch (value) {
case ValueContextOrdering::CONTROL_FLOW_MERGE:
stream << "Control flow merge";
break;
case ValueContextOrdering::CHANGED_BY_CODE:
stream << "Changed by code";
break;
default:
break;
}
}
} // namespace types
} // namespace propagation
} // namespace clangmetatool
std::ostream &operator<<(
std::ostream &stream,
clangmetatool::propagation::types::ValueContextOrdering::Value value) {
clangmetatool::propagation::types::ValueContextOrdering::print(stream, value);
return stream;
}
| 23.129032 | 80 | 0.728033 | RMGiroux |
4ef3bd8789d4e15e40a9dccdc5743feff5a98df6 | 519 | cpp | C++ | src/util/nm_log.cpp | nolmoonen/pbr | c5ed37795c8e67de1716762206fe7c58e9079ac0 | [
"MIT"
] | null | null | null | src/util/nm_log.cpp | nolmoonen/pbr | c5ed37795c8e67de1716762206fe7c58e9079ac0 | [
"MIT"
] | null | null | null | src/util/nm_log.cpp | nolmoonen/pbr | c5ed37795c8e67de1716762206fe7c58e9079ac0 | [
"MIT"
] | null | null | null | #include "nm_log.hpp"
const char *const nm_log::LEVEL_NAMES[] = {
"TRACE", "INFO ", "WARN ", "ERROR"
};
log_level_e nm_log::m_level = LOG_TRACE;
void nm_log::set_log_level(log_level_e t_level)
{
m_level = t_level;
}
void nm_log::log(log_level_e t_level, const char *t_format, ...)
{
if (t_level >= m_level) {
fprintf(stdout, "%s ", LEVEL_NAMES[t_level]);
va_list argptr;
va_start(argptr, t_format);
vfprintf(stdout, t_format, argptr);
va_end(argptr);
}
}
| 21.625 | 64 | 0.624277 | nolmoonen |
4ef3d0ae2a286a4ee6a1f5480b6113fdbe4af7e5 | 1,303 | cpp | C++ | src/main.cpp | dancol90/wifi-led-clock | d4d391226ddc26ff92fd894e184c5348953b3bfa | [
"MIT"
] | 2 | 2018-10-10T12:37:05.000Z | 2018-12-07T22:36:42.000Z | src/main.cpp | dancol90/wifi-led-clock | d4d391226ddc26ff92fd894e184c5348953b3bfa | [
"MIT"
] | null | null | null | src/main.cpp | dancol90/wifi-led-clock | d4d391226ddc26ff92fd894e184c5348953b3bfa | [
"MIT"
] | null | null | null | /*
Drivers (still services):
- [OK] Led display
- [OK] Time
- [OK] WiFi
- [OK] File System
List of needed services:
- [OK] Scroll management
- [OK] Configuration (over SPIFFS)
- [OK*] HTTP Server (?)
- [OK] NTP
- MQTT handling
*/
#include <Arduino.h>
#include "Service.hpp"
#include "drivers/LED.hpp"
#include "drivers/Clock.hpp"
#include "drivers/WiFi.hpp"
#include "drivers/FS.hpp"
#include "services/Scroll.hpp"
#include "services/HTTP.hpp"
#include "services/Registry.hpp"
#include "services/NTP.hpp"
#include "services/WebSocket.hpp"
#include "services/OTA.hpp"
#include "application/SlackApplication.hpp"
#include "application/ClockApplication.hpp"
void setup()
{
Serial.begin(115200);
Service* drivers[] = {
// "Priority" services & drivers
new FileSystemDriver(),
new RegistryService(),
// Drivers
new ClockDriver(),
new WiFiDriver(),
new LedMatrixDriver(),
// Services
new ScrollService(),
new HTTPService(),
new NTPService(),
new WebSocket(),
new OTAService(),
// Application
//new SlackApplication(),
new ClockApplication()
};
Service::InitAll();
}
void loop()
{
Service::SyncUpdate();
delay(0);
}
| 19.447761 | 43 | 0.6132 | dancol90 |
4ef4d8b1a1af8be443fee78f25a6ba05823fccf0 | 3,226 | cpp | C++ | cpp/varint/leveldb/varint.cpp | yyyshi/asshole_algorithm | 270460f2afcdb7a00a08979053e8cfb80ef93b5b | [
"Apache-2.0"
] | null | null | null | cpp/varint/leveldb/varint.cpp | yyyshi/asshole_algorithm | 270460f2afcdb7a00a08979053e8cfb80ef93b5b | [
"Apache-2.0"
] | null | null | null | cpp/varint/leveldb/varint.cpp | yyyshi/asshole_algorithm | 270460f2afcdb7a00a08979053e8cfb80ef93b5b | [
"Apache-2.0"
] | null | null | null | // encode
char* EncodeVarint32(char* dst, uint32_t v) {
// Operate on characters as unsigneds
uint8_t* ptr = reinterpret_cast<uint8_t*>(dst);
static const int B = 128;
if (v < (1 << 7)) {
*(ptr++) = v;
} else if (v < (1 << 14)) {
*(ptr++) = v | B;
*(ptr++) = v >> 7;
} else if (v < (1 << 21)) {
*(ptr++) = v | B;
*(ptr++) = (v >> 7) | B;
*(ptr++) = v >> 14;
} else if (v < (1 << 28)) {
*(ptr++) = v | B;
*(ptr++) = (v >> 7) | B;
*(ptr++) = (v >> 14) | B;
*(ptr++) = v >> 21;
} else {
*(ptr++) = v | B;
*(ptr++) = (v >> 7) | B;
*(ptr++) = (v >> 14) | B;
*(ptr++) = (v >> 21) | B;
*(ptr++) = v >> 28;
}
return reinterpret_cast<char*>(ptr);
}
char* EncodeVarint64(char* dst, uint64_t v) {
static const int B = 128;
uint8_t* ptr = reinterpret_cast<uint8_t*>(dst);
while (v >= B) {
*(ptr++) = v | B;
v >>= 7;
}
*(ptr++) = static_cast<uint8_t>(v);
return reinterpret_cast<char*>(ptr);
}
<!解码就是编码的逆过程,这里涉及到对Slice数据的解析
重点关注“GetVarint32Ptr()”,“GetVarint32PtrFallback()”
>
bool GetVarint32(Slice* input, uint32_t* value) {
const char* p = input->data();
const char* limit = p + input->size();
const char* q = GetVarint32Ptr(p, limit, value);
if (q == nullptr) {
return false;
} else {
*input = Slice(q, limit - q);
return true;
}
}
inline const char* GetVarint32Ptr(const char* p, const char* limit,
uint32_t* value) {
if (p < limit) {
uint32_t result = *(reinterpret_cast<const uint8_t*>(p));
if ((result & 128) == 0) {
<!128就是一个八位,最高位为1,其余位为0,
与128相与为0表示待解码的result<=127,所以长度就是一个字节
直接赋值给*Value即可。
>
*value = result;
return p + 1;
}
}
return GetVarint32PtrFallback(p, limit, value);
}
const char* GetVarint32PtrFallback(const char* p, const char* limit,
uint32_t* value) {
<!对于超过一个字节的长度编码,解码的过程就是按小端顺序,
每7位取出,然后移位来组装最后的实际长度,组装结束的表示就是MSB位为0>
uint32_t result = 0;
for (uint32_t shift = 0; shift <= 28 && p < limit; shift += 7) {
uint32_t byte = *(reinterpret_cast<const uint8_t*>(p));
p++;
if (byte & 128) {
// More bytes are present
result |= ((byte & 127) << shift);
} else {
result |= (byte << shift);
*value = result;
return reinterpret_cast<const char*>(p);
}
}
return nullptr;
}
<!Varint64位的流程可Varint32原理一样>
bool GetVarint64(Slice* input, uint64_t* value) {
const char* p = input->data();
const char* limit = p + input->size();
const char* q = GetVarint64Ptr(p, limit, value);
if (q == nullptr) {
return false;
} else {
*input = Slice(q, limit - q);
return true;
}
}
const char* GetVarint64Ptr(const char* p, const char* limit, uint64_t* value) {
uint64_t result = 0;
for (uint32_t shift = 0; shift <= 63 && p < limit; shift += 7) {
uint64_t byte = *(reinterpret_cast<const uint8_t*>(p));
p++;
if (byte & 128) {
// More bytes are present
result |= ((byte & 127) << shift);
} else {
result |= (byte << shift);
*value = result;
return reinterpret_cast<const char*>(p);
}
}
return nullptr;
}
| 26.442623 | 79 | 0.534408 | yyyshi |
4ef5cbcff6de89035266d99fb15b388ad952f900 | 22,080 | cpp | C++ | src/game/server/laserText.cpp | 35niavlys/teeworlds-fng2-mod | d73be893c060fb3832656679d7756a5c42bca7cc | [
"Zlib"
] | null | null | null | src/game/server/laserText.cpp | 35niavlys/teeworlds-fng2-mod | d73be893c060fb3832656679d7756a5c42bca7cc | [
"Zlib"
] | 3 | 2020-05-31T06:36:51.000Z | 2020-09-11T08:34:36.000Z | src/game/server/laserText.cpp | 35niavlys/teeworlds-fng2-mod | d73be893c060fb3832656679d7756a5c42bca7cc | [
"Zlib"
] | 1 | 2021-09-04T11:32:33.000Z | 2021-09-04T11:32:33.000Z | /* (c) Magnus Auvinen. See licence.txt in the root of the distribution for more information. */
/* If you are missing that file, acquire a complete release at teeworlds.com. */
#include <game/generated/protocol.h>
#include <game/server/gamecontext.h>
#include "laserText.h"
#include <string.h>
static const bool asciiTable[256][5][3] = {
{ {0,0,0}, {0,0,0}, {0,0,0}, {0,0,0}, {0,0,0} }, // ascii 0
{ {0,0,0}, {0,0,0}, {0,0,0}, {0,0,0}, {0,0,0} }, // ascii 1
{ {0,0,0}, {0,0,0}, {0,0,0}, {0,0,0}, {0,0,0} }, // ascii 2
{ {0,0,0}, {0,0,0}, {0,0,0}, {0,0,0}, {0,0,0} }, // ascii 3
{ {0,0,0}, {0,0,0}, {0,0,0}, {0,0,0}, {0,0,0} }, // ascii 4
{ {0,0,0}, {0,0,0}, {0,0,0}, {0,0,0}, {0,0,0} }, // ascii 5
{ {0,0,0}, {0,0,0}, {0,0,0}, {0,0,0}, {0,0,0} }, // ascii 6
{ {0,0,0}, {0,0,0}, {0,0,0}, {0,0,0}, {0,0,0} }, // ascii 7
{ {0,0,0}, {0,0,0}, {0,0,0}, {0,0,0}, {0,0,0} }, // ascii 8
{ {0,0,0}, {0,0,0}, {0,0,0}, {0,0,0}, {0,0,0} }, // ascii 9
{ {0,0,0}, {0,0,0}, {0,0,0}, {0,0,0}, {0,0,0} }, // ascii 10
{ {0,0,0}, {0,0,0}, {0,0,0}, {0,0,0}, {0,0,0} }, // ascii 11
{ {0,0,0}, {0,0,0}, {0,0,0}, {0,0,0}, {0,0,0} }, // ascii 12
{ {0,0,0}, {0,0,0}, {0,0,0}, {0,0,0}, {0,0,0} }, // ascii 13
{ {0,0,0}, {0,0,0}, {0,0,0}, {0,0,0}, {0,0,0} }, // ascii 14
{ {0,0,0}, {0,0,0}, {0,0,0}, {0,0,0}, {0,0,0} }, // ascii 15
{ {0,0,0}, {0,0,0}, {0,0,0}, {0,0,0}, {0,0,0} }, // ascii 16
{ {0,0,0}, {0,0,0}, {0,0,0}, {0,0,0}, {0,0,0} }, // ascii 17
{ {0,0,0}, {0,0,0}, {0,0,0}, {0,0,0}, {0,0,0} }, // ascii 18
{ {0,0,0}, {0,0,0}, {0,0,0}, {0,0,0}, {0,0,0} }, // ascii 19
{ {0,0,0}, {0,0,0}, {0,0,0}, {0,0,0}, {0,0,0} }, // ascii 20
{ {0,0,0}, {0,0,0}, {0,0,0}, {0,0,0}, {0,0,0} }, // ascii 21
{ {0,0,0}, {0,0,0}, {0,0,0}, {0,0,0}, {0,0,0} }, // ascii 22
{ {0,0,0}, {0,0,0}, {0,0,0}, {0,0,0}, {0,0,0} }, // ascii 23
{ {0,0,0}, {0,0,0}, {0,0,0}, {0,0,0}, {0,0,0} }, // ascii 24
{ {0,0,0}, {0,0,0}, {0,0,0}, {0,0,0}, {0,0,0} }, // ascii 25
{ {0,0,0}, {0,0,0}, {0,0,0}, {0,0,0}, {0,0,0} }, // ascii 26
{ {0,0,0}, {0,0,0}, {0,0,0}, {0,0,0}, {0,0,0} }, // ascii 27
{ {0,0,0}, {0,0,0}, {0,0,0}, {0,0,0}, {0,0,0} }, // ascii 28
{ {0,0,0}, {0,0,0}, {0,0,0}, {0,0,0}, {0,0,0} }, // ascii 29
{ {0,0,0}, {0,0,0}, {0,0,0}, {0,0,0}, {0,0,0} }, // ascii 30
{ {0,0,0}, {0,0,0}, {0,0,0}, {0,0,0}, {0,0,0} }, // ascii 31
{ {0,0,0}, {0,0,0}, {0,0,0}, {0,0,0}, {0,0,0} }, // ascii 32
{ {0,1,0}, {0,1,0}, {0,1,0}, {0,0,0}, {0,1,0} }, // ascii 33 !
{ {0,0,0}, {0,0,0}, {0,0,0}, {0,0,0}, {0,0,0} }, // ascii 34
{ {0,0,0}, {0,0,0}, {0,0,0}, {0,0,0}, {0,0,0} }, // ascii 35
{ {0,0,0}, {0,0,0}, {0,0,0}, {0,0,0}, {0,0,0} }, // ascii 36
{ {1,0,1}, {1,0,0}, {0,1,0}, {0,0,1}, {1,0,1} }, // ascii 37 %
{ {0,0,0}, {0,0,0}, {0,0,0}, {0,0,0}, {0,0,0} }, // ascii 38
{ {0,0,0}, {0,0,0}, {0,0,0}, {0,0,0}, {0,0,0} }, // ascii 39
{ {0,1,0}, {1,0,0}, {1,0,0}, {1,0,0}, {0,1,0} }, // ascii 40 (
{ {0,1,0}, {0,0,1}, {0,0,1}, {0,0,1}, {0,1,0} }, // ascii 41 )
{ {0,0,0}, {0,0,0}, {0,0,0}, {0,0,0}, {0,0,0} }, // ascii 42
{ {0,0,0}, {0,1,0}, {1,1,1}, {0,1,0}, {0,0,0} }, // ascii 43 +
{ {0,0,0}, {0,0,0}, {0,0,0}, {0,1,0}, {1,0,0} }, // ascii 44 ,
{ {0,0,0}, {0,0,0}, {1,1,1}, {0,0,0}, {0,0,0} }, // ascii 45 -
{ {0,0,0}, {0,0,0}, {0,0,0}, {0,0,0}, {0,1,0} }, // ascii 46 .
{ {0,0,0}, {0,0,1}, {0,1,0}, {1,0,0}, {0,0,0} }, // ascii 47 /
{ {1,1,1}, {1,0,1}, {1,0,1}, {1,0,1}, {1,1,1} }, // 0
{ {0,1,0}, {1,1,0}, {0,1,0}, {0,1,0}, {0,1,0} }, // 1
{ {1,1,1}, {0,0,1}, {1,1,1}, {1,0,0}, {1,1,1} }, // 2
{ {1,1,1}, {0,0,1}, {1,1,1}, {0,0,1}, {1,1,1} }, // 3
{ {1,0,1}, {1,0,1}, {1,1,1}, {0,0,1}, {0,0,1} }, // 4
{ {1,1,1}, {1,0,0}, {1,1,1}, {0,0,1}, {1,1,1} }, // 5
{ {1,1,1}, {1,0,0}, {1,1,1}, {1,0,1}, {1,1,1} }, // 6
{ {1,1,1}, {0,0,1}, {0,0,1}, {0,0,1}, {0,0,1} }, // 7
{ {1,1,1}, {1,0,1}, {1,1,1}, {1,0,1}, {1,1,1} }, // 8
{ {1,1,1}, {1,0,1}, {1,1,1}, {0,0,1}, {1,1,1} }, // 9
{ {0,0,0}, {0,1,0}, {0,0,0}, {0,1,0}, {0,0,0} }, // :
{ {0,0,0}, {0,0,0}, {0,0,0}, {0,0,0}, {0,0,0} }, // ascii 59
{ {0,0,0}, {0,0,0}, {0,0,0}, {0,0,0}, {0,0,0} }, // ascii 60
{ {0,0,0}, {1,1,1}, {0,0,0}, {1,1,1}, {0,0,0} }, // ascii 61 =
{ {0,0,0}, {0,0,0}, {0,0,0}, {0,0,0}, {0,0,0} }, // ascii 62
{ {0,0,0}, {0,0,0}, {0,0,0}, {0,0,0}, {0,0,0} }, // ascii 63
{ {0,0,0}, {0,0,0}, {0,0,0}, {0,0,0}, {0,0,0} }, // ascii 64
{ {1,1,1}, {1,0,1}, {1,1,1}, {1,0,1}, {1,0,1} }, // A
{ {1,0,0}, {1,0,0}, {1,1,1}, {1,0,1}, {1,1,1} }, // B
{ {1,1,1}, {1,0,0}, {1,0,0}, {1,0,0}, {1,1,1} }, // C
{ {0,0,1}, {0,0,1}, {1,1,1}, {1,0,1}, {1,1,1} }, // D
{ {1,1,1}, {1,0,0}, {1,1,1}, {1,0,0}, {1,1,1} }, // E
{ {1,1,1}, {1,0,0}, {1,1,1}, {1,0,0}, {1,0,0} }, // F
{ {1,1,1}, {1,0,1}, {1,1,1}, {0,0,1}, {0,1,1} }, // G
{ {1,0,1}, {1,0,1}, {1,1,1}, {1,0,1}, {1,0,1} }, // H
{ {1,0,0}, {1,0,0}, {1,0,0}, {1,0,0}, {1,0,0} }, // I
{ {0,0,1}, {0,0,1}, {1,0,1}, {1,0,1}, {1,1,1} }, // J
{ {1,0,0}, {1,0,0}, {1,0,1}, {1,1,0}, {1,0,1} }, // K
{ {1,0,0}, {1,0,0}, {1,0,0}, {1,0,0}, {1,1,1} }, // L
{ {1,0,1}, {1,1,1}, {1,1,1}, {1,0,1}, {1,0,1} }, // M
{ {0,0,0}, {0,0,0}, {1,1,1}, {1,0,1}, {1,0,1} }, // N
{ {0,0,0}, {0,0,0}, {1,1,1}, {1,0,1}, {1,1,1} }, // O
{ {1,1,1}, {1,0,1}, {1,1,1}, {1,0,0}, {1,0,0} }, // P
{ {1,1,1}, {1,0,1}, {1,1,1}, {0,0,1}, {0,0,1} }, // Q
{ {0,0,0}, {1,0,1}, {1,1,0}, {1,0,0}, {1,0,0} }, // R
{ {0,1,1}, {1,0,0}, {0,1,0}, {0,0,1}, {1,1,0} }, // S
{ {1,1,1}, {0,1,0}, {0,1,0}, {0,1,0}, {0,1,0} }, // T
{ {0,0,0}, {0,0,0}, {1,0,1}, {1,0,1}, {1,1,1} }, // U
{ {0,0,0}, {0,0,0}, {1,0,1}, {1,1,1}, {0,1,0} }, // V
{ {1,0,1}, {1,0,1}, {1,1,1}, {1,1,1}, {1,1,1} }, // W
{ {0,0,0}, {0,0,0}, {1,0,1}, {0,1,0}, {1,0,1} }, // X
{ {1,0,1}, {1,0,1}, {1,1,1}, {0,1,0}, {0,1,0} }, // Y
{ {1,1,1}, {0,0,1}, {0,1,0}, {1,0,0}, {1,1,1} }, // Z
{ {0,0,0}, {0,0,0}, {0,0,0}, {0,0,0}, {0,0,0} }, // ascii 91
{ {0,0,0}, {0,0,0}, {0,0,0}, {0,0,0}, {0,0,0} }, // ascii 92
{ {0,0,0}, {0,0,0}, {0,0,0}, {0,0,0}, {0,0,0} }, // ascii 93
{ {0,0,0}, {0,0,0}, {0,0,0}, {0,0,0}, {0,0,0} }, // ascii 94
{ {0,0,0}, {0,0,0}, {0,0,0}, {0,0,0}, {0,0,0} }, // ascii 95
{ {0,0,0}, {0,0,0}, {0,0,0}, {0,0,0}, {0,0,0} }, // ascii 96
{ {0,0,0}, {0,0,0}, {0,0,0}, {0,0,0}, {0,0,0} }, // ascii 97
{ {0,0,0}, {0,0,0}, {0,0,0}, {0,0,0}, {0,0,0} }, // ascii 98
{ {0,0,0}, {0,0,0}, {0,0,0}, {0,0,0}, {0,0,0} }, // ascii 99
{ {0,0,0}, {0,0,0}, {0,0,0}, {0,0,0}, {0,0,0} }, // ascii 100
{ {0,0,0}, {0,0,0}, {0,0,0}, {0,0,0}, {0,0,0} }, // ascii 101
{ {0,0,0}, {0,0,0}, {0,0,0}, {0,0,0}, {0,0,0} }, // ascii 102
{ {0,0,0}, {0,0,0}, {0,0,0}, {0,0,0}, {0,0,0} }, // ascii 103
{ {0,0,0}, {0,0,0}, {0,0,0}, {0,0,0}, {0,0,0} }, // ascii 104
{ {0,0,0}, {0,0,0}, {0,0,0}, {0,0,0}, {0,0,0} }, // ascii 105
{ {0,0,0}, {0,0,0}, {0,0,0}, {0,0,0}, {0,0,0} }, // ascii 106
{ {0,0,0}, {0,0,0}, {0,0,0}, {0,0,0}, {0,0,0} }, // ascii 107
{ {0,0,0}, {0,0,0}, {0,0,0}, {0,0,0}, {0,0,0} }, // ascii 108
{ {0,0,0}, {0,0,0}, {0,0,0}, {0,0,0}, {0,0,0} }, // ascii 109
{ {0,0,0}, {0,0,0}, {0,0,0}, {0,0,0}, {0,0,0} }, // ascii 110
{ {0,0,0}, {0,0,0}, {0,0,0}, {0,0,0}, {0,0,0} }, // ascii 111
{ {0,0,0}, {0,0,0}, {0,0,0}, {0,0,0}, {0,0,0} }, // ascii 112
{ {0,0,0}, {0,0,0}, {0,0,0}, {0,0,0}, {0,0,0} }, // ascii 113
{ {0,0,0}, {0,0,0}, {0,0,0}, {0,0,0}, {0,0,0} }, // ascii 114
{ {0,0,0}, {0,0,0}, {0,0,0}, {0,0,0}, {0,0,0} }, // ascii 115
{ {0,0,0}, {0,0,0}, {0,0,0}, {0,0,0}, {0,0,0} }, // ascii 116
{ {0,0,0}, {0,0,0}, {0,0,0}, {0,0,0}, {0,0,0} }, // ascii 117
{ {0,0,0}, {0,0,0}, {0,0,0}, {0,0,0}, {0,0,0} }, // ascii 118
{ {0,0,0}, {0,0,0}, {0,0,0}, {0,0,0}, {0,0,0} }, // ascii 119
{ {0,0,0}, {0,0,0}, {0,0,0}, {0,0,0}, {0,0,0} }, // ascii 120
{ {0,0,0}, {0,0,0}, {0,0,0}, {0,0,0}, {0,0,0} }, // ascii 121
{ {0,0,0}, {0,0,0}, {0,0,0}, {0,0,0}, {0,0,0} }, // ascii 122
{ {0,0,0}, {0,0,0}, {0,0,0}, {0,0,0}, {0,0,0} }, // ascii 123
{ {0,0,0}, {0,0,0}, {0,0,0}, {0,0,0}, {0,0,0} }, // ascii 124
{ {0,0,0}, {0,0,0}, {0,0,0}, {0,0,0}, {0,0,0} }, // ascii 125
{ {0,0,0}, {0,0,0}, {0,0,0}, {0,0,0}, {0,0,0} }, // ascii 126
{ {0,0,0}, {0,0,0}, {0,0,0}, {0,0,0}, {0,0,0} }, // ascii 127
{ {0,0,0}, {0,0,0}, {0,0,0}, {0,0,0}, {0,0,0} }, // ascii 128
{ {0,0,0}, {0,0,0}, {0,0,0}, {0,0,0}, {0,0,0} }, // ascii 129
{ {0,0,0}, {0,0,0}, {0,0,0}, {0,0,0}, {0,0,0} }, // ascii 130
{ {0,0,0}, {0,0,0}, {0,0,0}, {0,0,0}, {0,0,0} }, // ascii 131
{ {0,0,0}, {0,0,0}, {0,0,0}, {0,0,0}, {0,0,0} }, // ascii 132
{ {0,0,0}, {0,0,0}, {0,0,0}, {0,0,0}, {0,0,0} }, // ascii 133
{ {0,0,0}, {0,0,0}, {0,0,0}, {0,0,0}, {0,0,0} }, // ascii 134
{ {0,0,0}, {0,0,0}, {0,0,0}, {0,0,0}, {0,0,0} }, // ascii 135
{ {0,0,0}, {0,0,0}, {0,0,0}, {0,0,0}, {0,0,0} }, // ascii 136
{ {0,0,0}, {0,0,0}, {0,0,0}, {0,0,0}, {0,0,0} }, // ascii 137
{ {0,0,0}, {0,0,0}, {0,0,0}, {0,0,0}, {0,0,0} }, // ascii 138
{ {0,0,0}, {0,0,0}, {0,0,0}, {0,0,0}, {0,0,0} }, // ascii 139
{ {0,0,0}, {0,0,0}, {0,0,0}, {0,0,0}, {0,0,0} }, // ascii 140
{ {0,0,0}, {0,0,0}, {0,0,0}, {0,0,0}, {0,0,0} }, // ascii 141
{ {0,0,0}, {0,0,0}, {0,0,0}, {0,0,0}, {0,0,0} }, // ascii 142
{ {0,0,0}, {0,0,0}, {0,0,0}, {0,0,0}, {0,0,0} }, // ascii 143
{ {0,0,0}, {0,0,0}, {0,0,0}, {0,0,0}, {0,0,0} }, // ascii 144
{ {0,0,0}, {0,0,0}, {0,0,0}, {0,0,0}, {0,0,0} }, // ascii 145
{ {0,0,0}, {0,0,0}, {0,0,0}, {0,0,0}, {0,0,0} }, // ascii 146
{ {0,0,0}, {0,0,0}, {0,0,0}, {0,0,0}, {0,0,0} }, // ascii 147
{ {0,0,0}, {0,0,0}, {0,0,0}, {0,0,0}, {0,0,0} }, // ascii 148
{ {0,0,0}, {0,0,0}, {0,0,0}, {0,0,0}, {0,0,0} }, // ascii 149
{ {0,0,0}, {0,0,0}, {0,0,0}, {0,0,0}, {0,0,0} }, // ascii 150
{ {0,0,0}, {0,0,0}, {0,0,0}, {0,0,0}, {0,0,0} }, // ascii 151
{ {0,0,0}, {0,0,0}, {0,0,0}, {0,0,0}, {0,0,0} }, // ascii 152
{ {0,0,0}, {0,0,0}, {0,0,0}, {0,0,0}, {0,0,0} }, // ascii 153
{ {0,0,0}, {0,0,0}, {0,0,0}, {0,0,0}, {0,0,0} }, // ascii 154
{ {0,0,0}, {0,0,0}, {0,0,0}, {0,0,0}, {0,0,0} }, // ascii 155
{ {0,0,0}, {0,0,0}, {0,0,0}, {0,0,0}, {0,0,0} }, // ascii 156
{ {0,0,0}, {0,0,0}, {0,0,0}, {0,0,0}, {0,0,0} }, // ascii 157
{ {0,0,0}, {0,0,0}, {0,0,0}, {0,0,0}, {0,0,0} }, // ascii 158
{ {0,0,0}, {0,0,0}, {0,0,0}, {0,0,0}, {0,0,0} }, // ascii 159
{ {0,0,0}, {0,0,0}, {0,0,0}, {0,0,0}, {0,0,0} }, // ascii 160
{ {0,0,0}, {0,0,0}, {0,0,0}, {0,0,0}, {0,0,0} }, // ascii 161
{ {0,0,0}, {0,0,0}, {0,0,0}, {0,0,0}, {0,0,0} }, // ascii 162
{ {0,0,0}, {0,0,0}, {0,0,0}, {0,0,0}, {0,0,0} }, // ascii 163
{ {0,0,0}, {0,0,0}, {0,0,0}, {0,0,0}, {0,0,0} }, // ascii 164
{ {0,0,0}, {0,0,0}, {0,0,0}, {0,0,0}, {0,0,0} }, // ascii 165
{ {0,0,0}, {0,0,0}, {0,0,0}, {0,0,0}, {0,0,0} }, // ascii 166
{ {0,0,0}, {0,0,0}, {0,0,0}, {0,0,0}, {0,0,0} }, // ascii 167
{ {0,0,0}, {0,0,0}, {0,0,0}, {0,0,0}, {0,0,0} }, // ascii 168
{ {0,0,0}, {0,0,0}, {0,0,0}, {0,0,0}, {0,0,0} }, // ascii 169
{ {0,0,0}, {0,0,0}, {0,0,0}, {0,0,0}, {0,0,0} }, // ascii 170
{ {0,0,0}, {0,0,0}, {0,0,0}, {0,0,0}, {0,0,0} }, // ascii 171
{ {0,0,0}, {0,0,0}, {0,0,0}, {0,0,0}, {0,0,0} }, // ascii 172
{ {0,0,0}, {0,0,0}, {0,0,0}, {0,0,0}, {0,0,0} }, // ascii 173
{ {0,0,0}, {0,0,0}, {0,0,0}, {0,0,0}, {0,0,0} }, // ascii 174
{ {0,0,0}, {0,0,0}, {0,0,0}, {0,0,0}, {0,0,0} }, // ascii 175
{ {0,0,0}, {0,0,0}, {0,0,0}, {0,0,0}, {0,0,0} }, // ascii 176
{ {0,0,0}, {0,0,0}, {0,0,0}, {0,0,0}, {0,0,0} }, // ascii 177
{ {0,0,0}, {0,0,0}, {0,0,0}, {0,0,0}, {0,0,0} }, // ascii 178
{ {0,0,0}, {0,0,0}, {0,0,0}, {0,0,0}, {0,0,0} }, // ascii 179
{ {0,0,0}, {0,0,0}, {0,0,0}, {0,0,0}, {0,0,0} }, // ascii 180
{ {0,0,0}, {0,0,0}, {0,0,0}, {0,0,0}, {0,0,0} }, // ascii 181
{ {0,0,0}, {0,0,0}, {0,0,0}, {0,0,0}, {0,0,0} }, // ascii 182
{ {0,0,0}, {0,0,0}, {0,0,0}, {0,0,0}, {0,0,0} }, // ascii 183
{ {0,0,0}, {0,0,0}, {0,0,0}, {0,0,0}, {0,0,0} }, // ascii 184
{ {0,0,0}, {0,0,0}, {0,0,0}, {0,0,0}, {0,0,0} }, // ascii 185
{ {0,0,0}, {0,0,0}, {0,0,0}, {0,0,0}, {0,0,0} }, // ascii 186
{ {0,0,0}, {0,0,0}, {0,0,0}, {0,0,0}, {0,0,0} }, // ascii 187
{ {0,0,0}, {0,0,0}, {0,0,0}, {0,0,0}, {0,0,0} }, // ascii 188
{ {0,0,0}, {0,0,0}, {0,0,0}, {0,0,0}, {0,0,0} }, // ascii 189
{ {0,0,0}, {0,0,0}, {0,0,0}, {0,0,0}, {0,0,0} }, // ascii 190
{ {0,0,0}, {0,0,0}, {0,0,0}, {0,0,0}, {0,0,0} }, // ascii 191
{ {0,0,0}, {0,0,0}, {0,0,0}, {0,0,0}, {0,0,0} }, // ascii 192
{ {0,0,0}, {0,0,0}, {0,0,0}, {0,0,0}, {0,0,0} }, // ascii 193
{ {0,0,0}, {0,0,0}, {0,0,0}, {0,0,0}, {0,0,0} }, // ascii 194
{ {0,0,0}, {0,0,0}, {0,0,0}, {0,0,0}, {0,0,0} }, // ascii 195
{ {0,0,0}, {0,0,0}, {0,0,0}, {0,0,0}, {0,0,0} }, // ascii 196
{ {0,0,0}, {0,0,0}, {0,0,0}, {0,0,0}, {0,0,0} }, // ascii 197
{ {0,0,0}, {0,0,0}, {0,0,0}, {0,0,0}, {0,0,0} }, // ascii 198
{ {0,0,0}, {0,0,0}, {0,0,0}, {0,0,0}, {0,0,0} }, // ascii 199
{ {0,0,0}, {0,0,0}, {0,0,0}, {0,0,0}, {0,0,0} }, // ascii 200
{ {0,0,0}, {0,0,0}, {0,0,0}, {0,0,0}, {0,0,0} }, // ascii 201
{ {0,0,0}, {0,0,0}, {0,0,0}, {0,0,0}, {0,0,0} }, // ascii 202
{ {0,0,0}, {0,0,0}, {0,0,0}, {0,0,0}, {0,0,0} }, // ascii 203
{ {0,0,0}, {0,0,0}, {0,0,0}, {0,0,0}, {0,0,0} }, // ascii 204
{ {0,0,0}, {0,0,0}, {0,0,0}, {0,0,0}, {0,0,0} }, // ascii 205
{ {0,0,0}, {0,0,0}, {0,0,0}, {0,0,0}, {0,0,0} }, // ascii 206
{ {0,0,0}, {0,0,0}, {0,0,0}, {0,0,0}, {0,0,0} }, // ascii 207
{ {0,0,0}, {0,0,0}, {0,0,0}, {0,0,0}, {0,0,0} }, // ascii 208
{ {0,0,0}, {0,0,0}, {0,0,0}, {0,0,0}, {0,0,0} }, // ascii 209
{ {0,0,0}, {0,0,0}, {0,0,0}, {0,0,0}, {0,0,0} }, // ascii 210
{ {0,0,0}, {0,0,0}, {0,0,0}, {0,0,0}, {0,0,0} }, // ascii 211
{ {0,0,0}, {0,0,0}, {0,0,0}, {0,0,0}, {0,0,0} }, // ascii 212
{ {0,0,0}, {0,0,0}, {0,0,0}, {0,0,0}, {0,0,0} }, // ascii 213
{ {0,0,0}, {0,0,0}, {0,0,0}, {0,0,0}, {0,0,0} }, // ascii 214
{ {0,0,0}, {0,0,0}, {0,0,0}, {0,0,0}, {0,0,0} }, // ascii 215
{ {0,0,0}, {0,0,0}, {0,0,0}, {0,0,0}, {0,0,0} }, // ascii 216
{ {0,0,0}, {0,0,0}, {0,0,0}, {0,0,0}, {0,0,0} }, // ascii 217
{ {0,0,0}, {0,0,0}, {0,0,0}, {0,0,0}, {0,0,0} }, // ascii 218
{ {0,0,0}, {0,0,0}, {0,0,0}, {0,0,0}, {0,0,0} }, // ascii 219
{ {0,0,0}, {0,0,0}, {0,0,0}, {0,0,0}, {0,0,0} }, // ascii 220
{ {0,0,0}, {0,0,0}, {0,0,0}, {0,0,0}, {0,0,0} }, // ascii 221
{ {0,0,0}, {0,0,0}, {0,0,0}, {0,0,0}, {0,0,0} }, // ascii 222
{ {0,0,0}, {0,0,0}, {0,0,0}, {0,0,0}, {0,0,0} }, // ascii 223
{ {0,0,0}, {0,0,0}, {0,0,0}, {0,0,0}, {0,0,0} }, // ascii 224
{ {0,0,0}, {0,0,0}, {0,0,0}, {0,0,0}, {0,0,0} }, // ascii 225
{ {0,0,0}, {0,0,0}, {0,0,0}, {0,0,0}, {0,0,0} }, // ascii 226
{ {0,0,0}, {0,0,0}, {0,0,0}, {0,0,0}, {0,0,0} }, // ascii 227
{ {0,0,0}, {0,0,0}, {0,0,0}, {0,0,0}, {0,0,0} }, // ascii 228
{ {0,0,0}, {0,0,0}, {0,0,0}, {0,0,0}, {0,0,0} }, // ascii 229
{ {0,0,0}, {0,0,0}, {0,0,0}, {0,0,0}, {0,0,0} }, // ascii 230
{ {0,0,0}, {0,0,0}, {0,0,0}, {0,0,0}, {0,0,0} }, // ascii 231
{ {0,0,0}, {0,0,0}, {0,0,0}, {0,0,0}, {0,0,0} }, // ascii 232
{ {0,0,0}, {0,0,0}, {0,0,0}, {0,0,0}, {0,0,0} }, // ascii 233
{ {0,0,0}, {0,0,0}, {0,0,0}, {0,0,0}, {0,0,0} }, // ascii 234
{ {0,0,0}, {0,0,0}, {0,0,0}, {0,0,0}, {0,0,0} }, // ascii 235
{ {0,0,0}, {0,0,0}, {0,0,0}, {0,0,0}, {0,0,0} }, // ascii 236
{ {0,0,0}, {0,0,0}, {0,0,0}, {0,0,0}, {0,0,0} }, // ascii 237
{ {0,0,0}, {0,0,0}, {0,0,0}, {0,0,0}, {0,0,0} }, // ascii 238
{ {0,0,0}, {0,0,0}, {0,0,0}, {0,0,0}, {0,0,0} }, // ascii 239
{ {0,0,0}, {0,0,0}, {0,0,0}, {0,0,0}, {0,0,0} }, // ascii 240
{ {0,0,0}, {0,0,0}, {0,0,0}, {0,0,0}, {0,0,0} }, // ascii 241
{ {0,0,0}, {0,0,0}, {0,0,0}, {0,0,0}, {0,0,0} }, // ascii 242
{ {0,0,0}, {0,0,0}, {0,0,0}, {0,0,0}, {0,0,0} }, // ascii 243
{ {0,0,0}, {0,0,0}, {0,0,0}, {0,0,0}, {0,0,0} }, // ascii 244
{ {0,0,0}, {0,0,0}, {0,0,0}, {0,0,0}, {0,0,0} }, // ascii 245
{ {0,0,0}, {0,0,0}, {0,0,0}, {0,0,0}, {0,0,0} }, // ascii 246
{ {0,0,0}, {0,0,0}, {0,0,0}, {0,0,0}, {0,0,0} }, // ascii 247
{ {0,0,0}, {0,0,0}, {0,0,0}, {0,0,0}, {0,0,0} }, // ascii 248
{ {0,0,0}, {0,0,0}, {0,0,0}, {0,0,0}, {0,0,0} }, // ascii 249
{ {0,0,0}, {0,0,0}, {0,0,0}, {0,0,0}, {0,0,0} }, // ascii 250
{ {0,0,0}, {0,0,0}, {0,0,0}, {0,0,0}, {0,0,0} }, // ascii 251
{ {0,0,0}, {0,0,0}, {0,0,0}, {0,0,0}, {0,0,0} }, // ascii 252
{ {0,0,0}, {0,0,0}, {0,0,0}, {0,0,0}, {0,0,0} }, // ascii 253
{ {0,0,0}, {0,0,0}, {0,0,0}, {0,0,0}, {0,0,0} }, // ascii 254
{ {0,0,0}, {0,0,0}, {0,0,0}, {0,0,0}, {0,0,0} } // ascii 255
};
CLaserText::CLaserText(CGameWorld *pGameWorld, vec2 Pos, int Owner, int pAliveTicks, char* pText, int pTextLen)
: CEntity(pGameWorld, CGameWorld::ENTTYPE_LASER)
{
m_Pos = Pos;
m_Owner = Owner;
GameWorld()->InsertEntity(this);
m_CurTicks = Server()->Tick();
m_StartTick = Server()->Tick();
m_AliveTicks = pAliveTicks;
m_TextLen = pTextLen;
m_Text = new char[pTextLen];
memcpy(m_Text, pText, pTextLen);
m_CharNum = 0;
for(int i = 0; i < m_TextLen; ++i){
for(int n = 0; n < 5; ++n){
for(int j = 0; j < 3; ++j){
if(asciiTable[(unsigned char)m_Text[i]][n][j]){
++m_CharNum;
}
}
}
}
m_Chars = new CLaserChar*[m_CharNum];
m_PosOffsetCharPoints = 15.0;
m_PosOffsetChars = m_PosOffsetCharPoints * 3.5;
int charCount = 0;
for(int i = 0; i < m_TextLen; ++i){
makeLaser(m_Text[i], i, charCount);
}
}
CLaserText::CLaserText(CGameWorld *pGameWorld, vec2 Pos, int Owner, int pAliveTicks, char* pText, int pTextLen, float pCharPointOffset, float pCharOffsetFactor)
: CEntity(pGameWorld, CGameWorld::ENTTYPE_LASER)
{
m_Pos = Pos;
m_Owner = Owner;
GameWorld()->InsertEntity(this);
m_CurTicks = Server()->Tick();
m_StartTick = Server()->Tick();
m_AliveTicks = pAliveTicks;
m_TextLen = pTextLen;
m_Text = new char[pTextLen];
memcpy(m_Text, pText, pTextLen);
m_CharNum = 0;
for(int i = 0; i < m_TextLen; ++i){
for(int n = 0; n < 5; ++n){
for(int j = 0; j < 3; ++j){
if(asciiTable[(unsigned char)m_Text[i]][n][j]){
++m_CharNum;
}
}
}
}
m_Chars = new CLaserChar*[m_CharNum];
m_PosOffsetCharPoints = pCharPointOffset;
m_PosOffsetChars = m_PosOffsetCharPoints * pCharOffsetFactor;
int charCount = 0;
for(int i = 0; i < m_TextLen; ++i){
makeLaser(m_Text[i], i, charCount);
}
}
void CLaserText::Reset()
{
GameServer()->m_World.DestroyEntity(this);
}
void CLaserText::Tick()
{
if(++m_CurTicks - m_StartTick > m_AliveTicks) GameServer()->m_World.DestroyEntity(this);
}
void CLaserText::TickPaused()
{
}
inline char NeighboursVert(const bool pCharVert[3], int pVertOff){
char neighbours = 0;
if(pVertOff > 0){
if(pCharVert[pVertOff - 1]) ++neighbours;
}
if(pVertOff < 2){
if(pCharVert[pVertOff + 1]) ++neighbours;
}
return neighbours;
}
inline char NeighboursHor(const bool pCharHor[5][3], int pHorOff, int pVertOff){
char neighbours = 0;
if(pHorOff > 0){
if(pCharHor[pHorOff - 1][pVertOff]) ++neighbours;
}
if(pHorOff < 4){
if(pCharHor[pHorOff + 1][pVertOff]) ++neighbours;
}
return neighbours;
}
void CLaserText::makeLaser(char pChar, int pCharOffset, int& charCount){
unsigned short tail[5][3];
char neighbourCount[5][3];
for(int n = 0; n < 5; ++n){
for(int j = 0; j < 3; ++j){
if(asciiTable[(unsigned char)pChar][n][j]){
neighbourCount[n][j] = 0;
neighbourCount[n][j] += NeighboursVert(asciiTable[(unsigned char)pChar][n], j);
neighbourCount[n][j] += NeighboursHor(asciiTable[(unsigned char)pChar], n, j);
tail[n][j] = 0;
} else tail[n][j] = (unsigned short)-1;
}
}
for(int n = 0; n < 5; ++n){
for(int j = 0; j < 3; ++j){
if(asciiTable[(unsigned char)pChar][n][j]){
//additional x, y offset to draw a line
int x = j, y = n;
int maxNeighbour = 0;
//forced line draw
bool forceLine = false;
if(j > 0){
if(asciiTable[(unsigned char)pChar][n][j - 1]){
if(tail[n][j - 1] != 0){
if(tail[n][j - 1] != (n << 8 | j)){
forceLine = true;
tail[n][j] = (n << 8 | (j - 1));
x = j - 1;
y = n;
}
} else if(neighbourCount[n][j - 1] > maxNeighbour){
maxNeighbour = neighbourCount[n][j - 1];
x = j - 1;
y = n;
}
}
}
if(!forceLine && j < 2){
if(asciiTable[(unsigned char)pChar][n][j + 1]){
if(tail[n][j + 1] != 0){
if(tail[n][j + 1] != (n << 8 | j)){
forceLine = true;
tail[n][j] = (n << 8 | (j + 1));
x = j + 1;
y = n;
}
} else if(neighbourCount[n][j + 1] > maxNeighbour){
maxNeighbour = neighbourCount[n][j + 1];
x = j + 1;
y = n;
}
}
}
if(!forceLine && n > 0){
if(asciiTable[(unsigned char)pChar][n - 1][j]){
if(tail[n - 1][j] != 0){
if(tail[n - 1][j] != (n << 8 | j)){
forceLine = true;
tail[n][j] = ((n-1) << 8 | (j));
x = j;
y = n - 1;
}
} else if(neighbourCount[n - 1][j] > maxNeighbour){
maxNeighbour = neighbourCount[n - 1][j];
x = j;
y = n - 1;
}
}
}
if(!forceLine && n < 4){
if(asciiTable[(unsigned char)pChar][n + 1][j]){
if(tail[n + 1][j] != 0){
if(tail[n + 1][j] != (n << 8 | j)){
forceLine = true;
tail[n][j] = ((n+1) << 8 | (j));
x = j;
y = n + 1;
}
} else if(neighbourCount[n + 1][j] > maxNeighbour){
maxNeighbour = neighbourCount[n + 1][j];
x = j;
y = n + 1;
}
}
}
if(!forceLine){
tail[n][j] = (y << 8 | x);
}
CLaserChar* pObj = (m_Chars[charCount] = new CLaserChar(GameWorld()));
pObj->m_Pos.x = m_Pos.x + pCharOffset * m_PosOffsetChars + j * m_PosOffsetCharPoints;
pObj->m_Pos.y = m_Pos.y + n * m_PosOffsetCharPoints;
pObj->m_Frompos.x = m_Pos.x + pCharOffset * m_PosOffsetChars + x * m_PosOffsetCharPoints;
pObj->m_Frompos.y = m_Pos.y + y * m_PosOffsetCharPoints;
++charCount;
}
}
}
}
void CLaserText::Snap(int SnappingClient)
{
if(NetworkClipped(SnappingClient))
return;
for(int i = 0; i < m_CharNum; ++i){
CNetObj_Laser *pObj = static_cast<CNetObj_Laser *>(Server()->SnapNewItem(NETOBJTYPE_LASER, m_Chars[i]->getID(), sizeof(CNetObj_Laser)));
if(!pObj)
return;
pObj->m_X = m_Chars[i]->m_Pos.x;
pObj->m_Y = m_Chars[i]->m_Pos.y;
pObj->m_FromX = m_Chars[i]->m_Frompos.x;
pObj->m_FromY = m_Chars[i]->m_Frompos.y;
pObj->m_StartTick = Server()->Tick();
}
}
| 43.722772 | 160 | 0.417029 | 35niavlys |
4ef77cb8295f8f1e90370c72d417ed17e70c0bd2 | 537 | hpp | C++ | engine/generators/crypts/include/ICryptLayoutStrategy.hpp | sidav/shadow-of-the-wyrm | 747afdeebed885b1a4f7ab42f04f9f756afd3e52 | [
"MIT"
] | null | null | null | engine/generators/crypts/include/ICryptLayoutStrategy.hpp | sidav/shadow-of-the-wyrm | 747afdeebed885b1a4f7ab42f04f9f756afd3e52 | [
"MIT"
] | null | null | null | engine/generators/crypts/include/ICryptLayoutStrategy.hpp | sidav/shadow-of-the-wyrm | 747afdeebed885b1a4f7ab42f04f9f756afd3e52 | [
"MIT"
] | null | null | null | #pragma once
#include <tuple>
#include "common.hpp"
#include "Directions.hpp"
#include "Map.hpp"
// Interface for defining crypt layout strategies. These operate on a
// given map and crypt boundary, producing the characteristic look of the
// crypt: pillars, rooms, a central vault, etc.
class ICryptLayoutStrategy
{
public:
virtual void create_layout(MapPtr map, const std::tuple<Coordinate, Coordinate, Coordinate>& stair_loc_and_room_boundary) = 0;
};
using ICryptLayoutStrategyPtr = std::shared_ptr<ICryptLayoutStrategy>;
| 29.833333 | 130 | 0.772812 | sidav |
f600003f47e60792dabea9657b35e02919c55e2e | 2,956 | hpp | C++ | common/SoapySSDPEndpoint.hpp | bastille-attic/SoapyRemote | 63664b890ccfe2d5472901b879b1593aacc92ef1 | [
"BSL-1.0"
] | null | null | null | common/SoapySSDPEndpoint.hpp | bastille-attic/SoapyRemote | 63664b890ccfe2d5472901b879b1593aacc92ef1 | [
"BSL-1.0"
] | null | null | null | common/SoapySSDPEndpoint.hpp | bastille-attic/SoapyRemote | 63664b890ccfe2d5472901b879b1593aacc92ef1 | [
"BSL-1.0"
] | null | null | null | // Copyright (c) 2015-2016 Josh Blum
// SPDX-License-Identifier: BSL-1.0
#pragma once
#include "SoapyRPCSocket.hpp"
#include <string>
#include <csignal> //sig_atomic_t
#include <mutex>
#include <vector>
#include <memory>
class SoapyHTTPHeader;
struct SoapySSDPEndpointData;
/*!
* Service an SSDP endpoint to:
* keep track of discovered servers of interest,
* and to respond to discovery packets for us.
*/
class SoapySSDPEndpoint
{
public:
//! Get a singleton instance of the endpoint
static std::shared_ptr<SoapySSDPEndpoint> getInstance(void);
/*!
* Create a discovery endpoint
*/
SoapySSDPEndpoint(void);
~SoapySSDPEndpoint(void);
/*!
* Allow the endpoint to advertise that its running the RPC service
*/
void registerService(const std::string &uuid, const std::string &service);
/*!
* Enable the client endpoint to search for running services.
*/
void enablePeriodicSearch(const bool enable);
/*!
* Enable the server to send periodic notification messages.
*/
void enablePeriodicNotify(const bool enable);
/*!
* Get a list of all active server URLs.
*
* The same endpoint can be discovered under both IPv4 and IPv6.
* When 'only' is false, the ipVer specifies the IP version preference
* when both are discovered but will fallback to the other version.
* But when 'only' is true, only addresses of the ipVer type are used.
*
* \param ipVer the preferred IP version to discover (6 or 4)
* \param only true to ignore other discovered IP versions
*/
std::vector<std::string> getServerURLs(const int ipVer = 4, const bool only = false);
private:
SoapySocketSession sess;
//protection between threads
std::mutex mutex;
//service settings
bool serviceRegistered;
std::string uuid;
std::string service;
//configured messages
bool periodicSearchEnabled;
bool periodicNotifyEnabled;
//server data
std::vector<SoapySSDPEndpointData *> handlers;
//signal done to the thread
sig_atomic_t done;
void spawnHandler(const std::string &bindAddr, const std::string &groupAddr, const int ipVer);
void handlerLoop(SoapySSDPEndpointData *data);
void sendHeader(SoapyRPCSocket &sock, const SoapyHTTPHeader &header, const std::string &addr);
void sendSearchHeader(SoapySSDPEndpointData *data);
void sendNotifyHeader(SoapySSDPEndpointData *data, const std::string &nts);
void handleSearchRequest(SoapySSDPEndpointData *data, const SoapyHTTPHeader &header, const std::string &addr);
void handleSearchResponse(SoapySSDPEndpointData *data, const SoapyHTTPHeader &header, const std::string &addr);
void handleNotifyRequest(SoapySSDPEndpointData *data, const SoapyHTTPHeader &header, const std::string &addr);
void handleRegisterService(SoapySSDPEndpointData *, const SoapyHTTPHeader &header, const std::string &recvAddr);
};
| 31.784946 | 116 | 0.715832 | bastille-attic |
f6005e2eaa3c6d0eeb1b64e27da3234b58af2f2f | 8,489 | cpp | C++ | src/engine.cpp | mbeckem/extpp | 06aa153ebf617c779e66d612cfc11e01869c602a | [
"MIT"
] | 1 | 2018-05-22T15:47:14.000Z | 2018-05-22T15:47:14.000Z | src/engine.cpp | mbeckem/prequel | 06aa153ebf617c779e66d612cfc11e01869c602a | [
"MIT"
] | null | null | null | src/engine.cpp | mbeckem/prequel | 06aa153ebf617c779e66d612cfc11e01869c602a | [
"MIT"
] | null | null | null | #include <prequel/engine.hpp>
#include <prequel/deferred.hpp>
#include <boost/intrusive/list.hpp>
#include <boost/intrusive/list_hook.hpp>
#include <boost/intrusive/set.hpp>
#include <boost/intrusive/set_hook.hpp>
namespace prequel {
namespace detail {
// This is the real implementation of block handles,
// it contains the additional boost intrusive anchors.
//
// The index of a block handle instance MUST NOT change because
// it is used for indexing by the block handle manager.
//
// TODO: Maybe switch to intrusive hash table instead?
class block_handle_internal final : public block_handle_base {
friend engine;
friend block_handle_manager;
// Block handles are linked together using the block index field.
boost::intrusive::set_member_hook<> index_hook;
// Linked together in a free list.
boost::intrusive::list_member_hook<> freelist_hook;
void reset() {
m_refcount = 0;
m_engine = nullptr;
m_index = block_index();
m_data = nullptr;
m_cookie = 0;
}
};
class block_handle_manager {
public:
block_handle_manager() = default;
~block_handle_manager() {
m_freelist.clear_and_dispose([](block_handle_internal* handle) { delete handle; });
}
block_handle_manager(const block_handle_manager&) = delete;
block_handle_manager& operator=(const block_handle_manager&) = delete;
auto begin() { return m_handles.begin(); }
auto end() { return m_handles.end(); }
void insert(block_handle_internal& handle) noexcept {
auto result = m_handles.insert(handle);
PREQUEL_ASSERT(result.second, "Insertion must have succeeded.");
unused(result);
}
void remove(block_handle_internal& handle) noexcept {
PREQUEL_ASSERT(contains(handle), "Block handle is not linked.");
m_handles.erase(m_handles.iterator_to(handle));
}
bool contains(block_handle_internal& handle) const noexcept {
return handle.index_hook.is_linked();
}
block_handle_internal* find(block_index index) noexcept {
auto iterator = m_handles.find(index);
if (iterator == m_handles.end())
return nullptr;
return &*iterator;
}
size_t size() const noexcept { return m_handles.size(); }
block_handle_internal* allocate() {
if (!m_freelist.empty()) {
block_handle_internal* handle = &m_freelist.front();
m_freelist.pop_front();
return handle;
}
return new block_handle_internal();
}
void free(block_handle_internal* handle) {
static constexpr u32 max = 1024;
if (!handle)
return;
if (m_freelist.size() >= max) {
delete handle;
return;
}
handle->reset();
m_freelist.push_front(*handle);
}
private:
struct block_handle_index {
using type = block_index;
block_index operator()(const block_handle_base& handle_base) const noexcept {
return handle_base.index();
}
};
using set_t = boost::intrusive::set<
block_handle_internal,
boost::intrusive::member_hook<block_handle_internal, boost::intrusive::set_member_hook<>,
&block_handle_internal::index_hook>,
boost::intrusive::key_of_value<block_handle_index>>;
using freelist_t = boost::intrusive::list<
block_handle_internal,
boost::intrusive::member_hook<block_handle_internal, boost::intrusive::list_member_hook<>,
&block_handle_internal::freelist_hook>>;
private:
set_t m_handles;
freelist_t m_freelist;
};
} // namespace detail
engine::engine(u32 block_size)
: m_block_size(block_size)
, m_handle_manager(new detail::block_handle_manager()) {
if (!is_pow2(block_size)) {
PREQUEL_THROW(bad_argument(fmt::format("Block size is not a power of two: {}.", block_size)));
}
m_block_size_log = log2(block_size);
m_offset_mask = m_block_size - 1;
}
engine::~engine() {
if (handle_manager().size() > 0) {
PREQUEL_ABORT("There are still block handles in use while the engine is being destroyed.");
}
}
u64 engine::size() const {
return do_size();
}
void engine::grow(u64 n) {
if (n > 0) {
do_grow(n);
}
}
void engine::flush() {
do_flush();
}
block_handle engine::read(block_index index) {
if (!index.valid()) {
PREQUEL_THROW(bad_argument("Invalid block index."));
}
return internal_populate_handle(index, initialize_block_t{});
}
block_handle engine::overwrite_zero(block_index index) {
if (!index.valid()) {
PREQUEL_THROW(bad_argument("Invalid block index."));
}
return internal_populate_handle(index, initialize_zero_t{});
}
block_handle engine::overwrite(block_index index, const byte* data, size_t size) {
if (!index.valid()) {
PREQUEL_THROW(bad_argument("Invalid block index."));
}
if (size > m_block_size) {
PREQUEL_THROW(bad_argument(fmt::format(
"Buffer is too large for a single block ({} bytes given, block size is {} bytes).",
size, m_block_size)));
}
return internal_populate_handle(index, initialize_data_t{data, size});
}
template<typename Initializer>
block_handle engine::internal_populate_handle(block_index index, Initializer&& init) {
static constexpr bool overwrite =
!std::is_same_v<remove_cvref_t<Initializer>, initialize_block_t>;
PREQUEL_ASSERT(index.valid(), "Invalid index.");
auto& manager = handle_manager();
// We might have a handle to this block already.
if (auto handle = manager.find(index)) {
PREQUEL_ASSERT(handle->m_refcount > 0,
"The handle must be referenced "
"if it can be found through the manager.");
if constexpr (overwrite) {
init.apply(handle->m_data, m_block_size);
do_dirty(index, handle->m_cookie);
}
return block_handle(handle);
}
// Prepare a handle for the new block.
auto handle = manager.allocate();
deferred cleanup_handle = [&] { manager.free(handle); };
// Read the block from disk. Don't initialize the contents
// if we're about to overwrite them anyway.
pin_result pinned = do_pin(index, !overwrite);
deferred cleanup_pin = [&] { do_unpin(index, pinned.cookie); };
// Initialize the block contents.
if constexpr (overwrite) {
init.apply(pinned.data, m_block_size);
do_dirty(index, pinned.cookie);
}
handle->m_engine = this;
handle->m_index = index;
handle->m_data = pinned.data;
handle->m_cookie = pinned.cookie;
manager.insert(*handle);
cleanup_pin.disable();
cleanup_handle.disable();
return block_handle(handle);
(void) init; // unused warning :/
}
void engine::internal_flush_handle(detail::block_handle_base* base) {
PREQUEL_ASSERT(base, "Invalid handle instance.");
PREQUEL_ASSERT(base->get_engine() == this, "Handle does not belong to this engine.");
detail::block_handle_internal* handle = static_cast<detail::block_handle_internal*>(base);
PREQUEL_ASSERT(handle_manager().contains(*handle), "Handle is not managed by this instance.");
do_flush(handle->index(), handle->m_cookie);
}
void engine::internal_dirty_handle(detail::block_handle_base* base) {
PREQUEL_ASSERT(base, "Invalid handle instance.");
PREQUEL_ASSERT(base->get_engine() == this, "Handle does not belong to this engine.");
detail::block_handle_internal* handle = static_cast<detail::block_handle_internal*>(base);
PREQUEL_ASSERT(handle_manager().contains(*handle), "Handle is not managed by this instance.");
do_dirty(handle->index(), handle->m_cookie);
}
void engine::internal_release_handle(detail::block_handle_base* base) noexcept {
PREQUEL_ASSERT(base, "Invalid handle instance.");
PREQUEL_ASSERT(base->get_engine() == this, "Handle does not belong to this engine.");
detail::block_handle_internal* handle = static_cast<detail::block_handle_internal*>(base);
do_unpin(handle->index(), handle->m_cookie);
auto& manager = handle_manager();
manager.remove(*handle);
manager.free(handle);
}
detail::block_handle_manager& engine::handle_manager() const {
PREQUEL_ASSERT(m_handle_manager, "Invalid block handle manager instance.");
return *m_handle_manager;
}
} // namespace prequel
| 31.324723 | 102 | 0.668512 | mbeckem |
f607384ccf495e4bbd424b3041424762de927e46 | 4,460 | cpp | C++ | clicache/src/Execution.cpp | rhoughton-pivot/geode-native | ab6fe7d996e5ec23832f90663d03f1d66b9f5fbd | [
"Apache-2.0"
] | 1 | 2018-09-08T05:05:22.000Z | 2018-09-08T05:05:22.000Z | clicache/src/Execution.cpp | rhoughton-pivot/geode-native | ab6fe7d996e5ec23832f90663d03f1d66b9f5fbd | [
"Apache-2.0"
] | 1 | 2020-10-05T11:41:41.000Z | 2020-10-05T11:41:41.000Z | clicache/src/Execution.cpp | rhoughton-pivot/geode-native | ab6fe7d996e5ec23832f90663d03f1d66b9f5fbd | [
"Apache-2.0"
] | null | null | null | /*
* Licensed to the Apache Software Foundation (ASF) under one or more
* contributor license agreements. See the NOTICE file distributed with
* this work for additional information regarding copyright ownership.
* The ASF licenses this file to You under the Apache License, Version 2.0
* (the "License"); you may not use this file except in compliance with
* the License. You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
#include "Execution.hpp"
#include "begin_native.hpp"
#include <geode/Execution.hpp>
#include "end_native.hpp"
#include "ResultCollector.hpp"
#include "impl/ManagedResultCollector.hpp"
#include "ExceptionTypes.hpp"
#include "impl/SafeConvert.hpp"
#include "TimeUtils.hpp"
using namespace System;
namespace Apache
{
namespace Geode
{
namespace Client
{
namespace native = apache::geode::client;
generic<class TResult>
generic<class TFilter>
Execution<TResult>^ Execution<TResult>::WithFilter(System::Collections::Generic::ICollection<TFilter>^ routingObj)
{
if (routingObj != nullptr) {
_GF_MG_EXCEPTION_TRY2/* due to auto replace */
auto rsptr = native::CacheableVector::create();
for each(TFilter item in routingObj)
{
auto v = Serializable::GetUnmanagedValueGeneric<TFilter>(item);
rsptr->push_back(v);
}
try
{
return Execution<TResult>::Create(m_nativeptr->get()->withFilter(rsptr), this->m_rc);
}
finally
{
GC::KeepAlive(m_nativeptr);
}
_GF_MG_EXCEPTION_CATCH_ALL2/* due to auto replace */
}
else {
throw gcnew IllegalArgumentException("Execution<TResult>::WithFilter: null TFilter provided");
}
}
generic<class TResult>
generic<class TArgs>
Execution<TResult>^ Execution<TResult>::WithArgs( TArgs args )
{
_GF_MG_EXCEPTION_TRY2/* due to auto replace */
try
{
auto argsptr = Serializable::GetUnmanagedValueGeneric<TArgs>( args );
return Execution<TResult>::Create(m_nativeptr->get()->withArgs(argsptr), this->m_rc);
}
finally
{
GC::KeepAlive(m_nativeptr);
}
_GF_MG_EXCEPTION_CATCH_ALL2/* due to auto replace */
}
generic<class TResult>
Execution<TResult>^ Execution<TResult>::WithCollector(Client::IResultCollector<TResult>^ rc)
{
_GF_MG_EXCEPTION_TRY2/* due to auto replace */
std::shared_ptr<native::ResultCollector> rcptr;
if ( rc != nullptr ) {
auto rcg = gcnew ResultCollectorGeneric<TResult>();
rcg->SetResultCollector(rc);
rcptr = std::shared_ptr<native::ManagedResultCollectorGeneric>(new native::ManagedResultCollectorGeneric(rcg));
}
try
{
return Execution<TResult>::Create( m_nativeptr->get()->withCollector(rcptr), rc);
}
finally
{
GC::KeepAlive(m_nativeptr);
}
_GF_MG_EXCEPTION_CATCH_ALL2/* due to auto replace */
}
generic<class TResult>
IResultCollector<TResult>^ Execution<TResult>::Execute(String^ func, TimeSpan timeout)
{
_GF_MG_EXCEPTION_TRY2/* due to auto replace */
try
{
auto rc = m_nativeptr->get()->execute(marshal_as<std::string>(func), TimeUtils::TimeSpanToDurationCeil<std::chrono::milliseconds>(timeout));
if (m_rc == nullptr)
return gcnew ResultCollector<TResult>(rc);
else
return m_rc;
}
finally
{
GC::KeepAlive(m_nativeptr);
}
_GF_MG_EXCEPTION_CATCH_ALL2/* due to auto replace */
}
generic<class TResult>
IResultCollector<TResult>^ Execution<TResult>::Execute(String^ func)
{
return Execute(func, TimeUtils::DurationToTimeSpan(native::DEFAULT_QUERY_RESPONSE_TIMEOUT));
}
} // namespace Client
} // namespace Geode
} // namespace Apache
| 33.787879 | 150 | 0.634081 | rhoughton-pivot |
f60875c75cf897e0084395bae0c133aa63f02728 | 1,145 | cpp | C++ | src/tmp/student.cpp | asankagit/wacms | f6ecf9e1c740417a934acb8f6c53e2bb3388b5ee | [
"MIT"
] | 5 | 2021-10-14T07:27:31.000Z | 2022-01-04T17:20:15.000Z | src/tmp/student.cpp | asankagit/wacms | f6ecf9e1c740417a934acb8f6c53e2bb3388b5ee | [
"MIT"
] | null | null | null | src/tmp/student.cpp | asankagit/wacms | f6ecf9e1c740417a934acb8f6c53e2bb3388b5ee | [
"MIT"
] | null | null | null | // similar to MyClass, in this we are testing header file usage
#include <student.h>
#include "emscripten/bind.h"
using namespace emscripten;
Student::Student() {
}
void Student::setName(std::string name) {
this->name = name;
}
const std::string& Student::getName() {
for(int i=0; i<10000; i++) {
printf("%d",i);
}
std::string str = "response'data hi "+this->name+ "--";
return str;
}
// https://stackoverflow.com/questions/2298242/callback-functions-in-c
// typedef int (ClassName::*CallbackType)(float);
// void DoWorkObject(CallbackType callback)
// {
// //Class instance to invoke it through
// ClassName objectInstance;
// //Invocation
// int result = (objectInstance.*callback)(1.0f);
// }
// int main(int argc, char ** argv)
// {
// //Pass in SomeCallback to the DoWork
// DoWorkObject(&ClassName::Method);
// }
EMSCRIPTEN_BINDINGS(Student_example)
{
class_<Student>("Student").
constructor().
function("setName", &Student::setName).
function("getName", &Student::getName);
}
// em++ --bind student.cpp CombineClass.cpp -o student.js -I .
// | 21.203704 | 70 | 0.637555 | asankagit |
f60aebecafaaaf52fe9d95041c392350f6185103 | 1,531 | cpp | C++ | common/comline.cpp | yalehwy/linepw | 8e22ffaa49fa49dca44a6a8d6e38a16a64a41aa0 | [
"Apache-2.0"
] | null | null | null | common/comline.cpp | yalehwy/linepw | 8e22ffaa49fa49dca44a6a8d6e38a16a64a41aa0 | [
"Apache-2.0"
] | null | null | null | common/comline.cpp | yalehwy/linepw | 8e22ffaa49fa49dca44a6a8d6e38a16a64a41aa0 | [
"Apache-2.0"
] | null | null | null | #include "comline.hpp"
#define MOVESPACE 1
ComLine::ComLine()
{
map = new std::map<std::string, std::string>;
}
ComLine::~ComLine()
{
if (map)
{
delete map;
map = nullptr;
}
}
std::map<std::string, std::string>*
ComLine::getKeyValue(int argc, char* argv[])
{
for (int i = 1; i < argc; i++)
{
std::string t = std::string(argv[i]);
int idx = t.find('=', 1);
std::string key = t.substr(2, idx - MOVESPACE * 2);
std::string value = t.substr(idx + MOVESPACE);
if (!map)
{
map = new std::map<std::string, std::string>;
}
map->insert(std::make_pair(key, value));
}
return map;
}
bool ComLine::haveHelp()
{
for(std::map<std::string, std::string>::iterator iter = map->begin();
iter != map->end(); iter++)
{
if(iter->first == "help")
return true;
}
return false;
}
void ComLine::printHelpInfo()
{
std::cout << " --listen-port " << std::endl;
std::cout << " --pool-num " << std::endl;
std::cout << " --mysql-port " << std::endl;
std::cout << " --mysql-host " << std::endl;
std::cout << " --mysql-user " << std::endl;
std::cout << "--mysql-passwd " << std::endl;
std::cout << " --mysql-db " << std::endl;
}
// find args address
int ComLine::findParamIndex(int argc, char**argv, std::string param)
{
for (int i = 1; i < argc; i++)
{
std::string t = std::string(argv[i]);
int idx = t.find('=', 1);
std::string key = t.substr(2, idx - MOVESPACE * 2);
if(key == param) return i;
}
return -1;
}
| 21.263889 | 71 | 0.546048 | yalehwy |
f60b2bff941743aab59e7234d6a06828b5cdebf4 | 2,096 | cpp | C++ | Algorithms/0140.Word_Break_II.cpp | metehkaya/LeetCode | 52f4a1497758c6f996d515ced151e8783ae4d4d2 | [
"MIT"
] | 2 | 2020-07-20T06:40:22.000Z | 2021-11-20T01:23:26.000Z | Problems/LeetCode/Problems/0140.Word_Break_II.cpp | metehkaya/Algo-Archive | 03b5fdcf06f84a03125c57762c36a4e03ca6e756 | [
"MIT"
] | null | null | null | Problems/LeetCode/Problems/0140.Word_Break_II.cpp | metehkaya/Algo-Archive | 03b5fdcf06f84a03125c57762c36a4e03ca6e756 | [
"MIT"
] | null | null | null | typedef vector<int> vi;
typedef vector<string> vs;
class Node {
public:
bool isWord;
vector<Node*> child;
Node() {
isWord = false;
child.resize(26,NULL);
}
}*root;
class Solution {
public:
void solve(int i , int n , string& s , vi& last , string& word , vs& ans) {
if(i == n) {
ans.push_back(word);
return;
}
Node* node = root;
for( int j = i ; j <= last[i] ; j++ ) {
int c = s[j]-'a';
node = node->child[c];
word.push_back(s[j]);
if(node->isWord) {
if(j == n-1)
solve(j+1,n,s,last,word,ans);
else if(last[j+1] != -1) {
word.push_back(' ');
solve(j+1,n,s,last,word,ans);
word.pop_back();
}
}
}
for( int j = i ; j <= last[i] ; j++ )
word.pop_back();
}
vs wordBreak(string s, vs& words) {
root = new Node();
int n = words.size();
for( int i = 0 ; i < n ; i++ ) {
Node* node = root;
int len = words[i].length();
for( int j = 0 ; j < len ; j++ ) {
int c = words[i][j] - 'a';
if(node->child[c] == NULL)
node->child[c] = new Node();
node = node->child[c];
}
node->isWord = true;
}
n = s.length();
vi last(n+1,-1);
for( int i = n-1 ; i >= 0 ; i-- ) {
Node* node = root;
for( int j = i ; j < n ; j++ ) {
int c = s[j]-'a';
if(node->child[c]) {
node = node->child[c];
if(node->isWord)
if(j == n-1 or last[j+1] != -1)
last[i] = j;
}
else
break;
}
}
vs ans;
string word = "";
if(last[0] != -1)
solve(0,n,s,last,word,ans);
return ans;
}
}; | 27.946667 | 79 | 0.354485 | metehkaya |
f60eb6100c61281118c2d2ee25a3127f2f91d7e9 | 228 | cpp | C++ | 010-files/src/FilesBefore.cpp | platisd/refactoring-for-testablity-cpp | 126ee079c73c169bae8a31a2f2ccdc873e819cca | [
"MIT"
] | 33 | 2020-04-18T22:43:57.000Z | 2022-02-01T23:48:34.000Z | 010-files/src/FilesBefore.cpp | platisd/refactoring-for-testablity-cpp | 126ee079c73c169bae8a31a2f2ccdc873e819cca | [
"MIT"
] | null | null | null | 010-files/src/FilesBefore.cpp | platisd/refactoring-for-testablity-cpp | 126ee079c73c169bae8a31a2f2ccdc873e819cca | [
"MIT"
] | 7 | 2020-04-23T00:39:09.000Z | 2021-11-10T15:05:33.000Z | #include "FileEncoder.hpp"
using namespace before;
namespace
{
const auto kFilePath = "write.txt"; // File with some contents
}
int main()
{
FileEncoder f;
const auto r = f.encode(kFilePath);
return r ? 0 : 1;
}
| 13.411765 | 62 | 0.657895 | platisd |
f6121cfdbab82fc640601de7f28d2d1300055ee8 | 8,281 | cpp | C++ | examples/prepared_statement.cpp | tstrutz/sqlite_orm | 1ee0a8653fe57ed4d4f69b5a65839b1861c41d32 | [
"BSD-3-Clause"
] | 1,566 | 2016-12-20T15:31:04.000Z | 2022-03-31T18:17:34.000Z | examples/prepared_statement.cpp | tstrutz/sqlite_orm | 1ee0a8653fe57ed4d4f69b5a65839b1861c41d32 | [
"BSD-3-Clause"
] | 620 | 2017-01-06T13:53:35.000Z | 2022-03-31T12:05:50.000Z | examples/prepared_statement.cpp | tstrutz/sqlite_orm | 1ee0a8653fe57ed4d4f69b5a65839b1861c41d32 | [
"BSD-3-Clause"
] | 274 | 2017-01-07T05:34:24.000Z | 2022-03-27T18:22:47.000Z | /**
* There are two member functions in storage_t class which you need to use to operate with
* prepared statements: storage_t::prepare and storage_t::execute.
* Also if you need to rebind arguments just use get<N>(statement) = ... syntax
* just like you do with std::tuple.
* Once a statement is prepared it holds a connection to a database inside. This connection will be open
* until at least one statement object exists.
*/
#include <sqlite_orm/sqlite_orm.h>
#include <iostream>
using namespace sqlite_orm;
using std::cout;
using std::endl;
struct Doctor {
int doctor_id = 0;
std::string doctor_name;
std::string degree;
};
struct Speciality {
int spl_id = 0;
std::string spl_descrip;
int doctor_id = 0;
};
struct Visit {
int doctor_id = 0;
std::string patient_name;
std::string vdate;
};
int main() {
auto storage = make_storage("prepared.sqlite",
make_table("doctors",
make_column("doctor_id", &Doctor::doctor_id, primary_key()),
make_column("doctor_name", &Doctor::doctor_name),
make_column("degree", &Doctor::degree)),
make_table("speciality",
make_column("spl_id", &Speciality::spl_id, primary_key()),
make_column("spl_descrip", &Speciality::spl_descrip),
make_column("doctor_id", &Speciality::doctor_id)),
make_table("visits",
make_column("doctor_id", &Visit::doctor_id),
make_column("patient_name", &Visit::patient_name),
make_column("vdate", &Visit::vdate)));
storage.sync_schema();
storage.remove_all<Doctor>();
storage.remove_all<Speciality>();
storage.remove_all<Visit>();
{
// first we create a statement object for replace query with a doctor object
auto replaceStatement = storage.prepare(replace(Doctor{210, "Dr. John Linga", "MD"}));
cout << "replaceStatement = " << replaceStatement.sql() << endl;
// next we execute our statement
storage.execute(replaceStatement);
// now 'doctors' table has one row [210, 'Dr. John Linga', 'MD']
// Next we shall reuse the statement to replace another doctor
// replaceStatement contains a doctor inside it which can be obtained
// with get<0>(statement) function
get<0>(replaceStatement) = {211, "Dr. Peter Hall", "MBBS"};
storage.execute(replaceStatement);
// now 'doctors' table has two rows.
// Next we shall reuse the statement again with member assignment
auto &doctor = get<0>(replaceStatement); // doctor is Doctor &
doctor.doctor_id = 212;
doctor.doctor_name = "Dr. Ke Gee";
doctor.degree = "MD";
storage.execute(replaceStatement);
// now 'doctors' table has three rows.
}
{
// also prepared statement can store arguments by reference. To do this you can
// pass a std::reference_wrapper instead of object value.
Doctor doctorToReplace{213, "Dr. Pat Fay", "MD"};
auto replaceStatementByRef = storage.prepare(replace(std::ref(doctorToReplace)));
cout << "replaceStatementByRef = " << replaceStatementByRef.sql() << endl;
storage.execute(replaceStatementByRef);
// now 'doctors' table has four rows.
// next we shall change doctorToReplace object and then execute our statement.
// Statement will be affected cause it stores a reference to the doctor
doctorToReplace.doctor_id = 214;
doctorToReplace.doctor_name = "Mosby";
doctorToReplace.degree = "MBBS";
storage.execute(replaceStatementByRef);
// and now 'doctors' table has five rows
}
cout << "Doctors count = " << storage.count<Doctor>() << endl;
for(auto &doctor: storage.iterate<Doctor>()) {
cout << storage.dump(doctor) << endl;
}
{
auto insertStatement = storage.prepare(insert(Speciality{1, "CARDIO", 211}));
cout << "insertStatement = " << insertStatement.sql() << endl;
storage.execute(insertStatement);
get<0>(insertStatement) = {2, "NEURO", 213};
storage.execute(insertStatement);
get<0>(insertStatement) = {3, "ARTHO", 212};
storage.execute(insertStatement);
get<0>(insertStatement) = {4, "GYNO", 210};
storage.execute(insertStatement);
}
cout << "Specialities count = " << storage.count<Speciality>() << endl;
for(auto &speciality: storage.iterate<Speciality>()) {
cout << storage.dump(speciality) << endl;
}
{
// let's insert (replace) 5 visits. We create two vectors with 2 visits each
std::vector<Visit> visits;
visits.push_back({210, "Julia Nayer", "2013-10-15"});
visits.push_back({214, "TJ Olson", "2013-10-14"});
// let's make a statement
auto replaceRangeStatement = storage.prepare(replace_range(visits.begin(), visits.end()));
cout << "replaceRangeStatement = " << replaceRangeStatement.sql() << endl;
// replace two objects
storage.execute(replaceRangeStatement);
std::vector<Visit> visits2;
visits2.push_back({215, "John Seo", "2013-10-15"});
visits2.push_back({212, "James Marlow", "2013-10-16"});
// reassign iterators to point to other visits. Beware that if end - begin
// will have different distance then you'll get a runtime error cause statement is
// already compiled with a fixed amount of arguments to bind
get<0>(replaceRangeStatement) = visits2.begin();
get<1>(replaceRangeStatement) = visits2.end();
storage.execute(replaceRangeStatement);
storage.replace(Visit{212, "Jason Mallin", "2013-10-12"});
}
cout << "Visits count = " << storage.count<Visit>() << endl;
for(auto &visit: storage.iterate<Visit>()) {
cout << storage.dump(visit) << endl;
}
{
// SELECT doctor_id
// FROM visits
// WHERE LENGTH(patient_name) > 8
auto selectStatement = storage.prepare(select(&Visit::doctor_id, where(length(&Visit::patient_name) > 8)));
cout << "selectStatement = " << selectStatement.sql() << endl;
{
auto rows = storage.execute(selectStatement);
cout << "rows count = " << rows.size() << endl;
for(auto &id: rows) {
cout << id << endl;
}
}
// same statement, other bound values
// SELECT doctor_id
// FROM visits
// WHERE LENGTH(patient_name) > 11
{
get<0>(selectStatement) = 11;
auto rows = storage.execute(selectStatement);
cout << "rows count = " << rows.size() << endl;
for(auto &id: rows) {
cout << id << endl;
}
}
}
{
// SELECT rowid, 'Doctor ' || doctor_name
// FROM doctors
// WHERE degree LIKE '%S'
auto selectStatement = storage.prepare(
select(columns(rowid(), "Doctor " || c(&Doctor::doctor_name)), where(like(&Doctor::degree, "%S"))));
cout << "selectStatement = " << selectStatement.sql() << endl;
{
auto rows = storage.execute(selectStatement);
cout << "rows count = " << rows.size() << endl;
for(auto &row: rows) {
cout << get<0>(row) << '\t' << get<1>(row) << endl;
}
}
// SELECT rowid, 'Nice ' || doctor_name
// FROM doctors
// WHERE degree LIKE '%D'
get<0>(selectStatement) = "Nice ";
get<1>(selectStatement) = "%D";
{
auto rows = storage.execute(selectStatement);
cout << "rows count = " << rows.size() << endl;
for(auto &row: rows) {
cout << get<0>(row) << '\t' << get<1>(row) << endl;
}
}
}
return 0;
}
| 39.433333 | 115 | 0.567685 | tstrutz |
f6158dae5583f50ddac7a7d1cd73e8f50a57350b | 3,903 | cpp | C++ | 7th_100/problem650.cpp | takekoputa/project-euler | 6f434be429bd26f5d0f84f5ab0f5fa2bd677c790 | [
"MIT"
] | null | null | null | 7th_100/problem650.cpp | takekoputa/project-euler | 6f434be429bd26f5d0f84f5ab0f5fa2bd677c790 | [
"MIT"
] | null | null | null | 7th_100/problem650.cpp | takekoputa/project-euler | 6f434be429bd26f5d0f84f5ab0f5fa2bd677c790 | [
"MIT"
] | 1 | 2021-11-02T12:08:46.000Z | 2021-11-02T12:08:46.000Z | // Problem: https://projecteuler.net/problem=650
// g++ problem650.cpp -I$HOME/pari/include/ -L$HOME/pari/lib -lpari -O3
#include<pari/pari.h>
#include<iostream>
#include<vector>
#include<cmath>
#include<unordered_map>
#include<functional>
using namespace std;
#define endl "\n"
typedef int64_t i64;
const i64 N = 20000;
//const i64 N = 5;
const i64 MOD = 1'000'000'007;
vector<i64> get_primes(i64 n)
{
vector<i64> primes;
primes.reserve(n/10);
vector<bool> is_prime = vector<bool>(n/2+1, true);
i64 sqrt_n = i64(sqrt(n));
for (i64 p = 3; p <= sqrt_n; p+=2)
{
if (!is_prime[(p-3)/2])
continue;
for (i64 np = 3*p; np <= n; np += 2*p)
is_prime[(np-3)/2] = false;
}
primes.push_back(2);
i64 size = is_prime.size();
for (i64 p = 0; 2*p+3 <= n; p++)
{
if (is_prime[p])
primes.push_back(2*p+3);
}
return primes;
}
i64 modpow(i64 base, i64 pow, i64 mod)
{
i64 result = 1;
base = base % mod;
while (pow > 0)
{
if (pow % 2 == 1)
result = (result * base) % mod;
pow = pow / 2;
base = (base * base) % mod;
}
return result;
}
void factor(i64 n, const vector<i64>& primes, vector<i64>& bases, vector<i64>& exponents)
{
if (n <= 1)
return;
i64 i_prime = 0;
while (n > 1)
{
while (n % primes[i_prime] != 0)
i_prime += 1;
i64 base = primes[i_prime];
i64 exponent = 0;
while (n % base == 0)
{
exponent = exponent + 1;
n = n / base;
}
bases.push_back(base);
exponents.push_back(exponent);
}
}
unordered_map<i64, vector<i64>> cached_bases;
unordered_map<i64, vector<i64>> cached_exponents;
void cached_factor(i64 n, const vector<i64>& primes, vector<i64>& bases, vector<i64>& exponents)
{
if (cached_bases.find(n) == cached_bases.end())
{
vector<i64> _bases;
vector<i64> _exponents;
factor(n, primes, _bases, _exponents);
cached_bases[n] = move(_bases);
cached_exponents[n] = move(_exponents);
}
bases = ref(cached_bases[n]);
exponents = ref(cached_exponents[n]);
}
i64 invmod(i64 base, i64 mod)
{
// if k is the multiplicative order of a mod M, then a^k = 1 (mod M)
// -> a * a^(k-1) = 1 (mod M)
// -> invmod(a, M) = a^(k-1)
i64 multiplicative_order = gtolong(order(gmodulss(base, mod)));
return modpow(base, multiplicative_order-1, mod);
};
i64 D(i64 n, const vector<i64>& primes, const vector<i64>& invmods)
{
i64 ans = 1;
unordered_map<i64, i64> exponents;
for (auto p: primes)
{
if (p > n)
break;
exponents[p] = 0;
}
for (i64 k = 2; k <= n; k++)
{
i64 k_exponent_coeff = -n-1+2*k;
vector<i64> k_bases;
vector<i64> k_exponents;
cached_factor(k, primes, k_bases, k_exponents);
for (i64 j = 0; j < k_bases.size(); j++)
{
i64 base = k_bases[j];
i64 exponent = k_exponents[j];
exponents[base] += exponent * k_exponent_coeff;
}
}
for (auto p: exponents)
{
i64 base = p.first;
i64 exponent = p.second;
i64 next_coeff = modpow(base, exponent+1, MOD) - 1;
next_coeff = next_coeff * invmods[base-1]; // a^-1 % MOD
next_coeff = next_coeff % MOD;
ans = ans * next_coeff;
ans = ans % MOD;
}
return ans;
}
int main()
{
i64 ans = 0;
vector<i64> primes = get_primes(N);
pari_init(500000000,2);
vector<i64> invmods = vector<i64>(N+1, 0);
for (auto p: primes)
invmods[p-1] = (invmod(p-1, MOD));
pari_close();
for (i64 i = 1; i <= N; i++)
{
ans = ans + D(i, primes, invmods);
ans = ans % MOD;
}
cout << ans << endl;
return 0;
}
| 22.958824 | 96 | 0.539329 | takekoputa |
f6159135dbe79a3aa7e933e76b3e4ee570096fbd | 1,756 | cpp | C++ | src/Magnum/MeshTools/FlipNormals.cpp | glhrmfrts/magnum | c5d08156eaa03867403c32f4b0ee6a56202331e4 | [
"MIT"
] | 1 | 2019-04-23T07:31:01.000Z | 2019-04-23T07:31:01.000Z | src/Magnum/MeshTools/FlipNormals.cpp | glhrmfrts/magnum | c5d08156eaa03867403c32f4b0ee6a56202331e4 | [
"MIT"
] | null | null | null | src/Magnum/MeshTools/FlipNormals.cpp | glhrmfrts/magnum | c5d08156eaa03867403c32f4b0ee6a56202331e4 | [
"MIT"
] | 1 | 2022-03-31T08:48:52.000Z | 2022-03-31T08:48:52.000Z | /*
This file is part of Magnum.
Copyright © 2010, 2011, 2012, 2013, 2014, 2015, 2016, 2017, 2018, 2019
Vladimír Vondruš <mosra@centrum.cz>
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 "FlipNormals.h"
#include "Magnum/Math/Vector3.h"
namespace Magnum { namespace MeshTools {
void flipFaceWinding(std::vector<UnsignedInt>& indices) {
CORRADE_ASSERT(!(indices.size()%3), "MeshTools::flipNormals(): index count is not divisible by 3!", );
using std::swap;
for(std::size_t i = 0; i != indices.size(); i += 3)
swap(indices[i+1], indices[i+2]);
}
void flipNormals(std::vector<Vector3>& normals) {
for(Vector3& normal: normals)
normal = -normal;
}
}}
| 38.173913 | 106 | 0.715831 | glhrmfrts |
f616f24d16b479a5662683750dc5047c412e924e | 49,886 | cpp | C++ | project4/mariadb/server/storage/connect/tabfmt.cpp | jiunbae/ITE4065 | 3b9fcf9317e93ca7c829f1438b85f0f5ea2885db | [
"MIT"
] | 11 | 2017-10-28T08:41:08.000Z | 2021-06-24T07:24:21.000Z | project4/mariadb/server/storage/connect/tabfmt.cpp | jiunbae/ITE4065 | 3b9fcf9317e93ca7c829f1438b85f0f5ea2885db | [
"MIT"
] | null | null | null | project4/mariadb/server/storage/connect/tabfmt.cpp | jiunbae/ITE4065 | 3b9fcf9317e93ca7c829f1438b85f0f5ea2885db | [
"MIT"
] | 4 | 2017-09-07T09:33:26.000Z | 2021-02-19T07:45:08.000Z | /************* TabFmt C++ Program Source Code File (.CPP) **************/
/* PROGRAM NAME: TABFMT */
/* ------------- */
/* Version 3.9.2 */
/* */
/* COPYRIGHT: */
/* ---------- */
/* (C) Copyright to the author Olivier BERTRAND 2001 - 2017 */
/* */
/* WHAT THIS PROGRAM DOES: */
/* ----------------------- */
/* This program are the TABFMT classes DB execution routines. */
/* The base class CSV is comma separated files. */
/* FMT (Formatted) files are those having a complex internal record */
/* format described in the Format keyword of their definition. */
/***********************************************************************/
/***********************************************************************/
/* Include relevant MariaDB header file. */
/***********************************************************************/
#include "my_global.h"
#if defined(__WIN__)
#include <io.h>
#include <fcntl.h>
#include <errno.h>
#include <locale.h>
#if defined(__BORLANDC__)
#define __MFC_COMPAT__ // To define min/max as macro
#endif
//#include <windows.h>
#include "osutil.h"
#else
#if defined(UNIX)
#include <errno.h>
#include <unistd.h>
#include "osutil.h"
#else
#include <io.h>
#endif
#include <fcntl.h>
#endif
/***********************************************************************/
/* Include application header files: */
/* global.h is header containing all global declarations. */
/* plgdbsem.h is header containing the DB application declarations. */
/* tabdos.h is header containing the TABDOS class declarations. */
/***********************************************************************/
#include "global.h"
#include "plgdbsem.h"
#include "mycat.h"
#include "filamap.h"
#if defined(GZ_SUPPORT)
#include "filamgz.h"
#endif // GZ_SUPPORT
#if defined(ZIP_SUPPORT)
#include "filamzip.h"
#endif // ZIP_SUPPORT
#include "tabfmt.h"
#include "tabmul.h"
#define NO_FUNC
#include "plgcnx.h" // For DB types
#include "resource.h"
/***********************************************************************/
/* This should be an option. */
/***********************************************************************/
#define MAXCOL 200 /* Default max column nb in result */
#define TYPE_UNKNOWN 10 /* Must be greater than other types */
/***********************************************************************/
/* External function. */
/***********************************************************************/
USETEMP UseTemp(void);
/***********************************************************************/
/* CSVColumns: constructs the result blocks containing the description */
/* of all the columns of a CSV file that will be retrieved by #GetData.*/
/* Note: the algorithm to set the type is based on the internal values */
/* of types (TYPE_STRING < TYPE_DOUBLE < TYPE_INT) (1 < 2 < 7). */
/* If these values are changed, this will have to be revisited. */
/***********************************************************************/
PQRYRES CSVColumns(PGLOBAL g, PCSZ dp, PTOS topt, bool info)
{
static int buftyp[] = {TYPE_STRING, TYPE_SHORT, TYPE_STRING,
TYPE_INT, TYPE_INT, TYPE_SHORT};
static XFLD fldtyp[] = {FLD_NAME, FLD_TYPE, FLD_TYPENAME,
FLD_PREC, FLD_LENGTH, FLD_SCALE};
static unsigned int length[] = {6, 6, 8, 10, 10, 6};
const char *fn;
char sep, q;
int rc, mxr;
bool hdr;
char *p, *colname[MAXCOL], dechar, buf[8];
int i, imax, hmax, n, nerr, phase, blank, digit, dec, type;
int ncol = sizeof(buftyp) / sizeof(int);
int num_read = 0, num_max = 10000000; // Statistics
int len[MAXCOL], typ[MAXCOL], prc[MAXCOL];
PCSVDEF tdp;
PTDBCSV tcvp;
PTDBASE tdbp;
PQRYRES qrp;
PCOLRES crp;
if (info) {
imax = hmax = 0;
length[0] = 128;
goto skipit;
} // endif info
//if (GetIntegerTableOption(g, topt, "Multiple", 0)) {
// strcpy(g->Message, "Cannot find column definition for multiple table");
// return NULL;
//} // endif Multiple
// num_max = atoi(p+1); // Max num of record to test
imax = hmax = nerr = 0;
for (i = 0; i < MAXCOL; i++) {
colname[i] = NULL;
len[i] = 0;
typ[i] = TYPE_UNKNOWN;
prc[i] = 0;
} // endfor i
/*********************************************************************/
/* Get the CSV table description block. */
/*********************************************************************/
tdp = new(g) CSVDEF;
tdp->Database = dp;
if ((tdp->Zipped = GetBooleanTableOption(g, topt, "Zipped", false))) {
#if defined(ZIP_SUPPORT)
tdp->Entry = GetStringTableOption(g, topt, "Entry", NULL);
tdp->Mulentries = (tdp->Entry)
? strchr(tdp->Entry, '*') || strchr(tdp->Entry, '?')
: GetBooleanTableOption(g, topt, "Mulentries", false);
#else // !ZIP_SUPPORT
strcpy(g->Message, "ZIP not supported by this version");
return NULL;
#endif // !ZIP_SUPPORT
} // endif // Zipped
fn = tdp->Fn = GetStringTableOption(g, topt, "Filename", NULL);
if (!tdp->Fn) {
strcpy(g->Message, MSG(MISSING_FNAME));
return NULL;
} // endif Fn
if (!(tdp->Lrecl = GetIntegerTableOption(g, topt, "Lrecl", 0)))
tdp->Lrecl = 4096;
tdp->Multiple = GetIntegerTableOption(g, topt, "Multiple", 0);
p = (char*)GetStringTableOption(g, topt, "Separator", ",");
tdp->Sep = (strlen(p) == 2 && p[0] == '\\' && p[1] == 't') ? '\t' : *p;
#if defined(__WIN__)
if (tdp->Sep == ',' || strnicmp(setlocale(LC_NUMERIC, NULL), "French", 6))
dechar = '.';
else
dechar = ',';
#else // !__WIN__
dechar = '.';
#endif // !__WIN__
sep = tdp->Sep;
tdp->Quoted = GetIntegerTableOption(g, topt, "Quoted", -1);
p = (char*)GetStringTableOption(g, topt, "Qchar", "");
tdp->Qot = *p;
if (tdp->Qot && tdp->Quoted < 0)
tdp->Quoted = 0;
else if (!tdp->Qot && tdp->Quoted >= 0)
tdp->Qot = '"';
q = tdp->Qot;
hdr = GetBooleanTableOption(g, topt, "Header", false);
tdp->Maxerr = GetIntegerTableOption(g, topt, "Maxerr", 0);
tdp->Accept = GetBooleanTableOption(g, topt, "Accept", false);
if (tdp->Accept && tdp->Maxerr == 0)
tdp->Maxerr = INT_MAX32; // Accept all bad lines
mxr = MY_MAX(0, tdp->Maxerr);
if (trace)
htrc("File %s Sep=%c Qot=%c Header=%d maxerr=%d\n",
SVP(tdp->Fn), tdp->Sep, tdp->Qot, tdp->Header, tdp->Maxerr);
if (tdp->Zipped)
tcvp = new(g)TDBCSV(tdp, new(g)UNZFAM(tdp));
else
tcvp = new(g) TDBCSV(tdp, new(g) DOSFAM(tdp));
tcvp->SetMode(MODE_READ);
if (tdp->Multiple) {
tdbp = new(g)TDBMUL(tcvp);
tdbp->SetMode(MODE_READ);
} else
tdbp = tcvp;
/*********************************************************************/
/* Open the CSV file. */
/*********************************************************************/
if (tdbp->OpenDB(g))
return NULL;
if (hdr) {
/*******************************************************************/
/* Make the column names from the first line. */
/*******************************************************************/
phase = 0;
if ((rc = tdbp->ReadDB(g)) == RC_OK) {
p = PlgDBDup(g, tcvp->To_Line);
//skip leading blanks
for (; *p == ' '; p++) ;
if (q && *p == q) {
// Header is quoted
p++;
phase = 1;
} // endif q
colname[0] = p;
} else if (rc == RC_EF) {
sprintf(g->Message, MSG(FILE_IS_EMPTY), fn);
goto err;
} else
goto err;
for (i = 1; *p; p++)
if (phase == 1 && *p == q) {
*p = '\0';
phase = 0;
} else if (*p == sep && !phase) {
*p = '\0';
//skip leading blanks
for (; *(p+1) == ' '; p++) ;
if (q && *(p+1) == q) {
// Header is quoted
p++;
phase = 1;
} // endif q
colname[i++] = p + 1;
} // endif sep
num_read++;
imax = hmax = i;
for (i = 0; i < hmax; i++)
length[0] = MY_MAX(length[0], strlen(colname[i]));
tcvp->Header = true; // In case of multiple table
} // endif hdr
for (num_read++; num_read <= num_max; num_read++) {
/*******************************************************************/
/* Now start the reading process. Read one line. */
/*******************************************************************/
if ((rc = tdbp->ReadDB(g)) == RC_OK) {
} else if (rc == RC_EF) {
sprintf(g->Message, MSG(EOF_AFTER_LINE), num_read -1);
break;
} else {
sprintf(g->Message, MSG(ERR_READING_REC), num_read, fn);
goto err;
} // endif's
/*******************************************************************/
/* Make the test for field lengths. */
/*******************************************************************/
i = n = phase = blank = digit = dec = 0;
for (p = tcvp->To_Line; *p; p++)
if (*p == sep) {
if (phase != 1) {
if (i == MAXCOL - 1) {
sprintf(g->Message, MSG(TOO_MANY_FIELDS), num_read, fn);
goto err;
} // endif i
if (n) {
len[i] = MY_MAX(len[i], n);
type = (digit || (dec && n == 1)) ? TYPE_STRING
: (dec) ? TYPE_DOUBLE : TYPE_INT;
typ[i] = MY_MIN(type, typ[i]);
prc[i] = MY_MAX((typ[i] == TYPE_DOUBLE) ? (dec - 1) : 0, prc[i]);
} // endif n
i++;
n = phase = blank = digit = dec = 0;
} else // phase == 1
n++;
} else if (*p == ' ') {
if (phase < 2)
n++;
if (blank)
digit = 1;
} else if (*p == q) {
if (phase == 0) {
if (blank)
if (++nerr > mxr) {
sprintf(g->Message, MSG(MISPLACED_QUOTE), num_read);
goto err;
} else
goto skip;
n = 0;
phase = digit = 1;
} else if (phase == 1) {
if (*(p+1) == q) {
// This is currently not implemented for CSV tables
// if (++nerr > mxr) {
// sprintf(g->Message, MSG(QUOTE_IN_QUOTE), num_read);
// goto err;
// } else
// goto skip;
p++;
n++;
} else
phase = 2;
} else if (++nerr > mxr) { // phase == 2
sprintf(g->Message, MSG(MISPLACED_QUOTE), num_read);
goto err;
} else
goto skip;
} else {
if (phase == 2)
if (++nerr > mxr) {
sprintf(g->Message, MSG(MISPLACED_QUOTE), num_read);
goto err;
} else
goto skip;
// isdigit cannot be used here because of debug assert
if (!strchr("0123456789", *p)) {
if (!digit && *p == dechar)
dec = 1; // Decimal point found
else if (blank || !(*p == '-' || *p == '+'))
digit = 1;
} else if (dec)
dec++; // More decimals
n++;
blank = 1;
} // endif's *p
if (phase == 1)
if (++nerr > mxr) {
sprintf(g->Message, MSG(UNBALANCE_QUOTE), num_read);
goto err;
} else
goto skip;
if (n) {
len[i] = MY_MAX(len[i], n);
type = (digit || n == 0 || (dec && n == 1)) ? TYPE_STRING
: (dec) ? TYPE_DOUBLE : TYPE_INT;
typ[i] = MY_MIN(type, typ[i]);
prc[i] = MY_MAX((typ[i] == TYPE_DOUBLE) ? (dec - 1) : 0, prc[i]);
} // endif n
imax = MY_MAX(imax, i+1);
skip: ; // Skip erroneous line
} // endfor num_read
if (trace) {
htrc("imax=%d Lengths:", imax);
for (i = 0; i < imax; i++)
htrc(" %d", len[i]);
htrc("\n");
} // endif trace
tdbp->CloseDB(g);
skipit:
if (trace)
htrc("CSVColumns: imax=%d hmax=%d len=%d\n",
imax, hmax, length[0]);
/*********************************************************************/
/* Allocate the structures used to refer to the result set. */
/*********************************************************************/
qrp = PlgAllocResult(g, ncol, imax, IDS_COLUMNS + 3,
buftyp, fldtyp, length, false, false);
if (info || !qrp)
return qrp;
qrp->Nblin = imax;
/*********************************************************************/
/* Now get the results into blocks. */
/*********************************************************************/
for (i = 0; i < imax; i++) {
if (i >= hmax) {
sprintf(buf, "COL%.3d", i+1);
p = buf;
} else
p = colname[i];
if (typ[i] == TYPE_UNKNOWN) // Void column
typ[i] = TYPE_STRING;
crp = qrp->Colresp; // Column Name
crp->Kdata->SetValue(p, i);
crp = crp->Next; // Data Type
crp->Kdata->SetValue(typ[i], i);
crp = crp->Next; // Type Name
crp->Kdata->SetValue(GetTypeName(typ[i]), i);
crp = crp->Next; // Precision
crp->Kdata->SetValue(len[i], i);
crp = crp->Next; // Length
crp->Kdata->SetValue(len[i], i);
crp = crp->Next; // Scale (precision)
crp->Kdata->SetValue(prc[i], i);
} // endfor i
/*********************************************************************/
/* Return the result pointer for use by GetData routines. */
/*********************************************************************/
return qrp;
err:
tdbp->CloseDB(g);
return NULL;
} // end of CSVCColumns
/* --------------------------- Class CSVDEF -------------------------- */
/***********************************************************************/
/* CSVDEF constructor. */
/***********************************************************************/
CSVDEF::CSVDEF(void)
{
Fmtd = Header = false;
//Maxerr = 0;
Quoted = -1;
Sep = ',';
Qot = '\0';
} // end of CSVDEF constructor
/***********************************************************************/
/* DefineAM: define specific AM block values from XDB file. */
/***********************************************************************/
bool CSVDEF::DefineAM(PGLOBAL g, LPCSTR am, int poff)
{
char buf[8];
// Double check correctness of offset values
if (Catfunc == FNC_NO)
for (PCOLDEF cdp = To_Cols; cdp; cdp = cdp->GetNext())
if (cdp->GetOffset() < 1 && !cdp->IsSpecial()) {
strcpy(g->Message, MSG(BAD_OFFSET_VAL));
return true;
} // endif Offset
// Call DOSDEF DefineAM with am=CSV so FMT is not confused with FIX
if (DOSDEF::DefineAM(g, "CSV", poff))
return true;
GetCharCatInfo("Separator", ",", buf, sizeof(buf));
Sep = (strlen(buf) == 2 && buf[0] == '\\' && buf[1] == 't') ? '\t' : *buf;
Quoted = GetIntCatInfo("Quoted", -1);
GetCharCatInfo("Qchar", "", buf, sizeof(buf));
Qot = *buf;
if (Qot && Quoted < 0)
Quoted = 0;
else if (!Qot && Quoted >= 0)
Qot = '"';
Fmtd = (!Sep || (am && (*am == 'F' || *am == 'f')));
Header = GetBoolCatInfo("Header", false);
Maxerr = GetIntCatInfo("Maxerr", 0);
Accept = GetBoolCatInfo("Accept", false);
if (Accept && Maxerr == 0)
Maxerr = INT_MAX32; // Accept all bad lines
return false;
} // end of DefineAM
/***********************************************************************/
/* GetTable: makes a new Table Description Block. */
/***********************************************************************/
PTDB CSVDEF::GetTable(PGLOBAL g, MODE mode)
{
PTDBASE tdbp;
if (Catfunc != FNC_COL) {
USETEMP tmp = UseTemp();
bool map = Mapped && mode != MODE_INSERT &&
!(tmp != TMP_NO && mode == MODE_UPDATE) &&
!(tmp == TMP_FORCE &&
(mode == MODE_UPDATE || mode == MODE_DELETE));
PTXF txfp;
/*******************************************************************/
/* Allocate a file processing class of the proper type. */
/*******************************************************************/
if (Zipped) {
#if defined(ZIP_SUPPORT)
if (mode == MODE_READ || mode == MODE_ANY || mode == MODE_ALTER) {
txfp = new(g) UNZFAM(this);
} else if (mode == MODE_INSERT) {
txfp = new(g) ZIPFAM(this);
} else {
strcpy(g->Message, "UPDATE/DELETE not supported for ZIP");
return NULL;
} // endif's mode
#else // !ZIP_SUPPORT
strcpy(g->Message, "ZIP not supported");
return NULL;
#endif // !ZIP_SUPPORT
} else if (map) {
// Should be now compatible with UNIX
txfp = new(g) MAPFAM(this);
} else if (Compressed) {
#if defined(GZ_SUPPORT)
if (Compressed == 1)
txfp = new(g) GZFAM(this);
else
txfp = new(g) ZLBFAM(this);
#else // !GZ_SUPPORT
strcpy(g->Message, "Compress not supported");
return NULL;
#endif // !GZ_SUPPORT
} else
txfp = new(g) DOSFAM(this);
/*******************************************************************/
/* Allocate a TDB of the proper type. */
/* Column blocks will be allocated only when needed. */
/*******************************************************************/
if (!Fmtd)
tdbp = new(g) TDBCSV(this, txfp);
else
tdbp = new(g) TDBFMT(this, txfp);
if (Multiple)
tdbp = new(g) TDBMUL(tdbp);
else
/*****************************************************************/
/* For block tables, get eventually saved optimization values. */
/*****************************************************************/
if (tdbp->GetBlockValues(g)) {
PushWarning(g, tdbp);
// return NULL; // causes a crash when deleting index
} else {
if (IsOptimized()) {
if (map) {
txfp = new(g) MBKFAM(this);
} else if (Compressed) {
#if defined(GZ_SUPPORT)
if (Compressed == 1)
txfp = new(g) ZBKFAM(this);
else {
txfp->SetBlkPos(To_Pos);
((PZLBFAM)txfp)->SetOptimized(To_Pos != NULL);
} // endelse
#else
sprintf(g->Message, MSG(NO_FEAT_SUPPORT), "GZ");
return NULL;
#endif
} else
txfp = new(g) BLKFAM(this);
((PTDBDOS)tdbp)->SetTxfp(txfp);
} // endif Optimized
} // endelse
} else
tdbp = new(g)TDBCCL(this);
return tdbp;
} // end of GetTable
/* -------------------------- Class TDBCSV --------------------------- */
/***********************************************************************/
/* Implementation of the TDBCSV class. */
/***********************************************************************/
TDBCSV::TDBCSV(PCSVDEF tdp, PTXF txfp) : TDBDOS(tdp, txfp)
{
#if defined(_DEBUG)
assert (tdp);
#endif
Field = NULL;
Offset = NULL;
Fldlen = NULL;
Fields = 0;
Nerr = 0;
Quoted = tdp->Quoted;
Maxerr = tdp->Maxerr;
Accept = tdp->Accept;
Header = tdp->Header;
Sep = tdp->GetSep();
Qot = tdp->GetQot();
} // end of TDBCSV standard constructor
TDBCSV::TDBCSV(PGLOBAL g, PTDBCSV tdbp) : TDBDOS(g, tdbp)
{
Fields = tdbp->Fields;
if (Fields) {
if (tdbp->Offset)
Offset = (int*)PlugSubAlloc(g, NULL, sizeof(int) * Fields);
if (tdbp->Fldlen)
Fldlen = (int*)PlugSubAlloc(g, NULL, sizeof(int) * Fields);
Field = (PSZ *)PlugSubAlloc(g, NULL, sizeof(PSZ) * Fields);
for (int i = 0; i < Fields; i++) {
if (Offset)
Offset[i] = tdbp->Offset[i];
if (Fldlen)
Fldlen[i] = tdbp->Fldlen[i];
if (Field) {
assert (Fldlen);
Field[i] = (PSZ)PlugSubAlloc(g, NULL, Fldlen[i] + 1);
Field[i][Fldlen[i]] = '\0';
} // endif Field
} // endfor i
} else {
Field = NULL;
Offset = NULL;
Fldlen = NULL;
} // endif Fields
Nerr = tdbp->Nerr;
Maxerr = tdbp->Maxerr;
Quoted = tdbp->Quoted;
Accept = tdbp->Accept;
Header = tdbp->Header;
Sep = tdbp->Sep;
Qot = tdbp->Qot;
} // end of TDBCSV copy constructor
// Method
PTDB TDBCSV::Clone(PTABS t)
{
PTDB tp;
PCSVCOL cp1, cp2;
PGLOBAL g = t->G; // Is this really useful ???
tp = new(g) TDBCSV(g, this);
for (cp1 = (PCSVCOL)Columns; cp1; cp1 = (PCSVCOL)cp1->GetNext()) {
cp2 = new(g) CSVCOL(cp1, tp); // Make a copy
NewPointer(t, cp1, cp2);
} // endfor cp1
return tp;
} // end of Clone
/***********************************************************************/
/* Allocate CSV column description block. */
/***********************************************************************/
PCOL TDBCSV::MakeCol(PGLOBAL g, PCOLDEF cdp, PCOL cprec, int n)
{
return new(g) CSVCOL(g, cdp, this, cprec, n);
} // end of MakeCol
/***********************************************************************/
/* Check whether the number of errors is greater than the maximum. */
/***********************************************************************/
bool TDBCSV::CheckErr(void)
{
return (++Nerr) > Maxerr;
} // end of CheckErr
/***********************************************************************/
/* CSV EstimatedLength. Returns an estimated minimum line length. */
/***********************************************************************/
int TDBCSV::EstimatedLength(void)
{
int n = 0;
PCOLDEF cdp;
if (trace)
htrc("EstimatedLength: Fields=%d Columns=%p\n", Fields, Columns);
for (cdp = To_Def->GetCols(); cdp; cdp = cdp->GetNext())
if (!cdp->IsSpecial() && !cdp->IsVirtual()) // A true column
n++;
return --n; // Number of separators if all fields are null
} // end of Estimated Length
#if 0
/***********************************************************************/
/* CSV tables needs the use temporary files for Update. */
/***********************************************************************/
bool TDBCSV::IsUsingTemp(PGLOBAL g)
{
return (Use_Temp == TMP_YES || Use_Temp == TMP_FORCE ||
(Use_Temp == TMP_AUTO && Mode == MODE_UPDATE));
} // end of IsUsingTemp
#endif // 0 (Same as TDBDOS one)
/***********************************************************************/
/* CSV Access Method opening routine. */
/* First allocate the Offset and Fldlen arrays according to the */
/* greatest field used in that query. Then call the DOS opening fnc. */
/***********************************************************************/
bool TDBCSV::OpenDB(PGLOBAL g)
{
bool rc = false;
PCOLDEF cdp;
PDOSDEF tdp = (PDOSDEF)To_Def;
if (Use != USE_OPEN && (Columns || Mode == MODE_UPDATE)) {
// Allocate the storage used to read (or write) records
int i, len;
PCSVCOL colp;
if (!Fields) // May have been set in TABFMT::OpenDB
if (Mode != MODE_UPDATE && Mode != MODE_INSERT) {
for (colp = (PCSVCOL)Columns; colp; colp = (PCSVCOL)colp->Next)
if (!colp->IsSpecial() && !colp->IsVirtual())
Fields = MY_MAX(Fields, (int)colp->Fldnum);
if (Columns)
Fields++; // Fldnum was 0 based
} else
for (cdp = tdp->GetCols(); cdp; cdp = cdp->GetNext())
if (!cdp->IsSpecial() && !cdp->IsVirtual())
Fields++;
Offset = (int*)PlugSubAlloc(g, NULL, sizeof(int) * Fields);
Fldlen = (int*)PlugSubAlloc(g, NULL, sizeof(int) * Fields);
if (Mode == MODE_INSERT || Mode == MODE_UPDATE) {
Field = (PSZ*)PlugSubAlloc(g, NULL, sizeof(PSZ) * Fields);
Fldtyp = (bool*)PlugSubAlloc(g, NULL, sizeof(bool) * Fields);
} // endif Mode
for (i = 0; i < Fields; i++) {
Offset[i] = 0;
Fldlen[i] = 0;
if (Field) {
Field[i] = NULL;
Fldtyp[i] = false;
} // endif Field
} // endfor i
if (Field)
// Prepare writing fields
if (Mode != MODE_UPDATE) {
for (colp = (PCSVCOL)Columns; colp; colp = (PCSVCOL)colp->Next)
if (!colp->IsSpecial() && !colp->IsVirtual()) {
i = colp->Fldnum;
len = colp->GetLength();
Field[i] = (PSZ)PlugSubAlloc(g, NULL, len + 1);
Field[i][len] = '\0';
Fldlen[i] = len;
Fldtyp[i] = IsTypeNum(colp->GetResultType());
} // endif colp
} else // MODE_UPDATE
for (cdp = tdp->GetCols(); cdp; cdp = cdp->GetNext())
if (!cdp->IsSpecial() && !cdp->IsVirtual()) {
i = cdp->GetOffset() - 1;
len = cdp->GetLength();
Field[i] = (PSZ)PlugSubAlloc(g, NULL, len + 1);
Field[i][len] = '\0';
Fldlen[i] = len;
Fldtyp[i] = IsTypeNum(cdp->GetType());
} // endif cdp
} // endif Use
if (Header) {
// Check that the Lrecl is at least equal to the header line length
int headlen = 0;
PCOLDEF cdp;
PDOSDEF tdp = (PDOSDEF)To_Def;
for (cdp = tdp->GetCols(); cdp; cdp = cdp->GetNext())
headlen += strlen(cdp->GetName()) + 3; // 3 if names are quoted
if (headlen > Lrecl) {
Lrecl = headlen;
Txfp->Lrecl = headlen;
} // endif headlen
} // endif Header
Nerr = 0;
rc = TDBDOS::OpenDB(g);
if (!rc && Mode == MODE_UPDATE && To_Kindex)
// Because KINDEX::Init is executed in mode READ, we must restore
// the Fldlen array that was modified when reading the table file.
for (cdp = tdp->GetCols(); cdp; cdp = cdp->GetNext())
Fldlen[cdp->GetOffset() - 1] = cdp->GetLength();
return rc;
} // end of OpenDB
/***********************************************************************/
/* SkipHeader: Physically skip first header line if applicable. */
/* This is called from TDBDOS::OpenDB and must be executed before */
/* Kindex construction if the file is accessed using an index. */
/***********************************************************************/
bool TDBCSV::SkipHeader(PGLOBAL g)
{
int len = GetFileLength(g);
bool rc = false;
#if defined(_DEBUG)
if (len < 0)
return true;
#endif // _DEBUG
if (Header) {
if (Mode == MODE_INSERT) {
if (!len) {
// New file, the header line must be constructed and written
int i, n = 0;
int hlen = 0;
bool q = Qot && Quoted > 0;
PCOLDEF cdp;
// Estimate the length of the header list
for (cdp = To_Def->GetCols(); cdp; cdp = cdp->GetNext()) {
hlen += (1 + strlen(cdp->GetName()));
hlen += ((q) ? 2 : 0);
n++; // Calculate the number of columns
} // endfor cdp
if (hlen > Lrecl) {
sprintf(g->Message, MSG(LRECL_TOO_SMALL), hlen);
return true;
} // endif hlen
// File is empty, write a header record
memset(To_Line, 0, Lrecl);
// The column order in the file is given by the offset value
for (i = 1; i <= n; i++)
for (cdp = To_Def->GetCols(); cdp; cdp = cdp->GetNext())
if (cdp->GetOffset() == i) {
if (q)
To_Line[strlen(To_Line)] = Qot;
strcat(To_Line, cdp->GetName());
if (q)
To_Line[strlen(To_Line)] = Qot;
if (i < n)
To_Line[strlen(To_Line)] = Sep;
} // endif Offset
rc = (Txfp->WriteBuffer(g) == RC_FX);
} // endif !FileLength
} else if (Mode == MODE_DELETE) {
if (len)
rc = (Txfp->SkipRecord(g, true) == RC_FX);
} else if (len) // !Insert && !Delete
rc = (Txfp->SkipRecord(g, false) == RC_FX || Txfp->RecordPos(g));
} // endif Header
return rc;
} // end of SkipHeader
/***********************************************************************/
/* ReadBuffer: Physical read routine for the CSV access method. */
/***********************************************************************/
int TDBCSV::ReadBuffer(PGLOBAL g)
{
//char *p1, *p2, *p = NULL;
char *p2, *p = NULL;
int i, n, len, rc = Txfp->ReadBuffer(g);
bool bad = false;
if (trace > 1)
htrc("CSV: Row is '%s' rc=%d\n", To_Line, rc);
if (rc != RC_OK || !Fields)
return rc;
else
p2 = To_Line;
// Find the offsets and lengths of the columns for this row
for (i = 0; i < Fields; i++) {
if (!bad) {
if (Qot && *p2 == Qot) { // Quoted field
//for (n = 0, p1 = ++p2; (p = strchr(p1, Qot)); p1 = p + 2)
// if (*(p + 1) == Qot)
// n++; // Doubled internal quotes
// else
// break; // Final quote
for (n = 0, p = ++p2; p; p++)
if (*p == Qot || *p == '\\') {
if (*(++p) == Qot)
n++; // Escaped internal quotes
else if (*(p - 1) == Qot)
break; // Final quote
} // endif *p
if (p) {
//len = p++ - p2;
len = (int)(p - p2 - 1);
// if (Sep != ' ')
// for (; *p == ' '; p++) ; // Skip blanks
if (*p != Sep && i != Fields - 1) { // Should be the separator
if (CheckErr()) {
sprintf(g->Message, MSG(MISSING_FIELD),
i+1, Name, RowNumber(g));
return RC_FX;
} else if (Accept)
bad = true;
else
return RC_NF;
} // endif p
if (n) {
int j, k;
// Suppress the escape of internal quotes
for (j = k = 0; j < len; j++, k++) {
if (p2[j] == Qot || (p2[j] == '\\' && p2[j + 1] == Qot))
j++; // skip escape char
else if (p2[j] == '\\')
p2[k++] = p2[j++]; // avoid \\Qot
p2[k] = p2[j];
} // endfor i, j
len -= n;
} // endif n
} else if (CheckErr()) {
sprintf(g->Message, MSG(BAD_QUOTE_FIELD),
Name, i+1, RowNumber(g));
return RC_FX;
} else if (Accept) {
len = strlen(p2);
bad = true;
} else
return RC_NF;
} else if ((p = strchr(p2, Sep)))
len = (int)(p - p2);
else if (i == Fields - 1)
len = strlen(p2);
else if (Accept && Maxerr == 0) {
len = strlen(p2);
bad = true;
} else if (CheckErr()) {
sprintf(g->Message, MSG(MISSING_FIELD), i+1, Name, RowNumber(g));
return RC_FX;
} else if (Accept) {
len = strlen(p2);
bad = true;
} else
return RC_NF;
} else
len = 0;
Offset[i] = (int)(p2 - To_Line);
if (Mode != MODE_UPDATE)
Fldlen[i] = len;
else if (len > Fldlen[i]) {
sprintf(g->Message, MSG(FIELD_TOO_LONG), i+1, RowNumber(g));
return RC_FX;
} else {
strncpy(Field[i], p2, len);
Field[i][len] = '\0';
} // endif Mode
if (p)
p2 = p + 1;
} // endfor i
return rc;
} // end of ReadBuffer
/***********************************************************************/
/* Prepare the line to write. */
/***********************************************************************/
bool TDBCSV::PrepareWriting(PGLOBAL g)
{
char sep[2], qot[2];
int i, nlen, oldlen = strlen(To_Line);
if (trace > 1)
htrc("CSV WriteDB: R%d Mode=%d key=%p link=%p\n",
Tdb_No, Mode, To_Key_Col, To_Link);
// Before writing the line we must check its length
if ((nlen = CheckWrite(g)) < 0)
return true;
// Before writing the line we must make it
sep[0] = Sep;
sep[1] = '\0';
qot[0] = Qot;
qot[1] = '\0';
*To_Line = '\0';
for (i = 0; i < Fields; i++) {
if (i)
strcat(To_Line, sep);
if (Field[i])
if (!strlen(Field[i])) {
// Generally null fields are not quoted
if (Quoted > 2)
// Except if explicitely required
strcat(strcat(To_Line, qot), qot);
} else if (Qot && (strchr(Field[i], Sep) || *Field[i] == Qot
|| Quoted > 1 || (Quoted == 1 && !Fldtyp[i])))
if (strchr(Field[i], Qot)) {
// Field contains quotes that must be doubled
int j, k = strlen(To_Line), n = strlen(Field[i]);
To_Line[k++] = Qot;
for (j = 0; j < n; j++) {
if (Field[i][j] == Qot)
To_Line[k++] = Qot;
To_Line[k++] = Field[i][j];
} // endfor j
To_Line[k++] = Qot;
To_Line[k] = '\0';
} else
strcat(strcat(strcat(To_Line, qot), Field[i]), qot);
else
strcat(To_Line, Field[i]);
} // endfor i
#if defined(_DEBUG)
assert ((unsigned)nlen == strlen(To_Line));
#endif
if (Mode == MODE_UPDATE && nlen < oldlen
&& !((PDOSFAM)Txfp)->GetUseTemp()) {
// In Update mode with no temp file, line length must not change
To_Line[nlen] = Sep;
for (nlen++; nlen < oldlen; nlen++)
To_Line[nlen] = ' ';
To_Line[nlen] = '\0';
} // endif
if (trace > 1)
htrc("Write: line is=%s", To_Line);
return false;
} // end of PrepareWriting
/***********************************************************************/
/* Data Base write routine CSV file access method. */
/***********************************************************************/
int TDBCSV::WriteDB(PGLOBAL g)
{
// Before writing the line we must check and prepare it
if (PrepareWriting(g))
return RC_FX;
/*********************************************************************/
/* Now start the writing process. */
/*********************************************************************/
return Txfp->WriteBuffer(g);
} // end of WriteDB
/***********************************************************************/
/* Check whether a new line fit in the file lrecl size. */
/***********************************************************************/
int TDBCSV::CheckWrite(PGLOBAL g)
{
int maxlen, n, nlen = (Fields - 1);
if (trace > 1)
htrc("CheckWrite: R%d Mode=%d\n", Tdb_No, Mode);
// Before writing the line we must check its length
maxlen = (Mode == MODE_UPDATE && !Txfp->GetUseTemp())
? strlen(To_Line) : Lrecl;
// Check whether record is too int
for (int i = 0; i < Fields; i++)
if (Field[i]) {
if (!(n = strlen(Field[i])))
n += (Quoted > 2 ? 2 : 0);
else if (strchr(Field[i], Sep) || (Qot && *Field[i] == Qot)
|| Quoted > 1 || (Quoted == 1 && !Fldtyp[i]))
if (!Qot) {
sprintf(g->Message, MSG(SEP_IN_FIELD), i + 1);
return -1;
} else {
// Quotes inside a quoted field must be doubled
char *p1, *p2;
for (p1 = Field[i]; (p2 = strchr(p1, Qot)); p1 = p2 + 1)
n++;
n += 2; // Outside quotes
} // endif
if ((nlen += n) > maxlen) {
strcpy(g->Message, MSG(LINE_TOO_LONG));
return -1;
} // endif nlen
} // endif Field
return nlen;
} // end of CheckWrite
/* ------------------------------------------------------------------- */
/***********************************************************************/
/* Implementation of the TDBFMT class. */
/***********************************************************************/
TDBFMT::TDBFMT(PGLOBAL g, PTDBFMT tdbp) : TDBCSV(g, tdbp)
{
FldFormat = tdbp->FldFormat;
To_Fld = tdbp->To_Fld;
FmtTest = tdbp->FmtTest;
Linenum = tdbp->Linenum;
} // end of TDBFMT copy constructor
// Method
PTDB TDBFMT::Clone(PTABS t)
{
PTDB tp;
PCSVCOL cp1, cp2;
//PFMTCOL cp1, cp2;
PGLOBAL g = t->G; // Is this really useful ???
tp = new(g) TDBFMT(g, this);
for (cp1 = (PCSVCOL)Columns; cp1; cp1 = (PCSVCOL)cp1->GetNext()) {
//for (cp1 = (PFMTCOL)Columns; cp1; cp1 = (PFMTCOL)cp1->GetNext()) {
cp2 = new(g) CSVCOL(cp1, tp); // Make a copy
// cp2 = new(g) FMTCOL(cp1, tp); // Make a copy
NewPointer(t, cp1, cp2);
} // endfor cp1
return tp;
} // end of Clone
/***********************************************************************/
/* Allocate FMT column description block. */
/***********************************************************************/
PCOL TDBFMT::MakeCol(PGLOBAL g, PCOLDEF cdp, PCOL cprec, int n)
{
return new(g) CSVCOL(g, cdp, this, cprec, n);
//return new(g) FMTCOL(cdp, this, cprec, n);
} // end of MakeCol
/***********************************************************************/
/* FMT EstimatedLength. Returns an estimated minimum line length. */
/* The big problem here is how can we astimated that minimum ? */
/***********************************************************************/
int TDBFMT::EstimatedLength(void)
{
// This is rather stupid !!!
return ((PDOSDEF)To_Def)->GetEnding() + (int)((Lrecl / 10) + 1);
} // end of EstimatedLength
/***********************************************************************/
/* FMT Access Method opening routine. */
/***********************************************************************/
bool TDBFMT::OpenDB(PGLOBAL g)
{
Linenum = 0;
if (Mode == MODE_INSERT || Mode == MODE_UPDATE) {
sprintf(g->Message, MSG(FMT_WRITE_NIY), "FMT");
return true; // NIY
} // endif Mode
if (Use != USE_OPEN && Columns) {
// Make the formats used to read records
PSZ pfm;
int i, n;
PCSVCOL colp;
PCOLDEF cdp;
PDOSDEF tdp = (PDOSDEF)To_Def;
for (colp = (PCSVCOL)Columns; colp; colp = (PCSVCOL)colp->Next)
if (!colp->IsSpecial() && !colp->IsVirtual()) // a true column
Fields = MY_MAX(Fields, (int)colp->Fldnum);
if (Columns)
Fields++; // Fldnum was 0 based
To_Fld = PlugSubAlloc(g, NULL, Lrecl + 1);
FldFormat = (PSZ*)PlugSubAlloc(g, NULL, sizeof(PSZ) * Fields);
memset(FldFormat, 0, sizeof(PSZ) * Fields);
FmtTest = (int*)PlugSubAlloc(g, NULL, sizeof(int) * Fields);
memset(FmtTest, 0, sizeof(int) * Fields);
// Get the column formats
for (cdp = tdp->GetCols(); cdp; cdp = cdp->GetNext())
if (!cdp->IsSpecial() && !cdp->IsVirtual()
&& (i = cdp->GetOffset() - 1) < Fields) {
if (!(pfm = cdp->GetFmt())) {
sprintf(g->Message, MSG(NO_FLD_FORMAT), i + 1, Name);
return true;
} // endif pfm
// Roughly check the Fmt format
if ((n = strlen(pfm) - 2) < 4) {
sprintf(g->Message, MSG(BAD_FLD_FORMAT), i + 1, Name);
return true;
} // endif n
FldFormat[i] = (PSZ)PlugSubAlloc(g, NULL, n + 5);
strcpy(FldFormat[i], pfm);
if (!strcmp(pfm + n, "%m")) {
// This is a field that can be missing. Flag it so it can
// be handled with special processing.
FldFormat[i][n+1] = 'n'; // To have sscanf normal processing
FmtTest[i] = 2;
} else if (i+1 < Fields && strcmp(pfm + n, "%n")) {
// There are trailing characters after the field contents
// add a marker for the next field start position.
strcat(FldFormat[i], "%n");
FmtTest[i] = 1;
} // endif's
} // endif i
} // endif Use
return TDBCSV::OpenDB(g);
} // end of OpenDB
/***********************************************************************/
/* ReadBuffer: Physical read routine for the FMT access method. */
/***********************************************************************/
int TDBFMT::ReadBuffer(PGLOBAL g)
{
int i, len, n, deb, fin, nwp, pos = 0, rc;
bool bad = false;
if ((rc = Txfp->ReadBuffer(g)) != RC_OK || !Fields)
return rc;
else
++Linenum;
if (trace > 1)
htrc("FMT: Row %d is '%s' rc=%d\n", Linenum, To_Line, rc);
// Find the offsets and lengths of the columns for this row
for (i = 0; i < Fields; i++) {
if (!bad) {
deb = fin = -1;
if (!FldFormat[i]) {
n = 0;
} else if (FmtTest[i] == 1) {
nwp = -1;
n = sscanf(To_Line + pos, FldFormat[i], &deb, To_Fld, &fin, &nwp);
} else {
n = sscanf(To_Line + pos, FldFormat[i], &deb, To_Fld, &fin);
if (n != 1 && (deb >= 0 || i == Fields - 1) && FmtTest[i] == 2) {
// Missing optional field, not an error
n = 1;
if (i == Fields - 1)
fin = deb = 0;
else
fin = deb;
} // endif n
nwp = fin;
} // endif i
if (n != 1 || deb < 0 || fin < 0 || nwp < 0) {
// This is to avoid a very strange sscanf bug occuring
// with fields that ends with a null character.
// This bug causes subsequent sscanf to return in error,
// so next lines are not parsed correctly.
sscanf("a", "%*c"); // Seems to reset things Ok
if (CheckErr()) {
sprintf(g->Message, MSG(BAD_LINEFLD_FMT), Linenum, i + 1, Name);
return RC_FX;
} else if (Accept)
bad = true;
else
return RC_NF;
} // endif n...
} // endif !bad
if (!bad) {
Offset[i] = pos + deb;
len = fin - deb;
} else {
nwp = 0;
Offset[i] = pos;
len = 0;
} // endif bad
// if (Mode != MODE_UPDATE)
Fldlen[i] = len;
// else if (len > Fldlen[i]) {
// sprintf(g->Message, MSG(FIELD_TOO_LONG), i+1, To_Tdb->RowNumber(g));
// return RC_FX;
// } else {
// strncpy(Field[i], To_Line + pos, len);
// Field[i][len] = '\0';
// } // endif Mode
pos += nwp;
} // endfor i
if (bad)
Nerr++;
else
sscanf("a", "%*c"); // Seems to reset things Ok
return rc;
} // end of ReadBuffer
/***********************************************************************/
/* Data Base write routine FMT file access method. */
/***********************************************************************/
int TDBFMT::WriteDB(PGLOBAL g)
{
sprintf(g->Message, MSG(FMT_WRITE_NIY), "FMT");
return RC_FX; // NIY
} // end of WriteDB
// ------------------------ CSVCOL functions ----------------------------
/***********************************************************************/
/* CSVCOL public constructor */
/***********************************************************************/
CSVCOL::CSVCOL(PGLOBAL g, PCOLDEF cdp, PTDB tdbp, PCOL cprec, int i)
: DOSCOL(g, cdp, tdbp, cprec, i, "CSV")
{
Fldnum = Deplac - 1;
Deplac = 0;
} // end of CSVCOL constructor
/***********************************************************************/
/* CSVCOL constructor used for copying columns. */
/* tdbp is the pointer to the new table descriptor. */
/***********************************************************************/
CSVCOL::CSVCOL(CSVCOL *col1, PTDB tdbp) : DOSCOL(col1, tdbp)
{
Fldnum = col1->Fldnum;
} // end of CSVCOL copy constructor
/***********************************************************************/
/* VarSize: This function tells UpdateDB whether or not the block */
/* optimization file must be redone if this column is updated, even */
/* it is not sorted or clustered. This applies to a blocked table, */
/* because if it is updated using a temporary file, the block size */
/* may be modified. */
/***********************************************************************/
bool CSVCOL::VarSize(void)
{
PTXF txfp = ((PTDBCSV)To_Tdb)->Txfp;
if (txfp->IsBlocked() && txfp->GetUseTemp())
// Blocked table using a temporary file
return true;
else
return false;
} // end VarSize
/***********************************************************************/
/* ReadColumn: call DOSCOL::ReadColumn after having set the offet */
/* and length of the field to read as calculated by TDBCSV::ReadDB. */
/***********************************************************************/
void CSVCOL::ReadColumn(PGLOBAL g)
{
int rc;
PTDBCSV tdbp = (PTDBCSV)To_Tdb;
/*********************************************************************/
/* If physical reading of the line was deferred, do it now. */
/*********************************************************************/
if (!tdbp->IsRead())
if ((rc = tdbp->ReadBuffer(g)) != RC_OK) {
if (rc == RC_EF)
sprintf(g->Message, MSG(INV_DEF_READ), rc);
throw 34;
} // endif
if (tdbp->Mode != MODE_UPDATE) {
int colen = Long; // Column length
// Set the field offset and length for this row
Deplac = tdbp->Offset[Fldnum]; // Field offset
Long = tdbp->Fldlen[Fldnum]; // Field length
if (trace > 1)
htrc("CSV ReadColumn %s Fldnum=%d offset=%d fldlen=%d\n",
Name, Fldnum, Deplac, Long);
if (Long > colen && tdbp->CheckErr()) {
Long = colen; // Restore column length
sprintf(g->Message, MSG(FLD_TOO_LNG_FOR),
Fldnum + 1, Name, To_Tdb->RowNumber(g), tdbp->GetFile(g));
throw 34;
} // endif Long
// Now do the reading
DOSCOL::ReadColumn(g);
// Restore column length
Long = colen;
} else { // Mode Update
// Field have been copied in TDB Field array
PSZ fp = tdbp->Field[Fldnum];
if (Dsp)
for (int i = 0; fp[i]; i++)
if (fp[i] == Dsp)
fp[i] = '.';
Value->SetValue_psz(fp);
// Set null when applicable
if (Nullable)
Value->SetNull(Value->IsZero());
} // endif Mode
} // end of ReadColumn
/***********************************************************************/
/* WriteColumn: The column is written in TDBCSV matching Field. */
/***********************************************************************/
void CSVCOL::WriteColumn(PGLOBAL g)
{
char *p, buf[64];
int flen;
PTDBCSV tdbp = (PTDBCSV)To_Tdb;
if (trace > 1)
htrc("CSV WriteColumn: col %s R%d coluse=%.4X status=%.4X\n",
Name, tdbp->GetTdb_No(), ColUse, Status);
flen = GetLength();
if (trace > 1)
htrc("Lrecl=%d Long=%d field=%d coltype=%d colval=%p\n",
tdbp->Lrecl, Long, flen, Buf_Type, Value);
/*********************************************************************/
/* Check whether the new value has to be converted to Buf_Type. */
/*********************************************************************/
if (Value != To_Val)
Value->SetValue_pval(To_Val, false); // Convert the updated value
/*********************************************************************/
/* Get the string representation of the column value. */
/*********************************************************************/
p = Value->ShowValue(buf);
if (trace > 1)
htrc("new length(%p)=%d\n", p, strlen(p));
if ((signed)strlen(p) > flen) {
sprintf(g->Message, MSG(BAD_FLD_LENGTH), Name, p, flen,
tdbp->RowNumber(g), tdbp->GetFile(g));
throw 34;
} else if (Dsp)
for (int i = 0; p[i]; i++)
if (p[i] == '.')
p[i] = Dsp;
if (trace > 1)
htrc("buffer=%s\n", p);
/*********************************************************************/
/* Updating must be done also during the first pass so writing the */
/* updated record can be checked for acceptable record length. */
/*********************************************************************/
if (Fldnum < 0) {
// This can happen for wrong offset value in XDB files
sprintf(g->Message, MSG(BAD_FIELD_RANK), Fldnum + 1, Name);
throw 34;
} else
strncpy(tdbp->Field[Fldnum], p, flen);
if (trace > 1)
htrc(" col written: '%s'\n", p);
} // end of WriteColumn
/* ---------------------------TDBCCL class --------------------------- */
/***********************************************************************/
/* TDBCCL class constructor. */
/***********************************************************************/
TDBCCL::TDBCCL(PCSVDEF tdp) : TDBCAT(tdp)
{
Topt = tdp->GetTopt();
} // end of TDBCCL constructor
/***********************************************************************/
/* GetResult: Get the list the CSV file columns. */
/***********************************************************************/
PQRYRES TDBCCL::GetResult(PGLOBAL g)
{
return CSVColumns(g, ((PTABDEF)To_Def)->GetPath(), Topt, false);
} // end of GetResult
/* ------------------------ End of TabFmt ---------------------------- */
| 31.916827 | 77 | 0.434972 | jiunbae |
f617dbf2f2a635fcb5e8a5a3993d00b80ded8790 | 13,969 | cpp | C++ | sources/cpp/wasmint/main.cpp | xunilrj/sandbox | f92c12f83433cac01a885585e41c02bb5826a01f | [
"Apache-2.0"
] | 7 | 2017-04-01T17:18:35.000Z | 2022-01-12T05:23:23.000Z | sources/cpp/wasmint/main.cpp | xunilrj/sandbox | f92c12f83433cac01a885585e41c02bb5826a01f | [
"Apache-2.0"
] | 6 | 2020-05-24T13:36:50.000Z | 2022-02-15T06:44:20.000Z | sources/cpp/wasmint/main.cpp | xunilrj/sandbox | f92c12f83433cac01a885585e41c02bb5826a01f | [
"Apache-2.0"
] | 2 | 2018-09-20T01:07:39.000Z | 2019-02-22T14:55:38.000Z | #define CATCH_CONFIG_MAIN
#include "../catch/catch.hpp"
#include <Windows.h>
#include <string>
#include <stack>
#include <unordered_map>
template <typename T>
T &read(uint8_t *&p)
{
auto *ptr = (T *)p;
p += sizeof(T);
return *ptr;
}
uint32_t readULEB128(uint8_t *&p)
{
uint32_t result = 0;
uint32_t shift = 0;
while (true)
{
uint8_t byte = (*p);
++p;
result |= (byte & 0b01111111) << shift;
if ((byte & 0b10000000) == 0)
break;
shift += 7;
}
return result;
}
int32_t readLEB128(uint8_t *&p)
{
size_t size = 32;
int32_t result = 0;
int32_t shift = 0;
uint8_t byte;
do
{
byte = (*p);
++p;
result |= (byte & 0b01111111) << shift;
shift += 7;
} while ((byte & 0b10000000) != 0);
if ((shift < size) && (byte & 0b10000000))
result |= (~0 << shift);
return result;
}
std::string readString(uint8_t *&p)
{
auto nameSize = readULEB128(p);
auto str = std::string((char *)p, nameSize);
p += nameSize;
return str;
}
float readFloat(uint8_t *&p)
{
auto v = *(float *)p;
p += 4;
return v;
}
template <typename T>
std::vector<T> readVector(uint8_t *&p)
{
auto v = std::vector<T>{};
auto vectorSize = readULEB128(p);
while (vectorSize > 0)
{
auto item = T::read(p);
v.push_back(item);
--vectorSize;
}
return v;
}
uint8_t readOPCode(uint8_t *&p)
{
auto opcode = *p;
++p;
return opcode;
}
namespace wasm
{
struct TypeSection
{
uint8_t id;
uint32_t size;
};
struct Export
{
static Export read(uint8_t *&p)
{
auto name = ::readString(p);
auto type = ::read<uint8_t>(p);
auto idx = ::read<uint8_t>(p);
return {name, type, idx};
}
std::string name;
uint8_t type;
uint8_t idx;
};
struct ExportSection
{
static ExportSection read(uint8_t *&p)
{
auto size = readULEB128(p);
auto exports = readVector<wasm::Export>(p);
auto temp = ExportSection{size, exports};
temp.buildIndex();
return temp;
}
uint32_t size;
std::vector<Export> exports;
ExportSection()
{
}
ExportSection(uint32_t size, const std::vector<Export> &exports) : size{size}, exports{exports}
{
}
const Export *operator[](const std::string &name) const
{
auto it = byName.find(name);
if (it != byName.end())
return it->second;
else
return nullptr;
}
private:
std::unordered_map<std::string, Export *> byName;
void buildIndex()
{
byName.clear();
for (auto &&exp : exports)
{
byName.emplace(exp.name, &exp);
}
}
};
struct CodeLocal
{
static CodeLocal read(uint8_t *&p)
{
auto n = readULEB128(p);
auto type = readLEB128(p);
return {n, type};
}
uint32_t n;
int32_t type;
};
struct Code
{
static Code read(uint8_t *&p)
{
auto size = readULEB128(p);
auto end = p + size;
auto locals = readVector<wasm::CodeLocal>(p);
auto temp = Code{size, locals, p};
p = end;
return temp;
}
uint32_t size;
std::vector<CodeLocal> locals;
uint8_t *start;
};
struct CodeSection
{
static CodeSection read(uint8_t *&p)
{
auto size = ::readULEB128(p);
auto codes = ::readVector<wasm::Code>(p);
return {size, codes};
}
uint32_t size;
std::vector<Code> codes;
};
struct Import
{
static Import read(uint8_t *&p)
{
auto mod = ::readString(p);
auto name = ::readString(p);
auto type = ::read<uint8_t>(p);
auto param1 = ::readULEB128(p);
return {mod, name, type, param1};
}
std::string mod;
std::string name;
uint8_t type;
uint32_t param1;
};
struct ImportSection
{
static ImportSection read(uint8_t *&p)
{
auto size = ::readULEB128(p);
auto imports = ::readVector<wasm::Import>(p);
return {size, imports};
}
uint32_t size;
std::vector<Import> imports;
};
struct Func
{
static Func read(uint8_t *&p)
{
auto typeidx = ::readULEB128(p);
return {typeidx};
}
uint32_t typeidx;
};
struct FuncSection
{
static FuncSection read(uint8_t *&p)
{
auto size = ::readULEB128(p);
auto funcs = ::readVector<wasm::Func>(p);
return {size, funcs};
}
uint32_t size;
std::vector<Func> funcs;
};
struct FuncRecord
{
static FuncRecord import(Import *imp)
{
return {true, imp, 0};
}
static FuncRecord code(uint32_t idx, Code code)
{
return {false, nullptr, idx};
}
bool imported;
Import *imp;
uint32_t codeidx;
};
struct FunctionRegister
{
std::vector<FuncRecord> funcs;
};
namespace execution
{
struct value
{
union
{
int32_t i32;
int64_t i64;
uint32_t u32;
uint64_t u64;
float f32;
double f64;
};
value(int32_t v) : i32{v} {}
value(float v) : f32{v} {}
};
struct callframe
{
FunctionRegister *funcs;
uint8_t *IP;
};
enum class step_result_type
{
normal,
end,
call_imported
};
struct step_result_call_imported
{
FuncRecord *f;
};
struct step_result
{
step_result_type type;
union
{
step_result_call_imported call_imported;
};
step_result() {}
step_result(step_result_type type) : type{type}
{
}
step_result(step_result_call_imported imp)
: type{step_result_type::call_imported}, call_imported{imp}
{
}
};
struct thread
{
std::stack<callframe> callstack;
std::stack<value> valuestack;
thread(FunctionRegister *mod, uint8_t *ip)
{
if (ip != nullptr)
callstack.push({mod, ip});
}
step_result step()
{
if (callstack.size() == 0)
return {step_result_type::end};
auto &callframe = callstack.top();
uint8_t *&IP = callframe.IP;
//https://developercommunity.visualstudio.com/idea/965226/supoport-the-labels-as-values-in-cc-compiler-to-he.html
//https://gcc.gnu.org/onlinedocs/gcc/Labels-as-Values.html
//https://eli.thegreenplace.net/2012/07/12/computed-goto-for-efficient-dispatch-tables
static void *dispatch_table[] = {
0, 0, 0, 0, 0, 0, 0, 0,
0, 0, 0, 0, 0, 0, 0, 0,
&&call};
auto opcode = readOPCode(IP);
// 0x10 x:funcidx => call x
if (opcode == 0x10)
{
call:
auto operand = readULEB128(IP);
auto &f = callframe.funcs->funcs[operand];
if (f.imported)
{
return {step_result_call_imported{&f}};
}
//TODO find this function
}
else if (opcode == 0x41)
{
auto operand = readLEB128(IP);
valuestack.push(operand);
}
else if (opcode == 0x43)
{
auto operand = readFloat(IP);
valuestack.push(operand);
}
else if (opcode == 0x0b)
{
callstack.pop();
//end
return {step_result_type::end};
}
return {step_result_type::normal};
}
step_result stepUntilImport()
{
step_result r;
do
{
r = step();
} while (r.type != step_result_type::call_imported);
return r;
}
};
} // namespace execution
struct ModuleHeader
{
char magic[4];
uint32_t version;
};
struct Module
{
ModuleHeader header;
ExportSection exportSection;
CodeSection codeSection;
ImportSection importSection;
FuncSection funcSection;
FunctionRegister funcRegister;
static Module from(uint8_t *&p)
{
auto mod = wasm::Module{};
mod.header = read<wasm::ModuleHeader>(p);
return mod;
}
void readAllSections(uint8_t *&p, uint32_t size)
{
auto lastSection = 0;
while (size > 0)
{
auto [section, read] = readSection(p);
size -= read;
if (read == 0)
break;
lastSection = section;
auto nextSection = *p;
if ((nextSection < 0) && (nextSection >= 11))
break;
}
//assert(size == 0); //file bigger than necessary. Why?
setupFuncRegister();
}
std::tuple<int8_t, uint32_t> readSection(uint8_t *&p)
{
auto sectionType = read<uint8_t>(p);
switch (sectionType)
{
case 2:
{
importSection = wasm::ImportSection::read(p);
return {sectionType, importSection.size};
}
case 3:
{
funcSection = wasm::FuncSection::read(p);
return {sectionType, funcSection.size};
}
case 7:
{
exportSection = wasm::ExportSection::read(p);
return {sectionType, exportSection.size};
}
case 10:
{
codeSection = wasm::CodeSection::read(p);
return {sectionType, codeSection.size};
}
default:
{
auto size = readULEB128(p);
p += size;
return {sectionType, size};
}
}
return {-1, 0};
}
void setupFuncRegister()
{
for (auto &&x : importSection.imports)
{
funcRegister.funcs.emplace_back(FuncRecord::import(&x));
}
for (auto i = 0; i < codeSection.codes.size(); ++i)
{
auto &x = codeSection.codes[i];
funcRegister.funcs.emplace_back(FuncRecord::code(i, x));
}
}
execution::thread spawn(const std::string &name)
{
auto *exp = exportSection[name];
if (exp == nullptr)
return {&funcRegister, nullptr};
auto codeidx = funcRegister.funcs[exp->idx].codeidx;
auto code = codeSection.codes[codeidx];
return execution::thread{&funcRegister, code.start};
}
};
} // namespace wasm
TEST_CASE("Fake.Test.Will Pass", "[ok]")
{
// //auto fileName = TEXT("D:/github/sandbox/sources/cpp/wasmint/example1.wasm");
// auto fileName = TEXT("D:/github/sandbox/sources/cpp/wasmint/script.c.wasm");
// SYSTEM_INFO SysInfo;
// GetSystemInfo(&SysInfo);
// DWORD dwSysGran = SysInfo.dwAllocationGranularity;
// DWORD FILE_MAP_START = 0;
// DWORD BUFFSIZE = 1024;
// DWORD dwFileMapStart = (FILE_MAP_START / dwSysGran) * dwSysGran;
// DWORD dwFileMapSize = FILE_MAP_START + BUFFSIZE;
// DWORD dwMapViewSize = (FILE_MAP_START % dwSysGran) + BUFFSIZE;
// HANDLE hFile = CreateFile(fileName,
// GENERIC_READ | GENERIC_WRITE,
// 0,
// NULL,
// OPEN_EXISTING,
// FILE_ATTRIBUTE_NORMAL,
// NULL);
// REQUIRE(hFile != INVALID_HANDLE_VALUE);
// DWORD dwFileSize = GetFileSize(hFile, nullptr);
// HANDLE hMapFile = CreateFileMapping(hFile,
// NULL,
// PAGE_READWRITE,
// 0,
// dwFileMapSize,
// NULL);
// REQUIRE(hMapFile != NULL);
// auto *lpMapAddress = (uint8_t *)MapViewOfFile(hMapFile,
// FILE_MAP_ALL_ACCESS,
// 0,
// dwFileMapStart,
// dwMapViewSize);
// REQUIRE(lpMapAddress != NULL);
// auto mod = wasm::Module::from(lpMapAddress);
// auto t = mod.spawn("helloWorld1");
// auto r = t.stepUntilImport();
} | 23.919521 | 129 | 0.455222 | xunilrj |
f619649cdc5f0e650489a927b1e3198de377f5df | 5,105 | cpp | C++ | GlobalIllumination/src/Material.cpp | raptoravis/voxelbasedgi | aaf2b02929edfaf72528c2f029696728c5f1d30f | [
"MIT"
] | null | null | null | GlobalIllumination/src/Material.cpp | raptoravis/voxelbasedgi | aaf2b02929edfaf72528c2f029696728c5f1d30f | [
"MIT"
] | null | null | null | GlobalIllumination/src/Material.cpp | raptoravis/voxelbasedgi | aaf2b02929edfaf72528c2f029696728c5f1d30f | [
"MIT"
] | null | null | null | #include <stdafx.h>
#include <Demo.h>
#include <Material.h>
#define NUM_RENDER_STATES 27 // number of render-states that can be specified in material file
struct MaterialInfo
{
const char *name; // info as string
int mode; // info as int
};
// render-states
static const MaterialInfo renderStateList[NUM_RENDER_STATES] =
{
"NONE_CULL",NONE_CULL, "FRONT_CULL",FRONT_CULL, "BACK_CULL",BACK_CULL,
"ZERO_BLEND",ZERO_BLEND, "ONE_BLEND",ONE_BLEND, "SRC_COLOR_BLEND",SRC_COLOR_BLEND,
"INV_SRC_COLOR_BLEND",INV_SRC_COLOR_BLEND, "DST_COLOR_BLEND",DST_COLOR_BLEND,
"INV_DST_COLOR_BLEND",INV_DST_COLOR_BLEND, "SRC_ALPHA_BLEND",SRC_ALPHA_BLEND,
"INV_SRC_ALPHA_BLEND",INV_SRC_ALPHA_BLEND, "DST_ALPHA_BLEND",DST_ALPHA_BLEND,
"INV_DST_ALPHA_BLEND",INV_DST_ALPHA_BLEND, "CONST_COLOR_BLEND",CONST_COLOR_BLEND,
"INV_CONST_COLOR_BLEND",INV_CONST_COLOR_BLEND, "CONST_ALPHA_BLEND",CONST_ALPHA_BLEND,
"INV_CONST_ALPHA_BLEND",INV_CONST_ALPHA_BLEND, "SRC_ALPHA_SAT_BLEND",SRC_ALPHA_SAT_BLEND,
"SRC1_COLOR_BLEND",SRC1_COLOR_BLEND, "INV_SRC1_COLOR_BLEND",INV_SRC1_COLOR_BLEND,
"SRC1_ALPHA_BLEND",SRC1_ALPHA_BLEND, "INV_SRC1_ALPHA_BLEND",INV_SRC1_ALPHA_BLEND,
"ADD_BLEND_OP",ADD_BLEND_OP, "SUBTRACT_BLEND_OP",SUBTRACT_BLEND_OP,
"REV_SUBTRACT_BLEND_OP",REV_SUBTRACT_BLEND_OP, "MIN_BLEND_OP",MIN_BLEND_OP,
"MAX_BLEND_OP",MAX_BLEND_OP
};
// map string into corresponding render-state
#define STR_TO_STATE(str, stateType, state) \
for(unsigned int i=0; i<NUM_RENDER_STATES; i++) \
if(strcmp(renderStateList[i].name, str.c_str()) == 0) \
state = (stateType)renderStateList[i].mode;
bool Material::LoadTextures(std::ifstream &file)
{
std::string str, token;
file >> token;
while (true)
{
file >> str;
if ((str == "}") || (file.eof()))
break;
else if (str == "ColorTexture")
{
file >> str;
colorTexture = Demo::resourceManager->LoadTexture(str.c_str());
if (!colorTexture)
return false;
}
else if (str == "NormalTexture")
{
file >> str;
normalTexture = Demo::resourceManager->LoadTexture(str.c_str());
if (!normalTexture)
return false;
}
else if (str == "SpecularTexture")
{
file >> str;
specularTexture = Demo::resourceManager->LoadTexture(str.c_str());
if (!specularTexture)
return false;
}
}
return true;
}
void Material::LoadRenderStates(std::ifstream &file)
{
std::string str, token;
file >> token;
while (true)
{
file >> str;
if ((str == "}") || (file.eof()))
break;
else if (str == "cull")
{
file >> str;
STR_TO_STATE(str, cullModes, rasterDesc.cullMode);
}
else if (str == "noDepthTest")
depthStencilDesc.depthTest = false;
else if (str == "noDepthMask")
depthStencilDesc.depthMask = false;
else if (str == "colorBlend")
{
blendDesc.blend = true;
file >> str;
STR_TO_STATE(str, blendOptions, blendDesc.srcColorBlend);
file >> str;
STR_TO_STATE(str, blendOptions, blendDesc.dstColorBlend);
file >> str;
STR_TO_STATE(str, blendOps, blendDesc.blendColorOp);
}
else if (str == "alphaBlend")
{
blendDesc.blend = true;
file >> str;
STR_TO_STATE(str, blendOptions, blendDesc.srcAlphaBlend);
file >> str;
STR_TO_STATE(str, blendOptions, blendDesc.dstAlphaBlend);
file >> str;
STR_TO_STATE(str, blendOps, blendDesc.blendAlphaOp);
}
}
}
bool Material::LoadShader(std::ifstream &file)
{
std::string str, token;
unsigned int permutationMask = 0;
file >> token;
while (true)
{
file >> str;
if ((str == "}") || (file.eof()))
break;
else if (str == "permutation")
{
file >> permutationMask;
}
else if (str == "file")
{
file >> str;
shader = Demo::resourceManager->LoadShader(str.c_str(), permutationMask);
if (!shader)
return false;
}
}
return true;
}
bool Material::Load(const char *fileName)
{
strcpy(name, fileName);
char filePath[DEMO_MAX_FILEPATH];
if (!Demo::fileManager->GetFilePath(fileName, filePath))
return false;
std::ifstream file(filePath, std::ios::in);
if (!file.is_open())
return false;
std::string str, token;
file >> str;
while (!file.eof())
{
if (str == "Textures")
{
if (!LoadTextures(file))
{
file.close();
return false;
}
}
else if (str == "RenderStates")
{
LoadRenderStates(file);
}
else if (str == "Shader")
{
if (!LoadShader(file))
{
file.close();
return false;
}
}
file >> str;
}
file.close();
rasterizerState = Demo::renderer->CreateRasterizerState(rasterDesc);
if (!rasterizerState)
return false;
// Increment for all opaque geometry the stencil buffer. In this way direct as well
// as indirect illumination can be restricted to the area, where actually the scene
// geometry is located. On the other hand the sky can be easily rendered to the area,
// where the stencil buffer is still left to 0.
if (!blendDesc.blend)
depthStencilDesc.stencilTest = true;
depthStencilState = Demo::renderer->CreateDepthStencilState(depthStencilDesc);
if (!depthStencilState)
return false;
blendState = Demo::renderer->CreateBlendState(blendDesc);
if (!blendState)
return false;
return true;
}
| 26.045918 | 94 | 0.697747 | raptoravis |
f61998985015980fbba5f72e69a6f51ebff9ea8e | 13,031 | cpp | C++ | QP/v5.4.2/qpcpp/examples/lwip/arm-cm/lwip_ek-lm3s6965/lwipmgr.cpp | hyller/GladiatorCots | 36a69df68675bb40b562081c531e6674037192a8 | [
"Unlicense"
] | null | null | null | QP/v5.4.2/qpcpp/examples/lwip/arm-cm/lwip_ek-lm3s6965/lwipmgr.cpp | hyller/GladiatorCots | 36a69df68675bb40b562081c531e6674037192a8 | [
"Unlicense"
] | null | null | null | QP/v5.4.2/qpcpp/examples/lwip/arm-cm/lwip_ek-lm3s6965/lwipmgr.cpp | hyller/GladiatorCots | 36a69df68675bb40b562081c531e6674037192a8 | [
"Unlicense"
] | null | null | null | //****************************************************************************
// Product: lwIP-Manager Active Object
// Last Updated for Version: 5.4.0
// Date of the Last Update: 2015-05-12
//
// Q u a n t u m L e a P s
// ---------------------------
// innovating embedded systems
//
// Copyright (C) Quantum Leaps, LLC. All rights reserved.
//
// This program is open source software: you can redistribute it and/or
// modify it under the terms of the GNU General Public License as published
// by the Free Software Foundation, either version 3 of the License, or
// (at your option) any later version.
//
// Alternatively, this program may be distributed and modified under the
// terms of Quantum Leaps commercial licenses, which expressly supersede
// the GNU General Public License and are specifically designed for
// licensees interested in retaining the proprietary status of their code.
//
// This program is distributed in the hope that it will be useful,
// but WITHOUT ANY WARRANTY; without even the implied warranty of
// MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
// GNU General Public License for more details.
//
// You should have received a copy of the GNU General Public License
// along with this program. If not, see <http://www.gnu.org/licenses/>.
//
// Contact information:
// Web : http://www.state-machine.com
// Email: info@state-machine.com
//****************************************************************************
#define LWIP_ALLOWED
#include "qpcpp.h" // QP/C++ API
#include "dpp.h" // application events and active objects
#include "bsp.h" // Board Support Package
#include "lwip.h" // lwIP stack
#include "httpd.h" // lwIP application
#include <string.h>
#include <stdio.h>
Q_DEFINE_THIS_FILE
// application signals cannot overlap the device-driver signals
Q_ASSERT_COMPILE((LWIP_DRIVER_END - LWIP_DRIVER_GROUP) >= LWIP_MAX_OFFSET);
#define FLASH_USERREG0 (*(uint32_t const *)0x400FE1E0)
#define FLASH_USERREG1 (*(uint32_t const *)0x400FE1E4)
#define LWIP_SLOW_TICK_MS TCP_TMR_INTERVAL
// Active object class -------------------------------------------------------
class LwIPMgr : public QActive {
QTimeEvt m_te_LWIP_SLOW_TICK;
struct netif *m_netif;
struct udp_pcb *m_upcb;
uint32_t m_ip_addr; // IP address in the native host byte order
#if LWIP_TCP
uint32_t m_tcp_tmr;
#endif
#if LWIP_ARP
uint32_t m_arp_tmr;
#endif
#if LWIP_DHCP
uint32_t m_dhcp_fine_tmr;
uint32_t m_dhcp_coarse_tmr;
#endif
#if LWIP_AUTOIP
uint32_t m_auto_ip_tmr;
#endif
public:
LwIPMgr(); // ctor
private:
static QState initial(LwIPMgr *me, QEvt const *e);
static QState running(LwIPMgr *me, QEvt const *e);
};
// Local objects -------------------------------------------------------------
static LwIPMgr l_lwIPMgr; // the single instance of LwIPMgr AO
// Global-scope objects ------------------------------------------------------
QActive * const AO_LwIPMgr = (QActive *)&l_lwIPMgr; // "opaque" pointer
// Server-Side Include (SSI) demo ............................................
static char const * const ssi_tags[] = {
"s_xmit",
"s_recv",
"s_fw",
"s_drop",
"s_chkerr",
"s_lenerr",
"s_memerr",
"s_rterr",
"s_proerr",
"s_opterr",
"s_err",
};
static int ssi_handler(int iIndex, char *pcInsert, int iInsertLen);
// Common Gateway Iinterface (CG) demo .......................................
static char const *cgi_display(int index, int numParams,
char const *param[],
char const *value[]);
static tCGI const cgi_handlers[] = {
{ "/display.cgi", &cgi_display },
};
// UDP handler ...............................................................
static void udp_rx_handler(void *arg, struct udp_pcb *upcb,
struct pbuf *p, struct ip_addr *addr, u16_t port);
//............................................................................
LwIPMgr::LwIPMgr()
: QActive((QStateHandler)&LwIPMgr::initial),
m_te_LWIP_SLOW_TICK(LWIP_SLOW_TICK_SIG)
{}
//............................................................................
QState LwIPMgr::initial(LwIPMgr *me, QEvt const *e) {
unsigned long user0, user1;
uint8_t macaddr[NETIF_MAX_HWADDR_LEN];
(void)e; // suppress the compiler warning about unused parameter
// Configure the hardware MAC address for the Ethernet Controller
//
// For the Stellaris Eval Kits, the MAC address will be stored in the
// non-volatile USER0 and USER1 registers. These registers can be read
// using the FlashUserGet function, as illustrated below.
//
user0 = FLASH_USERREG0;
user1 = FLASH_USERREG1;
// the MAC address must have been programmed!
Q_ASSERT((user0 != 0xFFFFFFFF) && (user1 != 0xFFFFFFFF));
//
// Convert the 24/24 split MAC address from NV ram into a 32/16 split MAC
// address needed to program the hardware registers, then program the MAC
// address into the Ethernet Controller registers.
//
macaddr[0] = (uint8_t)user0; user0 >>= 8;
macaddr[1] = (uint8_t)user0; user0 >>= 8;
macaddr[2] = (uint8_t)user0; user0 >>= 8;
macaddr[3] = (uint8_t)user1; user1 >>= 8;
macaddr[4] = (uint8_t)user1; user1 >>= 8;
macaddr[5] = (uint8_t)user1;
// initialize the Ethernet Driver
me->m_netif = eth_driver_init((QActive *)me, LWIP_DRIVER_GROUP, macaddr);
me->m_ip_addr = 0xFFFFFFFF; // initialize to impossible value
// initialize the lwIP applications...
httpd_init(); // initialize the simple HTTP-Deamon (web server)
http_set_ssi_handler(&ssi_handler, ssi_tags, Q_DIM(ssi_tags));
http_set_cgi_handlers(cgi_handlers, Q_DIM(cgi_handlers));
me->m_upcb = udp_new();
udp_bind(me->m_upcb, IP_ADDR_ANY, 777); // use port 777 for UDP
udp_recv(me->m_upcb, &udp_rx_handler, me);
QS_OBJ_DICTIONARY(&l_lwIPMgr);
QS_OBJ_DICTIONARY(&l_lwIPMgr.m_te_LWIP_SLOW_TICK);
QS_FUN_DICTIONARY(&QHsm::top);
QS_FUN_DICTIONARY(&LwIPMgr::initial);
QS_FUN_DICTIONARY(&LwIPMgr::running);
QS_SIG_DICTIONARY(SEND_UDP_SIG, me);
QS_SIG_DICTIONARY(LWIP_SLOW_TICK_SIG, me);
QS_SIG_DICTIONARY(LWIP_DRIVER_GROUP + LWIP_RX_READY_OFFSET, me);
QS_SIG_DICTIONARY(LWIP_DRIVER_GROUP + LWIP_TX_READY_OFFSET, me);
QS_SIG_DICTIONARY(LWIP_DRIVER_GROUP + LWIP_RX_OVERRUN_OFFSET, me);
return Q_TRAN(&LwIPMgr::running);
}
//............................................................................
QState LwIPMgr::running(LwIPMgr *me, QEvt const *e) {
switch (e->sig) {
case Q_ENTRY_SIG: {
me->m_te_LWIP_SLOW_TICK.postEvery((QActive *)me,
(LWIP_SLOW_TICK_MS * BSP_TICKS_PER_SEC) / 1000);
return Q_HANDLED();
}
case Q_EXIT_SIG: {
me->m_te_LWIP_SLOW_TICK.disarm();
return Q_HANDLED();
}
case SEND_UDP_SIG: {
if (me->m_upcb->remote_port != (uint16_t)0) {
struct pbuf *p = pbuf_new((u8_t *)((TextEvt const *)e)->text,
strlen(((TextEvt const *)e)->text) + 1);
if (p != (struct pbuf *)0) {
udp_send(me->m_upcb, p);
pbuf_free(p); // don't leak the pbuf!
}
}
return Q_HANDLED();
}
case LWIP_DRIVER_GROUP + LWIP_RX_READY_OFFSET: {
eth_driver_read();
return Q_HANDLED();
}
case LWIP_DRIVER_GROUP + LWIP_TX_READY_OFFSET: {
eth_driver_write();
return Q_HANDLED();
}
case LWIP_SLOW_TICK_SIG: {
if (me->m_ip_addr != me->m_netif->ip_addr.addr) {
me->m_ip_addr = me->m_netif->ip_addr.addr; // save the IP addr
uint32_t ip_net = ntohl(me->m_ip_addr);// IP in network order
// publish the text event to display the new IP address
TextEvt *te = Q_NEW(TextEvt, DISPLAY_IPADDR_SIG);
snprintf(te->text, Q_DIM(te->text), "%d.%d.%d.%d",
((ip_net) >> 24) & 0xFF,
((ip_net) >> 16) & 0xFF,
((ip_net) >> 8) & 0xFF,
ip_net & 0xFF);
QF::PUBLISH(te, me);
}
#if LWIP_TCP
me->m_tcp_tmr += LWIP_SLOW_TICK_MS;
if (me->m_tcp_tmr >= TCP_TMR_INTERVAL) {
me->m_tcp_tmr = 0;
tcp_tmr();
}
#endif
#if LWIP_ARP
me->m_arp_tmr += LWIP_SLOW_TICK_MS;
if (me->m_arp_tmr >= ARP_TMR_INTERVAL) {
me->m_arp_tmr = 0;
etharp_tmr();
}
#endif
#if LWIP_DHCP
me->m_dhcp_fine_tmr += LWIP_SLOW_TICK_MS;
if (me->m_dhcp_fine_tmr >= DHCP_FINE_TIMER_MSECS) {
me->m_dhcp_fine_tmr = 0;
dhcp_fine_tmr();
}
me->m_dhcp_coarse_tmr += LWIP_SLOW_TICK_MS;
if (me->m_dhcp_coarse_tmr >= DHCP_COARSE_TIMER_MSECS) {
me->m_dhcp_coarse_tmr = 0;
dhcp_coarse_tmr();
}
#endif
#if LWIP_AUTOIP
me->auto_ip_tmr += LWIP_SLOW_TICK_MS;
if (me->auto_ip_tmr >= AUTOIP_TMR_INTERVAL) {
me->auto_ip_tmr = 0;
autoip_tmr();
}
#endif
return Q_HANDLED();
}
case LWIP_DRIVER_GROUP + LWIP_RX_OVERRUN_OFFSET: {
LINK_STATS_INC(link.err);
return Q_HANDLED();
}
}
return Q_SUPER(&QHsm::top);
}
// HTTPD customizations ------------------------------------------------------
// Server-Side Include (SSI) handler .........................................
static int ssi_handler(int iIndex, char *pcInsert, int iInsertLen) {
struct stats_proto *stats = &lwip_stats.link;
STAT_COUNTER value;
switch (iIndex) {
case 0: // s_xmit
value = stats->xmit;
break;
case 1: // s_recv
value = stats->recv;
break;
case 2: // s_fw
value = stats->fw;
break;
case 3: // s_drop
value = stats->drop;
break;
case 4: // s_chkerr
value = stats->chkerr;
break;
case 5: // s_lenerr
value = stats->lenerr;
break;
case 6: // s_memerr
value = stats->memerr;
break;
case 7: // s_rterr
value = stats->rterr;
break;
case 8: // s_proerr
value = stats->proterr;
break;
case 9: // s_opterr
value = stats->opterr;
break;
case 10: // s_err
value = stats->err;
break;
}
return snprintf(pcInsert, MAX_TAG_INSERT_LEN, "%d", value);
}
// Common Gateway Iinterface (CG) handler ....................................
static char const *cgi_display(int index, int numParams,
char const *param[],
char const *value[])
{
for (int i = 0; i < numParams; ++i) {
if (strstr(param[i], "text") != (char *)0) { // param text found?
TextEvt *te = Q_NEW(TextEvt, DISPLAY_CGI_SIG);
strncpy(te->text, value[i], Q_DIM(te->text));
QF::PUBLISH((QEvt *)te, AO_LwIPMgr);
return "/thank_you.htm";
}
}
return (char *)0; // no URI, HTTPD will send 404 error page to the browser
}
// UDP receive handler -------------------------------------------------------
static void udp_rx_handler(void *arg, struct udp_pcb *upcb,
struct pbuf *p, struct ip_addr *addr, u16_t port)
{
TextEvt *te = Q_NEW(TextEvt, DISPLAY_UDP_SIG);
strncpy(te->text, (char *)p->payload, Q_DIM(te->text));
QF::PUBLISH(te, AO_LwIPMgr);
udp_connect(upcb, addr, port); // connect to the remote host
pbuf_free(p); // don't leak the pbuf!
}
| 37.771014 | 78 | 0.514159 | hyller |
f619fc1aac3f323fb765aa700b3ab4e0cfd251b2 | 2,027 | hpp | C++ | src/configure/Platform.hpp | hotgloupi/configure | 888cf725c93df5a1cf01794cc0a581586a82855c | [
"BSD-3-Clause"
] | 1 | 2015-11-13T10:37:35.000Z | 2015-11-13T10:37:35.000Z | src/configure/Platform.hpp | hotgloupi/configure | 888cf725c93df5a1cf01794cc0a581586a82855c | [
"BSD-3-Clause"
] | 19 | 2015-02-10T17:18:58.000Z | 2015-07-11T11:31:08.000Z | src/configure/Platform.hpp | hotgloupi/configure | 888cf725c93df5a1cf01794cc0a581586a82855c | [
"BSD-3-Clause"
] | null | null | null | #pragma once
#include <iosfwd>
#include <string>
namespace configure {
class Platform
{
public:
enum class Vendor {
unknown,
pc,
apple,
};
enum class Arch {
unknown,
x86,
x86_64,
};
enum class SubArch {
unknown,
};
enum class OS {
unknown,
windows,
linux,
osx,
ios,
dragonfly,
freebsd,
netbsd,
openbsd,
aix,
hpux,
solaris,
};
private:
Vendor _vendor;
Arch _arch;
SubArch _sub_arch;
OS _os;
std::string _os_version;
public:
Platform();
public:
#define CONFIGURE_PLATFORM_PROPERTY(EnumType, name) \
EnumType name() const \
{ return _ ## name; } \
std::string name ## _string() const \
{ return to_string<EnumType>(_ ## name); } \
Platform& name(EnumType value) \
{ _ ## name = value; return *this; } \
Platform& name(std::string const& value) \
{ _ ## name = from_string<EnumType>(value); return *this; } \
/**/
CONFIGURE_PLATFORM_PROPERTY(Vendor, vendor);
CONFIGURE_PLATFORM_PROPERTY(Arch, arch);
CONFIGURE_PLATFORM_PROPERTY(SubArch, sub_arch);
CONFIGURE_PLATFORM_PROPERTY(OS, os);
#undef CONFIGURE_PLATFORM_PROPERTY
std::string os_version() const
{ return _os_version; }
Platform& os_version(std::string const& version)
{ _os_version = version; return *this; }
public:
bool is_osx() const { return _os == OS::osx; }
bool is_windows() const { return _os == OS::windows; }
bool is_linux() const { return _os == OS::linux; }
// Returns the number of bits necessary to address memory or 0 if the
// architecture is unknown.
unsigned address_model() const;
bool is_32bit() const { return address_model() == 32; }
bool is_64bit() const { return address_model() == 64; }
public:
static Platform current();
template<typename EnumType>
static std::string const& to_string(EnumType value);
template<typename EnumType>
static EnumType from_string(std::string const& value);
};
std::ostream& operator <<(std::ostream& out, Platform const& p);
}
| 20.896907 | 71 | 0.660582 | hotgloupi |
f61eada41d605c8284e0bbb196d25322ae8faab8 | 2,103 | cc | C++ | common/config.cc | yonsei-icsl/nebula | 12bc2440978018d27996df6b97180056dddefa6c | [
"BSD-3-Clause"
] | 5 | 2020-02-13T04:12:41.000Z | 2021-02-08T04:53:55.000Z | common/config.cc | yonsei-icsl/Nebula | 12bc2440978018d27996df6b97180056dddefa6c | [
"BSD-3-Clause"
] | 1 | 2020-10-29T10:59:08.000Z | 2020-12-31T04:04:58.000Z | common/config.cc | yonsei-icsl/Nebula | 12bc2440978018d27996df6b97180056dddefa6c | [
"BSD-3-Clause"
] | 2 | 2021-03-21T02:45:40.000Z | 2022-03-10T12:31:06.000Z | #include <algorithm>
#include <assert.h>
#include <cstdlib>
#include <fstream>
#include <iostream>
#include <locale>
#include "config.h"
#include "utils.h"
namespace nebula {
// Configuration section
section_config_t::section_config_t(std::string m_name) :
name(m_name) {
}
section_config_t::~section_config_t() {
settings.clear();
}
// Add (key, value) pair to the section settings
void section_config_t::add_setting(std::string m_key, std::string m_value) {
settings.insert(std::pair<std::string,std::string>(lowercase(m_key), lowercase(m_value)));
}
// Check if a setting exists.
bool section_config_t::exists(std::string m_key) {
return settings.find(lowercase(m_key)) != settings.end();
}
// Configuration
config_t::config_t() {
}
config_t::~config_t() {
sections.clear();
}
// Parse configuration file
void config_t::parse(std::string m_config_name) {
std::fstream file_stream;
file_stream.open(m_config_name.c_str(), std::fstream::in);
if(!file_stream.is_open()) {
std::cerr << "Error: failed to open " << m_config_name << std::endl;
exit(1);
}
std::string line;
while(getline(file_stream, line)) {
// Erase all spaces
line.erase(remove(line.begin(),line.end(),' '),line.end());
// Skip blank lines or comments
if(!line.size() || (line[0] == '#')) continue;
// Beginning of [section]
if(line[0] == '[') {
std::string section_name = line.substr(1, line.size()-2);
sections.push_back(section_config_t(section_name));
}
else {
size_t eq = line.find('=');
if(eq == std::string::npos) {
std::cerr << "Error: invalid config" << std::endl << line << std::endl;
exit(1);
}
// Save (key, value) pair in the latest section setting.
std::string key = line.substr(0, eq);
std::string value = line.substr(eq+1, line.size()-1);
sections[sections.size()-1].add_setting(key, value);
}
}
}
}
// End of namespace nebula
| 26.620253 | 94 | 0.603899 | yonsei-icsl |
f6228685796ff7236425071c249c5df5c898b8a9 | 9,517 | cpp | C++ | src/devices/bus/nes/tengen.cpp | Robbbert/messui | 49b756e2140d8831bc81335298ee8c5471045e79 | [
"BSD-3-Clause"
] | 26 | 2015-03-31T06:25:51.000Z | 2021-12-14T09:29:04.000Z | src/devices/bus/nes/tengen.cpp | Robbbert/messui | 49b756e2140d8831bc81335298ee8c5471045e79 | [
"BSD-3-Clause"
] | null | null | null | src/devices/bus/nes/tengen.cpp | Robbbert/messui | 49b756e2140d8831bc81335298ee8c5471045e79 | [
"BSD-3-Clause"
] | 10 | 2015-03-27T05:45:51.000Z | 2022-02-04T06:57:36.000Z | // license:BSD-3-Clause
// copyright-holders:Fabio Priuli
/***********************************************************************************************************
NES/Famicom cartridge emulation for Tengen PCBs
Here we emulate the following PCBs
* Tengen 800008
* Tengen 800032 [mapper 64]
* Tengen 800037 [mapper 158]
TODO:
- emulated the IRQ delay in 800032 (possibly reason of Skull & Crossbones not working?)
***********************************************************************************************************/
#include "emu.h"
#include "tengen.h"
#include "video/ppu2c0x.h" // this has to be included so that IRQ functions can access ppu2c0x_device::BOTTOM_VISIBLE_SCANLINE
#ifdef NES_PCB_DEBUG
#define VERBOSE 1
#else
#define VERBOSE 0
#endif
#define LOG_MMC(x) do { if (VERBOSE) logerror x; } while (0)
//-------------------------------------------------
// constructor
//-------------------------------------------------
DEFINE_DEVICE_TYPE(NES_TENGEN_800008, nes_tengen008_device, "nes_tengen008", "NES Cart Tengen 800008 PCB")
DEFINE_DEVICE_TYPE(NES_TENGEN_800032, nes_tengen032_device, "nes_tengen032", "NES Cart Tengen 800032 PCB")
DEFINE_DEVICE_TYPE(NES_TENGEN_800037, nes_tengen037_device, "nes_tengen037", "NES Cart Tengen 800037 PCB")
nes_tengen008_device::nes_tengen008_device(const machine_config &mconfig, const char *tag, device_t *owner, uint32_t clock)
: nes_nrom_device(mconfig, NES_TENGEN_800008, tag, owner, clock)
{
}
nes_tengen032_device::nes_tengen032_device(const machine_config &mconfig, device_type type, const char *tag, device_t *owner, uint32_t clock)
: nes_nrom_device(mconfig, type, tag, owner, clock), m_irq_count(0), m_irq_count_latch(0), m_irq_mode(0), m_irq_reset(0), m_irq_enable(0), m_latch(0), irq_timer(nullptr)
{
}
nes_tengen032_device::nes_tengen032_device(const machine_config &mconfig, const char *tag, device_t *owner, uint32_t clock)
: nes_tengen032_device(mconfig, NES_TENGEN_800032, tag, owner, clock)
{
}
nes_tengen037_device::nes_tengen037_device(const machine_config &mconfig, const char *tag, device_t *owner, uint32_t clock)
: nes_tengen032_device(mconfig, NES_TENGEN_800037, tag, owner, clock)
{
}
void nes_tengen008_device::device_start()
{
common_start();
}
void nes_tengen008_device::pcb_reset()
{
m_chr_source = m_vrom_chunks ? CHRROM : CHRRAM;
prg32(0);
chr8(0, m_chr_source);
}
void nes_tengen032_device::device_start()
{
common_start();
irq_timer = timer_alloc(TIMER_IRQ);
irq_timer->reset();
timer_freq = clocks_to_attotime(4);
save_item(NAME(m_mmc_prg_bank));
save_item(NAME(m_mmc_vrom_bank));
save_item(NAME(m_latch));
save_item(NAME(m_irq_mode));
save_item(NAME(m_irq_reset));
save_item(NAME(m_irq_enable));
save_item(NAME(m_irq_count));
save_item(NAME(m_irq_count_latch));
}
void nes_tengen032_device::pcb_reset()
{
m_chr_source = m_vrom_chunks ? CHRROM : CHRRAM;
prg16_89ab(m_prg_chunks - 1);
prg16_cdef(m_prg_chunks - 1);
chr8(0, m_chr_source);
memset(m_mmc_prg_bank, 0, sizeof(m_mmc_prg_bank));
memset(m_mmc_vrom_bank, 0, sizeof(m_mmc_vrom_bank));
m_latch = 0;
m_irq_mode = 0;
m_irq_reset = 0;
m_irq_enable = 0;
m_irq_count = m_irq_count_latch = 0;
}
/*-------------------------------------------------
mapper specific handlers
-------------------------------------------------*/
/*-------------------------------------------------
Tengen 800008 Board
iNES: mapper 3?
In MESS: Supported.
-------------------------------------------------*/
void nes_tengen008_device::write_h(offs_t offset, uint8_t data)
{
LOG_MMC(("tengen008 write_h, offset: %04x, data: %02x\n", offset, data));
// this pcb is subject to bus conflict
data = account_bus_conflict(offset, data);
prg32(data >> 3);
chr8(data, CHRROM);
}
/*-------------------------------------------------
Tengen 800032 Board
Games: Klax, Road Runner, Rolling Thunder, Shinobi, Skulls
& Crossbones, Xybots
This is very similar to MMC-3 (or more probably to the
Namcot predecessor of MMC-3), but with more registers
and with an alternative IRQ mode
iNES: mapper 64
In MESS: Partially Supported (there should be a small
delay between the IRQ and its execution, but that is not
emulated yet: this is possibly the problem with Skulls
& Crossbones)
-------------------------------------------------*/
inline void nes_tengen032_device::irq_clock(int blanked)
{
// From NESdev wiki: Regardless of the mode used to clock the counter, every time the counter is clocked,
// the following actions occur:
// - If Reset reg ($C001) was written to after previous clock, reload IRQ counter with IRQ Reload + 1
// - Otherwise, if IRQ Counter is 0, reload IRQ counter with IRQ Reload value
// - Otherwise, first decrement IRQ counter by 1, then if IRQ counter is now 0 and IRQs are enabled,
// trigger IRQ
if (m_irq_reset)
{
m_irq_reset = 0;
m_irq_count = m_irq_count_latch + 1;
}
else if (!m_irq_count)
m_irq_count = m_irq_count_latch;
m_irq_count--;
if (m_irq_enable && !blanked && !m_irq_count)
set_irq_line(ASSERT_LINE);
}
// we use the HBLANK IRQ latch from PPU for the scanline based IRQ mode
// and a timer for the cycle based IRQ mode, which both call irq_clock
void nes_tengen032_device::device_timer(emu_timer &timer, device_timer_id id, int param, void *ptr)
{
if (id == TIMER_IRQ)
{
irq_clock(0);
}
}
void nes_tengen032_device::hblank_irq(int scanline, int vblank, int blanked)
{
if (!m_irq_mode) // we are in scanline mode!
{
if (scanline < ppu2c0x_device::BOTTOM_VISIBLE_SCANLINE)
{
irq_clock(blanked);
}
}
}
void nes_tengen032_device::set_prg()
{
uint8_t prg_mode = m_latch & 0x40;
prg8_89(m_mmc_prg_bank[prg_mode ? 2: 0]);
prg8_ab(m_mmc_prg_bank[prg_mode ? 0: 1]);
prg8_cd(m_mmc_prg_bank[prg_mode ? 1: 2]);
}
void nes_tengen032_device::chr_cb(int start, int bank, int source)
{
chr1_x(start, bank, source);
}
void nes_tengen032_device::set_chr()
{
uint8_t chr_page = (m_latch & 0x80) >> 5;
if (m_latch & 0x20)
{
chr_cb(0 ^ chr_page, m_mmc_vrom_bank[0], CHRROM);
chr_cb(1 ^ chr_page, m_mmc_vrom_bank[6], CHRROM);
chr_cb(2 ^ chr_page, m_mmc_vrom_bank[1], CHRROM);
chr_cb(3 ^ chr_page, m_mmc_vrom_bank[7], CHRROM);
}
else
{
chr_cb(0 ^ chr_page, m_mmc_vrom_bank[0] & ~0x01, CHRROM);
chr_cb(1 ^ chr_page, m_mmc_vrom_bank[0] | 0x01, CHRROM);
chr_cb(2 ^ chr_page, m_mmc_vrom_bank[1] & ~0x01, CHRROM);
chr_cb(3 ^ chr_page, m_mmc_vrom_bank[1] | 0x01, CHRROM);
}
chr_cb(4 ^ chr_page, m_mmc_vrom_bank[2], CHRROM);
chr_cb(5 ^ chr_page, m_mmc_vrom_bank[3], CHRROM);
chr_cb(6 ^ chr_page, m_mmc_vrom_bank[4], CHRROM);
chr_cb(7 ^ chr_page, m_mmc_vrom_bank[5], CHRROM);
}
void nes_tengen032_device::tengen032_write(offs_t offset, uint8_t data)
{
uint8_t helper, cmd;
LOG_MMC(("tengen032_write, offset: %04x, data: %02x\n", offset, data));
switch (offset & 0x6001)
{
case 0x0000:
helper = m_latch ^ data;
m_latch = data;
// Has PRG Mode changed?
if (helper & 0x40)
set_prg();
// Has CHR Mode changed?
if (helper & 0xa0)
set_chr();
break;
case 0x0001:
cmd = m_latch & 0x0f;
switch (cmd)
{
case 0: case 1:
case 2: case 3:
case 4: case 5:
m_mmc_vrom_bank[cmd] = data;
set_chr();
break;
case 6: case 7:
m_mmc_prg_bank[cmd - 6] = data;
set_prg();
break;
case 8: case 9:
m_mmc_vrom_bank[cmd - 2] = data;
set_chr();
break;
case 0x0f:
m_mmc_prg_bank[2] = data;
set_prg();
break;
}
break;
case 0x2000:
set_nt_mirroring(BIT(data, 0) ? PPU_MIRROR_HORZ : PPU_MIRROR_VERT);
break;
case 0x4000:
m_irq_count_latch = data;
break;
case 0x4001: /* $c001 - IRQ scanline latch */
m_irq_mode = data & 0x01;
if (m_irq_mode)
irq_timer->adjust(attotime::zero, 0, timer_freq);
else
irq_timer->adjust(attotime::never);
m_irq_reset = 1;
break;
case 0x6000:
m_irq_enable = 0;
set_irq_line(CLEAR_LINE);
break;
case 0x6001:
m_irq_enable = 1;
break;
default:
LOG_MMC(("Tengen 800032 write. addr: %04x value: %02x\n", offset + 0x8000, data));
break;
}
}
/*-------------------------------------------------
Tengen 800037 Board
Games: Alien Syndrome
Same as above (mapper chip RAMBO-1) but CHR A17 output
is connected to CIRAM A10, so this differs from 800032
exactly in the same way as TLSROM differs from plain
MMC-3
iNES: mapper 158
In MESS: Supported.
-------------------------------------------------*/
void nes_tengen037_device::set_mirror()
{
if (m_latch & 0x80)
{
set_nt_page(0, CIRAM, BIT(m_mmc_vrom_bank[2],7), 1);
set_nt_page(1, CIRAM, BIT(m_mmc_vrom_bank[3],7), 1);
set_nt_page(2, CIRAM, BIT(m_mmc_vrom_bank[4],7), 1);
set_nt_page(3, CIRAM, BIT(m_mmc_vrom_bank[5],7), 1);
}
else
{
set_nt_page(0, CIRAM, BIT(m_mmc_vrom_bank[0],7), 1);
set_nt_page(1, CIRAM, BIT(m_mmc_vrom_bank[0],7), 1);
set_nt_page(2, CIRAM, BIT(m_mmc_vrom_bank[1],7), 1);
set_nt_page(3, CIRAM, BIT(m_mmc_vrom_bank[1],7), 1);
}
}
void nes_tengen037_device::chr_cb( int start, int bank, int source )
{
set_mirror(); // we could probably update only for one (e.g. the first) call, to slightly optimize the code
chr1_x(start, bank, source);
}
void nes_tengen037_device::write_h(offs_t offset, uint8_t data)
{
LOG_MMC(("tengen037 write_h, offset: %04x, data: %02x\n", offset, data));
switch (offset & 0x6001)
{
case 0x2000:
break;
default:
tengen032_write(offset, data);
break;
}
}
| 25.31117 | 170 | 0.65777 | Robbbert |
f622a2d64454d726a5561d310bfe9e66cbfc56c8 | 289 | hpp | C++ | engine/src/Resources/ImageData.hpp | aleksigron/graphics-toolkit | f8e60c57316a72dff9de07512e9771deb3799208 | [
"MIT"
] | 14 | 2017-10-17T16:20:20.000Z | 2021-12-21T14:49:00.000Z | engine/src/Resources/ImageData.hpp | aleksigron/graphics-toolkit | f8e60c57316a72dff9de07512e9771deb3799208 | [
"MIT"
] | null | null | null | engine/src/Resources/ImageData.hpp | aleksigron/graphics-toolkit | f8e60c57316a72dff9de07512e9771deb3799208 | [
"MIT"
] | 1 | 2019-05-12T13:50:23.000Z | 2019-05-12T13:50:23.000Z | #pragma once
#include <cstddef>
#include "Math/Vec2.hpp"
struct ImageData
{
unsigned char* imageData;
size_t imageDataSize;
Vec2i imageSize;
unsigned int pixelFormat;
unsigned int componentDataType;
size_t compressedSize;
bool compressed;
ImageData();
};
| 13.761905 | 33 | 0.705882 | aleksigron |
f624d363ac3f6f847615772a93146521aeef640b | 804 | cpp | C++ | bls_sig.cpp | ANSIIRU/BLS12_381-small_memory_c- | 6109d56c38a4c9243dcbcd0464b50feaa2f70a89 | [
"Unlicense"
] | null | null | null | bls_sig.cpp | ANSIIRU/BLS12_381-small_memory_c- | 6109d56c38a4c9243dcbcd0464b50feaa2f70a89 | [
"Unlicense"
] | null | null | null | bls_sig.cpp | ANSIIRU/BLS12_381-small_memory_c- | 6109d56c38a4c9243dcbcd0464b50feaa2f70a89 | [
"Unlicense"
] | null | null | null | #include "my_pairing.h"
#include <stdio.h>
void KeyGen(const char* s, EC_Fp2* pub, EC_Fp2* Q)
{
G2_SCM(pub, s, Q); // pub = sQ
// printf("pub=\n");
// EC_Fp2_print(pub);
}
void SignGen(EC_Fp *sign, const char* s, const char *m)
{
EC_Fp Hm;
hash_to_curve(&Hm,m);
// EC_Fp_from_Mont(&Hm);
// EC_Fp_print(&Hm);
//EC_Fp_to_Mont(&Hm.&Hm);
G1_SCM(sign,s,&Hm); // sign = s H(m)
}
int Verify(EC_Fp *sign,EC_Fp2 *Q,EC_Fp2 *pub,const char *m){
Fp12 e1,e2;
EC_Fp Hm;
hash_to_curve(&Hm,m);
// EC_Fp_print(sign);
// EC_Fp_print(&Hm);
// EC_Fp2_print(Q);
// EC_Fp2_print(pub);
my_pairing_proj(&e1,Q,sign);
my_pairing_proj(&e2,pub,&Hm);
printf("e1 = \n");
Fp12_print(&e1);
printf("e2 = \n");
Fp12_print(&e2);
return Fp12_cmp(&e1, &e2);
}
| 21.72973 | 61 | 0.588308 | ANSIIRU |
f6252d2cb128d926a9df58446183d716865a9409 | 961 | cc | C++ | aoj/2/2300.cc | eagletmt/procon | adbe503eb3c1bbcc1538b2ee8988aa353937e8d4 | [
"MIT"
] | 1 | 2015-04-17T09:54:23.000Z | 2015-04-17T09:54:23.000Z | aoj/2/2300.cc | eagletmt/procon | adbe503eb3c1bbcc1538b2ee8988aa353937e8d4 | [
"MIT"
] | null | null | null | aoj/2/2300.cc | eagletmt/procon | adbe503eb3c1bbcc1538b2ee8988aa353937e8d4 | [
"MIT"
] | null | null | null | #include <iostream>
#include <cstdio>
#include <vector>
using namespace std;
struct color
{
double L, a, b;
};
inline double sqr(double x) { return x*x; }
inline double operator-(const color& lhs, const color& rhs)
{
return sqr(lhs.L - rhs.L) + sqr(lhs.a - rhs.a) + sqr(lhs.b - rhs.b);
}
int main()
{
int N, M;
cin >> N >> M;
vector<color> cs;
for (int i = 0; i < N; i++) {
color c;
cin >> c.L >> c.a >> c.b;
cs.push_back(c);
}
double ans = 0.0;
for (int s = 0; s < (1<<N); s++) {
vector<color> v;
for (int i = 0; i < N; i++) {
if (s & (1<<i)) {
v.push_back(cs[i]);
}
}
if (v.size() != M) {
continue;
}
double x = 0.0;
for (vector<color>::const_iterator it = v.begin(); it != v.end(); ++it) {
for (vector<color>::const_iterator jt = it+1; jt != v.end(); ++jt) {
x += *it - *jt;
}
}
ans = max(ans, x);
}
printf("%.6f\n", ans);
return 0;
}
| 18.843137 | 77 | 0.488033 | eagletmt |
f6261d1897d3c4e2b3553ed526b581d863dec20b | 1,628 | cpp | C++ | Algorithms/0040.Combination_Sum_II.cpp | metehkaya/LeetCode | 52f4a1497758c6f996d515ced151e8783ae4d4d2 | [
"MIT"
] | 2 | 2020-07-20T06:40:22.000Z | 2021-11-20T01:23:26.000Z | Problems/LeetCode/Problems/0040.Combination_Sum_II.cpp | metehkaya/Algo-Archive | 03b5fdcf06f84a03125c57762c36a4e03ca6e756 | [
"MIT"
] | null | null | null | Problems/LeetCode/Problems/0040.Combination_Sum_II.cpp | metehkaya/Algo-Archive | 03b5fdcf06f84a03125c57762c36a4e03ca6e756 | [
"MIT"
] | null | null | null | #define fi first
#define se second
#define pb push_back
typedef pair<int,int> pi;
class Solution {
public:
int n,t;
vector<pi> ar;
bool dp[101][31];
vector<int> v[101][31];
vector<vector<int>> ans;
void f(int id , int k , vector<int>& curr) {
if(id == 0) {
vector<int> add;
for( int i = n-1 ; i >= 0 ; i-- )
for( int j = 0 ; j < curr[i] ; j++ )
add.pb(ar[n-1-i].fi);
ans.pb(add);
return;
}
int sz = v[id][k].size();
for( int i = 0 ; i < sz ; i++ ) {
int cnt = v[id][k][i];
int j = k - cnt*ar[id-1].fi;
curr.pb(cnt);
f(id-1,j,curr);
curr.pop_back();
}
}
vector<vector<int>> combinationSum2(vector<int>& arr, int t) {
this->t = t;
n = arr.size();
sort(arr.begin(),arr.end());
for( int i = 0 , j = 0 ; i < n ; i = j ) {
while(j < n && arr[i] == arr[j])
j++;
ar.pb(pi(arr[i],j-i));
}
n = ar.size();
dp[0][0] = true;
for( int i = 0 ; i < n ; i++ )
for( int j = 0 ; j <= t ; j++ )
if(dp[i][j]) {
int mx = min(ar[i].se,(t-j)/ar[i].fi);
for( int k = 0 ; k <= mx ; k++ ) {
int j2 = j + k*ar[i].fi;
v[i+1][j2].pb(k);
dp[i+1][j2] = true;
}
}
vector<int> curr;
if(dp[n][t])
f(n,t,curr);
return ans;
}
}; | 28.561404 | 66 | 0.355651 | metehkaya |
f626ac1cd81142105101fcf956b89ac1d4f0ee5f | 13,181 | cpp | C++ | test/unit/CopyPropagationTest.cpp | alanyee/redex | 35d261274571b1515e0eaec278cb8ecd79006559 | [
"BSD-3-Clause"
] | null | null | null | test/unit/CopyPropagationTest.cpp | alanyee/redex | 35d261274571b1515e0eaec278cb8ecd79006559 | [
"BSD-3-Clause"
] | null | null | null | test/unit/CopyPropagationTest.cpp | alanyee/redex | 35d261274571b1515e0eaec278cb8ecd79006559 | [
"BSD-3-Clause"
] | null | null | null | /**
* Copyright (c) 2016-present, Facebook, Inc.
* All rights reserved.
*
* This source code is licensed under the BSD-style license found in the
* LICENSE file in the root directory of this source tree. An additional grant
* of patent rights can be found in the PATENTS file in the same directory.
*/
#include <gtest/gtest.h>
#include "CopyPropagationPass.h"
#include "IRAssembler.h"
using namespace copy_propagation_impl;
TEST(CopyPropagationTest, simple) {
auto code = assembler::ircode_from_string(R"(
(
(const v0 0)
(move v1 v0)
(move v2 v1)
(return v2)
)
)");
code->set_registers_size(3);
CopyPropagationPass::Config config;
CopyPropagation(config).run(code.get());
auto expected_code = assembler::ircode_from_string(R"(
(
(const v0 0)
; these moves don't get deleted, but running DCE after will clean them up
(move v1 v0) ; this makes v0 the representative for v1
; this source register is remapped by replace_with_representative
(move v2 v0)
(return v0)
)
)");
EXPECT_EQ(assembler::to_s_expr(code.get()),
assembler::to_s_expr(expected_code.get()));
}
TEST(CopyPropagationTest, deleteRepeatedMove) {
auto code = assembler::ircode_from_string(R"(
(
(const v0 0)
(move-object v1 v0) ; this load doesn't get deleted, so that any reg
; operands that cannot get remapped (like the
; monitor-* instructions below) still remain valid
(move-object v1 v0) ; this move can be deleted
(monitor-enter v1) ; these won't be remapped to avoid breaking
; ART verification
(monitor-exit v1)
(return v1)
)
)");
code->set_registers_size(2);
CopyPropagationPass::Config config;
CopyPropagation(config).run(code.get());
auto expected_code = assembler::ircode_from_string(R"(
(
(const v0 0)
(move-object v1 v0)
(monitor-enter v1)
(monitor-exit v1)
(return v0)
)
)");
EXPECT_EQ(assembler::to_s_expr(code.get()),
assembler::to_s_expr(expected_code.get()));
}
TEST(CopyPropagationTest, noRemapRange) {
g_redex = new RedexContext();
auto code = assembler::ircode_from_string(R"(
(
(const v0 0)
(move-object v1 v0)
; v1 won't get remapped here because it's part of an instruction that
; will be converted to /range form during the lowering step
(invoke-static (v1 v2 v3 v4 v5 v6) "LFoo;.bar:(IIIIII)V")
(return v1)
)
)");
code->set_registers_size(7);
CopyPropagationPass::Config config;
CopyPropagation(config).run(code.get());
auto expected_code = assembler::ircode_from_string(R"(
(
(const v0 0)
(move-object v1 v0)
(invoke-static (v1 v2 v3 v4 v5 v6) "LFoo;.bar:(IIIIII)V")
(return v0)
)
)");
EXPECT_EQ(assembler::to_s_expr(code.get()),
assembler::to_s_expr(expected_code.get()));
delete g_redex;
}
TEST(CopyPropagationTest, deleteSelfMove) {
auto code = assembler::ircode_from_string(R"(
(
(const v1 0)
(move v0 v0)
)
)");
code->set_registers_size(2);
CopyPropagationPass::Config config;
CopyPropagation(config).run(code.get());
auto expected_code = assembler::ircode_from_string(R"(
(
(const v1 0)
)
)");
EXPECT_EQ(assembler::to_s_expr(code.get()),
assembler::to_s_expr(expected_code.get()));
}
TEST(CopyPropagationTest, representative) {
g_redex = new RedexContext();
auto code = assembler::ircode_from_string(R"(
(
(const v0 0)
(move v1 v0)
(invoke-static (v0) "Lcls;.foo:(I)V")
(invoke-static (v1) "Lcls;.bar:(I)V")
)
)");
code->set_registers_size(2);
CopyPropagationPass::Config config;
CopyPropagation(config).run(code.get());
auto expected_code = assembler::ircode_from_string(R"(
(
(const v0 0)
(move v1 v0)
(invoke-static (v0) "Lcls;.foo:(I)V")
(invoke-static (v0) "Lcls;.bar:(I)V")
)
)");
EXPECT_EQ(assembler::to_s_expr(code.get()),
assembler::to_s_expr(expected_code.get()));
delete g_redex;
}
TEST(CopyPropagationTest, verifyEnabled) {
// assuming verify-none is disabled for this test
auto code = assembler::ircode_from_string(R"(
(
(const v0 0)
(int-to-float v1 v0) ; use v0 as float
(const v0 0)
(float-to-int v1 v0) ; use v0 as int
)
)");
code->set_registers_size(2);
CopyPropagationPass::Config config;
CopyPropagation(config).run(code.get());
auto expected_code = assembler::ircode_from_string(R"(
(
(const v0 0)
(int-to-float v1 v0) ; use v0 as float
(const v0 0) ; DON'T delete this. Verifier needs it
(float-to-int v1 v0) ; use v0 as int
)
)");
EXPECT_EQ(assembler::to_s_expr(code.get()),
assembler::to_s_expr(expected_code.get()));
}
TEST(CopyPropagationTest, cliqueAliasing) {
auto code = assembler::ircode_from_string(R"(
(
(move v1 v2)
(move v0 v1)
(move v1 v3)
(move v0 v2)
)
)");
code->set_registers_size(4);
CopyPropagationPass::Config config;
config.replace_with_representative = false;
CopyPropagation(config).run(code.get());
auto expected_code = assembler::ircode_from_string(R"(
(
(move v1 v2)
(move v0 v1)
(move v1 v3)
)
)");
EXPECT_EQ(assembler::to_s_expr(code.get()),
assembler::to_s_expr(expected_code.get()));
}
TEST(CopyPropagationTest, loopNoChange) {
auto code = assembler::ircode_from_string(R"(
(
(const v0 0)
(const v1 10)
:loop
(if-eq v0 v1 :end)
(add-int/lit8 v0 v0 1)
(goto :loop)
:end
(return-void)
)
)");
code->set_registers_size(2);
CopyPropagationPass::Config config;
CopyPropagation(config).run(code.get());
auto expected_code = assembler::ircode_from_string(R"(
(
(const v0 0)
(const v1 10)
:loop
(if-eq v0 v1 :end)
(add-int/lit8 v0 v0 1)
(goto :loop)
:end
(return-void)
)
)");
EXPECT_EQ(assembler::to_s_expr(code.get()),
assembler::to_s_expr(expected_code.get()));
}
TEST(CopyPropagationTest, branchNoChange) {
auto code = assembler::ircode_from_string(R"(
(
(if-eqz v0 :true)
(move v1 v2)
(goto :end)
:true
(move v3 v2)
:end
(move v1 v3)
(return-void)
)
)");
code->set_registers_size(4);
CopyPropagationPass::Config config;
CopyPropagation(config).run(code.get());
auto expected_code = assembler::ircode_from_string(R"(
(
(if-eqz v0 :true)
(move v1 v2)
(goto :end)
:true
(move v3 v2)
:end
(move v1 v3)
(return-void)
)
)");
EXPECT_EQ(assembler::to_s_expr(code.get()),
assembler::to_s_expr(expected_code.get()));
}
TEST(CopyPropagationTest, intersect1) {
auto code = assembler::ircode_from_string(R"(
(
(if-eqz v0 :true)
(move v1 v2)
(goto :end)
:true
(move v1 v2)
:end
(move v1 v2)
(return-void)
)
)");
code->set_registers_size(4);
CopyPropagationPass::Config config;
CopyPropagation(config).run(code.get());
auto expected_code = assembler::ircode_from_string(R"(
(
(if-eqz v0 :true)
(move v1 v2)
(goto :end)
:true
(move v1 v2)
:end
(return-void)
)
)");
EXPECT_EQ(assembler::to_s_expr(code.get()),
assembler::to_s_expr(expected_code.get()));
}
TEST(CopyPropagationTest, intersect2) {
auto no_change = R"(
(
(move v0 v1)
(if-eqz v0 :true)
(move v3 v1)
(goto :end)
:true
(move v4 v1)
:end
(move v3 v4)
(return-void)
)
)";
auto code = assembler::ircode_from_string(no_change);
code->set_registers_size(5);
CopyPropagationPass::Config config;
config.replace_with_representative = false;
CopyPropagation(config).run(code.get());
auto expected_code = assembler::ircode_from_string(no_change);
EXPECT_EQ(assembler::to_s_expr(code.get()),
assembler::to_s_expr(expected_code.get()));
}
TEST(CopyPropagationTest, wide) {
auto code = assembler::ircode_from_string(R"(
(
(move-wide v0 v2)
(move-wide v0 v2)
)
)");
code->set_registers_size(4);
CopyPropagationPass::Config config;
config.wide_registers = true;
CopyPropagation(config).run(code.get());
auto expected_code = assembler::ircode_from_string(R"(
(
(move-wide v0 v2)
)
)");
EXPECT_EQ(assembler::to_s_expr(code.get()),
assembler::to_s_expr(expected_code.get()));
}
TEST(CopyPropagationTest, wideClobber) {
auto code = assembler::ircode_from_string(R"(
(
(move v1 v4)
(move-wide v0 v2)
(move v1 v4)
)
)");
code->set_registers_size(5);
CopyPropagationPass::Config config;
config.wide_registers = false;
CopyPropagation(config).run(code.get());
auto expected_code = assembler::ircode_from_string(R"(
(
(move v1 v4)
(move-wide v0 v2)
(move v1 v4)
)
)");
EXPECT_EQ(assembler::to_s_expr(code.get()),
assembler::to_s_expr(expected_code.get()));
}
TEST(CopyPropagationTest, wideClobberWideTrue) {
auto code = assembler::ircode_from_string(R"(
(
(move v1 v4)
(move-wide v0 v2)
(move v1 v4)
)
)");
code->set_registers_size(5);
CopyPropagationPass::Config config;
config.wide_registers = true;
CopyPropagation(config).run(code.get());
auto expected_code = assembler::ircode_from_string(R"(
(
(move v1 v4)
(move-wide v0 v2)
(move v1 v4)
)
)");
EXPECT_EQ(assembler::to_s_expr(code.get()),
assembler::to_s_expr(expected_code.get()));
}
TEST(CopyPropagationTest, repWide) {
auto code = assembler::ircode_from_string(R"(
(
(const-wide v0 0)
(move-wide v2 v0)
(const v1 0)
(move-wide v4 v2)
)
)");
code->set_registers_size(5);
CopyPropagationPass::Config config;
config.wide_registers = true;
config.replace_with_representative = true;
CopyPropagation(config).run(code.get());
auto expected_code = assembler::ircode_from_string(R"(
(
(const-wide v0 0)
(move-wide v2 v0)
(const v1 0)
(move-wide v4 v2) ; don't switch v2 to v0
; because `const v1` invalidated v0
)
)");
EXPECT_EQ(assembler::to_s_expr(code.get()),
assembler::to_s_expr(expected_code.get()));
}
// whichRep and whichRep2 make sure that we deterministically choose the
// representative after a merge point.
TEST(CopyPropagationTest, whichRep) {
auto no_change = R"(
(
(if-eqz v0 :true)
(move v1 v2)
(goto :end)
:true
(move v2 v1)
:end
(move v3 v1)
)
)";
auto code = assembler::ircode_from_string(no_change);
code->set_registers_size(4);
CopyPropagationPass::Config config;
config.replace_with_representative = true;
CopyPropagation(config).run(code.get());
auto expected_code = assembler::ircode_from_string(no_change);
EXPECT_EQ(assembler::to_s_expr(code.get()),
assembler::to_s_expr(expected_code.get()));
}
TEST(CopyPropagationTest, whichRep2) {
auto no_change = R"(
(
(if-eqz v0 :true)
(move v2 v1)
(goto :end)
:true
(move v1 v2)
:end
(move v3 v1)
)
)";
auto code = assembler::ircode_from_string(no_change);
code->set_registers_size(4);
CopyPropagationPass::Config config;
config.replace_with_representative = true;
CopyPropagation(config).run(code.get());
auto expected_code = assembler::ircode_from_string(no_change);
}
// make sure we keep using the oldest representative even after a merge
TEST(CopyPropagationTest, whichRepPreserve) {
auto code = assembler::ircode_from_string(R"(
(
(if-eqz v0 :true)
(move v1 v2)
(goto :end)
:true
(move v1 v2)
:end
(move v3 v1)
)
)");
code->set_registers_size(4);
CopyPropagationPass::Config config;
config.replace_with_representative = true;
CopyPropagation(config).run(code.get());
auto expected_code = assembler::ircode_from_string(R"(
(
(if-eqz v0 :true)
(move v1 v2)
(goto :end)
:true
(move v1 v2)
:end
(move v3 v2)
)
)");
EXPECT_EQ(assembler::to_s_expr(code.get()),
assembler::to_s_expr(expected_code.get()));
}
TEST(CopyPropagationTest, wideInvokeSources) {
g_redex = new RedexContext();
auto no_change = R"(
(
(move-wide v0 v15)
(invoke-static (v0) "Lcom;.foo:(J)V")
)
)";
auto code = assembler::ircode_from_string(no_change);
code->set_registers_size(16);
CopyPropagationPass::Config config;
config.replace_with_representative = true;
config.wide_registers = true;
config.regalloc_has_run = true;
CopyPropagation(config).run(code.get());
auto expected_code = assembler::ircode_from_string(no_change);
EXPECT_EQ(assembler::to_s_expr(code.get()),
assembler::to_s_expr(expected_code.get()));
delete g_redex;
}
| 22.041806 | 78 | 0.626053 | alanyee |
f628a6f16a9f1056b1989dcb8ae8e675ae08e8a5 | 541 | hpp | C++ | lib/AnimationStation/src/Effects/StaticColor.hpp | ez2torta/GP2040 | 50d2aaec40e02abeb6ef6d27f58de77009b19874 | [
"MIT"
] | 2 | 2021-08-30T23:05:29.000Z | 2021-09-03T04:28:25.000Z | lib/AnimationStation/src/Effects/StaticColor.hpp | ez2torta/GP2040 | 50d2aaec40e02abeb6ef6d27f58de77009b19874 | [
"MIT"
] | null | null | null | lib/AnimationStation/src/Effects/StaticColor.hpp | ez2torta/GP2040 | 50d2aaec40e02abeb6ef6d27f58de77009b19874 | [
"MIT"
] | null | null | null | #ifndef _STATIC_COLOR_H_
#define _STATIC_COLOR_H_
#include <vector>
#include <stdio.h>
#include <stdlib.h>
#include "../Animation.hpp"
#include "../AnimationStation.hpp"
class StaticColor : public Animation {
public:
StaticColor(PixelMatrix &matrix);
StaticColor(PixelMatrix &matrix, std::vector<Pixel> &pixels);
~StaticColor() {};
void Animate(RGB (&frame)[100]);
void SaveIndexOptions(uint8_t colorIndex);
uint8_t GetColor();
void ParameterUp();
void ParameterDown();
protected:
std::vector<Pixel> *pixels;
};
#endif
| 20.807692 | 63 | 0.726433 | ez2torta |
f629287e0571ed47dd294ebfb0d6cda890b59810 | 2,283 | cpp | C++ | codeforces/N - Wires/Wrong answer on test 1.cpp | kzvd4729/Problem-Solving | 13b105e725a4c2f8db7fecc5d7a8f932b9fef4ab | [
"MIT"
] | 1 | 2022-02-11T16:55:36.000Z | 2022-02-11T16:55:36.000Z | codeforces/N - Wires/Wrong answer on test 1.cpp | kzvd4729/Problem-Solving | 13b105e725a4c2f8db7fecc5d7a8f932b9fef4ab | [
"MIT"
] | null | null | null | codeforces/N - Wires/Wrong answer on test 1.cpp | kzvd4729/Problem-Solving | 13b105e725a4c2f8db7fecc5d7a8f932b9fef4ab | [
"MIT"
] | null | null | null | /****************************************************************************************
* @author: kzvd4729 created: Oct/27/2019 19:37
* solution_verdict: Wrong answer on test 1 language: GNU C++14
* run_time: 0 ms memory_used: 19700 KB
* problem: https://codeforces.com/contest/1250/problem/N
****************************************************************************************/
#include<bits/stdc++.h>
#define long long long
using namespace std;
const int N=1e6;
int par[N+2],uu[N+2],vv[N+2],ed[N+2],deg[N+2];
int get(int x)
{
if(x==par[x])return x;
return par[x]=get(par[x]);
}
int main()
{
ios_base::sync_with_stdio(0);cin.tie(0);
int t;cin>>t;
while(t--)
{
int n;cin>>n;vector<int>vc;
for(int i=1;i<=n;i++)
{
cin>>uu[i]>>vv[i];
vc.push_back(uu[i]);vc.push_back(vv[i]);
}
sort(vc.begin(),vc.end());
vc.erase(unique(vc.begin(),vc.end()),vc.end());
map<int,int>cn,rv;int sz=0;
for(auto x:vc)
{
cn[x]=++sz;rv[sz]=x;
}
for(int i=1;i<=n;i++)uu[i]=cn[uu[i]],vv[i]=cn[vv[i]];
for(int i=1;i<=sz;i++)par[i]=i,ed[i]=0,deg[i]=0;
// cout<<endl;
// for(int i=1;i<=n;i++)
// cout<<uu[i]<<"-->"<<vv[i]<<endl;
vector<int>ex;
for(int i=1;i<=n;i++)
{
int r1=get(uu[i]),r2=get(vv[i]);
if(r1==r2)ex.push_back(i);
else par[r1]=r2;
deg[uu[i]]++,deg[vv[i]]++;
}
// for(int i=1;i<=sz;i++)
// cout<<deg[i]<<" ";
// cout<<endl;
vector<int>rt;
for(int i=1;i<=sz;i++)
rt.push_back(get(i));
sort(rt.begin(),rt.end());
rt.erase(unique(rt.begin(),rt.end()),rt.end());
for(auto x:ex)
{
int r=get(uu[x]);
if(!ed[r])ed[r]=x;
}
for(int i=1;i<=n;i++)
{
if(deg[uu[i]]==1||deg[vv[i]]==1)
{
int r=get(uu[i]);
if(!ed[r])ed[r]=i;
}
}
cout<<rt.size()-1<<"\n";
for(int i=1;i<rt.size();i++)
{
int nm=ed[rt[i]];
cout<<nm<<" ";
if(deg[uu[nm]]==0)cout<<rv[uu[nm]]<<" "<<rv[rt[i-1]]<<"\n";
else cout<<rv[vv[nm]]<<" "<<rv[rt[i-1]]<<"\n";
}
}
return 0;
} | 28.5375 | 111 | 0.412615 | kzvd4729 |
f62931072abe30397a2b46e3eac694ac8d57fd71 | 48,597 | cc | C++ | components/payments/core/journey_logger_unittest.cc | metux/chromium-deb | 3c08e9b89a1b6f95f103a61ff4f528dbcd57fc42 | [
"BSD-3-Clause-No-Nuclear-License-2014",
"BSD-3-Clause"
] | null | null | null | components/payments/core/journey_logger_unittest.cc | metux/chromium-deb | 3c08e9b89a1b6f95f103a61ff4f528dbcd57fc42 | [
"BSD-3-Clause-No-Nuclear-License-2014",
"BSD-3-Clause"
] | null | null | null | components/payments/core/journey_logger_unittest.cc | metux/chromium-deb | 3c08e9b89a1b6f95f103a61ff4f528dbcd57fc42 | [
"BSD-3-Clause-No-Nuclear-License-2014",
"BSD-3-Clause"
] | null | null | null | // Copyright 2017 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 "components/payments/core/journey_logger.h"
#include "base/metrics/metrics_hashes.h"
#include "base/test/histogram_tester.h"
#include "base/test/scoped_feature_list.h"
#include "components/metrics/proto/ukm/entry.pb.h"
#include "components/ukm/test_ukm_recorder.h"
#include "components/ukm/ukm_source.h"
#include "testing/gmock/include/gmock/gmock.h"
#include "testing/gtest/include/gtest/gtest.h"
using testing::ContainerEq;
namespace payments {
// Tests the canMakePayment stats for the case where the merchant does not use
// it and does not show the PaymentRequest to the user.
TEST(JourneyLoggerTest,
RecordJourneyStatsHistograms_CanMakePaymentNotCalled_NoShow) {
base::HistogramTester histogram_tester;
JourneyLogger logger(/*is_incognito=*/false, /*url=*/GURL(""),
/*ukm_recorder=*/nullptr);
logger.SetCompleted();
histogram_tester.ExpectBucketCount("PaymentRequest.CanMakePayment.Usage",
JourneyLogger::CAN_MAKE_PAYMENT_NOT_USED,
1);
// There should be no completion stats since PR was not shown to the user
EXPECT_THAT(
histogram_tester.GetTotalCountsForPrefix(
"PaymentRequest.CanMakePayment.NotUsed.WithShowEffectOnCompletion"),
testing::ContainerEq(base::HistogramTester::CountsMap()));
}
// Tests the canMakePayment stats for the case where the merchant does not use
// it and the transaction is aborted.
TEST(JourneyLoggerTest,
RecordJourneyStatsHistograms_CanMakePaymentNotCalled_ShowAndUserAbort) {
base::HistogramTester histogram_tester;
JourneyLogger logger(/*is_incognito=*/false, /*url=*/GURL(""),
/*ukm_recorder=*/nullptr);
// Expect no log for CanMakePayment.
EXPECT_THAT(
histogram_tester.GetTotalCountsForPrefix("PaymentRequest.CanMakePayment"),
testing::ContainerEq(base::HistogramTester::CountsMap()));
// The merchant does not query CanMakePayment, show the PaymentRequest and the
// user aborts it.
logger.SetShowCalled();
logger.SetRequestedInformation(true, false, false, false);
logger.SetAborted(JourneyLogger::ABORT_REASON_ABORTED_BY_USER);
histogram_tester.ExpectBucketCount("PaymentRequest.CanMakePayment.Usage",
JourneyLogger::CAN_MAKE_PAYMENT_NOT_USED,
1);
// There should be a record for an abort when CanMakePayment is not used but
// the PR is shown to the user.
histogram_tester.ExpectBucketCount(
"PaymentRequest.CanMakePayment.NotUsed.WithShowEffectOnCompletion",
JourneyLogger::COMPLETION_STATUS_USER_ABORTED, 1);
}
// Tests the canMakePayment stats for the case where the merchant does not use
// it and the transaction is aborted.
TEST(JourneyLoggerTest,
RecordJourneyStatsHistograms_CanMakePaymentNotCalled_ShowAndOtherAbort) {
base::HistogramTester histogram_tester;
JourneyLogger logger(/*is_incognito=*/false, /*url=*/GURL(""),
/*ukm_recorder=*/nullptr);
// Expect no log for CanMakePayment.
EXPECT_THAT(
histogram_tester.GetTotalCountsForPrefix("PaymentRequest.CanMakePayment"),
testing::ContainerEq(base::HistogramTester::CountsMap()));
// The merchant does not query CanMakePayment, show the PaymentRequest and
// there is an abort not initiated by the user.
logger.SetShowCalled();
logger.SetRequestedInformation(true, false, false, false);
logger.SetAborted(JourneyLogger::ABORT_REASON_OTHER);
histogram_tester.ExpectBucketCount("PaymentRequest.CanMakePayment.Usage",
JourneyLogger::CAN_MAKE_PAYMENT_NOT_USED,
1);
// There should be a record for an abort when CanMakePayment is not used but
// the PR is shown to the user.
histogram_tester.ExpectBucketCount(
"PaymentRequest.CanMakePayment.NotUsed.WithShowEffectOnCompletion",
JourneyLogger::COMPLETION_STATUS_OTHER_ABORTED, 1);
}
// Tests the canMakePayment stats for the case where the merchant does not use
// it and the transaction is completed.
TEST(JourneyLoggerTest,
RecordJourneyStatsHistograms_CanMakePaymentNotCalled_ShowAndComplete) {
base::HistogramTester histogram_tester;
JourneyLogger logger(/*is_incognito=*/false, /*url=*/GURL(""),
/*ukm_recorder=*/nullptr);
// Expect no log for CanMakePayment.
EXPECT_THAT(
histogram_tester.GetTotalCountsForPrefix("PaymentRequest.CanMakePayment"),
testing::ContainerEq(base::HistogramTester::CountsMap()));
// The merchant does not query CanMakePayment, show the PaymentRequest and the
// user completes it.
logger.SetShowCalled();
logger.SetRequestedInformation(true, false, false, false);
logger.SetCompleted();
histogram_tester.ExpectBucketCount("PaymentRequest.CanMakePayment.Usage",
JourneyLogger::CAN_MAKE_PAYMENT_NOT_USED,
1);
// There should be a record for an abort when CanMakePayment is not used but
// the PR is shown to the user.
histogram_tester.ExpectBucketCount(
"PaymentRequest.CanMakePayment.NotUsed.WithShowEffectOnCompletion",
JourneyLogger::COMPLETION_STATUS_COMPLETED, 1);
}
// Tests the canMakePayment stats for the case where the merchant uses it,
// returns false and show is not called.
TEST(JourneyLoggerTest,
RecordJourneyStatsHistograms_CanMakePaymentCalled_FalseAndNoShow) {
base::HistogramTester histogram_tester;
JourneyLogger logger(/*is_incognito=*/false, /*url=*/GURL(""),
/*ukm_recorder=*/nullptr);
// Expect no log for CanMakePayment.
EXPECT_THAT(
histogram_tester.GetTotalCountsForPrefix("PaymentRequest.CanMakePayment"),
testing::ContainerEq(base::HistogramTester::CountsMap()));
// The user cannot make payment and the PaymentRequest is not shown.
logger.SetCanMakePaymentValue(false);
logger.SetAborted(JourneyLogger::ABORT_REASON_OTHER);
histogram_tester.ExpectBucketCount("PaymentRequest.CanMakePayment.Usage",
JourneyLogger::CAN_MAKE_PAYMENT_USED, 1);
// The CanMakePayment effect on show should be recorded as being false and not
// shown.
histogram_tester.ExpectBucketCount(
"PaymentRequest.CanMakePayment.Used.EffectOnShow",
JourneyLogger::CMP_EFFECT_ON_SHOW_COULD_NOT_MAKE_PAYMENT_AND_DID_NOT_SHOW,
1);
// There should be no completion stats since PR was not shown to the user.
EXPECT_THAT(
histogram_tester.GetTotalCountsForPrefix(
"PaymentRequest.CanMakePayment.NotUsed.WithShowEffectOnCompletion"),
testing::ContainerEq(base::HistogramTester::CountsMap()));
}
// Tests the canMakePayment stats for the case where the merchant uses it,
// returns true and show is not called.
TEST(JourneyLoggerTest,
RecordJourneyStatsHistograms_CanMakePaymentCalled_TrueAndNoShow) {
base::HistogramTester histogram_tester;
JourneyLogger logger(/*is_incognito=*/false, /*url=*/GURL(""),
/*ukm_recorder=*/nullptr);
// Expect no log for CanMakePayment.
EXPECT_THAT(
histogram_tester.GetTotalCountsForPrefix("PaymentRequest.CanMakePayment"),
testing::ContainerEq(base::HistogramTester::CountsMap()));
// The user cannot make payment and the PaymentRequest is not shown.
logger.SetCanMakePaymentValue(true);
logger.SetAborted(JourneyLogger::ABORT_REASON_OTHER);
histogram_tester.ExpectBucketCount("PaymentRequest.CanMakePayment.Usage",
JourneyLogger::CAN_MAKE_PAYMENT_USED, 1);
// The CanMakePayment effect on show should be recorded as being true and not
// shown.
histogram_tester.ExpectBucketCount(
"PaymentRequest.CanMakePayment.Used.EffectOnShow",
JourneyLogger::CMP_EFFECT_ON_SHOW_COULD_MAKE_PAYMENT, 1);
// There should be no completion stats since PR was not shown to the user.
EXPECT_THAT(
histogram_tester.GetTotalCountsForPrefix(
"PaymentRequest.CanMakePayment.NotUsed.WithShowEffectOnCompletion"),
testing::ContainerEq(base::HistogramTester::CountsMap()));
}
// Tests the canMakePayment stats for the case where the merchant uses it,
// returns false, show is called but the transaction is aborted by the user.
TEST(JourneyLoggerTest,
RecordJourneyStatsHistograms_CanMakePaymentCalled_FalseShowAndUserAbort) {
base::HistogramTester histogram_tester;
JourneyLogger logger(/*is_incognito=*/false, /*url=*/GURL(""),
/*ukm_recorder=*/nullptr);
// Expect no log for CanMakePayment.
EXPECT_THAT(
histogram_tester.GetTotalCountsForPrefix("PaymentRequest.CanMakePayment"),
testing::ContainerEq(base::HistogramTester::CountsMap()));
// The user cannot make payment and the PaymentRequest is not shown.
logger.SetShowCalled();
logger.SetRequestedInformation(true, false, false, false);
logger.SetCanMakePaymentValue(false);
logger.SetAborted(JourneyLogger::ABORT_REASON_ABORTED_BY_USER);
histogram_tester.ExpectBucketCount("PaymentRequest.CanMakePayment.Usage",
JourneyLogger::CAN_MAKE_PAYMENT_USED, 1);
// The CanMakePayment effect on show should be recorded as being false and
// shown.
histogram_tester.ExpectBucketCount(
"PaymentRequest.CanMakePayment.Used.EffectOnShow",
JourneyLogger::CMP_EFFECT_ON_SHOW_DID_SHOW, 1);
// There should be a record for an abort when CanMakePayment is false but the
// PR is shown to the user.
histogram_tester.ExpectBucketCount(
"PaymentRequest.CanMakePayment.Used.FalseWithShowEffectOnCompletion",
JourneyLogger::COMPLETION_STATUS_USER_ABORTED, 1);
}
// Tests the canMakePayment stats for the case where the merchant uses it,
// returns false, show is called but the transaction is aborted.
TEST(JourneyLoggerTest,
RecordJourneyStatsHistograms_CanMakePaymentCalled_FalseShowAndOtherAbort) {
base::HistogramTester histogram_tester;
JourneyLogger logger(/*is_incognito=*/false, /*url=*/GURL(""),
/*ukm_recorder=*/nullptr);
// Expect no log for CanMakePayment.
EXPECT_THAT(
histogram_tester.GetTotalCountsForPrefix("PaymentRequest.CanMakePayment"),
testing::ContainerEq(base::HistogramTester::CountsMap()));
// The user cannot make payment and the PaymentRequest is not shown.
logger.SetShowCalled();
logger.SetRequestedInformation(true, false, false, false);
logger.SetCanMakePaymentValue(false);
logger.SetAborted(JourneyLogger::ABORT_REASON_OTHER);
histogram_tester.ExpectBucketCount("PaymentRequest.CanMakePayment.Usage",
JourneyLogger::CAN_MAKE_PAYMENT_USED, 1);
// The CanMakePayment effect on show should be recorded as being false and
// shown.
histogram_tester.ExpectBucketCount(
"PaymentRequest.CanMakePayment.Used.EffectOnShow",
JourneyLogger::CMP_EFFECT_ON_SHOW_DID_SHOW, 1);
// There should be a record for an abort when CanMakePayment is false but the
// PR is shown to the user.
histogram_tester.ExpectBucketCount(
"PaymentRequest.CanMakePayment.Used.FalseWithShowEffectOnCompletion",
JourneyLogger::COMPLETION_STATUS_OTHER_ABORTED, 1);
}
// Tests the canMakePayment stats for the case where the merchant uses it,
// returns false, show is called and the transaction is completed.
TEST(JourneyLoggerTest,
RecordJourneyStatsHistograms_CanMakePaymentCalled_FalseShowAndComplete) {
base::HistogramTester histogram_tester;
JourneyLogger logger(/*is_incognito=*/false, /*url=*/GURL(""),
/*ukm_recorder=*/nullptr);
// Expect no log for CanMakePayment.
EXPECT_THAT(
histogram_tester.GetTotalCountsForPrefix("PaymentRequest.CanMakePayment"),
testing::ContainerEq(base::HistogramTester::CountsMap()));
// The user cannot make payment and the PaymentRequest is not shown.
logger.SetShowCalled();
logger.SetRequestedInformation(true, false, false, false);
logger.SetCanMakePaymentValue(false);
logger.SetCompleted();
histogram_tester.ExpectBucketCount("PaymentRequest.CanMakePayment.Usage",
JourneyLogger::CAN_MAKE_PAYMENT_USED, 1);
// The CanMakePayment effect on show should be recorded as being false and
// shown.
histogram_tester.ExpectBucketCount(
"PaymentRequest.CanMakePayment.Used.EffectOnShow",
JourneyLogger::CMP_EFFECT_ON_SHOW_DID_SHOW, 1);
// There should be a record for an completion when CanMakePayment is false but
// the PR is shown to the user.
histogram_tester.ExpectBucketCount(
"PaymentRequest.CanMakePayment.Used.FalseWithShowEffectOnCompletion",
JourneyLogger::COMPLETION_STATUS_COMPLETED, 1);
}
// Tests the canMakePayment stats for the case where the merchant uses it,
// returns true, show is called but the transaction is aborted by the user.
TEST(JourneyLoggerTest,
RecordJourneyStatsHistograms_CanMakePaymentCalled_TrueShowAndUserAbort) {
base::HistogramTester histogram_tester;
JourneyLogger logger(/*is_incognito=*/false, /*url=*/GURL(""),
/*ukm_recorder=*/nullptr);
// Expect no log for CanMakePayment.
EXPECT_THAT(
histogram_tester.GetTotalCountsForPrefix("PaymentRequest.CanMakePayment"),
testing::ContainerEq(base::HistogramTester::CountsMap()));
// The user cannot make payment and the PaymentRequest is not shown.
logger.SetShowCalled();
logger.SetRequestedInformation(true, false, false, false);
logger.SetCanMakePaymentValue(true);
logger.SetAborted(JourneyLogger::ABORT_REASON_ABORTED_BY_USER);
histogram_tester.ExpectBucketCount("PaymentRequest.CanMakePayment.Usage",
JourneyLogger::CAN_MAKE_PAYMENT_USED, 1);
// The CanMakePayment effect on show should be recorded as being true and not
// shown.
histogram_tester.ExpectBucketCount(
"PaymentRequest.CanMakePayment.Used.EffectOnShow",
JourneyLogger::CMP_EFFECT_ON_SHOW_DID_SHOW |
JourneyLogger::CMP_EFFECT_ON_SHOW_COULD_MAKE_PAYMENT,
1);
// There should be a record for an abort when CanMakePayment is true and the
// PR is shown to the user.
histogram_tester.ExpectBucketCount(
"PaymentRequest.CanMakePayment.Used.TrueWithShowEffectOnCompletion",
JourneyLogger::COMPLETION_STATUS_USER_ABORTED, 1);
}
// Tests the canMakePayment stats for the case where the merchant uses it,
// returns true, show is called but the transaction is aborted.
TEST(JourneyLoggerTest,
RecordJourneyStatsHistograms_CanMakePaymentCalled_TrueShowAndOtherAbort) {
base::HistogramTester histogram_tester;
JourneyLogger logger(/*is_incognito=*/false, /*url=*/GURL(""),
/*ukm_recorder=*/nullptr);
// Expect no log for CanMakePayment.
EXPECT_THAT(
histogram_tester.GetTotalCountsForPrefix("PaymentRequest.CanMakePayment"),
testing::ContainerEq(base::HistogramTester::CountsMap()));
// The user cannot make payment and the PaymentRequest is not shown.
logger.SetShowCalled();
logger.SetRequestedInformation(true, false, false, false);
logger.SetCanMakePaymentValue(true);
logger.SetAborted(JourneyLogger::ABORT_REASON_OTHER);
histogram_tester.ExpectBucketCount("PaymentRequest.CanMakePayment.Usage",
JourneyLogger::CAN_MAKE_PAYMENT_USED, 1);
// The CanMakePayment effect on show should be recorded as being true and not
// shown.
histogram_tester.ExpectBucketCount(
"PaymentRequest.CanMakePayment.Used.EffectOnShow",
JourneyLogger::CMP_EFFECT_ON_SHOW_DID_SHOW |
JourneyLogger::CMP_EFFECT_ON_SHOW_COULD_MAKE_PAYMENT,
1);
// There should be a record for an abort when CanMakePayment is true and the
// PR is shown to the user.
histogram_tester.ExpectBucketCount(
"PaymentRequest.CanMakePayment.Used.TrueWithShowEffectOnCompletion",
JourneyLogger::COMPLETION_STATUS_OTHER_ABORTED, 1);
}
// Tests the canMakePayment stats for the case where the merchant uses it,
// returns true, show is called and the transaction is completed.
TEST(JourneyLoggerTest,
RecordJourneyStatsHistograms_CanMakePaymentCalled_TrueShowAndComplete) {
base::HistogramTester histogram_tester;
JourneyLogger logger(/*is_incognito=*/false, /*url=*/GURL(""),
/*ukm_recorder=*/nullptr);
// Expect no log for CanMakePayment.
EXPECT_THAT(
histogram_tester.GetTotalCountsForPrefix("PaymentRequest.CanMakePayment"),
testing::ContainerEq(base::HistogramTester::CountsMap()));
// The user cannot make payment and the PaymentRequest is not shown.
logger.SetShowCalled();
logger.SetRequestedInformation(true, false, false, false);
logger.SetCanMakePaymentValue(true);
logger.SetCompleted();
histogram_tester.ExpectBucketCount("PaymentRequest.CanMakePayment.Usage",
JourneyLogger::CAN_MAKE_PAYMENT_USED, 1);
// The CanMakePayment effect on show should be recorded as being true and not
// shown.
histogram_tester.ExpectBucketCount(
"PaymentRequest.CanMakePayment.Used.EffectOnShow",
JourneyLogger::CMP_EFFECT_ON_SHOW_DID_SHOW |
JourneyLogger::CMP_EFFECT_ON_SHOW_COULD_MAKE_PAYMENT,
1);
// There should be a record for a completion when CanMakePayment is true and
// the PR is shown to the user.
histogram_tester.ExpectBucketCount(
"PaymentRequest.CanMakePayment.Used.TrueWithShowEffectOnCompletion",
JourneyLogger::COMPLETION_STATUS_COMPLETED, 1);
}
// Tests the canMakePayment metrics are not logged if the Payment Request was
// done in an incognito tab.
TEST(JourneyLoggerTest,
RecordJourneyStatsHistograms_CanMakePayment_IncognitoTab) {
base::HistogramTester histogram_tester;
JourneyLogger logger(/*is_incognito=*/true, /*url=*/GURL(""),
/*ukm_recorder=*/nullptr);
// Expect no log for CanMakePayment.
EXPECT_THAT(
histogram_tester.GetTotalCountsForPrefix("PaymentRequest.CanMakePayment"),
testing::ContainerEq(base::HistogramTester::CountsMap()));
// The user cannot make payment and the PaymentRequest is not shown.
logger.SetShowCalled();
logger.SetRequestedInformation(true, false, false, false);
logger.SetCanMakePaymentValue(true);
logger.SetCompleted();
// Expect no log for CanMakePayment.
EXPECT_THAT(
histogram_tester.GetTotalCountsForPrefix("PaymentRequest.CanMakePayment"),
testing::ContainerEq(base::HistogramTester::CountsMap()));
}
// Tests that the completion status metrics based on whether the user had
// suggestions for all the requested sections are logged as correctly.
TEST(JourneyLoggerTest,
RecordJourneyStatsHistograms_SuggestionsForEverything_Completed) {
base::HistogramTester histogram_tester;
JourneyLogger logger(/*is_incognito=*/false, /*url=*/GURL(""),
/*ukm_recorder=*/nullptr);
// The merchant only requests payment information.
logger.SetRequestedInformation(
/*requested_shipping=*/false, /*requested_email=*/false,
/*requested_phone=*/false, /*requested_name=*/false);
// Simulate that the user had suggestions for all the requested sections.
logger.SetNumberOfSuggestionsShown(JourneyLogger::SECTION_PAYMENT_METHOD, 1,
/*has_complete_suggestion=*/false);
// Simulate that the Payment Request was shown to the user.
logger.SetShowCalled();
// Simulate that the user completes the checkout.
logger.SetCompleted();
// Make sure that the expected metric was logged.
histogram_tester.ExpectBucketCount(
"PaymentRequest.UserHadSuggestionsForEverything.EffectOnCompletion",
JourneyLogger::COMPLETION_STATUS_COMPLETED, 1);
// Make sure the opposite metric was not logged.
EXPECT_THAT(histogram_tester.GetTotalCountsForPrefix(
"PaymentRequest.UserDidNotHaveSuggestionsForEverything."
"EffectOnCompletion"),
testing::ContainerEq(base::HistogramTester::CountsMap()));
// Make sure the correct events were logged.
std::vector<base::Bucket> buckets =
histogram_tester.GetAllSamples("PaymentRequest.Events");
ASSERT_EQ(1U, buckets.size());
EXPECT_FALSE(buckets[0].min &
JourneyLogger::EVENT_HAD_NECESSARY_COMPLETE_SUGGESTIONS);
EXPECT_TRUE(buckets[0].min &
JourneyLogger::EVENT_HAD_INITIAL_FORM_OF_PAYMENT);
EXPECT_TRUE(buckets[0].min & JourneyLogger::EVENT_COMPLETED);
EXPECT_FALSE(buckets[0].min & JourneyLogger::EVENT_USER_ABORTED);
EXPECT_FALSE(buckets[0].min & JourneyLogger::EVENT_OTHER_ABORTED);
}
// Tests that the completion status metrics based on whether the user had
// suggestions for all the requested sections are logged as correctly.
TEST(JourneyLoggerTest,
RecordJourneyStatsHistograms_SuggestionsForEverything_UserAborted) {
base::HistogramTester histogram_tester;
JourneyLogger logger(/*is_incognito=*/false, /*url=*/GURL(""),
/*ukm_recorder=*/nullptr);
// The merchant only requests payment information.
logger.SetRequestedInformation(
/*requested_shipping=*/false, /*requested_email=*/false,
/*requested_phone=*/false, /*requested_name=*/false);
// Simulate that the user had suggestions for all the requested sections.
logger.SetNumberOfSuggestionsShown(JourneyLogger::SECTION_PAYMENT_METHOD, 1,
/*has_complete_suggestion=*/false);
// Simulate that the Payment Request was shown to the user.
logger.SetShowCalled();
// Simulate that the user aborts the checkout.
logger.SetAborted(JourneyLogger::ABORT_REASON_ABORTED_BY_USER);
// Make sure the expected metric was logged.
histogram_tester.ExpectBucketCount(
"PaymentRequest.UserHadSuggestionsForEverything.EffectOnCompletion",
JourneyLogger::COMPLETION_STATUS_USER_ABORTED, 1);
// Make sure the opposite metric was not logged.
EXPECT_THAT(histogram_tester.GetTotalCountsForPrefix(
"PaymentRequest.UserDidNotHaveSuggestionsForEverything."
"EffectOnCompletion"),
testing::ContainerEq(base::HistogramTester::CountsMap()));
// Make sure the correct events were logged.
std::vector<base::Bucket> buckets =
histogram_tester.GetAllSamples("PaymentRequest.Events");
ASSERT_EQ(1U, buckets.size());
EXPECT_FALSE(buckets[0].min &
JourneyLogger::EVENT_HAD_NECESSARY_COMPLETE_SUGGESTIONS);
EXPECT_TRUE(buckets[0].min &
JourneyLogger::EVENT_HAD_INITIAL_FORM_OF_PAYMENT);
EXPECT_TRUE(buckets[0].min & JourneyLogger::EVENT_USER_ABORTED);
EXPECT_FALSE(buckets[0].min & JourneyLogger::EVENT_COMPLETED);
EXPECT_FALSE(buckets[0].min & JourneyLogger::EVENT_OTHER_ABORTED);
}
// Tests that the completion status metrics based on whether the user had
// suggestions for all the requested sections are logged as correctly.
TEST(JourneyLoggerTest,
RecordJourneyStatsHistograms_SuggestionsForEverything_OtherAborted) {
base::HistogramTester histogram_tester;
JourneyLogger logger(/*is_incognito=*/false, /*url=*/GURL(""),
/*ukm_recorder=*/nullptr);
// The merchant only requests payment information.
logger.SetRequestedInformation(
/*requested_shipping=*/false, /*requested_email=*/false,
/*requested_phone=*/false, /*requested_name=*/false);
// Simulate that the user had suggestions for all the requested sections.
logger.SetNumberOfSuggestionsShown(JourneyLogger::SECTION_PAYMENT_METHOD, 1,
/*has_complete_suggestion=*/false);
// Simulate that the Payment Request was shown to the user.
logger.SetShowCalled();
// Simulate that the checkout is aborted.
logger.SetAborted(JourneyLogger::ABORT_REASON_OTHER);
// Make sure the expected metric was logged.
histogram_tester.ExpectBucketCount(
"PaymentRequest.UserHadSuggestionsForEverything.EffectOnCompletion",
JourneyLogger::COMPLETION_STATUS_OTHER_ABORTED, 1);
// Make sure that the opposite metric was not logged.
EXPECT_THAT(histogram_tester.GetTotalCountsForPrefix(
"PaymentRequest.UserDidNotHaveSuggestionsForEverything."
"EffectOnCompletion"),
testing::ContainerEq(base::HistogramTester::CountsMap()));
// Make sure the correct events were logged.
std::vector<base::Bucket> buckets =
histogram_tester.GetAllSamples("PaymentRequest.Events");
ASSERT_EQ(1U, buckets.size());
EXPECT_FALSE(buckets[0].min &
JourneyLogger::EVENT_HAD_NECESSARY_COMPLETE_SUGGESTIONS);
EXPECT_TRUE(buckets[0].min &
JourneyLogger::EVENT_HAD_INITIAL_FORM_OF_PAYMENT);
EXPECT_TRUE(buckets[0].min & JourneyLogger::EVENT_OTHER_ABORTED);
EXPECT_FALSE(buckets[0].min & JourneyLogger::EVENT_COMPLETED);
EXPECT_FALSE(buckets[0].min & JourneyLogger::EVENT_USER_ABORTED);
}
// Tests that the completion status metrics based on whether the user had
// suggestions for all the requested sections are logged as correctly, even in
// incognito mode.
TEST(JourneyLoggerTest,
RecordJourneyStatsHistograms_SuggestionsForEverything_Incognito) {
base::HistogramTester histogram_tester;
JourneyLogger logger(/*is_incognito=*/true, /*url=*/GURL(""),
/*ukm_recorder=*/nullptr);
// The merchant only requests payment information.
logger.SetRequestedInformation(
/*requested_shipping=*/false, /*requested_email=*/false,
/*requested_phone=*/false, /*requested_name=*/false);
// Simulate that the user had suggestions for all the requested sections.
logger.SetNumberOfSuggestionsShown(JourneyLogger::SECTION_PAYMENT_METHOD, 1,
/*has_complete_suggestion=*/false);
// Simulate that the Payment Request was shown to the user.
logger.SetShowCalled();
// Simulate that the user completes the checkout.
logger.SetCompleted();
// Make sure the expected metric was logged.
histogram_tester.ExpectBucketCount(
"PaymentRequest.UserHadSuggestionsForEverything.EffectOnCompletion",
JourneyLogger::COMPLETION_STATUS_COMPLETED, 1);
// Make sure the opposite metric was not logged.
EXPECT_THAT(histogram_tester.GetTotalCountsForPrefix(
"PaymentRequest.UserDidNotHaveSuggestionsForEverything."
"EffectOnCompletion"),
testing::ContainerEq(base::HistogramTester::CountsMap()));
// Make sure the correct events were logged.
std::vector<base::Bucket> buckets =
histogram_tester.GetAllSamples("PaymentRequest.Events");
ASSERT_EQ(1U, buckets.size());
EXPECT_FALSE(buckets[0].min &
JourneyLogger::EVENT_HAD_NECESSARY_COMPLETE_SUGGESTIONS);
EXPECT_TRUE(buckets[0].min &
JourneyLogger::EVENT_HAD_INITIAL_FORM_OF_PAYMENT);
EXPECT_TRUE(buckets[0].min & JourneyLogger::EVENT_COMPLETED);
EXPECT_FALSE(buckets[0].min & JourneyLogger::EVENT_USER_ABORTED);
EXPECT_FALSE(buckets[0].min & JourneyLogger::EVENT_OTHER_ABORTED);
}
// Tests that the completion status metrics based on whether the user had
// suggestions for all the requested sections are logged as correctly.
TEST(JourneyLoggerTest,
RecordJourneyStatsHistograms_NoSuggestionsForEverything_Completed) {
base::HistogramTester histogram_tester;
JourneyLogger logger(/*is_incognito=*/false, /*url=*/GURL(""),
/*ukm_recorder=*/nullptr);
// The merchant only requests payment information.
logger.SetRequestedInformation(
/*requested_shipping=*/false, /*requested_email=*/false,
/*requested_phone=*/false, /*requested_name=*/false);
// Simulate that the user had suggestions for none of the requested sections.
logger.SetNumberOfSuggestionsShown(JourneyLogger::SECTION_PAYMENT_METHOD, 0,
/*has_complete_suggestion=*/false);
// Simulate that the Payment Request was shown to the user.
logger.SetShowCalled();
// Simulate that the user completes the checkout.
logger.SetCompleted();
// Make sure the expected metrics was logged.
histogram_tester.ExpectBucketCount(
"PaymentRequest.UserDidNotHaveSuggestionsForEverything."
"EffectOnCompletion",
JourneyLogger::COMPLETION_STATUS_COMPLETED, 1);
// Make sure the opposite metrics was not logged.
EXPECT_THAT(
histogram_tester.GetTotalCountsForPrefix(
"PaymentRequest.UserHadSuggestionsForEverything.EffectOnCompletion"),
testing::ContainerEq(base::HistogramTester::CountsMap()));
// Make sure the correct events were logged.
std::vector<base::Bucket> buckets =
histogram_tester.GetAllSamples("PaymentRequest.Events");
ASSERT_EQ(1U, buckets.size());
EXPECT_FALSE(buckets[0].min &
JourneyLogger::EVENT_HAD_NECESSARY_COMPLETE_SUGGESTIONS);
EXPECT_FALSE(buckets[0].min &
JourneyLogger::EVENT_HAD_INITIAL_FORM_OF_PAYMENT);
EXPECT_TRUE(buckets[0].min & JourneyLogger::EVENT_COMPLETED);
EXPECT_FALSE(buckets[0].min & JourneyLogger::EVENT_USER_ABORTED);
EXPECT_FALSE(buckets[0].min & JourneyLogger::EVENT_OTHER_ABORTED);
}
// Tests that the completion status metrics based on whether the user had
// suggestions for all the requested sections are logged as correctly.
TEST(JourneyLoggerTest,
RecordJourneyStatsHistograms_NoSuggestionsForEverything_UserAborted) {
base::HistogramTester histogram_tester;
JourneyLogger logger(/*is_incognito=*/false, /*url=*/GURL(""),
/*ukm_recorder=*/nullptr);
// The merchant only requests payment information.
logger.SetRequestedInformation(
/*requested_shipping=*/false, /*requested_email=*/false,
/*requested_phone=*/false, /*requested_name=*/false);
// Simulate that the user had suggestions for none of the requested sections.
logger.SetNumberOfSuggestionsShown(JourneyLogger::SECTION_PAYMENT_METHOD, 0,
/*has_complete_suggestion=*/false);
// Simulate that the Payment Request was shown to the user.
logger.SetShowCalled();
// Simulate that the user aborts the checkout.
logger.SetAborted(JourneyLogger::ABORT_REASON_ABORTED_BY_USER);
// Make sure the metric was logged.
histogram_tester.ExpectBucketCount(
"PaymentRequest.UserDidNotHaveSuggestionsForEverything."
"EffectOnCompletion",
JourneyLogger::COMPLETION_STATUS_USER_ABORTED, 1);
// Make sure the opposite metric was not logged.
EXPECT_THAT(histogram_tester.GetTotalCountsForPrefix(
"PaymentRequest.UserHadSuggestionsForEverything."
"EffectOnCompletion"),
testing::ContainerEq(base::HistogramTester::CountsMap()));
// Make sure the correct events were logged.
std::vector<base::Bucket> buckets =
histogram_tester.GetAllSamples("PaymentRequest.Events");
ASSERT_EQ(1U, buckets.size());
EXPECT_FALSE(buckets[0].min &
JourneyLogger::EVENT_HAD_NECESSARY_COMPLETE_SUGGESTIONS);
EXPECT_FALSE(buckets[0].min &
JourneyLogger::EVENT_HAD_INITIAL_FORM_OF_PAYMENT);
EXPECT_TRUE(buckets[0].min & JourneyLogger::EVENT_USER_ABORTED);
EXPECT_FALSE(buckets[0].min & JourneyLogger::EVENT_COMPLETED);
EXPECT_FALSE(buckets[0].min & JourneyLogger::EVENT_OTHER_ABORTED);
}
// Tests that the completion status metrics based on whether the user had
// suggestions for all the requested sections are logged as correctly.
TEST(JourneyLoggerTest,
RecordJourneyStatsHistograms_NoSuggestionsForEverything_OtherAborted) {
base::HistogramTester histogram_tester;
JourneyLogger logger(/*is_incognito=*/false, /*url=*/GURL(""),
/*ukm_recorder=*/nullptr);
// The merchant only requests payment information.
logger.SetRequestedInformation(
/*requested_shipping=*/false, /*requested_email=*/false,
/*requested_phone=*/false, /*requested_name=*/false);
// Simulate that the user had suggestions for none of the requested sections.
logger.SetNumberOfSuggestionsShown(JourneyLogger::SECTION_PAYMENT_METHOD, 0,
/*has_complete_suggestion=*/false);
// Simulate that the Payment Request was shown to the user.
logger.SetShowCalled();
// Simulate that the the checkout is aborted.
logger.SetAborted(JourneyLogger::ABORT_REASON_OTHER);
// Make sure the expected metric was logged.
histogram_tester.ExpectBucketCount(
"PaymentRequest.UserDidNotHaveSuggestionsForEverything."
"EffectOnCompletion",
JourneyLogger::COMPLETION_STATUS_OTHER_ABORTED, 1);
// Make sure the opposite metric was not logged.
EXPECT_THAT(histogram_tester.GetTotalCountsForPrefix(
"PaymentRequest.UserHadSuggestionsForEverything."
"EffectOnCompletion"),
testing::ContainerEq(base::HistogramTester::CountsMap()));
// Make sure the correct events were logged.
std::vector<base::Bucket> buckets =
histogram_tester.GetAllSamples("PaymentRequest.Events");
ASSERT_EQ(1U, buckets.size());
EXPECT_FALSE(buckets[0].min &
JourneyLogger::EVENT_HAD_NECESSARY_COMPLETE_SUGGESTIONS);
EXPECT_FALSE(buckets[0].min &
JourneyLogger::EVENT_HAD_INITIAL_FORM_OF_PAYMENT);
EXPECT_TRUE(buckets[0].min & JourneyLogger::EVENT_OTHER_ABORTED);
EXPECT_FALSE(buckets[0].min & JourneyLogger::EVENT_COMPLETED);
EXPECT_FALSE(buckets[0].min & JourneyLogger::EVENT_USER_ABORTED);
}
// Tests that the completion status metrics based on whether the user had
// suggestions for all the requested sections are logged as correctly, even in
// incognito mode.
TEST(JourneyLoggerTest,
RecordJourneyStatsHistograms_NoSuggestionsForEverything_Incognito) {
base::HistogramTester histogram_tester;
JourneyLogger logger(/*is_incognito=*/true, /*url=*/GURL(""),
/*ukm_recorder=*/nullptr);
// The merchant only requests payment information.
logger.SetRequestedInformation(
/*requested_shipping=*/false, /*requested_email=*/false,
/*requested_phone=*/false, /*requested_name=*/false);
// Simulate that the user had suggestions for none of the requested sections.
logger.SetNumberOfSuggestionsShown(JourneyLogger::SECTION_PAYMENT_METHOD, 0,
/*has_complete_suggestion=*/false);
// Simulate that the Payment Request was shown to the user.
logger.SetShowCalled();
// Simulate that the user aborts the checkout.
logger.SetAborted(JourneyLogger::ABORT_REASON_ABORTED_BY_USER);
// Make sure the expected metric was logged.
histogram_tester.ExpectBucketCount(
"PaymentRequest.UserDidNotHaveSuggestionsForEverything."
"EffectOnCompletion",
JourneyLogger::COMPLETION_STATUS_USER_ABORTED, 1);
// Make sure the opposite metric was not logged.
EXPECT_THAT(histogram_tester.GetTotalCountsForPrefix(
"PaymentRequest.UserHadSuggestionsForEverything."
"EffectOnCompletion"),
testing::ContainerEq(base::HistogramTester::CountsMap()));
// Make sure the correct events were logged.
std::vector<base::Bucket> buckets =
histogram_tester.GetAllSamples("PaymentRequest.Events");
ASSERT_EQ(1U, buckets.size());
EXPECT_FALSE(buckets[0].min &
JourneyLogger::EVENT_HAD_NECESSARY_COMPLETE_SUGGESTIONS);
EXPECT_FALSE(buckets[0].min &
JourneyLogger::EVENT_HAD_INITIAL_FORM_OF_PAYMENT);
EXPECT_TRUE(buckets[0].min & JourneyLogger::EVENT_USER_ABORTED);
EXPECT_FALSE(buckets[0].min & JourneyLogger::EVENT_COMPLETED);
EXPECT_FALSE(buckets[0].min & JourneyLogger::EVENT_OTHER_ABORTED);
}
// Tests that the completion status metrics based on whether the user had
// suggestions for all the requested sections are logged as correctly.
TEST(
JourneyLoggerTest,
RecordJourneyStatsHistograms_NoCompleteSuggestionsForEverything_OtherAborted) {
base::HistogramTester histogram_tester;
JourneyLogger logger(/*is_incognito=*/false, /*url=*/GURL(""),
/*ukm_recorder=*/nullptr);
// The merchant only requests payment information.
logger.SetRequestedInformation(
/*requested_shipping=*/false, /*requested_email=*/false,
/*requested_phone=*/false, /*requested_name=*/false);
// Simulate that the user had incomplete suggestions for the requested
// sections.
logger.SetNumberOfSuggestionsShown(JourneyLogger::SECTION_PAYMENT_METHOD, 2,
/*has_complete_suggestion=*/false);
// Simulate that the Payment Request was shown to the user.
logger.SetShowCalled();
// Simulate that the the checkout is aborted.
logger.SetAborted(JourneyLogger::ABORT_REASON_OTHER);
// Make sure the expected metric was logged.
histogram_tester.ExpectBucketCount(
"PaymentRequest.UserDidNotHaveCompleteSuggestionsForEverything."
"EffectOnCompletion",
JourneyLogger::COMPLETION_STATUS_OTHER_ABORTED, 1);
// Makes sure the opposite metric was not logged.
EXPECT_THAT(histogram_tester.GetTotalCountsForPrefix(
"PaymentRequest.UserHadCompleteSuggestionsForEverything."
"EffectOnCompletion"),
testing::ContainerEq(base::HistogramTester::CountsMap()));
// Make sure the correct events were logged.
std::vector<base::Bucket> buckets =
histogram_tester.GetAllSamples("PaymentRequest.Events");
ASSERT_EQ(1U, buckets.size());
EXPECT_FALSE(buckets[0].min &
JourneyLogger::EVENT_HAD_NECESSARY_COMPLETE_SUGGESTIONS);
EXPECT_TRUE(buckets[0].min &
JourneyLogger::EVENT_HAD_INITIAL_FORM_OF_PAYMENT);
EXPECT_TRUE(buckets[0].min & JourneyLogger::EVENT_OTHER_ABORTED);
EXPECT_FALSE(buckets[0].min & JourneyLogger::EVENT_COMPLETED);
EXPECT_FALSE(buckets[0].min & JourneyLogger::EVENT_USER_ABORTED);
}
// Tests that the completion status metrics based on whether the user had
// suggestions for all the requested sections are logged as correctly.
TEST(
JourneyLoggerTest,
RecordJourneyStatsHistograms_NoCompleteSuggestionsForEverything_SomeComplete_OtherAborted) {
base::HistogramTester histogram_tester;
JourneyLogger logger(/*is_incognito=*/false, /*url=*/GURL(""),
/*ukm_recorder=*/nullptr);
// The merchant only requests payment information.
logger.SetRequestedInformation(
/*requested_shipping=*/true, /*requested_email=*/false,
/*requested_phone=*/false, /*requested_name=*/false);
// Simulate that the user had incomplete suggestions for one of the requested
// sections.
logger.SetNumberOfSuggestionsShown(JourneyLogger::SECTION_PAYMENT_METHOD, 2,
/*has_complete_suggestion=*/false);
logger.SetNumberOfSuggestionsShown(JourneyLogger::SECTION_SHIPPING_ADDRESS, 1,
/*has_complete_suggestion=*/true);
// Simulate that the Payment Request was shown to the user.
logger.SetShowCalled();
// Simulate that the the checkout is aborted.
logger.SetAborted(JourneyLogger::ABORT_REASON_OTHER);
// Make sure that the expected metric was logged.
histogram_tester.ExpectBucketCount(
"PaymentRequest.UserDidNotHaveCompleteSuggestionsForEverything."
"EffectOnCompletion",
JourneyLogger::COMPLETION_STATUS_OTHER_ABORTED, 1);
// Make sure that the opposite metric was not logged.
EXPECT_THAT(histogram_tester.GetTotalCountsForPrefix(
"PaymentRequest.UserHadCompleteSuggestionsForEverything."
"EffectOnCompletion"),
testing::ContainerEq(base::HistogramTester::CountsMap()));
// Make sure the correct events were logged.
std::vector<base::Bucket> buckets =
histogram_tester.GetAllSamples("PaymentRequest.Events");
ASSERT_EQ(1U, buckets.size());
EXPECT_FALSE(buckets[0].min &
JourneyLogger::EVENT_HAD_NECESSARY_COMPLETE_SUGGESTIONS);
EXPECT_TRUE(buckets[0].min &
JourneyLogger::EVENT_HAD_INITIAL_FORM_OF_PAYMENT);
EXPECT_TRUE(buckets[0].min & JourneyLogger::EVENT_OTHER_ABORTED);
EXPECT_FALSE(buckets[0].min & JourneyLogger::EVENT_COMPLETED);
EXPECT_FALSE(buckets[0].min & JourneyLogger::EVENT_USER_ABORTED);
}
// Tests that the completion status metrics based on whether the user had
// suggestions for all the requested sections are logged as correctly.
TEST(
JourneyLoggerTest,
RecordJourneyStatsHistograms_CompleteSuggestionsForEverything_OtherAborted) {
base::HistogramTester histogram_tester;
JourneyLogger logger(/*is_incognito=*/false, /*url=*/GURL(""),
/*ukm_recorder=*/nullptr);
// The merchant only requests payment information.
logger.SetRequestedInformation(
/*requested_shipping=*/true, /*requested_email=*/false,
/*requested_phone=*/false, /*requested_name=*/false);
// Simulate that the user had incomplete suggestions for one of the requested
// sections.
logger.SetNumberOfSuggestionsShown(JourneyLogger::SECTION_PAYMENT_METHOD, 2,
/*has_complete_suggestion=*/true);
logger.SetNumberOfSuggestionsShown(JourneyLogger::SECTION_SHIPPING_ADDRESS, 1,
/*has_complete_suggestion=*/true);
// Simulate that the Payment Request was shown to the user.
logger.SetShowCalled();
// Simulate that the the checkout is aborted.
logger.SetAborted(JourneyLogger::ABORT_REASON_OTHER);
// Make sure that the expected metric was logged.
histogram_tester.ExpectBucketCount(
"PaymentRequest.UserHadCompleteSuggestionsForEverything."
"EffectOnCompletion",
JourneyLogger::COMPLETION_STATUS_OTHER_ABORTED, 1);
// Make sure that the opposite metric was not logged.
EXPECT_THAT(
histogram_tester.GetTotalCountsForPrefix(
"PaymentRequest.UserDidNotHaveCompleteSuggestionsForEverything."
"EffectOnCompletion"),
testing::ContainerEq(base::HistogramTester::CountsMap()));
// Make sure the correct events were logged.
std::vector<base::Bucket> buckets =
histogram_tester.GetAllSamples("PaymentRequest.Events");
ASSERT_EQ(1U, buckets.size());
EXPECT_TRUE(buckets[0].min &
JourneyLogger::EVENT_HAD_NECESSARY_COMPLETE_SUGGESTIONS);
EXPECT_TRUE(buckets[0].min &
JourneyLogger::EVENT_HAD_INITIAL_FORM_OF_PAYMENT);
EXPECT_TRUE(buckets[0].min & JourneyLogger::EVENT_OTHER_ABORTED);
EXPECT_FALSE(buckets[0].min & JourneyLogger::EVENT_COMPLETED);
EXPECT_FALSE(buckets[0].min & JourneyLogger::EVENT_USER_ABORTED);
}
// Tests that the metrics are logged correctly for two simultaneous Payment
// Requests.
TEST(JourneyLoggerTest, RecordJourneyStatsHistograms_TwoPaymentRequests) {
base::HistogramTester histogram_tester;
JourneyLogger logger1(/*is_incognito=*/false, /*url=*/GURL(""),
/*ukm_recorder=*/nullptr);
JourneyLogger logger2(/*is_incognito=*/false, /*url=*/GURL(""),
/*ukm_recorder=*/nullptr);
// Make the two loggers have different data.
logger1.SetShowCalled();
logger1.SetRequestedInformation(
/*requested_shipping=*/true, /*requested_email=*/true,
/*requested_phone=*/false, /*requested_name=*/false);
logger2.SetShowCalled();
logger2.SetRequestedInformation(
/*requested_shipping=*/true, /*requested_email=*/false,
/*requested_phone=*/false, /*requested_name=*/false);
logger1.SetCanMakePaymentValue(true);
logger1.SetNumberOfSuggestionsShown(JourneyLogger::SECTION_PAYMENT_METHOD, 1,
/*has_complete_suggestion=*/false);
logger2.SetNumberOfSuggestionsShown(JourneyLogger::SECTION_PAYMENT_METHOD, 0,
/*has_complete_suggestion=*/false);
// Simulate that the user completes one checkout and aborts the other.
logger1.SetCompleted();
logger2.SetAborted(JourneyLogger::ABORT_REASON_ABORTED_BY_USER);
// Make sure the appropriate metrics were logged for logger1.
histogram_tester.ExpectBucketCount(
"PaymentRequest.UserHadSuggestionsForEverything.EffectOnCompletion",
JourneyLogger::COMPLETION_STATUS_COMPLETED, 1);
histogram_tester.ExpectBucketCount("PaymentRequest.CanMakePayment.Usage",
JourneyLogger::CAN_MAKE_PAYMENT_USED, 1);
histogram_tester.ExpectBucketCount(
"PaymentRequest.CanMakePayment.Used.TrueWithShowEffectOnCompletion",
JourneyLogger::COMPLETION_STATUS_COMPLETED, 1);
// Make sure the appropriate metrics were logged for logger2.
histogram_tester.ExpectBucketCount(
"PaymentRequest.UserDidNotHaveSuggestionsForEverything."
"EffectOnCompletion",
JourneyLogger::COMPLETION_STATUS_USER_ABORTED, 1);
histogram_tester.ExpectBucketCount("PaymentRequest.CanMakePayment.Usage",
JourneyLogger::CAN_MAKE_PAYMENT_NOT_USED,
1);
histogram_tester.ExpectBucketCount(
"PaymentRequest.CanMakePayment.NotUsed.WithShowEffectOnCompletion",
JourneyLogger::COMPLETION_STATUS_USER_ABORTED, 1);
}
// Tests that the Payment Request UKMs are logged correctly when the user aborts
// the Payment Request.
TEST(JourneyLoggerTest,
RecordJourneyStatsHistograms_CheckoutFunnelUkm_UserAborted) {
ukm::TestAutoSetUkmRecorder ukm_recorder;
char test_url[] = "http://www.google.com/";
base::HistogramTester histogram_tester;
JourneyLogger logger(/*is_incognito=*/true, /*url=*/GURL(test_url),
/*ukm_recorder=*/&ukm_recorder);
// Simulate that the user aborts after being shown the Payment Request and
// clicking pay.
logger.SetEventOccurred(JourneyLogger::EVENT_SHOWN);
logger.SetEventOccurred(JourneyLogger::EVENT_PAY_CLICKED);
logger.SetAborted(JourneyLogger::ABORT_REASON_ABORTED_BY_USER);
// Make sure the UKM was logged correctly.
ASSERT_EQ(1U, ukm_recorder.sources_count());
const ukm::UkmSource* source = ukm_recorder.GetSourceForUrl(test_url);
ASSERT_NE(nullptr, source);
ASSERT_EQ(1U, ukm_recorder.entries_count());
const ukm::mojom::UkmEntry* entry = ukm_recorder.GetEntry(0);
EXPECT_EQ(source->id(), entry->source_id);
EXPECT_EQ(base::HashMetricName(internal::kUKMCheckoutEventsEntryName),
entry->event_hash);
const ukm::mojom::UkmMetric* status_metric = ukm::TestUkmRecorder::FindMetric(
entry, internal::kUKMCompletionStatusMetricName);
ASSERT_NE(nullptr, status_metric);
EXPECT_EQ(JourneyLogger::COMPLETION_STATUS_USER_ABORTED,
status_metric->value);
const ukm::mojom::UkmMetric* step_metric =
ukm::TestUkmRecorder::FindMetric(entry, internal::kUKMEventsMetricName);
ASSERT_NE(nullptr, step_metric);
EXPECT_EQ(JourneyLogger::EVENT_SHOWN | JourneyLogger::EVENT_PAY_CLICKED,
step_metric->value);
}
// Tests that the Payment Request UKMs are logged correctly when the user
// completes the Payment Request.
TEST(JourneyLoggerTest,
RecordJourneyStatsHistograms_CheckoutFunnelUkm_Completed) {
ukm::TestAutoSetUkmRecorder ukm_recorder;
char test_url[] = "http://www.google.com/";
base::HistogramTester histogram_tester;
JourneyLogger logger(/*is_incognito=*/true, /*url=*/GURL(test_url),
/*ukm_recorder=*/&ukm_recorder);
// Simulate that the user aborts after being shown the Payment Request.
logger.SetEventOccurred(JourneyLogger::EVENT_SHOWN);
logger.SetCompleted();
// Make sure the UKM was logged correctly.
ASSERT_EQ(1U, ukm_recorder.sources_count());
const ukm::UkmSource* source = ukm_recorder.GetSourceForUrl(test_url);
ASSERT_NE(nullptr, source);
ASSERT_EQ(1U, ukm_recorder.entries_count());
const ukm::mojom::UkmEntry* entry = ukm_recorder.GetEntry(0);
EXPECT_EQ(source->id(), entry->source_id);
EXPECT_EQ(base::HashMetricName(internal::kUKMCheckoutEventsEntryName),
entry->event_hash);
const ukm::mojom::UkmMetric* status_metric = ukm::TestUkmRecorder::FindMetric(
entry, internal::kUKMCompletionStatusMetricName);
ASSERT_NE(nullptr, status_metric);
EXPECT_EQ(JourneyLogger::COMPLETION_STATUS_COMPLETED, status_metric->value);
const ukm::mojom::UkmMetric* step_metric =
ukm::TestUkmRecorder::FindMetric(entry, internal::kUKMEventsMetricName);
ASSERT_NE(nullptr, step_metric);
EXPECT_EQ(JourneyLogger::EVENT_SHOWN, step_metric->value);
}
} // namespace payments
| 44.05893 | 96 | 0.73558 | metux |
f62b23f95c442075e0a6cadee50fc25b565bf479 | 4,132 | cpp | C++ | src/download.cpp | toyobayashi/evm-windows | 5734cfe8555ccc492671e15bc30b54467681c749 | [
"MIT"
] | null | null | null | src/download.cpp | toyobayashi/evm-windows | 5734cfe8555ccc492671e15bc30b54467681c749 | [
"MIT"
] | null | null | null | src/download.cpp | toyobayashi/evm-windows | 5734cfe8555ccc492671e15bc30b54467681c749 | [
"MIT"
] | null | null | null | #include <sstream>
#include <math.h>
#include <time.h>
#include "download.h"
#include <curl/curl.h>
#include <iostream>
#include "path.hpp"
//static size_t onDataString(void* buffer, size_t size, size_t nmemb, progressInfo * userp) {
// const char* d = (const char*)buffer;
// // userp->headerString.append(d, size * nmemb);
// std::string tmp(d);
// unsigned int contentlengthIndex = tmp.find(std::string("Content-Length: "));
// if (contentlengthIndex != std::string::npos) {
// userp->total = atoi(tmp.substr(16, tmp.find_first_of('\r')).c_str()) + userp->size;
// }
// return size * nmemb;
//}
static size_t onDataWrite(void* buffer, size_t size, size_t nmemb, progressInfo * userp) {
if (userp->code == -1) {
curl_easy_getinfo(userp->curl, CURLINFO_RESPONSE_CODE, &(userp->code));
}
if (userp->code >= 400) {
return size * nmemb;
}
if (userp->total == -1) {
curl_off_t cl;
curl_easy_getinfo(userp->curl, CURLINFO_CONTENT_LENGTH_DOWNLOAD_T, &cl);
if (cl != -1) {
userp->total = (long)cl + userp->size;
} else {
return size * nmemb;
}
}
if (userp->fp == nullptr) {
Path::mkdirp(Path::dirname(userp->path));
_wfopen_s(&(userp->fp), (userp->path + L".tmp").c_str(), L"ab+");
if (!(userp->fp)) {
return size * nmemb;
}
}
size_t iRec = fwrite(buffer, size, nmemb, userp->fp);
if (iRec < 0) {
return iRec;
}
userp->sum += iRec;
userp->speed += iRec;
int now = clock();
if (now - userp->last_time > 200) {
userp->last_time = now;
userp->speed = 0;
if (userp->callback) {
userp->callback(userp, userp->param);
}
} else if (userp->sum == userp->total - userp->size) {
userp->end_time = clock();
if (userp->callback) {
userp->callback(userp, userp->param);
}
}
return iRec;
}
bool download (std::wstring url, std::wstring path, downloadCallback callback, void* param) {
if (Path::exists(path)) {
if (Path::isDirectory(path)) {
return false;
}
return true;
}
CURL* curl = curl_easy_init();
struct curl_slist* headers = nullptr;
/*headers = curl_slist_append(headers, "Connection: Keep-Alive");
headers = curl_slist_append(headers, "Accept-Encoding: gzip");*/
headers = curl_slist_append(headers, "Accept: */*");
headers = curl_slist_append(headers, "User-Agent: Electron Version Manager");
struct _stat stat;
int res = _wstat((path + L".tmp").c_str(), &stat);
long size = stat.st_size;
if (size != 0) {
headers = curl_slist_append(headers, (std::string("Range: bytes=") + std::to_string(size) + "-").c_str());
}
curl_easy_setopt(curl, CURLOPT_HTTPHEADER, headers);
curl_easy_setopt(curl, CURLOPT_URL, Util::w2a(url, CP_UTF8).c_str());
curl_easy_setopt(curl, CURLOPT_CUSTOMREQUEST, "GET");
curl_easy_setopt(curl, CURLOPT_CONNECTTIMEOUT, 10);
curl_easy_setopt(curl, CURLOPT_FOLLOWLOCATION, 1);
//curl_easy_setopt(curl, CURLOPT_TIMEOUT, 10);
progressInfo info;
info.path = path;
info.curl = curl;
info.fp = nullptr;
info.size = size;
info.sum = 0;
info.speed = 0;
info.start_time = clock();
info.end_time = 0;
info.last_time = 0;
info.total = -1;
info.param = param;
info.code = -1;
info.callback = callback;
// curl_easy_setopt(curl, CURLOPT_HEADERFUNCTION, &onDataString);
// curl_easy_setopt(curl, CURLOPT_HEADERDATA, &info);
curl_easy_setopt(curl, CURLOPT_WRITEFUNCTION, &onDataWrite);
curl_easy_setopt(curl, CURLOPT_WRITEDATA, &info);
curl_easy_setopt(curl, CURLOPT_SSL_VERIFYPEER, 0L);
curl_easy_setopt(curl, CURLOPT_SSL_VERIFYHOST, 0L);
CURLcode code = curl_easy_perform(curl);
if (code != CURLE_OK) {
printf("%s\n", curl_easy_strerror(code));
if (info.fp != nullptr) {
fclose(info.fp);
info.fp = nullptr;
}
curl_slist_free_all(headers);
curl_easy_cleanup(curl);
return false;
}
if (info.fp != nullptr) {
fclose(info.fp);
info.fp = nullptr;
if (Path::exists(path + L".tmp")) {
Path::rename(path + L".tmp", path);
}
}
curl_slist_free_all(headers);
curl_easy_cleanup(curl);
return true;
}
| 27.731544 | 110 | 0.644966 | toyobayashi |
f62ea6aed389d2f91dcc32f5992bb286e7a61b01 | 2,636 | cpp | C++ | modules/core/engine/src/EngineServiceManager.cpp | syl22-00/aac-sdk | 79696da55b0bca09a4c68f361ef1f47efb8f717e | [
"Apache-2.0"
] | 4 | 2018-08-29T08:16:52.000Z | 2019-05-17T02:04:56.000Z | modules/core/engine/src/EngineServiceManager.cpp | syl22-00/aac-sdk | 79696da55b0bca09a4c68f361ef1f47efb8f717e | [
"Apache-2.0"
] | null | null | null | modules/core/engine/src/EngineServiceManager.cpp | syl22-00/aac-sdk | 79696da55b0bca09a4c68f361ef1f47efb8f717e | [
"Apache-2.0"
] | 1 | 2020-05-18T02:02:47.000Z | 2020-05-18T02:02:47.000Z | /*
* Copyright 2017-2018 Amazon.com, Inc. or its affiliates. All Rights Reserved.
*
* Licensed under the Apache License, Version 2.0 (the "License").
* You may not use this file except in compliance with the License.
* A copy of the License is located at
*
* http://aws.amazon.com/apache2.0/
*
* or in the "license" file accompanying this file. This file 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 "AACE/Engine/Core/EngineServiceManager.h"
#include "AACE/Engine/Core/EngineMacros.h"
namespace aace {
namespace engine {
namespace core {
// String to identify log entries originating from this file.
static const std::string TAG("aace.core.EngineServiceManager");
std::shared_ptr<EngineServiceManager> EngineServiceManager::s_instance = nullptr;
std::shared_ptr<EngineServiceManager> EngineServiceManager::getInstance()
{
if( s_instance == nullptr ) {
s_instance = std::shared_ptr<EngineServiceManager>( new EngineServiceManager() );
}
return s_instance;
}
bool EngineServiceManager::registerService( const ServiceDescription& description, std::function<std::shared_ptr<EngineService>(const ServiceDescription&)> constructor )
{
try
{
auto type = description.getType();
ThrowIfNot( getInstance()->m_serviceMap.find( type ) == getInstance()->m_serviceMap.end(), "serviceAlreadyRegistered" );
getInstance()->m_serviceMap[type] = ServiceFactory::create( description, constructor );
return true;
}
catch( std::exception& ex ) {
AACE_ERROR(LX(TAG,"registerService").d("reason", ex.what()));
return false;
}
}
EngineServiceManager::ServiceMap::iterator EngineServiceManager::registryBegin() {
return getInstance()->m_serviceMap.begin();
}
EngineServiceManager::ServiceMap::iterator EngineServiceManager::registryEnd() {
return getInstance()->m_serviceMap.end();
}
//
// ServiceFactory
//
std::shared_ptr<ServiceFactory> ServiceFactory::create( const ServiceDescription& description, std::function<std::shared_ptr<EngineService>(const ServiceDescription&)> constructor )
{
auto factory = std::shared_ptr<ServiceFactory>( new ServiceFactory() );
factory->m_description = description;
factory->m_constructor = constructor;
return factory;
}
std::shared_ptr<EngineService> ServiceFactory::newInstance() {
return m_constructor( m_description );
}
} // aace::engine::core
} // aace::engine
} // aace
| 31.380952 | 181 | 0.724583 | syl22-00 |
f62f1572f726e6299c7988be717afbe9be20041d | 11,294 | cc | C++ | zircon/system/utest/trace/record_tests.cc | casey/fuchsia | 2b965e9a1e8f2ea346db540f3611a5be16bb4d6b | [
"BSD-3-Clause"
] | null | null | null | zircon/system/utest/trace/record_tests.cc | casey/fuchsia | 2b965e9a1e8f2ea346db540f3611a5be16bb4d6b | [
"BSD-3-Clause"
] | null | null | null | zircon/system/utest/trace/record_tests.cc | casey/fuchsia | 2b965e9a1e8f2ea346db540f3611a5be16bb4d6b | [
"BSD-3-Clause"
] | null | null | null | // Copyright 2018 The Fuchsia Authors. All rights reserved.
// Use of this source code is governed by a BSD-style license that can be
// found in the LICENSE file.
#include <inttypes.h>
#include <zircon/syscalls.h>
#include <array>
#include <memory>
#include <fbl/algorithm.h>
#include <fbl/string_printf.h>
#include <fbl/vector.h>
#include <trace-engine/instrumentation.h>
#include <trace-test-utils/fixture.h>
#include <trace/event.h>
#include "fixture_macros.h"
namespace {
bool blob_test() {
BEGIN_TRACE_TEST;
fixture_initialize_and_start_tracing();
const char name[] = "name";
trace_string_ref_t name_ref = trace_make_inline_c_string_ref(name);
const char blob[] = "abc";
const size_t length = sizeof(blob);
const char preview[] = "<61 62 63 00>";
{
auto context = trace::TraceContext::Acquire();
trace_context_write_blob_record(context.get(), TRACE_BLOB_TYPE_DATA, &name_ref, blob, length);
}
auto expected =
fbl::StringPrintf("Blob(name: %s, size: %zu, preview: %s)\n", name, length, preview);
EXPECT_TRUE(fixture_compare_records(expected.c_str()), "record mismatch");
END_TRACE_TEST;
}
bool blob_macro_test() {
BEGIN_TRACE_TEST;
fixture_initialize_and_start_tracing();
const char name[] = "all-byte-values";
const size_t length = 256;
auto blob = std::make_unique<std::array<char, length>>();
for (unsigned i = 0; i < length; ++i) {
blob->at(i) = static_cast<char>(i);
}
const char preview[] = "<00 01 02 03 04 05 06 07 ... f8 f9 fa fb fc fd fe ff>";
TRACE_BLOB(TRACE_BLOB_TYPE_DATA, name, blob->data(), length);
auto expected = fbl::StringPrintf(
"String(index: 1, \"%s\")\n"
"Blob(name: %s, size: %zu, preview: %s)\n",
name, name, length, preview);
EXPECT_TRUE(fixture_compare_records(expected.c_str()), "record mismatch");
END_TRACE_TEST;
}
bool large_blob_attachment_test() {
BEGIN_TRACE_TEST;
fixture_initialize_and_start_tracing();
const char category[] = "+enabled";
const char name[] = "name";
trace_string_ref_t category_ref = trace_make_inline_c_string_ref(category);
trace_string_ref_t name_ref = trace_make_inline_c_string_ref(name);
const size_t length = (1ull << 15); // 32KB
auto blob = std::make_unique<std::array<char, length>>();
for (unsigned i = 0; i < length; ++i) {
blob->at(i) = static_cast<char>(i);
}
const char preview[] = "<00 01 02 03 04 05 06 07 ... f8 f9 fa fb fc fd fe ff>";
{
auto context = trace::TraceContext::Acquire();
trace_context_write_blob_attachment_record(context.get(), &category_ref, &name_ref,
blob->data(), length);
}
auto expected = fbl::StringPrintf(
"LargeRecord(Blob(format: blob_attachment, category: \"%s\", name: \"%s\", size: %zu, "
"preview: %s))\n",
category, name, length, preview);
EXPECT_TRUE(fixture_compare_records(expected.c_str()), "record mismatch");
END_TRACE_TEST;
}
bool large_blob_attachment_macro_test() {
BEGIN_TRACE_TEST;
fixture_initialize_and_start_tracing();
const char name[] = "all-byte-values";
const size_t length = 260;
auto blob = std::make_unique<std::array<char, length>>();
for (unsigned i = 0; i < length; ++i) {
blob->at(i) = static_cast<char>(i);
}
const char preview[] = "<00 01 02 03 04 05 06 07 ... fc fd fe ff 00 01 02 03>";
const char* category = "+enabled";
TRACE_BLOB_ATTACHMENT(category, name, blob->data(), length);
auto expected = fbl::StringPrintf(
"String(index: 1, \"%s\")\n"
"String(index: 2, \"%s\")\n"
"LargeRecord(Blob(format: blob_attachment, category: \"%s\", name: \"%s\", size: %zu, "
"preview: %s))\n",
category, name, category, name, length, preview);
EXPECT_TRUE(fixture_compare_records(expected.c_str()), "record mismatch");
END_TRACE_TEST;
}
bool large_blob_event_macro_args_test() {
BEGIN_TRACE_TEST;
fixture_initialize_and_start_tracing();
const char name[] = "all-byte-values";
const size_t length = 256;
auto blob = std::make_unique<std::array<char, length>>();
for (unsigned i = 0; i < length; ++i) {
blob->at(i) = static_cast<char>(i);
}
const char preview[] = "<00 01 02 03 04 05 06 07 ... f8 f9 fa fb fc fd fe ff>";
const char* category = "+enabled";
TRACE_BLOB_EVENT(category, name, blob->data(), length, "arg1", TA_INT32(234234));
auto expected = fbl::StringPrintf(
"String(index: 1, \"%s\")\n"
"String(index: 2, \"process\")\n"
"KernelObject(koid: <>, type: thread, name: \"initial-thread\", {process: koid(<>)})\n"
"Thread(index: 1, <>)\n"
"String(index: 3, \"%s\")\n"
"String(index: 4, \"arg1\")\n"
"LargeRecord(Blob(format: blob_event, category: \"%s\", name: \"%s\", ts: <>, pt: <>, {arg1: "
"int32(234234)}, "
"size: %zu, preview: %s))\n",
category, name, category, name, length, preview);
EXPECT_TRUE(fixture_compare_records(expected.c_str()), "record mismatch");
END_TRACE_TEST;
}
bool large_blob_event_macro_small_test() {
BEGIN_TRACE_TEST;
fixture_initialize_and_start_tracing();
const char name[] = "all-byte-values";
const size_t length = 260;
auto blob = std::make_unique<std::array<char, length>>();
for (unsigned i = 0; i < length; ++i) {
blob->at(i) = static_cast<char>(i);
}
const char preview[] = "<00 01 02 03 04 05 06 07 ... fc fd fe ff 00 01 02 03>";
const char* category = "+enabled";
TRACE_BLOB_EVENT(category, name, blob->data(), length);
auto expected = fbl::StringPrintf(
"String(index: 1, \"%s\")\n"
"String(index: 2, \"process\")\n"
"KernelObject(koid: <>, type: thread, name: \"initial-thread\", {process: koid(<>)})\n"
"Thread(index: 1, <>)\n"
"String(index: 3, \"%s\")\n"
"LargeRecord(Blob(format: blob_event, category: \"%s\", name: \"%s\", ts: <>, pt: <>, {}, "
"size: %zu, preview: %s))\n",
category, name, category, name, length, preview);
EXPECT_TRUE(fixture_compare_records(expected.c_str()), "record mismatch");
END_TRACE_TEST;
}
bool large_blob_event_macro_medium_test() {
BEGIN_TRACE_TEST;
fixture_initialize_and_start_tracing();
const char name[] = "all-byte-values";
const size_t length = (1ull << 15); // 32KB
auto blob = std::make_unique<std::array<char, length>>();
for (unsigned i = 0; i < length; ++i) {
blob->at(i) = static_cast<char>(i);
}
const char preview[] = "<00 01 02 03 04 05 06 07 ... f8 f9 fa fb fc fd fe ff>";
const char* category = "+enabled";
TRACE_BLOB_EVENT(category, name, blob->data(), length);
auto expected = fbl::StringPrintf(
"String(index: 1, \"%s\")\n"
"String(index: 2, \"process\")\n"
"KernelObject(koid: <>, type: thread, name: \"initial-thread\", {process: koid(<>)})\n"
"Thread(index: 1, <>)\n"
"String(index: 3, \"%s\")\n"
"LargeRecord(Blob(format: blob_event, category: \"%s\", name: \"%s\", ts: <>, pt: <>, {}, "
"size: %zu, preview: %s))\n",
category, name, category, name, length, preview);
EXPECT_TRUE(fixture_compare_records(expected.c_str()), "record mismatch");
END_TRACE_TEST;
}
bool large_blob_event_macro_big_test() {
BEGIN_TRACE_TEST;
fixture_initialize_and_start_tracing();
const char name[] = "all-byte-values";
const size_t length = TRACE_ENCODED_INLINE_LARGE_RECORD_MAX_SIZE - 356;
auto blob = std::make_unique<std::array<char, length>>();
for (unsigned i = 0; i < length; ++i) {
blob->at(i) = static_cast<char>(i);
}
const char preview[] = "<00 01 02 03 04 05 06 07 ... 94 95 96 97 98 99 9a 9b>";
const char* category = "+enabled";
TRACE_BLOB_EVENT(category, name, blob->data(), length);
auto expected = fbl::StringPrintf(
"String(index: 1, \"%s\")\n"
"String(index: 2, \"process\")\n"
"KernelObject(koid: <>, type: thread, name: \"initial-thread\", {process: koid(<>)})\n"
"Thread(index: 1, <>)\n"
"String(index: 3, \"%s\")\n"
"LargeRecord(Blob(format: blob_event, category: \"%s\", name: \"%s\", ts: <>, pt: <>, {}, "
"size: %zu, preview: %s))\n",
category, name, category, name, length, preview);
EXPECT_TRUE(fixture_compare_records(expected.c_str()), "record mismatch");
END_TRACE_TEST;
}
bool large_blob_event_macro_rejected_test() {
BEGIN_TRACE_TEST;
fixture_initialize_and_start_tracing();
const char name[] = "all-byte-values";
const size_t length = TRACE_ENCODED_INLINE_LARGE_RECORD_MAX_SIZE + 100;
auto blob = std::make_unique<std::array<char, length>>();
for (unsigned i = 0; i < length; ++i) {
blob->at(i) = static_cast<char>(i);
}
const char* category = "+enabled";
TRACE_BLOB_EVENT(category, name, blob->data(), length);
auto expected = fbl::StringPrintf(
"String(index: 1, \"%s\")\n"
"String(index: 2, \"process\")\n"
"KernelObject(koid: <>, type: thread, name: \"initial-thread\", {process: koid(<>)})\n"
"Thread(index: 1, <>)\n"
"String(index: 3, \"%s\")\n",
category, name);
EXPECT_TRUE(fixture_compare_records(expected.c_str()), "record mismatch");
END_TRACE_TEST;
}
bool arg_value_null_ending_test() {
BEGIN_TRACE_TEST;
fixture_initialize_and_start_tracing();
static const char terminated[5] = {'1', '2', '3', '4', '\0'};
static const char unterminated[5] = {'1', '2', '3', '4', '5'};
TRACE_DURATION_BEGIN("+enabled", "name", "key", "literal");
TRACE_DURATION_BEGIN("+enabled", "name", "key", terminated);
TRACE_DURATION_BEGIN("+enabled", "name", "key", unterminated);
fbl::Vector<trace::Record> records;
fixture_stop_and_terminate_tracing();
EXPECT_TRUE(fixture_read_records(&records));
EXPECT_EQ(records.size(), 10);
EXPECT_TRUE(fixture_compare_raw_records(
records, 1, 6,
"String(index: 1, \"+enabled\")\n"
"String(index: 2, \"process\")\n"
"KernelObject(koid: <>, type: thread, name: \"initial-thread\", {process: koid(<>)})\n"
"Thread(index: 1, <>)\n"
"String(index: 3, \"name\")\n"
"String(index: 4, \"key\")\n"));
// The comparison in the fixture_compare_*_records functions does not distinguish between strings
// that match up to the first null character. These checks ensure that the terminal null character
// is not included in the string argument values.
const auto& literal_arg = records[7].GetEvent().arguments[0].value().GetString();
EXPECT_EQ(literal_arg.length(), 7);
EXPECT_STR_EQ(literal_arg.c_str(), "literal");
const auto& terminated_arg = records[8].GetEvent().arguments[0].value().GetString();
EXPECT_EQ(terminated_arg.length(), 4);
EXPECT_STR_EQ(terminated_arg.c_str(), "1234");
const auto& unterminated_arg = records[9].GetEvent().arguments[0].value().GetString();
EXPECT_EQ(unterminated_arg.length(), 5);
EXPECT_STR_EQ(unterminated_arg.c_str(), "12345");
END_TRACE_TEST;
}
} // namespace
BEGIN_TEST_CASE(records)
RUN_TEST(blob_test)
RUN_TEST(blob_macro_test)
RUN_TEST(large_blob_attachment_test)
RUN_TEST(large_blob_attachment_macro_test)
RUN_TEST(large_blob_event_macro_args_test)
RUN_TEST(large_blob_event_macro_small_test)
RUN_TEST(large_blob_event_macro_medium_test)
RUN_TEST(large_blob_event_macro_big_test)
RUN_TEST(large_blob_event_macro_rejected_test)
RUN_TEST(arg_value_null_ending_test)
END_TEST_CASE(records)
| 34.224242 | 100 | 0.658226 | casey |
f62f1a39f186141cf5bcc647a9be7668ac6314ad | 7,801 | cpp | C++ | app/src/main/engine/android/esutil_android.cpp | qige023/learning-opengles3-android | cbe0742637a6eeed41c76756021913cc570cc30e | [
"MIT"
] | 10 | 2015-05-06T17:59:51.000Z | 2019-12-03T10:08:23.000Z | app/src/main/engine/android/esutil_android.cpp | qige023/OpenGL-ES3-Programming-On-Android | cbe0742637a6eeed41c76756021913cc570cc30e | [
"MIT"
] | null | null | null | app/src/main/engine/android/esutil_android.cpp | qige023/OpenGL-ES3-Programming-On-Android | cbe0742637a6eeed41c76756021913cc570cc30e | [
"MIT"
] | null | null | null | //
// This file contains the Android implementation of the windowing functions.
#include <android/log.h>
#include <android/keycodes.h>
#include <android/input.h>
#include <android_native_app_glue.h>
#include <time.h>
#include <iostream>
#include <stdexcept>
using std::cout;
using std::cerr;
using std::endl;
#include "esutil.h"
#include "esfile.h"
#include "android/buf_android.hpp"
///
// Global extern. The application must declare this function
// that runs the application.
//
extern ESScene *esCreateScene(ESContext *esContext);
static int esMain(ESContext *esContext) {
cout << "exec esMain..." << endl;
ESScene *scene = esCreateScene(esContext);
AAssetManager *assetManager = (( ANativeActivity * ) esContext->platformData)->assetManager;
ESFileWrapper::setAssetmanager(assetManager);
if(scene != NULL) {
esContext->scene = scene;
GLboolean result = esCreateWindow(esContext, "Simple VertexShader", 320, 240,
ES_WINDOW_RGB | ES_WINDOW_DEPTH);
if (result != GL_TRUE) {
throw new std::runtime_error("Unable to create EGL native window.");
return false;
}
scene->initScene(esContext);
return TRUE;
}
return FALSE;
}
//////////////////////////////////////////////////////////////////
//
// Private Functions
//
//
///
// GetCurrentTime()
//
static float GetCurrentTime() {
struct timespec clockRealTime;
clock_gettime( CLOCK_MONOTONIC, &clockRealTime);
double curTimeInSeconds = clockRealTime.tv_sec
+ (double) clockRealTime.tv_nsec / 1e9;
return (float) curTimeInSeconds;
}
///
// Android callback for onAppCmd
//
static void HandleCommand(struct android_app *pApp, int32_t cmd) {
ESContext *esContext = (ESContext *) pApp->userData;
switch (cmd) {
case APP_CMD_SAVE_STATE:
cout << "HandleCommand APP_CMD_SAVE_STATE" << endl;
// the OS asked us to save the state of the app
break;
case APP_CMD_INIT_WINDOW:
cout << "HandleCommand APP_CMD_INIT_WINDOW" << endl;
esContext->platformData = (void *) pApp->activity;
esContext->eglNativeDisplay = EGL_DEFAULT_DISPLAY;
esContext->eglNativeWindow = pApp->window;
cout.rdbuf(new outlogbuf());
cerr.rdbuf(new outlogbuf());
// Call the main entry point for the app
if (esMain(esContext) != GL_TRUE) {
exit(0); //@TEMP better way to exit?
}
break;
case APP_CMD_TERM_WINDOW:
cout << "HandleCommand APP_CMD_TERM_WINDOW" << endl;
delete esContext->scene;
cout.rdbuf(0);
cerr.rdbuf(0);
//reset esContext
memset(esContext, 0, sizeof(ESContext));
break;
case APP_CMD_LOST_FOCUS:
cout << "HandleCommand APP_CMD_LOST_FOCUS" << endl;
// if the app lost focus, avoid unnecessary processing (like monitoring the accelerometer)
break;
case APP_CMD_GAINED_FOCUS:
cout << "HandleCommand APP_CMD_GAINED_FOCUS" << endl;
// bring back a certain functionality, like monitoring the accelerometer
break;
}
}
///
// Android callback for onAppInput
//
static int32_t HandleInput(struct android_app* pApp, AInputEvent* event) {
ESContext *esContext = (ESContext *) pApp->userData;
int32_t eventType = AInputEvent_getType(event);
int32_t eventSource = AInputEvent_getSource(event);
int32_t eventAction;
float motionX, motionY;
size_t pointerIndex;
int32_t pointerId ,pointerCount;
switch (eventType) {
case AINPUT_EVENT_TYPE_MOTION:
switch (eventSource) {
case AINPUT_SOURCE_TOUCHSCREEN:
eventAction = AMotionEvent_getAction(event) & AMOTION_EVENT_ACTION_MASK;
pointerIndex = (AMotionEvent_getAction(event) & AMOTION_EVENT_ACTION_POINTER_INDEX_MASK) >> AMOTION_EVENT_ACTION_POINTER_INDEX_SHIFT;
pointerId = AMotionEvent_getPointerId(event, pointerIndex);
motionX = AMotionEvent_getX(event, pointerId);
motionY = AMotionEvent_getY(event, pointerId);
switch (eventAction) {
case AMOTION_EVENT_ACTION_MOVE:
//http://stackoverflow.com/questions/9028357/android-multitouch-second-finger-action-move-ignored
cout << "HandleInput AMOTION_EVENT_ACTION_MOVE" << endl;
pointerCount = AMotionEvent_getPointerCount(event);
for(int i = 0; i < pointerCount; ++i) {
pointerIndex = i;
pointerId = AMotionEvent_getPointerId(event, pointerIndex);
motionX = AMotionEvent_getX(event, pointerId);
motionY = AMotionEvent_getY(event, pointerId);
if(esContext->onMotionListener != NULL) {
esContext->onMotionListener->onMotionMove(pointerId, motionX, motionY);
cout <<"pointerId: "<< pointerId << " X: " << motionX << " Y: " << motionY << endl;
}
}
break;
case AMOTION_EVENT_ACTION_DOWN:
case AMOTION_EVENT_ACTION_POINTER_DOWN:
cout << "HandleInput AMOTION_EVENT_ACTION_POINTER_DOWN" << endl;
if(esContext->onMotionListener != NULL) {
esContext->onMotionListener->onMotionDown(pointerId, motionX, motionY);
cout <<"pointerId: "<< pointerId << " X: " << motionX << " Y: " << motionY << endl;
}
break;
case AMOTION_EVENT_ACTION_UP:
case AMOTION_EVENT_ACTION_POINTER_UP:
cout << "HandleInput AMOTION_EVENT_ACTION_UP" << endl;
if(esContext->onMotionListener != NULL) {
esContext->onMotionListener->onMotionUp(pointerId, motionX, motionY);
cout <<"pointerId: "<< pointerId << " X: " << motionX << " Y: " << motionY << endl;
}
break;
}
break;
case AINPUT_SOURCE_TRACKBALL:
break;
}
return 0;
break;
case AINPUT_EVENT_TYPE_KEY:
switch (AKeyEvent_getKeyCode(event))
case AKEYCODE_BACK:
return 0;
break;
default:
return 0;
}
}
//////////////////////////////////////////////////////////////////
//
// Public Functions
//
///
// android_main()
//
// Main entrypoint for Android application
//
void android_main(struct android_app *pApp) {
ESContext *esContext = new ESContext();
float lastTime;
// Make sure glue isn't stripped.
app_dummy();
// Initialize the context
memset(esContext, 0, sizeof(ESContext));
pApp->userData = esContext;
pApp->onAppCmd = HandleCommand;
//设置输入事件的处理函数,如触摸响应
pApp->onInputEvent = HandleInput;
lastTime = GetCurrentTime();
while (TRUE) {
int ident;
int events;
struct android_poll_source *pSource;
while ((ident = ALooper_pollAll(0, NULL, &events, (void **) &pSource))
>= 0) {
if (pSource != NULL) {
pSource->process(pApp, pSource);
}
if (pApp->destroyRequested != 0) {
return;
}
}
if (esContext->eglNativeWindow == NULL) {
continue;
}
// Call app update function
if (esContext->scene != NULL) {
float curTime = GetCurrentTime();
float deltaTime = (curTime - lastTime);
lastTime = curTime;
esContext->scene->update(esContext, deltaTime);
esContext->scene->render(esContext);
eglSwapBuffers(esContext->eglDisplay, esContext->eglSurface);
}
}
}
| 31.329317 | 145 | 0.596077 | qige023 |
f6313322b0b4bc5f88ab1c363dd727cbfc6bd9c6 | 10,729 | cpp | C++ | src/gridding/gridding.cpp | nio1814/3Dcones | 704b78a0d73b25ab59269e60babbd13876f8563e | [
"BSD-3-Clause"
] | 4 | 2019-09-10T13:46:41.000Z | 2022-03-21T20:19:23.000Z | src/gridding/gridding.cpp | nio1814/3Dcones | 704b78a0d73b25ab59269e60babbd13876f8563e | [
"BSD-3-Clause"
] | 1 | 2017-05-17T07:05:00.000Z | 2017-05-17T07:05:38.000Z | src/gridding/gridding.cpp | nio1814/3Dcones | 704b78a0d73b25ab59269e60babbd13876f8563e | [
"BSD-3-Clause"
] | 2 | 2020-04-12T09:39:29.000Z | 2022-03-21T20:19:25.000Z | /***************************************************************************
Copyright (c) 2014 The Board of Trustees of the Leland Stanford Junior University.
All rights reserved.
Contact: Okai Addy <noaddy@alumni.stanford.edu>
This source code is under a BSD 3-Clause License.
See LICENSE for more information.
To distribute this file, substitute the full license for the above reference.
**************************************************************************/
#include "gridding.h"
extern "C" {
#include "trajectory.h"
#include "numericalrecipes.h"
#include "arrayops.h"
}
#include <cmath>
#include <algorithm>
Gridding::Gridding(const Trajectory *trajectory, float oversamplingRatio, int kernelWidth) :
m_trajectory(trajectory), m_oversamplingFactor(oversamplingRatio),
m_kernelWidth(kernelWidth)
{
float beta = M_PI*sqrt(powf(m_kernelWidth/m_oversamplingFactor,2)*powf(m_oversamplingFactor-0.5,2)-0.8);
int numKernelPoints = 30*m_kernelWidth;
float scale = 1/besseli(0, beta);
float kernelSum = 0;
for(int n=0; n<=numKernelPoints; n++)
{
float x = 2*n/(float)numKernelPoints;
float value = besseli(0, beta*sqrt(1-pow(2*x/m_kernelWidth,2)))*scale;
kernelSum += 2*value;
m_kernelLookupTable.push_back(value);
}
kernelSum -= m_kernelLookupTable[0];
kernelSum /= .5*numKernelPoints*sqrt(m_oversamplingFactor);
scalefloats(m_kernelLookupTable.data(), m_kernelLookupTable.size()-1, 1/kernelSum);
m_deapodization.clear();
scale = -1/(2*beta)*(exp(-beta)-exp(beta));
float minSpatialResolution = INFINITY;
for(int d=0; d<numDimensions(); d++)
minSpatialResolution = std::min(minSpatialResolution, m_trajectory->spatialResolution[d]);
m_coordinateScale = .5*minSpatialResolution/5;
for(int d=0; d<numDimensions(); d++)
{
int dimension = static_cast<int>(std::roundf(m_oversamplingFactor*m_trajectory->imageDimensions[d]));
dimension += dimension%2;
m_gridDimensions.push_back(dimension);
m_normalizedToGridScale.push_back(m_trajectory->spatialResolution[d]/minSpatialResolution*m_gridDimensions[d]);
}
m_deapodization.resize(numDimensions());
for(int d=0; d<m_trajectory->numDimensions; d++)
{
for(int n=0; n<m_gridDimensions[d]; n++)
{
float arg = M_PI*m_kernelWidth*(-m_gridDimensions[d]/2.0f + n)/m_gridDimensions[d];
arg *= arg;
arg -= beta*beta;
float value;
if(arg<0)
value = -1.0f/(2.0f*sqrtf(-arg))*(expf(-sqrtf(-arg))-expf(sqrtf(-arg)));
else
value = sinf(sqrtf(arg))/sqrtf(arg);
value = scale/value;
m_deapodization[d].push_back(value);
}
}
}
std::vector<int> Gridding::imageDimensions()
{
std::vector<int> imageDims;
for(int d=0; d<m_trajectory->numDimensions; d++)
imageDims.push_back(m_trajectory->imageDimensions[d]);
return imageDims;
}
void Gridding::nearestGriddedPoint(const std::vector<float> &ungriddedPoint, std::vector<float> &griddedPoint)
{
for(int d=0; d<numDimensions(); d++)
griddedPoint[d] = roundf(m_normalizedToGridScale[d]*ungriddedPoint[d])/m_normalizedToGridScale[d];
}
float Gridding::lookupKernelValue(float x)
{
float kernelIndexDecimal = fabsf((x)/(float)m_kernelWidth/2*m_kernelLookupTable.size());
int kernelIndex = (int)kernelIndexDecimal;
float secondPointFraction = kernelIndexDecimal - kernelIndex;
return m_kernelLookupTable[kernelIndex]*(1-secondPointFraction) + m_kernelLookupTable[kernelIndex+1]*secondPointFraction;
}
std::vector<std::vector<float> > Gridding::kernelNeighborhood(const std::vector<float> &ungriddedPoint, const std::vector<float> &griddedPoint)
{
int lookupPoints = m_kernelLookupTable.size()-1;
std::vector<std::vector<float> > kernelValues(numDimensions());
for(int d=0; d<numDimensions(); d++)
{
float offset = (griddedPoint[d]-ungriddedPoint[d])*m_normalizedToGridScale[d]-1;
offset += ungriddedPoint[d]>=griddedPoint[d] ? 1 : 0;
for(int n=0; n<m_kernelWidth; n++)
{
int m = n-m_kernelWidth/2+1;
float kernelOffset = m+offset;
float kernelIndexDecimal = fabsf(kernelOffset/(float)m_kernelWidth*2*(lookupPoints-1));
int kernelIndex = (int)kernelIndexDecimal;
float secondPointFraction = kernelIndexDecimal - kernelIndex;
kernelValues[d].push_back(m_kernelLookupTable[kernelIndex]*(1-secondPointFraction) + m_kernelLookupTable[kernelIndex+1]*secondPointFraction);
}
}
return kernelValues;
}
size_t multiToSingleIndex(const std::vector<int> &indices, const std::vector<int>& size)
{
long index = indices[0];
long lowerDimensionSize = size[0];
for(size_t n=1; n<indices.size(); n++)
{
index += indices[n]*lowerDimensionSize;
lowerDimensionSize *= size[n];
}
return index;
}
void singleToMultiIndex(long index, const std::vector<int>& size, std::vector<int>& indices)
{
int lowerDimensions = 1;
for(size_t n=0; n<size.size(); n++)
{
indices[n] = (index/lowerDimensions)%size[n];
lowerDimensions *= size[n];
}
}
MRdata *Gridding::grid(MRdata &inputData, Direction direction)
{
std::vector<float> ungriddedPoint(3);
std::vector<float> griddedPoint(3);
int dimensionStart[3] = {0,0,0};
int dimensionEnd[3] = {1,1,1};
int offset[3] = {0,0,0};
MRdata* ungriddedData;
MRdata* griddedData;
if(direction==FORWARD)
{
ungriddedData = &inputData;
griddedData = new MRdata(m_gridDimensions, numDimensions());
}
else
{
std::vector<int> trajectorySize(2);
trajectorySize[0] = m_trajectory->numReadoutPoints;
trajectorySize[1] = m_trajectory->numReadouts;
ungriddedData = new MRdata(trajectorySize, numDimensions());
griddedData = &inputData;
}
std::vector<int> gridDimensions3 = m_gridDimensions;
if(numDimensions()==2)
gridDimensions3.push_back(1);
std::vector<float> one;
one.push_back(1);
for(size_t n=0; n<ungriddedData->points(); n++)
{
complexFloat ungriddedDataValue;
if(direction==FORWARD)
ungriddedDataValue = ungriddedData->signalValue(n);
else
ungriddedDataValue = 0;
int readoutPoint = n%m_trajectory->numReadoutPoints;
int readout = n/m_trajectory->numReadoutPoints;
float densityCompensation;
trajectoryCoordinates(readoutPoint, readout, m_trajectory, ungriddedPoint.data(), &densityCompensation);
scalefloats(ungriddedPoint.data(), numDimensions(), m_coordinateScale);
ungriddedDataValue *= densityCompensation;
nearestGriddedPoint(ungriddedPoint, griddedPoint);
for(int d=0; d<numDimensions(); d++)
{
const int gridPointCenter = static_cast<int>(std::round((griddedPoint[d]+.5)*m_normalizedToGridScale[d]));
int start = gridPointCenter-m_kernelWidth/2;
start += ungriddedPoint[d]>=griddedPoint[d] ? 1 : 0;
dimensionStart[d] = std::max(0, start);
offset[d] = dimensionStart[d]-start;
dimensionEnd[d] = std::min(start+m_kernelWidth, m_gridDimensions[d]);
}
std::vector<std::vector<float> > kernelValues = kernelNeighborhood(ungriddedPoint, griddedPoint);
std::vector<int> gridIndex(3);
for(int d=numDimensions(); d<3; d++)
kernelValues.push_back(one);
for(int gz=dimensionStart[2]; gz<dimensionEnd[2]; gz++)
{
gridIndex[2] = gz;
float kernelZ = kernelValues[2][gz-dimensionStart[2]+offset[2]];
for(int gy=dimensionStart[1]; gy<dimensionEnd[1]; gy++)
{
gridIndex[1] = gy;
float kernelY = kernelValues[1][gy-dimensionStart[1]+offset[1]];
for(int gx=dimensionStart[0]; gx<dimensionEnd[0]; gx++)
{
gridIndex[0] = gx;
float kernelX = kernelValues[0][gx-dimensionStart[0]+offset[0]];
long griddedDataIndex = multiToSingleIndex(gridIndex, gridDimensions3);
if(direction==FORWARD)
griddedData->addSignalValue(griddedDataIndex, kernelX*kernelY*kernelZ*ungriddedDataValue);
else
ungriddedDataValue += kernelX*kernelY*kernelZ*griddedData->signalValue(griddedDataIndex);
}
}
}
if(direction==INVERSE)
ungriddedData->setSignalValue(n, ungriddedDataValue);
}
if(direction==FORWARD)
return griddedData;
else
return ungriddedData;
}
MRdata *Gridding::conjugatePhaseForward(const MRdata &ungriddedData)
{
std::vector<int> imageDimensions(m_trajectory->imageDimensions, &m_trajectory->imageDimensions[m_trajectory->numDimensions]);
MRdata* griddedData = new MRdata(imageDimensions, numDimensions());
float imageScale = 1.0f/std::sqrt(griddedData->points());
std::vector<int> imageCenter;
std::vector<float> axisScale;
for(int d=0; d<numDimensions(); d++)
{
axisScale.push_back(m_normalizedToGridScale[d]/m_gridDimensions[d]*m_coordinateScale);
imageCenter.push_back(imageDimensions[d]/2);
}
float k[3];
std::vector<int> r(3);
for(size_t u=0; u<ungriddedData.points(); u++)
{
int readoutPoint = u%m_trajectory->numReadoutPoints;
int readout = u/m_trajectory->numReadoutPoints;
float densityCompensation;
trajectoryCoordinates(readoutPoint, readout, m_trajectory, k, &densityCompensation);
complexFloat ungriddedValue = densityCompensation*ungriddedData.signalValue(u);
for(size_t g=0; g<griddedData->points(); g++)
{
singleToMultiIndex(g, imageDimensions, r);
float exponentArgument = 0;
for(int d=0; d<numDimensions(); d++)
{
int p = r[d]-imageCenter[d];
exponentArgument += k[d]*p*axisScale[d];
}
exponentArgument *= static_cast<float>(2.0f * M_PI);
complexFloat griddedValue = complexFloat(std::cos(exponentArgument), std::sin(exponentArgument))*ungriddedValue*imageScale;
griddedData->addSignalValue(g, griddedValue);
}
}
return griddedData;
}
void Gridding::deapodize(MRdata &oversampledImage)
{
complexFloat* signal = oversampledImage.signalPointer();
std::vector<int> gridIndex(numDimensions());
for(size_t n=0; n<oversampledImage.points(); n++)
{
singleToMultiIndex(n, m_gridDimensions, gridIndex);
for(int d=0; d<numDimensions(); d++)
signal[n] *= m_deapodization[d][gridIndex[d]];
}
}
std::vector<MRdata *> Gridding::kSpaceToImage(MRdata &ungriddedData, bool returnGriddedKspace)
{
std::vector<MRdata*> output;
MRdata* griddedKspace = grid(ungriddedData, FORWARD);
MRdata* image;
if(returnGriddedKspace)
{
output.push_back(griddedKspace);
image = new MRdata(griddedKspace);
} else {
image = griddedKspace;
}
image->writeToOctave("temp");
image->fftShift();
image->fft(FFTW_BACKWARD);
image->fftShift();
deapodize(*image);
image->crop(imageDimensions());
output.push_back(image);
return output;
}
MRdata *Gridding::imageToKspace(const MRdata &image)
{
MRdata griddedKspace = image;
griddedKspace.pad(m_gridDimensions);
deapodize(griddedKspace);
griddedKspace.fftShift();
griddedKspace.fft(FFTW_FORWARD);
griddedKspace.fftShift();
MRdata* ungriddedKspace = grid(griddedKspace, INVERSE);
return ungriddedKspace;
}
int Gridding::numDimensions()
{
return m_trajectory->numDimensions;
}
std::vector<int> Gridding::gridDimensions()
{
return m_gridDimensions;
}
| 30.654286 | 144 | 0.721596 | nio1814 |
f6350a75839dd98d27716a02d3fc370e117f9ddf | 1,002 | cpp | C++ | include/h3api/H3AdventureMap/H3MapMine.cpp | Patrulek/H3API | 91f10de37c6b86f3160706c1fdf4792f927e9952 | [
"MIT"
] | 14 | 2020-09-07T21:49:26.000Z | 2021-11-29T18:09:41.000Z | include/h3api/H3AdventureMap/H3MapMine.cpp | Day-of-Reckoning/H3API | a82d3069ec7d5127b13528608d5350d2b80d57be | [
"MIT"
] | 2 | 2021-02-12T15:52:31.000Z | 2021-02-12T16:21:24.000Z | include/h3api/H3AdventureMap/H3MapMine.cpp | Day-of-Reckoning/H3API | a82d3069ec7d5127b13528608d5350d2b80d57be | [
"MIT"
] | 8 | 2021-02-12T15:52:41.000Z | 2022-01-31T15:28:10.000Z | //////////////////////////////////////////////////////////////////////
// //
// Created by RoseKavalier: //
// rosekavalierhc@gmail.com //
// Created or last updated on: 2021-02-02 //
// ***You may use or distribute these files freely //
// so long as this notice remains present.*** //
// //
//////////////////////////////////////////////////////////////////////
#include "h3api/H3AdventureMap/H3MapMine.hpp"
#include "h3api/H3GameData/H3Main.hpp"
namespace h3
{
_H3API_ H3Mine* H3MapitemMine::Get()
{
return Get(H3Main::Get());
}
_H3API_ H3Mine* H3MapitemMine::Get(H3Main* main)
{
return &main->minesLighthouses[index];
}
_H3API_ BOOL H3Mine::IsAbandonned() const
{
return abandoned;
}
} /* namespace h3 */
| 33.4 | 70 | 0.398204 | Patrulek |
f635f72038a3b9c564c0818f258c0b50c0d25c09 | 1,441 | cpp | C++ | EnglishEducator/GameState.cpp | Uno-Bayan/English-Educator | b031086f4fff5e5bcca2212a2b61f9c554f5ca92 | [
"MIT"
] | null | null | null | EnglishEducator/GameState.cpp | Uno-Bayan/English-Educator | b031086f4fff5e5bcca2212a2b61f9c554f5ca92 | [
"MIT"
] | null | null | null | EnglishEducator/GameState.cpp | Uno-Bayan/English-Educator | b031086f4fff5e5bcca2212a2b61f9c554f5ca92 | [
"MIT"
] | null | null | null | #include "stdafx.h"
#include <sstream>
#include "GameState.h"
#include "DEFINITIONS.h"
#include "MainMenuState.h"
#include "GrammarState.h"
#include <iostream>
namespace EnglishEducator
{
GameState::GameState(GameDataRef data) : _data(data)
{
_data->window.setFramerateLimit(30);
}
void GameState::Init()
{
_data->assets.LoadTexture("Game Background", GAME_BACKGROUND_FILEPATH);
_background.setTexture(_data->assets.GetTexture("Game Background"));
startMenu = new GamePlayStartMenu(_data);
}
void GameState::HandleInput()
{
sf::Event event;
while (_data->window.pollEvent(event))
{
if (sf::Event::Closed == event.type)
{
_data->window.close();
}
if (_data->input.IsSpriteClicked(startMenu->GetGrammarSprite(),
sf::Mouse::Left, _data->window))
{
_data->machine.AddState(StateRef(new GrammarState(_data)), true);
}
if (_data->input.IsSpriteClicked(startMenu->GetVocabularySprite(),
sf::Mouse::Left, _data->window))
{
_data->window.close();
}
if (_data->input.IsSpriteClicked(startMenu->GetOlympiadSprite(),
sf::Mouse::Left, _data->window))
{
_data->window.close();
}
}
}
void GameState::Update(float dt)
{
}
void GameState::Draw(float dt)
{
_data->window.clear();
_data->window.draw(_background);
startMenu->Draw();
_data->window.display();
}
} | 19.739726 | 74 | 0.639833 | Uno-Bayan |
f63801e52141d3566d949e3eabc9309d3d2ec863 | 987 | hpp | C++ | src/point.hpp | xyl1t/Cidr | 48ee260ec4871eddb795ccc0f3aa1fddfc2cd0aa | [
"MIT"
] | 6 | 2020-09-10T17:44:49.000Z | 2021-03-14T16:41:11.000Z | src/point.hpp | xyl1t/Cidr | 48ee260ec4871eddb795ccc0f3aa1fddfc2cd0aa | [
"MIT"
] | 1 | 2021-07-22T20:25:00.000Z | 2021-11-27T19:44:35.000Z | src/point.hpp | xyl1t/Cidr | 48ee260ec4871eddb795ccc0f3aa1fddfc2cd0aa | [
"MIT"
] | null | null | null | /********************************
* Project: Cidr *
* File: point.hpp *
* Date: 12.9.2020 *
********************************/
#ifndef CIDR_POINT_HPP
#define CIDR_POINT_HPP
#include "tensorMath.hpp"
// TODO: ADD CONSTURCTORS!
// In order to keep the code "consice" I just derive the point classes from vectors
// But Since points are not really vectors they shouldn't have length functions so I hide them
namespace cdr {
struct FPoint;
struct Point : public tem::ivec2 {
public:
Point();
Point(int x, int y);
operator cdr::FPoint() const;
private:
using tem::ivec2::length;
using tem::ivec2::setLength;
using tem::ivec2::addLength;
using tem::ivec2::subLength;
};
struct FPoint : public tem::vec2 {
public:
FPoint();
FPoint(float x, float y);
operator cdr::Point() const;
private:
using tem::vec2::length;
using tem::vec2::setLength;
using tem::vec2::addLength;
using tem::vec2::subLength;
};
}
#endif | 21.456522 | 94 | 0.616008 | xyl1t |
f63979213498b360b480d39e0eb915fec6641e5c | 4,595 | hpp | C++ | Kuplung/kuplung/objects/ObjectsManager.hpp | supudo/Kuplung | f0e11934fde0675fa531e6dc263bedcc20a5ea1a | [
"Unlicense"
] | 14 | 2017-02-17T17:12:40.000Z | 2021-12-22T01:55:06.000Z | Kuplung/kuplung/objects/ObjectsManager.hpp | supudo/Kuplung | f0e11934fde0675fa531e6dc263bedcc20a5ea1a | [
"Unlicense"
] | null | null | null | Kuplung/kuplung/objects/ObjectsManager.hpp | supudo/Kuplung | f0e11934fde0675fa531e6dc263bedcc20a5ea1a | [
"Unlicense"
] | 1 | 2019-10-15T08:10:10.000Z | 2019-10-15T08:10:10.000Z | //
// ObjectsManager.hpp
// Kuplung
//
// Created by Sergey Petrov on 12/3/15.
// Copyright © 2015 supudo.net. All rights reserved.
//
#ifndef ObjectsManager_hpp
#define ObjectsManager_hpp
#include <functional>
#include <map>
#include <string>
#include <vector>
#include <glm/glm.hpp>
#include "kuplung/objects/ObjectDefinitions.h"
#include "kuplung/meshes/helpers/Camera.hpp"
#include "kuplung/meshes/helpers/CameraModel.hpp"
#include "kuplung/meshes/helpers/Light.hpp"
#include "kuplung/meshes/helpers/AxisHelpers.hpp"
#include "kuplung/meshes/helpers/AxisLabels.hpp"
#include "kuplung/meshes/helpers/MiniAxis.hpp"
#include "kuplung/meshes/helpers/Skybox.hpp"
#include "kuplung/meshes/helpers/WorldGrid.hpp"
#include "kuplung/meshes/helpers/Grid2D.hpp"
#include "kuplung/meshes/artefacts/Terrain.hpp"
#include "kuplung/meshes/artefacts/Spaceship.hpp"
#include "kuplung/utilities/parsers/FileModelManager.hpp"
typedef enum GeometryEditMode {
GeometryEditMode_Vertex,
GeometryEditMode_Line,
GeometryEditMode_Face
} GeometryEditMode;
class ObjectsManager {
public:
~ObjectsManager();
void init(const std::function<void(float)>& doProgress,
const std::function<void()>& addTerrain,
const std::function<void()>& addSpaceship);
void loadSystemModels(const std::unique_ptr<FileModelManager> &fileParser);
void render();
void renderSkybox();
void resetPropertiesSystem();
void resetSettings();
void generateTerrain();
void generateSpaceship();
void clearAllLights();
void initCamera();
void initCameraModel();
void initGrid();
void initGrid2D();
void initAxisSystem();
void initAxisHelpers();
void initAxisLabels();
void initSkybox();
void initTerrain();
void initSpaceship();
void addLight(const LightSourceType type, std::string const& title = "", std::string const& description = "");
std::vector<Light*> lightSources;
std::unique_ptr<Camera> camera;
std::unique_ptr<CameraModel> cameraModel;
std::unique_ptr<WorldGrid> grid;
std::unique_ptr<Grid2D> grid2d;
std::unique_ptr<MiniAxis> axisSystem;
std::unique_ptr<Skybox> skybox;
std::unique_ptr<AxisHelpers> axisHelpers_xMinus, axisHelpers_xPlus, axisHelpers_yMinus, axisHelpers_yPlus, axisHelpers_zMinus, axisHelpers_zPlus;
std::unique_ptr<AxisLabels> axisLabels;
std::unique_ptr<Terrain> terrain;
std::unique_ptr<Spaceship> spaceship;
glm::mat4 matrixProjection;
float Setting_FOV = 45.0;
float Setting_OutlineThickness = 1.01f;
float Setting_RatioWidth = 4.0f, Setting_RatioHeight = 3.0f;
float Setting_PlaneClose = 0.1f, Setting_PlaneFar = 100.0f;
int Setting_GridSize = 30, Setting_Skybox = 0;
glm::vec4 Setting_OutlineColor;
glm::vec3 Setting_UIAmbientLight;
bool Setting_FixedGridWorld = true, Setting_OutlineColorPickerOpen = false, Setting_ShowAxisHelpers = true;
bool Setting_UseWorldGrid = false;
bool Settings_ShowZAxis = true;
bool Setting_DeferredTestMode, Setting_DeferredTestLights, Setting_DeferredRandomizeLightPositions;
int Setting_LightingPass_DrawMode, Setting_DeferredTestLightsNumber;
float Setting_DeferredAmbientStrength;
float Setting_GammaCoeficient;
ViewModelSkin viewModelSkin;
glm::vec3 SolidLight_Direction;
glm::vec3 SolidLight_MaterialColor, SolidLight_Ambient, SolidLight_Diffuse, SolidLight_Specular;
float SolidLight_Ambient_Strength, SolidLight_Diffuse_Strength, SolidLight_Specular_Strength;
bool SolidLight_MaterialColor_ColorPicker, SolidLight_Ambient_ColorPicker, SolidLight_Diffuse_ColorPicker, SolidLight_Specular_ColorPicker;
bool Setting_ShowTerrain, Setting_TerrainModel, Setting_TerrainAnimateX, Setting_TerrainAnimateY;
std::string heightmapImage;
int Setting_TerrainWidth = 100, Setting_TerrainHeight = 100;
bool Setting_ShowSpaceship, Setting_GenerateSpaceship, Setting_Cuda_ShowOceanFFT;
bool Setting_VertexSphere_Visible, Setting_VertexSphere_ColorPickerOpen;
bool Setting_VertexSphere_IsSphere, Setting_VertexSphere_ShowWireframes;
float Setting_VertexSphere_Radius;
int Setting_VertexSphere_Segments;
glm::vec4 Setting_VertexSphere_Color;
int VertexEditorModeID;
glm::vec3 VertexEditorMode;
GeometryEditMode Setting_GeometryEditMode;
std::map<std::string, MeshModel> systemModels;
bool Setting_Rendering_Depth, Setting_DebugShadowTexture;
std::string shaderSourceVertex, shaderSourceTCS, shaderSourceTES, shaderSourceGeometry, shaderSourceFragment;
private:
std::function<void(float)> funcProgress;
std::function<void()> funcAddTerrain;
std::function<void()> funcAddSpaceship;
};
#endif /* ObjectsManager_hpp */
| 36.181102 | 146 | 0.796953 | supudo |
f643a2479b7f181bdcc0a0eb0d546f15490fe208 | 24,468 | cpp | C++ | src/platforms/windows/direct2d.cpp | LinkDoyle/YuKi | 22c7ac495e48985e0f21574b327ee687563a88e5 | [
"Apache-2.0"
] | null | null | null | src/platforms/windows/direct2d.cpp | LinkDoyle/YuKi | 22c7ac495e48985e0f21574b327ee687563a88e5 | [
"Apache-2.0"
] | null | null | null | src/platforms/windows/direct2d.cpp | LinkDoyle/YuKi | 22c7ac495e48985e0f21574b327ee687563a88e5 | [
"Apache-2.0"
] | null | null | null | #include "direct2d.h"
#include <algorithm>
#include <cassert>
#include <exception>
#include <string_view>
#include <utility>
#undef max
#undef min
#pragma comment(lib, "d2d1")
#pragma comment(lib, "d3d11")
#pragma comment(lib, "dwrite.lib")
#pragma comment(lib, "dxguid.lib")
namespace yuki {
namespace platforms {
namespace windows {
using Microsoft::WRL::ComPtr;
template <typename R, typename S>
static constexpr R ConvertTo(S s) {
return static_cast<R>(s);
}
/*******************************************************************************
* class ComException
******************************************************************************/
struct ComException : std::exception {
HRESULT const hr;
explicit ComException(HRESULT const value) : hr(value) {}
};
inline void ThrowIfFailed(HRESULT const hr) {
if (S_OK != hr) throw ComException(hr);
}
inline void WarnIfFailed(HRESULT const hr) {
if (S_OK != hr) throw ComException(hr);
}
/*******************************************************************************
* Direct2D Device Dependent Resource
******************************************************************************/
class D2DDeviceDependentRes {
public:
D2DDeviceDependentRes() = default;
D2DDeviceDependentRes(const D2DDeviceDependentRes&) = default;
D2DDeviceDependentRes(D2DDeviceDependentRes&&) = default;
D2DDeviceDependentRes& operator=(const D2DDeviceDependentRes&) = default;
D2DDeviceDependentRes& operator=(D2DDeviceDependentRes&&) = default;
virtual ~D2DDeviceDependentRes() = default;
virtual void recreate() {}
};
/*******************************************************************************
* class D2DBrush
******************************************************************************/
class D2DBrush : public D2DDeviceDependentRes {
public:
D2DBrush() = default;
virtual ComPtr<ID2D1Brush> getD2DBrush() const = 0;
};
/*******************************************************************************
* class D2DSoildColorBrush
******************************************************************************/
class D2DSolidColorBrush : public D2DBrush {
public:
explicit D2DSolidColorBrush(ComPtr<ID2D1SolidColorBrush> brush)
: brush_(std::move(brush)) {}
ComPtr<ID2D1Brush> getD2DBrush() const override { return brush_; }
private:
ComPtr<ID2D1SolidColorBrush> brush_;
};
class D2DBitmap : public Bitmap, public D2DDeviceDependentRes {
public:
D2DBitmap() = default;
explicit D2DBitmap(ComPtr<ID2D1Bitmap> bitmap) : bitmap_(std::move(bitmap)) {}
D2DBitmap(const D2DBitmap&) = default;
D2DBitmap(D2DBitmap&&) = default;
D2DBitmap& operator=(const D2DBitmap&) = default;
D2DBitmap& operator=(D2DBitmap&&) = default;
virtual ~D2DBitmap() = default;
virtual ComPtr<ID2D1Bitmap> getD2DBitmap() const { return bitmap_; }
private:
ComPtr<ID2D1Bitmap> bitmap_;
};
/*******************************************************************************
* DirectWrite TextFormat Wrapper
******************************************************************************/
template <>
constexpr DWRITE_TEXT_ALIGNMENT ConvertTo(TextAlignment textAlignment) {
DWRITE_TEXT_ALIGNMENT result = DWRITE_TEXT_ALIGNMENT_LEADING;
switch (textAlignment) {
case TextAlignment::Leading:
result = DWRITE_TEXT_ALIGNMENT_LEADING;
break;
case TextAlignment::Trailing:
result = DWRITE_TEXT_ALIGNMENT_TRAILING;
break;
case TextAlignment::Center:
result = DWRITE_TEXT_ALIGNMENT_CENTER;
break;
case TextAlignment::Justified:
result = DWRITE_TEXT_ALIGNMENT_JUSTIFIED;
break;
}
return result;
}
template <>
constexpr TextAlignment ConvertTo(DWRITE_TEXT_ALIGNMENT textAlignment) {
TextAlignment result = TextAlignment::Leading;
switch (textAlignment) {
case DWRITE_TEXT_ALIGNMENT_LEADING:
result = TextAlignment::Leading;
break;
case DWRITE_TEXT_ALIGNMENT_TRAILING:
result = TextAlignment::Trailing;
break;
case DWRITE_TEXT_ALIGNMENT_CENTER:
result = TextAlignment::Center;
break;
case DWRITE_TEXT_ALIGNMENT_JUSTIFIED:
result = TextAlignment::Justified;
break;
}
return result;
}
template <>
constexpr DWRITE_PARAGRAPH_ALIGNMENT ConvertTo(
ParagraphAlignment paragraphAlignment) {
DWRITE_PARAGRAPH_ALIGNMENT result = DWRITE_PARAGRAPH_ALIGNMENT_NEAR;
switch (paragraphAlignment) {
case ParagraphAlignment::Near:
result = DWRITE_PARAGRAPH_ALIGNMENT_NEAR;
break;
case ParagraphAlignment::Far:
result = DWRITE_PARAGRAPH_ALIGNMENT_FAR;
break;
case ParagraphAlignment::Center:
result = DWRITE_PARAGRAPH_ALIGNMENT_CENTER;
break;
}
return result;
}
template <>
constexpr ParagraphAlignment ConvertTo(
DWRITE_PARAGRAPH_ALIGNMENT paragraphAlignment) {
ParagraphAlignment result = ParagraphAlignment::Near;
switch (paragraphAlignment) {
case DWRITE_PARAGRAPH_ALIGNMENT_NEAR:
result = ParagraphAlignment::Near;
break;
case DWRITE_PARAGRAPH_ALIGNMENT_FAR:
result = ParagraphAlignment::Far;
break;
case DWRITE_PARAGRAPH_ALIGNMENT_CENTER:
result = ParagraphAlignment::Center;
break;
}
return result;
}
template <>
constexpr DWRITE_WORD_WRAPPING ConvertTo(WordWrapping paragraphAlignment) {
DWRITE_WORD_WRAPPING result = DWRITE_WORD_WRAPPING_WRAP;
switch (paragraphAlignment) {
case WordWrapping::Wrap:
result = DWRITE_WORD_WRAPPING_WRAP;
break;
case WordWrapping::NoWrap:
result = DWRITE_WORD_WRAPPING_NO_WRAP;
break;
case WordWrapping::EmergencyBreak:
result = DWRITE_WORD_WRAPPING_EMERGENCY_BREAK;
break;
case WordWrapping::WholeWord:
result = DWRITE_WORD_WRAPPING_WHOLE_WORD;
break;
case WordWrapping::Character:
result = DWRITE_WORD_WRAPPING_CHARACTER;
break;
}
return result;
}
template <>
constexpr WordWrapping ConvertTo(DWRITE_WORD_WRAPPING paragraphAlignment) {
WordWrapping result = WordWrapping::Wrap;
switch (paragraphAlignment) {
case DWRITE_WORD_WRAPPING_WRAP:
result = WordWrapping::Wrap;
break;
case DWRITE_WORD_WRAPPING_NO_WRAP:
result = WordWrapping::NoWrap;
break;
case DWRITE_WORD_WRAPPING_EMERGENCY_BREAK:
result = WordWrapping::EmergencyBreak;
break;
case DWRITE_WORD_WRAPPING_WHOLE_WORD:
result = WordWrapping::WholeWord;
break;
case DWRITE_WORD_WRAPPING_CHARACTER:
result = WordWrapping::Character;
break;
}
return result;
}
template <>
constexpr FontWeight ConvertTo(DWRITE_FONT_WEIGHT fontWeight) {
return static_cast<FontWeight>(fontWeight);
}
template <>
constexpr DWRITE_FONT_WEIGHT ConvertTo(FontWeight fontWeight) {
return static_cast<DWRITE_FONT_WEIGHT>(fontWeight);
}
class DWriteTextFormat : public TextFormat {
public:
explicit DWriteTextFormat(ComPtr<IDWriteTextFormat> textFormat)
: textFormat_(std::move(textFormat)) {}
ComPtr<IDWriteTextFormat> getTextFormat() const { return textFormat_; }
String getFontFamilyName() const override {
auto length = textFormat_->GetFontFamilyNameLength();
auto buffer = std::make_unique<WCHAR[]>(length);
WarnIfFailed(textFormat_->GetFontFamilyName(buffer.get(), length));
std::wstring_view wstringView(buffer.get(), length);
return String(wstringView.begin(), wstringView.end());
}
float getSize() const override { return textFormat_->GetFontSize(); }
void setTextAlignment(TextAlignment textAlignment) override {
WarnIfFailed(textFormat_->SetTextAlignment(
ConvertTo<DWRITE_TEXT_ALIGNMENT>(textAlignment)));
}
TextAlignment getTextAlignment() const override {
return ConvertTo<TextAlignment>(textFormat_->GetTextAlignment());
}
void setParagraphAlignment(ParagraphAlignment paragraphAlignment) override {
WarnIfFailed(textFormat_->SetParagraphAlignment(
ConvertTo<DWRITE_PARAGRAPH_ALIGNMENT>(paragraphAlignment)));
}
ParagraphAlignment getParagraphAlignment() const override {
return ConvertTo<ParagraphAlignment>(textFormat_->GetParagraphAlignment());
}
void setWordWrapping(WordWrapping wordWrapping) override {
WarnIfFailed(textFormat_->SetWordWrapping(
ConvertTo<DWRITE_WORD_WRAPPING>(wordWrapping)));
}
WordWrapping getWordWrapping() const override {
return ConvertTo<WordWrapping>(textFormat_->GetWordWrapping());
}
int getWeight() const override { return textFormat_->GetFontWeight(); }
private:
ComPtr<IDWriteTextFormat> textFormat_;
};
/*******************************************************************************
* DirectX Type Helper Functions
******************************************************************************/
static float ConvertDipsToPixels(float dips, float dpi) {
static const auto DIPS_PER_INCH = 96.0f;
return floorf(dips * dpi / DIPS_PER_INCH + 0.5f);
}
static constexpr D2D1_POINT_2F ToD2DPointF(const PointF& point) noexcept {
return D2D1_POINT_2F{point.x(), point.y()};
}
static constexpr D2D1_RECT_F ToD2DRectF(const RectF& rect) noexcept {
return D2D1_RECT_F{rect.left(), rect.top(), rect.right(), rect.bottom()};
}
static constexpr D2D1_RECT_F ToD2DRectF(const RectF* rect) noexcept {
if (rect == nullptr) return D2D1_RECT_F{};
return D2D1_RECT_F{rect->left(), rect->top(), rect->right(), rect->bottom()};
}
static constexpr D2D1_ROUNDED_RECT ToD2DRoundedRectF(
const RoundedRectF& rect) noexcept {
return D2D1_ROUNDED_RECT{
{rect.left(), rect.top(), rect.right(), rect.bottom()},
rect.radiusX(),
rect.radiusY()};
}
static constexpr D2D1_ELLIPSE ToD2DEllipse(const EllipseF& ellipse) {
return D2D1_ELLIPSE{
{ellipse.x(), ellipse.y()}, ellipse.radiusX(), ellipse.radiusY()};
}
static constexpr D2D1_ELLIPSE ToD2DEllipse(const CircleF& circle) {
return D2D1_ELLIPSE{
{circle.x(), circle.y()}, circle.radius(), circle.radius()};
}
static constexpr D2D1_COLOR_F ToD2DColorF(const ColorF& color) noexcept {
return D2D1_COLOR_F{color.red(), color.green(), color.blue(), color.alpha()};
}
static ComPtr<ID2D1StrokeStyle> ToD2DStrokeStyle(
const StrokeStyle* strokeStyle) {
return ComPtr<ID2D1StrokeStyle>();
}
static ComPtr<ID2D1Bitmap1> ToD2DBitmap(const Bitmap* bitmap) {
return ComPtr<ID2D1Bitmap1>();
}
static ComPtr<IDWriteTextFormat> ToWriteTextFormat(const TextFormat* font) {
return dynamic_cast<const DWriteTextFormat*>(font)->getTextFormat();
}
/*******************************************************************************
* class DirectXRes
******************************************************************************/
ComPtr<ID3D11Device> DirectXRes::d3device_;
ComPtr<IDXGIDevice> DirectXRes::dxdevice_;
ComPtr<IDXGIAdapter> DirectXRes::adapter_;
ComPtr<IDXGIFactory2> DirectXRes::factory_;
ComPtr<ID2D1Factory1> DirectXRes::d2dFactory_;
ComPtr<ID2D1Device> DirectXRes::d2dDevice_;
ComPtr<IWICImagingFactory> DirectXRes::imagingFactory_;
ComPtr<IDWriteFactory1> DirectXRes::dWriteFactory_;
void DirectXRes::init() { createDeviceResources(); }
void DirectXRes::releaseAll() {
d3device_.Reset();
dxdevice_.Reset();
adapter_.Reset();
factory_.Reset();
d2dFactory_.Reset();
d2dDevice_.Reset();
}
void DirectXRes::handleDeviceLost() { throw; }
inline ComPtr<IDXGIFactory2> DirectXRes::getDXGIFactory() {
assert(factory_);
return factory_;
}
inline ComPtr<ID3D11Device> DirectXRes::getD3D11Device() {
assert(d3device_);
return d3device_;
}
inline ComPtr<ID2D1Factory1> DirectXRes::getD2DFactory() {
assert(d2dFactory_);
return d2dFactory_;
}
inline ComPtr<ID2D1Device> DirectXRes::getD2DDevice() {
assert(d2dDevice_);
return d2dDevice_;
}
inline ComPtr<IDWriteFactory1> DirectXRes::getDWriteFactory() {
if (dWriteFactory_ == nullptr) {
DWriteCreateFactory(
DWRITE_FACTORY_TYPE_SHARED, __uuidof(dWriteFactory_),
reinterpret_cast<IUnknown**>(dWriteFactory_.GetAddressOf()));
}
return dWriteFactory_;
}
ComPtr<IWICImagingFactory> DirectXRes::getImagingFactory() {
if (imagingFactory_ == nullptr) {
ThrowIfFailed(CoCreateInstance(CLSID_WICImagingFactory, nullptr,
CLSCTX_INPROC_SERVER,
IID_PPV_ARGS(&imagingFactory_)));
}
return imagingFactory_;
}
std::unique_ptr<D2DContext2D> DirectXRes::createContextFromHWnd(HWND hWnd) {
return std::make_unique<D2DContext2D>(hWnd);
}
void DirectXRes::createDeviceResources() {
auto hr = createD3D11Device(D3D_DRIVER_TYPE_HARDWARE, d3device_);
if (DXGI_ERROR_UNSUPPORTED == hr) {
hr = createD3D11Device(D3D_DRIVER_TYPE_WARP, d3device_);
}
ThrowIfFailed(hr);
ThrowIfFailed(d3device_.As(&dxdevice_));
ThrowIfFailed(dxdevice_->GetAdapter(adapter_.GetAddressOf()));
ThrowIfFailed(adapter_->GetParent(IID_PPV_ARGS(&factory_)));
D2D1_FACTORY_OPTIONS options = {};
#ifdef _DEBUG
options.debugLevel = D2D1_DEBUG_LEVEL_INFORMATION;
#endif
ThrowIfFailed(D2D1CreateFactory(D2D1_FACTORY_TYPE_SINGLE_THREADED, options,
d2dFactory_.GetAddressOf()));
ThrowIfFailed(
d2dFactory_->CreateDevice(dxdevice_.Get(), d2dDevice_.GetAddressOf()));
}
inline HRESULT DirectXRes::createD3D11Device(D3D_DRIVER_TYPE const type,
ComPtr<ID3D11Device>& device) {
UINT flags = D3D11_CREATE_DEVICE_BGRA_SUPPORT;
#ifdef _DEBUG
flags |= D3D11_CREATE_DEVICE_DEBUG;
#endif
return D3D11CreateDevice(nullptr, type, nullptr, flags, nullptr, 0,
D3D11_SDK_VERSION, device.GetAddressOf(), nullptr,
nullptr);
}
/*******************************************************************************
* class D2DBrushAllocation
******************************************************************************/
D2DBrushAllocation::D2DBrushAllocation() : soildColorBrushcache_(64) {}
ComPtr<ID2D1Brush> D2DBrushAllocation::getD2DBrush(
ID2D1DeviceContext* d2dContext, const Brush* brush) {
if (brush == nullptr) {
return nullptr;
}
switch (brush->style()) {
case BrushStyle::SolidColor: {
const auto solidColorBrush = static_cast<const SolidColorBrush*>(brush);
ColorF color = solidColorBrush->getColor();
if (auto result = soildColorBrushcache_.get(color)) {
return result.get();
} else {
ComPtr<ID2D1SolidColorBrush> d2dBrush;
ThrowIfFailed(d2dContext->CreateSolidColorBrush(
ToD2DColorF(solidColorBrush->getColor()), &d2dBrush));
soildColorBrushcache_.insert(color, d2dBrush);
return d2dBrush;
}
}
default:
return nullptr;
}
}
void D2DBrushAllocation::reset() { soildColorBrushcache_.clear(); }
/*******************************************************************************
* class D2DContext
******************************************************************************/
void D2DContext2D::resetSize(SizeF size) {
brushAllocation_->reset();
using namespace Microsoft::WRL;
const int DOUBLE_BUFFER_COUNT = 2;
context_->SetTarget(nullptr);
bitmap_.Reset();
UINT width = std::max(lround(size.width()), 8L);
UINT height = std::max(lround(size.height()), 8L);
auto hr = swapChain_->ResizeBuffers(DOUBLE_BUFFER_COUNT, width, height,
DXGI_FORMAT_B8G8R8A8_UNORM, 0);
if (hr == DXGI_ERROR_DEVICE_REMOVED || hr == DXGI_ERROR_DEVICE_RESET) {
handleDeviceLost();
return;
}
ThrowIfFailed(hr);
createDeviceSwapChainBitmap();
}
D2DContext2D::D2DContext2D(HWND hWnd)
: brushAllocation_(new D2DBrushAllocation) {
createDeviceContextFromHWnd(hWnd);
createDeviceSwapChainBitmap();
}
inline void D2DContext2D::begin() {}
inline bool D2DContext2D::flush() {
ThrowIfFailed(context_->Flush());
return true;
}
inline bool D2DContext2D::end() { return true; }
void D2DContext2D::setTransform(const Transform2D& transform) {}
void D2DContext2D::resetTransform() {}
Transform2D D2DContext2D::getTransform() const {
return Transform2D::identity();
}
void D2DContext2D::clear(Color color) {}
void D2DContext2D::clear(const ColorF& color) {
context_->Clear(ToD2DColorF(color));
}
void D2DContext2D::drawCircle(const CircleF& circle, const Brush* brush,
float strokeWidth, StrokeStyle* strokeStyle) {
auto d2dBrush = brushAllocation_->getD2DBrush(context_.Get(), brush);
context_->DrawEllipse(ToD2DEllipse(circle), d2dBrush.Get(), strokeWidth,
ToD2DStrokeStyle(strokeStyle).Get());
}
void D2DContext2D::drawEllipse(const EllipseF& ellipse, const Brush* brush,
float strokeWidth, StrokeStyle* strokeStyle) {
auto d2dBrush = brushAllocation_->getD2DBrush(context_.Get(), brush);
context_->DrawEllipse(ToD2DEllipse(ellipse), d2dBrush.Get(), strokeWidth,
ToD2DStrokeStyle(strokeStyle).Get());
}
void D2DContext2D::drawLine(const LineF& line, const Brush* brush,
float strokeWidth, StrokeStyle* strokeStyle) {
auto d2dBrush = brushAllocation_->getD2DBrush(context_.Get(), brush);
context_->DrawLine(ToD2DPointF(line.p1()), ToD2DPointF(line.p2()),
d2dBrush.Get(), strokeWidth,
ToD2DStrokeStyle(strokeStyle).Get());
}
void D2DContext2D::drawRect(const RectF& rect, const Brush* brush,
float strokeWidth, StrokeStyle* strokeStyle) {
auto d2dBrush = brushAllocation_->getD2DBrush(context_.Get(), brush);
context_->DrawRectangle(ToD2DRectF(rect), d2dBrush.Get(), strokeWidth,
ToD2DStrokeStyle(strokeStyle).Get());
}
void D2DContext2D::drawRoundedRect(const RoundedRectF& rect, const Brush* brush,
float strokeWidth,
StrokeStyle* strokeStyle) {
auto d2dBrush = brushAllocation_->getD2DBrush(context_.Get(), brush);
context_->DrawRoundedRectangle(ToD2DRoundedRectF(rect), d2dBrush.Get(),
strokeWidth,
ToD2DStrokeStyle(strokeStyle).Get());
}
void D2DContext2D::fillCircle(const CircleF& circle, const Brush* brush) {
auto d2dBrush = brushAllocation_->getD2DBrush(context_.Get(), brush);
context_->FillEllipse(ToD2DEllipse(circle), d2dBrush.Get());
}
void D2DContext2D::fillEllipse(const EllipseF& ellipse, const Brush* brush) {
auto d2dBrush = brushAllocation_->getD2DBrush(context_.Get(), brush);
context_->FillEllipse(ToD2DEllipse(ellipse), d2dBrush.Get());
}
void D2DContext2D::fillRect(const RectF& rect, const Brush* brush) {
auto d2dBrush = brushAllocation_->getD2DBrush(context_.Get(), brush);
context_->FillRectangle(ToD2DRectF(rect), d2dBrush.Get());
}
void D2DContext2D::fillRoundedRect(const RoundedRectF& rect,
const Brush* brush) {
auto d2dBrush = brushAllocation_->getD2DBrush(context_.Get(), brush);
context_->FillRoundedRectangle(ToD2DRoundedRectF(rect), d2dBrush.Get());
}
void D2DContext2D::pushClip(const RectF& rect) {
context_->PushAxisAlignedClip(ToD2DRectF(rect),
D2D1_ANTIALIAS_MODE_PER_PRIMITIVE);
}
void D2DContext2D::popClip() { context_->PopAxisAlignedClip(); }
void D2DContext2D::setDpi(float dpiX, float dpiY) {
context_->SetDpi(dpiX, dpiY);
}
void D2DContext2D::getDpi(float* dpiX, float* dpiY) {
context_->GetDpi(dpiX, dpiY);
}
void D2DContext2D::drawBitmap(const Bitmap* bitmap,
const RectF* destionationRectangle, float opacity,
BitmapInterpolationMode mode,
const RectF* sourceRectangle) {
if (destionationRectangle == nullptr) {
context_->DrawBitmap(ToD2DBitmap(bitmap).Get());
} else {
D2D1_BITMAP_INTERPOLATION_MODE interpolationMode;
switch (mode) {
case BitmapInterpolationMode::Linear:
interpolationMode = D2D1_BITMAP_INTERPOLATION_MODE_LINEAR;
break;
case BitmapInterpolationMode::NearestNeighbor:
interpolationMode = D2D1_BITMAP_INTERPOLATION_MODE_NEAREST_NEIGHBOR;
break;
default:
interpolationMode = D2D1_BITMAP_INTERPOLATION_MODE_LINEAR;
break;
}
if (sourceRectangle == nullptr) {
context_->DrawBitmap(ToD2DBitmap(bitmap).Get(),
ToD2DRectF(*destionationRectangle), opacity,
interpolationMode);
} else {
context_->DrawBitmap(ToD2DBitmap(bitmap).Get(),
ToD2DRectF(*destionationRectangle), opacity,
interpolationMode, ToD2DRectF(sourceRectangle));
}
}
}
void D2DContext2D::drawText(const String& text, const TextFormat* font,
const RectF& rect, const Brush* brush) {
auto d2dBrush = brushAllocation_->getD2DBrush(context_.Get(), brush);
context_->DrawTextW(text.c_str(), text.size(), ToWriteTextFormat(font).Get(),
ToD2DRectF(rect), d2dBrush.Get());
}
std::unique_ptr<Bitmap> D2DContext2D::loadBitmap(const String& filename) {
auto factory = DirectXRes::getImagingFactory();
ComPtr<IWICBitmapDecoder> decoder;
ThrowIfFailed(factory->CreateDecoderFromFilename(
filename.c_str(), nullptr, GENERIC_READ, WICDecodeMetadataCacheOnLoad,
&decoder));
ComPtr<IWICBitmapFrameDecode> source;
ThrowIfFailed(decoder->GetFrame(0, &source));
ComPtr<IWICFormatConverter> converter;
factory->CreateFormatConverter(&converter);
ThrowIfFailed(converter->Initialize(
source.Get(), GUID_WICPixelFormat32bppPBGRA, WICBitmapDitherTypeNone,
nullptr, 0.f, WICBitmapPaletteTypeMedianCut));
ComPtr<ID2D1Bitmap> bitmap;
ThrowIfFailed(context_->CreateBitmapFromWicBitmap(source.Get(), &bitmap));
return std::make_unique<D2DBitmap>(std::move(bitmap));
}
void D2DContext2D::createDeviceContextFromHWnd(HWND hWnd) {
DXGI_SWAP_CHAIN_DESC1 props_dscd = {};
props_dscd.Format = DXGI_FORMAT_B8G8R8A8_UNORM;
props_dscd.SampleDesc.Count = 1;
props_dscd.BufferUsage = DXGI_USAGE_RENDER_TARGET_OUTPUT;
props_dscd.BufferCount = 2;
ThrowIfFailed(DirectXRes::getDXGIFactory()->CreateSwapChainForHwnd(
DirectXRes ::getD3D11Device().Get(), hWnd, &props_dscd, nullptr, nullptr,
swapChain_.GetAddressOf()));
ThrowIfFailed(DirectXRes::getD2DDevice()->CreateDeviceContext(
D2D1_DEVICE_CONTEXT_OPTIONS_NONE, context_.GetAddressOf()));
}
void D2DContext2D::createDeviceSwapChainBitmap() {
float dpiX, dpiY;
DirectXRes::getD2DFactory()->GetDesktopDpi(&dpiX, &dpiY);
context_->SetDpi(dpiX, dpiY);
ComPtr<IDXGISurface> surface;
ThrowIfFailed(swapChain_->GetBuffer(0, IID_PPV_ARGS(&surface)));
const auto properties = D2D1::BitmapProperties1(
D2D1_BITMAP_OPTIONS_TARGET | D2D1_BITMAP_OPTIONS_CANNOT_DRAW,
D2D1::PixelFormat(DXGI_FORMAT_B8G8R8A8_UNORM, D2D1_ALPHA_MODE_IGNORE),
dpiX, dpiY);
ThrowIfFailed(context_->CreateBitmapFromDxgiSurface(surface.Get(), properties,
bitmap_.GetAddressOf()));
context_->SetTarget(bitmap_.Get());
context_->SetUnitMode(D2D1_UNIT_MODE_PIXELS);
}
void D2DContext2D::handleDeviceLost() {
HWND hWnd;
ThrowIfFailed(swapChain_->GetHwnd(&hWnd));
DirectXRes::handleDeviceLost();
context_->SetTarget(nullptr);
bitmap_.Reset();
context_.Reset();
swapChain_.Reset();
createDeviceContextFromHWnd(hWnd);
createDeviceSwapChainBitmap();
}
void D2DContext2D::beginDraw() { context_->BeginDraw(); }
bool D2DContext2D::endDraw() {
ThrowIfFailed(context_->EndDraw());
const auto hr = swapChain_->Present(1, 0);
if (S_OK != hr && DXGI_STATUS_OCCLUDED != hr) {
ThrowIfFailed(hr);
}
return true;
}
std::unique_ptr<TextFormat> D2DContext2D::createTextFormat(const String& name,
float size,
FontWeight weight) {
ComPtr<IDWriteTextFormat> textFormat;
auto factory = DirectXRes::getDWriteFactory();
ThrowIfFailed(factory->CreateTextFormat(
name.c_str(), nullptr, ConvertTo<DWRITE_FONT_WEIGHT>(weight),
DWRITE_FONT_STYLE_NORMAL, DWRITE_FONT_STRETCH_NORMAL, size, TEXT(""),
&textFormat));
return std::make_unique<DWriteTextFormat>(std::move(textFormat));
}
} // namespace windows
} // namespace platforms
} // namespace yuki
| 33.42623 | 80 | 0.671489 | LinkDoyle |
f6471ae1ea47ecb8a075b971b683f3bf0b55ff21 | 3,364 | cpp | C++ | Cores/FCEU/FCEU/boards/vrc3.cpp | werminghoff/Provenance | de61b4a64a3eb8e2774e0a8ed53488c6c7aa6cb2 | [
"BSD-3-Clause"
] | 3,459 | 2015-01-07T14:07:09.000Z | 2022-03-25T03:51:10.000Z | Cores/FCEU/FCEU/boards/vrc3.cpp | werminghoff/Provenance | de61b4a64a3eb8e2774e0a8ed53488c6c7aa6cb2 | [
"BSD-3-Clause"
] | 1,046 | 2018-03-24T17:56:16.000Z | 2022-03-23T08:13:09.000Z | Cores/FCEU/FCEU/boards/vrc3.cpp | werminghoff/Provenance | de61b4a64a3eb8e2774e0a8ed53488c6c7aa6cb2 | [
"BSD-3-Clause"
] | 549 | 2015-01-07T14:07:15.000Z | 2022-01-07T16:13:05.000Z | /* FCE Ultra - NES/Famicom Emulator
*
* Copyright notice for this file:
* Copyright (C) 2012 CaH4e3
*
* This program is free software; you can redistribute it and/or modify
* it under the terms of the GNU General Public License as published by
* the Free Software Foundation; either version 2 of the License, or
* (at your option) any later version.
*
* This program is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
* GNU General Public License for more details.
*
* You should have received a copy of the GNU General Public License
* along with this program; if not, write to the Free Software
* Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA
*
* VRC-3
*
*/
#include "mapinc.h"
static uint8 preg;
static uint8 IRQx; //autoenable
static uint8 IRQm; //mode
static uint8 IRQa;
static uint16 IRQReload, IRQCount;
static uint8 *WRAM = NULL;
static uint32 WRAMSIZE;
static SFORMAT StateRegs[] =
{
{ &preg, 1, "PREG" },
{ &IRQa, 1, "IRQA" },
{ &IRQx, 1, "IRQX" },
{ &IRQm, 1, "IRQM" },
{ &IRQReload, 2, "IRQR" },
{ &IRQCount, 2, "IRQC" },
{ 0 }
};
static void Sync(void) {
setprg8r(0x10, 0x6000, 0);
setprg16(0x8000, preg);
setprg16(0xC000, ~0);
setchr8(0);
}
static DECLFW(M73Write) {
switch (A & 0xF000) {
case 0x8000: IRQReload &= 0xFFF0; IRQReload |= (V & 0xF) << 0; break;
case 0x9000: IRQReload &= 0xFF0F; IRQReload |= (V & 0xF) << 4; break;
case 0xA000: IRQReload &= 0xF0FF; IRQReload |= (V & 0xF) << 8; break;
case 0xB000: IRQReload &= 0x0FFF; IRQReload |= (V & 0xF) << 12; break;
case 0xC000:
IRQm = V & 4;
IRQx = V & 1;
IRQa = V & 2;
if (IRQa) {
if (IRQm) {
IRQCount &= 0xFFFF;
IRQCount |= (IRQReload & 0xFF);
} else
IRQCount = IRQReload;
}
X6502_IRQEnd(FCEU_IQEXT);
break;
case 0xD000: X6502_IRQEnd(FCEU_IQEXT); IRQa = IRQx; break;
case 0xF000: preg = V; Sync(); break;
}
}
static void M73IRQHook(int a) {
int32 i;
if (!IRQa) return;
for (i = 0; i < a; i++) {
if (IRQm) {
uint16 temp = IRQCount;
temp &= 0xFF;
IRQCount &= 0xFF00;
if (temp == 0xFF) {
IRQCount = IRQReload;
IRQCount |= (uint16)(IRQReload & 0xFF);
X6502_IRQBegin(FCEU_IQEXT);
} else {
temp++;
IRQCount |= temp;
}
} else {
//16 bit mode
if (IRQCount == 0xFFFF) {
IRQCount = IRQReload;
X6502_IRQBegin(FCEU_IQEXT);
} else
IRQCount++;
}
}
}
static void M73Power(void) {
IRQReload = IRQm = IRQx = 0;
Sync();
SetReadHandler(0x6000, 0xFFFF, CartBR);
SetWriteHandler(0x6000, 0x7FFF, CartBW);
SetWriteHandler(0x8000, 0xFFFF, M73Write);
FCEU_CheatAddRAM(WRAMSIZE >> 10, 0x6000, WRAM);
}
static void M73Close(void)
{
if (WRAM)
FCEU_gfree(WRAM);
WRAM = NULL;
}
static void StateRestore(int version) {
Sync();
}
void Mapper73_Init(CartInfo *info) {
info->Power = M73Power;
info->Close = M73Close;
MapIRQHook = M73IRQHook;
WRAMSIZE = 8192;
WRAM = (uint8*)FCEU_gmalloc(WRAMSIZE);
SetupCartPRGMapping(0x10, WRAM, WRAMSIZE, 1);
AddExState(WRAM, WRAMSIZE, 0, "WRAM");
AddExState(&StateRegs, ~0, 0, 0);
GameStateRestore = StateRestore;
}
| 24.735294 | 82 | 0.630202 | werminghoff |
f64b21354c4953d937430e7b42d5cc6f202faf7b | 15,003 | cxx | C++ | main/unoxml/source/xpath/xpathapi.cxx | Grosskopf/openoffice | 93df6e8a695d5e3eac16f3ad5e9ade1b963ab8d7 | [
"Apache-2.0"
] | 679 | 2015-01-06T06:34:58.000Z | 2022-03-30T01:06:03.000Z | main/unoxml/source/xpath/xpathapi.cxx | Grosskopf/openoffice | 93df6e8a695d5e3eac16f3ad5e9ade1b963ab8d7 | [
"Apache-2.0"
] | 102 | 2017-11-07T08:51:31.000Z | 2022-03-17T12:13:49.000Z | main/unoxml/source/xpath/xpathapi.cxx | Grosskopf/openoffice | 93df6e8a695d5e3eac16f3ad5e9ade1b963ab8d7 | [
"Apache-2.0"
] | 331 | 2015-01-06T11:40:55.000Z | 2022-03-14T04:07:51.000Z | /**************************************************************
*
* Licensed to the Apache Software Foundation (ASF) under one
* or more contributor license agreements. See the NOTICE file
* distributed with this work for additional information
* regarding copyright ownership. The ASF licenses this file
* to you under the Apache License, Version 2.0 (the
* "License"); you may not use this file except in compliance
* with the License. You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing,
* software distributed under the License is distributed on an
* "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
* KIND, either express or implied. See the License for the
* specific language governing permissions and limitations
* under the License.
*
*************************************************************/
#include <xpathapi.hxx>
#include <stdarg.h>
#include <string.h>
#include <libxml/tree.h>
#include <libxml/xmlerror.h>
#include <libxml/xpath.h>
#include <libxml/xpathInternals.h>
#include <rtl/ustrbuf.hxx>
#include <nodelist.hxx>
#include <xpathobject.hxx>
#include "../dom/node.hxx"
#include "../dom/document.hxx"
using ::com::sun::star::lang::XMultiServiceFactory;
namespace XPath
{
// factory
Reference< XInterface > CXPathAPI::_getInstance(const Reference< XMultiServiceFactory >& rSMgr)
{
return Reference< XInterface >(static_cast<XXPathAPI*>(new CXPathAPI(rSMgr)));
}
// ctor
CXPathAPI::CXPathAPI(const Reference< XMultiServiceFactory >& rSMgr)
: m_aFactory(rSMgr)
{
}
const char* CXPathAPI::aImplementationName = "com.sun.star.comp.xml.xpath.XPathAPI";
const char* CXPathAPI::aSupportedServiceNames[] = {
"com.sun.star.xml.xpath.XPathAPI",
NULL
};
OUString CXPathAPI::_getImplementationName()
{
return OUString::createFromAscii(aImplementationName);
}
Sequence<OUString> CXPathAPI::_getSupportedServiceNames()
{
Sequence<OUString> aSequence;
for (int i=0; aSupportedServiceNames[i]!=NULL; i++) {
aSequence.realloc(i+1);
aSequence[i]=(OUString::createFromAscii(aSupportedServiceNames[i]));
}
return aSequence;
}
Sequence< OUString > SAL_CALL CXPathAPI::getSupportedServiceNames()
throw (RuntimeException)
{
return CXPathAPI::_getSupportedServiceNames();
}
OUString SAL_CALL CXPathAPI::getImplementationName()
throw (RuntimeException)
{
return CXPathAPI::_getImplementationName();
}
sal_Bool SAL_CALL CXPathAPI::supportsService(const OUString& aServiceName)
throw (RuntimeException)
{
Sequence< OUString > supported = CXPathAPI::_getSupportedServiceNames();
for (sal_Int32 i=0; i<supported.getLength(); i++)
{
if (supported[i] == aServiceName) return sal_True;
}
return sal_False;
}
// -------------------------------------------------------------------
void SAL_CALL CXPathAPI::registerNS(
const OUString& aPrefix,
const OUString& aURI)
throw (RuntimeException)
{
::osl::MutexGuard const g(m_Mutex);
m_nsmap.insert(nsmap_t::value_type(aPrefix, aURI));
}
void SAL_CALL CXPathAPI::unregisterNS(
const OUString& aPrefix,
const OUString& aURI)
throw (RuntimeException)
{
::osl::MutexGuard const g(m_Mutex);
if ((m_nsmap.find(aPrefix))->second.equals(aURI)) {
m_nsmap.erase(aPrefix);
}
}
// register all namespaces stored in the namespace list for this object
// with the current xpath evaluation context
static void lcl_registerNamespaces(
xmlXPathContextPtr ctx,
const nsmap_t& nsmap)
{
nsmap_t::const_iterator i = nsmap.begin();
OString oprefix, ouri;
xmlChar *p, *u;
while (i != nsmap.end())
{
oprefix = OUStringToOString(i->first, RTL_TEXTENCODING_UTF8);
ouri = OUStringToOString(i->second, RTL_TEXTENCODING_UTF8);
p = (xmlChar*)oprefix.getStr();
u = (xmlChar*)ouri.getStr();
xmlXPathRegisterNs(ctx, p, u);
i++;
}
}
// get all ns decls on a node (and parent nodes, if any)
static void lcl_collectNamespaces(
nsmap_t & rNamespaces, Reference< XNode > const& xNamespaceNode)
{
DOM::CNode *const pCNode(DOM::CNode::GetImplementation(xNamespaceNode));
if (!pCNode) { throw RuntimeException(); }
::osl::MutexGuard const g(pCNode->GetOwnerDocument().GetMutex());
xmlNodePtr pNode = pCNode->GetNodePtr();
while (pNode != 0) {
xmlNsPtr curDef = pNode->nsDef;
while (curDef != 0) {
const xmlChar* xHref = curDef->href;
OUString aURI((sal_Char*)xHref, strlen((char*)xHref), RTL_TEXTENCODING_UTF8);
const xmlChar* xPre = curDef->prefix;
OUString aPrefix((sal_Char*)xPre, strlen((char*)xPre), RTL_TEXTENCODING_UTF8);
// we could already have this prefix from a child node
if (rNamespaces.find(aPrefix) == rNamespaces.end())
{
rNamespaces.insert(::std::make_pair(aPrefix, aURI));
}
curDef = curDef->next;
}
pNode = pNode->parent;
}
}
static void lcl_collectRegisterNamespaces(
CXPathAPI & rAPI, Reference< XNode > const& xNamespaceNode)
{
nsmap_t namespaces;
lcl_collectNamespaces(namespaces, xNamespaceNode);
for (nsmap_t::const_iterator iter = namespaces.begin();
iter != namespaces.end(); ++iter)
{
rAPI.registerNS(iter->first, iter->second);
}
}
// register function and variable lookup functions with the current
// xpath evaluation context
static void lcl_registerExtensions(
xmlXPathContextPtr ctx,
const extensions_t& extensions)
{
extensions_t::const_iterator i = extensions.begin();
while (i != extensions.end())
{
Libxml2ExtensionHandle aHandle = (*i)->getLibxml2ExtensionHandle();
if ( aHandle.functionLookupFunction != 0 )
{
xmlXPathRegisterFuncLookup(ctx,
reinterpret_cast<xmlXPathFuncLookupFunc>(
sal::static_int_cast<sal_IntPtr>(aHandle.functionLookupFunction)),
reinterpret_cast<void*>(
sal::static_int_cast<sal_IntPtr>(aHandle.functionData)));
}
if ( aHandle.variableLookupFunction != 0 )
{
xmlXPathRegisterVariableLookup(ctx,
reinterpret_cast<xmlXPathVariableLookupFunc>(
sal::static_int_cast<sal_IntPtr>(aHandle.variableLookupFunction)),
reinterpret_cast<void*>(
sal::static_int_cast<sal_IntPtr>(aHandle.variableData)));
}
i++;
}
}
/**
* Use an XPath string to select a nodelist.
*/
Reference< XNodeList > SAL_CALL CXPathAPI::selectNodeList(
const Reference< XNode >& contextNode,
const OUString& expr)
throw (RuntimeException, XPathException)
{
Reference< XXPathObject > xobj = eval(contextNode, expr);
return xobj->getNodeList();
}
/**
* same as selectNodeList but registers all name space decalratiosn found on namespaceNode
*/
Reference< XNodeList > SAL_CALL CXPathAPI::selectNodeListNS(
const Reference< XNode >& contextNode,
const OUString& expr,
const Reference< XNode >& namespaceNode)
throw (RuntimeException, XPathException)
{
lcl_collectRegisterNamespaces(*this, namespaceNode);
return selectNodeList(contextNode, expr);
}
/**
* Same as selectNodeList but returns the first node (if any)
*/
Reference< XNode > SAL_CALL CXPathAPI::selectSingleNode(
const Reference< XNode >& contextNode,
const OUString& expr)
throw (RuntimeException, XPathException)
{
Reference< XNodeList > aList = selectNodeList(contextNode, expr);
Reference< XNode > aNode = aList->item(0);
return aNode;
}
/**
* Same as selectSingleNode but registers all namespaces declared on
* namespaceNode
*/
Reference< XNode > SAL_CALL CXPathAPI::selectSingleNodeNS(
const Reference< XNode >& contextNode,
const OUString& expr,
const Reference< XNode >& namespaceNode )
throw (RuntimeException, XPathException)
{
lcl_collectRegisterNamespaces(*this, namespaceNode);
return selectSingleNode(contextNode, expr);
}
static OUString make_error_message(xmlErrorPtr pError)
{
::rtl::OUStringBuffer buf;
if (pError->message) {
buf.appendAscii(pError->message);
}
int line = pError->line;
if (line) {
buf.appendAscii("Line: ");
buf.append(static_cast<sal_Int32>(line));
buf.appendAscii("\n");
}
int column = pError->int2;
if (column) {
buf.appendAscii("Column: ");
buf.append(static_cast<sal_Int32>(column));
buf.appendAscii("\n");
}
OUString msg = buf.makeStringAndClear();
return msg;
}
extern "C" {
static void generic_error_func(void *userData, const char *format, ...)
{
(void) userData;
char str[1000];
va_list args;
va_start(args, format);
#ifdef _WIN32
#define vsnprintf _vsnprintf
#endif
vsnprintf(str, sizeof(str), format, args);
va_end(args);
::rtl::OUStringBuffer buf(
OUString::createFromAscii("libxml2 error:\n"));
buf.appendAscii(str);
OString msg = OUStringToOString(buf.makeStringAndClear(),
RTL_TEXTENCODING_ASCII_US);
OSL_ENSURE(sal_False, msg.getStr());
}
static void structured_error_func(void * userData, xmlErrorPtr error)
{
(void) userData;
::rtl::OUStringBuffer buf(
OUString::createFromAscii("libxml2 error:\n"));
if (error) {
buf.append(make_error_message(error));
} else {
buf.append(OUString::createFromAscii("no error argument!"));
}
OString msg = OUStringToOString(buf.makeStringAndClear(),
RTL_TEXTENCODING_ASCII_US);
OSL_ENSURE(sal_False, msg.getStr());
}
} // extern "C"
/**
* evaluates an XPath string. relative XPath expressions are evaluated relative to
* the context Node
*/
Reference< XXPathObject > SAL_CALL CXPathAPI::eval(
Reference< XNode > const& xContextNode,
const OUString& expr)
throw (RuntimeException, XPathException)
{
if (!xContextNode.is()) { throw RuntimeException(); }
nsmap_t nsmap;
extensions_t extensions;
{
::osl::MutexGuard const g(m_Mutex);
nsmap = m_nsmap;
extensions = m_extensions;
}
// get the node and document
::rtl::Reference<DOM::CDocument> const pCDoc(
dynamic_cast<DOM::CDocument*>( DOM::CNode::GetImplementation(
xContextNode->getOwnerDocument())));
if (!pCDoc.is()) { throw RuntimeException(); }
DOM::CNode *const pCNode = DOM::CNode::GetImplementation(xContextNode);
if (!pCNode) { throw RuntimeException(); }
::osl::MutexGuard const g(pCDoc->GetMutex()); // lock the document!
xmlNodePtr const pNode = pCNode->GetNodePtr();
if (!pNode) { throw RuntimeException(); }
xmlDocPtr pDoc = pNode->doc;
/* NB: workaround for #i87252#:
libxml < 2.6.17 considers it an error if the context
node is the empty document (i.e. its xpathCtx->doc has no
children). libxml 2.6.17 does not consider it an error.
Unfortunately, old libxml prints an error message to stderr,
which (afaik) cannot be turned off in this case, so we handle it.
*/
if (!pDoc->children) {
throw XPathException();
}
/* Create xpath evaluation context */
::boost::shared_ptr<xmlXPathContext> const xpathCtx(
xmlXPathNewContext(pDoc), xmlXPathFreeContext);
if( !bool(xpathCtx)) { throw XPathException(); }
// set context node
xpathCtx->node = pNode;
// error handling
xpathCtx->error = structured_error_func;
xmlSetGenericErrorFunc(NULL, generic_error_func);
// register namespaces and extension
lcl_registerNamespaces(xpathCtx.get(), nsmap);
lcl_registerExtensions(xpathCtx.get(), extensions);
/* run the query */
OString o1 = OUStringToOString(expr, RTL_TEXTENCODING_UTF8);
xmlChar *xStr = (xmlChar*)o1.getStr();
::boost::shared_ptr<xmlXPathObject> const xpathObj(
xmlXPathEval(xStr, xpathCtx.get()), xmlXPathFreeObject);
if (0 == xpathObj) {
// OSL_ENSURE(xpathCtx->lastError == NULL, xpathCtx->lastError->message);
throw XPathException();
}
Reference<XXPathObject> const xObj(
new CXPathObject(pCDoc, pCDoc->GetMutex(), xpathObj));
return xObj;
}
/**
* same as eval but registers all namespace declarations found on namespaceNode
*/
Reference< XXPathObject > SAL_CALL CXPathAPI::evalNS(
const Reference< XNode >& contextNode,
const OUString& expr,
const Reference< XNode >& namespaceNode)
throw (RuntimeException, XPathException)
{
lcl_collectRegisterNamespaces(*this, namespaceNode);
return eval(contextNode, expr);
}
/**
* uses the service manager to create an instance of the service denoted by aName.
* If the returned object implements the XXPathExtension interface, it is added to the list
* of extensions that are used when evaluating XPath strings with this XPathAPI instance
*/
void SAL_CALL CXPathAPI::registerExtension(
const OUString& aName)
throw (RuntimeException)
{
::osl::MutexGuard const g(m_Mutex);
// get extension from service manager
Reference< XXPathExtension > const xExtension(
m_aFactory->createInstance(aName), UNO_QUERY_THROW);
m_extensions.push_back(xExtension);
}
/**
* registers the given extension instance to be used by XPath evaluations performed through this
* XPathAPI instance
*/
void SAL_CALL CXPathAPI::registerExtensionInstance(
Reference< XXPathExtension> const& xExtension)
throw (RuntimeException)
{
if (!xExtension.is()) {
throw RuntimeException();
}
::osl::MutexGuard const g(m_Mutex);
m_extensions.push_back( xExtension );
}
}
| 33.192478 | 99 | 0.619076 | Grosskopf |
f64be9f45f8fb11c6d45f13e8c5bf04c7a40ef5e | 4,206 | cpp | C++ | dev/src/BicycleFrontPanel_utest/BicycleFrontPanel_utest/tst_bicyclefrontpanel_utest.cpp | CountrySideEngineer/BicycleFrontPanel | de13a984f726d282f1703f9096dd61ef287806e9 | [
"MIT"
] | null | null | null | dev/src/BicycleFrontPanel_utest/BicycleFrontPanel_utest/tst_bicyclefrontpanel_utest.cpp | CountrySideEngineer/BicycleFrontPanel | de13a984f726d282f1703f9096dd61ef287806e9 | [
"MIT"
] | null | null | null | dev/src/BicycleFrontPanel_utest/BicycleFrontPanel_utest/tst_bicyclefrontpanel_utest.cpp | CountrySideEngineer/BicycleFrontPanel | de13a984f726d282f1703f9096dd61ef287806e9 | [
"MIT"
] | null | null | null | #include <QtTest>
#include <QDebug>
// add necessary includes here
#include "cdatetime.h"
#include "apart.h"
#include "cwheel.h"
#include "cwheelvelocity.h"
class BicycleFrontPanel_utest : public QObject
{
Q_OBJECT
public:
BicycleFrontPanel_utest();
~BicycleFrontPanel_utest();
private slots:
void initTestCase();
void cleanupTestCase();
void CWheelTest_001();
void CWheelTest_002();
void CWheelTest_003();
void CWheelTest_004();
void CWheelTest_005();
void CWheelTest_006();
void CWheelTest_007();
void CWheelTest_008();
void CWheelTest_009();
private:
CWheel *wheel;
};
BicycleFrontPanel_utest::BicycleFrontPanel_utest()
{
this->wheel = NULL;
}
BicycleFrontPanel_utest::~BicycleFrontPanel_utest() {}
void BicycleFrontPanel_utest::initTestCase() {}
void BicycleFrontPanel_utest::cleanupTestCase()
{
delete this->wheel;
this->wheel = NULL;
}
void BicycleFrontPanel_utest::CWheelTest_001()
{
this->initTestCase();
this->wheel = new CWheel();
QVERIFY(0 == this->wheel->GetGpioPin());
QVERIFY(false == this->wheel->GetIsFailure());
QVERIFY(0x0000 == this->wheel->GetFailureCode());
QVERIFY(0 == this->wheel->GetState());
QVERIFY(APart::PART_PIN_DIRECTION_MAX == this->wheel->GetPinDirection());
this->cleanupTestCase();
}
void BicycleFrontPanel_utest::CWheelTest_002()
{
this->initTestCase();
this->wheel = new CWheel(1, APart::PART_PIN_DIRECTION_INPUT, 10, 20);
QVERIFY(1 == this->wheel->GetGpioPin());
QVERIFY(false == this->wheel->GetIsFailure());
QVERIFY(0x000 == this->wheel->GetFailureCode());
QVERIFY(0 == this->wheel->GetState());
QVERIFY(APart::PART_PIN_DIRECTION_INPUT == this->wheel->GetPinDirection());
this->cleanupTestCase();
}
void BicycleFrontPanel_utest::CWheelTest_003()
{
this->initTestCase();
this->wheel = new CWheel(1, APart::PART_PIN_DIRECTION_OUTPUT, 10, 20);
QVERIFY(APart::PART_PIN_DIRECTION_OUTPUT == this->wheel->GetPinDirection());
}
void BicycleFrontPanel_utest::CWheelTest_004()
{
this->initTestCase();
this->wheel = new CWheel(1, APart::PART_PIN_DIRECTION_IN_OUT, 10, 20);
QVERIFY(APart::PART_PIN_DIRECTION_IN_OUT == this->wheel->GetPinDirection());
this->cleanupTestCase();
}
void BicycleFrontPanel_utest::CWheelTest_005()
{
this->initTestCase();
this->wheel = new CWheel();
QVERIFY(0 == this->wheel->GetState());
this->wheel->Update();
QVERIFY(1 == this->wheel->GetState());
this->cleanupTestCase();
}
void BicycleFrontPanel_utest::CWheelTest_006()
{
this->initTestCase();
this->wheel = new CWheel();
QVERIFY(0 == this->wheel->GetState());
this->wheel->Update(100);
QVERIFY(0 == this->wheel->GetState());
this->cleanupTestCase();
}
void BicycleFrontPanel_utest::CWheelTest_007()
{
this->initTestCase();
this->wheel = new CWheel();
QVERIFY(0 == this->wheel->GetState());
this->wheel->InterruptCallback(0);
QVERIFY(1 == this->wheel->GetState());
this->cleanupTestCase();
}
void BicycleFrontPanel_utest::CWheelTest_008()
{
this->initTestCase();
this->wheel = new CWheel();
for (int index = 0; index < 83; index++) {
this->wheel->InterruptCallback(0);
}
QVERIFY(83 == this->wheel->GetState());
QVERIFY(0 == this->wheel->GetRpm());
this->wheel->TimerCallback(0);
QVERIFY(0 == this->wheel->GetState());
QVERIFY(0 == this->wheel->GetRpm());
this->cleanupTestCase();
}
void BicycleFrontPanel_utest::CWheelTest_009()
{
this->initTestCase();
this->wheel = new CWheel();
for (int index = 0; index < 84; index++) {
this->wheel->InterruptCallback(0);
}
QVERIFY(84 == this->wheel->GetState());
QVERIFY(0 == this->wheel->GetRpm());
this->wheel->TimerCallback(0);
QVERIFY(0 == this->wheel->GetState());
QVERIFY(1 == this->wheel->GetRpm());
this->cleanupTestCase();
}
QTEST_APPLESS_MAIN(BicycleFrontPanel_utest)
#include "tst_bicyclefrontpanel_utest.moc"
| 24.887574 | 81 | 0.64194 | CountrySideEngineer |
f64dec40bd138e76dd99b023fda095d959fab0c3 | 149 | cpp | C++ | libng/core/src/libng_core/ui/platform/mac/MacWindow.cpp | gapry/libng | 8fbf927e5bb73f105bddbb618430d3e1bf2cf877 | [
"MIT"
] | null | null | null | libng/core/src/libng_core/ui/platform/mac/MacWindow.cpp | gapry/libng | 8fbf927e5bb73f105bddbb618430d3e1bf2cf877 | [
"MIT"
] | null | null | null | libng/core/src/libng_core/ui/platform/mac/MacWindow.cpp | gapry/libng | 8fbf927e5bb73f105bddbb618430d3e1bf2cf877 | [
"MIT"
] | null | null | null | #include <libng_core/ui/platform/mac/MacWindow.hpp>
namespace libng {
MacWindow::MacWindow() {
}
MacWindow::~MacWindow() {
}
} // namespace libng | 13.545455 | 51 | 0.711409 | gapry |
f64e1d74027d448ea856d893613a9544aa81cacb | 46,045 | cpp | C++ | hi_scripting/scripting/ScriptProcessorModules.cpp | Matt-Dub/HISE | ae2dd1653e1c8d749a9088edcd573de6252b0b96 | [
"Intel"
] | null | null | null | hi_scripting/scripting/ScriptProcessorModules.cpp | Matt-Dub/HISE | ae2dd1653e1c8d749a9088edcd573de6252b0b96 | [
"Intel"
] | null | null | null | hi_scripting/scripting/ScriptProcessorModules.cpp | Matt-Dub/HISE | ae2dd1653e1c8d749a9088edcd573de6252b0b96 | [
"Intel"
] | null | null | null | /* ===========================================================================
*
* This file is part of HISE.
* Copyright 2016 Christoph Hart
*
* HISE is free software: you can redistribute it and/or modify
* it under the terms of the GNU General Public License as published by
* the Free Software Foundation, either version 3 of the License, or
* (at your option) any later version.
*
* HISE is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
* GNU General Public License for more details.
*
* You should have received a copy of the GNU General Public License
* along with HISE. If not, see <http://www.gnu.org/licenses/>.
*
* Commercial licenses for using HISE in an closed source project are
* available on request. Please visit the project's website to get more
* information about commercial licensing:
*
* http://www.hise.audio/
*
* HISE is based on the JUCE library,
* which also must be licenced for commercial applications:
*
* http://www.juce.com
*
* ===========================================================================
*/
namespace hise { using namespace juce;
JavascriptMidiProcessor::JavascriptMidiProcessor(MainController *mc, const String &id) :
ScriptBaseMidiProcessor(mc, id),
JavascriptProcessor(mc),
onInitCallback(new SnippetDocument("onInit")),
onNoteOnCallback(new SnippetDocument("onNoteOn")),
onNoteOffCallback(new SnippetDocument("onNoteOff")),
onControllerCallback(new SnippetDocument("onController")),
onTimerCallback(new SnippetDocument("onTimer")),
onControlCallback(new SnippetDocument("onControl", "number value")),
front(false),
deferred(false),
deferredExecutioner(this),
deferredUpdatePending(false)
{
initContent();
editorStateIdentifiers.add("contentShown");
editorStateIdentifiers.add("onInitOpen");
editorStateIdentifiers.add("onNoteOnOpen");
editorStateIdentifiers.add("onNoteOffOpen");
editorStateIdentifiers.add("onControllerOpen");
editorStateIdentifiers.add("onTimerOpen");
editorStateIdentifiers.add("onControlOpen");
editorStateIdentifiers.add("externalPopupShown");
setEditorState(Identifier("contentShown"), true);
setEditorState(Identifier("onInitOpen"), true);
}
JavascriptMidiProcessor::~JavascriptMidiProcessor()
{
cleanupEngine();
clearExternalWindows();
serverObject = nullptr;
onInitCallback = nullptr;
onNoteOnCallback = nullptr;
onNoteOffCallback = nullptr;
onControllerCallback = nullptr;
onTimerCallback = nullptr;
onControlCallback = nullptr;
#if USE_BACKEND
if (consoleEnabled)
{
getMainController()->setWatchedScriptProcessor(nullptr, nullptr);
}
#endif
}
Path JavascriptMidiProcessor::getSpecialSymbol() const
{
Path path; path.loadPathFromData(HiBinaryData::SpecialSymbols::scriptProcessor, sizeof(HiBinaryData::SpecialSymbols::scriptProcessor)); return path;
}
ValueTree JavascriptMidiProcessor::exportAsValueTree() const
{
ValueTree v = ScriptBaseMidiProcessor::exportAsValueTree();
saveScript(v);
return v;
}
void JavascriptMidiProcessor::restoreFromValueTree(const ValueTree &v)
{
restoreScript(v);
ScriptBaseMidiProcessor::restoreFromValueTree(v);
}
JavascriptMidiProcessor::SnippetDocument * JavascriptMidiProcessor::getSnippet(int c)
{
switch (c)
{
case onInit: return onInitCallback;
case onNoteOn: return onNoteOnCallback;
case onNoteOff: return onNoteOffCallback;
case onController: return onControllerCallback;
case onTimer: return onTimerCallback;
case onControl: return onControlCallback;
default: jassertfalse; return nullptr;
}
}
const JavascriptMidiProcessor::SnippetDocument * JavascriptMidiProcessor::getSnippet(int c) const
{
switch (c)
{
case onInit: return onInitCallback;
case onNoteOn: return onNoteOnCallback;
case onNoteOff: return onNoteOffCallback;
case onController: return onControllerCallback;
case onTimer: return onTimerCallback;
case onControl: return onControlCallback;
default: jassertfalse; return nullptr;
}
}
ProcessorEditorBody *JavascriptMidiProcessor::createEditor(ProcessorEditor *parentEditor)
{
#if USE_BACKEND
return new ScriptingEditor(parentEditor);
#else
ignoreUnused(parentEditor);
jassertfalse;
return nullptr;
#endif
};
void JavascriptMidiProcessor::processHiseEvent(HiseEvent &m)
{
if (isDeferred())
{
deferredExecutioner.addPendingEvent(m);
}
else
{
ADD_GLITCH_DETECTOR(this, DebugLogger::Location::ScriptMidiEventCallback);
if (currentMidiMessage != nullptr)
{
ScopedValueSetter<HiseEvent*> svs(currentEvent, &m);
currentMidiMessage->setHiseEvent(m);
runScriptCallbacks();
}
}
}
void JavascriptMidiProcessor::registerApiClasses()
{
//content = new ScriptingApi::Content(this);
front = false;
currentMidiMessage = new ScriptingApi::Message(this);
engineObject = new ScriptingApi::Engine(this);
synthObject = new ScriptingApi::Synth(this, currentMidiMessage.get(), getOwnerSynth());
scriptEngine->registerApiClass(new ScriptingApi::ModuleIds(getOwnerSynth()));
samplerObject = new ScriptingApi::Sampler(this, dynamic_cast<ModulatorSampler*>(getOwnerSynth()));
scriptEngine->registerNativeObject("Content", getScriptingContent());
scriptEngine->registerApiClass(currentMidiMessage.get());
scriptEngine->registerApiClass(engineObject.get());
scriptEngine->registerApiClass(new ScriptingApi::Settings(this));
scriptEngine->registerApiClass(new ScriptingApi::FileSystem(this));
scriptEngine->registerApiClass(serverObject = new ScriptingApi::Server(this));
scriptEngine->registerApiClass(new ScriptingApi::Console(this));
scriptEngine->registerApiClass(new ScriptingApi::Colours());
scriptEngine->registerApiClass(synthObject);
scriptEngine->registerApiClass(samplerObject);
scriptEngine->registerNativeObject("Libraries", new DspFactory::LibraryLoader(this));
scriptEngine->registerNativeObject("Buffer", new VariantBuffer::Factory(64));
}
void JavascriptMidiProcessor::addToFront(bool addToFront_) noexcept
{
front = addToFront_;
#if USE_FRONTEND
content->getUpdateDispatcher()->suspendUpdates(false);
#endif
}
void JavascriptMidiProcessor::runScriptCallbacks()
{
if (currentEvent->isAllNotesOff())
{
synthObject->handleNoteCounter(*currentEvent);
// All notes off are controller message, so they should not be processed, or it can lead to loop.
currentMidiMessage->onAllNotesOff();
return;
}
#if ENABLE_SCRIPTING_BREAKPOINTS
breakpointWasHit(-1);
#endif
scriptEngine->maximumExecutionTime = isDeferred() ? RelativeTime(0.5) : RelativeTime(0.03);
synthObject->handleNoteCounter(*currentEvent);
switch (currentEvent->getType())
{
case HiseEvent::Type::NoteOn:
{
if (onNoteOnCallback->isSnippetEmpty()) return;
scriptEngine->executeCallback(onNoteOn, &lastResult);
BACKEND_ONLY(if (!lastResult.wasOk()) debugError(this, lastResult.getErrorMessage()));
break;
}
case HiseEvent::Type::NoteOff:
{
if (onNoteOffCallback->isSnippetEmpty()) return;
scriptEngine->executeCallback(onNoteOff, &lastResult);
BACKEND_ONLY(if (!lastResult.wasOk()) debugError(this, lastResult.getErrorMessage()));
break;
}
case HiseEvent::Type::Controller:
case HiseEvent::Type::PitchBend:
case HiseEvent::Type::Aftertouch:
case HiseEvent::Type::ProgramChange:
{
if (currentEvent->isControllerOfType(64))
{
synthObject->setSustainPedal(currentEvent->getControllerValue() > 64);
}
if (onControllerCallback->isSnippetEmpty()) return;
Result r = Result::ok();
scriptEngine->executeCallback(onController, &lastResult);
BACKEND_ONLY(if (!lastResult.wasOk()) debugError(this, lastResult.getErrorMessage()));
break;
}
case HiseEvent::Type::TimerEvent:
{
if (!currentEvent->isIgnored() && currentEvent->getChannel() == getIndexInChain())
{
runTimerCallback(currentEvent->getTimeStamp());
currentEvent->ignoreEvent(true);
}
break;
}
case HiseEvent::Type::AllNotesOff:
{
break;
}
case HiseEvent::Type::Empty:
case HiseEvent::Type::SongPosition:
case HiseEvent::Type::MidiStart:
case HiseEvent::Type::MidiStop:
case HiseEvent::Type::VolumeFade:
case HiseEvent::Type::PitchFade:
case HiseEvent::Type::numTypes:
break;
}
#if 0
else if (currentEvent->isSongPositionPointer())
{
Result r = Result::ok();
static const Identifier onClock("onClock");
var args = currentEvent->getSongPositionPointerMidiBeat();
scriptEngine->callInlineFunction(onClock, &args, 1, &r);
//scriptEngine->executeWithoutAllocation(onClock, var::NativeFunctionArgs(dynamic_cast<ReferenceCountedObject*>(this), args, 1), &r);
if (!r.wasOk()) debugError(this, r.getErrorMessage());
}
else if (currentEvent->isMidiStart() || currentEvent->isMidiStop())
{
Result r = Result::ok();
static const Identifier onTransport("onTransport");
var args = currentEvent->isMidiStart();
scriptEngine->callInlineFunction(onTransport, &args, 1, &r);
//scriptEngine->executeWithoutAllocation(onClock, var::NativeFunctionArgs(dynamic_cast<ReferenceCountedObject*>(this), args, 1), &r);
}
#endif
}
void JavascriptMidiProcessor::runTimerCallback(int /*offsetInBuffer*//*=-1*/)
{
if (isBypassed() || onTimerCallback->isSnippetEmpty()) return;
scriptEngine->maximumExecutionTime = isDeferred() ? RelativeTime(0.5) : RelativeTime(0.002);
if (lastResult.failed()) return;
scriptEngine->executeCallback(onTimer, &lastResult);
if (isDeferred())
{
sendSynchronousChangeMessage();
}
BACKEND_ONLY(if (!lastResult.wasOk()) debugError(this, lastResult.getErrorMessage()));
}
void JavascriptMidiProcessor::deferCallbacks(bool addToFront_)
{
deferred = addToFront_;
if (deferred)
{
getOwnerSynth()->stopSynthTimer(getIndexInChain());
}
else
{
stopTimer();
}
};
StringArray JavascriptMidiProcessor::getImageFileNames() const
{
jassert(isFront());
StringArray fileNames;
for (int i = 0; i < content->getNumComponents(); i++)
{
const ScriptingApi::Content::ScriptImage *image = dynamic_cast<const ScriptingApi::Content::ScriptImage*>(content->getComponent(i));
if (image != nullptr) fileNames.add(image->getScriptObjectProperty(ScriptingApi::Content::ScriptImage::FileName));
}
return fileNames;
}
JavascriptPolyphonicEffect::JavascriptPolyphonicEffect(MainController *mc, const String &id, int numVoices):
JavascriptProcessor(mc),
ProcessorWithScriptingContent(mc),
VoiceEffectProcessor(mc, id, numVoices),
onInitCallback(new SnippetDocument("onInit")),
onControlCallback(new SnippetDocument("onControl"))
{
initContent();
finaliseModChains();
editorStateIdentifiers.add("contentShown");
editorStateIdentifiers.add("onInitOpen");
editorStateIdentifiers.add("onControlOpen");
editorStateIdentifiers.add("externalPopupShown");
}
JavascriptPolyphonicEffect::~JavascriptPolyphonicEffect()
{
clearExternalWindows();
cleanupEngine();
#if USE_BACKEND
if (consoleEnabled)
{
getMainController()->setWatchedScriptProcessor(nullptr, nullptr);
}
#endif
}
juce::Path JavascriptPolyphonicEffect::getSpecialSymbol() const
{
Path path; path.loadPathFromData(HiBinaryData::SpecialSymbols::scriptProcessor, sizeof(HiBinaryData::SpecialSymbols::scriptProcessor)); return path;
}
hise::ProcessorEditorBody * JavascriptPolyphonicEffect::createEditor(ProcessorEditor *parentEditor)
{
#if USE_BACKEND
return new ScriptingEditor(parentEditor);
#else
ignoreUnused(parentEditor);
jassertfalse;
return nullptr;
#endif
}
hise::JavascriptProcessor::SnippetDocument * JavascriptPolyphonicEffect::getSnippet(int c)
{
Callback ca = (Callback)c;
switch (ca)
{
case Callback::onInit: return onInitCallback;
case Callback::onControl: return onControlCallback;
case Callback::numCallbacks: return nullptr;
default:
break;
}
return nullptr;
}
const hise::JavascriptProcessor::SnippetDocument * JavascriptPolyphonicEffect::getSnippet(int c) const
{
Callback ca = (Callback)c;
switch (ca)
{
case Callback::onInit: return onInitCallback;
case Callback::onControl: return onControlCallback;
case Callback::numCallbacks: return nullptr;
default:
break;
}
return nullptr;
}
void JavascriptPolyphonicEffect::registerApiClasses()
{
engineObject = new ScriptingApi::Engine(this);
scriptEngine->registerNativeObject("Content", content.get());
scriptEngine->registerApiClass(engineObject);
scriptEngine->registerApiClass(new ScriptingApi::Console(this));
scriptEngine->registerApiClass(new ScriptingApi::Settings(this));
scriptEngine->registerApiClass(new ScriptingApi::FileSystem(this));
scriptEngine->registerNativeObject("Libraries", new DspFactory::LibraryLoader(this));
scriptEngine->registerNativeObject("Buffer", new VariantBuffer::Factory(64));
}
void JavascriptPolyphonicEffect::postCompileCallback()
{
prepareToPlay(getSampleRate(), getLargestBlockSize());
}
void JavascriptPolyphonicEffect::prepareToPlay(double sampleRate, int samplesPerBlock)
{
VoiceEffectProcessor::prepareToPlay(sampleRate, samplesPerBlock);
if (sampleRate == -1.0)
return;
if (auto n = getActiveNetwork())
{
auto numChannels = dynamic_cast<RoutableProcessor*>(getParentProcessor(true))->getMatrix().getNumSourceChannels();
n->setNumChannels(numChannels);
n->prepareToPlay(sampleRate, (double)samplesPerBlock);
}
}
void JavascriptPolyphonicEffect::renderVoice(int voiceIndex, AudioSampleBuffer &b, int startSample, int numSamples)
{
if (auto n = getActiveNetwork())
{
float* channels[NUM_MAX_CHANNELS];
int numChannels = b.getNumChannels();
memcpy(channels, b.getArrayOfWritePointers(), sizeof(float*) * numChannels);
for (int i = 0; i < numChannels; i++)
channels[i] += startSample;
scriptnode::ProcessDataDyn d(channels, numSamples, numChannels);
scriptnode::DspNetwork::VoiceSetter vs(*n, voiceIndex);
n->getRootNode()->process(d);
}
}
void JavascriptPolyphonicEffect::startVoice(int voiceIndex, const HiseEvent& e)
{
if (auto n = getActiveNetwork())
{
voiceData.startVoice(*n, *n->getPolyHandler(), voiceIndex, e);
}
}
void JavascriptPolyphonicEffect::reset(int voiceIndex)
{
voiceData.reset(voiceIndex);
}
void JavascriptPolyphonicEffect::handleHiseEvent(const HiseEvent &m)
{
if (m.isNoteOn())
return;
HiseEvent c(m);
if (auto n = getActiveNetwork())
{
voiceData.handleHiseEvent(*n, *n->getPolyHandler(), m);
}
}
JavascriptMasterEffect::JavascriptMasterEffect(MainController *mc, const String &id):
JavascriptProcessor(mc),
ProcessorWithScriptingContent(mc),
MasterEffectProcessor(mc, id),
onInitCallback(new SnippetDocument("onInit")),
prepareToPlayCallback(new SnippetDocument("prepareToPlay", "sampleRate blockSize")),
processBlockCallback(new SnippetDocument("processBlock", "channels")),
onControlCallback(new SnippetDocument("onControl", "number value"))
{
initContent();
finaliseModChains();
editorStateIdentifiers.add("contentShown");
editorStateIdentifiers.add("onInitOpen");
editorStateIdentifiers.add("prepareToPlayOpen");
editorStateIdentifiers.add("processBlockOpen");
editorStateIdentifiers.add("onControlOpen");
editorStateIdentifiers.add("externalPopupShown");
getMatrix().setNumAllowedConnections(NUM_MAX_CHANNELS);
for (int i = 0; i < NUM_MAX_CHANNELS; i++)
{
buffers[i] = new VariantBuffer(0);
}
channels.ensureStorageAllocated(16);
channelIndexes.ensureStorageAllocated(16);
channelData = var(channels);
connectionChanged();
}
JavascriptMasterEffect::~JavascriptMasterEffect()
{
clearExternalWindows();
cleanupEngine();
#if USE_BACKEND
if (consoleEnabled)
{
getMainController()->setWatchedScriptProcessor(nullptr, nullptr);
}
#endif
}
Path JavascriptMasterEffect::getSpecialSymbol() const
{
Path path; path.loadPathFromData(HiBinaryData::SpecialSymbols::scriptProcessor, sizeof(HiBinaryData::SpecialSymbols::scriptProcessor)); return path;
}
void JavascriptMasterEffect::connectionChanged()
{
channels.clear();
channelIndexes.clear();
for (int i = 0; i < getMatrix().getNumSourceChannels(); i++)
{
if (getMatrix().getConnectionForSourceChannel(i) >= 0)
{
channels.add(buffers[channelIndexes.size()]);
channelIndexes.add(i);
}
}
auto numChannels = channels.size();
for (auto n : networks)
{
n->setNumChannels(numChannels);
}
channelData = var(channels);
}
ProcessorEditorBody * JavascriptMasterEffect::createEditor(ProcessorEditor *parentEditor)
{
#if USE_BACKEND
return new ScriptingEditor(parentEditor);
#else
ignoreUnused(parentEditor);
jassertfalse;
return nullptr;
#endif
}
JavascriptProcessor::SnippetDocument * JavascriptMasterEffect::getSnippet(int c)
{
Callback ca = (Callback)c;
switch (ca)
{
case Callback::onInit: return onInitCallback;
case Callback::prepareToPlay: return prepareToPlayCallback;
case Callback::processBlock: return processBlockCallback;
case Callback::onControl: return onControlCallback;
case Callback::numCallbacks: return nullptr;
default:
break;
}
return nullptr;
}
const JavascriptProcessor::SnippetDocument * JavascriptMasterEffect::getSnippet(int c) const
{
Callback ca = (Callback)c;
switch (ca)
{
case Callback::onInit: return onInitCallback;
case Callback::prepareToPlay: return prepareToPlayCallback;
case Callback::processBlock: return processBlockCallback;
case Callback::onControl: return onControlCallback;
case Callback::numCallbacks: return nullptr;
default:
break;
}
return nullptr;
}
void JavascriptMasterEffect::registerApiClasses()
{
//content = new ScriptingApi::Content(this);
engineObject = new ScriptingApi::Engine(this);
scriptEngine->registerNativeObject("Content", content.get());
scriptEngine->registerApiClass(engineObject);
scriptEngine->registerApiClass(new ScriptingApi::Console(this));
scriptEngine->registerApiClass(new ScriptingApi::Settings(this));
scriptEngine->registerApiClass(new ScriptingApi::FileSystem(this));
scriptEngine->registerNativeObject("Libraries", new DspFactory::LibraryLoader(this));
scriptEngine->registerNativeObject("Buffer", new VariantBuffer::Factory(64));
}
void JavascriptMasterEffect::postCompileCallback()
{
prepareToPlay(getSampleRate(), getLargestBlockSize());
}
void JavascriptMasterEffect::voicesKilled()
{
if (auto n = getActiveNetwork())
{
n->reset();
}
}
bool JavascriptMasterEffect::hasTail() const
{
if (auto n = getActiveNetwork())
{
return n->hasTail();
}
return false;
}
void JavascriptMasterEffect::prepareToPlay(double sampleRate, int samplesPerBlock)
{
MasterEffectProcessor::prepareToPlay(sampleRate, samplesPerBlock);
connectionChanged();
if (getActiveNetwork() != nullptr)
getActiveNetwork()->prepareToPlay(sampleRate, samplesPerBlock);
if (!prepareToPlayCallback->isSnippetEmpty() && lastResult.wasOk())
{
scriptEngine->setCallbackParameter((int)Callback::prepareToPlay, 0, sampleRate);
scriptEngine->setCallbackParameter((int)Callback::prepareToPlay, 1, samplesPerBlock);
scriptEngine->executeCallback((int)Callback::prepareToPlay, &lastResult);
BACKEND_ONLY(if (!lastResult.wasOk()) debugError(this, lastResult.getErrorMessage()));
}
}
void JavascriptMasterEffect::renderWholeBuffer(AudioSampleBuffer &buffer)
{
if (channelIndexes.size() == 2)
{
MasterEffectProcessor::renderWholeBuffer(buffer);
}
else
{
if (getActiveNetwork() != nullptr)
{
getActiveNetwork()->process(buffer, eventBuffer);
return;
}
if (!processBlockCallback->isSnippetEmpty() && lastResult.wasOk())
{
const int numSamples = buffer.getNumSamples();
jassert(channelIndexes.size() == channels.size());
for (int i = 0; i < channelIndexes.size(); i++)
{
float* d = buffer.getWritePointer(channelIndexes[i], 0);
CHECK_AND_LOG_BUFFER_DATA(this, DebugLogger::Location::ScriptFXRendering, d, true, numSamples);
auto b = channels[i].getBuffer();
if (b != nullptr)
b->referToData(d, numSamples);
}
scriptEngine->setCallbackParameter((int)Callback::processBlock, 0, channelData);
scriptEngine->executeCallback((int)Callback::processBlock, &lastResult);
BACKEND_ONLY(if (!lastResult.wasOk()) debugError(this, lastResult.getErrorMessage()));
}
}
}
void JavascriptMasterEffect::applyEffect(AudioSampleBuffer &b, int startSample, int numSamples)
{
ignoreUnused(startSample);
if (getActiveNetwork() != nullptr)
{
getActiveNetwork()->process(b, eventBuffer);
return;
}
if (!processBlockCallback->isSnippetEmpty() && lastResult.wasOk())
{
jassert(startSample == 0);
CHECK_AND_LOG_ASSERTION(this, DebugLogger::Location::ScriptFXRendering, startSample == 0, startSample);
float *l = b.getWritePointer(0, 0);
float *r = b.getWritePointer(1, 0);
if (auto lb = channels[0].getBuffer())
lb->referToData(l, numSamples);
if (auto rb = channels[1].getBuffer())
rb->referToData(r, numSamples);
scriptEngine->setCallbackParameter((int)Callback::processBlock, 0, channelData);
scriptEngine->executeCallback((int)Callback::processBlock, &lastResult);
BACKEND_ONLY(if (!lastResult.wasOk()) debugError(this, lastResult.getErrorMessage()));
}
}
void JavascriptMasterEffect::setBypassed(bool shouldBeBypassed, NotificationType notifyChangeHandler) noexcept
{
MasterEffectProcessor::setBypassed(shouldBeBypassed, notifyChangeHandler);
if (!shouldBeBypassed)
{
if (auto n = getActiveNetwork())
{
n->reset();
}
}
}
JavascriptVoiceStartModulator::JavascriptVoiceStartModulator(MainController *mc, const String &id, int voiceAmount, Modulation::Mode m) :
JavascriptProcessor(mc),
ProcessorWithScriptingContent(mc),
VoiceStartModulator(mc, id, voiceAmount, m),
Modulation(m)
{
initContent();
onInitCallback = new SnippetDocument("onInit");
onVoiceStartCallback = new SnippetDocument("onVoiceStart", "voiceIndex");
onVoiceStopCallback = new SnippetDocument("onVoiceStop", "voiceIndex");
onControllerCallback = new SnippetDocument("onController");
onControlCallback = new SnippetDocument("onControl", "number value");
editorStateIdentifiers.add("contentShown");
editorStateIdentifiers.add("onInitOpen");
editorStateIdentifiers.add("onVoiceStartOpen");
editorStateIdentifiers.add("onVoiceStopOpen");
editorStateIdentifiers.add("onControllerOpen");
editorStateIdentifiers.add("onControlOpen");
editorStateIdentifiers.add("externalPopupShown");
}
JavascriptVoiceStartModulator::~JavascriptVoiceStartModulator()
{
clearExternalWindows();
cleanupEngine();
#if USE_BACKEND
if (consoleEnabled)
{
getMainController()->setWatchedScriptProcessor(nullptr, nullptr);
}
#endif
}
Path JavascriptVoiceStartModulator::getSpecialSymbol() const
{
Path path; path.loadPathFromData(HiBinaryData::SpecialSymbols::scriptProcessor, sizeof(HiBinaryData::SpecialSymbols::scriptProcessor)); return path;
}
ProcessorEditorBody * JavascriptVoiceStartModulator::createEditor(ProcessorEditor *parentEditor)
{
#if USE_BACKEND
return new ScriptingEditor(parentEditor);
#else
ignoreUnused(parentEditor);
jassertfalse;
return nullptr;
#endif
}
void JavascriptVoiceStartModulator::handleHiseEvent(const HiseEvent& m)
{
currentMidiMessage->setHiseEvent(m);
synthObject->handleNoteCounter(m);
if (m.isNoteOff())
{
if (!onVoiceStopCallback->isSnippetEmpty())
{
scriptEngine->setCallbackParameter(onVoiceStop, 0, 0);
scriptEngine->executeCallback(onVoiceStop, &lastResult);
BACKEND_ONLY(if (!lastResult.wasOk()) debugError(this, lastResult.getErrorMessage()));
}
}
else if (m.isController() && !onControllerCallback->isSnippetEmpty())
{
scriptEngine->executeCallback(onController, &lastResult);
BACKEND_ONLY(if (!lastResult.wasOk()) debugError(this, lastResult.getErrorMessage()));
}
}
float JavascriptVoiceStartModulator::startVoice(int voiceIndex)
{
if (!onVoiceStartCallback->isSnippetEmpty())
{
synthObject->setVoiceGainValue(voiceIndex, 1.0f);
synthObject->setVoicePitchValue(voiceIndex, 1.0f);
scriptEngine->setCallbackParameter(onVoiceStart, 0, voiceIndex);
unsavedValue = (float)scriptEngine->executeCallback(onVoiceStart, &lastResult);
}
return VoiceStartModulator::startVoice(voiceIndex);
}
JavascriptProcessor::SnippetDocument * JavascriptVoiceStartModulator::getSnippet(int c)
{
switch (c)
{
case Callback::onInit: return onInitCallback;
case Callback::onVoiceStart: return onVoiceStartCallback;
case Callback::onVoiceStop: return onVoiceStopCallback;
case Callback::onController: return onControllerCallback;
case Callback::onControl: return onControlCallback;
}
return nullptr;
}
const JavascriptProcessor::SnippetDocument * JavascriptVoiceStartModulator::getSnippet(int c) const
{
switch (c)
{
case Callback::onInit: return onInitCallback;
case Callback::onVoiceStart: return onVoiceStartCallback;
case Callback::onVoiceStop: return onVoiceStopCallback;
case Callback::onController: return onControllerCallback;
case Callback::onControl: return onControlCallback;
}
return nullptr;
}
void JavascriptVoiceStartModulator::registerApiClasses()
{
currentMidiMessage = new ScriptingApi::Message(this);
engineObject = new ScriptingApi::Engine(this);
synthObject = new ScriptingApi::Synth(this, currentMidiMessage.get(), dynamic_cast<ModulatorSynth*>(ProcessorHelpers::findParentProcessor(this, true)));
scriptEngine->registerNativeObject("Content", content.get());
scriptEngine->registerApiClass(currentMidiMessage.get());
scriptEngine->registerApiClass(engineObject.get());
scriptEngine->registerApiClass(new ScriptingApi::Console(this));
scriptEngine->registerApiClass(new ScriptingApi::ModulatorApi(this));
scriptEngine->registerApiClass(synthObject);
}
JavascriptTimeVariantModulator::JavascriptTimeVariantModulator(MainController *mc, const String &id, Modulation::Mode m) :
TimeVariantModulator(mc, id, m),
Modulation(m),
JavascriptProcessor(mc),
ProcessorWithScriptingContent(mc),
buffer(new VariantBuffer(0))
{
initContent();
onInitCallback = new SnippetDocument("onInit");
prepareToPlayCallback = new SnippetDocument("prepareToPlay", "sampleRate samplesPerBlock");
processBlockCallback = new SnippetDocument("processBlock", "buffer");
onNoteOnCallback = new SnippetDocument("onNoteOn");
onNoteOffCallback = new SnippetDocument("onNoteOff");
onControllerCallback = new SnippetDocument("onController");
onControlCallback = new SnippetDocument("onControl", "number value");
editorStateIdentifiers.add("contentShown");
editorStateIdentifiers.add("onInitOpen");
editorStateIdentifiers.add("prepareToPlayOpen");
editorStateIdentifiers.add("processBlockOpen");
editorStateIdentifiers.add("onNoteOnOpen");
editorStateIdentifiers.add("onNoteOffOpen");
editorStateIdentifiers.add("onControllerOpen");
editorStateIdentifiers.add("onControlOpen");
editorStateIdentifiers.add("externalPopupShown");
}
JavascriptTimeVariantModulator::~JavascriptTimeVariantModulator()
{
clearExternalWindows();
cleanupEngine();
onInitCallback = new SnippetDocument("onInit");
prepareToPlayCallback = new SnippetDocument("prepareToPlay", "sampleRate samplesPerBlock");
processBlockCallback = new SnippetDocument("processBlock", "buffer");
onNoteOnCallback = new SnippetDocument("onNoteOn");
onNoteOffCallback = new SnippetDocument("onNoteOff");
onControllerCallback = new SnippetDocument("onController");
onControlCallback = new SnippetDocument("onControl", "number value");
bufferVar = var::undefined();
buffer = nullptr;
#if USE_BACKEND
if (consoleEnabled)
{
getMainController()->setWatchedScriptProcessor(nullptr, nullptr);
}
#endif
}
Path JavascriptTimeVariantModulator::getSpecialSymbol() const
{
Path path; path.loadPathFromData(HiBinaryData::SpecialSymbols::scriptProcessor, sizeof(HiBinaryData::SpecialSymbols::scriptProcessor)); return path;
}
ProcessorEditorBody * JavascriptTimeVariantModulator::createEditor(ProcessorEditor *parentEditor)
{
#if USE_BACKEND
return new ScriptingEditor(parentEditor);
#else
ignoreUnused(parentEditor);
jassertfalse;
return nullptr;
#endif
}
void JavascriptTimeVariantModulator::handleHiseEvent(const HiseEvent &m)
{
if (auto n = getActiveNetwork())
{
HiseEvent c(m);
n->getRootNode()->handleHiseEvent(c);
}
currentMidiMessage->setHiseEvent(m);
synthObject->handleNoteCounter(m);
if (m.isNoteOn())
{
if (!onNoteOnCallback->isSnippetEmpty())
scriptEngine->executeCallback(onNoteOn, &lastResult);
BACKEND_ONLY(if (!lastResult.wasOk()) debugError(this, lastResult.getErrorMessage()));
}
else if (m.isNoteOff())
{
if (!onNoteOffCallback->isSnippetEmpty())
scriptEngine->executeCallback(onNoteOff, &lastResult);
BACKEND_ONLY(if (!lastResult.wasOk()) debugError(this, lastResult.getErrorMessage()));
}
else if (m.isController() && !onControllerCallback->isSnippetEmpty())
{
scriptEngine->executeCallback(onController, &lastResult);
BACKEND_ONLY(if (!lastResult.wasOk()) debugError(this, lastResult.getErrorMessage()));
}
}
void JavascriptTimeVariantModulator::prepareToPlay(double sampleRate, int samplesPerBlock)
{
TimeVariantModulator::prepareToPlay(sampleRate, samplesPerBlock);
if (auto n = getActiveNetwork())
{
n->prepareToPlay(getControlRate(), samplesPerBlock / HISE_EVENT_RASTER);
n->setNumChannels(1);
}
if(internalBuffer.getNumChannels() > 0)
buffer->referToData(internalBuffer.getWritePointer(0), samplesPerBlock);
bufferVar = var(buffer.get());
if (!prepareToPlayCallback->isSnippetEmpty())
{
scriptEngine->setCallbackParameter(Callback::prepare, 0, sampleRate);
scriptEngine->setCallbackParameter(Callback::prepare, 1, samplesPerBlock);
scriptEngine->executeCallback(Callback::prepare, &lastResult);
BACKEND_ONLY(if (!lastResult.wasOk()) debugError(this, lastResult.getErrorMessage()));
}
}
void JavascriptTimeVariantModulator::calculateBlock(int startSample, int numSamples)
{
if (auto n = getActiveNetwork())
{
auto ptr = internalBuffer.getWritePointer(0, startSample);
FloatVectorOperations::clear(ptr, numSamples);
snex::Types::ProcessDataDyn d(&ptr, numSamples, 1);
if (auto s = SimpleReadWriteLock::ScopedTryReadLock(n->getConnectionLock()))
{
if(n->getExceptionHandler().isOk())
n->getRootNode()->process(d);
}
FloatVectorOperations::clip(ptr, ptr, 0.0f, 1.0f, numSamples);
}
else if (!processBlockCallback->isSnippetEmpty() && lastResult.wasOk())
{
buffer->referToData(internalBuffer.getWritePointer(0, startSample), numSamples);
scriptEngine->setCallbackParameter(Callback::processBlock, 0, bufferVar);
scriptEngine->executeCallback(Callback::processBlock, &lastResult);
BACKEND_ONLY(if (!lastResult.wasOk()) debugError(this, lastResult.getErrorMessage()));
}
#if ENABLE_ALL_PEAK_METERS
setOutputValue(internalBuffer.getSample(0, startSample));
#endif
}
JavascriptProcessor::SnippetDocument* JavascriptTimeVariantModulator::getSnippet(int c)
{
switch (c)
{
case Callback::onInit: return onInitCallback;
case Callback::prepare: return prepareToPlayCallback;
case Callback::processBlock: return processBlockCallback;
case Callback::onNoteOn: return onNoteOnCallback;
case Callback::onNoteOff: return onNoteOffCallback;
case Callback::onController: return onControllerCallback;
case Callback::onControl: return onControlCallback;
}
return nullptr;
}
const JavascriptProcessor::SnippetDocument * JavascriptTimeVariantModulator::getSnippet(int c) const
{
switch (c)
{
case Callback::onInit: return onInitCallback;
case Callback::prepare: return prepareToPlayCallback;
case Callback::processBlock: return processBlockCallback;
case Callback::onNoteOn: return onNoteOnCallback;
case Callback::onNoteOff: return onNoteOffCallback;
case Callback::onController: return onControllerCallback;
case Callback::onControl: return onControlCallback;
}
return nullptr;
}
void JavascriptTimeVariantModulator::registerApiClasses()
{
currentMidiMessage = new ScriptingApi::Message(this);
engineObject = new ScriptingApi::Engine(this);
synthObject = new ScriptingApi::Synth(this, currentMidiMessage.get(), dynamic_cast<ModulatorSynth*>(ProcessorHelpers::findParentProcessor(this, true)));
scriptEngine->registerNativeObject("Content", content.get());
scriptEngine->registerApiClass(currentMidiMessage.get());
scriptEngine->registerApiClass(engineObject.get());
scriptEngine->registerApiClass(new ScriptingApi::Console(this));
scriptEngine->registerApiClass(new ScriptingApi::ModulatorApi(this));
scriptEngine->registerApiClass(synthObject);
scriptEngine->registerNativeObject("Libraries", new DspFactory::LibraryLoader(this));
scriptEngine->registerNativeObject("Buffer", new VariantBuffer::Factory(64));
}
void JavascriptTimeVariantModulator::postCompileCallback()
{
prepareToPlay(getSampleRate(), getLargestBlockSize());
}
JavascriptEnvelopeModulator::JavascriptEnvelopeModulator(MainController *mc, const String &id, int numVoices, Modulation::Mode m):
ProcessorWithScriptingContent(mc),
JavascriptProcessor(mc),
EnvelopeModulator(mc, id, numVoices, m),
Modulation(m)
{
setVoiceKillerToUse(this);
initContent();
onInitCallback = new SnippetDocument("onInit");
onControlCallback = new SnippetDocument("onControl", "number value");
for (int i = 0; i < polyManager.getVoiceAmount(); i++) states.add(createSubclassedState(i));
editorStateIdentifiers.add("contentShown");
editorStateIdentifiers.add("onInitOpen");
editorStateIdentifiers.add("onControlOpen");
editorStateIdentifiers.add("externalPopupShown");
}
JavascriptEnvelopeModulator::~JavascriptEnvelopeModulator()
{
cleanupEngine();
clearExternalWindows();
}
Path JavascriptEnvelopeModulator::getSpecialSymbol() const
{
Path path; path.loadPathFromData(HiBinaryData::SpecialSymbols::scriptProcessor, sizeof(HiBinaryData::SpecialSymbols::scriptProcessor)); return path;
}
int JavascriptEnvelopeModulator::getNumActiveVoices() const
{
int counter = 0;
for (int i = 0; i < polyManager.getVoiceAmount(); i++)
{
if (auto ses = static_cast<ScriptEnvelopeState*>(states[i]))
{
if (ses->isPlaying)
counter++;
}
}
return counter;
}
ProcessorEditorBody * JavascriptEnvelopeModulator::createEditor(ProcessorEditor *parentEditor)
{
#if USE_BACKEND
return new ScriptingEditor(parentEditor);
#else
ignoreUnused(parentEditor);
jassertfalse;
return nullptr;
#endif
}
void JavascriptEnvelopeModulator::handleHiseEvent(const HiseEvent &m)
{
currentMidiMessage->setHiseEvent(m);
if (m.isNoteOn())
lastNoteOn = m;
if (auto n = getActiveNetwork())
{
voiceData.handleHiseEvent(*n, *n->getPolyHandler(), m);
}
}
void JavascriptEnvelopeModulator::prepareToPlay(double sampleRate, int samplesPerBlock)
{
EnvelopeModulator::prepareToPlay(sampleRate, samplesPerBlock);
if (auto n = getActiveNetwork())
{
n->prepareToPlay(getControlRate(), samplesPerBlock / HISE_EVENT_RASTER);
n->setNumChannels(1);
}
}
void JavascriptEnvelopeModulator::calculateBlock(int startSample, int numSamples)
{
if (auto n = getActiveNetwork())
{
scriptnode::DspNetwork::VoiceSetter vs(*n, polyManager.getCurrentVoice());
float* ptr = internalBuffer.getWritePointer(0, startSample);
memset(ptr, 0, sizeof(float)*numSamples);
scriptnode::ProcessDataDyn d(&ptr, numSamples, 1);
if (auto s = SimpleReadWriteLock::ScopedTryReadLock(n->getConnectionLock()))
{
if(n->getExceptionHandler().isOk())
n->getRootNode()->process(d);
}
}
#if ENABLE_ALL_PEAK_METERS
setOutputValue(internalBuffer.getSample(0, startSample));
#endif
}
float JavascriptEnvelopeModulator::startVoice(int voiceIndex)
{
ScriptEnvelopeState* state = static_cast<ScriptEnvelopeState*>(states[voiceIndex]);
state->uptime = 0.0f;
state->isPlaying = true;
state->isRingingOff = false;
if (auto n = getActiveNetwork())
{
voiceData.startVoice(*n, *n->getPolyHandler(), voiceIndex, lastNoteOn);
}
return 0.0f;
}
void JavascriptEnvelopeModulator::stopVoice(int voiceIndex)
{
ScriptEnvelopeState* state = static_cast<ScriptEnvelopeState*>(states[voiceIndex]);
state->isRingingOff = true;
}
void JavascriptEnvelopeModulator::reset(int voiceIndex)
{
ScriptEnvelopeState* state = static_cast<ScriptEnvelopeState*>(states[voiceIndex]);
state->uptime = 0.0f;
state->isPlaying = false;
state->isRingingOff = false;
voiceData.reset(voiceIndex);
}
bool JavascriptEnvelopeModulator::isPlaying(int voiceIndex) const
{
ScriptEnvelopeState* state = static_cast<ScriptEnvelopeState*>(states[voiceIndex]);
return state->isPlaying;
}
JavascriptProcessor::SnippetDocument * JavascriptEnvelopeModulator::getSnippet(int c)
{
Callback cb = (Callback)c;
switch (cb)
{
case JavascriptEnvelopeModulator::onInit: return onInitCallback;
case JavascriptEnvelopeModulator::onControl: return onControlCallback;
case JavascriptEnvelopeModulator::numCallbacks:
default:
break;
}
jassertfalse;
return nullptr;
}
const JavascriptProcessor::SnippetDocument * JavascriptEnvelopeModulator::getSnippet(int c) const
{
Callback cb = (Callback)c;
switch (cb)
{
case JavascriptEnvelopeModulator::onInit: return onInitCallback;
case JavascriptEnvelopeModulator::onControl: return onControlCallback;
case JavascriptEnvelopeModulator::numCallbacks:
default:
break;
}
jassertfalse;
return nullptr;
}
void JavascriptEnvelopeModulator::registerApiClasses()
{
currentMidiMessage = new ScriptingApi::Message(this);
engineObject = new ScriptingApi::Engine(this);
synthObject = new ScriptingApi::Synth(this, currentMidiMessage.get(), dynamic_cast<ModulatorSynth*>(ProcessorHelpers::findParentProcessor(this, true)));
scriptEngine->registerNativeObject("Content", content.get());
scriptEngine->registerApiClass(currentMidiMessage.get());
scriptEngine->registerApiClass(engineObject.get());
scriptEngine->registerApiClass(new ScriptingApi::Console(this));
scriptEngine->registerApiClass(new ScriptingApi::ModulatorApi(this));
scriptEngine->registerApiClass(new ScriptingApi::Settings(this));
scriptEngine->registerApiClass(new ScriptingApi::FileSystem(this));
scriptEngine->registerApiClass(synthObject);
scriptEngine->registerNativeObject("Libraries", new DspFactory::LibraryLoader(this));
scriptEngine->registerNativeObject("Buffer", new VariantBuffer::Factory(64));
}
void JavascriptEnvelopeModulator::postCompileCallback()
{
prepareToPlay(getSampleRate(), getLargestBlockSize());
}
JavascriptSynthesiser::JavascriptSynthesiser(MainController *mc, const String &id, int numVoices):
JavascriptProcessor(mc),
ProcessorWithScriptingContent(mc),
ModulatorSynth(mc, id, numVoices)
{
initContent();
onInitCallback = new SnippetDocument("onInit");
onControlCallback = new SnippetDocument("onControl", "number value");
editorStateIdentifiers.add("contentShown");
editorStateIdentifiers.add("onInitOpen");
editorStateIdentifiers.add("onControlOpen");
modChains += { this, "Extra1" };
modChains += { this, "Extra2" };
finaliseModChains();
modChains[Extra1].setIncludeMonophonicValuesInVoiceRendering(true);
modChains[Extra1].setExpandToAudioRate(false);
modChains[Extra2].setIncludeMonophonicValuesInVoiceRendering(true);
modChains[Extra2].setExpandToAudioRate(false);
modChains[Extra1].getChain()->setColour(Colour(0xFF888888));
modChains[Extra2].getChain()->setColour(Colour(0xFF888888));
for (int i = 0; i < numVoices; i++)
{
addVoice(new Voice(this));
}
addSound(new Sound());
}
JavascriptSynthesiser::~JavascriptSynthesiser()
{
}
juce::Path JavascriptSynthesiser::getSpecialSymbol() const
{
Path path; path.loadPathFromData(HiBinaryData::SpecialSymbols::scriptProcessor, sizeof(HiBinaryData::SpecialSymbols::scriptProcessor)); return path;
}
hise::ProcessorEditorBody * JavascriptSynthesiser::createEditor(ProcessorEditor *parentEditor)
{
#if USE_BACKEND
return new ScriptingEditor(parentEditor);
#else
ignoreUnused(parentEditor);
jassertfalse;
return nullptr;
#endif
}
hise::JavascriptProcessor::SnippetDocument * JavascriptSynthesiser::getSnippet(int c)
{
Callback ca = (Callback)c;
switch (ca)
{
case Callback::onInit: return onInitCallback;
case Callback::onControl: return onControlCallback;
case Callback::numCallbacks: return nullptr;
default:
break;
}
return nullptr;
}
const hise::JavascriptProcessor::SnippetDocument * JavascriptSynthesiser::getSnippet(int c) const
{
Callback ca = (Callback)c;
switch (ca)
{
case Callback::onInit: return onInitCallback;
case Callback::onControl: return onControlCallback;
case Callback::numCallbacks: return nullptr;
default:
break;
}
return nullptr;
}
void JavascriptSynthesiser::registerApiClasses()
{
engineObject = new ScriptingApi::Engine(this);
scriptEngine->registerNativeObject("Content", content.get());
scriptEngine->registerApiClass(engineObject);
scriptEngine->registerApiClass(new ScriptingApi::Console(this));
scriptEngine->registerApiClass(new ScriptingApi::Settings(this));
scriptEngine->registerApiClass(new ScriptingApi::FileSystem(this));
scriptEngine->registerNativeObject("Libraries", new DspFactory::LibraryLoader(this));
scriptEngine->registerNativeObject("Buffer", new VariantBuffer::Factory(64));
}
void JavascriptSynthesiser::postCompileCallback()
{
prepareToPlay(getSampleRate(), getLargestBlockSize());
}
void JavascriptSynthesiser::preHiseEventCallback(HiseEvent &e)
{
ModulatorSynth::preHiseEventCallback(e);
if (e.isNoteOn())
return; // will be handled by preStartVoice
if (auto n = getActiveNetwork())
{
voiceData.handleHiseEvent(*n, *n->getPolyHandler(), e);
}
}
void JavascriptSynthesiser::preStartVoice(int voiceIndex, const HiseEvent& e)
{
ModulatorSynth::preStartVoice(voiceIndex, e);
if (auto n = getActiveNetwork())
{
static_cast<Voice*>(getVoice(voiceIndex))->setVoiceStartDataForNextRenderCallback();
currentVoiceStartSample = jlimit(0, getLargestBlockSize(), e.getTimeStamp());
}
}
void JavascriptSynthesiser::prepareToPlay(double newSampleRate, int samplesPerBlock)
{
ModulatorSynth::prepareToPlay(newSampleRate, samplesPerBlock);
if (newSampleRate == -1.0)
return;
if (auto n = getActiveNetwork())
{
if (auto vk = ProcessorHelpers::getFirstProcessorWithType<ScriptnodeVoiceKiller>(gainChain))
setVoiceKillerToUse(vk);
n->prepareToPlay(newSampleRate, (double)samplesPerBlock);
n->setNumChannels(getMatrix().getNumSourceChannels());
}
}
void JavascriptSynthesiser::restoreFromValueTree(const ValueTree &v)
{
ModulatorSynth::restoreFromValueTree(v);
if (auto vk = ProcessorHelpers::getFirstProcessorWithType<ScriptnodeVoiceKiller>(gainChain))
setVoiceKillerToUse(vk);
restoreScript(v);
restoreContent(v);
}
void JavascriptSynthesiser::Voice::calculateBlock(int startSample, int numSamples)
{
if (auto n = synth->getActiveNetwork())
{
if (isVoiceStart)
{
n->setVoiceKiller(synth->vk);
synth->voiceData.startVoice(*n, *n->getPolyHandler(), getVoiceIndex(), getCurrentHiseEvent());
isVoiceStart = false;
}
float* channels[NUM_MAX_CHANNELS];
voiceBuffer.clear();
int numChannels = voiceBuffer.getNumChannels();
memcpy(channels, voiceBuffer.getArrayOfWritePointers(), sizeof(float*) * numChannels);
for (int i = 0; i < numChannels; i++)
channels[i] += startSample;
scriptnode::ProcessDataDyn d(channels, numSamples, numChannels);
{
scriptnode::DspNetwork::VoiceSetter vs(*n, getVoiceIndex());
n->process(d);
}
if (auto modValues = getOwnerSynth()->getVoiceGainValues())
{
for(int i = 0; i < voiceBuffer.getNumChannels(); i++)
FloatVectorOperations::multiply(voiceBuffer.getWritePointer(i, startSample), modValues + startSample, numSamples);
}
else
{
const float gainValue = getOwnerSynth()->getConstantGainModValue();
for (int i = 0; i < voiceBuffer.getNumChannels(); i++)
FloatVectorOperations::multiply(voiceBuffer.getWritePointer(i, startSample), gainValue, numSamples);
}
getOwnerSynth()->effectChain->renderVoice(voiceIndex, voiceBuffer, startSample, numSamples);
}
}
hise::ProcessorEditorBody * ScriptnodeVoiceKiller::createEditor(ProcessorEditor *parentEditor)
{
#if USE_BACKEND
return new EmptyProcessorEditorBody(parentEditor);;
#else
ignoreUnused(parentEditor);
return nullptr;
#endif
}
void VoiceDataStack::reset(int voiceIndex)
{
for (int i = 0; i < voiceNoteOns.size(); i++)
{
if (voiceNoteOns[i].voiceIndex == voiceIndex)
{
voiceNoteOns.removeElement(i--);
break;
}
}
}
} // namespace hise
| 28.248466 | 154 | 0.738473 | Matt-Dub |
f65649ca1352400cf3cc53daee9b4085b521cf68 | 572 | cpp | C++ | hackerrank/non-divisible-subset/solution.cpp | SamProkopchuk/coding-problems | fa0ca2c05ac90e41945de1a5751e5545a8459ac4 | [
"MIT"
] | null | null | null | hackerrank/non-divisible-subset/solution.cpp | SamProkopchuk/coding-problems | fa0ca2c05ac90e41945de1a5751e5545a8459ac4 | [
"MIT"
] | null | null | null | hackerrank/non-divisible-subset/solution.cpp | SamProkopchuk/coding-problems | fa0ca2c05ac90e41945de1a5751e5545a8459ac4 | [
"MIT"
] | null | null | null | #include <iostream>
#include <unordered_map>
using namespace std;
int main() {
int n, mod, temp, res;
cin >> n >> mod;
unordered_map<int, int> remcount;
for (int posrem = 0; posrem < mod; posrem++) {
// Simple defaultdict-like behavior
remcount[posrem] = 0;
}
for (int c = 0; c < n; c++) {
cin >> temp;
remcount[temp % mod] += 1;
}
res = (remcount[0] > 0) + (mod % 2 == 0 && remcount[mod / 2]);
for (int rem = 1; rem < (mod + 1) / 2; rem++) {
res += max(remcount[rem], remcount[mod - rem]);
}
cout << res << endl;
return 0;
}
| 22.88 | 64 | 0.547203 | SamProkopchuk |
f657235d328c6925462f7c4b577082034446ce78 | 1,758 | cc | C++ | tsdf_plusplus/src/core/segment.cc | TheMangalex/tsdf-plusplus | aefb7fa40b53475ce424d5082b3045587bbb5de3 | [
"MIT"
] | 91 | 2021-05-18T03:15:18.000Z | 2022-03-28T01:53:02.000Z | tsdf_plusplus/src/core/segment.cc | ali-robot/tsdf-plusplus | 602f2aeec267a82ac3c5d88ef3eabba2ea2f3c04 | [
"MIT"
] | 4 | 2021-05-18T06:10:20.000Z | 2022-01-25T11:38:33.000Z | tsdf_plusplus/src/core/segment.cc | cmrobotics/tsdf-plusplus | 9cb15273b2bd5e7b13f67ef563856d2f92cd34dd | [
"MIT"
] | 16 | 2021-05-18T02:17:48.000Z | 2022-03-07T02:57:01.000Z | // Copyright (c) 2020- Margarita Grinvald, Autonomous Systems Lab, ETH Zurich
// Licensed under the MIT License (see LICENSE for details)
#include "tsdf_plusplus/core/segment.h"
#include <pcl/common/centroid.h>
Segment::Segment(const pcl::PointCloud<InputPointType>& pointcloud_pcl,
const voxblox::Transformation& T_G_C)
: T_G_C_(T_G_C), semantic_class_(pointcloud_pcl.points[0].semantic_class) {
pointcloud_ = pointcloud_pcl;
convertPointcloud();
}
Segment::Segment(const pcl::PointCloud<GTInputPointType>& pointcloud_pcl,
const voxblox::Transformation& T_G_C)
: T_G_C_(T_G_C),
object_id_(pointcloud_pcl.points[0].label + 1),
semantic_class_(BackgroundClass) {
pcl::copyPointCloud(pointcloud_pcl, pointcloud_);
convertPointcloud();
}
void Segment::convertPointcloud() {
points_C_.clear();
colors_.clear();
points_C_.reserve(pointcloud_.points.size());
colors_.reserve(pointcloud_.points.size());
for (size_t i = 0u; i < pointcloud_.points.size(); ++i) {
if (!std::isfinite(pointcloud_.points[i].x) ||
!std::isfinite(pointcloud_.points[i].y) ||
!std::isfinite(pointcloud_.points[i].z)) {
continue;
}
points_C_.push_back(voxblox::Point(pointcloud_.points[i].x,
pointcloud_.points[i].y,
pointcloud_.points[i].z));
colors_.push_back(
voxblox::Color(pointcloud_.points[i].r, pointcloud_.points[i].g,
pointcloud_.points[i].b, pointcloud_.points[i].a));
}
Eigen::Vector4f centroid_c;
pcl::compute3DCentroid(pointcloud_, centroid_c);
centroid_ =
T_G_C_ * voxblox::Point(centroid_c.x(), centroid_c.y(), centroid_c.z());
}
| 33.169811 | 79 | 0.661547 | TheMangalex |
f65767d98e7cbc5ab4836a02bd29a882e9f2f24a | 183 | cpp | C++ | src/GameOptions.cpp | ceilingfans/pnut-butta | d2f5d6f1f1379b4324d2b58edf102e30a6b792cb | [
"MIT"
] | null | null | null | src/GameOptions.cpp | ceilingfans/pnut-butta | d2f5d6f1f1379b4324d2b58edf102e30a6b792cb | [
"MIT"
] | null | null | null | src/GameOptions.cpp | ceilingfans/pnut-butta | d2f5d6f1f1379b4324d2b58edf102e30a6b792cb | [
"MIT"
] | null | null | null | #include "GameOptions.hpp"
bool isValidOption(const GameOptions& opt)
{
return opt.playerCount > 0 && opt.substringLength >= 2 && !opt.options.empty() && opt.options.size() >= 2;
} | 30.5 | 108 | 0.693989 | ceilingfans |
f658eb874ea759e96055caee9956cd764bbd35c7 | 3,889 | cpp | C++ | Libraries/xcassets/Sources/Asset/CubeTextureSet.cpp | djgalloway/xcbuild | 936df10e59e5f5d531efca8bd48e445d88e78e0c | [
"BSD-2-Clause-NetBSD"
] | 9 | 2018-04-30T23:18:27.000Z | 2021-06-20T15:13:38.000Z | Libraries/xcassets/Sources/Asset/CubeTextureSet.cpp | djgalloway/xcbuild | 936df10e59e5f5d531efca8bd48e445d88e78e0c | [
"BSD-2-Clause-NetBSD"
] | null | null | null | Libraries/xcassets/Sources/Asset/CubeTextureSet.cpp | djgalloway/xcbuild | 936df10e59e5f5d531efca8bd48e445d88e78e0c | [
"BSD-2-Clause-NetBSD"
] | 4 | 2018-10-10T19:44:17.000Z | 2020-01-12T11:56:31.000Z | /**
Copyright (c) 2015-present, Facebook, Inc.
All rights reserved.
This source code is licensed under the BSD-style license found in the
LICENSE file in the root directory of this source tree. An additional grant
of patent rights can be found in the PATENTS file in the same directory.
*/
#include <xcassets/Asset/CubeTextureSet.h>
#include <plist/Array.h>
#include <plist/Dictionary.h>
#include <plist/String.h>
#include <plist/Keys/Unpack.h>
using xcassets::Asset::CubeTextureSet;
bool CubeTextureSet::Texture::
parse(plist::Dictionary const *dict)
{
std::unordered_set<std::string> seen;
auto unpack = plist::Keys::Unpack("CubeTextureSetTexture", dict, &seen);
auto CS = unpack.cast <plist::String> ("color-space");
auto CF = unpack.cast <plist::String> ("cube-face");
auto F = unpack.cast <plist::String> ("filename");
auto GFS = unpack.cast <plist::String> ("graphics-feature-set");
auto I = unpack.cast <plist::String> ("idiom");
auto M = unpack.cast <plist::String> ("memory");
auto PF = unpack.cast <plist::String> ("pixel-format");
auto S = unpack.cast <plist::String> ("scale");
if (!unpack.complete(true)) {
fprintf(stderr, "%s", unpack.errorText().c_str());
}
if (CS != nullptr) {
_colorSpace = Slot::ColorSpaces::Parse(CS->value());
}
if (CF != nullptr) {
_cubeFace = CubeFaces::Parse(CF->value());
}
if (F != nullptr) {
_fileName = F->value();
}
if (GFS != nullptr) {
_graphicsFeatureSet = Slot::GraphicsFeatureSets::Parse(GFS->value());
}
if (I != nullptr) {
_idiom = Slot::Idioms::Parse(I->value());
}
if (M != nullptr) {
_memory = Slot::MemoryRequirements::Parse(M->value());
}
if (PF != nullptr) {
_pixelFormat = TexturePixelFormats::Parse(PF->value());
}
if (S != nullptr) {
_scale = Slot::Scale::Parse(S->value());
}
return true;
}
bool CubeTextureSet::
parse(plist::Dictionary const *dict, std::unordered_set<std::string> *seen, bool check)
{
if (!Asset::parse(dict, seen, false)) {
return false;
}
auto unpack = plist::Keys::Unpack("CubeTextureSet", dict, seen);
auto P = unpack.cast <plist::Dictionary> ("properties");
auto Ts = unpack.cast <plist::Array> ("textures");
if (!unpack.complete(check)) {
fprintf(stderr, "%s", unpack.errorText().c_str());
}
if (P != nullptr) {
std::unordered_set<std::string> seen;
auto unpack = plist::Keys::Unpack("Properties", P, &seen);
auto I = unpack.cast <plist::String> ("interpretation");
auto O = unpack.cast <plist::String> ("origin");
auto ODRT = unpack.cast <plist::Array> ("on-demand-resource-tags");
if (!unpack.complete(true)) {
fprintf(stderr, "%s", unpack.errorText().c_str());
}
if (I != nullptr) {
_interpretation = TextureInterpretations::Parse(I->value());
}
if (O != nullptr) {
_origin = TextureOrigins::Parse(O->value());
}
if (ODRT != nullptr) {
_onDemandResourceTags = std::vector<std::string>();
_onDemandResourceTags->reserve(ODRT->count());
for (size_t n = 0; n < ODRT->count(); n++) {
if (auto string = ODRT->value<plist::String>(n)) {
_onDemandResourceTags->push_back(string->value());
}
}
}
}
if (Ts != nullptr) {
_textures = std::vector<Texture>();
for (size_t n = 0; n < Ts->count(); ++n) {
if (auto dict = Ts->value<plist::Dictionary>(n)) {
Texture texture;
if (texture.parse(dict)) {
_textures->push_back(texture);
}
}
}
}
return true;
}
| 28.807407 | 87 | 0.568527 | djgalloway |
f65967a614d415e3dd4256e6d33476b1d14e53de | 2,729 | hpp | C++ | include/tudocomp/compressors/MTFCompressor.hpp | dominiKoeppl/tudocomp | b5512f85f6b3408fb88e19c08899ec4c2716c642 | [
"ECL-2.0",
"Apache-2.0"
] | 17 | 2017-03-04T13:04:49.000Z | 2021-12-03T06:58:20.000Z | include/tudocomp/compressors/MTFCompressor.hpp | dominiKoeppl/tudocomp | b5512f85f6b3408fb88e19c08899ec4c2716c642 | [
"ECL-2.0",
"Apache-2.0"
] | 27 | 2016-01-22T18:31:37.000Z | 2021-11-27T10:50:40.000Z | include/tudocomp/compressors/MTFCompressor.hpp | dominiKoeppl/tudocomp | b5512f85f6b3408fb88e19c08899ec4c2716c642 | [
"ECL-2.0",
"Apache-2.0"
] | 16 | 2017-03-14T12:46:51.000Z | 2021-06-25T18:19:50.000Z | #pragma once
#include <tudocomp/util.hpp>
#include <tudocomp/Compressor.hpp>
#include <tudocomp/Env.hpp>
#include <numeric>
#include <tudocomp/def.hpp>
namespace tdc {
/**
* Encodes a character 'v' by Move-To-Front Coding
* Needs and modifies a lookup table storing the last-used characters
*/
template<class value_type = uliteral_t>
value_type mtf_encode_char(const value_type v, value_type*const table, const size_t table_size) {
for(size_t i = 0; i < table_size; ++i) {
if(table[i] == v) {
for(size_t j = i; j > 0; --j) {
table[j] = table[j-1];
}
table[0] = v;
return i;
}
}
DCHECK(false) << v << "(" << static_cast<size_t>(static_cast<typename std::make_unsigned<value_type>::type>(v)) << " not in " << arr_to_debug_string(table,table_size);
return 0;
}
/**
* Decodes a character encoded as 'v' by Move-To-Front Coding
* Needs and modifies a lookup table storing the last-used characters
*/
template<class value_type = uliteral_t>
value_type mtf_decode_char(const value_type v, value_type*const table) {
const value_type return_value = table[v];
for(size_t j = v; j > 0; --j) {
table[j] = table[j-1];
}
table[0] = return_value;
return return_value;
}
template<class char_type = uliteral_t>
void mtf_encode(std::basic_istream<char_type>& is, std::basic_ostream<char_type>& os) {
typedef typename std::make_unsigned<char_type>::type value_type; // -> default: uint8_t
static constexpr size_t table_size = std::numeric_limits<value_type>::max()+1;
value_type table[table_size];
std::iota(table, table+table_size, 0);
char_type c;
while(is.get(c)) {
os << mtf_encode_char(static_cast<value_type>(c), table, table_size);
}
}
template<class char_type = uliteral_t>
void mtf_decode(std::basic_istream<char_type>& is, std::basic_ostream<char_type>& os) {
typedef typename std::make_unsigned<char_type>::type value_type; // -> default: uint8_t
static constexpr size_t table_size = std::numeric_limits<value_type>::max()+1;
value_type table[table_size];
std::iota(table, table+table_size, 0);
char_type c;
while(is.get(c)) {
os << mtf_decode_char(static_cast<value_type>(c), table);
}
}
class MTFCompressor : public Compressor {
public:
inline static Meta meta() {
Meta m("compressor", "mtf", "Move To Front Compressor");
return m;
}
inline MTFCompressor(Env&& env)
: Compressor(std::move(env)) {
}
inline virtual void compress(Input& input, Output& output) override {
auto is = input.as_stream();
auto os = output.as_stream();
mtf_encode(is,os);
}
inline virtual void decompress(Input& input, Output& output) override {
auto is = input.as_stream();
auto os = output.as_stream();
mtf_decode(is,os);
}
};
}//ns
| 28.427083 | 168 | 0.698791 | dominiKoeppl |
2cecaf0734df6cb043c486468da5daace582823e | 1,663 | cc | C++ | paddle/fluid/distributed/collective/NCCLTools.cc | L-Net-1992/Paddle | 4d0ca02ba56760b456f3d4b42a538555b9b6c307 | [
"Apache-2.0"
] | 11 | 2016-08-29T07:43:26.000Z | 2016-08-29T07:51:24.000Z | paddle/fluid/distributed/collective/NCCLTools.cc | L-Net-1992/Paddle | 4d0ca02ba56760b456f3d4b42a538555b9b6c307 | [
"Apache-2.0"
] | null | null | null | paddle/fluid/distributed/collective/NCCLTools.cc | L-Net-1992/Paddle | 4d0ca02ba56760b456f3d4b42a538555b9b6c307 | [
"Apache-2.0"
] | 1 | 2021-09-24T11:23:36.000Z | 2021-09-24T11:23:36.000Z | // Copyright (c) 2022 PaddlePaddle Authors. All Rights Reserved.
//
// Licensed under the Apache License, Version 2.0 (the "License");
// you may not use this file except in compliance with the License.
// You may obtain a copy of the License at
//
// http://www.apache.org/licenses/LICENSE-2.0
//
// Unless required by applicable law or agreed to in writing, software
// distributed under the License is distributed on an "AS IS" BASIS,
// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
// See the License for the specific language governing permissions and
// limitations under the License.
#include "paddle/fluid/distributed/collective/NCCLTools.h"
#include "paddle/fluid/distributed/collective/Types.h"
namespace paddle {
namespace distributed {
ncclRedOp_t ToNCCLRedType(ReduceOp reduction) {
static const std::map<ReduceOp, ncclRedOp_t> red_type = {
{ReduceOp::MIN, ncclMin},
{ReduceOp::MAX, ncclMax},
{ReduceOp::SUM, ncclSum},
{ReduceOp::PRODUCT, ncclProd},
};
auto it = red_type.find(reduction);
PADDLE_ENFORCE_EQ(it != red_type.end(), true,
platform::errors::InvalidArgument(
"Invalid nccl reduction. Must be ncclMin | ncclMax | "
"ncclProd | ncclSum"));
return it->second;
}
std::string SerializeNCCLUniqueId(const ncclUniqueId& ncclID) {
const uint8_t* bytes = reinterpret_cast<const uint8_t*>(&ncclID);
std::ostringstream oss;
for (auto i = 0; i < NCCL_UNIQUE_ID_BYTES; ++i) {
oss << std::hex << static_cast<int>(bytes[i]);
}
return oss.str();
}
} // namespace distributed
} // namespace paddle
| 34.645833 | 78 | 0.689116 | L-Net-1992 |
2cf243e0ff44f73c7888a0199c24ba62cea38e16 | 3,101 | cpp | C++ | src/thunderbots/software/ai/hl/stp/evaluation/calc_best_shot.cpp | FSXAC/Software | 3754f5ec2c513906f66a05d4399aca516d03ba9f | [
"MIT"
] | null | null | null | src/thunderbots/software/ai/hl/stp/evaluation/calc_best_shot.cpp | FSXAC/Software | 3754f5ec2c513906f66a05d4399aca516d03ba9f | [
"MIT"
] | null | null | null | src/thunderbots/software/ai/hl/stp/evaluation/calc_best_shot.cpp | FSXAC/Software | 3754f5ec2c513906f66a05d4399aca516d03ba9f | [
"MIT"
] | null | null | null | #include "ai/hl/stp/evaluation/calc_best_shot.h"
#include "geom/util.h"
namespace Evaluation
{
std::pair<Point, Angle> calcBestShotOnEnemyGoal(const Field &f,
const std::vector<Point> &obstacles,
const Point &p, double radius)
{
// Calculate the location of goalpost then use angleSweepCircle function to get
// the pair
const Point p1 = f.enemyGoalpostNeg();
const Point p2 = f.enemyGoalpostPos();
return angleSweepCircles(p, p1, p2, obstacles, radius);
}
std::vector<std::pair<Point, Angle>> calcBestShotOnEnemyGoalAll(
const Field &f, const std::vector<Point> &obstacles, const Point &p,
double radius)
{
const Point p1 = f.enemyGoalpostNeg();
const Point p2 = f.enemyGoalpostPos();
return angleSweepCirclesAll(p, p1, p2, obstacles, radius);
}
std::pair<Point, Angle> calcBestShotOnEnemyGoal(const World &world,
const Point &point, double radius)
{
std::vector<Point> obstacles;
const Team &enemy = world.enemyTeam();
const Team &friendly = world.friendlyTeam();
obstacles.reserve(enemy.numRobots() + friendly.numRobots());
// create a vector of points for all the robots except the shooting one
for (const Robot &i : enemy.getAllRobots())
{
obstacles.emplace_back(i.position());
}
for (const Robot &fpl : friendly.getAllRobots())
{
if (fpl.position() == point)
{
continue;
}
obstacles.emplace_back(fpl.position());
}
std::pair<Point, Angle> best_shot =
calcBestShotOnEnemyGoal(world.field(), obstacles, point, radius);
// if there is no good shot at least make the
// target within the goal area
if (best_shot.second == Angle::zero())
{
Point temp = world.field().enemyGoal();
best_shot.first = temp;
}
return best_shot;
}
std::vector<std::pair<Point, Angle>> calcBestShotOnEnemyGoalAll(const World &world,
const Point &point,
double radius)
{
std::vector<Point> obstacles;
const Team &enemy = world.enemyTeam();
const Team &friendly = world.friendlyTeam();
obstacles.reserve(enemy.numRobots() + friendly.numRobots());
for (const Robot &i : enemy.getAllRobots())
{
obstacles.push_back(i.position());
}
for (const Robot &fpl : friendly.getAllRobots())
{
if (fpl.position() == point)
{
continue;
}
obstacles.push_back(fpl.position());
}
return calcBestShotOnEnemyGoalAll(world.field(), obstacles, point, radius);
}
} // namespace Evaluation
| 37.361446 | 88 | 0.538858 | FSXAC |
2cf3c08183e51e9c16b5bc6a416df1032a818c7e | 98 | cpp | C++ | core/utilities.cpp | evias/web-irc-docbot | ffc05223eb580a363188dc361938d23b141c6091 | [
"BSD-3-Clause"
] | 1 | 2021-08-28T01:42:34.000Z | 2021-08-28T01:42:34.000Z | core/utilities.cpp | evias/web-irc-docbot | ffc05223eb580a363188dc361938d23b141c6091 | [
"BSD-3-Clause"
] | null | null | null | core/utilities.cpp | evias/web-irc-docbot | ffc05223eb580a363188dc361938d23b141c6091 | [
"BSD-3-Clause"
] | 1 | 2015-03-24T15:45:04.000Z | 2015-03-24T15:45:04.000Z | #include "utilities.hpp"
using namespace std;
using namespace evias;
using namespace utilities;
| 14 | 26 | 0.795918 | evias |
2cfb9af139ad425a03cf71bd0daefa032bb9e9dd | 1,568 | cpp | C++ | 6 复试/1 机试/资料/清华计算机考研机试/2018/cong.cpp | ladike/912_project | 5178c1c93ac6ca30ffc72dd689f5c6932704b4ab | [
"MIT"
] | 1 | 2022-03-02T16:05:49.000Z | 2022-03-02T16:05:49.000Z | 6 复试/1 机试/资料/清华计算机考研机试/2018/cong.cpp | ladike/912_project | 5178c1c93ac6ca30ffc72dd689f5c6932704b4ab | [
"MIT"
] | null | null | null | 6 复试/1 机试/资料/清华计算机考研机试/2018/cong.cpp | ladike/912_project | 5178c1c93ac6ca30ffc72dd689f5c6932704b4ab | [
"MIT"
] | null | null | null | # include<iostream>
# include<map>
# include<vector>
using namespace std;
typedef struct{int x,y;} position;
typedef struct{int id,f;} idfight;
typedef struct{int id;position p;int d;int f;bool live;} cong;
typedef vector<cong> conglist;
conglist all_cong;
map<int,vector<idfight> >war_map;
int n,m,k,times;
void init(){
cin>>n>>m>>k;
for(int i=0;i<n;i++){
int x,y,d,f;
cin >> x >>y>>d>>f;
cong c1 ={i,{x,y},d,f,1};
all_cong.push_back(c1);
}
cin >> times;
}
void action(cong &c){
if(c.live){
switch(c.d){
case 0: if(c.p.y==m) c.d=1;else c.p.y++;break;
case 1: if(c.p.y==1) c.d=0;else c.p.y--;break;
case 2: if(c.p.x==1) c.d=3;else c.p.x--;break;
case 3: if(c.p.y==n) c.d=2;else c.p.x++;break;
default:;break;
}
int pi = c.p.x*1000+c.p.y;
idfight idf = {c.id,c.f};
war_map[pi].push_back(idf);
}
}
void printans(){
for(vector<cong>::iterator i = all_cong.begin();i!=all_cong.end();i++)
cout<<(*i).p.y<<" "<<(*i).p.x<<endl;
}
void fight(){
map<int,vector<idfight> >::iterator it;
it = war_map.begin();
while(it!=war_map.end()){
if((*it).second.size()>1){
int max = 0;
for(vector<idfight>::iterator i = (*it).second.begin();i!=(*it).second.end();i++){
if((*i).f>max)max = (*i).f;
}
for(vector<idfight>::iterator i = (*it).second.begin();i!=(*it).second.end();i++){
if((*i).f<max) all_cong[(*i).id].live=0;
}
}
it++;
}
}
int main() {
init();
while(times--){
for(vector<cong>::iterator i = all_cong.begin();i!=all_cong.end();i++){
action(*i);
}
fight();
war_map.clear();
}
printans();
return 0;
} | 23.402985 | 87 | 0.586097 | ladike |
2cfe0fd3dda379a720e73736d58c1f0a8eb56baf | 103 | cpp | C++ | src/uniform-initialization-too-few-initializers.cpp | zzlc/cxx11tests | d471b3f8b96548c762be6b7e410abe56a57811ae | [
"MIT"
] | 48 | 2015-01-06T20:50:45.000Z | 2021-02-15T02:48:32.000Z | src/uniform-initialization-too-few-initializers.cpp | zzlc/cxx11tests | d471b3f8b96548c762be6b7e410abe56a57811ae | [
"MIT"
] | 3 | 2016-01-19T15:02:19.000Z | 2019-04-29T08:51:13.000Z | src/uniform-initialization-too-few-initializers.cpp | zzlc/cxx11tests | d471b3f8b96548c762be6b7e410abe56a57811ae | [
"MIT"
] | 24 | 2015-02-13T17:40:04.000Z | 2019-12-03T06:59:03.000Z | // Check if too few initializers are supported
struct Point3D {
int x, y, z;
};
Point3D p = {1, 2};
| 14.714286 | 46 | 0.640777 | zzlc |
2cfe6152d781ead5b251bb4a0c32fc277b8a1c1b | 965 | cpp | C++ | oli/vii2018puzzle/main.cpp | rockoanna/nirvana | 81fadbe66b0a24244feec312c6f7fe5c8effccaa | [
"MIT"
] | null | null | null | oli/vii2018puzzle/main.cpp | rockoanna/nirvana | 81fadbe66b0a24244feec312c6f7fe5c8effccaa | [
"MIT"
] | 12 | 2019-09-04T10:38:24.000Z | 2019-12-08T18:09:41.000Z | oli/vii2018puzzle/main.cpp | rockoanna/nirvana | 81fadbe66b0a24244feec312c6f7fe5c8effccaa | [
"MIT"
] | null | null | null | #include <iostream>
#include <vector>
using namespace std;
int main()
{
int n;
cin >> n;
vector<int> pieces(n);
for(int i = 0; i < n; i++)
{
cin >> pieces[i];
}
int res = 0;
for(int i = 0; i < n - 1; i++)
{
for(int j = i + 1; j < n; j++)
{
bool ok = true;
int nr1 = pieces[i];
int nr2 = pieces[j];
int x = nr1 % 10 + nr2 % 10;
nr1 = nr1 / 10;
nr2 = nr2 / 10;
while(nr1 != 0)
{
if(nr1 % 10 + nr2 % 10 == x)
{
nr1 = nr1 / 10;
nr2 = nr2 / 10;
}
else
{
ok = false;
break;
}
}
if(ok == true)
{
res += 1;
}
}
}
cout << res << endl;
return 0;
}
| 16.929825 | 44 | 0.288083 | rockoanna |
fa0127da60d6209d0864b825a6f2927fd44126a7 | 318 | cpp | C++ | 5e/C++11/354_bind.cpp | mallius/CppPrimer | 0285fabe5934492dfed0a9cf67ba5650982a5f76 | [
"MIT"
] | null | null | null | 5e/C++11/354_bind.cpp | mallius/CppPrimer | 0285fabe5934492dfed0a9cf67ba5650982a5f76 | [
"MIT"
] | null | null | null | 5e/C++11/354_bind.cpp | mallius/CppPrimer | 0285fabe5934492dfed0a9cf67ba5650982a5f76 | [
"MIT"
] | 1 | 2022-01-25T15:51:34.000Z | 2022-01-25T15:51:34.000Z | #include <iostream>
#include <functional>
using namespace std;
using namespace std::placeholders;
bool check_size(const string& s, string::size_type sz)
{
return s.size() >= sz;
}
int main(void)
{
auto check6 = bind(check_size, _1, 6);
string s = "hello";
bool b1 = check6(s);
cout << b1 << endl;
return 0;
}
| 15.9 | 54 | 0.672956 | mallius |
fa02242491b1549964e6d4be74b9a0df7f604474 | 3,152 | cc | C++ | gpu/ipc/common/gpu_surface_tracker.cc | xzhan96/chromium.src | 1bd0cf3997f947746c0fc5406a2466e7b5f6159e | [
"BSD-3-Clause-No-Nuclear-License-2014",
"BSD-3-Clause"
] | 1 | 2021-01-07T18:51:03.000Z | 2021-01-07T18:51:03.000Z | gpu/ipc/common/gpu_surface_tracker.cc | emilio/chromium.src | 1bd0cf3997f947746c0fc5406a2466e7b5f6159e | [
"BSD-3-Clause-No-Nuclear-License-2014",
"BSD-3-Clause"
] | null | null | null | gpu/ipc/common/gpu_surface_tracker.cc | emilio/chromium.src | 1bd0cf3997f947746c0fc5406a2466e7b5f6159e | [
"BSD-3-Clause-No-Nuclear-License-2014",
"BSD-3-Clause"
] | null | null | null | // Copyright (c) 2012 The Chromium Authors. All rights reserved.
// Use of this source code is governed by a BSD-style license that can be
// found in the LICENSE file.
#include "gpu/ipc/common/gpu_surface_tracker.h"
#include "base/logging.h"
#include "build/build_config.h"
#if defined(OS_ANDROID)
#include <android/native_window_jni.h>
#include "ui/gl/android/scoped_java_surface.h"
#endif // defined(OS_ANDROID)
namespace gpu {
GpuSurfaceTracker::GpuSurfaceTracker()
: next_surface_handle_(1) {
gpu::GpuSurfaceLookup::InitInstance(this);
}
GpuSurfaceTracker::~GpuSurfaceTracker() {
gpu::GpuSurfaceLookup::InitInstance(NULL);
}
GpuSurfaceTracker* GpuSurfaceTracker::GetInstance() {
return base::Singleton<GpuSurfaceTracker>::get();
}
int GpuSurfaceTracker::AddSurfaceForNativeWidget(
gfx::AcceleratedWidget widget) {
base::AutoLock lock(surface_map_lock_);
gpu::SurfaceHandle surface_handle = next_surface_handle_++;
surface_map_[surface_handle] = widget;
return surface_handle;
}
bool GpuSurfaceTracker::IsValidSurfaceHandle(
gpu::SurfaceHandle surface_handle) const {
base::AutoLock lock(surface_map_lock_);
return surface_map_.find(surface_handle) != surface_map_.end();
}
void GpuSurfaceTracker::RemoveSurface(gpu::SurfaceHandle surface_handle) {
base::AutoLock lock(surface_map_lock_);
DCHECK(surface_map_.find(surface_handle) != surface_map_.end());
surface_map_.erase(surface_handle);
}
gfx::AcceleratedWidget GpuSurfaceTracker::AcquireNativeWidget(
gpu::SurfaceHandle surface_handle) {
base::AutoLock lock(surface_map_lock_);
SurfaceMap::iterator it = surface_map_.find(surface_handle);
if (it == surface_map_.end())
return gfx::kNullAcceleratedWidget;
#if defined(OS_ANDROID)
if (it->second != gfx::kNullAcceleratedWidget)
ANativeWindow_acquire(it->second);
#endif // defined(OS_ANDROID)
return it->second;
}
#if defined(OS_ANDROID)
void GpuSurfaceTracker::RegisterViewSurface(
int surface_id, const base::android::JavaRef<jobject>& j_surface) {
base::AutoLock lock(surface_view_map_lock_);
DCHECK(surface_view_map_.find(surface_id) == surface_view_map_.end());
surface_view_map_[surface_id] =
gl::ScopedJavaSurface::AcquireExternalSurface(j_surface.obj());
CHECK(surface_view_map_[surface_id].IsValid());
}
void GpuSurfaceTracker::UnregisterViewSurface(int surface_id)
{
base::AutoLock lock(surface_view_map_lock_);
DCHECK(surface_view_map_.find(surface_id) != surface_view_map_.end());
surface_view_map_.erase(surface_id);
}
gl::ScopedJavaSurface GpuSurfaceTracker::AcquireJavaSurface(int surface_id) {
base::AutoLock lock(surface_view_map_lock_);
SurfaceViewMap::const_iterator iter = surface_view_map_.find(surface_id);
if (iter == surface_view_map_.end())
return gl::ScopedJavaSurface();
const gl::ScopedJavaSurface& j_surface = iter->second;
DCHECK(j_surface.IsValid());
return gl::ScopedJavaSurface::AcquireExternalSurface(
j_surface.j_surface().obj());
}
#endif
std::size_t GpuSurfaceTracker::GetSurfaceCount() {
base::AutoLock lock(surface_map_lock_);
return surface_map_.size();
}
} // namespace gpu
| 30.901961 | 77 | 0.770939 | xzhan96 |
fa07f64fd2e732f36b583c07f1bc9aa264706f7c | 7,480 | cpp | C++ | lib/djvViewApp/ViewData.cpp | belzecue/DJV | 94fb63a2f56cc0c41ab5d518ef9f2e0590c295c0 | [
"BSD-3-Clause"
] | 456 | 2018-10-06T00:07:14.000Z | 2022-03-31T06:14:22.000Z | lib/djvViewApp/ViewData.cpp | belzecue/DJV | 94fb63a2f56cc0c41ab5d518ef9f2e0590c295c0 | [
"BSD-3-Clause"
] | 438 | 2018-10-31T15:05:51.000Z | 2022-03-31T09:01:24.000Z | lib/djvViewApp/ViewData.cpp | belzecue/DJV | 94fb63a2f56cc0c41ab5d518ef9f2e0590c295c0 | [
"BSD-3-Clause"
] | 54 | 2018-10-29T10:18:36.000Z | 2022-03-23T06:56:11.000Z | // SPDX-License-Identifier: BSD-3-Clause
// Copyright (c) 2020 Darby Johnston
// All rights reserved.
#include <djvViewApp/ViewData.h>
#include <djvImage/Color.h>
using namespace djv::Core;
namespace djv
{
namespace ViewApp
{
bool GridOptions::operator == (const GridOptions& other) const
{
return enabled == other.enabled &&
size == other.size &&
color == other.color &&
labels == other.labels &&
labelsColor == other.labelsColor;
}
bool HUDData::operator == (const HUDData& other) const
{
return
fileName == other.fileName &&
layer == other.layer &&
size == other.size &&
type == other.type &&
isSequence == other.isSequence &&
currentFrame == other.currentFrame &&
speed == other.speed &&
realSpeed == other.realSpeed;
}
bool HUDOptions::operator == (const HUDOptions& other) const
{
return
enabled == other.enabled &&
color == other.color &&
background == other.background;
}
bool ViewBackgroundOptions::operator == (const ViewBackgroundOptions& other) const
{
return
background == other.background &&
color == other.color &&
checkersSize == other.checkersSize &&
checkersColors[0] == other.checkersColors[0] &&
checkersColors[1] == other.checkersColors[1] &&
border == other.border &&
borderWidth == other.borderWidth &&
borderColor == other.borderColor;
}
} // namespace ViewApp
rapidjson::Value toJSON(const ViewApp::GridOptions& value, rapidjson::Document::AllocatorType& allocator)
{
rapidjson::Value out(rapidjson::kObjectType);
out.AddMember("Enabled", toJSON(value.enabled, allocator), allocator);
out.AddMember("Size", toJSON(value.size, allocator), allocator);
out.AddMember("Color", toJSON(value.color, allocator), allocator);
out.AddMember("Labels", toJSON(value.labels, allocator), allocator);
out.AddMember("LabelsColor", toJSON(value.labelsColor, allocator), allocator);
return out;
}
rapidjson::Value toJSON(const ViewApp::HUDOptions& value, rapidjson::Document::AllocatorType& allocator)
{
rapidjson::Value out(rapidjson::kObjectType);
out.AddMember("Enabled", toJSON(value.enabled, allocator), allocator);
out.AddMember("Color", toJSON(value.color, allocator), allocator);
out.AddMember("Background", toJSON(value.background, allocator), allocator);
return out;
}
rapidjson::Value toJSON(const ViewApp::ViewBackgroundOptions& value, rapidjson::Document::AllocatorType& allocator)
{
rapidjson::Value out(rapidjson::kObjectType);
out.AddMember("Background", toJSON(value.background, allocator), allocator);
out.AddMember("Color", toJSON(value.color, allocator), allocator);
out.AddMember("CheckersSize", toJSON(value.checkersSize, allocator), allocator);
out.AddMember("CheckersColors0", toJSON(value.checkersColors[0], allocator), allocator);
out.AddMember("CheckersColors1", toJSON(value.checkersColors[1], allocator), allocator);
out.AddMember("Border", toJSON(value.border, allocator), allocator);
out.AddMember("BorderWidth", toJSON(value.borderWidth, allocator), allocator);
out.AddMember("BorderColor", toJSON(value.borderColor, allocator), allocator);
return out;
}
void fromJSON(const rapidjson::Value& value, ViewApp::GridOptions& out)
{
if (value.IsObject())
{
for (const auto& i : value.GetObject())
{
if (0 == strcmp("Enabled", i.name.GetString()))
{
fromJSON(i.value, out.enabled);
}
else if (0 == strcmp("Size", i.name.GetString()))
{
fromJSON(i.value, out.size);
}
else if (0 == strcmp("Color", i.name.GetString()))
{
fromJSON(i.value, out.color);
}
else if (0 == strcmp("Labels", i.name.GetString()))
{
fromJSON(i.value, out.labels);
}
else if (0 == strcmp("LabelsColor", i.name.GetString()))
{
fromJSON(i.value, out.labelsColor);
}
}
}
else
{
//! \todo How can we translate this?
throw std::invalid_argument(DJV_TEXT("error_cannot_parse_the_value"));
}
}
void fromJSON(const rapidjson::Value& value, ViewApp::HUDOptions& out)
{
if (value.IsObject())
{
for (const auto& i : value.GetObject())
{
if (0 == strcmp("Enabled", i.name.GetString()))
{
fromJSON(i.value, out.enabled);
}
else if (0 == strcmp("Color", i.name.GetString()))
{
fromJSON(i.value, out.color);
}
else if (0 == strcmp("Background", i.name.GetString()))
{
fromJSON(i.value, out.background);
}
}
}
else
{
//! \todo How can we translate this?
throw std::invalid_argument(DJV_TEXT("error_cannot_parse_the_value"));
}
}
void fromJSON(const rapidjson::Value& value, ViewApp::ViewBackgroundOptions& out)
{
if (value.IsObject())
{
for (const auto& i : value.GetObject())
{
if (0 == strcmp("Background", i.name.GetString()))
{
fromJSON(i.value, out.background);
}
else if (0 == strcmp("Color", i.name.GetString()))
{
fromJSON(i.value, out.color);
}
else if (0 == strcmp("CheckersSize", i.name.GetString()))
{
fromJSON(i.value, out.checkersSize);
}
else if (0 == strcmp("CheckersColors0", i.name.GetString()))
{
fromJSON(i.value, out.checkersColors[0]);
}
else if (0 == strcmp("CheckersColors1", i.name.GetString()))
{
fromJSON(i.value, out.checkersColors[1]);
}
else if (0 == strcmp("Border", i.name.GetString()))
{
fromJSON(i.value, out.border);
}
else if (0 == strcmp("BorderWidth", i.name.GetString()))
{
fromJSON(i.value, out.borderWidth);
}
else if (0 == strcmp("BorderColor", i.name.GetString()))
{
fromJSON(i.value, out.borderColor);
}
}
}
else
{
//! \todo How can we translate this?
throw std::invalid_argument(DJV_TEXT("error_cannot_parse_the_value"));
}
}
} // namespace djv
| 36.487805 | 119 | 0.512299 | belzecue |
fa0916f810206180426544fdf9db4310b2e390a0 | 12,292 | cxx | C++ | xp_comm_proj/rd_shape/shprdpnt.cxx | avs/express-community | c699a68330d3b678b7e6bcea823e0891b874049c | [
"Apache-2.0"
] | 3 | 2020-08-03T08:52:20.000Z | 2021-04-10T11:55:49.000Z | xp_comm_proj/rd_shape/shprdpnt.cxx | avs/express-community | c699a68330d3b678b7e6bcea823e0891b874049c | [
"Apache-2.0"
] | null | null | null | xp_comm_proj/rd_shape/shprdpnt.cxx | avs/express-community | c699a68330d3b678b7e6bcea823e0891b874049c | [
"Apache-2.0"
] | 1 | 2021-06-08T18:16:45.000Z | 2021-06-08T18:16:45.000Z | #include "pnt_gen.h"
#include "gsshape.h"
#include "gsesri.h"
int
ReadShape_ReadShapeMods_ReadShapePoint::ReadShapePoint(OMevent_mask event_mask, int seq_num)
{
// ShapeFileName (OMXstr read req notify)
// FeatureNumber (OMXint read notify)
// Coordinates (OMXdouble_array write)
double *Coordinates_arr;
// FeatureID (OMXint_array write)
int *FeatureID_arr;
XP_GIS_ESRI_Shape_c ShapeFile; // shape file reader object
unsigned long ReturnValue; // return from read method
unsigned long LocalNumberOfPoints; // local version of express value
unsigned long LocalFeatureNumber; // local version of express value
unsigned long LocalNumberOfFeatures; // local version of express value
unsigned long LocalShapeType; // local version of express value
unsigned long TotalNumberOfPoints; // total # of points output
//unsigned long TotalNumberOfPointsInFeature; // # of features in 1 feature
unsigned long FeatureStart; // first feature to process
unsigned long FeatureEnd; // last feature to process
long NumberOfPointsInFeature; // # of points in 1 feature
long RecordNumber; // record number read
double *CoordinatesPtr; // ptr to coordinate list
int *FeatureIDPtr; // ptr to feature id list
/***********************/
/* Function's Body */
/***********************/
#ifdef DEBUG
ERRverror("",ERR_NO_HEADER | ERR_PRINT,
"I'm in method: ReadShapePoint::ReadShapePoint\n");
#endif
//
// Tell the shape file object what the shape file name is.
//
if (ShapeFile.FileName(ShapeFileName) == NULL)
{
ERRverror("",ERR_NO_HEADER | ERR_PRINT,
"Error opening shape file.\n");
return 0;
}
//
// Print out the header to see what we've got.
//
#ifdef DEBUG
if (ShapeFile.ShapeHeader().PrintFileHeader(cout) != XP_GIS_OK)
{
ERRverror("",ERR_NO_HEADER | ERR_PRINT,
"Error printing shape file header\n");
return 0;
}
#endif
//
// Validate the header to make sure we have a good shape file.
//
if (ShapeFile.ShapeHeader().ValidateFileHeader() != XP_GIS_OK)
{
ERRverror("",ERR_NO_HEADER | ERR_PRINT,
"Error validating shape file header\n");
return 0;
}
//
// Get the shape type.
//
LocalShapeType = ShapeFile.ShapeHeader().ShapeType();
if ((LocalShapeType != XP_GIS_POINT_SHAPE) &&
(LocalShapeType != XP_GIS_MULTIPOINT_SHAPE))
{
ERRverror("",ERR_NO_HEADER | ERR_PRINT,
"The shape type is not point or multipoint.\n");
return 0;
}
//
// Get the number of features in the shape file.
//
if (ShapeFile.NumberOfDataRecords(&LocalNumberOfFeatures) != XP_GIS_OK)
{
ERRverror("",ERR_NO_HEADER | ERR_PRINT,
"Error getting number of data records\n");
return 0;
}
//
// If the feature number was provided, we want to read only that
// feature. Otherwise, we want to read all the features. FeatureStart
// and FeatureEnd are loop start and end control variables that
// tell us which feature(s) to process.
//
FeatureStart = 1;
FeatureEnd = LocalNumberOfFeatures;
LocalFeatureNumber = (int) FeatureNumber;
if (FeatureNumber.valid_obj())
{
//
// Check to see if the feature number requested is valid.
//
if ((LocalFeatureNumber <= 0) ||
(LocalFeatureNumber > LocalNumberOfFeatures))
{
ERRverror("",ERR_NO_HEADER | ERR_PRINT,
"The feature number is not valid.\n");
return 0;
}
FeatureStart = (unsigned long) (LocalFeatureNumber);
FeatureEnd = FeatureStart;
//
// We are only reading one feature. We need to figure out the
// number of parts and points for the requested feature so we
// can allocate the correct amount of space for the arrays.
//
LocalNumberOfFeatures = 1;
if (LocalShapeType == XP_GIS_POINT_SHAPE)
{
TotalNumberOfPoints = 1;
}
else if (LocalShapeType == XP_GIS_MULTIPOINT_SHAPE)
{
if (ShapeFile.SeekToDataRecord((long) LocalFeatureNumber) != XP_GIS_OK)
{
ERRverror("",ERR_NO_HEADER | ERR_PRINT,
"Error seeking to the feature.\n");
return 0;
}
if (ShapeFile.GetMultiPointShapeInfo(&RecordNumber,
&NumberOfPointsInFeature) != XP_GIS_OK)
{
ERRverror("",ERR_NO_HEADER | ERR_PRINT,
"Error getting information for feature.\n");
return 0;
}
else if (RecordNumber != LocalFeatureNumber)
{
ERRverror("",ERR_NO_HEADER | ERR_PRINT,
"Unexpected record number found.\n");
return 0;
}
TotalNumberOfPoints = NumberOfPointsInFeature;
}
}
else
{
//
// We are going to read all the features in the file. We need to
// figure out the total number of points for all features
// in the file so we can allocate the correct amount of space
// for the arrays.
//
if (ShapeFile.NumberOfPoints(&TotalNumberOfPoints) != XP_GIS_OK)
{
ERRverror("",ERR_NO_HEADER | ERR_PRINT,
"Error getting number of parts in file.\n");
return 0;
}
}
LocalNumberOfPoints = TotalNumberOfPoints;
//
// Allocate space for the coordinates array.
//
Coordinates_arr = (double *) malloc(sizeof(double) *
(LocalNumberOfPoints * 2));
if (Coordinates_arr == NULL)
{
ERRverror("",ERR_NO_HEADER | ERR_PRINT,
"Error allocating space for coordinate array.\n");
return 0;
}
//
// Allocate space for the feature id array.
//
FeatureID_arr = (int *) malloc(sizeof(int) * LocalNumberOfFeatures);
if (FeatureID_arr == NULL)
{
if (Coordinates_arr != NULL) free(Coordinates_arr);
ERRverror("",ERR_NO_HEADER | ERR_PRINT,
"Error allocating space for FeatureID array.\n");
return 0;
}
//
// Seek to the start of the requested feature.
//
if (ShapeFile.SeekToDataRecord((long) FeatureStart) != XP_GIS_OK)
{
if (Coordinates_arr != NULL) free(Coordinates_arr);
if (FeatureID_arr != NULL) free(FeatureID_arr);
ERRverror("",ERR_NO_HEADER | ERR_PRINT,
"Error seeking to the feature.\n");
return 0;
}
//
// Assign temporary pointers to allow more convenient increment.
//
CoordinatesPtr = Coordinates_arr;
FeatureIDPtr = FeatureID_arr;
//
// This module handles point feature types. It handles both
// shape points and multipoints. Switch based on the shape
// type.
//
switch (LocalShapeType)
{
case XP_GIS_POINT_SHAPE: // point shape type
{
double XPoint; // x point for the feature
double YPoint; // y point for the feature
//
// Loop for each feature.
//
for (LocalFeatureNumber = FeatureStart;
LocalFeatureNumber <= FeatureEnd;
LocalFeatureNumber++)
{
//
// Read the feature.
//
ReturnValue = ShapeFile.ReadPointShape(&RecordNumber,
&XPoint,
&YPoint);
if (ReturnValue != XP_GIS_OK)
{
if (ReturnValue == XP_GIS_EOF)
{
ERRverror("",ERR_NO_HEADER | ERR_PRINT,
"Reached unexpected end of file.\n");
break;
}
else
{
ERRverror("",ERR_NO_HEADER | ERR_PRINT,
"Error reading point feature.\n");
continue;
}
}
else if (RecordNumber != LocalFeatureNumber)
{
ERRverror("",ERR_NO_HEADER | ERR_PRINT,
"Unexpected record number found.\n");
break;
}
else
{
*CoordinatesPtr++ = XPoint; // assign the X coordinate
*CoordinatesPtr++ = YPoint; // assign the Y coordinate
*FeatureIDPtr++ = LocalFeatureNumber; // assign the feature #
}
}
break;
}
case XP_GIS_MULTIPOINT_SHAPE: // multipoint shape type
{
double XMin; // feature X min
double YMin; // feature Y min
double XMax; // feature X max
double YMax; // feature Y max
double *XPoints; // array of feature X coords
double *YPoints; // array of feature Y coords
unsigned long PointNumber; // point # we are working with
long MaximumNumberOfPoints; // max # of pts we can handle
MaximumNumberOfPoints = 0; // init to 0...will be reassigned
XPoints = NULL; // init to NULL...will be allocated
YPoints = NULL; // init to NULL...will be allocated
//
// For each feature in the file
//
for (LocalFeatureNumber = FeatureStart;
LocalFeatureNumber < FeatureEnd;
LocalFeatureNumber++)
{
//
// Read the feature.
//
ReturnValue = ShapeFile.ReadMultiPointShape(&RecordNumber,
&XMin,
&YMin,
&XMax,
&YMax,
&NumberOfPointsInFeature,
&MaximumNumberOfPoints,
&XPoints,
&YPoints);
if (ReturnValue != XP_GIS_OK)
{
if (ReturnValue == XP_GIS_EOF)
{
ERRverror("",ERR_NO_HEADER | ERR_PRINT,
"Reached unexpected end of file.\n");
break;
}
else
{
ERRverror("",ERR_NO_HEADER | ERR_PRINT,
"Error reading multipoint feature.\n");
continue;
}
}
else if (RecordNumber != LocalFeatureNumber)
{
ERRverror("",ERR_NO_HEADER | ERR_PRINT,
"Unexpected record number found.\n");
break;
}
else
{
//
// For each point in the feature.
//
for (PointNumber = 0;
PointNumber < NumberOfPointsInFeature;
PointNumber++)
{
*CoordinatesPtr++ = XPoints[PointNumber]; // assign X coord
*CoordinatesPtr++ = YPoints[PointNumber]; // assign Y coord
*FeatureIDPtr++ = LocalFeatureNumber; // assign feature #
}
}
}
//
// Free the arrays that were allocated by the read method.
//
if (XPoints != NULL) free(XPoints);
if (YPoints != NULL) free(YPoints);
}
default: // Invalid shape type
{
ERRverror("",ERR_NO_HEADER | ERR_PRINT,
"The shape type is not point or multipoint.\n");
return 0;
}
}
//
// Now, set the values that belong to express.
//
NumberOfPoints = (int) LocalNumberOfPoints;
NumberOfFeatures = (int) LocalNumberOfFeatures;
ShapeType = (int) LocalShapeType;
Coordinates.set_array(OM_TYPE_DOUBLE,
(char *) Coordinates_arr,
(int) (LocalNumberOfPoints * 2),
OM_SET_ARRAY_FREE);
FeatureID.set_array(OM_TYPE_INT,
(char *) FeatureID_arr,
(int) LocalNumberOfFeatures,
OM_SET_ARRAY_FREE);
// return 1 for success
return(1);
}
| 30.501241 | 92 | 0.537179 | avs |
fa0c2a9138d1544996c4f86726aa3ddd479d5a70 | 1,952 | hpp | C++ | src/tsdf/ewa_viz.hpp | Algomorph/LevelSetFusionExperimentsCPP | f56962f0ad5c62e6706f818062782a2e1660afda | [
"Apache-2.0"
] | 8 | 2019-01-07T14:12:21.000Z | 2021-01-12T01:48:03.000Z | src/tsdf/ewa_viz.hpp | Algomorph/LevelSetFusionExperimentsCPP | f56962f0ad5c62e6706f818062782a2e1660afda | [
"Apache-2.0"
] | 6 | 2018-12-19T16:43:33.000Z | 2019-06-06T19:50:22.000Z | src/tsdf/ewa_viz.hpp | Algomorph/LevelSetFusionExperimentsCPP | f56962f0ad5c62e6706f818062782a2e1660afda | [
"Apache-2.0"
] | 2 | 2019-01-07T14:12:28.000Z | 2019-03-06T06:30:24.000Z | // ================================================================
// Created by Gregory Kramida on 1/30/19.
// Copyright (c) 2019 Gregory Kramida
// 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.
// ================================================================
#pragma once
//stdlib
//libs
#include <Eigen/Eigen>
#include <unsupported/Eigen/CXX11/Tensor>
//local
#include "../math/typedefs.hpp"
namespace eig = Eigen;
namespace tsdf {
math::MatrixXuc generate_TSDF_3D_EWA_image_visualization(
const eig::Matrix<unsigned short, eig::Dynamic, eig::Dynamic>& depth_image,
float depth_unit_ratio,
const eig::Tensor<float, 3>& field,
const eig::Matrix3f& camera_intrinsic_matrix,
const eig::Matrix4f& camera_pose = eig::Matrix4f::Identity(4, 4),
const eig::Vector3i& array_offset =
[] {eig::Vector3i default_offset; default_offset << -64, -64, 64; return default_offset;}(),
float voxel_size = 0.004,
int scale=20,
float tsdf_threshold = 0.1f,
float gaussian_covariance_scale = 1.0f);
eig::MatrixXf sampling_area_heatmap_2D_EWA_image(int image_y_coordinate,
const eig::Matrix<unsigned short, eig::Dynamic, eig::Dynamic>& depth_image,
float depth_unit_ratio,
const eig::Matrix3f& camera_intrinsic_matrix,
const eig::Matrix4f& camera_pose,
const eig::Vector3i& array_offset,
int field_size,
float voxel_size,
int narrow_band_width_voxels,
float gaussian_covariance_scale);
} // namespace tsdf
| 34.245614 | 96 | 0.696721 | Algomorph |
fa0cc8fd0f23c1f4fa9ba5bd8faf9bdf174fc2fa | 1,205 | cpp | C++ | codebook/code/Matching/Blossom.cpp | NCTU-PCCA/NCTU_Yggdrasill | 4f086c9737502f69044f574514cf191d536aaf22 | [
"MIT"
] | null | null | null | codebook/code/Matching/Blossom.cpp | NCTU-PCCA/NCTU_Yggdrasill | 4f086c9737502f69044f574514cf191d536aaf22 | [
"MIT"
] | null | null | null | codebook/code/Matching/Blossom.cpp | NCTU-PCCA/NCTU_Yggdrasill | 4f086c9737502f69044f574514cf191d536aaf22 | [
"MIT"
] | null | null | null | #define MAXN 505
vector<int>g[MAXN];//用vector存圖
int pa[MAXN],match[MAXN],st[MAXN],S[MAXN],vis[MAXN];
int t,n;
inline int lca(int u,int v){//找花的花托
for(++t;;swap(u,v)){
if(u==0)continue;
if(vis[u]==t)return u;
vis[u]=t;//這種方法可以不用清空vis陣列
u=st[pa[match[u]]];
}
}
#define qpush(u) q.push(u),S[u]=0
inline void flower(int u,int v,int l,queue<int> &q){
while(st[u]!=l){
pa[u]=v;//所有未匹配邊的pa都是雙向的
if(S[v=match[u]]==1)qpush(v);//所有奇點變偶點
st[u]=st[v]=l,u=pa[v];
}
}
inline bool bfs(int u){
for(int i=1;i<=n;++i)st[i]=i;//st[i]表示第i個點的集合
memset(S+1,-1,sizeof(int)*n);//-1:沒走過 0:偶點 1:奇點
queue<int>q;qpush(u);
while(q.size()){
u=q.front(),q.pop();
for(size_t i=0;i<g[u].size();++i){
int v=g[u][i];
if(S[v]==-1){
pa[v]=u,S[v]=1;
if(!match[v]){//有增廣路直接擴充
for(int lst;u;v=lst,u=pa[v])
lst=match[u],match[u]=v,match[v]=u;
return 1;
}
qpush(match[v]);
}else if(!S[v]&&st[v]!=st[u]){
int l=lca(st[v],st[u]);//遇到花,做花的處理
flower(v,u,l,q),flower(u,v,l,q);
}
}
}
return 0;
}
inline int blossom(){
memset(pa+1,0,sizeof(int)*n);
memset(match+1,0,sizeof(int)*n);
int ans=0;
for(int i=1;i<=n;++i)
if(!match[i]&&bfs(i))++ans;
return ans;
} | 23.173077 | 52 | 0.559336 | NCTU-PCCA |
fa0d99ae5c5f24a96a0bd0f127c0cedd118144ff | 1,214 | cpp | C++ | Problem201-250/p222_2.cpp | dingqunfei/LeetCode | c74a21ea56ee7b35308d2f387ef24ab29b031e24 | [
"Apache-2.0"
] | null | null | null | Problem201-250/p222_2.cpp | dingqunfei/LeetCode | c74a21ea56ee7b35308d2f387ef24ab29b031e24 | [
"Apache-2.0"
] | null | null | null | Problem201-250/p222_2.cpp | dingqunfei/LeetCode | c74a21ea56ee7b35308d2f387ef24ab29b031e24 | [
"Apache-2.0"
] | null | null | null | /**
* @file p222_2.cpp
* @brief
* @author dingqunfei (dqflying@gmail.com)
* @version 1.0
* @date 2021-04-11
*
* @copyright Copyright (c) 2021 DQFLYING
*
* @par :
*
*
* Date : 2021-04-11
* Version : 1.0
* Author : dqflying
* Lisence :
* Description :
*
*
*
*
*/
/**
* Definition for a binary tree node.
* struct TreeNode {
* int val;
* TreeNode *left;
* TreeNode *right;
* TreeNode() : val(0), left(nullptr), right(nullptr) {}
* TreeNode(int x) : val(x), left(nullptr), right(nullptr) {}
* TreeNode(int x, TreeNode *left, TreeNode *right) : val(x), left(left), right(right) {}
* };
*/
class Solution {
public:
int countNodes(TreeNode* root) {
if(!root)
{
return 0;
}
int lh = 0, rh = 0;
TreeNode *left = root;
TreeNode *right = root;
while(left)
{
++lh;
left = left->left;
}
while(right)
{
++rh;
right = right->right;
}
if(rh == lh)
{
return pow(2, rh)-1;
}
return 1+countNodes(root->left)+countNodes(root->right);
}
}; | 19.580645 | 93 | 0.474465 | dingqunfei |
fa0e0437ec04fa419d4d14000c86ed654c7fe6b8 | 1,002 | cpp | C++ | CLASSES/inheritance/practice_question2(absract class).cpp | shauryauppal/Algo-DS-StudyMaterial | 1c481f066d21b33ec2533156e75f45fa9b6a7606 | [
"Apache-2.0"
] | 3 | 2020-12-03T14:52:23.000Z | 2021-12-19T09:26:50.000Z | CLASSES/inheritance/practice_question2(absract class).cpp | shauryauppal/Algo-DS-StudyMaterial | 1c481f066d21b33ec2533156e75f45fa9b6a7606 | [
"Apache-2.0"
] | null | null | null | CLASSES/inheritance/practice_question2(absract class).cpp | shauryauppal/Algo-DS-StudyMaterial | 1c481f066d21b33ec2533156e75f45fa9b6a7606 | [
"Apache-2.0"
] | null | null | null | #include <iostream>
#include <cstdio>
using namespace std;
//give act as a virtual class
class give
{
//protected members
protected:
int width,height;
public:
//pure virtual function used
virtual int getarea()=0;
//use to get data
void getheight()
{
cout<<"\nEnter height->";
cin>>height;
}
//used to get data
void getwidth()
{
cout<<"\nEnter width->";
cin>>width;
}
};
//derived class visibility public
class rectangle:public give
{
public:
int getarea()
{
return (height*width);
}
};
//derived class
class triangle:public give
{
public:
int getarea()
{
return ((height*width)/2);
}
};
int main()
{
rectangle r;
r.getheight();
r.getwidth();
cout<<"\nRectange area->"<<r.getarea();
triangle t;
t.getheight();
t.getwidth();
cout<<"\nTriangle area->"<<t.getarea();
return 0;
}
| 17.892857 | 44 | 0.533932 | shauryauppal |
fa116ab2dba71367016ae32a0d280ef1ceac0c7a | 11,082 | cxx | C++ | src/escape.cxx | jktjkt/replxx | 12f2adee7f9123880db1f870c360a88c1f7ba182 | [
"Apache-2.0"
] | 1 | 2019-06-11T06:49:15.000Z | 2019-06-11T06:49:15.000Z | src/escape.cxx | jktjkt/replxx | 12f2adee7f9123880db1f870c360a88c1f7ba182 | [
"Apache-2.0"
] | null | null | null | src/escape.cxx | jktjkt/replxx | 12f2adee7f9123880db1f870c360a88c1f7ba182 | [
"Apache-2.0"
] | 1 | 2019-06-10T16:48:55.000Z | 2019-06-10T16:48:55.000Z | #include "escape.hxx"
#include "io.hxx"
#include "keycodes.hxx"
#ifndef _WIN32
namespace replxx {
namespace EscapeSequenceProcessing { // move these out of global namespace
// This chunk of code does parsing of the escape sequences sent by various Linux
// terminals.
//
// It handles arrow keys, Home, End and Delete keys by interpreting the
// sequences sent by
// gnome terminal, xterm, rxvt, konsole, aterm and yakuake including the Alt and
// Ctrl key
// combinations that are understood by replxx.
//
// The parsing uses tables, a bunch of intermediate dispatch routines and a
// doDispatch
// loop that reads the tables and sends control to "deeper" routines to continue
// the
// parsing. The starting call to doDispatch( c, initialDispatch ) will
// eventually return
// either a character (with optional CTRL and META bits set), or -1 if parsing
// fails, or
// zero if an attempt to read from the keyboard fails.
//
// This is rather sloppy escape sequence processing, since we're not paying
// attention to what the
// actual TERM is set to and are processing all key sequences for all terminals,
// but it works with
// the most common keystrokes on the most common terminals. It's intricate, but
// the nested 'if'
// statements required to do it directly would be worse. This way has the
// advantage of allowing
// changes and extensions without having to touch a lot of code.
static char32_t thisKeyMetaCtrl = 0; // holds pre-set Meta and/or Ctrl modifiers
// This dispatch routine is given a dispatch table and then farms work out to
// routines
// listed in the table based on the character it is called with. The dispatch
// routines can
// read more input characters to decide what should eventually be returned.
// Eventually,
// a called routine returns either a character or -1 to indicate parsing
// failure.
//
char32_t doDispatch(char32_t c, CharacterDispatch& dispatchTable) {
for (unsigned int i = 0; i < dispatchTable.len; ++i) {
if (static_cast<unsigned char>(dispatchTable.chars[i]) == c) {
return dispatchTable.dispatch[i](c);
}
}
return dispatchTable.dispatch[dispatchTable.len](c);
}
// Final dispatch routines -- return something
//
static char32_t normalKeyRoutine(char32_t c) { return thisKeyMetaCtrl | c; }
static char32_t upArrowKeyRoutine(char32_t) {
return thisKeyMetaCtrl | UP_ARROW_KEY;
}
static char32_t downArrowKeyRoutine(char32_t) {
return thisKeyMetaCtrl | DOWN_ARROW_KEY;
}
static char32_t rightArrowKeyRoutine(char32_t) {
return thisKeyMetaCtrl | RIGHT_ARROW_KEY;
}
static char32_t leftArrowKeyRoutine(char32_t) {
return thisKeyMetaCtrl | LEFT_ARROW_KEY;
}
static char32_t homeKeyRoutine(char32_t) { return thisKeyMetaCtrl | HOME_KEY; }
static char32_t endKeyRoutine(char32_t) { return thisKeyMetaCtrl | END_KEY; }
static char32_t pageUpKeyRoutine(char32_t) {
return thisKeyMetaCtrl | PAGE_UP_KEY;
}
static char32_t pageDownKeyRoutine(char32_t) {
return thisKeyMetaCtrl | PAGE_DOWN_KEY;
}
static char32_t deleteCharRoutine(char32_t) {
return thisKeyMetaCtrl | ctrlChar('H');
} // key labeled Backspace
static char32_t deleteKeyRoutine(char32_t) {
return thisKeyMetaCtrl | DELETE_KEY;
} // key labeled Delete
static char32_t ctrlUpArrowKeyRoutine(char32_t) {
return thisKeyMetaCtrl | CTRL | UP_ARROW_KEY;
}
static char32_t ctrlDownArrowKeyRoutine(char32_t) {
return thisKeyMetaCtrl | CTRL | DOWN_ARROW_KEY;
}
static char32_t ctrlRightArrowKeyRoutine(char32_t) {
return thisKeyMetaCtrl | CTRL | RIGHT_ARROW_KEY;
}
static char32_t ctrlLeftArrowKeyRoutine(char32_t) {
return thisKeyMetaCtrl | CTRL | LEFT_ARROW_KEY;
}
static char32_t escFailureRoutine(char32_t) {
beep();
return -1;
}
// Handle ESC [ 1 ; 3 (or 5) <more stuff> escape sequences
//
static CharacterDispatchRoutine escLeftBracket1Semicolon3or5Routines[] = {
upArrowKeyRoutine, downArrowKeyRoutine, rightArrowKeyRoutine,
leftArrowKeyRoutine, escFailureRoutine};
static CharacterDispatch escLeftBracket1Semicolon3or5Dispatch = {
4, "ABCD", escLeftBracket1Semicolon3or5Routines};
// Handle ESC [ 1 ; <more stuff> escape sequences
//
static char32_t escLeftBracket1Semicolon3Routine(char32_t c) {
c = readUnicodeCharacter();
if (c == 0) return 0;
thisKeyMetaCtrl |= META;
return doDispatch(c, escLeftBracket1Semicolon3or5Dispatch);
}
static char32_t escLeftBracket1Semicolon5Routine(char32_t c) {
c = readUnicodeCharacter();
if (c == 0) return 0;
thisKeyMetaCtrl |= CTRL;
return doDispatch(c, escLeftBracket1Semicolon3or5Dispatch);
}
static CharacterDispatchRoutine escLeftBracket1SemicolonRoutines[] = {
escLeftBracket1Semicolon3Routine, escLeftBracket1Semicolon5Routine,
escFailureRoutine};
static CharacterDispatch escLeftBracket1SemicolonDispatch = {
2, "35", escLeftBracket1SemicolonRoutines};
// Handle ESC [ 1 <more stuff> escape sequences
//
static char32_t escLeftBracket1SemicolonRoutine(char32_t c) {
c = readUnicodeCharacter();
if (c == 0) return 0;
return doDispatch(c, escLeftBracket1SemicolonDispatch);
}
static CharacterDispatchRoutine escLeftBracket1Routines[] = {
homeKeyRoutine, escLeftBracket1SemicolonRoutine, escFailureRoutine};
static CharacterDispatch escLeftBracket1Dispatch = {2, "~;",
escLeftBracket1Routines};
// Handle ESC [ 3 <more stuff> escape sequences
//
static CharacterDispatchRoutine escLeftBracket3Routines[] = {deleteKeyRoutine,
escFailureRoutine};
static CharacterDispatch escLeftBracket3Dispatch = {1, "~",
escLeftBracket3Routines};
// Handle ESC [ 4 <more stuff> escape sequences
//
static CharacterDispatchRoutine escLeftBracket4Routines[] = {endKeyRoutine,
escFailureRoutine};
static CharacterDispatch escLeftBracket4Dispatch = {1, "~",
escLeftBracket4Routines};
// Handle ESC [ 5 <more stuff> escape sequences
//
static CharacterDispatchRoutine escLeftBracket5Routines[] = {pageUpKeyRoutine,
escFailureRoutine};
static CharacterDispatch escLeftBracket5Dispatch = {1, "~",
escLeftBracket5Routines};
// Handle ESC [ 6 <more stuff> escape sequences
//
static CharacterDispatchRoutine escLeftBracket6Routines[] = {pageDownKeyRoutine,
escFailureRoutine};
static CharacterDispatch escLeftBracket6Dispatch = {1, "~",
escLeftBracket6Routines};
// Handle ESC [ 7 <more stuff> escape sequences
//
static CharacterDispatchRoutine escLeftBracket7Routines[] = {homeKeyRoutine,
escFailureRoutine};
static CharacterDispatch escLeftBracket7Dispatch = {1, "~",
escLeftBracket7Routines};
// Handle ESC [ 8 <more stuff> escape sequences
//
static CharacterDispatchRoutine escLeftBracket8Routines[] = {endKeyRoutine,
escFailureRoutine};
static CharacterDispatch escLeftBracket8Dispatch = {1, "~",
escLeftBracket8Routines};
// Handle ESC [ <digit> escape sequences
//
static char32_t escLeftBracket0Routine(char32_t c) {
return escFailureRoutine(c);
}
static char32_t escLeftBracket1Routine(char32_t c) {
c = readUnicodeCharacter();
if (c == 0) return 0;
return doDispatch(c, escLeftBracket1Dispatch);
}
static char32_t escLeftBracket2Routine(char32_t c) {
return escFailureRoutine(c); // Insert key, unused
}
static char32_t escLeftBracket3Routine(char32_t c) {
c = readUnicodeCharacter();
if (c == 0) return 0;
return doDispatch(c, escLeftBracket3Dispatch);
}
static char32_t escLeftBracket4Routine(char32_t c) {
c = readUnicodeCharacter();
if (c == 0) return 0;
return doDispatch(c, escLeftBracket4Dispatch);
}
static char32_t escLeftBracket5Routine(char32_t c) {
c = readUnicodeCharacter();
if (c == 0) return 0;
return doDispatch(c, escLeftBracket5Dispatch);
}
static char32_t escLeftBracket6Routine(char32_t c) {
c = readUnicodeCharacter();
if (c == 0) return 0;
return doDispatch(c, escLeftBracket6Dispatch);
}
static char32_t escLeftBracket7Routine(char32_t c) {
c = readUnicodeCharacter();
if (c == 0) return 0;
return doDispatch(c, escLeftBracket7Dispatch);
}
static char32_t escLeftBracket8Routine(char32_t c) {
c = readUnicodeCharacter();
if (c == 0) return 0;
return doDispatch(c, escLeftBracket8Dispatch);
}
static char32_t escLeftBracket9Routine(char32_t c) {
return escFailureRoutine(c);
}
// Handle ESC [ <more stuff> escape sequences
//
static CharacterDispatchRoutine escLeftBracketRoutines[] = {
upArrowKeyRoutine, downArrowKeyRoutine, rightArrowKeyRoutine,
leftArrowKeyRoutine, homeKeyRoutine, endKeyRoutine,
escLeftBracket0Routine, escLeftBracket1Routine, escLeftBracket2Routine,
escLeftBracket3Routine, escLeftBracket4Routine, escLeftBracket5Routine,
escLeftBracket6Routine, escLeftBracket7Routine, escLeftBracket8Routine,
escLeftBracket9Routine, escFailureRoutine};
static CharacterDispatch escLeftBracketDispatch = {16, "ABCDHF0123456789",
escLeftBracketRoutines};
// Handle ESC O <char> escape sequences
//
static CharacterDispatchRoutine escORoutines[] = {
upArrowKeyRoutine, downArrowKeyRoutine, rightArrowKeyRoutine,
leftArrowKeyRoutine, homeKeyRoutine, endKeyRoutine,
ctrlUpArrowKeyRoutine, ctrlDownArrowKeyRoutine, ctrlRightArrowKeyRoutine,
ctrlLeftArrowKeyRoutine, escFailureRoutine};
static CharacterDispatch escODispatch = {10, "ABCDHFabcd", escORoutines};
// Initial ESC dispatch -- could be a Meta prefix or the start of an escape
// sequence
//
static char32_t escLeftBracketRoutine(char32_t c) {
c = readUnicodeCharacter();
if (c == 0) return 0;
return doDispatch(c, escLeftBracketDispatch);
}
static char32_t escORoutine(char32_t c) {
c = readUnicodeCharacter();
if (c == 0) return 0;
return doDispatch(c, escODispatch);
}
static char32_t setMetaRoutine(char32_t c); // need forward reference
static CharacterDispatchRoutine escRoutines[] = {escLeftBracketRoutine,
escORoutine, setMetaRoutine};
static CharacterDispatch escDispatch = {2, "[O", escRoutines};
// Initial dispatch -- we are not in the middle of anything yet
//
static char32_t escRoutine(char32_t c) {
c = readUnicodeCharacter();
if (c == 0) return 0;
return doDispatch(c, escDispatch);
}
static CharacterDispatchRoutine initialRoutines[] = {
escRoutine, deleteCharRoutine, normalKeyRoutine};
static CharacterDispatch initialDispatch = {2, "\x1B\x7F", initialRoutines};
// Special handling for the ESC key because it does double duty
//
static char32_t setMetaRoutine(char32_t c) {
thisKeyMetaCtrl = META;
if (c == 0x1B) { // another ESC, stay in ESC processing mode
c = readUnicodeCharacter();
if (c == 0) return 0;
return doDispatch(c, escDispatch);
}
return doDispatch(c, initialDispatch);
}
char32_t doDispatch(char32_t c) {
EscapeSequenceProcessing::thisKeyMetaCtrl = 0; // no modifiers yet at initialDispatch
return doDispatch(c, initialDispatch);
}
} // namespace EscapeSequenceProcessing // move these out of global namespace
}
#endif /* #ifndef _WIN32 */
| 35.748387 | 86 | 0.750135 | jktjkt |
fa145534ed2ca5a09dd724073d7b787b656e1cc4 | 816 | cpp | C++ | Notebook/codes/estruturas/map.cpp | rodrigoAMF7/Notebook---Maratonas | 06b38197a042bfbd27b20f707493e0a19fda7234 | [
"MIT"
] | 4 | 2019-01-25T21:22:55.000Z | 2019-03-20T18:04:01.000Z | Notebook/codes/estruturas/map.cpp | rodrigoAMF/competitive-programming-notebook | 06b38197a042bfbd27b20f707493e0a19fda7234 | [
"MIT"
] | null | null | null | Notebook/codes/estruturas/map.cpp | rodrigoAMF/competitive-programming-notebook | 06b38197a042bfbd27b20f707493e0a19fda7234 | [
"MIT"
] | null | null | null | // Map é uma variação da estrutura set e sua implementação também é feita utilizando Red- Black Trees. A principal diferença entre um set e um map é o segundo armazena os conjuntos chave, valor e o primeiro apenas chave.
map<string, int> M; // Declaração
M.insert(make_pair("Alana", 10)); //Inserimos uma variável do tipo pair diretamente no map
M["Alana"] = 10; // Relacionando o valor 10 à chave "Alana"
if(M.find("Alana") != M.end()) //Se a chave "Alana" foi inserida no map
cout<<M["Alana"]<<"\n"; //Imprime o valor da chave "Alana", no caso, o valor 10.
M.erase("Alana"); //Apaga o elemento que possui a chave "Alana" do map
// clear(): Apaga todos os elementos.
// size(): Retorna a quantidade de elementos.
// begin(): Retorna um ponteiro para o inicio do map
// end(): Retorna um ponteiro para o final do map | 74.181818 | 220 | 0.714461 | rodrigoAMF7 |
fa153b29e0dadd67b3f118338572dde64f19b438 | 2,337 | cpp | C++ | Material/RobertLafore_Book/Book_SourceCode/Progs/Ch08/Englconv.cpp | hpaucar/OOP-C-plus-plus-repo | e1fedd376029996a53d70d452b7738d9c43173c0 | [
"MIT"
] | 4 | 2020-12-26T03:17:45.000Z | 2022-01-11T05:54:40.000Z | Material/RobertLafore_Book/Book_SourceCode/Progs/Ch08/Englconv.cpp | hpaucar/OOP-C-plus-plus-repo | e1fedd376029996a53d70d452b7738d9c43173c0 | [
"MIT"
] | null | null | null | Material/RobertLafore_Book/Book_SourceCode/Progs/Ch08/Englconv.cpp | hpaucar/OOP-C-plus-plus-repo | e1fedd376029996a53d70d452b7738d9c43173c0 | [
"MIT"
] | null | null | null | // englconv.cpp
// conversions: Distance to meters, meters to Distance
#include <iostream>
using namespace std;
////////////////////////////////////////////////////////////////
class Distance //English Distance class
{
private:
const float MTF; //meters to feet
int feet;
float inches;
public: //constructor (no args)
Distance() : feet(0), inches(0.0), MTF(3.280833F)
{ } //constructor (one arg)
Distance(float meters) : MTF(3.280833F)
{ //convert meters to Distance
float fltfeet = MTF * meters; //convert to float feet
feet = int(fltfeet); //feet is integer part
inches = 12*(fltfeet-feet); //inches is what's left
} //constructor (two args)
Distance(int ft, float in) : feet(ft),
inches(in), MTF(3.280833F)
{ }
void getdist() //get length from user
{
cout << "\nEnter feet: "; cin >> feet;
cout << "Enter inches: "; cin >> inches;
}
void showdist() const //display distance
{ cout << feet << "\'-" << inches << '\"'; }
operator float() const //conversion operator
{ //converts Distance to meters
float fracfeet = inches/12; //convert the inches
fracfeet += static_cast<float>(feet); //add the feet
return fracfeet/MTF; //convert to meters
}
};
////////////////////////////////////////////////////////////////
int main()
{
float mtrs;
Distance dist1 = 2.35F; //uses 1-arg constructor to
//convert meters to Distance
cout << "\ndist1 = "; dist1.showdist();
mtrs = static_cast<float>(dist1); //uses conversion operator
//for Distance to meters
cout << "\ndist1 = " << mtrs << " meters\n";
Distance dist2(5, 10.25); //uses 2-arg constructor
mtrs = dist2; //also uses conversion op
cout << "\ndist2 = " << mtrs << " meters\n";
// dist2 = mtrs; //error, = won't convert
return 0;
}
| 39.610169 | 95 | 0.451433 | hpaucar |
fa1acb3ec000410176148209f2e3ef08501890b6 | 511 | cpp | C++ | Luogu/P3912.cpp | XenonWZH/involution | 189f6ce2bbfe3a7c5d536bbd769f353e4c06e7c6 | [
"MIT"
] | null | null | null | Luogu/P3912.cpp | XenonWZH/involution | 189f6ce2bbfe3a7c5d536bbd769f353e4c06e7c6 | [
"MIT"
] | null | null | null | Luogu/P3912.cpp | XenonWZH/involution | 189f6ce2bbfe3a7c5d536bbd769f353e4c06e7c6 | [
"MIT"
] | null | null | null | // P3912 素数个数
// WzhDnwzWzh
#include <cstring>
#include <cstdio>
const int MAXN = 100000000;
int main() {
int n;
scanf("%d", &n);
static bool a[MAXN + 1];
memset(a, true, sizeof(a));
for (int i = 2; i * i <= n; i++) {
if (a[i]) {
for (int j = i * i; j <= n; j += i) {
if (a[j]) a[j] = false;
}
}
}
int ans = 0;
for (int i = 2; i <= n; i++) {
if (a[i]) ans++;
}
printf("%d\n", ans);
return 0;
} | 15.484848 | 49 | 0.395303 | XenonWZH |
fa1d427f4907498834b2f85ae3fa22c683432fd1 | 7,916 | cpp | C++ | CodeSnippets/rotateMatrix.cpp | Teabeans/CPP_Learn | a767dd323d67fab5c2baffb5aa6dd3f1e6baa35a | [
"MIT"
] | 1 | 2019-01-31T23:42:59.000Z | 2019-01-31T23:42:59.000Z | CodeSnippets/rotateMatrix.cpp | Teabeans/CPP_Learn | a767dd323d67fab5c2baffb5aa6dd3f1e6baa35a | [
"MIT"
] | null | null | null | CodeSnippets/rotateMatrix.cpp | Teabeans/CPP_Learn | a767dd323d67fab5c2baffb5aa6dd3f1e6baa35a | [
"MIT"
] | 1 | 2020-03-04T18:09:15.000Z | 2020-03-04T18:09:15.000Z | //-----------------------------------------------------------------------------|
// Authorship
//-----------------------------------------------------------------------------|
//
// Tim Lum
// twhlum@gmail.com
// Created: 2018.07.15
// Modified: 2018.08.22
//
/*
1.7 - RotateMatrix() - P.91
Given an image represented by an NxN matrix, where each pixel in the image is 4
bytes, write a method to rotate the image by 90 degrees.
Can you do this in place?
//-----------------------------------------------------------------------------|
// PROBLEM SETUP AND ASSUMPTIONS
//-----------------------------------------------------------------------------|
A left rotation may be performed by calling a right rotation 3 times.
Only the right (clockwise) rotation shall be handled
The nature of the pixel is immaterial; we may handle the pixel as a 32-bit int
Since the problem specifies an N x N matrix, we address a square aspect ratio
To move a pixel
0 1 X 0 1 X
+---+---+ +---+---+ ([0][0] becomes [1][0])
0 | 1 | 2 | 0 | 4 | 1 | ([1][0] becomes [1][1])
+---+---+ +---+---+
1 | 4 | 3 | 1 | 3 | 2 |
+---+---+ +---+---+
Y Y
Output format is ambiguous, though it is implied that the data itself should be
rotated. However, displaying the "image" and its rotated result may also be
acceptable.
//-----------------------------------------------------------------------------|
// NAIVE APPROACH
//-----------------------------------------------------------------------------|
Iterate across every pixel within a quadrant and for (4) times
Identify the 4 sister-pixels
And swap them in turn
0 1 2 X [X][Y] is sister to
+---+---+---+ [XMax - X][Y] which is sister to
0 | 1 | 2 | 3 | [XMax - X][YMax - Y] which is sister to
+---+---+---+ [X][YMax-Y]
1 | 8 | 9 | 4 |
+---+---+---+
2 | 7 | 6 | 5 |
+---+---+---+
The global behavioral rule may be defined as:
The 90 degree rotational position of any pixel in a square matrix with coordinates:
X, Y
Is
(XMax - Y), X
0 1 2 X
+---+---+---+
0 | X | O | X | 0, 0 rotates 90 degrees to
+---+---+---+ 2, 0 which rotates 90 degrees to
1 | O | O | O | 2, 2 which rotates 90 degrees to
+---+---+---+ 0, 2
2 | X | O | X |
+---+---+---+
//-----------------------------------------------------------------------------|
// OPTIMIZATIONS
//-----------------------------------------------------------------------------|
1) The orientation of the image may be stored as a separate value from 0 to 3.
This may then be used to interpret the N, E, S, W orientation of the image
without modifying the image itself.
Effectively, we may interject an orientation filter which appropriately redirects
array access based upon the rotational state of the image.
This has the added benefit of functioning on non-square arrays, and also facilitates
easy addition of -90 and 180 degree rotations.
From an image editing standpoint, interpretation rather than alteration of the base
data will also better preserve image information.
//-----------------------------------------------------------------------------|
// TIME COMPLEXITY
//-----------------------------------------------------------------------------|
Any solution which modifies the original body of data may not complete faster
than in a time complexity of:
O( n^2 )
A filter solution, however, only adds a constant time alteration to the random
access lookup of the parent data. As a "rotation" is merely the toggling of a
rotation byte, the filter may complete in a time complexity of:
O( 1 )
//-----------------------------------------------------------------------------|
// PSEUDOLOGIC
//-----------------------------------------------------------------------------|
Compare string lengths for equality
Declare alphabet table charCounts
For each character in string1
Add 1 to the appropriate table in charCounts
For each character in string2
Subtract 1 from the appropriate table in charCounts
If the result is <0
Return false
//-----------------------------------------------------------------------------|
// CODE (C++)
//-----------------------------------------------------------------------------|
*/
// Compile with:
// $ g++ --std=c++11 01_07_RotateMatrix.cpp -o RotateMatrix
// Run with:
// $ ./RotateMatrix
#include <string>
#include <iostream>
#include <iomanip>
#define WIDTH 3
#define HEIGHT 7
// Rotation control:
// 0 == Base image
// 1 == 90 degree clockwise rotation
// 2 == 180 degree rotation
// 3 == 270 degree rotation
int ROTATION = 0;
int IMAGE[ WIDTH ][ HEIGHT ];
// (+) --------------------------------|
// #printMatrix( )
// ------------------------------------|
// Desc: Print a matrix
// Params: None
// PreCons: None
// PosCons: None
// RetVal: None
void printMatrix( ) {
int xDim = WIDTH;
int yDim = HEIGHT;
if( ROTATION == 0 ) {
// For rows 0 to MAX...
for( int row = 0 ; row < yDim ; row++ ) {
// Print column 0 to MAX
for( int col = 0 ; col < xDim; col++ ) {
std::cout << std::setw( 3 ) << IMAGE[ col ][ row ] << " ";
}
std::cout << std::endl << std::endl;
}
}
else if( ROTATION == 1 ) {
for( int col = 0 ; col < xDim ; col++ ) {
for( int row = ( yDim - 1 ) ; row >= 0; row-- ) {
std::cout << std::setw( 3 ) << IMAGE[ col ][ row ] << " ";
}
std::cout << std::endl << std::endl;
}
}
else if ( ROTATION == 2 ) {
for( int row = yDim-1 ; row >= 0 ; row-- ) {
for( int col = ( xDim - 1 ) ; col >= 0 ; col-- ) {
std::cout << std::setw( 3 ) << IMAGE[ col ][ row ] << " ";
}
std::cout << std::endl << std::endl;
}
}
else if ( ROTATION == 3 ) {
for( int col = ( xDim - 1 ) ; col >= 0 ; col-- ) {
for( int row = 0 ; row < yDim ; row++ ) {
std::cout << std::setw( 3 ) << IMAGE[ col ][ row ] << " ";
}
std::cout << std::endl << std::endl;
}
}
}
// (+) --------------------------------|
// #rotateMatrix( )
// ------------------------------------|
// Desc: Rotates a matrix
// Params: None
// PreCons: None
// PosCons: None
// RetVal: None
void rotateMatrix( ) {
ROTATION = ( ROTATION + 1 ) % 4;
}
//-----------------------------------------------------------------------------|
// DRIVER
//-----------------------------------------------------------------------------|
// (+) --------------------------------|
// #main( int, char* )
// ------------------------------------|
// Desc: Code driver
// Params: int arg1 - The number of command line arguments passed in
// char* arg2 - The content of the command line arguments
// PreCons: None
// PosCons: None
// RetVal: int - The exit code (0 for normal, -1 for error)
int main( int argc, char* argv[ ] ) {
std::cout << "Test of rotateMatrix( )" << std::endl;
int xDim = WIDTH;
int yDim = HEIGHT;
// For row 0 to MAX
for( int row = 0 ; row < yDim ; row++ ) {
for( int col = 0 ; col < xDim ; col++ ) {
IMAGE[ col ][ row ] = ( xDim * row ) + col;
}
}
printMatrix( );
std::cout << std::endl;
std::cout << "Rotating..." << std::endl << std::endl;
rotateMatrix( );
printMatrix( );
std::cout << std::endl;
std::cout << "Rotating..." << std::endl << std::endl;
rotateMatrix( );
printMatrix( );
std::cout << std::endl;
std::cout << "Rotating..." << std::endl << std::endl;
rotateMatrix( );
printMatrix( );
std::cout << std::endl;
std::cout << "Rotating..." << std::endl << std::endl;
rotateMatrix( );
printMatrix( );
return( 0 );
} // Closing main( int, char* )
// End of file 01_07_RotateMatrix.cpp
| 28.681159 | 84 | 0.457302 | Teabeans |
fa1d53c016e8862b1034f23a46c39111cbee4868 | 139 | cc | C++ | tests/data/test-diff-suppr/test22-suppr-removed-var-sym-v1.cc | insilications/libabigail-clr | 1eb5d367686626660d3cc987b473f296b0a59152 | [
"Apache-2.0"
] | 3 | 2021-01-29T20:26:44.000Z | 2021-04-28T07:49:48.000Z | tests/data/test-diff-suppr/test22-suppr-removed-var-sym-v1.cc | insilications/libabigail-clr | 1eb5d367686626660d3cc987b473f296b0a59152 | [
"Apache-2.0"
] | 2 | 2021-03-07T19:31:56.000Z | 2021-03-07T23:26:13.000Z | tests/data/test-diff-suppr/test22-suppr-removed-var-sym-v1.cc | insilications/libabigail-clr | 1eb5d367686626660d3cc987b473f296b0a59152 | [
"Apache-2.0"
] | 1 | 2021-03-07T19:14:08.000Z | 2021-03-07T19:14:08.000Z | // Compile this without debug info with:
// g++ -Wall -c test22-suppr-removed-var-sym-v1.cc
int global_var0 = 0;
double global_var3 = 0;
| 23.166667 | 51 | 0.705036 | insilications |
fa22efbe915b9c31259c8762a991b410db1c96cb | 2,920 | cpp | C++ | client/cpp/src/net/tcp_client.cpp | Heng-W/network | 49e34a51b19f34b443f7a914b45f47acd146d562 | [
"MIT"
] | null | null | null | client/cpp/src/net/tcp_client.cpp | Heng-W/network | 49e34a51b19f34b443f7a914b45f47acd146d562 | [
"MIT"
] | null | null | null | client/cpp/src/net/tcp_client.cpp | Heng-W/network | 49e34a51b19f34b443f7a914b45f47acd146d562 | [
"MIT"
] | null | null | null |
#include "tcp_client.h"
#include "../util/logger.h"
#include "connector.h"
#include "socket.h"
namespace net
{
TcpClient::TcpClient(const InetAddress& serverAddr)
: connector_(new Connector(serverAddr)),
connectionCallback_(defaultConnectionCallback),
messageCallback_(defaultMessageCallback),
quit_(false),
recv_(false),
connect_(true),
retry_(false),
name_("Tcp Client"),
baseThreadId_(std::this_thread::get_id()),
recvThread_{&TcpClient::recvThreadFunc, this}
{
connector_->setNewConnectionCallback([this](int sockfd) { this->newConnection(sockfd); });
LOG(INFO) << "TcpClient::TcpClient[" << name_
<< "] - connector " << connector_.get();
}
TcpClient::~TcpClient()
{
LOG(INFO) << "TcpClient::~TcpClient[" << name_
<< "] - connector " << connector_.get();
quit_ = true;
recvCond_.notify_one();
recvThread_.join();
}
void TcpClient::start()
{
assert(isInBaseThread());
LOG(INFO) << "TcpClient::connect[" << name_ << "] - connecting to "
<< connector_->serverAddress().toIpPort();
connect_ = true;
connector_->start();
}
void TcpClient::stop()
{
connect_ = false;
TcpConnectionPtr conn;
{
std::lock_guard<std::mutex> lock(mutex_);
conn = connection_;
}
if (conn)
{
conn->shutdown();
}
else
{
connector_->stop();
}
}
void TcpClient::setRetryDelay(int delayMs, bool fixed)
{
connector_->setRetryDelay(delayMs, fixed);
}
void TcpClient::newConnection(int sockfd)
{
InetAddress peerAddr = sockets::getPeerAddr(sockfd);
TcpConnectionPtr conn = std::make_shared<TcpConnection>(sockfd, peerAddr);
conn->setMessageCallback(messageCallback_);
conn->setWriteCompleteCallback(writeCompleteCallback_);
{
std::lock_guard<std::mutex> lock(mutex_);
connection_ = conn;
}
if (!connect_) return;
conn->connectEstablished();
// enable reading
recv_ = true;
recvCond_.notify_one();
connectionCallback_(conn);
conn->doSendEvent();
{
std::unique_lock<std::mutex> lock(mutex_);
recvCond_.wait(lock, [this] { return !recv_ || quit_; });
connection_.reset();
}
conn->connectDestroyed();
connectionCallback_(conn);
conn.reset();
if (retry_ && connect_)
{
LOG(INFO) << "TcpClient::connect[" << name_ << "] - Reconnecting to "
<< connector_->serverAddress().toIpPort();
connector_->start();
}
}
void TcpClient::recvThreadFunc()
{
while (!quit_)
{
{
std::unique_lock<std::mutex> lock(mutex_);
recvCond_.wait(lock, [this] { return recv_ || quit_; });
}
if (quit_) return;
connection_->doRecvEvent();
recv_ = false;
recvCond_.notify_one();
}
}
} // namespace net
| 21.62963 | 94 | 0.603082 | Heng-W |
fa26334d0dd0ebdc20aba0b1d40e6a776c173f77 | 3,306 | cpp | C++ | benchmark/pubsub.cpp | Watch-Later/shadesmar | be782a0ead538ea74463947a2ca17c94124ab514 | [
"MIT"
] | 298 | 2019-08-05T04:28:05.000Z | 2022-03-28T09:02:18.000Z | benchmark/pubsub.cpp | xian0gang/shadesmar | 041ce70133ad413f3e68645fa5d1ad5800d7354b | [
"MIT"
] | 34 | 2019-11-26T15:52:04.000Z | 2022-03-06T14:04:24.000Z | benchmark/pubsub.cpp | xian0gang/shadesmar | 041ce70133ad413f3e68645fa5d1ad5800d7354b | [
"MIT"
] | 38 | 2019-11-24T14:18:38.000Z | 2022-03-31T01:58:53.000Z | /* MIT License
Copyright (c) 2020 Dheeraj R Reddy
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 <cassert>
#include <chrono>
#include <iostream>
#ifdef SINGLE_HEADER
#include "shadesmar.h"
#else
#include "shadesmar/memory/copier.h"
#include "shadesmar/memory/dragons.h"
#include "shadesmar/pubsub/publisher.h"
#include "shadesmar/pubsub/subscriber.h"
#include "shadesmar/stats.h"
#endif
const char topic[] = "raw_benchmark_topic";
shm::stats::Welford per_second_lag;
struct Message {
uint64_t count;
uint64_t timestamp;
uint8_t *data;
};
uint64_t current_count = 0;
void callback(shm::memory::Memblock *memblock) {
if (memblock->is_empty()) {
return;
}
auto *msg = reinterpret_cast<Message *>(memblock->ptr);
auto lag = shm::current_time() - msg->timestamp;
// assert(current_count == msg->count - 1);
assert(current_count < msg->count);
current_count = msg->count;
per_second_lag.add(lag);
}
void subscribe_loop(int seconds) {
shm::pubsub::Subscriber sub(topic, callback);
for (int sec = 0; sec < seconds; ++sec) {
auto start = std::chrono::steady_clock::now();
for (auto now = start; now < start + std::chrono::seconds(1);
now = std::chrono::steady_clock::now()) {
sub.spin_once();
}
std::cout << per_second_lag << std::endl;
per_second_lag.clear();
}
}
void publish_loop(int seconds, int vector_size) {
std::cout << "Number of bytes = " << vector_size << std::endl;
std::cout << "Time unit = " << TIMESCALE_NAME << std::endl;
auto *rawptr = malloc(vector_size);
std::memset(rawptr, 255, vector_size);
Message *msg = reinterpret_cast<Message *>(rawptr);
msg->count = 0;
shm::pubsub::Publisher pub(topic);
auto start = std::chrono::steady_clock::now();
for (auto now = start; now < start + std::chrono::seconds(seconds);
now = std::chrono::steady_clock::now()) {
msg->count++;
msg->timestamp = shm::current_time();
pub.publish(msg, vector_size);
}
free(msg);
}
int main() {
const int SECONDS = 10;
const int VECTOR_SIZE = 32 * 1024;
std::thread subscribe_thread(subscribe_loop, SECONDS);
std::thread publish_thread(publish_loop, SECONDS, VECTOR_SIZE);
subscribe_thread.join();
publish_thread.join();
}
| 31.188679 | 80 | 0.699335 | Watch-Later |
fa2773883101d19fb4a9236d013891fd8d8796f5 | 2,172 | cpp | C++ | src/e101_200/q1414.cpp | extremedeckguru/leetcode | e45923ccbca7ae1c5f85d8c996392e8b492c1306 | [
"MIT"
] | 9 | 2020-04-09T12:37:50.000Z | 2021-04-01T14:01:14.000Z | src/e101_200/q1414.cpp | extremedeckguru/leetcode | e45923ccbca7ae1c5f85d8c996392e8b492c1306 | [
"MIT"
] | 3 | 2020-05-05T02:43:54.000Z | 2020-05-20T11:12:16.000Z | src/e101_200/q1414.cpp | extremedeckguru/leetcode | e45923ccbca7ae1c5f85d8c996392e8b492c1306 | [
"MIT"
] | 5 | 2020-04-17T02:32:10.000Z | 2020-05-20T10:12:26.000Z | /*
#面试刷题# 第0101期
#Leetcode# Q1414 找出和为K的斐波那契数的最小个数
难度:中
给定一个数k,返回其总和等于k的斐波那契数的最小值,一个斐波那契数是否可以多次使用。
斐波那契数的定义为。
F1 = 1
F2 = 1
Fn = Fn-1 + Fn-2 ,对于 n > 2。
可以保证,对于给定的约束,我们总是可以找到这样的斐波那契数和k。
约束条件:
1 <= k <= 10^9
示例1:
Input: k = 7
Output: 2
Explanation: The Fibonacci numbers are: 1, 1, 2, 3, 5, 8, 13, ...
For k = 7 we can use 2 + 5 = 7.
示例2:
Input: k = 10
Output: 2
Explanation: For k = 10 we can use 2 + 8 = 10.
示例3:
Input: k = 19
Output: 3
Explanation: For k = 19 we can use 1 + 5 + 13 = 19.
*/
#include "leetcode.h"
namespace q1414 {
template<typename T>
bool run_testcases() {
T slt;
CHECK_RET(2 == slt.findMinFibonacciNumbers(7));
CHECK_RET(2 == slt.findMinFibonacciNumbers(10));
CHECK_RET(3 == slt.findMinFibonacciNumbers(19));
return true;
}
// Runtime: 4 ms, faster than 79.64%
// Memory Usage: 6.5 MB, less than 100.00%
class Solution {
public:
int findMinFibonacciNumbers(int k) {
// compute fibonacci
vector<int> fib{1,1};
for (int i=0; fib[i] + fib[i+1] <= k; ++i) {
fib.push_back(fib[i] + fib[i+1]);
}
// search answer starting from the bigger
int ret = 0;
for (auto iter = fib.rbegin(); iter != fib.rend(); ++iter) {
if (*iter > k) {continue;}
k -= *iter;
++ret;
if(0 == k) {break;}
}
return ret;
}
};
TEST(Q1414, Solution) {EXPECT_TRUE(run_testcases<Solution>());}
// @Tiabeanie2
class Solution02 {
public:
int findMinFibonacciNumbers(int k) {
vector<int> fibos = {1, 1};
while (fibos.back() < 1e9)
{
fibos.push_back(fibos.back() + fibos[fibos.size() - 2]);
}
int ans = 0;
while (k > 1)
{
auto it = std::lower_bound(fibos.begin(), fibos.end(), k);
if (*it == k)
{
ans ++;
break;
}
--it;
ans ++;
k -= *it;
}
if (k == 1) ans ++;
return ans;
}
};
TEST(Q1414, Solution02) {EXPECT_TRUE(run_testcases<Solution02>());}
}; // nam;espace q1414
| 21.939394 | 70 | 0.521179 | extremedeckguru |
fa3088878e65c7ab1c033618f5767c58136e9b80 | 215 | cpp | C++ | Dataset/Leetcode/train/9/223.cpp | kkcookies99/UAST | fff81885aa07901786141a71e5600a08d7cb4868 | [
"MIT"
] | null | null | null | Dataset/Leetcode/train/9/223.cpp | kkcookies99/UAST | fff81885aa07901786141a71e5600a08d7cb4868 | [
"MIT"
] | null | null | null | Dataset/Leetcode/train/9/223.cpp | kkcookies99/UAST | fff81885aa07901786141a71e5600a08d7cb4868 | [
"MIT"
] | null | null | null | class Solution {
public:
bool XXX(int x) {
if(x<0) return false;
int a=0,b=x;
while(x&&a<INT_MAX/10){
a=a*10+x%10;
x/=10;
}
return a==b;
}
};
| 15.357143 | 31 | 0.4 | kkcookies99 |
fa3160e3512af74c6b754aca100ddde23e4fb24a | 5,372 | cpp | C++ | 03_Tutorial/T02_XMCocos2D-CookBook/Source/Recipes/Ch7_Waypoints.cpp | mcodegeeks/OpenKODE-Framework | d4382d781da7f488a0e7667362a89e8e389468dd | [
"MIT"
] | 2 | 2017-08-03T07:15:00.000Z | 2018-06-18T10:32:53.000Z | 03_Tutorial/T02_XMCocos2D-CookBook/Source/Recipes/Ch7_Waypoints.cpp | mcodegeeks/OpenKODE-Framework | d4382d781da7f488a0e7667362a89e8e389468dd | [
"MIT"
] | null | null | null | 03_Tutorial/T02_XMCocos2D-CookBook/Source/Recipes/Ch7_Waypoints.cpp | mcodegeeks/OpenKODE-Framework | d4382d781da7f488a0e7667362a89e8e389468dd | [
"MIT"
] | 2 | 2019-03-04T22:57:42.000Z | 2020-03-06T01:32:26.000Z | /* --------------------------------------------------------------------------
*
* File Ch7_Waypoints.cpp
* Ported By Young-Hwan Mun
* Contact xmsoft77@gmail.com
*
* Created By Nate Burba
* Contact Cocos2dCookbook@gmail.com
*
* --------------------------------------------------------------------------
*
* Copyright (c) 2010-2013 XMSoft.
* Copyright (c) 2011 COCOS2D COOKBOOK. 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 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 in 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 "Ch7_Waypoints.h"
KDbool Ch7_Waypoints::init ( KDvoid )
{
// Set game area size
m_tGameAreaSize = ccp ( 1000 / PTM_RATIO, 600 / PTM_RATIO ); // Box2d units
if ( !GameArea2D::init ( ) )
{
return KD_FALSE;
}
m_pMessage->setString ( "Tap the screen move the actor to that point.\nTap again to queue another waypoint." );
// Add polygons
this->addRandomPolygons ( 10 );
// Create Actor
this->addActor ( );
// Add draw layer
this->addDrawLayer ( );
// Create level boundaries
this->addLevelBoundaries ( );
// Initial variables
m_fCameraZoom = 0.45f;
return KD_TRUE;
}
KDvoid Ch7_Waypoints::step ( KDfloat fDelta )
{
GameArea2D::step ( fDelta );
// Process actor waypoints
m_pActor->processWaypoints ( );
// Turn actor toward waypoints
if ( m_pActor->getWaypoints ( )->count ( ) > 0 )
{
b2Body* pBody = m_pActor->getBody ( );
CCPoint tMovementVector = ccp ( pBody->GetLinearVelocity ( ).x, pBody->GetLinearVelocity ( ).y );
pBody->SetTransform ( pBody->GetPosition ( ), -1 * GameHelper::vectorToRadians ( tMovementVector ) + PI_CONSTANT / 2 );
}
}
/// Add actor to scene
KDvoid Ch7_Waypoints::addActor ( KDvoid )
{
m_pActor = GameActor::create ( );
m_pActor->setGameArea ( this );
b2BodyDef* pBodyDef = m_pActor->getBodyDef ( );
pBodyDef->type = b2_dynamicBody;
pBodyDef->position.Set ( 240 / PTM_RATIO, 160 / PTM_RATIO );
pBodyDef->userData = m_pActor;
b2Body* pBody = m_pWorld->CreateBody ( pBodyDef );
m_pActor->setBody ( pBody );
b2CircleShape* pShape = new b2CircleShape ( );
m_pActor->setCircleShape ( pShape );
pShape->m_radius = 0.5f;
b2FixtureDef* pFixtureDef = m_pActor->getFixtureDef ( );
pFixtureDef->shape = pShape;
pFixtureDef->isSensor = KD_FALSE;
pBody->CreateFixture ( pFixtureDef );
}
/// Draw all waypoint lines
KDvoid Ch7_Waypoints::drawLayer ( KDvoid )
{
ccDrawColor4B ( 255, 255, 0, 128 );
b2Vec2 tPosition = m_pActor->getBody ( )->GetPosition ( );
CCPoint tActorPosition = ccp ( tPosition.x * PTM_RATIO, tPosition.y * PTM_RATIO );
CCArray* pWaypoints = m_pActor->getWaypoints ( );
if ( pWaypoints->count ( ) == 1 )
{
GameWaypoint* pWaypoint = (GameWaypoint*) pWaypoints->objectAtIndex ( 0 );
ccDrawLine ( tActorPosition, pWaypoint->getPosition ( ) );
}
else if ( pWaypoints->count ( ) > 1 )
{
for ( KDuint i = 0; i < pWaypoints->count ( ) - 1; i++ )
{
GameWaypoint* pWaypoint = (GameWaypoint*) pWaypoints->objectAtIndex ( i );
GameWaypoint* pWaypointNext = (GameWaypoint*) pWaypoints->objectAtIndex ( i + 1 );
if ( i == 0 )
{
// From actor to first waypoint
ccDrawLine ( tActorPosition, pWaypoint->getPosition ( ) );
ccDrawLine ( pWaypoint->getPosition ( ), pWaypointNext->getPosition ( ) );
}
else
{
// From this waypoint to next one
ccDrawLine ( pWaypoint->getPosition ( ), pWaypointNext->getPosition ( ) );
}
}
}
}
/// Add extra drawing layer
KDvoid Ch7_Waypoints::addDrawLayer ( KDvoid )
{
m_pDrawLayer = DrawLayer::create ( );
m_pDrawLayer->setPosition ( ccp ( 0, 0 ) );
m_pDrawLayer->setRecipe ( this );
m_pGameNode->addChild ( m_pDrawLayer, 10 );
}
/// Add a new waypoint when you touch the screen
KDvoid Ch7_Waypoints::tapWithPoint ( const CCPoint& tPoint )
{
GameWaypoint* pWaypoint = GameWaypoint::create ( this->convertTouchCoord ( tPoint ), 1.f );
pWaypoint->setPreCallback ( ObjectCallback::create ( this, callfunc_selector ( Ch7_Waypoints::movingToWaypoint ) ) );
pWaypoint->setPostCallback ( ObjectCallback::create ( this, callfunc_selector ( Ch7_Waypoints::reachedWaypoint ) ) );
m_pActor->addWaypoint ( pWaypoint );
}
/// WP message callbacks
KDvoid Ch7_Waypoints::reachedWaypoint ( KDvoid )
{
this->showMessage ( "Moving to WP" );
}
KDvoid Ch7_Waypoints::movingToWaypoint ( KDvoid )
{
this->showMessage ( "Reached WP" );
} | 31.232558 | 121 | 0.632725 | mcodegeeks |
fa33c7e062e7c5ed1374704d895628d0627ec2a1 | 2,474 | hpp | C++ | include/rcppmath/clamp.hpp | shumov-ag/rcpputils | a7898d98ab684bb5d0cb2c20c823a1b4014fa0dc | [
"Apache-2.0"
] | 14 | 2019-05-05T06:36:41.000Z | 2022-02-11T06:43:37.000Z | include/rcppmath/clamp.hpp | shumov-ag/rcpputils | a7898d98ab684bb5d0cb2c20c823a1b4014fa0dc | [
"Apache-2.0"
] | 125 | 2019-02-26T18:38:18.000Z | 2022-01-21T20:18:59.000Z | include/rcppmath/clamp.hpp | shumov-ag/rcpputils | a7898d98ab684bb5d0cb2c20c823a1b4014fa0dc | [
"Apache-2.0"
] | 39 | 2019-02-26T18:12:29.000Z | 2022-03-11T15:23:01.000Z | // Copyright 2020 PAL Robotics S.L.
//
// Licensed under the Apache License, Version 2.0 (the "License");
// you may not use this file except in compliance with the License.
// You may obtain a copy of the License at
//
// http://www.apache.org/licenses/LICENSE-2.0
//
// Unless required by applicable law or agreed to in writing, software
// distributed under the License is distributed on an "AS IS" BASIS,
// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
// See the License for the specific language governing permissions and
// limitations under the License.
/*! \file clamp.hpp
* \brief Restrict a value between two bounds.
*/
#ifndef RCPPMATH__CLAMP_HPP_
#define RCPPMATH__CLAMP_HPP_
#include <cassert>
namespace rcppmath
{
/**
* If v compares less than lo, returns lo; otherwise if hi compares less
* than v, returns hi; otherwise returns v. Uses operator< to compare the values.
*
* \param[in] v The value to clamp.
* \param[in] lo The lower boundary.
* \param[in] hi The higher boundary.
* \return Reference to lo if v is less than lo, reference to hi if hi is less than v, otherwise
* reference to v.
* \note Implementation from https://en.cppreference.com/w/cpp/algorithm/clamp.
* \warning Capturing the result of clamp by reference if one of the parameters is rvalue produces
* a dangling reference if that parameter is returned.
*/
template<class T>
constexpr const T & clamp(const T & v, const T & lo, const T & hi)
{
assert(!(hi < lo) );
return (v < lo) ? lo : (hi < v) ? hi : v;
}
/**
* Performs clamping with a provided Comparison object (comp).
*
* \param[in] v The value to clamp.
* \param[in] lo The lower boundary.
* \param[in] hi The higher boundary.
* \param[in] comp Comparison object that returns true if the first argument is
* less than the second.
* \return Reference to lo if v is less than lo, reference to hi if hi is less than v, otherwise
* reference to v. "Less than" semantics determined by Comparison object.
* \warning Capturing the result of clamp by reference if one of the parameters is rvalue produces
* a dangling reference if that parameter is returned.
* \sa rcppmath::clamp(const T&, const T&, const T&)
*/
template<class T, class Compare>
constexpr const T & clamp(const T & v, const T & lo, const T & hi, Compare comp)
{
assert(!comp(hi, lo) );
return comp(v, lo) ? lo : comp(hi, v) ? hi : v;
}
} // namespace rcppmath
#endif // RCPPMATH__CLAMP_HPP_
| 35.342857 | 98 | 0.710994 | shumov-ag |
fa35dd16f796e2efc6d61495c26e22b135919be9 | 406 | cpp | C++ | src/techniques/lrel.cpp | shibii/nn | 2022ec423c3bfe179997630d6ba705aeaabdd918 | [
"MIT"
] | 1 | 2020-11-17T14:25:28.000Z | 2020-11-17T14:25:28.000Z | src/techniques/lrel.cpp | shibii/nn | 2022ec423c3bfe179997630d6ba705aeaabdd918 | [
"MIT"
] | null | null | null | src/techniques/lrel.cpp | shibii/nn | 2022ec423c3bfe179997630d6ba705aeaabdd918 | [
"MIT"
] | null | null | null | #include "lrel.hpp"
namespace nn {
LReL::LReL(float leak) : leak_(leak) {}
void LReL::forward(Feed &f) {
input_ = f.signal;
f.signal = (input_ > 0.f) * input_ + (input_ <= 0.f) * input_ * leak_;
}
void LReL::backward(Feed &f) {
f.signal = (input_ > 0.f) * f.signal + (input_ <= 0.f) * f.signal * leak_;
}
template <class Archive>
void LReL::serialize(Archive &ar) {
ar(leak_);
}
} // namespace nn | 25.375 | 76 | 0.618227 | shibii |
fa3601c6cb60c9c0200636a17693bc5d3438e55b | 471 | cpp | C++ | BASIC c++/pointer-and-referencers/pointer1.cpp | jattramesh/Learning_git | 5191ecc6c0c11b69b9786f2a8bdd3db7228987d6 | [
"MIT"
] | null | null | null | BASIC c++/pointer-and-referencers/pointer1.cpp | jattramesh/Learning_git | 5191ecc6c0c11b69b9786f2a8bdd3db7228987d6 | [
"MIT"
] | null | null | null | BASIC c++/pointer-and-referencers/pointer1.cpp | jattramesh/Learning_git | 5191ecc6c0c11b69b9786f2a8bdd3db7228987d6 | [
"MIT"
] | null | null | null | //
// Created by Rahul on 6/5/2019.
//
#include <iostream>
#include<math.h>
using namespace std;
int var,*ptr;
int main()
{
var=100;
ptr=&var;
cout<<"value of var "<<var<<"address of ptr"<<&var<<endl;
cout<<"value pf ptr "<<ptr<<"address od ptr "<<&ptr<<endl;
long a=10,b;
long *ptr;
ptr=&a;
b=*ptr;
cout<<ptr<<endl<<b<<endl;
double x,y,*px;
px=&x;
*px=12;
*px+=4.5;
cout<<sin(*px)<<endl<<x<<endl;
return 0;
}
| 17.444444 | 62 | 0.532909 | jattramesh |
fa3685a95830cfa707379fe292adfeb218693d7e | 76,936 | hpp | C++ | snark-logic/libs-source/marshalling/include/nil/marshalling/options.hpp | idealatom/podlodkin-freeton-year-control | 6aa96e855fe065c9a75c76da976a87fe2d1668e6 | [
"MIT"
] | null | null | null | snark-logic/libs-source/marshalling/include/nil/marshalling/options.hpp | idealatom/podlodkin-freeton-year-control | 6aa96e855fe065c9a75c76da976a87fe2d1668e6 | [
"MIT"
] | null | null | null | snark-logic/libs-source/marshalling/include/nil/marshalling/options.hpp | idealatom/podlodkin-freeton-year-control | 6aa96e855fe065c9a75c76da976a87fe2d1668e6 | [
"MIT"
] | 1 | 2021-09-15T20:27:27.000Z | 2021-09-15T20:27:27.000Z | //---------------------------------------------------------------------------//
// Copyright (c) 2017-2021 Mikhail Komarov <nemo@nil.foundation>
// Copyright (c) 2020-2021 Nikita Kaskov <nbering@nil.foundation>
//
// MIT License
//
// 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.
//---------------------------------------------------------------------------//
/// @file
/// Contains definition of all the options used by the @b Marshalling library
#ifndef MARSHALLING_OPTIONS_HPP
#define MARSHALLING_OPTIONS_HPP
#include <tuple>
#include <type_traits>
#include <limits>
#include <ratio>
#include <cstdint>
#include <cstddef>
#include <nil/marshalling/endianness.hpp>
#include <nil/marshalling/units_types.hpp>
#include <nil/marshalling/status_type.hpp>
#include <nil/marshalling/types/optional_mode.hpp>
namespace nil {
namespace marshalling {
namespace option {
namespace detail {
template<typename T>
struct is_ratio_t {
static const bool value = false;
};
template<std::intmax_t TNum, std::intmax_t TDen>
struct is_ratio_t<std::ratio<TNum, TDen>> {
static const bool value = true;
};
template<typename T>
constexpr bool is_ratio() {
return is_ratio_t<T>::value;
}
} // namespace detail
// message/field_t common options
/// @brief options to specify endian.
/// @tparam TEndian endian_type type. Must be either nil::marshalling::endian::big_endian or
/// nil::marshalling::endian::little_endian.
/// @headerfile nil/marshalling/options.hpp
template<typename TEndian>
struct endian { };
/// @brief Alias option to endian_type specifying big endian.
/// @headerfile nil/marshalling/options.hpp
using big_endian = endian<nil::marshalling::endian::big_endian>;
/// @brief Alias option to endian_type specifying little endian.
/// @headerfile nil/marshalling/options.hpp
using little_endian = endian<nil::marshalling::endian::little_endian>;
/// @brief No-op option, doesn't have any effect.
/// @headerfile nil/marshalling/options.hpp
struct empty_option { };
/// @brief Option used to specify type of the ID.
/// @tparam T Type of the message ID.
/// @headerfile nil/marshalling/options.hpp
template<typename T>
struct msg_id_type { };
/// @brief Option used to specify type of iterator used for reading.
/// @tparam TIter Type of the iterator.
/// @headerfile nil/marshalling/options.hpp
template<typename TIter>
struct read_iterator { };
/// @brief Option used to specify type of iterator used for writing.
/// @tparam TIter Type of the iterator.
/// @headerfile nil/marshalling/options.hpp
template<typename TIter>
struct write_iterator { };
/// @brief Option used to add @b get_id() function into message interface.
/// @headerfile nil/marshalling/options.hpp
struct id_info_interface { };
/// @brief Option used to add @b valid() function into message interface.
/// @headerfile nil/marshalling/options.hpp
struct valid_check_interface { };
/// @brief Option used to add @b length() function into message interface.
/// @headerfile nil/marshalling/options.hpp
struct length_info_interface { };
/// @brief Option used to add @b refresh() function into message interface.
/// @headerfile nil/marshalling/options.hpp
struct refresh_interface { };
/// @brief Option used to add @b name() function into message interface.
/// @headerfile nil/marshalling/options.hpp
struct name_interface { };
/// @brief Option used to specify type of the message handler.
/// @tparam T Type of the handler.
/// @headerfile nil/marshalling/options.hpp
template<typename T>
struct handler { };
/// @brief Option used to specify numeric ID of the message.
/// @tparam TId Numeric ID value.
/// @headerfile nil/marshalling/options.hpp
template<std::intmax_t TId>
struct static_num_id_impl { };
/// @brief Option used to specify that message doesn't have valid ID.
/// @headerfile nil/marshalling/options.hpp
struct no_id_impl { };
/// @brief Option used to specify actual type of the message.
/// @headerfile nil/marshalling/options.hpp
template<typename TMsg>
struct msg_type { };
/// @brief Option used to inhibit default implementation of @b dispatch_impl()
/// in nil::marshalling::message_base.
/// @headerfile nil/marshalling/options.hpp
struct no_dispatch_impl { };
/// @brief Option used to specify some extra fields from transport framing.
/// @details Some fields from transport framing may influence the way on how
/// message fields get read or written. It may also have an influence on
/// how message is handled. This option is intended to provide a list
/// of such fields, bundled in @b std::tuple, to @ref nil::marshalling::message interface
/// class.
/// @tparam TFields The fields of the message bundled in std::tuple.
/// @headerfile nil/marshalling/options.hpp
template<typename TFields>
struct extra_transport_fields { };
/// @brief Option used to specify index of the version field inside
/// extra transport fields tuple provided with @ref
/// nil::marshalling::option::extra_transport_fields_type option.
/// @tparam TIdx Index of the field inside the tuple.
/// @headerfile nil/marshalling/options.hpp
template<std::size_t TIdx>
struct version_in_extra_transport_fields { };
/// @brief Option used to specify fields of the message and force implementation
/// of default read, write, validity check, and length retrieval information
/// of the message.
/// @tparam TFields The fields of the message bundled in std::tuple.
/// @headerfile nil/marshalling/options.hpp
template<typename TFields>
struct fields_impl;
/// @cond SKIP_DOC
template<typename... TFields>
struct fields_impl<std::tuple<TFields...>> { };
/// @endcond
/// @brief Alias to FieldsImpl<std::tuple<> >
/// @headerfile nil/marshalling/options.hpp
using zero_fields_impl = fields_impl<std::tuple<>>;
/// @brief Option that inhibits implementation of nil::marshalling::message_base::read_impl()
/// regardless of other availability conditions.
/// @headerfile nil/marshalling/options.hpp
struct no_read_impl { };
/// @brief Option that inhibits implementation of nil::marshalling::message_base::write_impl()
/// regardless of other availability conditions.
/// @headerfile nil/marshalling/options.hpp
struct no_write_impl { };
/// @brief Option that inhibits implementation of nil::marshalling::message_base::valid_impl()
/// regardless of other availability conditions.
/// @headerfile nil/marshalling/options.hpp
struct no_valid_impl { };
/// @brief Option that inhibits implementation of nil::marshalling::message_base::length_impl()
/// regardless of other availability conditions.
/// @headerfile nil/marshalling/options.hpp
struct no_length_impl { };
/// @brief Option that inhibits implementation of nil::marshalling::message_base::refresh_impl()
/// regardless of other availability conditions.
/// @headerfile nil/marshalling/options.hpp
struct no_refresh_impl { };
/// @brief Option that notifies nil::marshalling::message_base about existence of
/// @b eval_get_id() member function in derived class.
/// @headerfile nil/marshalling/options.hpp
struct has_do_get_id { };
/// @brief Option that notifies nil::marshalling::message_base about existence of
/// access to fields.
/// @details Can be useful when there is a chain of inheritances from
/// nil::marshalling::message_base.
/// @headerfile nil/marshalling/options.hpp
struct assume_fields_existence { };
/// @brief Option that forces "in place" allocation with placement "new" for
/// initialisation, instead of usage of dynamic memory allocation.
/// @headerfile nil/marshalling/options.hpp
struct in_place_allocation { };
/// @brief Option used to allow @ref nil::marshalling::generic_message generation inside
/// @ref nil::marshalling::msg_factory and/or @ref nil::marshalling::protocol::MsgIdLayer classes.
/// @tparam TGenericMessage Type of message, expected to be a variant of
/// @ref nil::marshalling::generic_message.
template<typename TGenericMessage>
struct support_generic_message { };
/// @brief Option used to specify number of bytes that is used for field serialization.
/// @details Applicable only to numeric fields, such as nil::marshalling::types::integral or
/// nil::marshalling::types::enumeration.
///
/// For example, protocol specifies that some field is serialized using
/// only 3 bytes. There is no basic integral type that takes 3 bytes
/// of space exactly. The closest alternative is std::int32_t or
/// std::uint32_t. Such field may be defined as:
/// @code
/// using MyFieldBase = nil::marshalling::field_type<nil::marshalling::option::BigEndian>;
/// using MyField =
/// nil::marshalling::types::integral<
/// MyFieldBase,
/// std::uint32_t,
/// nil::marshalling::option::fixed_length<3>
/// >;
/// @endcode
/// @tparam TLen length of the serialized value.
/// @tparam TSignExtend Perform sign extension, relevant only to signed types.
/// @headerfile nil/marshalling/options.hpp
template<std::size_t TLen, bool TSignExtend = true>
struct fixed_length { };
/// @brief Option used to specify number of bits that is used for field serialization
/// when a field is a member of nil::marshalling::types::bitfield.
/// @details For example, the protocol specifies that two independent integer
/// values of 6 and 10 bits respectively packed into two bytes to save space.
/// Such combined field may be defined as:
/// @code
/// using MyFieldBase = nil::marshalling::field_type<nil::marshalling::option::BigEndian>;
/// using MyField =
/// nil::marshalling::types::bitfield<
/// MyFieldBase,
/// std::tuple<
/// nil::marshalling::types::integral<
/// MyFieldBase,
/// std::uint8_t,
/// nil::marshalling::option::fixed_bit_length<6>
/// >,
/// nil::marshalling::types::integral<
/// MyFieldBase,
/// std::uint16_t,
/// nil::marshalling::option::fixed_bit_length<10>
/// >
/// >
/// >;
/// @endcode
/// @tparam TLen length of the serialized value in bits.
/// @headerfile nil/marshalling/options.hpp
template<std::size_t TLen>
struct fixed_bit_length { };
/// @brief Option used to specify that field may have variable serialization length
/// @details Applicable only to numeric fields, such as nil::marshalling::types::integral
/// or nil::marshalling::types::enumeration.
/// Use this option to specify that serialized value has
/// <a href="https://en.wikipedia.org/wiki/Variable-length_quantity">Base-128</a>
/// encoding, i.e. the most significant bit in the byte indicates whether
/// the encoding of the value is complete or the next byte in
/// sequence still encodes the current integer value. For example field
/// which value can be serialized using between 1 and 4 bytes can be
/// defined as:
/// @code
/// using MyFieldBase = nil::marshalling::field_type<nil::marshalling::option::BigEndian>;
/// using MyField =
/// nil::marshalling::types::integral<
/// MyFieldBase,
/// std::uint32_t,
/// nil::marshalling::option::var_length<1, 4>
/// >;
/// @endcode
/// @tparam TMin Minimal length the field may consume.
/// @tparam TMax Maximal length the field may consume.
/// @pre TMin <= TMax
/// @headerfile nil/marshalling/options.hpp
template<std::size_t TMin, std::size_t TMax>
struct var_length {
static_assert(TMin <= TMax, "TMin must not be greater that TMax.");
};
/// @brief Option to specify numeric value serialization offset.
/// @details Applicable only to numeric fields such as nil::marshalling::types::integral or
/// nil::marshalling::types::enumeration.
/// The provided value will be added to the field's value and the
/// result will be written to the buffer when serialising. Good example
/// for such option would be serialising a "current year" value. Most protocols
/// now specify it as an offset from year 2000 or later and written as a
/// single byte, i.e. to specify year 2015 is to write value 15.
/// However it may be inconvenient to manually adjust serialized/deserialized
/// value by predefined offset 2000. To help with such case option
/// nil::marshalling::option::num_value_ser_offset can be used. For example:
/// @code
/// using MyFieldBase = nil::marshalling::field_type<nil::marshalling::option::BigEndian>;
/// using MyField =
/// nil::marshalling::types::integral<
/// MyFieldBase,
/// std::uint16_t,
/// nil::marshalling::option::fixed_length<1>,
/// nil::marshalling::option::num_value_ser_offset<-2000>
/// >;
/// @endcode
/// Note that in the example above the field value (accessible by @b value() member
/// function of the field) will have type std::uint16_t and will be equal to
/// say 2015, while when serialized it consumes only 1 byte (thanks to
/// nil::marshalling::option::fixed_length option) and reduced value of 15 is written.
/// @tparam TOffset Offset value to be added when serialising field.
/// @headerfile nil/marshalling/options.hpp
template<std::intmax_t TOffset>
struct num_value_ser_offset { };
/// @brief Option that forces usage of embedded uninitialised data area instead
/// of dynamic memory allocation.
/// @details Applicable to fields that represent collection of raw data or other
/// fields, such as nil::marshalling::types::array_list or nil::marshalling::types::string. By
/// default, these fields will use
/// <a href="http://en.cppreference.com/w/cpp/container/vector">std::vector</a> or
/// <a href="http://en.cppreference.com/w/cpp/string/basic_string">std::string</a>
/// for their internal data storage. If this option is used, it will force
/// such fields to use @ref nil::marshalling::container::static_vector or @ref
/// nil::marshalling::container::static_string with the capacity provided by this option.
/// @tparam TSize Size of the storage area in number of elements, for strings it does @b NOT include
/// the '\0' terminating character.
/// @headerfile nil/marshalling/options.hpp
template<std::size_t TSize>
struct fixed_size_storage { };
/// @brief Set custom storage type for fields like nil::marshalling::types::string or
/// nil::marshalling::types::array_list.
/// @details By default nil::marshalling::types::string uses
/// <a href="http://en.cppreference.com/w/cpp/string/basic_string">std::string</a>
/// and nil::marshalling::types::array_list uses
/// <a href="http://en.cppreference.com/w/cpp/container/vector">std::vector</a> as
/// their internal storage types. The @ref fixed_size_storage option forces
/// them to use nil::marshalling::container::static_string and
/// nil::marshalling::container::static_vector instead. This option can be used to provide any other
/// third party type. Such type must define the same public interface as @b std::string (when used with
/// nil::marshalling::types::string) or @b std::vector (when used with
/// nil::marshalling::types::array_list).
/// @tparam TType Custom storage type
/// @headerfile nil/marshalling/options.hpp
template<typename TType>
struct custom_storage_type { };
/// @brief Option to specify scaling ratio.
/// @details Applicable only to nil::marshalling::types::integral.
/// Sometimes the protocol specifies values being transmitted in
/// one units while when handling the message they are better to be handled
/// in another. For example, some distance information is transmitted as
/// integer value of millimetres, but while processing it should be handled as floating
/// point value of meters. Such field is defined as:
/// @code
/// using MyFieldBase = nil::marshalling::field_type<nil::marshalling::option::BigEndian>;
/// using MyField =
/// nil::marshalling::types::integral<
/// MyFieldBase,
/// std::int32_t,
/// nil::marshalling::option::scaling_ratio<1, 100>
/// >;
/// @endcode
/// Then, to accessed the scaled value of the field use @b scale_as() or
/// @b set_scaled() methods of nil::marshalling::types::integral field:
/// @code
/// void processField(const MyField& field)
/// {
/// auto distInMillimetres = field.value();
/// auto distInMeters = field.scale_as<double>();
/// }
/// @endcode
/// @tparam TNum Numerator of the scaling ratio.
/// @tparam TDenom Denominator of the scaling ratio.
/// @headerfile nil/marshalling/options.hpp
template<std::intmax_t TNum, std::intmax_t TDenom>
struct scaling_ratio {
static_assert(TNum != 0, "Wrong scaling ratio");
static_assert(TDenom != 0, "Wrong scaling ratio");
};
/// @brief Option that modifies the default behaviour of collection fields to
/// prepend the serialized data with number of @b elements information.
/// @details Quite often when collection of fields is serialized it must be
/// prepended with one or more bytes indicating number of elements that will
/// follow.
/// Applicable to fields that represent collection of raw data or other
/// fields, such as nil::marshalling::types::array_list or nil::marshalling::types::string.@n
/// For example sequence of raw bytes must be prefixed with 2 bytes stating
/// the size of the sequence:
/// @code
/// using MyFieldBase = nil::marshalling::field_type<nil::marshalling::option::BigEndian>;
/// using MyField =
/// nil::marshalling::types::array_list<
/// MyFieldBase,
/// std::uint8_t,
/// nil::marshalling::option::sequence_size_field_prefix_type<
/// nil::marshalling::types::integral<MyFieldBase, std::uint16_t>
/// >
/// >;
/// @endcode
/// @tparam TField Type of the field that represents size
/// @headerfile nil/marshalling/options.hpp
template<typename TField>
struct sequence_size_field_prefix { };
/// @brief Option that modifies the default behaviour of collection fields to
/// prepend the serialized data with number of @b bytes information.
/// @details Similar to @ref sequence_size_field_prefix_type, but instead of
/// number of @b elements to follow, the prefix field contains number of
/// @b bytes that will follow.
/// @code
/// using MyFieldBase = nil::marshalling::field_type<nil::marshalling::option::BigEndian>;
/// using MyField =
/// nil::marshalling::types::array_list<
/// MyFieldBase,
/// nil::marshalling::types::bundle<
/// std::tuple<
/// nil::marshalling::types::integral<MyFieldBase, std::uint32_t>,
/// nil::marshalling::types::string<MyFieldBase>
/// >
/// >,
/// nil::marshalling::option::sequence_ser_length_field_prefix_type<
/// nil::marshalling::types::integral<MyFieldBase, std::uint16_t>
/// >
/// >;
/// @endcode
/// @tparam TField Type of the field that represents serialization length
/// @tparam TReadErrorStatus Error status to return in case read operation fails when should not
/// @headerfile nil/marshalling/options.hpp
template<typename TField,
status_type TReadErrorStatus = status_type::invalid_msg_data>
struct sequence_ser_length_field_prefix { };
/// @brief Option that forces <b>every element</b> of @ref nil::marshalling::types::array_list to
/// be prefixed with its serialization length.
/// @details Similar to @ref sequence_ser_length_field_prefix_type but instead of the whole
/// list, every element is prepended with its serialization length.
/// @tparam TField Type of the field that represents serialization length
/// @tparam TReadErrorStatus Error status to return in case read operation fails when should not
/// @headerfile nil/marshalling/options.hpp
template<typename TField,
status_type TReadErrorStatus = status_type::invalid_msg_data>
struct sequence_elem_ser_length_field_prefix { };
/// @brief Option that forces @b first element only of @ref nil::marshalling::types::array_list to
/// be prefixed with its serialization length.
/// @details Similar to @ref sequence_elem_ser_length_field_prefix_type, but
/// applicable only to the lists where elements are of the same
/// fixed size, where there is no need to prefix @b every element
/// with its size.
/// @tparam TField Type of the field that represents serialization length
/// @tparam TReadErrorStatus Error status to return in case read operation fails when should not
/// @headerfile nil/marshalling/options.hpp
template<typename TField,
status_type TReadErrorStatus = status_type::invalid_msg_data>
struct sequence_elem_fixed_ser_length_field_prefix { };
/// @brief Option that forces termination of the sequence when predefined value
/// is encountered.
/// @details Sometimes protocols use zero-termination for strings instead of
/// prefixing them with their size. Below is an example of how to achieve
/// such termination using sequence_termination_field_suffix option.
/// @code
/// using MyFieldBase = nil::marshalling::field_type<nil::marshalling::option::BigEndian>;
/// using MyField =
/// nil::marshalling::types::string<
/// MyFieldBase,
/// nil::marshalling::option::sequence_termination_field_suffix<
/// nil::marshalling::types::integral<MyFieldBase, char,
/// nil::marshalling::option::default_num_value<0> >
/// >
/// >;
/// @endcode
/// @tparam TField Type of the field that represents suffix
/// @headerfile nil/marshalling/options.hpp
template<typename TField>
struct sequence_termination_field_suffix { };
/// @brief Option that forces collection fields to append provides suffix every
/// time it is serialized.
/// @details It is a bit looser version than sequence_termination_field_suffix.
/// Encountering the expected termination value doesn't terminate the
/// read operation on the sequence. The size of the sequence should
/// be defined by other means. For example, zero termination string that
/// occupies exactly 6 bytes when serialized (padded with zeroes at the end)
/// will be defined like this:
/// @code
/// using MyFieldBase = nil::marshalling::field_type<nil::marshalling::option::BigEndian>;
/// using MyField =
/// nil::marshalling::types::string<
/// MyFieldBase,
/// nil::marshalling::option::sequence_fixed_size<5>,
/// nil::marshalling::option::sequence_trailing_field_suffix<
/// nil::marshalling::types::integral<MyFieldBase, char,
/// nil::marshalling::option::default_num_value<0> >
/// >
/// >;
/// @endcode
/// @tparam TField Type of the field that represents suffix
/// @headerfile nil/marshalling/options.hpp
template<typename TField>
struct sequence_trailing_field_suffix { };
/// @brief Option to enable external forcing of the collection's elements count.
/// @details Sometimes the size information is detached from the data sequence
/// itself, i.e. there may be one or more independent fields between the
/// size field and the first byte of the collection. In such case it becomes
/// impossible to use @ref sequence_size_field_prefix_type option. Instead, the size
/// information must be provided by external calls. Usage of this option
/// enables @b force_read_elem_count() and @b clear_read_elem_count() functions in
/// the collection fields, such as nil::marshalling::types::array_list or
/// nil::marshalling::types::string which can be used to specify the size information after it was read
/// independently.
/// @headerfile nil/marshalling/options.hpp
struct sequence_size_forcing_enabled { };
/// @brief Option to enable external forcing of the collection's serialization length
/// duting "read" operation.
/// @details Sometimes the length information is detached from the data sequence
/// itself, i.e. there may be one or more independent fields between the
/// length field and the first byte of the collection. In such case it becomes
/// impossible to use @ref sequence_ser_length_field_prefix_type option. Instead, the length
/// information must be provided by external calls. Usage of this option
/// enables @b force_read_length() and @b clear_read_length_forcing() functions in
/// the collection fields, such as nil::marshalling::types::array_list or
/// nil::marshalling::types::string which can be used to specify the size information after it was read
/// independently.
/// @headerfile nil/marshalling/options.hpp
struct sequence_length_forcing_enabled { };
/// @brief Option to enable external forcing of the collection element
/// serialization length.
/// @details Some protocols may prefix the variable length lists with serialization
/// length of a <b>single element</b> in addition to the number of elements
/// in the list. Usage of this option
/// enables @b force_read_elem_length() and @b clear_read_elem_length_forcing() functions in
/// the nil::marshalling::types::array_list
/// which can be used to specify the element serialization length after it was read
/// independently. @n
/// @headerfile nil/marshalling/options.hpp
struct sequence_elem_length_forcing_enabled { };
/// @brief Option used to define exact number of elements in the collection field.
/// @details Protocol specification may define that there is exact number of
/// elements in the sequence. Use sequence_fixed_size option to convey
/// this information to the field definition, which will force @b read() and
/// @b write() member functions of the collection field to behave as expected.
/// @headerfile nil/marshalling/options.hpp
template<std::size_t TSize>
struct sequence_fixed_size { };
/// @brief Option that forces usage of fixed size storage for sequences with fixed
/// size.
/// @details Equivalent to @ref fixed_size_storage option, but applicable only
/// to sequence types @ref nil::marshalling::types::array_list or @ref nil::marshalling::types::string,
/// that alrady use @ref sequence_fixed_size option. Usage of this option do not require knowledge of
/// the storage area size.
/// @headerfile nil/marshalling/options.hpp
struct sequence_fixed_size_use_fixed_size_storage { };
/// @brief Option that specifies default initialisation class.
/// @details Use this option when default constructor of the field must assign
/// some special value. The initialiser class provided as template argument
/// must define the following member function:
/// @code
/// struct MyInitialiser
/// {
/// template <typename TField>
/// void operator()(TField& field) {...}
/// };
/// @endcode
/// For example, we want string field that will have "hello" as its default
/// value. The provided initialiser class with the option will be instantiated
/// and its operator() is invoked which is responsible to assign proper
/// value to the field.
/// @code
/// struct MyStringInitialiser
/// {
/// template <typename TField>
/// void operator()(TField& field) const
/// {
/// field.value() = hello;
/// }
/// };
///
/// using MyFieldBase = nil::marshalling::field_type<nil::marshalling::option::BigEndian>;
/// using MyField =
/// nil::marshalling::types::string<
/// MyFieldBase,
/// nil::marshalling::option::default_value_initializer<MyStringInitialiser>
/// >;
/// @endcode
/// @tparam T Type of the initialiser class.
/// @headerfile nil/marshalling/options.hpp
template<typename T>
struct default_value_initialiser { };
/// @brief Option that specifies custom validation class.
/// @details By default, value of every field is considered to be valid
/// (@b valid() member function of the field returns @b true). If there is a need
/// to validate the value of the function, use this option to define
/// custom validation logic for the field. The validation class provided as
/// a template argument to this option must define the following member function:
/// @code
/// struct MyValidator
/// {
/// template <typename TField>
/// bool operator()(const TField& field) {...}
/// };
/// @endcode
/// For example, value of the string field considered to be valid if it's
/// not empty and starts with '$' character.
/// The provided validator class with the option will be instantiated
/// and its operator() will be invoked.
/// @code
/// struct MyStringValidator
/// {
/// template <typename TField>
/// bool operator()(TField& field) const
/// {
/// auto& str = field.value();
/// return (!str.empty()) && (str[0] == '$');
/// }
/// };
///
/// using MyFieldBase = nil::marshalling::field_type<nil::marshalling::option::BigEndian>;
/// using MyField =
/// nil::marshalling::types::string<
/// MyFieldBase,
/// nil::marshalling::option::contents_validator<MyStringValidator>
/// >;
/// @endcode
/// Note that in the example above the default constructed MyField will
/// have invalid value. To fix that you must also use
/// nil::marshalling::option::default_value_initializer option to specify proper default
/// value.
/// @tparam T Type of the validator class.
/// @headerfile nil/marshalling/options.hpp
template<typename T>
struct contents_validator { };
/// @brief Option that specifies custom refreshing class.
/// @details The "refreshing" functionality is there to allow bringing field's
/// contents into a consistent state if it's not. The default "refreshing"
/// functionality does nothing and returns @b false (meaning nothing has
/// been changed). If there is a need to provide custom refreshing functionality
/// use this option and provide custom refresher class. It must
/// define the following member function:
/// @code
/// struct MyRefresher
/// {
/// template <typename TField>
/// bool operator()(TField& field) {
/// ... // return true if field's contents changed
/// }
/// };
/// @endcode
/// @tparam T Type of the refresher class.
/// @headerfile nil/marshalling/options.hpp
template<typename T>
struct contents_refresher { };
/// @brief Option that specifies custom value reader class.
/// @details It may be useful to override default reading functionality for complex
/// fields, such as nil::marshalling::types::bundle, where the way members are read is
/// defined by the values of other members. For example, bundle of two integer
/// fields, the first one is normal, and the second one is optional.
/// The optional mode of the latter is determined by
/// the value of the first field. If its value is 0, than the second
/// member exists, otherwise it's missing.
/// @code
/// typedef nil::marshalling::types::bundle<
/// nil::marshalling::field_type<BigEndianOpt>,
/// std::tuple<
/// nil::marshalling::types::integral<
/// nil::marshalling::field_type<BigEndianOpt>,
/// std::uint8_t
/// >,
/// nil::marshalling::types::optional<
/// nil::marshalling::types::integral<
/// nil::marshalling::field_type<BigEndianOpt>,
/// std::uint16_t
/// >
/// >
/// >,
/// nil::marshalling::option::custom_value_reader<MyCustomReader>
/// > field_type;
/// @endcode
/// The @b MyCustomReader custom reading class may implement required
/// functionality of reading the first member, analysing its value, setting
/// appropriate mode for the second one and read the second member.
///
/// The custom value reader class provided as template argument
/// must define the following member function:
/// @code
/// struct MyCustomReader
/// {
/// template <typename TField, typename TIter>
/// nil::marshalling::ErrorStatus operator()(TField& field, TIter& iter, std::size_t len) {...}
/// };
/// @endcode
///
/// The custom reader for the example above may be implemented as:
/// @code
/// struct MyCustomReader
/// {
/// template <typename TField, typename TIter>
/// nil::marshalling::ErrorStatus operator()(TField& field, TIter& iter, std::size_t len) const
/// {
/// auto& members = field.value();
/// auto& first = std::get<0>(members);
/// auto& second = std::get<1>(members);
///
/// auto es = first.read(iter, len);
/// if (es != nil::marshalling::ErrorStatus::Success) {
/// return es;
/// }
///
/// if (first.value() != 0) {
/// second.set_mode(nil::marshalling::types::optional_mode::missing);
/// }
/// else {
/// second.set_mode(nil::marshalling::types::optional_mode::exists);
/// }
///
/// return second.read(iter, len - first.length());
/// }
/// };
/// @endcode
/// @tparam T Type of the custom reader class.
/// @headerfile nil/marshalling/options.hpp
template<typename T>
struct custom_value_reader { };
/// @brief Option that forces field's read operation to fail if invalid value
/// is received.
/// @details Sometimes protocol is very strict about what field's values are
/// allowed and forces to abandon a message if invalid value is received.
/// If nil::marshalling::option::fail_on_invalid is provided as an option to a field,
/// the validity is going to checked automatically after the read. If invalid
/// value is identified, error will be returned from the @b read() operation.
/// @tparam TStatus Error status to return when the content of the read field is invalid.
/// @headerfile nil/marshalling/options.hpp
template<status_type TStatus = status_type::invalid_msg_data>
struct fail_on_invalid { };
/// @brief Option that forces field's read operation to ignore read data if invalid value
/// is received.
/// @details If this option is provided to the field, the read operation will
/// check the validity of the read value. If it is identified as invalid,
/// the read value is not assigned to the field, i.e. the field's value
/// remains unchanged, although no error is reported.
/// @headerfile nil/marshalling/options.hpp
struct ignore_invalid { };
/// @brief Force the destructor of nil::marshalling::message class to be @b non-virtual,
/// even if there are other virtual functions defined.
/// @headerfile nil/marshalling/options.hpp
struct no_virtual_destructor { };
/// @brief options to specify units of the field.
/// @tparam TType Type of the unints, can be any type from nil::marshalling::traits::units
/// namespace.
/// @tparam TRatio Ratio within the units type, must be a variant of
/// @b std::ratio type.
/// @headerfile nil/marshalling/options.hpp
template<typename TType, typename TRatio>
struct units {
static_assert(detail::is_ratio_t<TRatio>(), "TRatio parameter must be a variant of std::ratio");
static_assert(TRatio::num != 0, "Wrong ratio value");
static_assert(TRatio::den != 0, "Wrong ratio value");
};
/// @brief Alias option, specifying field value units are "nanoseconds".
/// @headerfile nil/marshalling/options.hpp
using units_nanoseconds
= units<nil::marshalling::traits::units::Time, nil::marshalling::traits::units::nanoseconds_ratio>;
/// @brief Alias option, specifying field value units are "microseconds".
/// @headerfile nil/marshalling/options.hpp
using units_microseconds
= units<nil::marshalling::traits::units::Time, nil::marshalling::traits::units::microseconds_ratio>;
/// @brief Alias option, specifying field value units are "milliseconds".
/// @headerfile nil/marshalling/options.hpp
using units_milliseconds
= units<nil::marshalling::traits::units::Time, nil::marshalling::traits::units::milliseconds_ratio>;
/// @brief Alias option, specifying field value units are "seconds".
/// @headerfile nil/marshalling/options.hpp
using units_seconds
= units<nil::marshalling::traits::units::Time, nil::marshalling::traits::units::seconds_ratio>;
/// @brief Alias option, specifying field value units are "minutes".
/// @headerfile nil/marshalling/options.hpp
using units_minutes
= units<nil::marshalling::traits::units::Time, nil::marshalling::traits::units::minutes_ratio>;
/// @brief Alias option, specifying field value units are "hours".
/// @headerfile nil/marshalling/options.hpp
using units_hours
= units<nil::marshalling::traits::units::Time, nil::marshalling::traits::units::hours_ratio>;
/// @brief Alias option, specifying field value units are "days".
/// @headerfile nil/marshalling/options.hpp
using units_days
= units<nil::marshalling::traits::units::Time, nil::marshalling::traits::units::days_ratio>;
/// @brief Alias option, specifying field value units are "weeks".
/// @headerfile nil/marshalling/options.hpp
using units_weeks
= units<nil::marshalling::traits::units::Time, nil::marshalling::traits::units::weeks_ratio>;
/// @brief Alias option, specifying field value units are "nanometers".
/// @headerfile nil/marshalling/options.hpp
using units_nanometers
= units<nil::marshalling::traits::units::distance, nil::marshalling::traits::units::nanometers_ratio>;
/// @brief Alias option, specifying field value units are "micrometers".
/// @headerfile nil/marshalling/options.hpp
using units_micrometers
= units<nil::marshalling::traits::units::distance, nil::marshalling::traits::units::micrometers_ratio>;
/// @brief Alias option, specifying field value units are "millimeters".
/// @headerfile nil/marshalling/options.hpp
using units_millimeters
= units<nil::marshalling::traits::units::distance, nil::marshalling::traits::units::millimeters_ratio>;
/// @brief Alias option, specifying field value units are "centimeters".
/// @headerfile nil/marshalling/options.hpp
using units_centimeters
= units<nil::marshalling::traits::units::distance, nil::marshalling::traits::units::centimeters_ratio>;
/// @brief Alias option, specifying field value units are "meters".
/// @headerfile nil/marshalling/options.hpp
using units_meters
= units<nil::marshalling::traits::units::distance, nil::marshalling::traits::units::meters_ratio>;
/// @brief Alias option, specifying field value units are "kilometers".
/// @headerfile nil/marshalling/options.hpp
using units_kilometers
= units<nil::marshalling::traits::units::distance, nil::marshalling::traits::units::kilometers_ratio>;
/// @brief Alias option, specifying field value units are "nanometers per second".
/// @headerfile nil/marshalling/options.hpp
using units_nanometers_per_second = units<nil::marshalling::traits::units::speed,
nil::marshalling::traits::units::nanometers_per_second_ratio>;
/// @brief Alias option, specifying field value units are "micrometers per second".
/// @headerfile nil/marshalling/options.hpp
using units_micrometers_per_second = units<nil::marshalling::traits::units::speed,
nil::marshalling::traits::units::micrometers_per_second_ratio>;
/// @brief Alias option, specifying field value units are "millimeters per second".
/// @headerfile nil/marshalling/options.hpp
using units_millimeters_per_second = units<nil::marshalling::traits::units::speed,
nil::marshalling::traits::units::millimeters_per_second_ratio>;
/// @brief Alias option, specifying field value units are "centimeters per second".
/// @headerfile nil/marshalling/options.hpp
using units_centimeters_per_second = units<nil::marshalling::traits::units::speed,
nil::marshalling::traits::units::centimeters_per_second_ratio>;
/// @brief Alias option, specifying field value units are "meters per second".
/// @headerfile nil/marshalling/options.hpp
using units_meters_per_second = units<nil::marshalling::traits::units::speed,
nil::marshalling::traits::units::meters_per_second_ratio>;
/// @brief Alias option, specifying field value units are "kilometers per second".
/// @headerfile nil/marshalling/options.hpp
using units_kilometers_per_second = units<nil::marshalling::traits::units::speed,
nil::marshalling::traits::units::kilometers_per_second_ratio>;
/// @brief Alias option, specifying field value units are "kilometers per hour".
/// @headerfile nil/marshalling/options.hpp
using units_kilometers_per_hour = units<nil::marshalling::traits::units::speed,
nil::marshalling::traits::units::kilometers_per_hour_ratio>;
/// @brief Alias option, specifying field value units are "hertz".
/// @headerfile nil/marshalling/options.hpp
using units_hertz
= units<nil::marshalling::traits::units::frequency, nil::marshalling::traits::units::hz_ratio>;
/// @brief Alias option, specifying field value units are "kilohertz".
/// @headerfile nil/marshalling/options.hpp
using units_kilohertz
= units<nil::marshalling::traits::units::frequency, nil::marshalling::traits::units::kilo_hz_ratio>;
/// @brief Alias option, specifying field value units are "megahertz".
/// @headerfile nil/marshalling/options.hpp
using units_megahertz
= units<nil::marshalling::traits::units::frequency, nil::marshalling::traits::units::mega_hz_ratio>;
/// @brief Alias option, specifying field value units are "gigahertz".
/// @headerfile nil/marshalling/options.hpp
using units_gigahertz
= units<nil::marshalling::traits::units::frequency, nil::marshalling::traits::units::giga_hz_ratio>;
/// @brief Alias option, specifying field value units are "degrees".
/// @headerfile nil/marshalling/options.hpp
using units_degrees
= units<nil::marshalling::traits::units::angle, nil::marshalling::traits::units::degrees_ratio>;
/// @brief Alias option, specifying field value units are "radians".
/// @headerfile nil/marshalling/options.hpp
using units_radians
= units<nil::marshalling::traits::units::angle, nil::marshalling::traits::units::radians_ratio>;
/// @brief Alias option, specifying field value units are "nanoamps".
/// @headerfile nil/marshalling/options.hpp
using units_nanoamps
= units<nil::marshalling::traits::units::current, nil::marshalling::traits::units::nanoamps_ratio>;
/// @brief Alias option, specifying field value units are "microamps".
/// @headerfile nil/marshalling/options.hpp
using units_microamps
= units<nil::marshalling::traits::units::current, nil::marshalling::traits::units::microamps_ratio>;
/// @brief Alias option, specifying field value units are "milliamps".
/// @headerfile nil/marshalling/options.hpp
using units_milliamps
= units<nil::marshalling::traits::units::current, nil::marshalling::traits::units::milliamps_ratio>;
/// @brief Alias option, specifying field value units are "amps".
/// @headerfile nil/marshalling/options.hpp
using units_amps
= units<nil::marshalling::traits::units::current, nil::marshalling::traits::units::amps_ratio>;
/// @brief Alias option, specifying field value units are "kiloamps".
/// @headerfile nil/marshalling/options.hpp
using units_kiloamps
= units<nil::marshalling::traits::units::current, nil::marshalling::traits::units::kiloamps_ratio>;
/// @brief Alias option, specifying field value units are "nanovolts".
/// @headerfile nil/marshalling/options.hpp
using units_nanovolts
= units<nil::marshalling::traits::units::voltage, nil::marshalling::traits::units::nanovolts_ratio>;
/// @brief Alias option, specifying field value units are "microvolts".
/// @headerfile nil/marshalling/options.hpp
using units_microvolts
= units<nil::marshalling::traits::units::voltage, nil::marshalling::traits::units::microvolts_ratio>;
/// @brief Alias option, specifying field value units are "millivolts".
/// @headerfile nil/marshalling/options.hpp
using units_millivolts
= units<nil::marshalling::traits::units::voltage, nil::marshalling::traits::units::millivolts_ratio>;
/// @brief Alias option, specifying field value units are "volts".
/// @headerfile nil/marshalling/options.hpp
using units_volts
= units<nil::marshalling::traits::units::voltage, nil::marshalling::traits::units::volts_ratio>;
/// @brief Alias option, specifying field value units are "kilovolts".
/// @headerfile nil/marshalling/options.hpp
using units_kilovolts
= units<nil::marshalling::traits::units::voltage, nil::marshalling::traits::units::kilovolts_ratio>;
namespace detail {
template<typename T, T TVal>
struct default_num_value_initialiser {
template<typename TField>
void operator()(TField &&field) {
using field_type = typename std::decay<TField>::type;
using value_type = typename field_type::value_type;
field.value() = static_cast<value_type>(TVal);
}
};
template<std::intmax_t TMinValue, std::intmax_t TMaxValue>
struct num_value_range_validator {
static_assert(TMinValue <= TMaxValue, "Min value must be not greater than Max value");
template<typename TField>
constexpr bool operator()(const TField &field) const {
using MinTag =
typename std::conditional<(std::numeric_limits<decltype(MinValue)>::min() < MinValue),
compare_tag, return_true_tag>::type;
using MaxTag =
typename std::conditional<(MaxValue < std::numeric_limits<decltype(MaxValue)>::max()),
compare_tag, return_true_tag>::type;
return above_min(field.value(), MinTag()) && below_max(field.value(), MaxTag());
}
private:
struct return_true_tag { };
struct compare_tag { };
template<typename TValue>
static constexpr bool above_min(const TValue &value, compare_tag) {
using value_type = typename std::decay<decltype(value)>::type;
return (static_cast<value_type>(MinValue) <= static_cast<value_type>(value));
}
template<typename TValue>
static constexpr bool above_min(const TValue &, return_true_tag) {
return true;
}
template<typename TValue>
static constexpr bool below_max(const TValue &value, compare_tag) {
using value_type = typename std::decay<decltype(value)>::type;
return (value <= static_cast<value_type>(MaxValue));
}
template<typename TValue>
static constexpr bool below_max(const TValue &, return_true_tag) {
return true;
}
static const auto MinValue = TMinValue;
static const auto MaxValue = TMaxValue;
};
template<std::uintmax_t TMask, std::uintmax_t TValue>
struct bitmask_reserved_bits_validator {
template<typename TField>
constexpr bool operator()(TField &&field) const {
using field_type = typename std::decay<TField>::type;
using value_type = typename field_type::value_type;
return (field.value() & static_cast<value_type>(TMask)) == static_cast<value_type>(TValue);
}
};
template<nil::marshalling::types::optional_mode TVal>
struct default_opt_mode_initialiser {
template<typename TField>
void operator()(TField &field) const {
field.set_mode(TVal);
}
};
template<std::size_t TIdx>
struct default_variant_index_initialiser {
template<typename TField>
void operator()(TField &field) {
field.template init_field<TIdx>();
}
};
} // namespace detail
/// @brief Alias to default_value_initializer, it defines initialiser class that
/// assigns numeric value provided as the template argument to this option.
/// @details If the required numeric value is too big (doesn't fit into @b
/// std::intmax_t type), please use @ref DefaultBigUnsignedNumValue option
/// class instead.
/// @tparam TVal Numeric value is to be assigned to the field in default constructor.
/// @see @ref DefaultBigUnsignedNumValue
/// @headerfile nil/marshalling/options.hpp
template<std::intmax_t TVal>
using default_num_value
= default_value_initialiser<detail::default_num_value_initialiser<std::intmax_t, TVal>>;
/// @brief Alias to default_value_initializer, it defines initialiser class that
/// assigns big unsigned numeric value provided as the template argument to this option.
/// @details If the required numeric value is small enough to fit into @b
/// std::intmax_t type, it is recommended to use @ref default_num_value option
/// class instead.
/// @tparam TVal Numeric value is to be assigned to the field in default constructor.
/// @see @ref DefaultBigUnsignedNumValue
/// @headerfile nil/marshalling/options.hpp
template<std::uintmax_t TVal>
using default_big_unsigned_num_value
= default_value_initialiser<detail::default_num_value_initialiser<std::uintmax_t, TVal>>;
/// @brief Provide range of valid numeric values.
/// @details Quite often numeric fields such as nil::marshalling::types::integral or
/// nil::marshalling::types::enumeration have limited number of valid values ranges.
/// This option can be used multiple times to provide several valid ranges.@n
/// If values are too big to fit into @b std::intmax_t type, please use
/// @ref ValidBigUnsignedNumValueRange option instead.
/// @tparam TMinValue Minimal valid numeric value
/// @tparam TMaxValue Maximal valid numeric value
/// @note The intersection of the provided multiple ranges is @b NOT checked.
/// @warning Some older compilers (@b gcc-4.7) fail to compile valid C++11 code
/// that allows usage of multiple @ref valid_num_value_range options. If this is
/// the case, please don't pass more than one @ref valid_num_value_range option.
/// @see @ref ValidNumValue
/// @see @ref ValidBigUnsignedNumValueRange
/// @headerfile nil/marshalling/options.hpp
template<std::intmax_t TMinValue, std::intmax_t TMaxValue>
struct valid_num_value_range {
static_assert(TMinValue <= TMaxValue, "Invalid range");
};
/// @brief Clear accumulated ranges of valid values.
struct valid_ranges_clear { };
/// @brief Similar to @ref valid_num_value_range, but overrides (nullifies)
/// all previously set valid values ranges.
/// @see @ref ValidNumValueOverride
/// @see @ref ValidBigUnsignedNumValueRangeOverride
/// @deprecated Use @ref valid_ranges_clear instead.
template<std::intmax_t TMinValue, std::intmax_t TMaxValue>
using valid_num_value_range_override
= std::tuple<valid_num_value_range<TMinValue, TMaxValue>, valid_ranges_clear>;
/// @brief Alias to @ref valid_num_value_range.
/// @details Equivalent to @b valid_num_value_range<TValue, TValue>
template<std::intmax_t TValue>
using valid_num_value = valid_num_value_range<TValue, TValue>;
/// @brief Alias to @ref valid_num_value_rangeOverride.
/// @details Equivalent to @b valid_num_value_rangeOverride<TValue, TValue>
/// @deprecated Use @ref valid_ranges_clear instead.
template<std::intmax_t TValue>
using valid_num_value_override = valid_num_value_range_override<TValue, TValue>;
/// @brief Provide range of valid unsigned numeric values.
/// @details Similar to @ref valid_num_value_range, but dedicated to
/// big unsigned numbers, which don't fit into @b std::intmax_t type.
/// @tparam TMinValue Minimal valid numeric value
/// @tparam TMaxValue Maximal valid numeric value
/// @note The intersection of the provided multiple ranges is @b NOT checked.
/// @warning Some older compilers (@b gcc-4.7) fail to compile valid C++11 code
/// that allows usage of multiple @ref valid_num_value_range options. If this is
/// the case, please don't pass more than one
/// @ref valid_num_value_range or @ref ValidBigUnsignedNumValueRange option.
/// @see @ref valid_num_value_range
/// @see @ref ValidBigUnsignedNumValue
/// @headerfile nil/marshalling/options.hpp
template<std::uintmax_t TMinValue, std::uintmax_t TMaxValue>
struct valid_big_unsigned_num_value_range {
static_assert(TMinValue <= TMaxValue, "Invalid range");
};
/// @brief Similar to @ref ValidBigUnsignedNumValueRange, but overrides (nullifies)
/// all previously set valid values ranges.
/// @see @ref ValidNumValueOverride
/// @see @ref ValidBigUnsignedNumValueOverride
/// @deprecated Use @ref valid_ranges_clear instead.
template<std::uintmax_t TMinValue, std::uintmax_t TMaxValue>
using valid_big_unsigned_num_value_range_override
= std::tuple<valid_big_unsigned_num_value_range<TMinValue, TMaxValue>, valid_ranges_clear>;
/// @brief Alias to @ref ValidBigUnsignedNumValueRange.
/// @details Equivalent to @b ValidBigUnsignedNumValueRange<TValue, TValue>
template<std::uintmax_t TValue>
using valid_big_unsigned_num_value = valid_big_unsigned_num_value_range<TValue, TValue>;
/// @brief Alias to @ref ValidBigUnsignedNumValueRangeOverride.
/// @details Equivalent to @b ValidBigUnsignedNumValueRangeOverride<TValue, TValue>
/// @deprecated Use @ref valid_ranges_clear instead.
template<std::uintmax_t TValue>
using valid_big_unsigned_num_value_override = valid_big_unsigned_num_value_range_override<TValue, TValue>;
/// @brief Alias to contents_validator, it defines validator class that checks
/// that reserved bits of the field have expected values.
/// @details It is usually used with nil::marshalling::types::BitmaskValue field to
/// specify values of the unused/reserved bits.
/// The custom validator will return true if
/// @code
/// (field.value() & TMask) == TValue
/// @endcode
/// @tparam TMask Mask that specifies reserved bits.
/// @tparam TValue Expected value of the reserved bits. Defaults to 0.
/// @headerfile nil/marshalling/options.hpp
template<std::uintmax_t TMask, std::uintmax_t TValue = 0U>
using bitmask_reserved_bits = contents_validator<detail::bitmask_reserved_bits_validator<TMask, TValue>>;
/// @brief Alias to default_value_initializer, it sets default mode
/// to types::optional field.
/// @tparam TVal optional mode value is to be assigned to the field in default constructor.
/// @see @ref MissingByDefault
/// @see @ref ExistsByDefault
/// @headerfile nil/marshalling/options.hpp
template<nil::marshalling::types::optional_mode TVal>
using default_optional_mode = default_value_initialiser<detail::default_opt_mode_initialiser<TVal>>;
/// @brief Alias to @ref DefaultOptionalMode.
/// @details Equivalent to
/// @code
/// DefaultOptionalMode<nil::marshalling::types::optional_mode::missing>
/// @endcode
using missing_by_default = default_optional_mode<nil::marshalling::types::optional_mode::missing>;
/// @brief Alias to @ref DefaultOptionalMode.
/// @details Equivalent to
/// @code
/// DefaultOptionalMode<nil::marshalling::types::optional_mode::exists>
/// @endcode
using exists_by_default = default_optional_mode<nil::marshalling::types::optional_mode::exists>;
/// @brief Alias to DefaultOptionalMode<nil::marshalling::types::OptinalMode::missing>
using optional_missing_by_default = missing_by_default;
/// @brief Alias to DefaultOptionalMode<nil::marshalling::types::OptinalMode::exists>
using optional_exists_by_default = exists_by_default;
/// @brief Alias to default_value_initializer, it initalises nil::marshalling::types::variant field
/// to contain valid default value of the specified member.
/// @tparam TIdx Index of the default member.
/// @headerfile nil/marshalling/options.hpp
template<std::size_t TIdx>
using default_variant_index = default_value_initialiser<detail::default_variant_index_initialiser<TIdx>>;
/// @brief Force nil::marshalling::protocol::ChecksumLayer and
/// nil::marshalling::protocol::ChecksumPrefixLayer, to verify checksum prior to
/// forwarding read to the wrapped layer(s).
/// @headerfile nil/marshalling/options.hpp
struct checksum_layer_verify_before_read { };
/// @brief Use "view" on original raw data instead of copying it.
/// @details Can be used with @ref nil::marshalling::types::string and raw data @ref
/// nil::marshalling::types::array_list,
/// will force usage of @ref nil::marshalling::container::string_view and
/// nil::marshalling::container::array_view respectively as data storage type.
/// @note The original data must be preserved until destruction of the field
/// that uses the "view".
/// @note Incompatible with other options that contol data storage type,
/// such as @ref nil::marshalling::option::custom_storage_type or @ref
/// nil::marshalling::option::fixed_size_storage
/// @headerfile nil/marshalling/options.hpp
struct orig_data_view { };
/// @brief Force field not to be serialized during read/write operations
/// @details Some protocols may define some constant values that are predefined
/// and are not present on I/O link when serialized. Sometimes it is convenient
/// to have such values abstracted away as fields, which are not actually
/// serialized. Using this option will have such effect: read/write operaitons
/// will not change the value of iterators and will report immediate success.
/// The serialization length is always reported as 0.
/// @headerfile nil/marshalling/options.hpp
struct empty_serialization { };
/// @brief Option to force @ref nil::marshalling::protocol::ProtocolLayerBase class to
/// split read operation "until" and "from" data (payload) layer.
/// @details Can be used by some layers which require its read operation to be
/// fully complete before read is forwared to data layer, i.e. until message
/// contents being read.
/// @headerfile nil/marshalling/options.hpp
struct protocol_layer_force_read_until_data_split { };
/// @brief Disallow usage of @ref ProtocolLayerForceReadUntilDataSplit option in
/// earlier (outer wrapping) layers.
/// @details Some layers, such as @ref nil::marshalling::protocol::ChecksumLayer cannot
/// split their "read" operation to "until" and "from" data layer. They can
/// use this option to prevent outer layers from using
/// @ref ProtocolLayerForceReadUntilDataSplit one.
/// @headerfile nil/marshalling/options.hpp
struct protocol_layer_disallow_read_until_data_split { };
/// @brief Mark this class to have custom
/// implementation of @b read functionality.
/// @headerfile nil/marshalling/options.hpp
struct has_custom_read { };
/// @brief Mark this class to have custom
/// implementation of @b refresh functionality.
/// @headerfile nil/marshalling/options.hpp
struct has_custom_refresh { };
/// @brief Mark this class as providing its name information
/// @headerfile nil/marshalling/options.hpp
struct has_name { };
/// @brief Option that notifies nil::marshalling::message_base about existence of
/// custom refresh functionality in derived class.
/// @details Alias to @ref has_custom_refresh for backward compatibility.
/// @deprecated Use @ref has_custom_refresh instead.
/// @headerfile nil/marshalling/options.hpp
using has_do_refresh = has_custom_refresh;
/// @brief Option for @ref nil::marshalling::protocol::TransportValueLayer to
/// mark that the handled field is a "pseudo" one, i.e. is not serialized.
struct pseudo_value { };
/// @brief Provide type to be used for versioning
/// @tparam T Type of the version value. Expected to be unsigned integral one.
template<typename T>
struct version_type {
static_assert(std::is_integral<T>::value, "Only unsigned integral types are supported for versions");
static_assert(std::is_unsigned<T>::value, "Only unsigned integral types are supported for versions");
};
/// @brief Mark this class to have custom
/// implementation of version update functionality.
/// @headerfile nil/marshalling/options.hpp
struct has_custom_version_update { };
/// @brief Mark an @ref nil::marshalling::types::optional field as existing
/// between specified versions.
/// @tparam TFrom First version when field has been added
/// @tparam TUntil Last version when field still hasn't been removed.
/// @pre @b TFrom <= @b TUntil
template<std::uintmax_t TFrom, std::uintmax_t TUntil>
struct exists_between_versions {
static_assert(TFrom <= TUntil, "Invalid version parameters");
};
/// @brief Mark an @ref nil::marshalling::types::optional field as existing
/// starting from specified version.
/// @details Alias to @ref ExistsBetweenVersions
/// @tparam TVer First version when field has been added
template<std::uintmax_t TVer>
using exists_since_version = exists_between_versions<TVer, std::numeric_limits<std::uintmax_t>::max()>;
/// @brief Mark an @ref nil::marshalling::types::optional field as existing
/// only until specified version.
/// @details Alias to @ref ExistsBetweenVersions
/// @tparam TVer Last version when field still hasn't been removed.
template<std::uintmax_t TVer>
using exists_until_version = exists_between_versions<0, TVer>;
/// @brief Make the field's contents to be invalid by default.
struct invalid_by_default { };
/// @brief Add storage of version information inside private data members.
/// @details The version information can be accessed using @b get_version() member function.
struct version_storage { };
} // namespace option
} // namespace marshalling
} // namespace nil
#endif // MARSHALLING_OPTIONS_HPP
| 56.82127 | 119 | 0.578312 | idealatom |
fa38ac46bc11e9f2e41a8b0f9614b0efcfe90edf | 7,074 | cpp | C++ | src/solvers/refinement/string_constraint_generator_concat.cpp | chrisr-diffblue/cbmc | 854b26fec145ebb345cf45c9512201143c823cd1 | [
"BSD-4-Clause"
] | null | null | null | src/solvers/refinement/string_constraint_generator_concat.cpp | chrisr-diffblue/cbmc | 854b26fec145ebb345cf45c9512201143c823cd1 | [
"BSD-4-Clause"
] | 2 | 2018-06-18T10:34:36.000Z | 2018-07-03T15:43:57.000Z | src/solvers/refinement/string_constraint_generator_concat.cpp | chrisr-diffblue/cbmc | 854b26fec145ebb345cf45c9512201143c823cd1 | [
"BSD-4-Clause"
] | null | null | null | /*******************************************************************\
Module: Generates string constraints for functions adding content
add the end of strings
Author: Romain Brenguier, romain.brenguier@diffblue.com
\*******************************************************************/
/// \file
/// Generates string constraints for functions adding content add the end of
/// strings
#include <solvers/refinement/string_constraint_generator.h>
/// Add axioms enforcing that `res` is the concatenation of `s1` with
/// the substring of `s2` starting at index `start_index` and ending
/// at index `end_index`.
///
/// If `start_index >= end_index`, the value returned is `s1`.
/// If `end_index > |s2|` and/or `start_index < 0`, the appended string will
/// be of length `end_index - start_index` and padded with non-deterministic
/// values.
///
/// These axioms are:
/// 1. \f$end\_index > start\_index \Rightarrow |res| = |s_1| + end\_index -
/// start\_index
/// \f$
/// 2. \f$end\_index \le start\_index \Rightarrow res = s_1 \f$
/// 3. \f$\forall i<|s_1|. res[i]=s_1[i] \f$
/// 4. \f$\forall i< end\_index - start\_index.\ res[i+|s_1|]
/// = s_2[start\_index+i]\f$
///
/// \param res: an array of characters expression
/// \param s1: an array of characters expression
/// \param s2: an array of characters expression
/// \param start_index: integer expression
/// \param end_index: integer expression
/// \return integer expression `0`
exprt string_constraint_generatort::add_axioms_for_concat_substr(
const array_string_exprt &res,
const array_string_exprt &s1,
const array_string_exprt &s2,
const exprt &start_index,
const exprt &end_index)
{
binary_relation_exprt prem(end_index, ID_gt, start_index);
exprt res_length=plus_exprt_with_overflow_check(
s1.length(), minus_exprt(end_index, start_index));
implies_exprt a1(prem, equal_exprt(res.length(), res_length));
lemmas.push_back(a1);
implies_exprt a2(not_exprt(prem), equal_exprt(res.length(), s1.length()));
lemmas.push_back(a2);
symbol_exprt idx=fresh_univ_index("QA_index_concat", res.length().type());
string_constraintt a3(idx, s1.length(), equal_exprt(s1[idx], res[idx]));
constraints.push_back(a3);
symbol_exprt idx2=fresh_univ_index("QA_index_concat2", res.length().type());
equal_exprt res_eq(
res[plus_exprt(idx2, s1.length())], s2[plus_exprt(start_index, idx2)]);
string_constraintt a4(idx2, minus_exprt(end_index, start_index), res_eq);
constraints.push_back(a4);
// We should have a enum type for the possible error codes
return from_integer(0, res.length().type());
}
/// Add axioms enforcing that `res` is the concatenation of `s1` with
/// character `c`.
/// These axioms are :
/// * \f$ |res|=|s1|+1 \f$
/// * \f$ \forall i<|s1|. res[i]=s1[i] \f$
/// * \f$ res[|s1|]=c \f$
///
/// \param res: string expression
/// \param s1: string expression
/// \param c: character expression
/// \return code 0 on success
exprt string_constraint_generatort::add_axioms_for_concat_char(
const array_string_exprt &res,
const array_string_exprt &s1,
const exprt &c)
{
const typet &index_type = res.length().type();
const equal_exprt a1(
res.length(), plus_exprt(s1.length(), from_integer(1, index_type)));
lemmas.push_back(a1);
symbol_exprt idx = fresh_univ_index("QA_index_concat_char", index_type);
string_constraintt a2(idx, s1.length(), equal_exprt(s1[idx], res[idx]));
constraints.push_back(a2);
equal_exprt a3(res[s1.length()], c);
lemmas.push_back(a3);
// We should have a enum type for the possible error codes
return from_integer(0, get_return_code_type());
}
/// Add axioms enforcing that `res` is equal to the concatenation of `s1` and
/// `s2`.
///
/// \deprecated should use concat_substr instead
/// \param res: string_expression corresponding to the result
/// \param s1: the string expression to append to
/// \param s2: the string expression to append to the first one
/// \return an integer expression
exprt string_constraint_generatort::add_axioms_for_concat(
const array_string_exprt &res,
const array_string_exprt &s1,
const array_string_exprt &s2)
{
exprt index_zero=from_integer(0, s2.length().type());
return add_axioms_for_concat_substr(res, s1, s2, index_zero, s2.length());
}
/// String concatenation
///
/// This primitive accepts 4 or 6 arguments.
/// \copybrief string_constraint_generatort::add_axioms_for_concat_substr
/// \link string_constraint_generatort::add_axioms_for_concat_substr
/// (More...) \endlink
///
/// \param f: function application with arguments integer `|res|`, character
/// pointer `&res[0]`, refined_string `s1`, refined_string `s2`,
/// optional integer `start_index`, optional integer `end_index`
/// \return an integer expression
exprt string_constraint_generatort::add_axioms_for_concat(
const function_application_exprt &f)
{
const function_application_exprt::argumentst &args=f.arguments();
PRECONDITION(args.size() == 4 || args.size() == 6);
const array_string_exprt s1 = get_string_expr(args[2]);
const array_string_exprt s2 = get_string_expr(args[3]);
const array_string_exprt res = char_array_of_pointer(args[1], args[0]);
if(args.size() == 6)
return add_axioms_for_concat_substr(res, s1, s2, args[4], args[5]);
else // args.size()==4
return add_axioms_for_concat(res, s1, s2);
}
/// Add axioms enforcing that the string represented by the two first
/// expressions is equal to the concatenation of the string argument and
/// the character argument of the function application.
/// \todo This should be merged with add_axioms_for_concat.
/// \param f: function application with a length, pointer, string and character
/// argument.
/// \return code 0 on success
exprt string_constraint_generatort::add_axioms_for_concat_char(
const function_application_exprt &f)
{
const function_application_exprt::argumentst &args = f.arguments();
PRECONDITION(args.size() == 4);
const array_string_exprt s1 = get_string_expr(args[2]);
const exprt &c = args[3];
const array_string_exprt res = char_array_of_pointer(args[1], args[0]);
return add_axioms_for_concat_char(res, s1, c);
}
/// Add axioms corresponding to the StringBuilder.appendCodePoint(I) function
/// \deprecated java specific
/// \param f: function application with two arguments: a string and a code point
/// \return an expression
exprt string_constraint_generatort::add_axioms_for_concat_code_point(
const function_application_exprt &f)
{
PRECONDITION(f.arguments().size() == 4);
const array_string_exprt res =
char_array_of_pointer(f.arguments()[1], f.arguments()[0]);
const array_string_exprt s1 = get_string_expr(f.arguments()[2]);
const typet &char_type = s1.content().type().subtype();
const typet &index_type = s1.length().type();
const array_string_exprt code_point = fresh_string(index_type, char_type);
const exprt return_code1 =
add_axioms_for_code_point(code_point, f.arguments()[3]);
return add_axioms_for_concat(res, s1, code_point);
}
| 39.082873 | 80 | 0.71063 | chrisr-diffblue |
fa3b963e8bff7662eee819b9d93b379986e5926b | 3,241 | cpp | C++ | tests/utils_test.cpp | louiz/batajelo | 4d8edce8da9d3b17dbad68eb4881d7f6fee2f76e | [
"BSL-1.0",
"BSD-2-Clause",
"Zlib",
"MIT"
] | 7 | 2015-01-28T09:17:08.000Z | 2020-04-21T13:51:16.000Z | tests/utils_test.cpp | louiz/batajelo | 4d8edce8da9d3b17dbad68eb4881d7f6fee2f76e | [
"BSL-1.0",
"BSD-2-Clause",
"Zlib",
"MIT"
] | null | null | null | tests/utils_test.cpp | louiz/batajelo | 4d8edce8da9d3b17dbad68eb4881d7f6fee2f76e | [
"BSL-1.0",
"BSD-2-Clause",
"Zlib",
"MIT"
] | 1 | 2020-07-11T09:20:25.000Z | 2020-07-11T09:20:25.000Z | #include <utils/base64.hpp>
#include <utils/string.hpp>
#include <utils/scopeguard.hpp>
#include <utils/zlib.hpp>
#include <utils/time.hpp>
#include "catch.hpp"
TEST_CASE("Both", "[base64]")
{
std::string hello = "Coucou ici";
CHECK(base64_decode(base64_encode(reinterpret_cast<const unsigned char*>(hello.c_str()), hello.size())) ==
"Coucou ici");
}
TEST_CASE("encode", "[base64]")
{
std::string encoded("TWFuIGlzIGRpc3Rpbmd1aXNoZWQsIG5vdCBvbmx5IGJ5IGhpcyByZWFzb24sIGJ1dCBieSB0aGlzIHNpbmd1bGFyIHBhc3Npb24gZnJvbSBvdGhlciBhbmltYWxzLCB3aGljaCBpcyBhIGx1c3Qgb2YgdGhlIG1pbmQsIHRoYXQgYnkgYSBwZXJzZXZlcmFuY2Ugb2YgZGVsaWdodCBpbiB0aGUgY29udGludWVkIGFuZCBpbmRlZmF0aWdhYmxlIGdlbmVyYXRpb24gb2Yga25vd2xlZGdlLCBleGNlZWRzIHRoZSBzaG9ydCB2ZWhlbWVuY2Ugb2YgYW55IGNhcm5hbCBwbGVhc3VyZS4=");
CHECK(base64_decode(encoded) == "Man is distinguished, not only by his reason, but by this singular passion from other animals, which is a lust of the mind, that by a perseverance of delight in the continued and indefatigable generation of knowledge, exceeds the short vehemence of any carnal pleasure.");
}
TEST_CASE("decompressAndCompress", "[zlib]")
{
std::string original("coucou coucou");
CHECK(zlib_decompress(zlib_compress(original)) == "coucou coucou");
}
TEST_CASE("trim", "[strings]")
{
std::string original(" coucou\n");
utils::trim(original);
CHECK(original == "coucou");
original = " coucou";
utils::trim(original);
CHECK(original == "coucou");
original = "coucou ";
utils::trim(original);
CHECK(original == "coucou");
original = "coucou";
utils::trim(original);
CHECK(original == "coucou");
original = "\n\ncoucou \r\n ";
utils::trim(original);
CHECK(original == "coucou");
}
TEST_CASE("Scopeguard")
{
int i = 5;
{
CHECK(i == 5);
utils::ScopeGuard guard([&i]() {--i;});
CHECK(i == 5);
}
CHECK(i == 4);
{
CHECK(i == 4);
utils::ScopeGuard guard;
guard.add_callback([&i]() {--i;});
guard.add_callback([&i]() {--i;});
CHECK(i == 4);
}
CHECK(i == 2);
{
CHECK(i == 2);
utils::ScopeGuard guard;
guard.add_callback([&i]() {--i;});
CHECK(i == 2);
guard.disable();
}
CHECK(i == 2);
}
TEST_CASE("BasicTick", "[time]")
{
using namespace std::chrono_literals;
utils::Duration dt = 1s;
auto ticks = utils::get_number_of_ticks(dt);
CHECK(ticks == 50);
CHECK(dt == 0s);
}
TEST_CASE("BasicTick2", "[time]")
{
using namespace std::chrono_literals;
utils::Duration dt = 500000us;
auto ticks = utils::get_number_of_ticks(dt);
CHECK(ticks == 25);
CHECK(dt == 0s);
}
TEST_CASE("Ticks", "[time]")
{
using namespace std::chrono_literals;
utils::Duration dt = 420000us;
auto ticks = utils::get_number_of_ticks(dt);
CHECK(ticks == 21);
CHECK(dt == 0us);
}
TEST_CASE("ConvertToFloatingSeconds", "[time]")
{
using namespace std::chrono_literals;
utils::Duration dt = 8420000us;
auto secs = utils::sec(dt);
CHECK(secs == 8.42s);
dt = -8420000us;
secs = utils::sec(dt);
CHECK(secs == -8.42s);
}
TEST_CASE("NullTime", "[time]")
{
using namespace std::chrono_literals;
utils::Duration dt = 0h;
auto ticks = utils::get_number_of_ticks(dt);
CHECK(ticks == 0);
CHECK(dt == 0us);
}
| 24.930769 | 386 | 0.676026 | louiz |
fa3dc8242a4300646a6928fc98e0f9577e9c4499 | 17,909 | cc | C++ | mindspore/lite/src/runtime/kernel/arm/fp32/convolution_fp32.cc | taroxd/mindspore | 9bb620ff2caaac7f1c53c4b104935f22352cb88f | [
"Apache-2.0"
] | 55 | 2020-12-17T10:26:06.000Z | 2022-03-28T07:18:26.000Z | mindspore/lite/src/runtime/kernel/arm/fp32/convolution_fp32.cc | taroxd/mindspore | 9bb620ff2caaac7f1c53c4b104935f22352cb88f | [
"Apache-2.0"
] | null | null | null | mindspore/lite/src/runtime/kernel/arm/fp32/convolution_fp32.cc | taroxd/mindspore | 9bb620ff2caaac7f1c53c4b104935f22352cb88f | [
"Apache-2.0"
] | 14 | 2021-01-29T02:39:47.000Z | 2022-03-23T05:00:26.000Z | /**
* Copyright 2020 Huawei Technologies Co., Ltd
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
#include "src/runtime/kernel/arm/fp32/convolution_fp32.h"
#include "src/runtime/kernel/arm/fp32/convolution_1x1_fp32.h"
#include "src/runtime/kernel/arm/fp32/convolution_winograd_fp32.h"
#include "src/runtime/kernel/arm/fp32/group_convolution_fp32.h"
#include "nnacl/fp32/conv_fp32.h"
#include "nnacl/common_func.h"
#include "schema/model_generated.h"
#include "src/kernel_registry.h"
#include "include/errorcode.h"
#include "src/runtime/runtime_api.h"
#include "src/runtime/kernel/arm/base/dequant.h"
using mindspore::kernel::KERNEL_ARCH::kCPU;
using mindspore::lite::KernelRegistrar;
using mindspore::lite::RET_ERROR;
using mindspore::lite::RET_INFER_INVALID;
using mindspore::lite::RET_OK;
using mindspore::schema::PrimitiveType_Conv2D;
using mindspore::schema::Format::Format_NHWC;
namespace mindspore::kernel {
int ConvolutionCPUKernel::InitWeightBias() {
auto filter_tensor = in_tensors_.at(kWeightIndex);
int in_channel = filter_tensor->Channel();
int out_channel = filter_tensor->Batch();
conv_param_->input_channel_ = in_channel;
conv_param_->output_channel_ = out_channel;
int kernel_plane = filter_tensor->Height() * filter_tensor->Width();
#ifdef ENABLE_AVX
const int oc_block = C16NUM;
#elif ENABLE_ARM32
const int oc_block = C4NUM;
#else
const int oc_block = C8NUM;
#endif
int oc_block_num = UP_ROUND(out_channel, oc_block);
int pack_weight_size = oc_block_num * in_channel * kernel_plane;
auto origin_weight = reinterpret_cast<float *>(filter_tensor->data_c());
packed_weight_ = reinterpret_cast<float *>(malloc(pack_weight_size * sizeof(float)));
if (packed_weight_ == nullptr) {
MS_LOG(ERROR) << "malloc packed weight failed.";
return RET_ERROR;
}
memset(packed_weight_, 0, pack_weight_size * sizeof(float));
#ifdef ENABLE_AVX
RowMajor2Col16Major(origin_weight, packed_weight_, out_channel, in_channel * kernel_plane);
#elif ENABLE_ARM32
RowMajor2Col4Major(origin_weight, packed_weight_, out_channel, in_channel * kernel_plane);
#else
RowMajor2Col8Major(origin_weight, packed_weight_, out_channel, in_channel * kernel_plane);
#endif
bias_data_ = reinterpret_cast<float *>(malloc(oc_block_num * sizeof(float)));
if (bias_data_ == nullptr) {
MS_LOG(ERROR) << "malloc bias failed.";
return RET_ERROR;
}
memset(bias_data_, 0, oc_block_num * sizeof(float));
if (in_tensors_.size() == kInputSize2) {
auto ori_bias = reinterpret_cast<float *>(in_tensors_.at(kBiasIndex)->data_c());
memcpy(bias_data_, ori_bias, out_channel * sizeof(float));
} else {
MS_ASSERT(in_tensors_.size() == kInputSize1);
}
return RET_OK;
}
int ConvolutionCPUKernel::InitTmpBuffer() {
MS_ASSERT(ctx_->allocator != nullptr);
#ifdef ENABLE_AVX
int unit_size = conv_param_->kernel_h_ * conv_param_->kernel_w_ * conv_param_->input_channel_ * C6NUM * thread_count_;
#elif ENABLE_SSE
int unit_size = conv_param_->kernel_h_ * conv_param_->kernel_w_ * conv_param_->input_channel_ * C4NUM * thread_count_;
#else
int unit_size =
conv_param_->kernel_h_ * conv_param_->kernel_w_ * conv_param_->input_channel_ * C12NUM * thread_count_;
#endif
packed_input_ = reinterpret_cast<float *>(ctx_->allocator->Malloc(unit_size * sizeof(float)));
if (packed_input_ == nullptr) {
MS_LOG(ERROR) << "malloc packed input failed.";
return RET_ERROR;
}
col_major_input_ = reinterpret_cast<float *>(ctx_->allocator->Malloc(unit_size * sizeof(float)));
if (col_major_input_ == nullptr) {
MS_LOG(ERROR) << "malloc col_major_input_ failed.";
return RET_ERROR;
}
return RET_OK;
}
int ConvolutionCPUKernel::Init() {
auto ret = InitWeightBias();
if (ret != RET_OK) {
MS_LOG(ERROR) << "Init weight bias failed.";
return RET_ERROR;
}
if (!InferShapeDone()) {
return RET_OK;
}
return ReSize();
}
int ConvolutionCPUKernel::ReSize() {
auto ret = ConvolutionBaseCPUKernel::CheckResizeValid();
if (ret != RET_OK) {
MS_LOG(ERROR) << "Resize is invalid.";
return ret;
}
ret = ConvolutionBaseCPUKernel::Init();
if (ret != RET_OK) {
MS_LOG(ERROR) << "ConvolutionBase init failed.";
return RET_ERROR;
}
return RET_OK;
}
int ConvolutionCPUKernel::RunImpl(int task_id) {
auto ori_input_data = reinterpret_cast<float *>(in_tensors_.at(kInputIndex)->data_c());
auto output_addr = reinterpret_cast<float *>(out_tensors_.at(kOutputIndex)->data_c());
ConvFp32(ori_input_data, packed_input_, packed_weight_, reinterpret_cast<float *>(bias_data_), col_major_input_,
output_addr, task_id, conv_param_);
return RET_OK;
}
int ConvolutionImpl(void *cdata, int task_id) {
auto conv = reinterpret_cast<ConvolutionCPUKernel *>(cdata);
auto error_code = conv->RunImpl(task_id);
if (error_code != RET_OK) {
MS_LOG(ERROR) << "Convolution Run error task_id[" << task_id << "] error_code[" << error_code << "]";
return RET_ERROR;
}
return RET_OK;
}
int ConvolutionCPUKernel::Run() {
auto ret = InitTmpBuffer();
if (ret != RET_OK) {
MS_LOG(ERROR) << "Init tmp buffer failed.";
FreeTmpBuffer();
return RET_ERROR;
}
ret = ParallelLaunch(this->context_->thread_pool_, ConvolutionImpl, this, thread_count_);
if (ret != RET_OK) {
MS_LOG(ERROR) << "conv error error_code[" << ret << "]";
}
FreeTmpBuffer();
return ret;
}
ConvParameter *CreateNewConvParameter(ConvParameter *parameter) {
auto conv_parameter = new (std::nothrow) ConvParameter;
if (conv_parameter == nullptr) {
MS_LOG(ERROR) << "Malloc new conv parameter failed.";
return nullptr;
}
memcpy(conv_parameter, parameter, sizeof(ConvParameter));
return conv_parameter;
}
void FreeMemory(const std::vector<kernel::LiteKernel *> &group_convs, const std::vector<lite::Tensor *> &new_inputs,
const std::vector<lite::Tensor *> &new_outputs) {
for (auto sub_conv : group_convs) {
delete sub_conv;
}
for (auto in_tensor : new_inputs) {
delete in_tensor;
}
for (auto out_tensor : new_outputs) {
delete out_tensor;
}
}
lite::Tensor *CreateInputTensor(TypeId data_type, std::vector<int> in_shape, bool infered_flag) {
auto in_tensor = new (std::nothrow) lite::Tensor(data_type, in_shape, Format_NHWC, lite::Tensor::Category::VAR);
if (in_tensor == nullptr) {
MS_LOG(ERROR) << "new in_tensor failed.";
return nullptr;
}
if (infered_flag) {
auto ret = in_tensor->MallocData();
if (ret != RET_OK) {
delete in_tensor;
MS_LOG(ERROR) << "in tensor malloc failed.";
return nullptr;
}
}
return in_tensor;
}
lite::Tensor *CreateFilterTensorFp32(TypeId data_type, std::vector<int> filter_shape,
const std::vector<lite::Tensor *> &inputs, int copy_length, int index) {
auto filter_tensor =
new (std::nothrow) lite::Tensor(data_type, filter_shape, Format_NHWC, lite::Tensor::Category::CONST_TENSOR);
if (filter_tensor == nullptr) {
MS_LOG(ERROR) << "new filter_tensor failed.";
return nullptr;
}
auto ret = filter_tensor->MallocData();
if (ret != RET_OK) {
delete filter_tensor;
MS_LOG(ERROR) << "filter_tensor malloc failed.";
return nullptr;
}
MS_ASSERT(data_type == kNumberTypeFloat32);
auto *origin_weight = reinterpret_cast<float *>(inputs.at(kWeightIndex)->data_c());
memcpy(filter_tensor->data_c(), origin_weight + index * copy_length, copy_length * sizeof(float));
return filter_tensor;
}
lite::Tensor *CreateBiasTensorFp32(TypeId data_type, std::vector<int> bias_shape,
const std::vector<lite::Tensor *> &inputs, int new_out_channel, int index) {
auto *origin_bias = inputs.at(kBiasIndex)->data_c();
auto bias_tensor =
new (std::nothrow) lite::Tensor(data_type, bias_shape, Format_NHWC, lite::Tensor::Category::CONST_TENSOR);
if (bias_tensor == nullptr) {
MS_LOG(ERROR) << "new bias_tensor failed.";
return nullptr;
}
auto ret = bias_tensor->MallocData();
if (ret != RET_OK) {
delete bias_tensor;
MS_LOG(ERROR) << "bias_tensor malloc failed.";
return nullptr;
}
MS_ASSERT(data_type == kNumberTypeFloat32);
auto bias_data = reinterpret_cast<float *>(origin_bias);
memcpy(bias_tensor->data_c(), bias_data + index * new_out_channel, new_out_channel * sizeof(float));
return bias_tensor;
}
lite::Tensor *CreateOutputTensor(std::vector<int> out_shape, const std::vector<lite::Tensor *> &outputs,
bool infered_flag, int index) {
auto out_tensor = new (std::nothrow) lite::Tensor();
if (out_tensor == nullptr) {
MS_LOG(ERROR) << "new tmp_out_tensor failed.";
return nullptr;
}
out_tensor->set_data_type(outputs.at(index)->data_type());
out_tensor->set_format(outputs.at(index)->format());
if (infered_flag) {
out_tensor->set_shape(out_shape);
auto ret = out_tensor->MallocData();
if (ret != RET_OK) {
delete out_tensor;
MS_LOG(ERROR) << "out_tensor malloc data failed.";
return nullptr;
}
}
return out_tensor;
}
kernel::LiteKernel *CpuConvFp32KernelSelect(const std::vector<lite::Tensor *> &inputs,
const std::vector<lite::Tensor *> &outputs, OpParameter *op_parameter,
const InnerContext *ctx, const mindspore::lite::PrimitiveC *primitive,
bool use_winograd, int out_unit) {
auto conv_param = reinterpret_cast<ConvParameter *>(op_parameter);
if (conv_param->kernel_h_ == 1 && conv_param->kernel_w_ == 1) {
return new (std::nothrow) kernel::Convolution1x1CPUKernel(op_parameter, inputs, outputs, ctx, primitive);
} else if (use_winograd) {
return new (std::nothrow)
kernel::ConvolutionWinogradCPUKernel(op_parameter, inputs, outputs, ctx, primitive, out_unit);
} else {
return new (std::nothrow) kernel::ConvolutionCPUKernel(op_parameter, inputs, outputs, ctx, primitive);
}
return nullptr;
}
kernel::LiteKernel *CpuGroupConvFp32KernelCreator(const std::vector<lite::Tensor *> &inputs,
const std::vector<lite::Tensor *> &outputs, OpParameter *op_parameter,
const InnerContext *ctx, const mindspore::lite::PrimitiveC *primitive,
int group) {
int out_unit;
bool has_bias = inputs.size() == 3;
bool use_winograd = false;
bool infered_flag = primitive != nullptr && primitive->infer_flag();
auto conv_param = reinterpret_cast<ConvParameter *>(op_parameter);
std::vector<int> in_shape;
std::vector<int> out_shape;
int new_in_channel = inputs.at(kWeightIndex)->Channel();
int new_out_channel = 0;
if (group == 0) {
MS_LOG(ERROR) << "Divisor 'group' cannot be 0.";
return nullptr;
} else {
new_out_channel = inputs.at(kWeightIndex)->Batch() / group;
}
int batch = inputs.front()->Batch();
conv_param->input_batch_ = batch;
conv_param->output_batch_ = batch;
if (infered_flag) {
int in_h = inputs.front()->Height();
int in_w = inputs.front()->Width();
conv_param->input_channel_ = new_in_channel;
conv_param->output_channel_ = new_out_channel;
CheckIfUseWinograd(&use_winograd, &out_unit, conv_param);
in_shape = {batch, in_h, in_w, new_in_channel};
out_shape = {batch, conv_param->output_h_, conv_param->output_w_, new_out_channel};
}
std::vector<int> filter_shape = {new_out_channel, conv_param->kernel_h_, conv_param->kernel_w_, new_in_channel};
std::vector<int> bias_shape = {new_out_channel};
// create sub kernels
std::vector<kernel::LiteKernel *> group_convs;
for (int i = 0; i < group; ++i) {
std::vector<lite::Tensor *> new_inputs;
std::vector<lite::Tensor *> new_outputs;
auto new_conv_parameter = CreateNewConvParameter(conv_param);
if (new_conv_parameter == nullptr) {
FreeMemory(group_convs, new_inputs, new_outputs);
MS_LOG(ERROR) << "Get new conv parameter failed.";
return nullptr;
}
// create new input for each group
auto in_tensor = CreateInputTensor(inputs.front()->data_type(), in_shape, infered_flag);
if (in_tensor == nullptr) {
delete new_conv_parameter;
FreeMemory(group_convs, new_inputs, new_outputs);
MS_LOG(ERROR) << "create input tensor failed.";
return nullptr;
}
new_inputs.emplace_back(in_tensor);
// create new weight
int copy_length = conv_param->kernel_h_ * conv_param->kernel_w_ * new_in_channel * new_out_channel;
auto filter_tensor =
CreateFilterTensorFp32(inputs.at(kWeightIndex)->data_type(), filter_shape, inputs, copy_length, i);
if (filter_tensor == nullptr) {
delete new_conv_parameter;
FreeMemory(group_convs, new_inputs, new_outputs);
MS_LOG(ERROR) << "create filter tensor failed.";
return nullptr;
}
new_inputs.emplace_back(filter_tensor);
// if has bias, create new bias
if (has_bias) {
auto bias_tensor =
CreateBiasTensorFp32(inputs.at(kBiasIndex)->data_type(), bias_shape, inputs, new_out_channel, i);
if (bias_tensor == nullptr) {
delete new_conv_parameter;
FreeMemory(group_convs, new_inputs, new_outputs);
MS_LOG(ERROR) << "create bias_tensor failed.";
return nullptr;
}
new_inputs.emplace_back(bias_tensor);
}
// create new output tensor
for (size_t j = 0; j < outputs.size(); ++j) {
auto out_tensor = CreateOutputTensor(out_shape, outputs, infered_flag, j);
if (out_tensor == nullptr) {
delete new_conv_parameter;
FreeMemory(group_convs, new_inputs, new_outputs);
MS_LOG(ERROR) << "new out_tensor failed.";
return nullptr;
}
new_outputs.emplace_back(out_tensor);
}
group_convs.emplace_back(CpuConvFp32KernelSelect(new_inputs, new_outputs,
reinterpret_cast<OpParameter *>(new_conv_parameter), ctx,
primitive, use_winograd, out_unit));
}
return new (std::nothrow)
GroupConvolutionCPUKernel(op_parameter, inputs, outputs, ctx, primitive, group_convs, group);
}
kernel::LiteKernel *CpuConvFp32KernelCreator(const std::vector<lite::Tensor *> &inputs,
const std::vector<lite::Tensor *> &outputs, OpParameter *op_parameter,
const InnerContext *ctx, const kernel::KernelKey &desc,
const mindspore::lite::PrimitiveC *primitive) {
MS_ASSERT(op_parameter != nullptr);
MS_ASSERT(desc.type == schema::PrimitiveType_Conv2D);
MS_ASSERT(desc.data_type == kNumberTypeFloat32);
auto conv_param = reinterpret_cast<ConvParameter *>(op_parameter);
int group = conv_param->group_;
bool use_winograd = false;
int out_unit;
if (primitive != nullptr && primitive->infer_flag()) {
conv_param->input_h_ = inputs.front()->Height();
conv_param->input_w_ = inputs.front()->Width();
conv_param->input_channel_ = inputs.front()->Channel();
conv_param->output_h_ = outputs.front()->Height();
conv_param->output_w_ = outputs.front()->Width();
conv_param->output_channel_ = outputs.front()->Channel();
conv_param->op_parameter_.thread_num_ = ctx->thread_num_;
CheckIfUseWinograd(&use_winograd, &out_unit, conv_param);
}
auto *weight_tensor = inputs.at(kWeightIndex);
auto *restore_data = weight_tensor->data_c();
auto restore_type = weight_tensor->data_type();
bool dequant_flag =
!weight_tensor->quant_params().empty() && weight_tensor->quant_params().front().inited && restore_data != nullptr;
if (dequant_flag) {
auto *dequant_weight = kernel::DequantUtil::DequantWeight(weight_tensor);
if (dequant_weight == nullptr) {
MS_LOG(ERROR) << "dequant data is nullptr.";
free(op_parameter);
return nullptr;
}
weight_tensor->set_data(dequant_weight);
}
kernel::LiteKernel *kernel;
if (group == 1) {
kernel = CpuConvFp32KernelSelect(inputs, outputs, op_parameter, ctx, primitive, use_winograd, out_unit);
} else {
kernel = CpuGroupConvFp32KernelCreator(inputs, outputs, op_parameter, ctx, primitive, group);
}
if (kernel == nullptr) {
MS_LOG(ERROR) << "kernel is nullptr.";
if (dequant_flag) {
weight_tensor->FreeData();
weight_tensor->set_data(restore_data);
weight_tensor->set_data_type(restore_type);
}
free(op_parameter);
return nullptr;
}
auto ret = kernel->Init();
if (ret != RET_OK && ret != RET_INFER_INVALID) {
MS_LOG(ERROR) << "Init kernel failed, name: " << op_parameter->name_ << ", type: "
<< schema::EnumNamePrimitiveType(static_cast<schema::PrimitiveType>(op_parameter->type_));
if (dequant_flag) {
weight_tensor->FreeData();
weight_tensor->set_data(restore_data);
weight_tensor->set_data_type(restore_type);
}
delete kernel;
return nullptr;
}
if (dequant_flag) {
weight_tensor->FreeData();
weight_tensor->set_data(restore_data);
weight_tensor->set_data_type(restore_type);
}
return kernel;
}
REG_KERNEL(kCPU, kNumberTypeFloat32, PrimitiveType_Conv2D, CpuConvFp32KernelCreator)
} // namespace mindspore::kernel
| 37.942797 | 120 | 0.685633 | taroxd |
fa3e9a0bc2dd0bcba79d797ef2269824617ff5b6 | 3,440 | cpp | C++ | genome/genome.cpp | nicodex/lianzifu | 67c08abf0636e85512bfc91ac9ebe43dc2255186 | [
"MIT"
] | 2 | 2018-02-01T04:08:48.000Z | 2018-02-03T16:33:38.000Z | genome/genome.cpp | nicodex/lianzifu | 67c08abf0636e85512bfc91ac9ebe43dc2255186 | [
"MIT"
] | 1 | 2018-02-02T12:28:32.000Z | 2018-02-09T13:13:53.000Z | genome/genome.cpp | nicodex/lianzifu | 67c08abf0636e85512bfc91ac9ebe43dc2255186 | [
"MIT"
] | 1 | 2020-05-20T15:52:21.000Z | 2020-05-20T15:52:21.000Z | //
// Copyright (c) 2018 Nico Bendlin <nico@nicode.net>
//
// 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 <genome/genome.hpp>
#include <genome/locale.hpp>
#include <genome/filesystem.hpp>
void
init_genome(void)
{
genome::locale::init();
genome::filesystem::init();
}
namespace genome {
namespace /*{anonymous}*/ {
char const*
skip_space(char const*& s)
{
if (!s) {
s = "";
} else {
while (('\t' == *s) || (' ' == *s)) {
++s;
}
}
return (s);
}
bool
is_end(char const*& s)
{
return ('\0' == *skip_space(s));
}
} // namespace genome::{anonymous}
//
// platforms
//
char const*
platform_name(platform target)
{
switch (target) {
default:
case platform_unknown:
return ("<invalid>");
case platform_pc:
return ("pc");
case platform_x64:
return ("x64");
case platform_ps3:
return ("ps3");
case platform_ps4:
return ("ps4");
case platform_x360:
return ("x360");
case platform_xone:
return ("xone");
}
}
char const*
platform_desc(platform target)
{
switch (target) {
default:
case platform_unknown:
return ("<invalid>");
case platform_pc:
return ("Windows (32-bit)");
case platform_x64:
return ("Windows (64-bit)");
case platform_ps3:
return ("PlayStation 3");
case platform_ps4:
return ("PlayStation 4");
case platform_x360:
return ("Xbox 360");
case platform_xone:
return ("Xbox One");
}
}
platform
platform_from_name(char const* name)
{
switch (*skip_space(name)) {
case 'p': case 'P':
switch (*++name) {
case 'c': case 'C':
if (is_end(++name)) {
return (platform_pc);
}
break;
case 's': case 'S':
switch (*++name) {
case '3':
if (is_end(++name)) {
return (platform_ps3);
}
break;
case '4':
if (is_end(++name)) {
return (platform_ps4);
}
break;
}
break;
}
break;
case 'x': case 'X':
switch (*++name) {
case '3':
if ('6' == *++name) {
if ('0' == *++name) {
if (is_end(++name)) {
return (platform_x360);
}
}
}
break;
case '6':
if ('4' == *++name) {
if (is_end(++name)) {
return (platform_x64);
}
}
break;
case 'o': case 'O':
if (++name, ('n' == *name) || ('N' == *name)) {
if (++name, ('e' == *name) || ('E' == *name)) {
if (is_end(++name)) {
return (platform_xone);
}
}
}
break;
}
break;
}
return (platform_unknown);
}
} // namespace genome
| 20.598802 | 80 | 0.623256 | nicodex |
fa41bd932a3d0556d52ae51a1763aa49055ceffe | 2,106 | cc | C++ | kernel/src/arch/x86_64/hal/task/context.cc | igarfieldi/Danaos64 | f4a2df8de5f214af7a4d18e14790740d2c481c48 | [
"Apache-2.0"
] | 2 | 2017-09-16T19:41:14.000Z | 2017-11-04T10:41:38.000Z | kernel/src/arch/x86_64/hal/task/context.cc | igarfieldi/Danaos64 | f4a2df8de5f214af7a4d18e14790740d2c481c48 | [
"Apache-2.0"
] | null | null | null | kernel/src/arch/x86_64/hal/task/context.cc | igarfieldi/Danaos64 | f4a2df8de5f214af7a4d18e14790740d2c481c48 | [
"Apache-2.0"
] | null | null | null | #include "context.h"
#include "hal/interrupts/gdt.h"
#include "main/task/task.h"
namespace hal {
task_context create_context(volatile uint64_t *stack, task::task &task) {
task_context context(&stack[-21]);
// New state
stack[-21] = reinterpret_cast<uint64_t>(&stack[0]); // RBP
stack[-20] = 0xAAAAAAAAAAAAAAAA; // RAX
stack[-19] = 0xBBBBBBBBBBBBBBBB; // RBX
stack[-18] = 0xCCCCCCCCCCCCCCCC; // RCX
stack[-17] = 0xDDDDDDDDDDDDDDDD; // RDX
stack[-16] = 0x8888888888888888; // R8
stack[-15] = 0x9999999999999999; // R9
stack[-14] = 0x0000000000000000; // R10
stack[-13] = 0x1111111111111111; // R11
stack[-12] = 0x2222222222222222; // R12
stack[-11] = 0x3333333333333333; // R13
stack[-10] = 0x4444444444444444; // R14
stack[-9] = 0x5555555555555555; // R15
stack[-8] = 0x5151515151515151; // RSI
stack[-7] = reinterpret_cast<uint64_t>(&task); // RDI
stack[-6] = 0x0; // Interrupt number
stack[-5] = 0x0; // Error code
stack[-4] = reinterpret_cast<uint64_t>(&task::task::start); // Return RIP
stack[-3] = 0x8; // Return CS
stack[-2] = 0x200; // RFLAGS (enable interrupts)
stack[-1] = reinterpret_cast<uint64_t>(&stack[0]); // Return RSP
stack[0] = 0x10; // Return SS
return context;
}
} // namespace hal
| 55.421053 | 101 | 0.395537 | igarfieldi |
fa425c1f643a874587973399f192364a916e82ae | 139,538 | cxx | C++ | SimModel_Python_API/simmodel_swig/SimModel_Dll_lib/framework/SimFlowPlant_ElectricalGenerator_Photovoltaic.cxx | EnEff-BIM/EnEffBIM-Framework | 6328d39b498dc4065a60b5cc9370b8c2a9a1cddf | [
"MIT"
] | 3 | 2016-05-30T15:12:16.000Z | 2022-03-22T08:11:13.000Z | SimModel_Python_API/simmodel_swig/SimModel_Dll_lib/framework/SimFlowPlant_ElectricalGenerator_Photovoltaic.cxx | EnEff-BIM/EnEffBIM-Framework | 6328d39b498dc4065a60b5cc9370b8c2a9a1cddf | [
"MIT"
] | 21 | 2016-06-13T11:33:45.000Z | 2017-05-23T09:46:52.000Z | SimModel_Python_API/simmodel_swig/SimModel_Dll_lib/framework/SimFlowPlant_ElectricalGenerator_Photovoltaic.cxx | EnEff-BIM/EnEffBIM-Framework | 6328d39b498dc4065a60b5cc9370b8c2a9a1cddf | [
"MIT"
] | null | null | null | // Copyright (c) 2005-2014 Code Synthesis Tools CC
//
// This program was generated by CodeSynthesis XSD, an XML Schema to
// C++ data binding compiler.
//
// This program is free software; you can redistribute it and/or modify
// it under the terms of the GNU General Public License version 2 as
// published by the Free Software Foundation.
//
// This program is distributed in the hope that it will be useful,
// but WITHOUT ANY WARRANTY; without even the implied warranty of
// MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
// GNU General Public License for more details.
//
// You should have received a copy of the GNU General Public License
// along with this program; if not, write to the Free Software
// Foundation, Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301 USA
//
// In addition, as a special exception, Code Synthesis Tools CC gives
// permission to link this program with the Xerces-C++ library (or with
// modified versions of Xerces-C++ that use the same license as Xerces-C++),
// and distribute linked combinations including the two. You must obey
// the GNU General Public License version 2 in all respects for all of
// the code used other than Xerces-C++. If you modify this copy of the
// program, you may extend this exception to your version of the program,
// but you are not obligated to do so. If you do not wish to do so, delete
// this exception statement from your version.
//
// Furthermore, Code Synthesis Tools CC makes a special exception for
// the Free/Libre and Open Source Software (FLOSS) which is described
// in the accompanying FLOSSE file.
//
// Begin prologue.
//
//
// End prologue.
#include <xsd/cxx/pre.hxx>
#include "SimFlowPlant_ElectricalGenerator_Photovoltaic.hxx"
#include "doublelist.hxx"
namespace schema
{
namespace simxml
{
namespace MepModel
{
// SimFlowPlant_ElectricalGenerator_Photovoltaic
//
const SimFlowPlant_ElectricalGenerator_Photovoltaic::SimFlowPlant_Name_optional& SimFlowPlant_ElectricalGenerator_Photovoltaic::
SimFlowPlant_Name () const
{
return this->SimFlowPlant_Name_;
}
SimFlowPlant_ElectricalGenerator_Photovoltaic::SimFlowPlant_Name_optional& SimFlowPlant_ElectricalGenerator_Photovoltaic::
SimFlowPlant_Name ()
{
return this->SimFlowPlant_Name_;
}
void SimFlowPlant_ElectricalGenerator_Photovoltaic::
SimFlowPlant_Name (const SimFlowPlant_Name_type& x)
{
this->SimFlowPlant_Name_.set (x);
}
void SimFlowPlant_ElectricalGenerator_Photovoltaic::
SimFlowPlant_Name (const SimFlowPlant_Name_optional& x)
{
this->SimFlowPlant_Name_ = x;
}
void SimFlowPlant_ElectricalGenerator_Photovoltaic::
SimFlowPlant_Name (::std::auto_ptr< SimFlowPlant_Name_type > x)
{
this->SimFlowPlant_Name_.set (x);
}
const SimFlowPlant_ElectricalGenerator_Photovoltaic::SimFlowPlant_SurfName_optional& SimFlowPlant_ElectricalGenerator_Photovoltaic::
SimFlowPlant_SurfName () const
{
return this->SimFlowPlant_SurfName_;
}
SimFlowPlant_ElectricalGenerator_Photovoltaic::SimFlowPlant_SurfName_optional& SimFlowPlant_ElectricalGenerator_Photovoltaic::
SimFlowPlant_SurfName ()
{
return this->SimFlowPlant_SurfName_;
}
void SimFlowPlant_ElectricalGenerator_Photovoltaic::
SimFlowPlant_SurfName (const SimFlowPlant_SurfName_type& x)
{
this->SimFlowPlant_SurfName_.set (x);
}
void SimFlowPlant_ElectricalGenerator_Photovoltaic::
SimFlowPlant_SurfName (const SimFlowPlant_SurfName_optional& x)
{
this->SimFlowPlant_SurfName_ = x;
}
void SimFlowPlant_ElectricalGenerator_Photovoltaic::
SimFlowPlant_SurfName (::std::auto_ptr< SimFlowPlant_SurfName_type > x)
{
this->SimFlowPlant_SurfName_.set (x);
}
const SimFlowPlant_ElectricalGenerator_Photovoltaic::SimFlowPlant_PhotovoltaicPerfObjType_optional& SimFlowPlant_ElectricalGenerator_Photovoltaic::
SimFlowPlant_PhotovoltaicPerfObjType () const
{
return this->SimFlowPlant_PhotovoltaicPerfObjType_;
}
SimFlowPlant_ElectricalGenerator_Photovoltaic::SimFlowPlant_PhotovoltaicPerfObjType_optional& SimFlowPlant_ElectricalGenerator_Photovoltaic::
SimFlowPlant_PhotovoltaicPerfObjType ()
{
return this->SimFlowPlant_PhotovoltaicPerfObjType_;
}
void SimFlowPlant_ElectricalGenerator_Photovoltaic::
SimFlowPlant_PhotovoltaicPerfObjType (const SimFlowPlant_PhotovoltaicPerfObjType_type& x)
{
this->SimFlowPlant_PhotovoltaicPerfObjType_.set (x);
}
void SimFlowPlant_ElectricalGenerator_Photovoltaic::
SimFlowPlant_PhotovoltaicPerfObjType (const SimFlowPlant_PhotovoltaicPerfObjType_optional& x)
{
this->SimFlowPlant_PhotovoltaicPerfObjType_ = x;
}
void SimFlowPlant_ElectricalGenerator_Photovoltaic::
SimFlowPlant_PhotovoltaicPerfObjType (::std::auto_ptr< SimFlowPlant_PhotovoltaicPerfObjType_type > x)
{
this->SimFlowPlant_PhotovoltaicPerfObjType_.set (x);
}
const SimFlowPlant_ElectricalGenerator_Photovoltaic::SimFlowPlant_ModulePerfName_optional& SimFlowPlant_ElectricalGenerator_Photovoltaic::
SimFlowPlant_ModulePerfName () const
{
return this->SimFlowPlant_ModulePerfName_;
}
SimFlowPlant_ElectricalGenerator_Photovoltaic::SimFlowPlant_ModulePerfName_optional& SimFlowPlant_ElectricalGenerator_Photovoltaic::
SimFlowPlant_ModulePerfName ()
{
return this->SimFlowPlant_ModulePerfName_;
}
void SimFlowPlant_ElectricalGenerator_Photovoltaic::
SimFlowPlant_ModulePerfName (const SimFlowPlant_ModulePerfName_type& x)
{
this->SimFlowPlant_ModulePerfName_.set (x);
}
void SimFlowPlant_ElectricalGenerator_Photovoltaic::
SimFlowPlant_ModulePerfName (const SimFlowPlant_ModulePerfName_optional& x)
{
this->SimFlowPlant_ModulePerfName_ = x;
}
void SimFlowPlant_ElectricalGenerator_Photovoltaic::
SimFlowPlant_ModulePerfName (::std::auto_ptr< SimFlowPlant_ModulePerfName_type > x)
{
this->SimFlowPlant_ModulePerfName_.set (x);
}
const SimFlowPlant_ElectricalGenerator_Photovoltaic::SimFlowPlant_HeatTranstegrationMode_optional& SimFlowPlant_ElectricalGenerator_Photovoltaic::
SimFlowPlant_HeatTranstegrationMode () const
{
return this->SimFlowPlant_HeatTranstegrationMode_;
}
SimFlowPlant_ElectricalGenerator_Photovoltaic::SimFlowPlant_HeatTranstegrationMode_optional& SimFlowPlant_ElectricalGenerator_Photovoltaic::
SimFlowPlant_HeatTranstegrationMode ()
{
return this->SimFlowPlant_HeatTranstegrationMode_;
}
void SimFlowPlant_ElectricalGenerator_Photovoltaic::
SimFlowPlant_HeatTranstegrationMode (const SimFlowPlant_HeatTranstegrationMode_type& x)
{
this->SimFlowPlant_HeatTranstegrationMode_.set (x);
}
void SimFlowPlant_ElectricalGenerator_Photovoltaic::
SimFlowPlant_HeatTranstegrationMode (const SimFlowPlant_HeatTranstegrationMode_optional& x)
{
this->SimFlowPlant_HeatTranstegrationMode_ = x;
}
void SimFlowPlant_ElectricalGenerator_Photovoltaic::
SimFlowPlant_HeatTranstegrationMode (::std::auto_ptr< SimFlowPlant_HeatTranstegrationMode_type > x)
{
this->SimFlowPlant_HeatTranstegrationMode_.set (x);
}
const SimFlowPlant_ElectricalGenerator_Photovoltaic::SimFlowPlant_NumberofSeriesStringsinParallel_optional& SimFlowPlant_ElectricalGenerator_Photovoltaic::
SimFlowPlant_NumberofSeriesStringsinParallel () const
{
return this->SimFlowPlant_NumberofSeriesStringsinParallel_;
}
SimFlowPlant_ElectricalGenerator_Photovoltaic::SimFlowPlant_NumberofSeriesStringsinParallel_optional& SimFlowPlant_ElectricalGenerator_Photovoltaic::
SimFlowPlant_NumberofSeriesStringsinParallel ()
{
return this->SimFlowPlant_NumberofSeriesStringsinParallel_;
}
void SimFlowPlant_ElectricalGenerator_Photovoltaic::
SimFlowPlant_NumberofSeriesStringsinParallel (const SimFlowPlant_NumberofSeriesStringsinParallel_type& x)
{
this->SimFlowPlant_NumberofSeriesStringsinParallel_.set (x);
}
void SimFlowPlant_ElectricalGenerator_Photovoltaic::
SimFlowPlant_NumberofSeriesStringsinParallel (const SimFlowPlant_NumberofSeriesStringsinParallel_optional& x)
{
this->SimFlowPlant_NumberofSeriesStringsinParallel_ = x;
}
const SimFlowPlant_ElectricalGenerator_Photovoltaic::SimFlowPlant_NumModulesSeries_optional& SimFlowPlant_ElectricalGenerator_Photovoltaic::
SimFlowPlant_NumModulesSeries () const
{
return this->SimFlowPlant_NumModulesSeries_;
}
SimFlowPlant_ElectricalGenerator_Photovoltaic::SimFlowPlant_NumModulesSeries_optional& SimFlowPlant_ElectricalGenerator_Photovoltaic::
SimFlowPlant_NumModulesSeries ()
{
return this->SimFlowPlant_NumModulesSeries_;
}
void SimFlowPlant_ElectricalGenerator_Photovoltaic::
SimFlowPlant_NumModulesSeries (const SimFlowPlant_NumModulesSeries_type& x)
{
this->SimFlowPlant_NumModulesSeries_.set (x);
}
void SimFlowPlant_ElectricalGenerator_Photovoltaic::
SimFlowPlant_NumModulesSeries (const SimFlowPlant_NumModulesSeries_optional& x)
{
this->SimFlowPlant_NumModulesSeries_ = x;
}
const SimFlowPlant_ElectricalGenerator_Photovoltaic::PhotovoltaicPerformance_Simple_Name_optional& SimFlowPlant_ElectricalGenerator_Photovoltaic::
PhotovoltaicPerformance_Simple_Name () const
{
return this->PhotovoltaicPerformance_Simple_Name_;
}
SimFlowPlant_ElectricalGenerator_Photovoltaic::PhotovoltaicPerformance_Simple_Name_optional& SimFlowPlant_ElectricalGenerator_Photovoltaic::
PhotovoltaicPerformance_Simple_Name ()
{
return this->PhotovoltaicPerformance_Simple_Name_;
}
void SimFlowPlant_ElectricalGenerator_Photovoltaic::
PhotovoltaicPerformance_Simple_Name (const PhotovoltaicPerformance_Simple_Name_type& x)
{
this->PhotovoltaicPerformance_Simple_Name_.set (x);
}
void SimFlowPlant_ElectricalGenerator_Photovoltaic::
PhotovoltaicPerformance_Simple_Name (const PhotovoltaicPerformance_Simple_Name_optional& x)
{
this->PhotovoltaicPerformance_Simple_Name_ = x;
}
void SimFlowPlant_ElectricalGenerator_Photovoltaic::
PhotovoltaicPerformance_Simple_Name (::std::auto_ptr< PhotovoltaicPerformance_Simple_Name_type > x)
{
this->PhotovoltaicPerformance_Simple_Name_.set (x);
}
const SimFlowPlant_ElectricalGenerator_Photovoltaic::PhotovoltaicPerformance_Simple_FractionOfSurfAreawithActiveSolarCells_optional& SimFlowPlant_ElectricalGenerator_Photovoltaic::
PhotovoltaicPerformance_Simple_FractionOfSurfAreawithActiveSolarCells () const
{
return this->PhotovoltaicPerformance_Simple_FractionOfSurfAreawithActiveSolarCells_;
}
SimFlowPlant_ElectricalGenerator_Photovoltaic::PhotovoltaicPerformance_Simple_FractionOfSurfAreawithActiveSolarCells_optional& SimFlowPlant_ElectricalGenerator_Photovoltaic::
PhotovoltaicPerformance_Simple_FractionOfSurfAreawithActiveSolarCells ()
{
return this->PhotovoltaicPerformance_Simple_FractionOfSurfAreawithActiveSolarCells_;
}
void SimFlowPlant_ElectricalGenerator_Photovoltaic::
PhotovoltaicPerformance_Simple_FractionOfSurfAreawithActiveSolarCells (const PhotovoltaicPerformance_Simple_FractionOfSurfAreawithActiveSolarCells_type& x)
{
this->PhotovoltaicPerformance_Simple_FractionOfSurfAreawithActiveSolarCells_.set (x);
}
void SimFlowPlant_ElectricalGenerator_Photovoltaic::
PhotovoltaicPerformance_Simple_FractionOfSurfAreawithActiveSolarCells (const PhotovoltaicPerformance_Simple_FractionOfSurfAreawithActiveSolarCells_optional& x)
{
this->PhotovoltaicPerformance_Simple_FractionOfSurfAreawithActiveSolarCells_ = x;
}
const SimFlowPlant_ElectricalGenerator_Photovoltaic::PhotovoltaicPerformance_Simple_ConversionEfficiencyInputMode_optional& SimFlowPlant_ElectricalGenerator_Photovoltaic::
PhotovoltaicPerformance_Simple_ConversionEfficiencyInputMode () const
{
return this->PhotovoltaicPerformance_Simple_ConversionEfficiencyInputMode_;
}
SimFlowPlant_ElectricalGenerator_Photovoltaic::PhotovoltaicPerformance_Simple_ConversionEfficiencyInputMode_optional& SimFlowPlant_ElectricalGenerator_Photovoltaic::
PhotovoltaicPerformance_Simple_ConversionEfficiencyInputMode ()
{
return this->PhotovoltaicPerformance_Simple_ConversionEfficiencyInputMode_;
}
void SimFlowPlant_ElectricalGenerator_Photovoltaic::
PhotovoltaicPerformance_Simple_ConversionEfficiencyInputMode (const PhotovoltaicPerformance_Simple_ConversionEfficiencyInputMode_type& x)
{
this->PhotovoltaicPerformance_Simple_ConversionEfficiencyInputMode_.set (x);
}
void SimFlowPlant_ElectricalGenerator_Photovoltaic::
PhotovoltaicPerformance_Simple_ConversionEfficiencyInputMode (const PhotovoltaicPerformance_Simple_ConversionEfficiencyInputMode_optional& x)
{
this->PhotovoltaicPerformance_Simple_ConversionEfficiencyInputMode_ = x;
}
void SimFlowPlant_ElectricalGenerator_Photovoltaic::
PhotovoltaicPerformance_Simple_ConversionEfficiencyInputMode (::std::auto_ptr< PhotovoltaicPerformance_Simple_ConversionEfficiencyInputMode_type > x)
{
this->PhotovoltaicPerformance_Simple_ConversionEfficiencyInputMode_.set (x);
}
const SimFlowPlant_ElectricalGenerator_Photovoltaic::PhotovoltaicPerformance_Simple_ValueforCellEfficiencyifFixed_optional& SimFlowPlant_ElectricalGenerator_Photovoltaic::
PhotovoltaicPerformance_Simple_ValueforCellEfficiencyifFixed () const
{
return this->PhotovoltaicPerformance_Simple_ValueforCellEfficiencyifFixed_;
}
SimFlowPlant_ElectricalGenerator_Photovoltaic::PhotovoltaicPerformance_Simple_ValueforCellEfficiencyifFixed_optional& SimFlowPlant_ElectricalGenerator_Photovoltaic::
PhotovoltaicPerformance_Simple_ValueforCellEfficiencyifFixed ()
{
return this->PhotovoltaicPerformance_Simple_ValueforCellEfficiencyifFixed_;
}
void SimFlowPlant_ElectricalGenerator_Photovoltaic::
PhotovoltaicPerformance_Simple_ValueforCellEfficiencyifFixed (const PhotovoltaicPerformance_Simple_ValueforCellEfficiencyifFixed_type& x)
{
this->PhotovoltaicPerformance_Simple_ValueforCellEfficiencyifFixed_.set (x);
}
void SimFlowPlant_ElectricalGenerator_Photovoltaic::
PhotovoltaicPerformance_Simple_ValueforCellEfficiencyifFixed (const PhotovoltaicPerformance_Simple_ValueforCellEfficiencyifFixed_optional& x)
{
this->PhotovoltaicPerformance_Simple_ValueforCellEfficiencyifFixed_ = x;
}
const SimFlowPlant_ElectricalGenerator_Photovoltaic::PhotovoltaicPerformance_Simple_EfficiencyScheduleName_optional& SimFlowPlant_ElectricalGenerator_Photovoltaic::
PhotovoltaicPerformance_Simple_EfficiencyScheduleName () const
{
return this->PhotovoltaicPerformance_Simple_EfficiencyScheduleName_;
}
SimFlowPlant_ElectricalGenerator_Photovoltaic::PhotovoltaicPerformance_Simple_EfficiencyScheduleName_optional& SimFlowPlant_ElectricalGenerator_Photovoltaic::
PhotovoltaicPerformance_Simple_EfficiencyScheduleName ()
{
return this->PhotovoltaicPerformance_Simple_EfficiencyScheduleName_;
}
void SimFlowPlant_ElectricalGenerator_Photovoltaic::
PhotovoltaicPerformance_Simple_EfficiencyScheduleName (const PhotovoltaicPerformance_Simple_EfficiencyScheduleName_type& x)
{
this->PhotovoltaicPerformance_Simple_EfficiencyScheduleName_.set (x);
}
void SimFlowPlant_ElectricalGenerator_Photovoltaic::
PhotovoltaicPerformance_Simple_EfficiencyScheduleName (const PhotovoltaicPerformance_Simple_EfficiencyScheduleName_optional& x)
{
this->PhotovoltaicPerformance_Simple_EfficiencyScheduleName_ = x;
}
void SimFlowPlant_ElectricalGenerator_Photovoltaic::
PhotovoltaicPerformance_Simple_EfficiencyScheduleName (::std::auto_ptr< PhotovoltaicPerformance_Simple_EfficiencyScheduleName_type > x)
{
this->PhotovoltaicPerformance_Simple_EfficiencyScheduleName_.set (x);
}
const SimFlowPlant_ElectricalGenerator_Photovoltaic::PVPerf_EquivOne_Diode_Name_optional& SimFlowPlant_ElectricalGenerator_Photovoltaic::
PVPerf_EquivOne_Diode_Name () const
{
return this->PVPerf_EquivOne_Diode_Name_;
}
SimFlowPlant_ElectricalGenerator_Photovoltaic::PVPerf_EquivOne_Diode_Name_optional& SimFlowPlant_ElectricalGenerator_Photovoltaic::
PVPerf_EquivOne_Diode_Name ()
{
return this->PVPerf_EquivOne_Diode_Name_;
}
void SimFlowPlant_ElectricalGenerator_Photovoltaic::
PVPerf_EquivOne_Diode_Name (const PVPerf_EquivOne_Diode_Name_type& x)
{
this->PVPerf_EquivOne_Diode_Name_.set (x);
}
void SimFlowPlant_ElectricalGenerator_Photovoltaic::
PVPerf_EquivOne_Diode_Name (const PVPerf_EquivOne_Diode_Name_optional& x)
{
this->PVPerf_EquivOne_Diode_Name_ = x;
}
void SimFlowPlant_ElectricalGenerator_Photovoltaic::
PVPerf_EquivOne_Diode_Name (::std::auto_ptr< PVPerf_EquivOne_Diode_Name_type > x)
{
this->PVPerf_EquivOne_Diode_Name_.set (x);
}
const SimFlowPlant_ElectricalGenerator_Photovoltaic::PVPerf_EquivOne_Diode_CellType_optional& SimFlowPlant_ElectricalGenerator_Photovoltaic::
PVPerf_EquivOne_Diode_CellType () const
{
return this->PVPerf_EquivOne_Diode_CellType_;
}
SimFlowPlant_ElectricalGenerator_Photovoltaic::PVPerf_EquivOne_Diode_CellType_optional& SimFlowPlant_ElectricalGenerator_Photovoltaic::
PVPerf_EquivOne_Diode_CellType ()
{
return this->PVPerf_EquivOne_Diode_CellType_;
}
void SimFlowPlant_ElectricalGenerator_Photovoltaic::
PVPerf_EquivOne_Diode_CellType (const PVPerf_EquivOne_Diode_CellType_type& x)
{
this->PVPerf_EquivOne_Diode_CellType_.set (x);
}
void SimFlowPlant_ElectricalGenerator_Photovoltaic::
PVPerf_EquivOne_Diode_CellType (const PVPerf_EquivOne_Diode_CellType_optional& x)
{
this->PVPerf_EquivOne_Diode_CellType_ = x;
}
void SimFlowPlant_ElectricalGenerator_Photovoltaic::
PVPerf_EquivOne_Diode_CellType (::std::auto_ptr< PVPerf_EquivOne_Diode_CellType_type > x)
{
this->PVPerf_EquivOne_Diode_CellType_.set (x);
}
const SimFlowPlant_ElectricalGenerator_Photovoltaic::PVPerf_EquivOne_Diode_NumCellsSeries_optional& SimFlowPlant_ElectricalGenerator_Photovoltaic::
PVPerf_EquivOne_Diode_NumCellsSeries () const
{
return this->PVPerf_EquivOne_Diode_NumCellsSeries_;
}
SimFlowPlant_ElectricalGenerator_Photovoltaic::PVPerf_EquivOne_Diode_NumCellsSeries_optional& SimFlowPlant_ElectricalGenerator_Photovoltaic::
PVPerf_EquivOne_Diode_NumCellsSeries ()
{
return this->PVPerf_EquivOne_Diode_NumCellsSeries_;
}
void SimFlowPlant_ElectricalGenerator_Photovoltaic::
PVPerf_EquivOne_Diode_NumCellsSeries (const PVPerf_EquivOne_Diode_NumCellsSeries_type& x)
{
this->PVPerf_EquivOne_Diode_NumCellsSeries_.set (x);
}
void SimFlowPlant_ElectricalGenerator_Photovoltaic::
PVPerf_EquivOne_Diode_NumCellsSeries (const PVPerf_EquivOne_Diode_NumCellsSeries_optional& x)
{
this->PVPerf_EquivOne_Diode_NumCellsSeries_ = x;
}
const SimFlowPlant_ElectricalGenerator_Photovoltaic::PVPerf_EquivOne_Diode_ActiveArea_optional& SimFlowPlant_ElectricalGenerator_Photovoltaic::
PVPerf_EquivOne_Diode_ActiveArea () const
{
return this->PVPerf_EquivOne_Diode_ActiveArea_;
}
SimFlowPlant_ElectricalGenerator_Photovoltaic::PVPerf_EquivOne_Diode_ActiveArea_optional& SimFlowPlant_ElectricalGenerator_Photovoltaic::
PVPerf_EquivOne_Diode_ActiveArea ()
{
return this->PVPerf_EquivOne_Diode_ActiveArea_;
}
void SimFlowPlant_ElectricalGenerator_Photovoltaic::
PVPerf_EquivOne_Diode_ActiveArea (const PVPerf_EquivOne_Diode_ActiveArea_type& x)
{
this->PVPerf_EquivOne_Diode_ActiveArea_.set (x);
}
void SimFlowPlant_ElectricalGenerator_Photovoltaic::
PVPerf_EquivOne_Diode_ActiveArea (const PVPerf_EquivOne_Diode_ActiveArea_optional& x)
{
this->PVPerf_EquivOne_Diode_ActiveArea_ = x;
}
const SimFlowPlant_ElectricalGenerator_Photovoltaic::PVPerf_EquivOne_Diode_TransAbsorptanceProduct_optional& SimFlowPlant_ElectricalGenerator_Photovoltaic::
PVPerf_EquivOne_Diode_TransAbsorptanceProduct () const
{
return this->PVPerf_EquivOne_Diode_TransAbsorptanceProduct_;
}
SimFlowPlant_ElectricalGenerator_Photovoltaic::PVPerf_EquivOne_Diode_TransAbsorptanceProduct_optional& SimFlowPlant_ElectricalGenerator_Photovoltaic::
PVPerf_EquivOne_Diode_TransAbsorptanceProduct ()
{
return this->PVPerf_EquivOne_Diode_TransAbsorptanceProduct_;
}
void SimFlowPlant_ElectricalGenerator_Photovoltaic::
PVPerf_EquivOne_Diode_TransAbsorptanceProduct (const PVPerf_EquivOne_Diode_TransAbsorptanceProduct_type& x)
{
this->PVPerf_EquivOne_Diode_TransAbsorptanceProduct_.set (x);
}
void SimFlowPlant_ElectricalGenerator_Photovoltaic::
PVPerf_EquivOne_Diode_TransAbsorptanceProduct (const PVPerf_EquivOne_Diode_TransAbsorptanceProduct_optional& x)
{
this->PVPerf_EquivOne_Diode_TransAbsorptanceProduct_ = x;
}
const SimFlowPlant_ElectricalGenerator_Photovoltaic::PVPerf_EquivOne_Diode_SemiconductorBandgap_optional& SimFlowPlant_ElectricalGenerator_Photovoltaic::
PVPerf_EquivOne_Diode_SemiconductorBandgap () const
{
return this->PVPerf_EquivOne_Diode_SemiconductorBandgap_;
}
SimFlowPlant_ElectricalGenerator_Photovoltaic::PVPerf_EquivOne_Diode_SemiconductorBandgap_optional& SimFlowPlant_ElectricalGenerator_Photovoltaic::
PVPerf_EquivOne_Diode_SemiconductorBandgap ()
{
return this->PVPerf_EquivOne_Diode_SemiconductorBandgap_;
}
void SimFlowPlant_ElectricalGenerator_Photovoltaic::
PVPerf_EquivOne_Diode_SemiconductorBandgap (const PVPerf_EquivOne_Diode_SemiconductorBandgap_type& x)
{
this->PVPerf_EquivOne_Diode_SemiconductorBandgap_.set (x);
}
void SimFlowPlant_ElectricalGenerator_Photovoltaic::
PVPerf_EquivOne_Diode_SemiconductorBandgap (const PVPerf_EquivOne_Diode_SemiconductorBandgap_optional& x)
{
this->PVPerf_EquivOne_Diode_SemiconductorBandgap_ = x;
}
const SimFlowPlant_ElectricalGenerator_Photovoltaic::PVPerf_EquivOne_Diode_ShuntResist_optional& SimFlowPlant_ElectricalGenerator_Photovoltaic::
PVPerf_EquivOne_Diode_ShuntResist () const
{
return this->PVPerf_EquivOne_Diode_ShuntResist_;
}
SimFlowPlant_ElectricalGenerator_Photovoltaic::PVPerf_EquivOne_Diode_ShuntResist_optional& SimFlowPlant_ElectricalGenerator_Photovoltaic::
PVPerf_EquivOne_Diode_ShuntResist ()
{
return this->PVPerf_EquivOne_Diode_ShuntResist_;
}
void SimFlowPlant_ElectricalGenerator_Photovoltaic::
PVPerf_EquivOne_Diode_ShuntResist (const PVPerf_EquivOne_Diode_ShuntResist_type& x)
{
this->PVPerf_EquivOne_Diode_ShuntResist_.set (x);
}
void SimFlowPlant_ElectricalGenerator_Photovoltaic::
PVPerf_EquivOne_Diode_ShuntResist (const PVPerf_EquivOne_Diode_ShuntResist_optional& x)
{
this->PVPerf_EquivOne_Diode_ShuntResist_ = x;
}
const SimFlowPlant_ElectricalGenerator_Photovoltaic::PVPerf_EquivOne_Diode_ShortCircuitCurrent_optional& SimFlowPlant_ElectricalGenerator_Photovoltaic::
PVPerf_EquivOne_Diode_ShortCircuitCurrent () const
{
return this->PVPerf_EquivOne_Diode_ShortCircuitCurrent_;
}
SimFlowPlant_ElectricalGenerator_Photovoltaic::PVPerf_EquivOne_Diode_ShortCircuitCurrent_optional& SimFlowPlant_ElectricalGenerator_Photovoltaic::
PVPerf_EquivOne_Diode_ShortCircuitCurrent ()
{
return this->PVPerf_EquivOne_Diode_ShortCircuitCurrent_;
}
void SimFlowPlant_ElectricalGenerator_Photovoltaic::
PVPerf_EquivOne_Diode_ShortCircuitCurrent (const PVPerf_EquivOne_Diode_ShortCircuitCurrent_type& x)
{
this->PVPerf_EquivOne_Diode_ShortCircuitCurrent_.set (x);
}
void SimFlowPlant_ElectricalGenerator_Photovoltaic::
PVPerf_EquivOne_Diode_ShortCircuitCurrent (const PVPerf_EquivOne_Diode_ShortCircuitCurrent_optional& x)
{
this->PVPerf_EquivOne_Diode_ShortCircuitCurrent_ = x;
}
const SimFlowPlant_ElectricalGenerator_Photovoltaic::PVPerf_EquivOne_Diode_OpenCircuitVolt_optional& SimFlowPlant_ElectricalGenerator_Photovoltaic::
PVPerf_EquivOne_Diode_OpenCircuitVolt () const
{
return this->PVPerf_EquivOne_Diode_OpenCircuitVolt_;
}
SimFlowPlant_ElectricalGenerator_Photovoltaic::PVPerf_EquivOne_Diode_OpenCircuitVolt_optional& SimFlowPlant_ElectricalGenerator_Photovoltaic::
PVPerf_EquivOne_Diode_OpenCircuitVolt ()
{
return this->PVPerf_EquivOne_Diode_OpenCircuitVolt_;
}
void SimFlowPlant_ElectricalGenerator_Photovoltaic::
PVPerf_EquivOne_Diode_OpenCircuitVolt (const PVPerf_EquivOne_Diode_OpenCircuitVolt_type& x)
{
this->PVPerf_EquivOne_Diode_OpenCircuitVolt_.set (x);
}
void SimFlowPlant_ElectricalGenerator_Photovoltaic::
PVPerf_EquivOne_Diode_OpenCircuitVolt (const PVPerf_EquivOne_Diode_OpenCircuitVolt_optional& x)
{
this->PVPerf_EquivOne_Diode_OpenCircuitVolt_ = x;
}
const SimFlowPlant_ElectricalGenerator_Photovoltaic::PVPerf_EquivOne_Diode_RefTemp_optional& SimFlowPlant_ElectricalGenerator_Photovoltaic::
PVPerf_EquivOne_Diode_RefTemp () const
{
return this->PVPerf_EquivOne_Diode_RefTemp_;
}
SimFlowPlant_ElectricalGenerator_Photovoltaic::PVPerf_EquivOne_Diode_RefTemp_optional& SimFlowPlant_ElectricalGenerator_Photovoltaic::
PVPerf_EquivOne_Diode_RefTemp ()
{
return this->PVPerf_EquivOne_Diode_RefTemp_;
}
void SimFlowPlant_ElectricalGenerator_Photovoltaic::
PVPerf_EquivOne_Diode_RefTemp (const PVPerf_EquivOne_Diode_RefTemp_type& x)
{
this->PVPerf_EquivOne_Diode_RefTemp_.set (x);
}
void SimFlowPlant_ElectricalGenerator_Photovoltaic::
PVPerf_EquivOne_Diode_RefTemp (const PVPerf_EquivOne_Diode_RefTemp_optional& x)
{
this->PVPerf_EquivOne_Diode_RefTemp_ = x;
}
const SimFlowPlant_ElectricalGenerator_Photovoltaic::PVPerf_EquivOne_Diode_RefInsol_optional& SimFlowPlant_ElectricalGenerator_Photovoltaic::
PVPerf_EquivOne_Diode_RefInsol () const
{
return this->PVPerf_EquivOne_Diode_RefInsol_;
}
SimFlowPlant_ElectricalGenerator_Photovoltaic::PVPerf_EquivOne_Diode_RefInsol_optional& SimFlowPlant_ElectricalGenerator_Photovoltaic::
PVPerf_EquivOne_Diode_RefInsol ()
{
return this->PVPerf_EquivOne_Diode_RefInsol_;
}
void SimFlowPlant_ElectricalGenerator_Photovoltaic::
PVPerf_EquivOne_Diode_RefInsol (const PVPerf_EquivOne_Diode_RefInsol_type& x)
{
this->PVPerf_EquivOne_Diode_RefInsol_.set (x);
}
void SimFlowPlant_ElectricalGenerator_Photovoltaic::
PVPerf_EquivOne_Diode_RefInsol (const PVPerf_EquivOne_Diode_RefInsol_optional& x)
{
this->PVPerf_EquivOne_Diode_RefInsol_ = x;
}
const SimFlowPlant_ElectricalGenerator_Photovoltaic::PVPerf_EquivOne_Diode_ModuleCurrentAtMaxPwr_optional& SimFlowPlant_ElectricalGenerator_Photovoltaic::
PVPerf_EquivOne_Diode_ModuleCurrentAtMaxPwr () const
{
return this->PVPerf_EquivOne_Diode_ModuleCurrentAtMaxPwr_;
}
SimFlowPlant_ElectricalGenerator_Photovoltaic::PVPerf_EquivOne_Diode_ModuleCurrentAtMaxPwr_optional& SimFlowPlant_ElectricalGenerator_Photovoltaic::
PVPerf_EquivOne_Diode_ModuleCurrentAtMaxPwr ()
{
return this->PVPerf_EquivOne_Diode_ModuleCurrentAtMaxPwr_;
}
void SimFlowPlant_ElectricalGenerator_Photovoltaic::
PVPerf_EquivOne_Diode_ModuleCurrentAtMaxPwr (const PVPerf_EquivOne_Diode_ModuleCurrentAtMaxPwr_type& x)
{
this->PVPerf_EquivOne_Diode_ModuleCurrentAtMaxPwr_.set (x);
}
void SimFlowPlant_ElectricalGenerator_Photovoltaic::
PVPerf_EquivOne_Diode_ModuleCurrentAtMaxPwr (const PVPerf_EquivOne_Diode_ModuleCurrentAtMaxPwr_optional& x)
{
this->PVPerf_EquivOne_Diode_ModuleCurrentAtMaxPwr_ = x;
}
const SimFlowPlant_ElectricalGenerator_Photovoltaic::PVPerf_EquivOne_Diode_ModuleVoltAtMaxPwr_optional& SimFlowPlant_ElectricalGenerator_Photovoltaic::
PVPerf_EquivOne_Diode_ModuleVoltAtMaxPwr () const
{
return this->PVPerf_EquivOne_Diode_ModuleVoltAtMaxPwr_;
}
SimFlowPlant_ElectricalGenerator_Photovoltaic::PVPerf_EquivOne_Diode_ModuleVoltAtMaxPwr_optional& SimFlowPlant_ElectricalGenerator_Photovoltaic::
PVPerf_EquivOne_Diode_ModuleVoltAtMaxPwr ()
{
return this->PVPerf_EquivOne_Diode_ModuleVoltAtMaxPwr_;
}
void SimFlowPlant_ElectricalGenerator_Photovoltaic::
PVPerf_EquivOne_Diode_ModuleVoltAtMaxPwr (const PVPerf_EquivOne_Diode_ModuleVoltAtMaxPwr_type& x)
{
this->PVPerf_EquivOne_Diode_ModuleVoltAtMaxPwr_.set (x);
}
void SimFlowPlant_ElectricalGenerator_Photovoltaic::
PVPerf_EquivOne_Diode_ModuleVoltAtMaxPwr (const PVPerf_EquivOne_Diode_ModuleVoltAtMaxPwr_optional& x)
{
this->PVPerf_EquivOne_Diode_ModuleVoltAtMaxPwr_ = x;
}
const SimFlowPlant_ElectricalGenerator_Photovoltaic::PVPerf_EquivOne_Diode_TempCoefShortCircuitCurrent_optional& SimFlowPlant_ElectricalGenerator_Photovoltaic::
PVPerf_EquivOne_Diode_TempCoefShortCircuitCurrent () const
{
return this->PVPerf_EquivOne_Diode_TempCoefShortCircuitCurrent_;
}
SimFlowPlant_ElectricalGenerator_Photovoltaic::PVPerf_EquivOne_Diode_TempCoefShortCircuitCurrent_optional& SimFlowPlant_ElectricalGenerator_Photovoltaic::
PVPerf_EquivOne_Diode_TempCoefShortCircuitCurrent ()
{
return this->PVPerf_EquivOne_Diode_TempCoefShortCircuitCurrent_;
}
void SimFlowPlant_ElectricalGenerator_Photovoltaic::
PVPerf_EquivOne_Diode_TempCoefShortCircuitCurrent (const PVPerf_EquivOne_Diode_TempCoefShortCircuitCurrent_type& x)
{
this->PVPerf_EquivOne_Diode_TempCoefShortCircuitCurrent_.set (x);
}
void SimFlowPlant_ElectricalGenerator_Photovoltaic::
PVPerf_EquivOne_Diode_TempCoefShortCircuitCurrent (const PVPerf_EquivOne_Diode_TempCoefShortCircuitCurrent_optional& x)
{
this->PVPerf_EquivOne_Diode_TempCoefShortCircuitCurrent_ = x;
}
const SimFlowPlant_ElectricalGenerator_Photovoltaic::PVPerf_EquivOne_Diode_TempCoefOpenCircuitVolt_optional& SimFlowPlant_ElectricalGenerator_Photovoltaic::
PVPerf_EquivOne_Diode_TempCoefOpenCircuitVolt () const
{
return this->PVPerf_EquivOne_Diode_TempCoefOpenCircuitVolt_;
}
SimFlowPlant_ElectricalGenerator_Photovoltaic::PVPerf_EquivOne_Diode_TempCoefOpenCircuitVolt_optional& SimFlowPlant_ElectricalGenerator_Photovoltaic::
PVPerf_EquivOne_Diode_TempCoefOpenCircuitVolt ()
{
return this->PVPerf_EquivOne_Diode_TempCoefOpenCircuitVolt_;
}
void SimFlowPlant_ElectricalGenerator_Photovoltaic::
PVPerf_EquivOne_Diode_TempCoefOpenCircuitVolt (const PVPerf_EquivOne_Diode_TempCoefOpenCircuitVolt_type& x)
{
this->PVPerf_EquivOne_Diode_TempCoefOpenCircuitVolt_.set (x);
}
void SimFlowPlant_ElectricalGenerator_Photovoltaic::
PVPerf_EquivOne_Diode_TempCoefOpenCircuitVolt (const PVPerf_EquivOne_Diode_TempCoefOpenCircuitVolt_optional& x)
{
this->PVPerf_EquivOne_Diode_TempCoefOpenCircuitVolt_ = x;
}
const SimFlowPlant_ElectricalGenerator_Photovoltaic::PVPerf_EquivOne_Diode_NomOperatCellTempTestAmbTemp_optional& SimFlowPlant_ElectricalGenerator_Photovoltaic::
PVPerf_EquivOne_Diode_NomOperatCellTempTestAmbTemp () const
{
return this->PVPerf_EquivOne_Diode_NomOperatCellTempTestAmbTemp_;
}
SimFlowPlant_ElectricalGenerator_Photovoltaic::PVPerf_EquivOne_Diode_NomOperatCellTempTestAmbTemp_optional& SimFlowPlant_ElectricalGenerator_Photovoltaic::
PVPerf_EquivOne_Diode_NomOperatCellTempTestAmbTemp ()
{
return this->PVPerf_EquivOne_Diode_NomOperatCellTempTestAmbTemp_;
}
void SimFlowPlant_ElectricalGenerator_Photovoltaic::
PVPerf_EquivOne_Diode_NomOperatCellTempTestAmbTemp (const PVPerf_EquivOne_Diode_NomOperatCellTempTestAmbTemp_type& x)
{
this->PVPerf_EquivOne_Diode_NomOperatCellTempTestAmbTemp_.set (x);
}
void SimFlowPlant_ElectricalGenerator_Photovoltaic::
PVPerf_EquivOne_Diode_NomOperatCellTempTestAmbTemp (const PVPerf_EquivOne_Diode_NomOperatCellTempTestAmbTemp_optional& x)
{
this->PVPerf_EquivOne_Diode_NomOperatCellTempTestAmbTemp_ = x;
}
const SimFlowPlant_ElectricalGenerator_Photovoltaic::PVPerf_EquivOne_Diode_NomOperatCellTempTestCellTemp_optional& SimFlowPlant_ElectricalGenerator_Photovoltaic::
PVPerf_EquivOne_Diode_NomOperatCellTempTestCellTemp () const
{
return this->PVPerf_EquivOne_Diode_NomOperatCellTempTestCellTemp_;
}
SimFlowPlant_ElectricalGenerator_Photovoltaic::PVPerf_EquivOne_Diode_NomOperatCellTempTestCellTemp_optional& SimFlowPlant_ElectricalGenerator_Photovoltaic::
PVPerf_EquivOne_Diode_NomOperatCellTempTestCellTemp ()
{
return this->PVPerf_EquivOne_Diode_NomOperatCellTempTestCellTemp_;
}
void SimFlowPlant_ElectricalGenerator_Photovoltaic::
PVPerf_EquivOne_Diode_NomOperatCellTempTestCellTemp (const PVPerf_EquivOne_Diode_NomOperatCellTempTestCellTemp_type& x)
{
this->PVPerf_EquivOne_Diode_NomOperatCellTempTestCellTemp_.set (x);
}
void SimFlowPlant_ElectricalGenerator_Photovoltaic::
PVPerf_EquivOne_Diode_NomOperatCellTempTestCellTemp (const PVPerf_EquivOne_Diode_NomOperatCellTempTestCellTemp_optional& x)
{
this->PVPerf_EquivOne_Diode_NomOperatCellTempTestCellTemp_ = x;
}
const SimFlowPlant_ElectricalGenerator_Photovoltaic::PVPerf_EquivOne_Diode_NomOperatCellTempTestInsol_optional& SimFlowPlant_ElectricalGenerator_Photovoltaic::
PVPerf_EquivOne_Diode_NomOperatCellTempTestInsol () const
{
return this->PVPerf_EquivOne_Diode_NomOperatCellTempTestInsol_;
}
SimFlowPlant_ElectricalGenerator_Photovoltaic::PVPerf_EquivOne_Diode_NomOperatCellTempTestInsol_optional& SimFlowPlant_ElectricalGenerator_Photovoltaic::
PVPerf_EquivOne_Diode_NomOperatCellTempTestInsol ()
{
return this->PVPerf_EquivOne_Diode_NomOperatCellTempTestInsol_;
}
void SimFlowPlant_ElectricalGenerator_Photovoltaic::
PVPerf_EquivOne_Diode_NomOperatCellTempTestInsol (const PVPerf_EquivOne_Diode_NomOperatCellTempTestInsol_type& x)
{
this->PVPerf_EquivOne_Diode_NomOperatCellTempTestInsol_.set (x);
}
void SimFlowPlant_ElectricalGenerator_Photovoltaic::
PVPerf_EquivOne_Diode_NomOperatCellTempTestInsol (const PVPerf_EquivOne_Diode_NomOperatCellTempTestInsol_optional& x)
{
this->PVPerf_EquivOne_Diode_NomOperatCellTempTestInsol_ = x;
}
const SimFlowPlant_ElectricalGenerator_Photovoltaic::PVPerf_EquivOne_Diode_ModuleHeatLossCoef_optional& SimFlowPlant_ElectricalGenerator_Photovoltaic::
PVPerf_EquivOne_Diode_ModuleHeatLossCoef () const
{
return this->PVPerf_EquivOne_Diode_ModuleHeatLossCoef_;
}
SimFlowPlant_ElectricalGenerator_Photovoltaic::PVPerf_EquivOne_Diode_ModuleHeatLossCoef_optional& SimFlowPlant_ElectricalGenerator_Photovoltaic::
PVPerf_EquivOne_Diode_ModuleHeatLossCoef ()
{
return this->PVPerf_EquivOne_Diode_ModuleHeatLossCoef_;
}
void SimFlowPlant_ElectricalGenerator_Photovoltaic::
PVPerf_EquivOne_Diode_ModuleHeatLossCoef (const PVPerf_EquivOne_Diode_ModuleHeatLossCoef_type& x)
{
this->PVPerf_EquivOne_Diode_ModuleHeatLossCoef_.set (x);
}
void SimFlowPlant_ElectricalGenerator_Photovoltaic::
PVPerf_EquivOne_Diode_ModuleHeatLossCoef (const PVPerf_EquivOne_Diode_ModuleHeatLossCoef_optional& x)
{
this->PVPerf_EquivOne_Diode_ModuleHeatLossCoef_ = x;
}
const SimFlowPlant_ElectricalGenerator_Photovoltaic::PVPerf_EquivOne_Diode_TotalHeatCap_optional& SimFlowPlant_ElectricalGenerator_Photovoltaic::
PVPerf_EquivOne_Diode_TotalHeatCap () const
{
return this->PVPerf_EquivOne_Diode_TotalHeatCap_;
}
SimFlowPlant_ElectricalGenerator_Photovoltaic::PVPerf_EquivOne_Diode_TotalHeatCap_optional& SimFlowPlant_ElectricalGenerator_Photovoltaic::
PVPerf_EquivOne_Diode_TotalHeatCap ()
{
return this->PVPerf_EquivOne_Diode_TotalHeatCap_;
}
void SimFlowPlant_ElectricalGenerator_Photovoltaic::
PVPerf_EquivOne_Diode_TotalHeatCap (const PVPerf_EquivOne_Diode_TotalHeatCap_type& x)
{
this->PVPerf_EquivOne_Diode_TotalHeatCap_.set (x);
}
void SimFlowPlant_ElectricalGenerator_Photovoltaic::
PVPerf_EquivOne_Diode_TotalHeatCap (const PVPerf_EquivOne_Diode_TotalHeatCap_optional& x)
{
this->PVPerf_EquivOne_Diode_TotalHeatCap_ = x;
}
const SimFlowPlant_ElectricalGenerator_Photovoltaic::PVPerf_Sandia_Name_optional& SimFlowPlant_ElectricalGenerator_Photovoltaic::
PVPerf_Sandia_Name () const
{
return this->PVPerf_Sandia_Name_;
}
SimFlowPlant_ElectricalGenerator_Photovoltaic::PVPerf_Sandia_Name_optional& SimFlowPlant_ElectricalGenerator_Photovoltaic::
PVPerf_Sandia_Name ()
{
return this->PVPerf_Sandia_Name_;
}
void SimFlowPlant_ElectricalGenerator_Photovoltaic::
PVPerf_Sandia_Name (const PVPerf_Sandia_Name_type& x)
{
this->PVPerf_Sandia_Name_.set (x);
}
void SimFlowPlant_ElectricalGenerator_Photovoltaic::
PVPerf_Sandia_Name (const PVPerf_Sandia_Name_optional& x)
{
this->PVPerf_Sandia_Name_ = x;
}
void SimFlowPlant_ElectricalGenerator_Photovoltaic::
PVPerf_Sandia_Name (::std::auto_ptr< PVPerf_Sandia_Name_type > x)
{
this->PVPerf_Sandia_Name_.set (x);
}
const SimFlowPlant_ElectricalGenerator_Photovoltaic::PVPerf_Sandia_ActiveArea_optional& SimFlowPlant_ElectricalGenerator_Photovoltaic::
PVPerf_Sandia_ActiveArea () const
{
return this->PVPerf_Sandia_ActiveArea_;
}
SimFlowPlant_ElectricalGenerator_Photovoltaic::PVPerf_Sandia_ActiveArea_optional& SimFlowPlant_ElectricalGenerator_Photovoltaic::
PVPerf_Sandia_ActiveArea ()
{
return this->PVPerf_Sandia_ActiveArea_;
}
void SimFlowPlant_ElectricalGenerator_Photovoltaic::
PVPerf_Sandia_ActiveArea (const PVPerf_Sandia_ActiveArea_type& x)
{
this->PVPerf_Sandia_ActiveArea_.set (x);
}
void SimFlowPlant_ElectricalGenerator_Photovoltaic::
PVPerf_Sandia_ActiveArea (const PVPerf_Sandia_ActiveArea_optional& x)
{
this->PVPerf_Sandia_ActiveArea_ = x;
}
const SimFlowPlant_ElectricalGenerator_Photovoltaic::PVPerf_Sandia_NumCellsSeries_optional& SimFlowPlant_ElectricalGenerator_Photovoltaic::
PVPerf_Sandia_NumCellsSeries () const
{
return this->PVPerf_Sandia_NumCellsSeries_;
}
SimFlowPlant_ElectricalGenerator_Photovoltaic::PVPerf_Sandia_NumCellsSeries_optional& SimFlowPlant_ElectricalGenerator_Photovoltaic::
PVPerf_Sandia_NumCellsSeries ()
{
return this->PVPerf_Sandia_NumCellsSeries_;
}
void SimFlowPlant_ElectricalGenerator_Photovoltaic::
PVPerf_Sandia_NumCellsSeries (const PVPerf_Sandia_NumCellsSeries_type& x)
{
this->PVPerf_Sandia_NumCellsSeries_.set (x);
}
void SimFlowPlant_ElectricalGenerator_Photovoltaic::
PVPerf_Sandia_NumCellsSeries (const PVPerf_Sandia_NumCellsSeries_optional& x)
{
this->PVPerf_Sandia_NumCellsSeries_ = x;
}
const SimFlowPlant_ElectricalGenerator_Photovoltaic::PVPerf_Sandia_NumCellsParallel_optional& SimFlowPlant_ElectricalGenerator_Photovoltaic::
PVPerf_Sandia_NumCellsParallel () const
{
return this->PVPerf_Sandia_NumCellsParallel_;
}
SimFlowPlant_ElectricalGenerator_Photovoltaic::PVPerf_Sandia_NumCellsParallel_optional& SimFlowPlant_ElectricalGenerator_Photovoltaic::
PVPerf_Sandia_NumCellsParallel ()
{
return this->PVPerf_Sandia_NumCellsParallel_;
}
void SimFlowPlant_ElectricalGenerator_Photovoltaic::
PVPerf_Sandia_NumCellsParallel (const PVPerf_Sandia_NumCellsParallel_type& x)
{
this->PVPerf_Sandia_NumCellsParallel_.set (x);
}
void SimFlowPlant_ElectricalGenerator_Photovoltaic::
PVPerf_Sandia_NumCellsParallel (const PVPerf_Sandia_NumCellsParallel_optional& x)
{
this->PVPerf_Sandia_NumCellsParallel_ = x;
}
const SimFlowPlant_ElectricalGenerator_Photovoltaic::PVPerf_Sandia_ShortCircuitCurrent_optional& SimFlowPlant_ElectricalGenerator_Photovoltaic::
PVPerf_Sandia_ShortCircuitCurrent () const
{
return this->PVPerf_Sandia_ShortCircuitCurrent_;
}
SimFlowPlant_ElectricalGenerator_Photovoltaic::PVPerf_Sandia_ShortCircuitCurrent_optional& SimFlowPlant_ElectricalGenerator_Photovoltaic::
PVPerf_Sandia_ShortCircuitCurrent ()
{
return this->PVPerf_Sandia_ShortCircuitCurrent_;
}
void SimFlowPlant_ElectricalGenerator_Photovoltaic::
PVPerf_Sandia_ShortCircuitCurrent (const PVPerf_Sandia_ShortCircuitCurrent_type& x)
{
this->PVPerf_Sandia_ShortCircuitCurrent_.set (x);
}
void SimFlowPlant_ElectricalGenerator_Photovoltaic::
PVPerf_Sandia_ShortCircuitCurrent (const PVPerf_Sandia_ShortCircuitCurrent_optional& x)
{
this->PVPerf_Sandia_ShortCircuitCurrent_ = x;
}
const SimFlowPlant_ElectricalGenerator_Photovoltaic::PVPerf_Sandia_OpenCircuitVolt_optional& SimFlowPlant_ElectricalGenerator_Photovoltaic::
PVPerf_Sandia_OpenCircuitVolt () const
{
return this->PVPerf_Sandia_OpenCircuitVolt_;
}
SimFlowPlant_ElectricalGenerator_Photovoltaic::PVPerf_Sandia_OpenCircuitVolt_optional& SimFlowPlant_ElectricalGenerator_Photovoltaic::
PVPerf_Sandia_OpenCircuitVolt ()
{
return this->PVPerf_Sandia_OpenCircuitVolt_;
}
void SimFlowPlant_ElectricalGenerator_Photovoltaic::
PVPerf_Sandia_OpenCircuitVolt (const PVPerf_Sandia_OpenCircuitVolt_type& x)
{
this->PVPerf_Sandia_OpenCircuitVolt_.set (x);
}
void SimFlowPlant_ElectricalGenerator_Photovoltaic::
PVPerf_Sandia_OpenCircuitVolt (const PVPerf_Sandia_OpenCircuitVolt_optional& x)
{
this->PVPerf_Sandia_OpenCircuitVolt_ = x;
}
const SimFlowPlant_ElectricalGenerator_Photovoltaic::PVPerf_Sandia_CurrentAtMaxPwrPoint_optional& SimFlowPlant_ElectricalGenerator_Photovoltaic::
PVPerf_Sandia_CurrentAtMaxPwrPoint () const
{
return this->PVPerf_Sandia_CurrentAtMaxPwrPoint_;
}
SimFlowPlant_ElectricalGenerator_Photovoltaic::PVPerf_Sandia_CurrentAtMaxPwrPoint_optional& SimFlowPlant_ElectricalGenerator_Photovoltaic::
PVPerf_Sandia_CurrentAtMaxPwrPoint ()
{
return this->PVPerf_Sandia_CurrentAtMaxPwrPoint_;
}
void SimFlowPlant_ElectricalGenerator_Photovoltaic::
PVPerf_Sandia_CurrentAtMaxPwrPoint (const PVPerf_Sandia_CurrentAtMaxPwrPoint_type& x)
{
this->PVPerf_Sandia_CurrentAtMaxPwrPoint_.set (x);
}
void SimFlowPlant_ElectricalGenerator_Photovoltaic::
PVPerf_Sandia_CurrentAtMaxPwrPoint (const PVPerf_Sandia_CurrentAtMaxPwrPoint_optional& x)
{
this->PVPerf_Sandia_CurrentAtMaxPwrPoint_ = x;
}
const SimFlowPlant_ElectricalGenerator_Photovoltaic::PVPerf_Sandia_VoltAtMaxPwrPoint_optional& SimFlowPlant_ElectricalGenerator_Photovoltaic::
PVPerf_Sandia_VoltAtMaxPwrPoint () const
{
return this->PVPerf_Sandia_VoltAtMaxPwrPoint_;
}
SimFlowPlant_ElectricalGenerator_Photovoltaic::PVPerf_Sandia_VoltAtMaxPwrPoint_optional& SimFlowPlant_ElectricalGenerator_Photovoltaic::
PVPerf_Sandia_VoltAtMaxPwrPoint ()
{
return this->PVPerf_Sandia_VoltAtMaxPwrPoint_;
}
void SimFlowPlant_ElectricalGenerator_Photovoltaic::
PVPerf_Sandia_VoltAtMaxPwrPoint (const PVPerf_Sandia_VoltAtMaxPwrPoint_type& x)
{
this->PVPerf_Sandia_VoltAtMaxPwrPoint_.set (x);
}
void SimFlowPlant_ElectricalGenerator_Photovoltaic::
PVPerf_Sandia_VoltAtMaxPwrPoint (const PVPerf_Sandia_VoltAtMaxPwrPoint_optional& x)
{
this->PVPerf_Sandia_VoltAtMaxPwrPoint_ = x;
}
const SimFlowPlant_ElectricalGenerator_Photovoltaic::PVPerf_Sandia_SandiaDbParamAc_optional& SimFlowPlant_ElectricalGenerator_Photovoltaic::
PVPerf_Sandia_SandiaDbParamAc () const
{
return this->PVPerf_Sandia_SandiaDbParamAc_;
}
SimFlowPlant_ElectricalGenerator_Photovoltaic::PVPerf_Sandia_SandiaDbParamAc_optional& SimFlowPlant_ElectricalGenerator_Photovoltaic::
PVPerf_Sandia_SandiaDbParamAc ()
{
return this->PVPerf_Sandia_SandiaDbParamAc_;
}
void SimFlowPlant_ElectricalGenerator_Photovoltaic::
PVPerf_Sandia_SandiaDbParamAc (const PVPerf_Sandia_SandiaDbParamAc_type& x)
{
this->PVPerf_Sandia_SandiaDbParamAc_.set (x);
}
void SimFlowPlant_ElectricalGenerator_Photovoltaic::
PVPerf_Sandia_SandiaDbParamAc (const PVPerf_Sandia_SandiaDbParamAc_optional& x)
{
this->PVPerf_Sandia_SandiaDbParamAc_ = x;
}
const SimFlowPlant_ElectricalGenerator_Photovoltaic::PVPerf_Sandia_SandiaDbParamAImp_optional& SimFlowPlant_ElectricalGenerator_Photovoltaic::
PVPerf_Sandia_SandiaDbParamAImp () const
{
return this->PVPerf_Sandia_SandiaDbParamAImp_;
}
SimFlowPlant_ElectricalGenerator_Photovoltaic::PVPerf_Sandia_SandiaDbParamAImp_optional& SimFlowPlant_ElectricalGenerator_Photovoltaic::
PVPerf_Sandia_SandiaDbParamAImp ()
{
return this->PVPerf_Sandia_SandiaDbParamAImp_;
}
void SimFlowPlant_ElectricalGenerator_Photovoltaic::
PVPerf_Sandia_SandiaDbParamAImp (const PVPerf_Sandia_SandiaDbParamAImp_type& x)
{
this->PVPerf_Sandia_SandiaDbParamAImp_.set (x);
}
void SimFlowPlant_ElectricalGenerator_Photovoltaic::
PVPerf_Sandia_SandiaDbParamAImp (const PVPerf_Sandia_SandiaDbParamAImp_optional& x)
{
this->PVPerf_Sandia_SandiaDbParamAImp_ = x;
}
const SimFlowPlant_ElectricalGenerator_Photovoltaic::PVPerf_Sandia_SandiaDBParamc0_optional& SimFlowPlant_ElectricalGenerator_Photovoltaic::
PVPerf_Sandia_SandiaDBParamc0 () const
{
return this->PVPerf_Sandia_SandiaDBParamc0_;
}
SimFlowPlant_ElectricalGenerator_Photovoltaic::PVPerf_Sandia_SandiaDBParamc0_optional& SimFlowPlant_ElectricalGenerator_Photovoltaic::
PVPerf_Sandia_SandiaDBParamc0 ()
{
return this->PVPerf_Sandia_SandiaDBParamc0_;
}
void SimFlowPlant_ElectricalGenerator_Photovoltaic::
PVPerf_Sandia_SandiaDBParamc0 (const PVPerf_Sandia_SandiaDBParamc0_type& x)
{
this->PVPerf_Sandia_SandiaDBParamc0_.set (x);
}
void SimFlowPlant_ElectricalGenerator_Photovoltaic::
PVPerf_Sandia_SandiaDBParamc0 (const PVPerf_Sandia_SandiaDBParamc0_optional& x)
{
this->PVPerf_Sandia_SandiaDBParamc0_ = x;
}
const SimFlowPlant_ElectricalGenerator_Photovoltaic::PVPerf_Sandia_SandiaDBParamc1_optional& SimFlowPlant_ElectricalGenerator_Photovoltaic::
PVPerf_Sandia_SandiaDBParamc1 () const
{
return this->PVPerf_Sandia_SandiaDBParamc1_;
}
SimFlowPlant_ElectricalGenerator_Photovoltaic::PVPerf_Sandia_SandiaDBParamc1_optional& SimFlowPlant_ElectricalGenerator_Photovoltaic::
PVPerf_Sandia_SandiaDBParamc1 ()
{
return this->PVPerf_Sandia_SandiaDBParamc1_;
}
void SimFlowPlant_ElectricalGenerator_Photovoltaic::
PVPerf_Sandia_SandiaDBParamc1 (const PVPerf_Sandia_SandiaDBParamc1_type& x)
{
this->PVPerf_Sandia_SandiaDBParamc1_.set (x);
}
void SimFlowPlant_ElectricalGenerator_Photovoltaic::
PVPerf_Sandia_SandiaDBParamc1 (const PVPerf_Sandia_SandiaDBParamc1_optional& x)
{
this->PVPerf_Sandia_SandiaDBParamc1_ = x;
}
const SimFlowPlant_ElectricalGenerator_Photovoltaic::PVPerf_Sandia_SandiaDbParamBVoc0_optional& SimFlowPlant_ElectricalGenerator_Photovoltaic::
PVPerf_Sandia_SandiaDbParamBVoc0 () const
{
return this->PVPerf_Sandia_SandiaDbParamBVoc0_;
}
SimFlowPlant_ElectricalGenerator_Photovoltaic::PVPerf_Sandia_SandiaDbParamBVoc0_optional& SimFlowPlant_ElectricalGenerator_Photovoltaic::
PVPerf_Sandia_SandiaDbParamBVoc0 ()
{
return this->PVPerf_Sandia_SandiaDbParamBVoc0_;
}
void SimFlowPlant_ElectricalGenerator_Photovoltaic::
PVPerf_Sandia_SandiaDbParamBVoc0 (const PVPerf_Sandia_SandiaDbParamBVoc0_type& x)
{
this->PVPerf_Sandia_SandiaDbParamBVoc0_.set (x);
}
void SimFlowPlant_ElectricalGenerator_Photovoltaic::
PVPerf_Sandia_SandiaDbParamBVoc0 (const PVPerf_Sandia_SandiaDbParamBVoc0_optional& x)
{
this->PVPerf_Sandia_SandiaDbParamBVoc0_ = x;
}
const SimFlowPlant_ElectricalGenerator_Photovoltaic::PVPerf_Sandia_SandiaDbParamMBVoc_optional& SimFlowPlant_ElectricalGenerator_Photovoltaic::
PVPerf_Sandia_SandiaDbParamMBVoc () const
{
return this->PVPerf_Sandia_SandiaDbParamMBVoc_;
}
SimFlowPlant_ElectricalGenerator_Photovoltaic::PVPerf_Sandia_SandiaDbParamMBVoc_optional& SimFlowPlant_ElectricalGenerator_Photovoltaic::
PVPerf_Sandia_SandiaDbParamMBVoc ()
{
return this->PVPerf_Sandia_SandiaDbParamMBVoc_;
}
void SimFlowPlant_ElectricalGenerator_Photovoltaic::
PVPerf_Sandia_SandiaDbParamMBVoc (const PVPerf_Sandia_SandiaDbParamMBVoc_type& x)
{
this->PVPerf_Sandia_SandiaDbParamMBVoc_.set (x);
}
void SimFlowPlant_ElectricalGenerator_Photovoltaic::
PVPerf_Sandia_SandiaDbParamMBVoc (const PVPerf_Sandia_SandiaDbParamMBVoc_optional& x)
{
this->PVPerf_Sandia_SandiaDbParamMBVoc_ = x;
}
const SimFlowPlant_ElectricalGenerator_Photovoltaic::PVPerf_Sandia_SandiaDbParamBVmp0_optional& SimFlowPlant_ElectricalGenerator_Photovoltaic::
PVPerf_Sandia_SandiaDbParamBVmp0 () const
{
return this->PVPerf_Sandia_SandiaDbParamBVmp0_;
}
SimFlowPlant_ElectricalGenerator_Photovoltaic::PVPerf_Sandia_SandiaDbParamBVmp0_optional& SimFlowPlant_ElectricalGenerator_Photovoltaic::
PVPerf_Sandia_SandiaDbParamBVmp0 ()
{
return this->PVPerf_Sandia_SandiaDbParamBVmp0_;
}
void SimFlowPlant_ElectricalGenerator_Photovoltaic::
PVPerf_Sandia_SandiaDbParamBVmp0 (const PVPerf_Sandia_SandiaDbParamBVmp0_type& x)
{
this->PVPerf_Sandia_SandiaDbParamBVmp0_.set (x);
}
void SimFlowPlant_ElectricalGenerator_Photovoltaic::
PVPerf_Sandia_SandiaDbParamBVmp0 (const PVPerf_Sandia_SandiaDbParamBVmp0_optional& x)
{
this->PVPerf_Sandia_SandiaDbParamBVmp0_ = x;
}
const SimFlowPlant_ElectricalGenerator_Photovoltaic::PVPerf_Sandia_SandiaDbParamMBVmp_optional& SimFlowPlant_ElectricalGenerator_Photovoltaic::
PVPerf_Sandia_SandiaDbParamMBVmp () const
{
return this->PVPerf_Sandia_SandiaDbParamMBVmp_;
}
SimFlowPlant_ElectricalGenerator_Photovoltaic::PVPerf_Sandia_SandiaDbParamMBVmp_optional& SimFlowPlant_ElectricalGenerator_Photovoltaic::
PVPerf_Sandia_SandiaDbParamMBVmp ()
{
return this->PVPerf_Sandia_SandiaDbParamMBVmp_;
}
void SimFlowPlant_ElectricalGenerator_Photovoltaic::
PVPerf_Sandia_SandiaDbParamMBVmp (const PVPerf_Sandia_SandiaDbParamMBVmp_type& x)
{
this->PVPerf_Sandia_SandiaDbParamMBVmp_.set (x);
}
void SimFlowPlant_ElectricalGenerator_Photovoltaic::
PVPerf_Sandia_SandiaDbParamMBVmp (const PVPerf_Sandia_SandiaDbParamMBVmp_optional& x)
{
this->PVPerf_Sandia_SandiaDbParamMBVmp_ = x;
}
const SimFlowPlant_ElectricalGenerator_Photovoltaic::PVPerf_Sandia_DiodeFactor_optional& SimFlowPlant_ElectricalGenerator_Photovoltaic::
PVPerf_Sandia_DiodeFactor () const
{
return this->PVPerf_Sandia_DiodeFactor_;
}
SimFlowPlant_ElectricalGenerator_Photovoltaic::PVPerf_Sandia_DiodeFactor_optional& SimFlowPlant_ElectricalGenerator_Photovoltaic::
PVPerf_Sandia_DiodeFactor ()
{
return this->PVPerf_Sandia_DiodeFactor_;
}
void SimFlowPlant_ElectricalGenerator_Photovoltaic::
PVPerf_Sandia_DiodeFactor (const PVPerf_Sandia_DiodeFactor_type& x)
{
this->PVPerf_Sandia_DiodeFactor_.set (x);
}
void SimFlowPlant_ElectricalGenerator_Photovoltaic::
PVPerf_Sandia_DiodeFactor (const PVPerf_Sandia_DiodeFactor_optional& x)
{
this->PVPerf_Sandia_DiodeFactor_ = x;
}
const SimFlowPlant_ElectricalGenerator_Photovoltaic::PVPerf_Sandia_SandiaDBParamc2_optional& SimFlowPlant_ElectricalGenerator_Photovoltaic::
PVPerf_Sandia_SandiaDBParamc2 () const
{
return this->PVPerf_Sandia_SandiaDBParamc2_;
}
SimFlowPlant_ElectricalGenerator_Photovoltaic::PVPerf_Sandia_SandiaDBParamc2_optional& SimFlowPlant_ElectricalGenerator_Photovoltaic::
PVPerf_Sandia_SandiaDBParamc2 ()
{
return this->PVPerf_Sandia_SandiaDBParamc2_;
}
void SimFlowPlant_ElectricalGenerator_Photovoltaic::
PVPerf_Sandia_SandiaDBParamc2 (const PVPerf_Sandia_SandiaDBParamc2_type& x)
{
this->PVPerf_Sandia_SandiaDBParamc2_.set (x);
}
void SimFlowPlant_ElectricalGenerator_Photovoltaic::
PVPerf_Sandia_SandiaDBParamc2 (const PVPerf_Sandia_SandiaDBParamc2_optional& x)
{
this->PVPerf_Sandia_SandiaDBParamc2_ = x;
}
const SimFlowPlant_ElectricalGenerator_Photovoltaic::PVPerf_Sandia_SandiaDBParamc3_optional& SimFlowPlant_ElectricalGenerator_Photovoltaic::
PVPerf_Sandia_SandiaDBParamc3 () const
{
return this->PVPerf_Sandia_SandiaDBParamc3_;
}
SimFlowPlant_ElectricalGenerator_Photovoltaic::PVPerf_Sandia_SandiaDBParamc3_optional& SimFlowPlant_ElectricalGenerator_Photovoltaic::
PVPerf_Sandia_SandiaDBParamc3 ()
{
return this->PVPerf_Sandia_SandiaDBParamc3_;
}
void SimFlowPlant_ElectricalGenerator_Photovoltaic::
PVPerf_Sandia_SandiaDBParamc3 (const PVPerf_Sandia_SandiaDBParamc3_type& x)
{
this->PVPerf_Sandia_SandiaDBParamc3_.set (x);
}
void SimFlowPlant_ElectricalGenerator_Photovoltaic::
PVPerf_Sandia_SandiaDBParamc3 (const PVPerf_Sandia_SandiaDBParamc3_optional& x)
{
this->PVPerf_Sandia_SandiaDBParamc3_ = x;
}
const SimFlowPlant_ElectricalGenerator_Photovoltaic::PVPerf_Sandia_SandiaDbParama_0_0_optional& SimFlowPlant_ElectricalGenerator_Photovoltaic::
PVPerf_Sandia_SandiaDbParama_0_0 () const
{
return this->PVPerf_Sandia_SandiaDbParama_0_0_;
}
SimFlowPlant_ElectricalGenerator_Photovoltaic::PVPerf_Sandia_SandiaDbParama_0_0_optional& SimFlowPlant_ElectricalGenerator_Photovoltaic::
PVPerf_Sandia_SandiaDbParama_0_0 ()
{
return this->PVPerf_Sandia_SandiaDbParama_0_0_;
}
void SimFlowPlant_ElectricalGenerator_Photovoltaic::
PVPerf_Sandia_SandiaDbParama_0_0 (const PVPerf_Sandia_SandiaDbParama_0_0_type& x)
{
this->PVPerf_Sandia_SandiaDbParama_0_0_.set (x);
}
void SimFlowPlant_ElectricalGenerator_Photovoltaic::
PVPerf_Sandia_SandiaDbParama_0_0 (const PVPerf_Sandia_SandiaDbParama_0_0_optional& x)
{
this->PVPerf_Sandia_SandiaDbParama_0_0_ = x;
}
void SimFlowPlant_ElectricalGenerator_Photovoltaic::
PVPerf_Sandia_SandiaDbParama_0_0 (::std::auto_ptr< PVPerf_Sandia_SandiaDbParama_0_0_type > x)
{
this->PVPerf_Sandia_SandiaDbParama_0_0_.set (x);
}
const SimFlowPlant_ElectricalGenerator_Photovoltaic::PVPerf_Sandia_SandiaDbParama_1_1_optional& SimFlowPlant_ElectricalGenerator_Photovoltaic::
PVPerf_Sandia_SandiaDbParama_1_1 () const
{
return this->PVPerf_Sandia_SandiaDbParama_1_1_;
}
SimFlowPlant_ElectricalGenerator_Photovoltaic::PVPerf_Sandia_SandiaDbParama_1_1_optional& SimFlowPlant_ElectricalGenerator_Photovoltaic::
PVPerf_Sandia_SandiaDbParama_1_1 ()
{
return this->PVPerf_Sandia_SandiaDbParama_1_1_;
}
void SimFlowPlant_ElectricalGenerator_Photovoltaic::
PVPerf_Sandia_SandiaDbParama_1_1 (const PVPerf_Sandia_SandiaDbParama_1_1_type& x)
{
this->PVPerf_Sandia_SandiaDbParama_1_1_.set (x);
}
void SimFlowPlant_ElectricalGenerator_Photovoltaic::
PVPerf_Sandia_SandiaDbParama_1_1 (const PVPerf_Sandia_SandiaDbParama_1_1_optional& x)
{
this->PVPerf_Sandia_SandiaDbParama_1_1_ = x;
}
void SimFlowPlant_ElectricalGenerator_Photovoltaic::
PVPerf_Sandia_SandiaDbParama_1_1 (::std::auto_ptr< PVPerf_Sandia_SandiaDbParama_1_1_type > x)
{
this->PVPerf_Sandia_SandiaDbParama_1_1_.set (x);
}
const SimFlowPlant_ElectricalGenerator_Photovoltaic::PVPerf_Sandia_SandiaDBParama2_optional& SimFlowPlant_ElectricalGenerator_Photovoltaic::
PVPerf_Sandia_SandiaDBParama2 () const
{
return this->PVPerf_Sandia_SandiaDBParama2_;
}
SimFlowPlant_ElectricalGenerator_Photovoltaic::PVPerf_Sandia_SandiaDBParama2_optional& SimFlowPlant_ElectricalGenerator_Photovoltaic::
PVPerf_Sandia_SandiaDBParama2 ()
{
return this->PVPerf_Sandia_SandiaDBParama2_;
}
void SimFlowPlant_ElectricalGenerator_Photovoltaic::
PVPerf_Sandia_SandiaDBParama2 (const PVPerf_Sandia_SandiaDBParama2_type& x)
{
this->PVPerf_Sandia_SandiaDBParama2_.set (x);
}
void SimFlowPlant_ElectricalGenerator_Photovoltaic::
PVPerf_Sandia_SandiaDBParama2 (const PVPerf_Sandia_SandiaDBParama2_optional& x)
{
this->PVPerf_Sandia_SandiaDBParama2_ = x;
}
const SimFlowPlant_ElectricalGenerator_Photovoltaic::PVPerf_Sandia_SandiaDBParama3_optional& SimFlowPlant_ElectricalGenerator_Photovoltaic::
PVPerf_Sandia_SandiaDBParama3 () const
{
return this->PVPerf_Sandia_SandiaDBParama3_;
}
SimFlowPlant_ElectricalGenerator_Photovoltaic::PVPerf_Sandia_SandiaDBParama3_optional& SimFlowPlant_ElectricalGenerator_Photovoltaic::
PVPerf_Sandia_SandiaDBParama3 ()
{
return this->PVPerf_Sandia_SandiaDBParama3_;
}
void SimFlowPlant_ElectricalGenerator_Photovoltaic::
PVPerf_Sandia_SandiaDBParama3 (const PVPerf_Sandia_SandiaDBParama3_type& x)
{
this->PVPerf_Sandia_SandiaDBParama3_.set (x);
}
void SimFlowPlant_ElectricalGenerator_Photovoltaic::
PVPerf_Sandia_SandiaDBParama3 (const PVPerf_Sandia_SandiaDBParama3_optional& x)
{
this->PVPerf_Sandia_SandiaDBParama3_ = x;
}
const SimFlowPlant_ElectricalGenerator_Photovoltaic::PVPerf_Sandia_SandiaDBParama4_optional& SimFlowPlant_ElectricalGenerator_Photovoltaic::
PVPerf_Sandia_SandiaDBParama4 () const
{
return this->PVPerf_Sandia_SandiaDBParama4_;
}
SimFlowPlant_ElectricalGenerator_Photovoltaic::PVPerf_Sandia_SandiaDBParama4_optional& SimFlowPlant_ElectricalGenerator_Photovoltaic::
PVPerf_Sandia_SandiaDBParama4 ()
{
return this->PVPerf_Sandia_SandiaDBParama4_;
}
void SimFlowPlant_ElectricalGenerator_Photovoltaic::
PVPerf_Sandia_SandiaDBParama4 (const PVPerf_Sandia_SandiaDBParama4_type& x)
{
this->PVPerf_Sandia_SandiaDBParama4_.set (x);
}
void SimFlowPlant_ElectricalGenerator_Photovoltaic::
PVPerf_Sandia_SandiaDBParama4 (const PVPerf_Sandia_SandiaDBParama4_optional& x)
{
this->PVPerf_Sandia_SandiaDBParama4_ = x;
}
const SimFlowPlant_ElectricalGenerator_Photovoltaic::PVPerf_Sandia_SandiaDbParamb_0_0_optional& SimFlowPlant_ElectricalGenerator_Photovoltaic::
PVPerf_Sandia_SandiaDbParamb_0_0 () const
{
return this->PVPerf_Sandia_SandiaDbParamb_0_0_;
}
SimFlowPlant_ElectricalGenerator_Photovoltaic::PVPerf_Sandia_SandiaDbParamb_0_0_optional& SimFlowPlant_ElectricalGenerator_Photovoltaic::
PVPerf_Sandia_SandiaDbParamb_0_0 ()
{
return this->PVPerf_Sandia_SandiaDbParamb_0_0_;
}
void SimFlowPlant_ElectricalGenerator_Photovoltaic::
PVPerf_Sandia_SandiaDbParamb_0_0 (const PVPerf_Sandia_SandiaDbParamb_0_0_type& x)
{
this->PVPerf_Sandia_SandiaDbParamb_0_0_.set (x);
}
void SimFlowPlant_ElectricalGenerator_Photovoltaic::
PVPerf_Sandia_SandiaDbParamb_0_0 (const PVPerf_Sandia_SandiaDbParamb_0_0_optional& x)
{
this->PVPerf_Sandia_SandiaDbParamb_0_0_ = x;
}
void SimFlowPlant_ElectricalGenerator_Photovoltaic::
PVPerf_Sandia_SandiaDbParamb_0_0 (::std::auto_ptr< PVPerf_Sandia_SandiaDbParamb_0_0_type > x)
{
this->PVPerf_Sandia_SandiaDbParamb_0_0_.set (x);
}
const SimFlowPlant_ElectricalGenerator_Photovoltaic::PVPerf_Sandia_SandiaDbParamb_1_1_optional& SimFlowPlant_ElectricalGenerator_Photovoltaic::
PVPerf_Sandia_SandiaDbParamb_1_1 () const
{
return this->PVPerf_Sandia_SandiaDbParamb_1_1_;
}
SimFlowPlant_ElectricalGenerator_Photovoltaic::PVPerf_Sandia_SandiaDbParamb_1_1_optional& SimFlowPlant_ElectricalGenerator_Photovoltaic::
PVPerf_Sandia_SandiaDbParamb_1_1 ()
{
return this->PVPerf_Sandia_SandiaDbParamb_1_1_;
}
void SimFlowPlant_ElectricalGenerator_Photovoltaic::
PVPerf_Sandia_SandiaDbParamb_1_1 (const PVPerf_Sandia_SandiaDbParamb_1_1_type& x)
{
this->PVPerf_Sandia_SandiaDbParamb_1_1_.set (x);
}
void SimFlowPlant_ElectricalGenerator_Photovoltaic::
PVPerf_Sandia_SandiaDbParamb_1_1 (const PVPerf_Sandia_SandiaDbParamb_1_1_optional& x)
{
this->PVPerf_Sandia_SandiaDbParamb_1_1_ = x;
}
void SimFlowPlant_ElectricalGenerator_Photovoltaic::
PVPerf_Sandia_SandiaDbParamb_1_1 (::std::auto_ptr< PVPerf_Sandia_SandiaDbParamb_1_1_type > x)
{
this->PVPerf_Sandia_SandiaDbParamb_1_1_.set (x);
}
const SimFlowPlant_ElectricalGenerator_Photovoltaic::PVPerf_Sandia_SandiaDBParamb2_optional& SimFlowPlant_ElectricalGenerator_Photovoltaic::
PVPerf_Sandia_SandiaDBParamb2 () const
{
return this->PVPerf_Sandia_SandiaDBParamb2_;
}
SimFlowPlant_ElectricalGenerator_Photovoltaic::PVPerf_Sandia_SandiaDBParamb2_optional& SimFlowPlant_ElectricalGenerator_Photovoltaic::
PVPerf_Sandia_SandiaDBParamb2 ()
{
return this->PVPerf_Sandia_SandiaDBParamb2_;
}
void SimFlowPlant_ElectricalGenerator_Photovoltaic::
PVPerf_Sandia_SandiaDBParamb2 (const PVPerf_Sandia_SandiaDBParamb2_type& x)
{
this->PVPerf_Sandia_SandiaDBParamb2_.set (x);
}
void SimFlowPlant_ElectricalGenerator_Photovoltaic::
PVPerf_Sandia_SandiaDBParamb2 (const PVPerf_Sandia_SandiaDBParamb2_optional& x)
{
this->PVPerf_Sandia_SandiaDBParamb2_ = x;
}
const SimFlowPlant_ElectricalGenerator_Photovoltaic::PVPerf_Sandia_SandiaDBParamb3_optional& SimFlowPlant_ElectricalGenerator_Photovoltaic::
PVPerf_Sandia_SandiaDBParamb3 () const
{
return this->PVPerf_Sandia_SandiaDBParamb3_;
}
SimFlowPlant_ElectricalGenerator_Photovoltaic::PVPerf_Sandia_SandiaDBParamb3_optional& SimFlowPlant_ElectricalGenerator_Photovoltaic::
PVPerf_Sandia_SandiaDBParamb3 ()
{
return this->PVPerf_Sandia_SandiaDBParamb3_;
}
void SimFlowPlant_ElectricalGenerator_Photovoltaic::
PVPerf_Sandia_SandiaDBParamb3 (const PVPerf_Sandia_SandiaDBParamb3_type& x)
{
this->PVPerf_Sandia_SandiaDBParamb3_.set (x);
}
void SimFlowPlant_ElectricalGenerator_Photovoltaic::
PVPerf_Sandia_SandiaDBParamb3 (const PVPerf_Sandia_SandiaDBParamb3_optional& x)
{
this->PVPerf_Sandia_SandiaDBParamb3_ = x;
}
const SimFlowPlant_ElectricalGenerator_Photovoltaic::PVPerf_Sandia_SandiaDBParamb4_optional& SimFlowPlant_ElectricalGenerator_Photovoltaic::
PVPerf_Sandia_SandiaDBParamb4 () const
{
return this->PVPerf_Sandia_SandiaDBParamb4_;
}
SimFlowPlant_ElectricalGenerator_Photovoltaic::PVPerf_Sandia_SandiaDBParamb4_optional& SimFlowPlant_ElectricalGenerator_Photovoltaic::
PVPerf_Sandia_SandiaDBParamb4 ()
{
return this->PVPerf_Sandia_SandiaDBParamb4_;
}
void SimFlowPlant_ElectricalGenerator_Photovoltaic::
PVPerf_Sandia_SandiaDBParamb4 (const PVPerf_Sandia_SandiaDBParamb4_type& x)
{
this->PVPerf_Sandia_SandiaDBParamb4_.set (x);
}
void SimFlowPlant_ElectricalGenerator_Photovoltaic::
PVPerf_Sandia_SandiaDBParamb4 (const PVPerf_Sandia_SandiaDBParamb4_optional& x)
{
this->PVPerf_Sandia_SandiaDBParamb4_ = x;
}
const SimFlowPlant_ElectricalGenerator_Photovoltaic::PVPerf_Sandia_SandiaDBParamb5_optional& SimFlowPlant_ElectricalGenerator_Photovoltaic::
PVPerf_Sandia_SandiaDBParamb5 () const
{
return this->PVPerf_Sandia_SandiaDBParamb5_;
}
SimFlowPlant_ElectricalGenerator_Photovoltaic::PVPerf_Sandia_SandiaDBParamb5_optional& SimFlowPlant_ElectricalGenerator_Photovoltaic::
PVPerf_Sandia_SandiaDBParamb5 ()
{
return this->PVPerf_Sandia_SandiaDBParamb5_;
}
void SimFlowPlant_ElectricalGenerator_Photovoltaic::
PVPerf_Sandia_SandiaDBParamb5 (const PVPerf_Sandia_SandiaDBParamb5_type& x)
{
this->PVPerf_Sandia_SandiaDBParamb5_.set (x);
}
void SimFlowPlant_ElectricalGenerator_Photovoltaic::
PVPerf_Sandia_SandiaDBParamb5 (const PVPerf_Sandia_SandiaDBParamb5_optional& x)
{
this->PVPerf_Sandia_SandiaDBParamb5_ = x;
}
const SimFlowPlant_ElectricalGenerator_Photovoltaic::PVPerf_Sandia_SandiaDbParamDeltaTc_optional& SimFlowPlant_ElectricalGenerator_Photovoltaic::
PVPerf_Sandia_SandiaDbParamDeltaTc () const
{
return this->PVPerf_Sandia_SandiaDbParamDeltaTc_;
}
SimFlowPlant_ElectricalGenerator_Photovoltaic::PVPerf_Sandia_SandiaDbParamDeltaTc_optional& SimFlowPlant_ElectricalGenerator_Photovoltaic::
PVPerf_Sandia_SandiaDbParamDeltaTc ()
{
return this->PVPerf_Sandia_SandiaDbParamDeltaTc_;
}
void SimFlowPlant_ElectricalGenerator_Photovoltaic::
PVPerf_Sandia_SandiaDbParamDeltaTc (const PVPerf_Sandia_SandiaDbParamDeltaTc_type& x)
{
this->PVPerf_Sandia_SandiaDbParamDeltaTc_.set (x);
}
void SimFlowPlant_ElectricalGenerator_Photovoltaic::
PVPerf_Sandia_SandiaDbParamDeltaTc (const PVPerf_Sandia_SandiaDbParamDeltaTc_optional& x)
{
this->PVPerf_Sandia_SandiaDbParamDeltaTc_ = x;
}
const SimFlowPlant_ElectricalGenerator_Photovoltaic::PVPerf_Sandia_SandiaDbParamFd_optional& SimFlowPlant_ElectricalGenerator_Photovoltaic::
PVPerf_Sandia_SandiaDbParamFd () const
{
return this->PVPerf_Sandia_SandiaDbParamFd_;
}
SimFlowPlant_ElectricalGenerator_Photovoltaic::PVPerf_Sandia_SandiaDbParamFd_optional& SimFlowPlant_ElectricalGenerator_Photovoltaic::
PVPerf_Sandia_SandiaDbParamFd ()
{
return this->PVPerf_Sandia_SandiaDbParamFd_;
}
void SimFlowPlant_ElectricalGenerator_Photovoltaic::
PVPerf_Sandia_SandiaDbParamFd (const PVPerf_Sandia_SandiaDbParamFd_type& x)
{
this->PVPerf_Sandia_SandiaDbParamFd_.set (x);
}
void SimFlowPlant_ElectricalGenerator_Photovoltaic::
PVPerf_Sandia_SandiaDbParamFd (const PVPerf_Sandia_SandiaDbParamFd_optional& x)
{
this->PVPerf_Sandia_SandiaDbParamFd_ = x;
}
const SimFlowPlant_ElectricalGenerator_Photovoltaic::PVPerf_Sandia_SandiaDbParamA_optional& SimFlowPlant_ElectricalGenerator_Photovoltaic::
PVPerf_Sandia_SandiaDbParamA () const
{
return this->PVPerf_Sandia_SandiaDbParamA_;
}
SimFlowPlant_ElectricalGenerator_Photovoltaic::PVPerf_Sandia_SandiaDbParamA_optional& SimFlowPlant_ElectricalGenerator_Photovoltaic::
PVPerf_Sandia_SandiaDbParamA ()
{
return this->PVPerf_Sandia_SandiaDbParamA_;
}
void SimFlowPlant_ElectricalGenerator_Photovoltaic::
PVPerf_Sandia_SandiaDbParamA (const PVPerf_Sandia_SandiaDbParamA_type& x)
{
this->PVPerf_Sandia_SandiaDbParamA_.set (x);
}
void SimFlowPlant_ElectricalGenerator_Photovoltaic::
PVPerf_Sandia_SandiaDbParamA (const PVPerf_Sandia_SandiaDbParamA_optional& x)
{
this->PVPerf_Sandia_SandiaDbParamA_ = x;
}
const SimFlowPlant_ElectricalGenerator_Photovoltaic::PVPerf_Sandia_SandiaDbParamB_optional& SimFlowPlant_ElectricalGenerator_Photovoltaic::
PVPerf_Sandia_SandiaDbParamB () const
{
return this->PVPerf_Sandia_SandiaDbParamB_;
}
SimFlowPlant_ElectricalGenerator_Photovoltaic::PVPerf_Sandia_SandiaDbParamB_optional& SimFlowPlant_ElectricalGenerator_Photovoltaic::
PVPerf_Sandia_SandiaDbParamB ()
{
return this->PVPerf_Sandia_SandiaDbParamB_;
}
void SimFlowPlant_ElectricalGenerator_Photovoltaic::
PVPerf_Sandia_SandiaDbParamB (const PVPerf_Sandia_SandiaDbParamB_type& x)
{
this->PVPerf_Sandia_SandiaDbParamB_.set (x);
}
void SimFlowPlant_ElectricalGenerator_Photovoltaic::
PVPerf_Sandia_SandiaDbParamB (const PVPerf_Sandia_SandiaDbParamB_optional& x)
{
this->PVPerf_Sandia_SandiaDbParamB_ = x;
}
const SimFlowPlant_ElectricalGenerator_Photovoltaic::PVPerf_Sandia_SandiaDBParamc4_optional& SimFlowPlant_ElectricalGenerator_Photovoltaic::
PVPerf_Sandia_SandiaDBParamc4 () const
{
return this->PVPerf_Sandia_SandiaDBParamc4_;
}
SimFlowPlant_ElectricalGenerator_Photovoltaic::PVPerf_Sandia_SandiaDBParamc4_optional& SimFlowPlant_ElectricalGenerator_Photovoltaic::
PVPerf_Sandia_SandiaDBParamc4 ()
{
return this->PVPerf_Sandia_SandiaDBParamc4_;
}
void SimFlowPlant_ElectricalGenerator_Photovoltaic::
PVPerf_Sandia_SandiaDBParamc4 (const PVPerf_Sandia_SandiaDBParamc4_type& x)
{
this->PVPerf_Sandia_SandiaDBParamc4_.set (x);
}
void SimFlowPlant_ElectricalGenerator_Photovoltaic::
PVPerf_Sandia_SandiaDBParamc4 (const PVPerf_Sandia_SandiaDBParamc4_optional& x)
{
this->PVPerf_Sandia_SandiaDBParamc4_ = x;
}
const SimFlowPlant_ElectricalGenerator_Photovoltaic::PVPerf_Sandia_SandiaDBParamc5_optional& SimFlowPlant_ElectricalGenerator_Photovoltaic::
PVPerf_Sandia_SandiaDBParamc5 () const
{
return this->PVPerf_Sandia_SandiaDBParamc5_;
}
SimFlowPlant_ElectricalGenerator_Photovoltaic::PVPerf_Sandia_SandiaDBParamc5_optional& SimFlowPlant_ElectricalGenerator_Photovoltaic::
PVPerf_Sandia_SandiaDBParamc5 ()
{
return this->PVPerf_Sandia_SandiaDBParamc5_;
}
void SimFlowPlant_ElectricalGenerator_Photovoltaic::
PVPerf_Sandia_SandiaDBParamc5 (const PVPerf_Sandia_SandiaDBParamc5_type& x)
{
this->PVPerf_Sandia_SandiaDBParamc5_.set (x);
}
void SimFlowPlant_ElectricalGenerator_Photovoltaic::
PVPerf_Sandia_SandiaDBParamc5 (const PVPerf_Sandia_SandiaDBParamc5_optional& x)
{
this->PVPerf_Sandia_SandiaDBParamc5_ = x;
}
const SimFlowPlant_ElectricalGenerator_Photovoltaic::PVPerf_Sandia_SandiaDbParamIx0_optional& SimFlowPlant_ElectricalGenerator_Photovoltaic::
PVPerf_Sandia_SandiaDbParamIx0 () const
{
return this->PVPerf_Sandia_SandiaDbParamIx0_;
}
SimFlowPlant_ElectricalGenerator_Photovoltaic::PVPerf_Sandia_SandiaDbParamIx0_optional& SimFlowPlant_ElectricalGenerator_Photovoltaic::
PVPerf_Sandia_SandiaDbParamIx0 ()
{
return this->PVPerf_Sandia_SandiaDbParamIx0_;
}
void SimFlowPlant_ElectricalGenerator_Photovoltaic::
PVPerf_Sandia_SandiaDbParamIx0 (const PVPerf_Sandia_SandiaDbParamIx0_type& x)
{
this->PVPerf_Sandia_SandiaDbParamIx0_.set (x);
}
void SimFlowPlant_ElectricalGenerator_Photovoltaic::
PVPerf_Sandia_SandiaDbParamIx0 (const PVPerf_Sandia_SandiaDbParamIx0_optional& x)
{
this->PVPerf_Sandia_SandiaDbParamIx0_ = x;
}
const SimFlowPlant_ElectricalGenerator_Photovoltaic::PVPerf_Sandia_SandiaDbParamIxx0_optional& SimFlowPlant_ElectricalGenerator_Photovoltaic::
PVPerf_Sandia_SandiaDbParamIxx0 () const
{
return this->PVPerf_Sandia_SandiaDbParamIxx0_;
}
SimFlowPlant_ElectricalGenerator_Photovoltaic::PVPerf_Sandia_SandiaDbParamIxx0_optional& SimFlowPlant_ElectricalGenerator_Photovoltaic::
PVPerf_Sandia_SandiaDbParamIxx0 ()
{
return this->PVPerf_Sandia_SandiaDbParamIxx0_;
}
void SimFlowPlant_ElectricalGenerator_Photovoltaic::
PVPerf_Sandia_SandiaDbParamIxx0 (const PVPerf_Sandia_SandiaDbParamIxx0_type& x)
{
this->PVPerf_Sandia_SandiaDbParamIxx0_.set (x);
}
void SimFlowPlant_ElectricalGenerator_Photovoltaic::
PVPerf_Sandia_SandiaDbParamIxx0 (const PVPerf_Sandia_SandiaDbParamIxx0_optional& x)
{
this->PVPerf_Sandia_SandiaDbParamIxx0_ = x;
}
const SimFlowPlant_ElectricalGenerator_Photovoltaic::PVPerf_Sandia_SandiaDBParamc6_optional& SimFlowPlant_ElectricalGenerator_Photovoltaic::
PVPerf_Sandia_SandiaDBParamc6 () const
{
return this->PVPerf_Sandia_SandiaDBParamc6_;
}
SimFlowPlant_ElectricalGenerator_Photovoltaic::PVPerf_Sandia_SandiaDBParamc6_optional& SimFlowPlant_ElectricalGenerator_Photovoltaic::
PVPerf_Sandia_SandiaDBParamc6 ()
{
return this->PVPerf_Sandia_SandiaDBParamc6_;
}
void SimFlowPlant_ElectricalGenerator_Photovoltaic::
PVPerf_Sandia_SandiaDBParamc6 (const PVPerf_Sandia_SandiaDBParamc6_type& x)
{
this->PVPerf_Sandia_SandiaDBParamc6_.set (x);
}
void SimFlowPlant_ElectricalGenerator_Photovoltaic::
PVPerf_Sandia_SandiaDBParamc6 (const PVPerf_Sandia_SandiaDBParamc6_optional& x)
{
this->PVPerf_Sandia_SandiaDBParamc6_ = x;
}
const SimFlowPlant_ElectricalGenerator_Photovoltaic::PVPerf_Sandia_SandiaDBParamc7_optional& SimFlowPlant_ElectricalGenerator_Photovoltaic::
PVPerf_Sandia_SandiaDBParamc7 () const
{
return this->PVPerf_Sandia_SandiaDBParamc7_;
}
SimFlowPlant_ElectricalGenerator_Photovoltaic::PVPerf_Sandia_SandiaDBParamc7_optional& SimFlowPlant_ElectricalGenerator_Photovoltaic::
PVPerf_Sandia_SandiaDBParamc7 ()
{
return this->PVPerf_Sandia_SandiaDBParamc7_;
}
void SimFlowPlant_ElectricalGenerator_Photovoltaic::
PVPerf_Sandia_SandiaDBParamc7 (const PVPerf_Sandia_SandiaDBParamc7_type& x)
{
this->PVPerf_Sandia_SandiaDBParamc7_.set (x);
}
void SimFlowPlant_ElectricalGenerator_Photovoltaic::
PVPerf_Sandia_SandiaDBParamc7 (const PVPerf_Sandia_SandiaDBParamc7_optional& x)
{
this->PVPerf_Sandia_SandiaDBParamc7_ = x;
}
}
}
}
#include <xsd/cxx/xml/dom/parsing-source.hxx>
#include <xsd/cxx/tree/type-factory-map.hxx>
namespace _xsd
{
static
const ::xsd::cxx::tree::type_factory_plate< 0, char >
type_factory_plate_init;
}
namespace schema
{
namespace simxml
{
namespace MepModel
{
// SimFlowPlant_ElectricalGenerator_Photovoltaic
//
SimFlowPlant_ElectricalGenerator_Photovoltaic::
SimFlowPlant_ElectricalGenerator_Photovoltaic ()
: ::schema::simxml::MepModel::SimFlowPlant_ElectricalGenerator (),
SimFlowPlant_Name_ (this),
SimFlowPlant_SurfName_ (this),
SimFlowPlant_PhotovoltaicPerfObjType_ (this),
SimFlowPlant_ModulePerfName_ (this),
SimFlowPlant_HeatTranstegrationMode_ (this),
SimFlowPlant_NumberofSeriesStringsinParallel_ (this),
SimFlowPlant_NumModulesSeries_ (this),
PhotovoltaicPerformance_Simple_Name_ (this),
PhotovoltaicPerformance_Simple_FractionOfSurfAreawithActiveSolarCells_ (this),
PhotovoltaicPerformance_Simple_ConversionEfficiencyInputMode_ (this),
PhotovoltaicPerformance_Simple_ValueforCellEfficiencyifFixed_ (this),
PhotovoltaicPerformance_Simple_EfficiencyScheduleName_ (this),
PVPerf_EquivOne_Diode_Name_ (this),
PVPerf_EquivOne_Diode_CellType_ (this),
PVPerf_EquivOne_Diode_NumCellsSeries_ (this),
PVPerf_EquivOne_Diode_ActiveArea_ (this),
PVPerf_EquivOne_Diode_TransAbsorptanceProduct_ (this),
PVPerf_EquivOne_Diode_SemiconductorBandgap_ (this),
PVPerf_EquivOne_Diode_ShuntResist_ (this),
PVPerf_EquivOne_Diode_ShortCircuitCurrent_ (this),
PVPerf_EquivOne_Diode_OpenCircuitVolt_ (this),
PVPerf_EquivOne_Diode_RefTemp_ (this),
PVPerf_EquivOne_Diode_RefInsol_ (this),
PVPerf_EquivOne_Diode_ModuleCurrentAtMaxPwr_ (this),
PVPerf_EquivOne_Diode_ModuleVoltAtMaxPwr_ (this),
PVPerf_EquivOne_Diode_TempCoefShortCircuitCurrent_ (this),
PVPerf_EquivOne_Diode_TempCoefOpenCircuitVolt_ (this),
PVPerf_EquivOne_Diode_NomOperatCellTempTestAmbTemp_ (this),
PVPerf_EquivOne_Diode_NomOperatCellTempTestCellTemp_ (this),
PVPerf_EquivOne_Diode_NomOperatCellTempTestInsol_ (this),
PVPerf_EquivOne_Diode_ModuleHeatLossCoef_ (this),
PVPerf_EquivOne_Diode_TotalHeatCap_ (this),
PVPerf_Sandia_Name_ (this),
PVPerf_Sandia_ActiveArea_ (this),
PVPerf_Sandia_NumCellsSeries_ (this),
PVPerf_Sandia_NumCellsParallel_ (this),
PVPerf_Sandia_ShortCircuitCurrent_ (this),
PVPerf_Sandia_OpenCircuitVolt_ (this),
PVPerf_Sandia_CurrentAtMaxPwrPoint_ (this),
PVPerf_Sandia_VoltAtMaxPwrPoint_ (this),
PVPerf_Sandia_SandiaDbParamAc_ (this),
PVPerf_Sandia_SandiaDbParamAImp_ (this),
PVPerf_Sandia_SandiaDBParamc0_ (this),
PVPerf_Sandia_SandiaDBParamc1_ (this),
PVPerf_Sandia_SandiaDbParamBVoc0_ (this),
PVPerf_Sandia_SandiaDbParamMBVoc_ (this),
PVPerf_Sandia_SandiaDbParamBVmp0_ (this),
PVPerf_Sandia_SandiaDbParamMBVmp_ (this),
PVPerf_Sandia_DiodeFactor_ (this),
PVPerf_Sandia_SandiaDBParamc2_ (this),
PVPerf_Sandia_SandiaDBParamc3_ (this),
PVPerf_Sandia_SandiaDbParama_0_0_ (this),
PVPerf_Sandia_SandiaDbParama_1_1_ (this),
PVPerf_Sandia_SandiaDBParama2_ (this),
PVPerf_Sandia_SandiaDBParama3_ (this),
PVPerf_Sandia_SandiaDBParama4_ (this),
PVPerf_Sandia_SandiaDbParamb_0_0_ (this),
PVPerf_Sandia_SandiaDbParamb_1_1_ (this),
PVPerf_Sandia_SandiaDBParamb2_ (this),
PVPerf_Sandia_SandiaDBParamb3_ (this),
PVPerf_Sandia_SandiaDBParamb4_ (this),
PVPerf_Sandia_SandiaDBParamb5_ (this),
PVPerf_Sandia_SandiaDbParamDeltaTc_ (this),
PVPerf_Sandia_SandiaDbParamFd_ (this),
PVPerf_Sandia_SandiaDbParamA_ (this),
PVPerf_Sandia_SandiaDbParamB_ (this),
PVPerf_Sandia_SandiaDBParamc4_ (this),
PVPerf_Sandia_SandiaDBParamc5_ (this),
PVPerf_Sandia_SandiaDbParamIx0_ (this),
PVPerf_Sandia_SandiaDbParamIxx0_ (this),
PVPerf_Sandia_SandiaDBParamc6_ (this),
PVPerf_Sandia_SandiaDBParamc7_ (this)
{
}
SimFlowPlant_ElectricalGenerator_Photovoltaic::
SimFlowPlant_ElectricalGenerator_Photovoltaic (const RefId_type& RefId)
: ::schema::simxml::MepModel::SimFlowPlant_ElectricalGenerator (RefId),
SimFlowPlant_Name_ (this),
SimFlowPlant_SurfName_ (this),
SimFlowPlant_PhotovoltaicPerfObjType_ (this),
SimFlowPlant_ModulePerfName_ (this),
SimFlowPlant_HeatTranstegrationMode_ (this),
SimFlowPlant_NumberofSeriesStringsinParallel_ (this),
SimFlowPlant_NumModulesSeries_ (this),
PhotovoltaicPerformance_Simple_Name_ (this),
PhotovoltaicPerformance_Simple_FractionOfSurfAreawithActiveSolarCells_ (this),
PhotovoltaicPerformance_Simple_ConversionEfficiencyInputMode_ (this),
PhotovoltaicPerformance_Simple_ValueforCellEfficiencyifFixed_ (this),
PhotovoltaicPerformance_Simple_EfficiencyScheduleName_ (this),
PVPerf_EquivOne_Diode_Name_ (this),
PVPerf_EquivOne_Diode_CellType_ (this),
PVPerf_EquivOne_Diode_NumCellsSeries_ (this),
PVPerf_EquivOne_Diode_ActiveArea_ (this),
PVPerf_EquivOne_Diode_TransAbsorptanceProduct_ (this),
PVPerf_EquivOne_Diode_SemiconductorBandgap_ (this),
PVPerf_EquivOne_Diode_ShuntResist_ (this),
PVPerf_EquivOne_Diode_ShortCircuitCurrent_ (this),
PVPerf_EquivOne_Diode_OpenCircuitVolt_ (this),
PVPerf_EquivOne_Diode_RefTemp_ (this),
PVPerf_EquivOne_Diode_RefInsol_ (this),
PVPerf_EquivOne_Diode_ModuleCurrentAtMaxPwr_ (this),
PVPerf_EquivOne_Diode_ModuleVoltAtMaxPwr_ (this),
PVPerf_EquivOne_Diode_TempCoefShortCircuitCurrent_ (this),
PVPerf_EquivOne_Diode_TempCoefOpenCircuitVolt_ (this),
PVPerf_EquivOne_Diode_NomOperatCellTempTestAmbTemp_ (this),
PVPerf_EquivOne_Diode_NomOperatCellTempTestCellTemp_ (this),
PVPerf_EquivOne_Diode_NomOperatCellTempTestInsol_ (this),
PVPerf_EquivOne_Diode_ModuleHeatLossCoef_ (this),
PVPerf_EquivOne_Diode_TotalHeatCap_ (this),
PVPerf_Sandia_Name_ (this),
PVPerf_Sandia_ActiveArea_ (this),
PVPerf_Sandia_NumCellsSeries_ (this),
PVPerf_Sandia_NumCellsParallel_ (this),
PVPerf_Sandia_ShortCircuitCurrent_ (this),
PVPerf_Sandia_OpenCircuitVolt_ (this),
PVPerf_Sandia_CurrentAtMaxPwrPoint_ (this),
PVPerf_Sandia_VoltAtMaxPwrPoint_ (this),
PVPerf_Sandia_SandiaDbParamAc_ (this),
PVPerf_Sandia_SandiaDbParamAImp_ (this),
PVPerf_Sandia_SandiaDBParamc0_ (this),
PVPerf_Sandia_SandiaDBParamc1_ (this),
PVPerf_Sandia_SandiaDbParamBVoc0_ (this),
PVPerf_Sandia_SandiaDbParamMBVoc_ (this),
PVPerf_Sandia_SandiaDbParamBVmp0_ (this),
PVPerf_Sandia_SandiaDbParamMBVmp_ (this),
PVPerf_Sandia_DiodeFactor_ (this),
PVPerf_Sandia_SandiaDBParamc2_ (this),
PVPerf_Sandia_SandiaDBParamc3_ (this),
PVPerf_Sandia_SandiaDbParama_0_0_ (this),
PVPerf_Sandia_SandiaDbParama_1_1_ (this),
PVPerf_Sandia_SandiaDBParama2_ (this),
PVPerf_Sandia_SandiaDBParama3_ (this),
PVPerf_Sandia_SandiaDBParama4_ (this),
PVPerf_Sandia_SandiaDbParamb_0_0_ (this),
PVPerf_Sandia_SandiaDbParamb_1_1_ (this),
PVPerf_Sandia_SandiaDBParamb2_ (this),
PVPerf_Sandia_SandiaDBParamb3_ (this),
PVPerf_Sandia_SandiaDBParamb4_ (this),
PVPerf_Sandia_SandiaDBParamb5_ (this),
PVPerf_Sandia_SandiaDbParamDeltaTc_ (this),
PVPerf_Sandia_SandiaDbParamFd_ (this),
PVPerf_Sandia_SandiaDbParamA_ (this),
PVPerf_Sandia_SandiaDbParamB_ (this),
PVPerf_Sandia_SandiaDBParamc4_ (this),
PVPerf_Sandia_SandiaDBParamc5_ (this),
PVPerf_Sandia_SandiaDbParamIx0_ (this),
PVPerf_Sandia_SandiaDbParamIxx0_ (this),
PVPerf_Sandia_SandiaDBParamc6_ (this),
PVPerf_Sandia_SandiaDBParamc7_ (this)
{
}
SimFlowPlant_ElectricalGenerator_Photovoltaic::
SimFlowPlant_ElectricalGenerator_Photovoltaic (const SimFlowPlant_ElectricalGenerator_Photovoltaic& x,
::xml_schema::flags f,
::xml_schema::container* c)
: ::schema::simxml::MepModel::SimFlowPlant_ElectricalGenerator (x, f, c),
SimFlowPlant_Name_ (x.SimFlowPlant_Name_, f, this),
SimFlowPlant_SurfName_ (x.SimFlowPlant_SurfName_, f, this),
SimFlowPlant_PhotovoltaicPerfObjType_ (x.SimFlowPlant_PhotovoltaicPerfObjType_, f, this),
SimFlowPlant_ModulePerfName_ (x.SimFlowPlant_ModulePerfName_, f, this),
SimFlowPlant_HeatTranstegrationMode_ (x.SimFlowPlant_HeatTranstegrationMode_, f, this),
SimFlowPlant_NumberofSeriesStringsinParallel_ (x.SimFlowPlant_NumberofSeriesStringsinParallel_, f, this),
SimFlowPlant_NumModulesSeries_ (x.SimFlowPlant_NumModulesSeries_, f, this),
PhotovoltaicPerformance_Simple_Name_ (x.PhotovoltaicPerformance_Simple_Name_, f, this),
PhotovoltaicPerformance_Simple_FractionOfSurfAreawithActiveSolarCells_ (x.PhotovoltaicPerformance_Simple_FractionOfSurfAreawithActiveSolarCells_, f, this),
PhotovoltaicPerformance_Simple_ConversionEfficiencyInputMode_ (x.PhotovoltaicPerformance_Simple_ConversionEfficiencyInputMode_, f, this),
PhotovoltaicPerformance_Simple_ValueforCellEfficiencyifFixed_ (x.PhotovoltaicPerformance_Simple_ValueforCellEfficiencyifFixed_, f, this),
PhotovoltaicPerformance_Simple_EfficiencyScheduleName_ (x.PhotovoltaicPerformance_Simple_EfficiencyScheduleName_, f, this),
PVPerf_EquivOne_Diode_Name_ (x.PVPerf_EquivOne_Diode_Name_, f, this),
PVPerf_EquivOne_Diode_CellType_ (x.PVPerf_EquivOne_Diode_CellType_, f, this),
PVPerf_EquivOne_Diode_NumCellsSeries_ (x.PVPerf_EquivOne_Diode_NumCellsSeries_, f, this),
PVPerf_EquivOne_Diode_ActiveArea_ (x.PVPerf_EquivOne_Diode_ActiveArea_, f, this),
PVPerf_EquivOne_Diode_TransAbsorptanceProduct_ (x.PVPerf_EquivOne_Diode_TransAbsorptanceProduct_, f, this),
PVPerf_EquivOne_Diode_SemiconductorBandgap_ (x.PVPerf_EquivOne_Diode_SemiconductorBandgap_, f, this),
PVPerf_EquivOne_Diode_ShuntResist_ (x.PVPerf_EquivOne_Diode_ShuntResist_, f, this),
PVPerf_EquivOne_Diode_ShortCircuitCurrent_ (x.PVPerf_EquivOne_Diode_ShortCircuitCurrent_, f, this),
PVPerf_EquivOne_Diode_OpenCircuitVolt_ (x.PVPerf_EquivOne_Diode_OpenCircuitVolt_, f, this),
PVPerf_EquivOne_Diode_RefTemp_ (x.PVPerf_EquivOne_Diode_RefTemp_, f, this),
PVPerf_EquivOne_Diode_RefInsol_ (x.PVPerf_EquivOne_Diode_RefInsol_, f, this),
PVPerf_EquivOne_Diode_ModuleCurrentAtMaxPwr_ (x.PVPerf_EquivOne_Diode_ModuleCurrentAtMaxPwr_, f, this),
PVPerf_EquivOne_Diode_ModuleVoltAtMaxPwr_ (x.PVPerf_EquivOne_Diode_ModuleVoltAtMaxPwr_, f, this),
PVPerf_EquivOne_Diode_TempCoefShortCircuitCurrent_ (x.PVPerf_EquivOne_Diode_TempCoefShortCircuitCurrent_, f, this),
PVPerf_EquivOne_Diode_TempCoefOpenCircuitVolt_ (x.PVPerf_EquivOne_Diode_TempCoefOpenCircuitVolt_, f, this),
PVPerf_EquivOne_Diode_NomOperatCellTempTestAmbTemp_ (x.PVPerf_EquivOne_Diode_NomOperatCellTempTestAmbTemp_, f, this),
PVPerf_EquivOne_Diode_NomOperatCellTempTestCellTemp_ (x.PVPerf_EquivOne_Diode_NomOperatCellTempTestCellTemp_, f, this),
PVPerf_EquivOne_Diode_NomOperatCellTempTestInsol_ (x.PVPerf_EquivOne_Diode_NomOperatCellTempTestInsol_, f, this),
PVPerf_EquivOne_Diode_ModuleHeatLossCoef_ (x.PVPerf_EquivOne_Diode_ModuleHeatLossCoef_, f, this),
PVPerf_EquivOne_Diode_TotalHeatCap_ (x.PVPerf_EquivOne_Diode_TotalHeatCap_, f, this),
PVPerf_Sandia_Name_ (x.PVPerf_Sandia_Name_, f, this),
PVPerf_Sandia_ActiveArea_ (x.PVPerf_Sandia_ActiveArea_, f, this),
PVPerf_Sandia_NumCellsSeries_ (x.PVPerf_Sandia_NumCellsSeries_, f, this),
PVPerf_Sandia_NumCellsParallel_ (x.PVPerf_Sandia_NumCellsParallel_, f, this),
PVPerf_Sandia_ShortCircuitCurrent_ (x.PVPerf_Sandia_ShortCircuitCurrent_, f, this),
PVPerf_Sandia_OpenCircuitVolt_ (x.PVPerf_Sandia_OpenCircuitVolt_, f, this),
PVPerf_Sandia_CurrentAtMaxPwrPoint_ (x.PVPerf_Sandia_CurrentAtMaxPwrPoint_, f, this),
PVPerf_Sandia_VoltAtMaxPwrPoint_ (x.PVPerf_Sandia_VoltAtMaxPwrPoint_, f, this),
PVPerf_Sandia_SandiaDbParamAc_ (x.PVPerf_Sandia_SandiaDbParamAc_, f, this),
PVPerf_Sandia_SandiaDbParamAImp_ (x.PVPerf_Sandia_SandiaDbParamAImp_, f, this),
PVPerf_Sandia_SandiaDBParamc0_ (x.PVPerf_Sandia_SandiaDBParamc0_, f, this),
PVPerf_Sandia_SandiaDBParamc1_ (x.PVPerf_Sandia_SandiaDBParamc1_, f, this),
PVPerf_Sandia_SandiaDbParamBVoc0_ (x.PVPerf_Sandia_SandiaDbParamBVoc0_, f, this),
PVPerf_Sandia_SandiaDbParamMBVoc_ (x.PVPerf_Sandia_SandiaDbParamMBVoc_, f, this),
PVPerf_Sandia_SandiaDbParamBVmp0_ (x.PVPerf_Sandia_SandiaDbParamBVmp0_, f, this),
PVPerf_Sandia_SandiaDbParamMBVmp_ (x.PVPerf_Sandia_SandiaDbParamMBVmp_, f, this),
PVPerf_Sandia_DiodeFactor_ (x.PVPerf_Sandia_DiodeFactor_, f, this),
PVPerf_Sandia_SandiaDBParamc2_ (x.PVPerf_Sandia_SandiaDBParamc2_, f, this),
PVPerf_Sandia_SandiaDBParamc3_ (x.PVPerf_Sandia_SandiaDBParamc3_, f, this),
PVPerf_Sandia_SandiaDbParama_0_0_ (x.PVPerf_Sandia_SandiaDbParama_0_0_, f, this),
PVPerf_Sandia_SandiaDbParama_1_1_ (x.PVPerf_Sandia_SandiaDbParama_1_1_, f, this),
PVPerf_Sandia_SandiaDBParama2_ (x.PVPerf_Sandia_SandiaDBParama2_, f, this),
PVPerf_Sandia_SandiaDBParama3_ (x.PVPerf_Sandia_SandiaDBParama3_, f, this),
PVPerf_Sandia_SandiaDBParama4_ (x.PVPerf_Sandia_SandiaDBParama4_, f, this),
PVPerf_Sandia_SandiaDbParamb_0_0_ (x.PVPerf_Sandia_SandiaDbParamb_0_0_, f, this),
PVPerf_Sandia_SandiaDbParamb_1_1_ (x.PVPerf_Sandia_SandiaDbParamb_1_1_, f, this),
PVPerf_Sandia_SandiaDBParamb2_ (x.PVPerf_Sandia_SandiaDBParamb2_, f, this),
PVPerf_Sandia_SandiaDBParamb3_ (x.PVPerf_Sandia_SandiaDBParamb3_, f, this),
PVPerf_Sandia_SandiaDBParamb4_ (x.PVPerf_Sandia_SandiaDBParamb4_, f, this),
PVPerf_Sandia_SandiaDBParamb5_ (x.PVPerf_Sandia_SandiaDBParamb5_, f, this),
PVPerf_Sandia_SandiaDbParamDeltaTc_ (x.PVPerf_Sandia_SandiaDbParamDeltaTc_, f, this),
PVPerf_Sandia_SandiaDbParamFd_ (x.PVPerf_Sandia_SandiaDbParamFd_, f, this),
PVPerf_Sandia_SandiaDbParamA_ (x.PVPerf_Sandia_SandiaDbParamA_, f, this),
PVPerf_Sandia_SandiaDbParamB_ (x.PVPerf_Sandia_SandiaDbParamB_, f, this),
PVPerf_Sandia_SandiaDBParamc4_ (x.PVPerf_Sandia_SandiaDBParamc4_, f, this),
PVPerf_Sandia_SandiaDBParamc5_ (x.PVPerf_Sandia_SandiaDBParamc5_, f, this),
PVPerf_Sandia_SandiaDbParamIx0_ (x.PVPerf_Sandia_SandiaDbParamIx0_, f, this),
PVPerf_Sandia_SandiaDbParamIxx0_ (x.PVPerf_Sandia_SandiaDbParamIxx0_, f, this),
PVPerf_Sandia_SandiaDBParamc6_ (x.PVPerf_Sandia_SandiaDBParamc6_, f, this),
PVPerf_Sandia_SandiaDBParamc7_ (x.PVPerf_Sandia_SandiaDBParamc7_, f, this)
{
}
SimFlowPlant_ElectricalGenerator_Photovoltaic::
SimFlowPlant_ElectricalGenerator_Photovoltaic (const ::xercesc::DOMElement& e,
::xml_schema::flags f,
::xml_schema::container* c)
: ::schema::simxml::MepModel::SimFlowPlant_ElectricalGenerator (e, f | ::xml_schema::flags::base, c),
SimFlowPlant_Name_ (this),
SimFlowPlant_SurfName_ (this),
SimFlowPlant_PhotovoltaicPerfObjType_ (this),
SimFlowPlant_ModulePerfName_ (this),
SimFlowPlant_HeatTranstegrationMode_ (this),
SimFlowPlant_NumberofSeriesStringsinParallel_ (this),
SimFlowPlant_NumModulesSeries_ (this),
PhotovoltaicPerformance_Simple_Name_ (this),
PhotovoltaicPerformance_Simple_FractionOfSurfAreawithActiveSolarCells_ (this),
PhotovoltaicPerformance_Simple_ConversionEfficiencyInputMode_ (this),
PhotovoltaicPerformance_Simple_ValueforCellEfficiencyifFixed_ (this),
PhotovoltaicPerformance_Simple_EfficiencyScheduleName_ (this),
PVPerf_EquivOne_Diode_Name_ (this),
PVPerf_EquivOne_Diode_CellType_ (this),
PVPerf_EquivOne_Diode_NumCellsSeries_ (this),
PVPerf_EquivOne_Diode_ActiveArea_ (this),
PVPerf_EquivOne_Diode_TransAbsorptanceProduct_ (this),
PVPerf_EquivOne_Diode_SemiconductorBandgap_ (this),
PVPerf_EquivOne_Diode_ShuntResist_ (this),
PVPerf_EquivOne_Diode_ShortCircuitCurrent_ (this),
PVPerf_EquivOne_Diode_OpenCircuitVolt_ (this),
PVPerf_EquivOne_Diode_RefTemp_ (this),
PVPerf_EquivOne_Diode_RefInsol_ (this),
PVPerf_EquivOne_Diode_ModuleCurrentAtMaxPwr_ (this),
PVPerf_EquivOne_Diode_ModuleVoltAtMaxPwr_ (this),
PVPerf_EquivOne_Diode_TempCoefShortCircuitCurrent_ (this),
PVPerf_EquivOne_Diode_TempCoefOpenCircuitVolt_ (this),
PVPerf_EquivOne_Diode_NomOperatCellTempTestAmbTemp_ (this),
PVPerf_EquivOne_Diode_NomOperatCellTempTestCellTemp_ (this),
PVPerf_EquivOne_Diode_NomOperatCellTempTestInsol_ (this),
PVPerf_EquivOne_Diode_ModuleHeatLossCoef_ (this),
PVPerf_EquivOne_Diode_TotalHeatCap_ (this),
PVPerf_Sandia_Name_ (this),
PVPerf_Sandia_ActiveArea_ (this),
PVPerf_Sandia_NumCellsSeries_ (this),
PVPerf_Sandia_NumCellsParallel_ (this),
PVPerf_Sandia_ShortCircuitCurrent_ (this),
PVPerf_Sandia_OpenCircuitVolt_ (this),
PVPerf_Sandia_CurrentAtMaxPwrPoint_ (this),
PVPerf_Sandia_VoltAtMaxPwrPoint_ (this),
PVPerf_Sandia_SandiaDbParamAc_ (this),
PVPerf_Sandia_SandiaDbParamAImp_ (this),
PVPerf_Sandia_SandiaDBParamc0_ (this),
PVPerf_Sandia_SandiaDBParamc1_ (this),
PVPerf_Sandia_SandiaDbParamBVoc0_ (this),
PVPerf_Sandia_SandiaDbParamMBVoc_ (this),
PVPerf_Sandia_SandiaDbParamBVmp0_ (this),
PVPerf_Sandia_SandiaDbParamMBVmp_ (this),
PVPerf_Sandia_DiodeFactor_ (this),
PVPerf_Sandia_SandiaDBParamc2_ (this),
PVPerf_Sandia_SandiaDBParamc3_ (this),
PVPerf_Sandia_SandiaDbParama_0_0_ (this),
PVPerf_Sandia_SandiaDbParama_1_1_ (this),
PVPerf_Sandia_SandiaDBParama2_ (this),
PVPerf_Sandia_SandiaDBParama3_ (this),
PVPerf_Sandia_SandiaDBParama4_ (this),
PVPerf_Sandia_SandiaDbParamb_0_0_ (this),
PVPerf_Sandia_SandiaDbParamb_1_1_ (this),
PVPerf_Sandia_SandiaDBParamb2_ (this),
PVPerf_Sandia_SandiaDBParamb3_ (this),
PVPerf_Sandia_SandiaDBParamb4_ (this),
PVPerf_Sandia_SandiaDBParamb5_ (this),
PVPerf_Sandia_SandiaDbParamDeltaTc_ (this),
PVPerf_Sandia_SandiaDbParamFd_ (this),
PVPerf_Sandia_SandiaDbParamA_ (this),
PVPerf_Sandia_SandiaDbParamB_ (this),
PVPerf_Sandia_SandiaDBParamc4_ (this),
PVPerf_Sandia_SandiaDBParamc5_ (this),
PVPerf_Sandia_SandiaDbParamIx0_ (this),
PVPerf_Sandia_SandiaDbParamIxx0_ (this),
PVPerf_Sandia_SandiaDBParamc6_ (this),
PVPerf_Sandia_SandiaDBParamc7_ (this)
{
if ((f & ::xml_schema::flags::base) == 0)
{
::xsd::cxx::xml::dom::parser< char > p (e, true, false, true);
this->parse (p, f);
}
}
void SimFlowPlant_ElectricalGenerator_Photovoltaic::
parse (::xsd::cxx::xml::dom::parser< char >& p,
::xml_schema::flags f)
{
this->::schema::simxml::MepModel::SimFlowPlant_ElectricalGenerator::parse (p, f);
for (; p.more_content (); p.next_content (false))
{
const ::xercesc::DOMElement& i (p.cur_element ());
const ::xsd::cxx::xml::qualified_name< char > n (
::xsd::cxx::xml::dom::name< char > (i));
// SimFlowPlant_Name
//
if (n.name () == "SimFlowPlant_Name" && n.namespace_ () == "http://d-alchemy.com/schema/simxml/MepModel")
{
::std::auto_ptr< SimFlowPlant_Name_type > r (
SimFlowPlant_Name_traits::create (i, f, this));
if (!this->SimFlowPlant_Name_)
{
this->SimFlowPlant_Name_.set (r);
continue;
}
}
// SimFlowPlant_SurfName
//
if (n.name () == "SimFlowPlant_SurfName" && n.namespace_ () == "http://d-alchemy.com/schema/simxml/MepModel")
{
::std::auto_ptr< SimFlowPlant_SurfName_type > r (
SimFlowPlant_SurfName_traits::create (i, f, this));
if (!this->SimFlowPlant_SurfName_)
{
this->SimFlowPlant_SurfName_.set (r);
continue;
}
}
// SimFlowPlant_PhotovoltaicPerfObjType
//
if (n.name () == "SimFlowPlant_PhotovoltaicPerfObjType" && n.namespace_ () == "http://d-alchemy.com/schema/simxml/MepModel")
{
::std::auto_ptr< SimFlowPlant_PhotovoltaicPerfObjType_type > r (
SimFlowPlant_PhotovoltaicPerfObjType_traits::create (i, f, this));
if (!this->SimFlowPlant_PhotovoltaicPerfObjType_)
{
this->SimFlowPlant_PhotovoltaicPerfObjType_.set (r);
continue;
}
}
// SimFlowPlant_ModulePerfName
//
if (n.name () == "SimFlowPlant_ModulePerfName" && n.namespace_ () == "http://d-alchemy.com/schema/simxml/MepModel")
{
::std::auto_ptr< SimFlowPlant_ModulePerfName_type > r (
SimFlowPlant_ModulePerfName_traits::create (i, f, this));
if (!this->SimFlowPlant_ModulePerfName_)
{
this->SimFlowPlant_ModulePerfName_.set (r);
continue;
}
}
// SimFlowPlant_HeatTranstegrationMode
//
if (n.name () == "SimFlowPlant_HeatTranstegrationMode" && n.namespace_ () == "http://d-alchemy.com/schema/simxml/MepModel")
{
::std::auto_ptr< SimFlowPlant_HeatTranstegrationMode_type > r (
SimFlowPlant_HeatTranstegrationMode_traits::create (i, f, this));
if (!this->SimFlowPlant_HeatTranstegrationMode_)
{
this->SimFlowPlant_HeatTranstegrationMode_.set (r);
continue;
}
}
// SimFlowPlant_NumberofSeriesStringsinParallel
//
if (n.name () == "SimFlowPlant_NumberofSeriesStringsinParallel" && n.namespace_ () == "http://d-alchemy.com/schema/simxml/MepModel")
{
if (!this->SimFlowPlant_NumberofSeriesStringsinParallel_)
{
this->SimFlowPlant_NumberofSeriesStringsinParallel_.set (SimFlowPlant_NumberofSeriesStringsinParallel_traits::create (i, f, this));
continue;
}
}
// SimFlowPlant_NumModulesSeries
//
if (n.name () == "SimFlowPlant_NumModulesSeries" && n.namespace_ () == "http://d-alchemy.com/schema/simxml/MepModel")
{
if (!this->SimFlowPlant_NumModulesSeries_)
{
this->SimFlowPlant_NumModulesSeries_.set (SimFlowPlant_NumModulesSeries_traits::create (i, f, this));
continue;
}
}
// PhotovoltaicPerformance_Simple_Name
//
if (n.name () == "PhotovoltaicPerformance_Simple_Name" && n.namespace_ () == "http://d-alchemy.com/schema/simxml/MepModel")
{
::std::auto_ptr< PhotovoltaicPerformance_Simple_Name_type > r (
PhotovoltaicPerformance_Simple_Name_traits::create (i, f, this));
if (!this->PhotovoltaicPerformance_Simple_Name_)
{
this->PhotovoltaicPerformance_Simple_Name_.set (r);
continue;
}
}
// PhotovoltaicPerformance_Simple_FractionOfSurfAreawithActiveSolarCells
//
if (n.name () == "PhotovoltaicPerformance_Simple_FractionOfSurfAreawithActiveSolarCells" && n.namespace_ () == "http://d-alchemy.com/schema/simxml/MepModel")
{
if (!this->PhotovoltaicPerformance_Simple_FractionOfSurfAreawithActiveSolarCells_)
{
this->PhotovoltaicPerformance_Simple_FractionOfSurfAreawithActiveSolarCells_.set (PhotovoltaicPerformance_Simple_FractionOfSurfAreawithActiveSolarCells_traits::create (i, f, this));
continue;
}
}
// PhotovoltaicPerformance_Simple_ConversionEfficiencyInputMode
//
if (n.name () == "PhotovoltaicPerformance_Simple_ConversionEfficiencyInputMode" && n.namespace_ () == "http://d-alchemy.com/schema/simxml/MepModel")
{
::std::auto_ptr< PhotovoltaicPerformance_Simple_ConversionEfficiencyInputMode_type > r (
PhotovoltaicPerformance_Simple_ConversionEfficiencyInputMode_traits::create (i, f, this));
if (!this->PhotovoltaicPerformance_Simple_ConversionEfficiencyInputMode_)
{
this->PhotovoltaicPerformance_Simple_ConversionEfficiencyInputMode_.set (r);
continue;
}
}
// PhotovoltaicPerformance_Simple_ValueforCellEfficiencyifFixed
//
if (n.name () == "PhotovoltaicPerformance_Simple_ValueforCellEfficiencyifFixed" && n.namespace_ () == "http://d-alchemy.com/schema/simxml/MepModel")
{
if (!this->PhotovoltaicPerformance_Simple_ValueforCellEfficiencyifFixed_)
{
this->PhotovoltaicPerformance_Simple_ValueforCellEfficiencyifFixed_.set (PhotovoltaicPerformance_Simple_ValueforCellEfficiencyifFixed_traits::create (i, f, this));
continue;
}
}
// PhotovoltaicPerformance_Simple_EfficiencyScheduleName
//
if (n.name () == "PhotovoltaicPerformance_Simple_EfficiencyScheduleName" && n.namespace_ () == "http://d-alchemy.com/schema/simxml/MepModel")
{
::std::auto_ptr< PhotovoltaicPerformance_Simple_EfficiencyScheduleName_type > r (
PhotovoltaicPerformance_Simple_EfficiencyScheduleName_traits::create (i, f, this));
if (!this->PhotovoltaicPerformance_Simple_EfficiencyScheduleName_)
{
this->PhotovoltaicPerformance_Simple_EfficiencyScheduleName_.set (r);
continue;
}
}
// PVPerf_EquivOne_Diode_Name
//
if (n.name () == "PVPerf_EquivOne_Diode_Name" && n.namespace_ () == "http://d-alchemy.com/schema/simxml/MepModel")
{
::std::auto_ptr< PVPerf_EquivOne_Diode_Name_type > r (
PVPerf_EquivOne_Diode_Name_traits::create (i, f, this));
if (!this->PVPerf_EquivOne_Diode_Name_)
{
this->PVPerf_EquivOne_Diode_Name_.set (r);
continue;
}
}
// PVPerf_EquivOne_Diode_CellType
//
if (n.name () == "PVPerf_EquivOne_Diode_CellType" && n.namespace_ () == "http://d-alchemy.com/schema/simxml/MepModel")
{
::std::auto_ptr< PVPerf_EquivOne_Diode_CellType_type > r (
PVPerf_EquivOne_Diode_CellType_traits::create (i, f, this));
if (!this->PVPerf_EquivOne_Diode_CellType_)
{
this->PVPerf_EquivOne_Diode_CellType_.set (r);
continue;
}
}
// PVPerf_EquivOne_Diode_NumCellsSeries
//
if (n.name () == "PVPerf_EquivOne_Diode_NumCellsSeries" && n.namespace_ () == "http://d-alchemy.com/schema/simxml/MepModel")
{
if (!this->PVPerf_EquivOne_Diode_NumCellsSeries_)
{
this->PVPerf_EquivOne_Diode_NumCellsSeries_.set (PVPerf_EquivOne_Diode_NumCellsSeries_traits::create (i, f, this));
continue;
}
}
// PVPerf_EquivOne_Diode_ActiveArea
//
if (n.name () == "PVPerf_EquivOne_Diode_ActiveArea" && n.namespace_ () == "http://d-alchemy.com/schema/simxml/MepModel")
{
if (!this->PVPerf_EquivOne_Diode_ActiveArea_)
{
this->PVPerf_EquivOne_Diode_ActiveArea_.set (PVPerf_EquivOne_Diode_ActiveArea_traits::create (i, f, this));
continue;
}
}
// PVPerf_EquivOne_Diode_TransAbsorptanceProduct
//
if (n.name () == "PVPerf_EquivOne_Diode_TransAbsorptanceProduct" && n.namespace_ () == "http://d-alchemy.com/schema/simxml/MepModel")
{
if (!this->PVPerf_EquivOne_Diode_TransAbsorptanceProduct_)
{
this->PVPerf_EquivOne_Diode_TransAbsorptanceProduct_.set (PVPerf_EquivOne_Diode_TransAbsorptanceProduct_traits::create (i, f, this));
continue;
}
}
// PVPerf_EquivOne_Diode_SemiconductorBandgap
//
if (n.name () == "PVPerf_EquivOne_Diode_SemiconductorBandgap" && n.namespace_ () == "http://d-alchemy.com/schema/simxml/MepModel")
{
if (!this->PVPerf_EquivOne_Diode_SemiconductorBandgap_)
{
this->PVPerf_EquivOne_Diode_SemiconductorBandgap_.set (PVPerf_EquivOne_Diode_SemiconductorBandgap_traits::create (i, f, this));
continue;
}
}
// PVPerf_EquivOne_Diode_ShuntResist
//
if (n.name () == "PVPerf_EquivOne_Diode_ShuntResist" && n.namespace_ () == "http://d-alchemy.com/schema/simxml/MepModel")
{
if (!this->PVPerf_EquivOne_Diode_ShuntResist_)
{
this->PVPerf_EquivOne_Diode_ShuntResist_.set (PVPerf_EquivOne_Diode_ShuntResist_traits::create (i, f, this));
continue;
}
}
// PVPerf_EquivOne_Diode_ShortCircuitCurrent
//
if (n.name () == "PVPerf_EquivOne_Diode_ShortCircuitCurrent" && n.namespace_ () == "http://d-alchemy.com/schema/simxml/MepModel")
{
if (!this->PVPerf_EquivOne_Diode_ShortCircuitCurrent_)
{
this->PVPerf_EquivOne_Diode_ShortCircuitCurrent_.set (PVPerf_EquivOne_Diode_ShortCircuitCurrent_traits::create (i, f, this));
continue;
}
}
// PVPerf_EquivOne_Diode_OpenCircuitVolt
//
if (n.name () == "PVPerf_EquivOne_Diode_OpenCircuitVolt" && n.namespace_ () == "http://d-alchemy.com/schema/simxml/MepModel")
{
if (!this->PVPerf_EquivOne_Diode_OpenCircuitVolt_)
{
this->PVPerf_EquivOne_Diode_OpenCircuitVolt_.set (PVPerf_EquivOne_Diode_OpenCircuitVolt_traits::create (i, f, this));
continue;
}
}
// PVPerf_EquivOne_Diode_RefTemp
//
if (n.name () == "PVPerf_EquivOne_Diode_RefTemp" && n.namespace_ () == "http://d-alchemy.com/schema/simxml/MepModel")
{
if (!this->PVPerf_EquivOne_Diode_RefTemp_)
{
this->PVPerf_EquivOne_Diode_RefTemp_.set (PVPerf_EquivOne_Diode_RefTemp_traits::create (i, f, this));
continue;
}
}
// PVPerf_EquivOne_Diode_RefInsol
//
if (n.name () == "PVPerf_EquivOne_Diode_RefInsol" && n.namespace_ () == "http://d-alchemy.com/schema/simxml/MepModel")
{
if (!this->PVPerf_EquivOne_Diode_RefInsol_)
{
this->PVPerf_EquivOne_Diode_RefInsol_.set (PVPerf_EquivOne_Diode_RefInsol_traits::create (i, f, this));
continue;
}
}
// PVPerf_EquivOne_Diode_ModuleCurrentAtMaxPwr
//
if (n.name () == "PVPerf_EquivOne_Diode_ModuleCurrentAtMaxPwr" && n.namespace_ () == "http://d-alchemy.com/schema/simxml/MepModel")
{
if (!this->PVPerf_EquivOne_Diode_ModuleCurrentAtMaxPwr_)
{
this->PVPerf_EquivOne_Diode_ModuleCurrentAtMaxPwr_.set (PVPerf_EquivOne_Diode_ModuleCurrentAtMaxPwr_traits::create (i, f, this));
continue;
}
}
// PVPerf_EquivOne_Diode_ModuleVoltAtMaxPwr
//
if (n.name () == "PVPerf_EquivOne_Diode_ModuleVoltAtMaxPwr" && n.namespace_ () == "http://d-alchemy.com/schema/simxml/MepModel")
{
if (!this->PVPerf_EquivOne_Diode_ModuleVoltAtMaxPwr_)
{
this->PVPerf_EquivOne_Diode_ModuleVoltAtMaxPwr_.set (PVPerf_EquivOne_Diode_ModuleVoltAtMaxPwr_traits::create (i, f, this));
continue;
}
}
// PVPerf_EquivOne_Diode_TempCoefShortCircuitCurrent
//
if (n.name () == "PVPerf_EquivOne_Diode_TempCoefShortCircuitCurrent" && n.namespace_ () == "http://d-alchemy.com/schema/simxml/MepModel")
{
if (!this->PVPerf_EquivOne_Diode_TempCoefShortCircuitCurrent_)
{
this->PVPerf_EquivOne_Diode_TempCoefShortCircuitCurrent_.set (PVPerf_EquivOne_Diode_TempCoefShortCircuitCurrent_traits::create (i, f, this));
continue;
}
}
// PVPerf_EquivOne_Diode_TempCoefOpenCircuitVolt
//
if (n.name () == "PVPerf_EquivOne_Diode_TempCoefOpenCircuitVolt" && n.namespace_ () == "http://d-alchemy.com/schema/simxml/MepModel")
{
if (!this->PVPerf_EquivOne_Diode_TempCoefOpenCircuitVolt_)
{
this->PVPerf_EquivOne_Diode_TempCoefOpenCircuitVolt_.set (PVPerf_EquivOne_Diode_TempCoefOpenCircuitVolt_traits::create (i, f, this));
continue;
}
}
// PVPerf_EquivOne_Diode_NomOperatCellTempTestAmbTemp
//
if (n.name () == "PVPerf_EquivOne_Diode_NomOperatCellTempTestAmbTemp" && n.namespace_ () == "http://d-alchemy.com/schema/simxml/MepModel")
{
if (!this->PVPerf_EquivOne_Diode_NomOperatCellTempTestAmbTemp_)
{
this->PVPerf_EquivOne_Diode_NomOperatCellTempTestAmbTemp_.set (PVPerf_EquivOne_Diode_NomOperatCellTempTestAmbTemp_traits::create (i, f, this));
continue;
}
}
// PVPerf_EquivOne_Diode_NomOperatCellTempTestCellTemp
//
if (n.name () == "PVPerf_EquivOne_Diode_NomOperatCellTempTestCellTemp" && n.namespace_ () == "http://d-alchemy.com/schema/simxml/MepModel")
{
if (!this->PVPerf_EquivOne_Diode_NomOperatCellTempTestCellTemp_)
{
this->PVPerf_EquivOne_Diode_NomOperatCellTempTestCellTemp_.set (PVPerf_EquivOne_Diode_NomOperatCellTempTestCellTemp_traits::create (i, f, this));
continue;
}
}
// PVPerf_EquivOne_Diode_NomOperatCellTempTestInsol
//
if (n.name () == "PVPerf_EquivOne_Diode_NomOperatCellTempTestInsol" && n.namespace_ () == "http://d-alchemy.com/schema/simxml/MepModel")
{
if (!this->PVPerf_EquivOne_Diode_NomOperatCellTempTestInsol_)
{
this->PVPerf_EquivOne_Diode_NomOperatCellTempTestInsol_.set (PVPerf_EquivOne_Diode_NomOperatCellTempTestInsol_traits::create (i, f, this));
continue;
}
}
// PVPerf_EquivOne_Diode_ModuleHeatLossCoef
//
if (n.name () == "PVPerf_EquivOne_Diode_ModuleHeatLossCoef" && n.namespace_ () == "http://d-alchemy.com/schema/simxml/MepModel")
{
if (!this->PVPerf_EquivOne_Diode_ModuleHeatLossCoef_)
{
this->PVPerf_EquivOne_Diode_ModuleHeatLossCoef_.set (PVPerf_EquivOne_Diode_ModuleHeatLossCoef_traits::create (i, f, this));
continue;
}
}
// PVPerf_EquivOne_Diode_TotalHeatCap
//
if (n.name () == "PVPerf_EquivOne_Diode_TotalHeatCap" && n.namespace_ () == "http://d-alchemy.com/schema/simxml/MepModel")
{
if (!this->PVPerf_EquivOne_Diode_TotalHeatCap_)
{
this->PVPerf_EquivOne_Diode_TotalHeatCap_.set (PVPerf_EquivOne_Diode_TotalHeatCap_traits::create (i, f, this));
continue;
}
}
// PVPerf_Sandia_Name
//
if (n.name () == "PVPerf_Sandia_Name" && n.namespace_ () == "http://d-alchemy.com/schema/simxml/MepModel")
{
::std::auto_ptr< PVPerf_Sandia_Name_type > r (
PVPerf_Sandia_Name_traits::create (i, f, this));
if (!this->PVPerf_Sandia_Name_)
{
this->PVPerf_Sandia_Name_.set (r);
continue;
}
}
// PVPerf_Sandia_ActiveArea
//
if (n.name () == "PVPerf_Sandia_ActiveArea" && n.namespace_ () == "http://d-alchemy.com/schema/simxml/MepModel")
{
if (!this->PVPerf_Sandia_ActiveArea_)
{
this->PVPerf_Sandia_ActiveArea_.set (PVPerf_Sandia_ActiveArea_traits::create (i, f, this));
continue;
}
}
// PVPerf_Sandia_NumCellsSeries
//
if (n.name () == "PVPerf_Sandia_NumCellsSeries" && n.namespace_ () == "http://d-alchemy.com/schema/simxml/MepModel")
{
if (!this->PVPerf_Sandia_NumCellsSeries_)
{
this->PVPerf_Sandia_NumCellsSeries_.set (PVPerf_Sandia_NumCellsSeries_traits::create (i, f, this));
continue;
}
}
// PVPerf_Sandia_NumCellsParallel
//
if (n.name () == "PVPerf_Sandia_NumCellsParallel" && n.namespace_ () == "http://d-alchemy.com/schema/simxml/MepModel")
{
if (!this->PVPerf_Sandia_NumCellsParallel_)
{
this->PVPerf_Sandia_NumCellsParallel_.set (PVPerf_Sandia_NumCellsParallel_traits::create (i, f, this));
continue;
}
}
// PVPerf_Sandia_ShortCircuitCurrent
//
if (n.name () == "PVPerf_Sandia_ShortCircuitCurrent" && n.namespace_ () == "http://d-alchemy.com/schema/simxml/MepModel")
{
if (!this->PVPerf_Sandia_ShortCircuitCurrent_)
{
this->PVPerf_Sandia_ShortCircuitCurrent_.set (PVPerf_Sandia_ShortCircuitCurrent_traits::create (i, f, this));
continue;
}
}
// PVPerf_Sandia_OpenCircuitVolt
//
if (n.name () == "PVPerf_Sandia_OpenCircuitVolt" && n.namespace_ () == "http://d-alchemy.com/schema/simxml/MepModel")
{
if (!this->PVPerf_Sandia_OpenCircuitVolt_)
{
this->PVPerf_Sandia_OpenCircuitVolt_.set (PVPerf_Sandia_OpenCircuitVolt_traits::create (i, f, this));
continue;
}
}
// PVPerf_Sandia_CurrentAtMaxPwrPoint
//
if (n.name () == "PVPerf_Sandia_CurrentAtMaxPwrPoint" && n.namespace_ () == "http://d-alchemy.com/schema/simxml/MepModel")
{
if (!this->PVPerf_Sandia_CurrentAtMaxPwrPoint_)
{
this->PVPerf_Sandia_CurrentAtMaxPwrPoint_.set (PVPerf_Sandia_CurrentAtMaxPwrPoint_traits::create (i, f, this));
continue;
}
}
// PVPerf_Sandia_VoltAtMaxPwrPoint
//
if (n.name () == "PVPerf_Sandia_VoltAtMaxPwrPoint" && n.namespace_ () == "http://d-alchemy.com/schema/simxml/MepModel")
{
if (!this->PVPerf_Sandia_VoltAtMaxPwrPoint_)
{
this->PVPerf_Sandia_VoltAtMaxPwrPoint_.set (PVPerf_Sandia_VoltAtMaxPwrPoint_traits::create (i, f, this));
continue;
}
}
// PVPerf_Sandia_SandiaDbParamAc
//
if (n.name () == "PVPerf_Sandia_SandiaDbParamAc" && n.namespace_ () == "http://d-alchemy.com/schema/simxml/MepModel")
{
if (!this->PVPerf_Sandia_SandiaDbParamAc_)
{
this->PVPerf_Sandia_SandiaDbParamAc_.set (PVPerf_Sandia_SandiaDbParamAc_traits::create (i, f, this));
continue;
}
}
// PVPerf_Sandia_SandiaDbParamAImp
//
if (n.name () == "PVPerf_Sandia_SandiaDbParamAImp" && n.namespace_ () == "http://d-alchemy.com/schema/simxml/MepModel")
{
if (!this->PVPerf_Sandia_SandiaDbParamAImp_)
{
this->PVPerf_Sandia_SandiaDbParamAImp_.set (PVPerf_Sandia_SandiaDbParamAImp_traits::create (i, f, this));
continue;
}
}
// PVPerf_Sandia_SandiaDBParamc0
//
if (n.name () == "PVPerf_Sandia_SandiaDBParamc0" && n.namespace_ () == "http://d-alchemy.com/schema/simxml/MepModel")
{
if (!this->PVPerf_Sandia_SandiaDBParamc0_)
{
this->PVPerf_Sandia_SandiaDBParamc0_.set (PVPerf_Sandia_SandiaDBParamc0_traits::create (i, f, this));
continue;
}
}
// PVPerf_Sandia_SandiaDBParamc1
//
if (n.name () == "PVPerf_Sandia_SandiaDBParamc1" && n.namespace_ () == "http://d-alchemy.com/schema/simxml/MepModel")
{
if (!this->PVPerf_Sandia_SandiaDBParamc1_)
{
this->PVPerf_Sandia_SandiaDBParamc1_.set (PVPerf_Sandia_SandiaDBParamc1_traits::create (i, f, this));
continue;
}
}
// PVPerf_Sandia_SandiaDbParamBVoc0
//
if (n.name () == "PVPerf_Sandia_SandiaDbParamBVoc0" && n.namespace_ () == "http://d-alchemy.com/schema/simxml/MepModel")
{
if (!this->PVPerf_Sandia_SandiaDbParamBVoc0_)
{
this->PVPerf_Sandia_SandiaDbParamBVoc0_.set (PVPerf_Sandia_SandiaDbParamBVoc0_traits::create (i, f, this));
continue;
}
}
// PVPerf_Sandia_SandiaDbParamMBVoc
//
if (n.name () == "PVPerf_Sandia_SandiaDbParamMBVoc" && n.namespace_ () == "http://d-alchemy.com/schema/simxml/MepModel")
{
if (!this->PVPerf_Sandia_SandiaDbParamMBVoc_)
{
this->PVPerf_Sandia_SandiaDbParamMBVoc_.set (PVPerf_Sandia_SandiaDbParamMBVoc_traits::create (i, f, this));
continue;
}
}
// PVPerf_Sandia_SandiaDbParamBVmp0
//
if (n.name () == "PVPerf_Sandia_SandiaDbParamBVmp0" && n.namespace_ () == "http://d-alchemy.com/schema/simxml/MepModel")
{
if (!this->PVPerf_Sandia_SandiaDbParamBVmp0_)
{
this->PVPerf_Sandia_SandiaDbParamBVmp0_.set (PVPerf_Sandia_SandiaDbParamBVmp0_traits::create (i, f, this));
continue;
}
}
// PVPerf_Sandia_SandiaDbParamMBVmp
//
if (n.name () == "PVPerf_Sandia_SandiaDbParamMBVmp" && n.namespace_ () == "http://d-alchemy.com/schema/simxml/MepModel")
{
if (!this->PVPerf_Sandia_SandiaDbParamMBVmp_)
{
this->PVPerf_Sandia_SandiaDbParamMBVmp_.set (PVPerf_Sandia_SandiaDbParamMBVmp_traits::create (i, f, this));
continue;
}
}
// PVPerf_Sandia_DiodeFactor
//
if (n.name () == "PVPerf_Sandia_DiodeFactor" && n.namespace_ () == "http://d-alchemy.com/schema/simxml/MepModel")
{
if (!this->PVPerf_Sandia_DiodeFactor_)
{
this->PVPerf_Sandia_DiodeFactor_.set (PVPerf_Sandia_DiodeFactor_traits::create (i, f, this));
continue;
}
}
// PVPerf_Sandia_SandiaDBParamc2
//
if (n.name () == "PVPerf_Sandia_SandiaDBParamc2" && n.namespace_ () == "http://d-alchemy.com/schema/simxml/MepModel")
{
if (!this->PVPerf_Sandia_SandiaDBParamc2_)
{
this->PVPerf_Sandia_SandiaDBParamc2_.set (PVPerf_Sandia_SandiaDBParamc2_traits::create (i, f, this));
continue;
}
}
// PVPerf_Sandia_SandiaDBParamc3
//
if (n.name () == "PVPerf_Sandia_SandiaDBParamc3" && n.namespace_ () == "http://d-alchemy.com/schema/simxml/MepModel")
{
if (!this->PVPerf_Sandia_SandiaDBParamc3_)
{
this->PVPerf_Sandia_SandiaDBParamc3_.set (PVPerf_Sandia_SandiaDBParamc3_traits::create (i, f, this));
continue;
}
}
// PVPerf_Sandia_SandiaDbParama_0_0
//
if (n.name () == "PVPerf_Sandia_SandiaDbParama_0_0" && n.namespace_ () == "http://d-alchemy.com/schema/simxml/MepModel")
{
::std::auto_ptr< PVPerf_Sandia_SandiaDbParama_0_0_type > r (
PVPerf_Sandia_SandiaDbParama_0_0_traits::create (i, f, this));
if (!this->PVPerf_Sandia_SandiaDbParama_0_0_)
{
this->PVPerf_Sandia_SandiaDbParama_0_0_.set (r);
continue;
}
}
// PVPerf_Sandia_SandiaDbParama_1_1
//
if (n.name () == "PVPerf_Sandia_SandiaDbParama_1_1" && n.namespace_ () == "http://d-alchemy.com/schema/simxml/MepModel")
{
::std::auto_ptr< PVPerf_Sandia_SandiaDbParama_1_1_type > r (
PVPerf_Sandia_SandiaDbParama_1_1_traits::create (i, f, this));
if (!this->PVPerf_Sandia_SandiaDbParama_1_1_)
{
this->PVPerf_Sandia_SandiaDbParama_1_1_.set (r);
continue;
}
}
// PVPerf_Sandia_SandiaDBParama2
//
if (n.name () == "PVPerf_Sandia_SandiaDBParama2" && n.namespace_ () == "http://d-alchemy.com/schema/simxml/MepModel")
{
if (!this->PVPerf_Sandia_SandiaDBParama2_)
{
this->PVPerf_Sandia_SandiaDBParama2_.set (PVPerf_Sandia_SandiaDBParama2_traits::create (i, f, this));
continue;
}
}
// PVPerf_Sandia_SandiaDBParama3
//
if (n.name () == "PVPerf_Sandia_SandiaDBParama3" && n.namespace_ () == "http://d-alchemy.com/schema/simxml/MepModel")
{
if (!this->PVPerf_Sandia_SandiaDBParama3_)
{
this->PVPerf_Sandia_SandiaDBParama3_.set (PVPerf_Sandia_SandiaDBParama3_traits::create (i, f, this));
continue;
}
}
// PVPerf_Sandia_SandiaDBParama4
//
if (n.name () == "PVPerf_Sandia_SandiaDBParama4" && n.namespace_ () == "http://d-alchemy.com/schema/simxml/MepModel")
{
if (!this->PVPerf_Sandia_SandiaDBParama4_)
{
this->PVPerf_Sandia_SandiaDBParama4_.set (PVPerf_Sandia_SandiaDBParama4_traits::create (i, f, this));
continue;
}
}
// PVPerf_Sandia_SandiaDbParamb_0_0
//
if (n.name () == "PVPerf_Sandia_SandiaDbParamb_0_0" && n.namespace_ () == "http://d-alchemy.com/schema/simxml/MepModel")
{
::std::auto_ptr< PVPerf_Sandia_SandiaDbParamb_0_0_type > r (
PVPerf_Sandia_SandiaDbParamb_0_0_traits::create (i, f, this));
if (!this->PVPerf_Sandia_SandiaDbParamb_0_0_)
{
this->PVPerf_Sandia_SandiaDbParamb_0_0_.set (r);
continue;
}
}
// PVPerf_Sandia_SandiaDbParamb_1_1
//
if (n.name () == "PVPerf_Sandia_SandiaDbParamb_1_1" && n.namespace_ () == "http://d-alchemy.com/schema/simxml/MepModel")
{
::std::auto_ptr< PVPerf_Sandia_SandiaDbParamb_1_1_type > r (
PVPerf_Sandia_SandiaDbParamb_1_1_traits::create (i, f, this));
if (!this->PVPerf_Sandia_SandiaDbParamb_1_1_)
{
this->PVPerf_Sandia_SandiaDbParamb_1_1_.set (r);
continue;
}
}
// PVPerf_Sandia_SandiaDBParamb2
//
if (n.name () == "PVPerf_Sandia_SandiaDBParamb2" && n.namespace_ () == "http://d-alchemy.com/schema/simxml/MepModel")
{
if (!this->PVPerf_Sandia_SandiaDBParamb2_)
{
this->PVPerf_Sandia_SandiaDBParamb2_.set (PVPerf_Sandia_SandiaDBParamb2_traits::create (i, f, this));
continue;
}
}
// PVPerf_Sandia_SandiaDBParamb3
//
if (n.name () == "PVPerf_Sandia_SandiaDBParamb3" && n.namespace_ () == "http://d-alchemy.com/schema/simxml/MepModel")
{
if (!this->PVPerf_Sandia_SandiaDBParamb3_)
{
this->PVPerf_Sandia_SandiaDBParamb3_.set (PVPerf_Sandia_SandiaDBParamb3_traits::create (i, f, this));
continue;
}
}
// PVPerf_Sandia_SandiaDBParamb4
//
if (n.name () == "PVPerf_Sandia_SandiaDBParamb4" && n.namespace_ () == "http://d-alchemy.com/schema/simxml/MepModel")
{
if (!this->PVPerf_Sandia_SandiaDBParamb4_)
{
this->PVPerf_Sandia_SandiaDBParamb4_.set (PVPerf_Sandia_SandiaDBParamb4_traits::create (i, f, this));
continue;
}
}
// PVPerf_Sandia_SandiaDBParamb5
//
if (n.name () == "PVPerf_Sandia_SandiaDBParamb5" && n.namespace_ () == "http://d-alchemy.com/schema/simxml/MepModel")
{
if (!this->PVPerf_Sandia_SandiaDBParamb5_)
{
this->PVPerf_Sandia_SandiaDBParamb5_.set (PVPerf_Sandia_SandiaDBParamb5_traits::create (i, f, this));
continue;
}
}
// PVPerf_Sandia_SandiaDbParamDeltaTc
//
if (n.name () == "PVPerf_Sandia_SandiaDbParamDeltaTc" && n.namespace_ () == "http://d-alchemy.com/schema/simxml/MepModel")
{
if (!this->PVPerf_Sandia_SandiaDbParamDeltaTc_)
{
this->PVPerf_Sandia_SandiaDbParamDeltaTc_.set (PVPerf_Sandia_SandiaDbParamDeltaTc_traits::create (i, f, this));
continue;
}
}
// PVPerf_Sandia_SandiaDbParamFd
//
if (n.name () == "PVPerf_Sandia_SandiaDbParamFd" && n.namespace_ () == "http://d-alchemy.com/schema/simxml/MepModel")
{
if (!this->PVPerf_Sandia_SandiaDbParamFd_)
{
this->PVPerf_Sandia_SandiaDbParamFd_.set (PVPerf_Sandia_SandiaDbParamFd_traits::create (i, f, this));
continue;
}
}
// PVPerf_Sandia_SandiaDbParamA
//
if (n.name () == "PVPerf_Sandia_SandiaDbParamA" && n.namespace_ () == "http://d-alchemy.com/schema/simxml/MepModel")
{
if (!this->PVPerf_Sandia_SandiaDbParamA_)
{
this->PVPerf_Sandia_SandiaDbParamA_.set (PVPerf_Sandia_SandiaDbParamA_traits::create (i, f, this));
continue;
}
}
// PVPerf_Sandia_SandiaDbParamB
//
if (n.name () == "PVPerf_Sandia_SandiaDbParamB" && n.namespace_ () == "http://d-alchemy.com/schema/simxml/MepModel")
{
if (!this->PVPerf_Sandia_SandiaDbParamB_)
{
this->PVPerf_Sandia_SandiaDbParamB_.set (PVPerf_Sandia_SandiaDbParamB_traits::create (i, f, this));
continue;
}
}
// PVPerf_Sandia_SandiaDBParamc4
//
if (n.name () == "PVPerf_Sandia_SandiaDBParamc4" && n.namespace_ () == "http://d-alchemy.com/schema/simxml/MepModel")
{
if (!this->PVPerf_Sandia_SandiaDBParamc4_)
{
this->PVPerf_Sandia_SandiaDBParamc4_.set (PVPerf_Sandia_SandiaDBParamc4_traits::create (i, f, this));
continue;
}
}
// PVPerf_Sandia_SandiaDBParamc5
//
if (n.name () == "PVPerf_Sandia_SandiaDBParamc5" && n.namespace_ () == "http://d-alchemy.com/schema/simxml/MepModel")
{
if (!this->PVPerf_Sandia_SandiaDBParamc5_)
{
this->PVPerf_Sandia_SandiaDBParamc5_.set (PVPerf_Sandia_SandiaDBParamc5_traits::create (i, f, this));
continue;
}
}
// PVPerf_Sandia_SandiaDbParamIx0
//
if (n.name () == "PVPerf_Sandia_SandiaDbParamIx0" && n.namespace_ () == "http://d-alchemy.com/schema/simxml/MepModel")
{
if (!this->PVPerf_Sandia_SandiaDbParamIx0_)
{
this->PVPerf_Sandia_SandiaDbParamIx0_.set (PVPerf_Sandia_SandiaDbParamIx0_traits::create (i, f, this));
continue;
}
}
// PVPerf_Sandia_SandiaDbParamIxx0
//
if (n.name () == "PVPerf_Sandia_SandiaDbParamIxx0" && n.namespace_ () == "http://d-alchemy.com/schema/simxml/MepModel")
{
if (!this->PVPerf_Sandia_SandiaDbParamIxx0_)
{
this->PVPerf_Sandia_SandiaDbParamIxx0_.set (PVPerf_Sandia_SandiaDbParamIxx0_traits::create (i, f, this));
continue;
}
}
// PVPerf_Sandia_SandiaDBParamc6
//
if (n.name () == "PVPerf_Sandia_SandiaDBParamc6" && n.namespace_ () == "http://d-alchemy.com/schema/simxml/MepModel")
{
if (!this->PVPerf_Sandia_SandiaDBParamc6_)
{
this->PVPerf_Sandia_SandiaDBParamc6_.set (PVPerf_Sandia_SandiaDBParamc6_traits::create (i, f, this));
continue;
}
}
// PVPerf_Sandia_SandiaDBParamc7
//
if (n.name () == "PVPerf_Sandia_SandiaDBParamc7" && n.namespace_ () == "http://d-alchemy.com/schema/simxml/MepModel")
{
if (!this->PVPerf_Sandia_SandiaDBParamc7_)
{
this->PVPerf_Sandia_SandiaDBParamc7_.set (PVPerf_Sandia_SandiaDBParamc7_traits::create (i, f, this));
continue;
}
}
break;
}
}
SimFlowPlant_ElectricalGenerator_Photovoltaic* SimFlowPlant_ElectricalGenerator_Photovoltaic::
_clone (::xml_schema::flags f,
::xml_schema::container* c) const
{
return new class SimFlowPlant_ElectricalGenerator_Photovoltaic (*this, f, c);
}
SimFlowPlant_ElectricalGenerator_Photovoltaic& SimFlowPlant_ElectricalGenerator_Photovoltaic::
operator= (const SimFlowPlant_ElectricalGenerator_Photovoltaic& x)
{
if (this != &x)
{
static_cast< ::schema::simxml::MepModel::SimFlowPlant_ElectricalGenerator& > (*this) = x;
this->SimFlowPlant_Name_ = x.SimFlowPlant_Name_;
this->SimFlowPlant_SurfName_ = x.SimFlowPlant_SurfName_;
this->SimFlowPlant_PhotovoltaicPerfObjType_ = x.SimFlowPlant_PhotovoltaicPerfObjType_;
this->SimFlowPlant_ModulePerfName_ = x.SimFlowPlant_ModulePerfName_;
this->SimFlowPlant_HeatTranstegrationMode_ = x.SimFlowPlant_HeatTranstegrationMode_;
this->SimFlowPlant_NumberofSeriesStringsinParallel_ = x.SimFlowPlant_NumberofSeriesStringsinParallel_;
this->SimFlowPlant_NumModulesSeries_ = x.SimFlowPlant_NumModulesSeries_;
this->PhotovoltaicPerformance_Simple_Name_ = x.PhotovoltaicPerformance_Simple_Name_;
this->PhotovoltaicPerformance_Simple_FractionOfSurfAreawithActiveSolarCells_ = x.PhotovoltaicPerformance_Simple_FractionOfSurfAreawithActiveSolarCells_;
this->PhotovoltaicPerformance_Simple_ConversionEfficiencyInputMode_ = x.PhotovoltaicPerformance_Simple_ConversionEfficiencyInputMode_;
this->PhotovoltaicPerformance_Simple_ValueforCellEfficiencyifFixed_ = x.PhotovoltaicPerformance_Simple_ValueforCellEfficiencyifFixed_;
this->PhotovoltaicPerformance_Simple_EfficiencyScheduleName_ = x.PhotovoltaicPerformance_Simple_EfficiencyScheduleName_;
this->PVPerf_EquivOne_Diode_Name_ = x.PVPerf_EquivOne_Diode_Name_;
this->PVPerf_EquivOne_Diode_CellType_ = x.PVPerf_EquivOne_Diode_CellType_;
this->PVPerf_EquivOne_Diode_NumCellsSeries_ = x.PVPerf_EquivOne_Diode_NumCellsSeries_;
this->PVPerf_EquivOne_Diode_ActiveArea_ = x.PVPerf_EquivOne_Diode_ActiveArea_;
this->PVPerf_EquivOne_Diode_TransAbsorptanceProduct_ = x.PVPerf_EquivOne_Diode_TransAbsorptanceProduct_;
this->PVPerf_EquivOne_Diode_SemiconductorBandgap_ = x.PVPerf_EquivOne_Diode_SemiconductorBandgap_;
this->PVPerf_EquivOne_Diode_ShuntResist_ = x.PVPerf_EquivOne_Diode_ShuntResist_;
this->PVPerf_EquivOne_Diode_ShortCircuitCurrent_ = x.PVPerf_EquivOne_Diode_ShortCircuitCurrent_;
this->PVPerf_EquivOne_Diode_OpenCircuitVolt_ = x.PVPerf_EquivOne_Diode_OpenCircuitVolt_;
this->PVPerf_EquivOne_Diode_RefTemp_ = x.PVPerf_EquivOne_Diode_RefTemp_;
this->PVPerf_EquivOne_Diode_RefInsol_ = x.PVPerf_EquivOne_Diode_RefInsol_;
this->PVPerf_EquivOne_Diode_ModuleCurrentAtMaxPwr_ = x.PVPerf_EquivOne_Diode_ModuleCurrentAtMaxPwr_;
this->PVPerf_EquivOne_Diode_ModuleVoltAtMaxPwr_ = x.PVPerf_EquivOne_Diode_ModuleVoltAtMaxPwr_;
this->PVPerf_EquivOne_Diode_TempCoefShortCircuitCurrent_ = x.PVPerf_EquivOne_Diode_TempCoefShortCircuitCurrent_;
this->PVPerf_EquivOne_Diode_TempCoefOpenCircuitVolt_ = x.PVPerf_EquivOne_Diode_TempCoefOpenCircuitVolt_;
this->PVPerf_EquivOne_Diode_NomOperatCellTempTestAmbTemp_ = x.PVPerf_EquivOne_Diode_NomOperatCellTempTestAmbTemp_;
this->PVPerf_EquivOne_Diode_NomOperatCellTempTestCellTemp_ = x.PVPerf_EquivOne_Diode_NomOperatCellTempTestCellTemp_;
this->PVPerf_EquivOne_Diode_NomOperatCellTempTestInsol_ = x.PVPerf_EquivOne_Diode_NomOperatCellTempTestInsol_;
this->PVPerf_EquivOne_Diode_ModuleHeatLossCoef_ = x.PVPerf_EquivOne_Diode_ModuleHeatLossCoef_;
this->PVPerf_EquivOne_Diode_TotalHeatCap_ = x.PVPerf_EquivOne_Diode_TotalHeatCap_;
this->PVPerf_Sandia_Name_ = x.PVPerf_Sandia_Name_;
this->PVPerf_Sandia_ActiveArea_ = x.PVPerf_Sandia_ActiveArea_;
this->PVPerf_Sandia_NumCellsSeries_ = x.PVPerf_Sandia_NumCellsSeries_;
this->PVPerf_Sandia_NumCellsParallel_ = x.PVPerf_Sandia_NumCellsParallel_;
this->PVPerf_Sandia_ShortCircuitCurrent_ = x.PVPerf_Sandia_ShortCircuitCurrent_;
this->PVPerf_Sandia_OpenCircuitVolt_ = x.PVPerf_Sandia_OpenCircuitVolt_;
this->PVPerf_Sandia_CurrentAtMaxPwrPoint_ = x.PVPerf_Sandia_CurrentAtMaxPwrPoint_;
this->PVPerf_Sandia_VoltAtMaxPwrPoint_ = x.PVPerf_Sandia_VoltAtMaxPwrPoint_;
this->PVPerf_Sandia_SandiaDbParamAc_ = x.PVPerf_Sandia_SandiaDbParamAc_;
this->PVPerf_Sandia_SandiaDbParamAImp_ = x.PVPerf_Sandia_SandiaDbParamAImp_;
this->PVPerf_Sandia_SandiaDBParamc0_ = x.PVPerf_Sandia_SandiaDBParamc0_;
this->PVPerf_Sandia_SandiaDBParamc1_ = x.PVPerf_Sandia_SandiaDBParamc1_;
this->PVPerf_Sandia_SandiaDbParamBVoc0_ = x.PVPerf_Sandia_SandiaDbParamBVoc0_;
this->PVPerf_Sandia_SandiaDbParamMBVoc_ = x.PVPerf_Sandia_SandiaDbParamMBVoc_;
this->PVPerf_Sandia_SandiaDbParamBVmp0_ = x.PVPerf_Sandia_SandiaDbParamBVmp0_;
this->PVPerf_Sandia_SandiaDbParamMBVmp_ = x.PVPerf_Sandia_SandiaDbParamMBVmp_;
this->PVPerf_Sandia_DiodeFactor_ = x.PVPerf_Sandia_DiodeFactor_;
this->PVPerf_Sandia_SandiaDBParamc2_ = x.PVPerf_Sandia_SandiaDBParamc2_;
this->PVPerf_Sandia_SandiaDBParamc3_ = x.PVPerf_Sandia_SandiaDBParamc3_;
this->PVPerf_Sandia_SandiaDbParama_0_0_ = x.PVPerf_Sandia_SandiaDbParama_0_0_;
this->PVPerf_Sandia_SandiaDbParama_1_1_ = x.PVPerf_Sandia_SandiaDbParama_1_1_;
this->PVPerf_Sandia_SandiaDBParama2_ = x.PVPerf_Sandia_SandiaDBParama2_;
this->PVPerf_Sandia_SandiaDBParama3_ = x.PVPerf_Sandia_SandiaDBParama3_;
this->PVPerf_Sandia_SandiaDBParama4_ = x.PVPerf_Sandia_SandiaDBParama4_;
this->PVPerf_Sandia_SandiaDbParamb_0_0_ = x.PVPerf_Sandia_SandiaDbParamb_0_0_;
this->PVPerf_Sandia_SandiaDbParamb_1_1_ = x.PVPerf_Sandia_SandiaDbParamb_1_1_;
this->PVPerf_Sandia_SandiaDBParamb2_ = x.PVPerf_Sandia_SandiaDBParamb2_;
this->PVPerf_Sandia_SandiaDBParamb3_ = x.PVPerf_Sandia_SandiaDBParamb3_;
this->PVPerf_Sandia_SandiaDBParamb4_ = x.PVPerf_Sandia_SandiaDBParamb4_;
this->PVPerf_Sandia_SandiaDBParamb5_ = x.PVPerf_Sandia_SandiaDBParamb5_;
this->PVPerf_Sandia_SandiaDbParamDeltaTc_ = x.PVPerf_Sandia_SandiaDbParamDeltaTc_;
this->PVPerf_Sandia_SandiaDbParamFd_ = x.PVPerf_Sandia_SandiaDbParamFd_;
this->PVPerf_Sandia_SandiaDbParamA_ = x.PVPerf_Sandia_SandiaDbParamA_;
this->PVPerf_Sandia_SandiaDbParamB_ = x.PVPerf_Sandia_SandiaDbParamB_;
this->PVPerf_Sandia_SandiaDBParamc4_ = x.PVPerf_Sandia_SandiaDBParamc4_;
this->PVPerf_Sandia_SandiaDBParamc5_ = x.PVPerf_Sandia_SandiaDBParamc5_;
this->PVPerf_Sandia_SandiaDbParamIx0_ = x.PVPerf_Sandia_SandiaDbParamIx0_;
this->PVPerf_Sandia_SandiaDbParamIxx0_ = x.PVPerf_Sandia_SandiaDbParamIxx0_;
this->PVPerf_Sandia_SandiaDBParamc6_ = x.PVPerf_Sandia_SandiaDBParamc6_;
this->PVPerf_Sandia_SandiaDBParamc7_ = x.PVPerf_Sandia_SandiaDBParamc7_;
}
return *this;
}
SimFlowPlant_ElectricalGenerator_Photovoltaic::
~SimFlowPlant_ElectricalGenerator_Photovoltaic ()
{
}
}
}
}
#include <istream>
#include <xsd/cxx/xml/sax/std-input-source.hxx>
#include <xsd/cxx/tree/error-handler.hxx>
namespace schema
{
namespace simxml
{
namespace MepModel
{
}
}
}
#include <xsd/cxx/post.hxx>
// Begin epilogue.
//
//
// End epilogue.
| 43.769762 | 195 | 0.725179 | EnEff-BIM |
fa42f7d64228c4762e9e0fc5e8e7546e729a0bb5 | 3,354 | cpp | C++ | src/seraphon/SaurusEternityWarden.cpp | rweyrauch/AoSSimulator | d2bfbbe0fab904cc543f1a01e62e0b82cf67c27b | [
"MIT"
] | 5 | 2019-02-01T01:41:19.000Z | 2021-06-17T02:16:13.000Z | src/seraphon/SaurusEternityWarden.cpp | rweyrauch/AoSSimulator | d2bfbbe0fab904cc543f1a01e62e0b82cf67c27b | [
"MIT"
] | 2 | 2020-01-14T16:57:42.000Z | 2021-04-01T00:53:18.000Z | src/seraphon/SaurusEternityWarden.cpp | rweyrauch/AoSSimulator | d2bfbbe0fab904cc543f1a01e62e0b82cf67c27b | [
"MIT"
] | 1 | 2019-03-02T20:03:51.000Z | 2019-03-02T20:03:51.000Z | /*
* Warhammer Age of Sigmar battle simulator.
*
* Copyright (C) 2019 by Rick Weyrauch - rpweyrauch@gmail.com
*
* This code is licensed under the MIT license (MIT) (http://opensource.org/licenses/MIT)
*/
#include <seraphon/SaurusEternityWarden.h>
#include <UnitFactory.h>
#include "SeraphonPrivate.h"
namespace Seraphon {
static const int g_basesize = 40;
static const int g_wounds = 7;
static const int g_pointsPerUnit = 125;
bool SaurusEternityWarden::s_registered = false;
SaurusEternityWarden::SaurusEternityWarden(WayOfTheSeraphon way, Constellation constellation, CommandTrait trait, Artefact artefact, bool isGeneral) :
SeraphonBase("Saurus Eternity Warden", 5, g_wounds, 8, 3, false, g_pointsPerUnit) {
m_keywords = {ORDER, SERAPHON, SAURUS, HERO, ETERNITY_WARDEN};
m_weapons = {&m_mace, &m_jaws};
m_battleFieldRole = Role::Leader;
setWayOfTheSeraphon(way, constellation);
setCommandTrait(trait);
setArtefact(artefact);
setGeneral(isGeneral);
auto model = new Model(g_basesize, wounds());
model->addMeleeWeapon(&m_mace);
model->addMeleeWeapon(&m_jaws);
addModel(model);
}
Unit *SaurusEternityWarden::Create(const ParameterList ¶meters) {
auto way = (WayOfTheSeraphon) GetEnumParam("Way of the Seraphon", parameters, g_wayOfTheSeraphon[0]);
auto constellation = (Constellation) GetEnumParam("Constellation", parameters, g_constellation[0]);
auto trait = (CommandTrait) GetEnumParam("Command Trait", parameters, g_saurusCommandTrait[0]);
auto artefact = (Artefact) GetEnumParam("Artefact", parameters, g_celestialRelicsOfTheWarrior[0]);
auto general = GetBoolParam("General", parameters, false);
return new SaurusEternityWarden(way, constellation, trait, artefact, general);
}
void SaurusEternityWarden::Init() {
if (!s_registered) {
static FactoryMethod factoryMethod = {
Create,
SeraphonBase::ValueToString,
SeraphonBase::EnumStringToInt,
ComputePoints,
{
EnumParameter("Way of the Seraphon", g_wayOfTheSeraphon[0], g_wayOfTheSeraphon),
EnumParameter("Constellation", g_constellation[0], g_constellation),
EnumParameter("Command Trait", g_saurusCommandTrait[0], g_saurusCommandTrait),
EnumParameter("Artefact", g_celestialRelicsOfTheWarrior[0], g_celestialRelicsOfTheWarrior),
BoolParameter("General")
},
ORDER,
{SERAPHON}
};
s_registered = UnitFactory::Register("Saurus Eternity Warden", factoryMethod);
}
}
int SaurusEternityWarden::generateHits(int unmodifiedHitRoll, const Weapon *weapon, const Unit *unit) const {
// Cold Ferocity
if ((unmodifiedHitRoll == 6) && (weapon->name() == m_mace.name())) {
return 2;
}
return SeraphonBase::generateHits(unmodifiedHitRoll, weapon, unit);
}
int SaurusEternityWarden::ComputePoints(const ParameterList& /*parameters*/) {
return g_pointsPerUnit;
}
} //namespace Seraphon
| 40.902439 | 154 | 0.640429 | rweyrauch |
fa436636d8dac56b1c2ef14b9a1b811fc6eae866 | 10,898 | hpp | C++ | include/algebra/array/multi_array.hpp | hyperpower/Nablla | 5a9be9f3b064a235572a1a2c9c5c2c19118697c5 | [
"MIT"
] | null | null | null | include/algebra/array/multi_array.hpp | hyperpower/Nablla | 5a9be9f3b064a235572a1a2c9c5c2c19118697c5 | [
"MIT"
] | null | null | null | include/algebra/array/multi_array.hpp | hyperpower/Nablla | 5a9be9f3b064a235572a1a2c9c5c2c19118697c5 | [
"MIT"
] | null | null | null | /************************
// \file multi_array.hpp
// \brief
//
// \author czhou
// \date 20 janv. 2018
***********************/
#ifndef MULTI_ARRAY_HPP_
#define MULTI_ARRAY_HPP_
#include <iostream>
#include <assert.h>
#include "algebra/algebra_define.hpp"
#include <array>
#include "array_list.hpp"
namespace carpio {
template<typename T, St DIM>
class MultiArray_ {
public:
static const St Dim = DIM;
// type definitions===================
typedef T value_t;
typedef MultiArray_<value_t, Dim> Self;
typedef MultiArray_<value_t, Dim>* pSelf;
typedef T* pointer;
typedef const T* const_pointer;
typedef T& reference;
typedef const T& const_reference;
typedef St size_type;
typedef St difference_type;
typedef typename ArrayListT_<value_t>::iterator iterator;
typedef typename ArrayListT_<value_t>::const_iterator const_iterator;
private:
std::array<St, Dim> m_len;
ArrayListT_<value_t> m_mp;
public:
//constructor==========================
MultiArray_(){
m_len.fill(0);
}
MultiArray_(const Self& a){
this->m_len = a.m_len;
this->m_mp = a.m_mp;
}
MultiArray_(St iLen, St jLen= 0, St kLen= 0){
St len = iLen;
this->m_len[0] = iLen;
if (Dim >= 2) {
ASSERT(iLen > 0 && jLen > 0);
this->m_len[1] = jLen;
len *= jLen;
}
if (Dim == 3) {
ASSERT(iLen > 0 && jLen > 0 && kLen > 0);
this->m_len[2] = kLen;
len *= kLen;
}
this->m_mp.reconstruct(len);
}
void reconstruct(St iLen, St jLen = 0, St kLen= 0){
St len = iLen;
this->m_len[0] = iLen;
if (Dim >= 2) {
ASSERT(iLen > 0 && jLen > 0);
this->m_len[1] = jLen;
len *= jLen;
}
if (Dim == 3) {
ASSERT(iLen > 0 && jLen > 0 && kLen > 0);
this->m_len[2] = kLen;
len *= kLen;
}
this->m_mp.reconstruct(len);
}
//=============================================
MultiArray_<T, DIM>& operator=(const MultiArray_<T, DIM>& a){
if (this == &a) {
return *this;
}
this->m_len = a.m_len;
this->m_mp = a.m_mp;
return *this;
}
//=============================================
~MultiArray_() {
}
//Capacity=====================================
St size() const {
return m_mp.size();
}
St size_i() const {
return m_len[0];
}
St size_j() const {
return Dim >= 2 ? m_len[1] : 0;
}
St size_k() const {
return Dim >= 3 ? m_len[2] : 0;
}
bool empty() const {
return m_mp.empty();
}
/*
* iterator
*/
iterator begin() {
return m_mp.begin();
}
const_iterator begin() const {
return m_mp.begin();
}
iterator end() {
return m_mp.end();
}
const_iterator end() const {
return m_mp.end();
}
//Element access===============================
St to_1d_idx(St i, St j = 0, St k = 0) const{
ASSERT(i < this->m_len[0]);
if (Dim >= 2)
ASSERT(j < this->m_len[1]);
if (Dim >= 3)
ASSERT(k < this->m_len[2]);
std::array<St, Dim> inp;
inp[0] = i;
if (Dim >= 2) {
inp[1] = j;
}
if (Dim >= 3) {
inp[2] = k;
}
St idx = 0;
for (St ii = 0; ii < Dim; ii++) {
St b = 1;
for (St jj = ii + 1; jj < Dim; jj++) {
b *= m_len[jj];
}
idx += b * inp[ii];
}
return idx;
}
reference at(St i, St j= 0, St k= 0){
St idx = to_1d_idx(i, j, k);
return m_mp[idx];
}
const_reference at(St i, St j = 0, St k = 0) const{
St idx = to_1d_idx(i, j, k);
return m_mp[idx];
}
reference operator()(St i, St j = 0, St k = 0){
return at(i, j, k);
}
const_reference operator()(St i, St j = 0, St k = 0) const{
return at(i, j, k);
}
reference at_1d(St i){ return m_mp[i];}
const_reference at_1d(St i) const{ return m_mp[i];}
T get(St i, St j = 0, St k = 0){
return at(i, j, k);
}
void set(const T& value, St i, St j = 0, St k = 0){
this->at(i, j, k) = value;
}
void assign(const T& value){
m_mp.assign(value);
}
//element access===============================
// T* getpValue(St i, St = 0, St = 0); //not good
inline bool check_idx(St dim, St idx) const {
ASSERT(dim < Dim);
if (idx >= 0 && idx < m_len[dim]) {
return true;
} else {
return false;
}
}
inline bool check_idx_ijk(St i, St j, St k) const {
return check_idx(0, i) && ((Dim >= 2) ? check_idx(1, j) : true)
&& ((Dim >= 3) ? check_idx(2, k) : true);
}
inline St count_equal(const T& nd) const { //overload ==
return m_mp.count_equal(nd);
}
};
template<typename T, St DIM>
class MultiArrayV_ {
public:
static const St Dim = DIM;
// type definitions===================
typedef T value_t;
typedef MultiArrayV_<value_t, Dim> Self;
typedef MultiArrayV_<value_t, Dim>& ref_Self;
typedef const MultiArrayV_<value_t, Dim>& const_ref_Self;
typedef MultiArrayV_<value_t, Dim>* pSelf;
typedef T* pointer;
typedef const T* const_pointer;
typedef T& reference;
typedef const T& const_reference;
typedef St size_type;
typedef St difference_type;
typedef typename ArrayListT_<value_t>::iterator iterator;
typedef typename ArrayListT_<value_t>::const_iterator const_iterator;
private:
std::array<St, Dim> m_len;
ArrayListV_<value_t> m_mp;
public:
//constructor==========================
MultiArrayV_(){
m_len.fill(0);
}
MultiArrayV_(const Self& a):
m_len(a.m_len), m_mp(a.m_mp){
}
MultiArrayV_(St iLen, St jLen= 0, St kLen= 0){
St len = iLen;
this->m_len[0] = iLen;
if (Dim >= 2) {
ASSERT(iLen > 0 && jLen > 0);
this->m_len[1] = jLen;
len *= jLen;
}
if (Dim >= 3) {
ASSERT(iLen > 0 && jLen > 0 && kLen > 0);
this->m_len[2] = kLen;
len *= kLen;
}
this->m_mp.reconstruct(len);
}
void reconstruct(St iLen, St jLen = 0, St kLen= 0){
St Len = 0;
this->m_len[0] = iLen;
if (Dim == 1) {
Len = iLen;
}
if (Dim >= 2) {
ASSERT(iLen > 0 && jLen > 0);
this->m_len[1] = jLen;
Len = iLen * jLen;
}
if (Dim >= 3) {
ASSERT(iLen > 0 && jLen > 0 && kLen > 0);
this->m_len[2] = kLen;
Len = iLen * jLen * kLen;
}
this->m_mp.reconstruct(Len);
}
//=============================================
ref_Self operator=(const Self& a){
if (this == &a) {
return *this;
}
this->m_len = a.m_len;
this->m_mp = a.m_mp;
return *this;
}
//=============================================
~MultiArrayV_() {
}
//Capacity=====================================
St size() const {
return m_mp.size();
}
St size_i() const {
return m_len[0];
}
St size_j() const {
return Dim >= 2 ? m_len[1] : 0;
}
St size_k() const {
return Dim >= 3 ? m_len[2] : 0;
}
bool empty() const {
return m_mp.empty();
}
bool is_compatible(const Self& other) const{
for(St i = 0; i< Dim;++i){
if(m_len[i] != other.m_len[i]){
return false;
}
}
return true;
}
/*
* iterator
*/
iterator begin() {
return m_mp.begin();
}
const_iterator begin() const {
return m_mp.begin();
}
iterator end() {
return m_mp.end();
}
const_iterator end() const {
return m_mp.end();
}
//Element access===============================
St to_1d_idx(St i, St j = 0, St k = 0) const{
ASSERT(i < this->m_len[0]);
if (Dim >= 2)
ASSERT(j < this->m_len[1]);
if (Dim >= 3)
ASSERT(k < this->m_len[2]);
std::array<St, Dim> inp;
inp[0] = i;
if (Dim >= 2) {
inp[1] = j;
}
if (Dim >= 3) {
inp[2] = k;
}
St idx = 0;
for (St ii = 0; ii < Dim; ii++) {
St b = 1;
for (St jj = ii + 1; jj < Dim; jj++) {
b *= m_len[jj];
}
idx += b * inp[ii];
}
return idx;
}
reference at(const St& i,
const St& j= 0,
const St& k= 0){
St idx = to_1d_idx(i, j, k);
return m_mp[idx];
}
const_reference at(const St& i,
const St& j = 0,
const St& k = 0) const{
St idx = to_1d_idx(i, j, k);
return m_mp[idx];
}
reference operator()(const St& i,
const St& j = 0,
const St& k = 0){
return at(i, j, k);
}
const_reference operator()(const St i,
const St j = 0,
const St k = 0) const{
return at(i, j, k);
}
reference at_1d(St i){ return m_mp[i];}
const_reference at_1d(St i) const{ return m_mp[i];}
T get(St i, St j = 0, St k = 0){
return at(i, j, k);
}
void set(const T& value, St i, St j = 0, St k = 0){
this->at(i, j, k) = value;
}
void assign(const T& value){
m_mp.assign(value);
}
T max() const {
return this->m_mp.max();
}
T min() const {
return this->m_mp.min();
}
void abs(){
this->m_mp.abs();
}
T norm1() const{
return this->m_mp.norm1();
}
T norm2() const{
return this->m_mp.norm2();
}
T norminf() const{
return this->m_mp.norminf();
}
//element access===============================
inline bool check_idx(St dim, St idx) const {
ASSERT(dim < Dim);
if (idx >= 0 && idx < m_len[dim]) {
return true;
} else {
return false;
}
}
inline bool check_idx_ijk(St i, St j, St k) const {
return check_idx(0, i) && ((Dim >= 2) ? check_idx(1, j) : true)
&& ((Dim >= 3) ? check_idx(2, k) : true);
}
inline St count_equal(const T& nd) const { //overload ==
return m_mp.count_equal(nd);
}
// operator ====================================
Self operator-(){
Self res(*this);
res.m_mp = -res.m_mp;
return res;
}
ref_Self operator+=(const Self& a) {
ASSERT(this->is_compatible(a));
m_mp += a.m_mp;
return *this;
}
ref_Self operator-=(const Self& a) {
ASSERT(this->is_compatible(a));
m_mp -= a.m_mp;
return *this;
}
ref_Self operator*=(const Self& a) {
ASSERT(this->is_compatible(a));
m_mp *= a.m_mp;
return *this;
}
ref_Self operator/=(const Self& a) {
ASSERT(this->is_compatible(a));
m_mp /= a.m_mp;
return *this;
}
ref_Self operator+=(const Vt& a) {
m_mp += a;
return *this;
}
ref_Self operator-=(const Vt& a) {
m_mp -= a;
return *this;
}
ref_Self operator*=(const Vt& a) {
m_mp *= a;
return *this;
}
ref_Self operator/=(const Vt& a) {
m_mp /= a;
return *this;
}
};
template<typename T, St DIM>
MultiArrayV_<T, DIM> Abs(const MultiArrayV_<T, DIM> a){
MultiArrayV_<T, DIM> res(a);
}
}
#endif /* MULTI_ARRAY_HPP */
| 22.751566 | 73 | 0.497706 | hyperpower |
fa43abe574becae19946a822d743f83aaf3c239e | 561 | cpp | C++ | infer/tests/build_systems/deduplicate_template_warnings/src/templates.cpp | JacobBarthelmeh/infer | 12c582a69855e17a2cf9c7b6cdf7f8e9c71e5341 | [
"MIT"
] | 14,499 | 2015-06-11T16:00:28.000Z | 2022-03-31T23:43:54.000Z | infer/tests/build_systems/deduplicate_template_warnings/src/templates.cpp | JacobBarthelmeh/infer | 12c582a69855e17a2cf9c7b6cdf7f8e9c71e5341 | [
"MIT"
] | 1,529 | 2015-06-11T16:55:30.000Z | 2022-03-27T15:59:46.000Z | infer/tests/build_systems/deduplicate_template_warnings/src/templates.cpp | JacobBarthelmeh/infer | 12c582a69855e17a2cf9c7b6cdf7f8e9c71e5341 | [
"MIT"
] | 2,225 | 2015-06-11T16:36:10.000Z | 2022-03-31T05:16:59.000Z | /*
* Copyright (c) Facebook, Inc. and its affiliates.
*
* This source code is licensed under the MIT license found in the
* LICENSE file in the root directory of this source tree.
*/
// we should only report one dead store warning on this file
template <class T>
T* unused_var_template_bad() {
int i = 42;
return 0;
}
int* unused_var_template1_bad() { return unused_var_template_bad<int>(); }
char* unused_var_template2_bad() { return unused_var_template_bad<char>(); }
long* unused_var_template3_bad() { return unused_var_template_bad<long>(); }
| 26.714286 | 76 | 0.736185 | JacobBarthelmeh |
fa459b841083b74b712407ef9cafc530e61568f7 | 5,207 | cpp | C++ | TrigBatch.cpp | TheFakeMontyOnTheRun/gles2-renderer | 76ed7aba3fa19cf34ec9ed27ce101d3ebfe1c07f | [
"BSD-2-Clause"
] | 1 | 2018-04-05T14:53:03.000Z | 2018-04-05T14:53:03.000Z | TrigBatch.cpp | TheFakeMontyOnTheRun/gles2-renderer | 76ed7aba3fa19cf34ec9ed27ce101d3ebfe1c07f | [
"BSD-2-Clause"
] | null | null | null | TrigBatch.cpp | TheFakeMontyOnTheRun/gles2-renderer | 76ed7aba3fa19cf34ec9ed27ce101d3ebfe1c07f | [
"BSD-2-Clause"
] | null | null | null | //
// Created by monty on 25/02/16.
//
#include "glm/glm.hpp"
#if defined(__ANDROID__ ) || defined(__EMSCRIPTEN__) || defined(MESA_GLES2) || defined(TARGET_IOS)
#ifdef __APPLE__
#if TARGET_IOS
#import <OpenGLES/ES2/gl.h>
#import <OpenGLES/ES2/glext.h>
#else
#import <OpenGL/OpenGL.h>
#import <OpenGL/gl3.h>
#endif
#else
#include <GLES2/gl2.h>
#include <GLES2/gl2ext.h>
#include <EGL/egl.h>
#endif
#endif
#include <memory>
#include <iostream>
#include <sstream>
#include <unordered_set>
#include <map>
#include <EASTL/vector.h>
#include <EASTL/array.h>
using eastl::vector;
using eastl::array;
#include "NativeBitmap.h"
#include "Material.h"
#include "Trig.h"
#include "TrigBatch.h"
namespace odb {
void TrigBatch::draw(unsigned int vertexAttributePosition,
unsigned int textureCoordinatesAttributePosition) {
#if defined(__ANDROID__ ) || defined(__EMSCRIPTEN__) || defined(MESA_GLES2) || defined(TARGET_IOS)
glVertexAttribPointer(vertexAttributePosition, 3, GL_FLOAT, GL_FALSE, 3 * sizeof(float),
vertex);
glVertexAttribPointer(textureCoordinatesAttributePosition, 2, GL_FLOAT, GL_FALSE,
2 * sizeof(float), uv);
glDrawArrays(GL_TRIANGLES, 0, vertexCount);
#endif
}
void TrigBatch::draw(unsigned int vertexAttributePosition,
unsigned int textureCoordinatesAttributePosition, unsigned int normalAttributePosition, unsigned int tangentVectorShaderPosition) {
#if defined(__ANDROID__ ) || defined(__EMSCRIPTEN__) || defined(MESA_GLES2) || defined(TARGET_IOS)
glVertexAttribPointer(vertexAttributePosition, 3, GL_FLOAT, GL_FALSE, 3 * sizeof(float),
vertex);
glVertexAttribPointer(textureCoordinatesAttributePosition, 2, GL_FLOAT, GL_FALSE,
2 * sizeof(float), uv);
glVertexAttribPointer(normalAttributePosition, 3, GL_FLOAT, GL_TRUE,
sizeof(float) * 3, normal);
glVertexAttribPointer(tangentVectorShaderPosition, 3, GL_FLOAT, GL_FALSE,
sizeof(float) * 3, normaltangent);
glDrawArrays(GL_TRIANGLES, 0, vertexCount);
#endif
}
TrigBatch::TrigBatch(const vector<Trig> &triangles) {
size_t size = triangles.size();
cachedMeshData = new float[5 * 3 * size];
vertex = new float[3 * 3 * size];
normal = new float[3 * 3 * size];
normaltangent = new float[3 * 3 * size];
uv = new float[3 * 2 * size];
int vertexIndex = 0;
int normalIndex = 0;
int normalTangentIndex = 0;
int uvIndex = 0;
int meshIndex = 0;
vertexCount = 0;
for (auto &trig : triangles) {
cachedMeshData[ meshIndex++ ] = trig.p0.x;
cachedMeshData[ meshIndex++ ] = trig.p0.y;
cachedMeshData[ meshIndex++ ] = trig.p0.z;
cachedMeshData[ meshIndex++ ] = trig.t0.x;
cachedMeshData[ meshIndex++ ] = trig.t0.y;
cachedMeshData[ meshIndex++ ] = trig.p1.x;
cachedMeshData[ meshIndex++ ] = trig.p1.y;
cachedMeshData[ meshIndex++ ] = trig.p1.z;
cachedMeshData[ meshIndex++ ] = trig.t1.x;
cachedMeshData[ meshIndex++ ] = trig.t1.y;
cachedMeshData[ meshIndex++ ] = trig.p2.x;
cachedMeshData[ meshIndex++ ] = trig.p2.y;
cachedMeshData[ meshIndex++ ] = trig.p2.z;
cachedMeshData[ meshIndex++ ] = trig.t2.x;
cachedMeshData[ meshIndex++ ] = trig.t2.y;
vertex[vertexIndex++] = trig.p0.x;
vertex[vertexIndex++] = trig.p0.y;
vertex[vertexIndex++] = trig.p0.z;
normal[normalIndex++] = trig.n0.x;
normal[normalIndex++] = trig.n0.y;
normal[normalIndex++] = trig.n0.z;
normaltangent[normalTangentIndex++] = trig.nt0.x;
normaltangent[normalTangentIndex++] = trig.nt0.y;
normaltangent[normalTangentIndex++] = trig.nt0.z;
uv[uvIndex++] = trig.t0.x;
uv[uvIndex++] = trig.t0.y;
++vertexCount;
vertex[vertexIndex++] = trig.p1.x;
vertex[vertexIndex++] = trig.p1.y;
vertex[vertexIndex++] = trig.p1.z;
normal[normalIndex++] = trig.n1.x;
normal[normalIndex++] = trig.n1.y;
normal[normalIndex++] = trig.n1.z;
normaltangent[normalTangentIndex++] = trig.nt1.x;
normaltangent[normalTangentIndex++] = trig.nt1.y;
normaltangent[normalTangentIndex++] = trig.nt1.z;
uv[uvIndex++] = trig.t1.x;
uv[uvIndex++] = trig.t1.y;
++vertexCount;
vertex[vertexIndex++] = trig.p2.x;
vertex[vertexIndex++] = trig.p2.y;
vertex[vertexIndex++] = trig.p2.z;
normal[normalIndex++] = trig.n2.x;
normal[normalIndex++] = trig.n2.y;
normal[normalIndex++] = trig.n2.z;
normaltangent[normalTangentIndex++] = trig.nt2.x;
normaltangent[normalTangentIndex++] = trig.nt2.y;
normaltangent[normalTangentIndex++] = trig.nt2.z;
uv[uvIndex++] = trig.t2.x;
uv[uvIndex++] = trig.t2.y;
++vertexCount;
}
}
float *TrigBatch::getVertexData() {
return this->cachedMeshData;
}
int TrigBatch::getVertexCount() {
return this->vertexCount;
}
float *TrigBatch::getUVData() {
return this->uv;
}
float *TrigBatch::getNormalData() {
return this->normal;
}
unsigned short *TrigBatch::getIndices() {
unsigned short *toReturn = new unsigned short[ vertexCount ];
for ( unsigned short c = 0; c < vertexCount; ++c ) {
toReturn[ c ] = c;
}
return toReturn;
}
int TrigBatch::getIndicesCount() {
return vertexCount;
}
}
| 29.252809 | 153 | 0.673132 | TheFakeMontyOnTheRun |
fa490073c133f6add5e423d69c2ba6046a6935e4 | 1,636 | cpp | C++ | cpp/subprojects/common/src/common/sampling/weight_vector_dense.cpp | mrapp-ke/SyndromeLearner | ed18c282949bebbc8e1dd5d2ddfb0b224ee71293 | [
"MIT"
] | null | null | null | cpp/subprojects/common/src/common/sampling/weight_vector_dense.cpp | mrapp-ke/SyndromeLearner | ed18c282949bebbc8e1dd5d2ddfb0b224ee71293 | [
"MIT"
] | null | null | null | cpp/subprojects/common/src/common/sampling/weight_vector_dense.cpp | mrapp-ke/SyndromeLearner | ed18c282949bebbc8e1dd5d2ddfb0b224ee71293 | [
"MIT"
] | 1 | 2022-03-08T22:06:56.000Z | 2022-03-08T22:06:56.000Z | #include "common/sampling/weight_vector_dense.hpp"
template<class T>
DenseWeightVector<T>::DenseWeightVector(uint32 numElements)
: DenseWeightVector<T>(numElements, false) {
}
template<class T>
DenseWeightVector<T>::DenseWeightVector(uint32 numElements, bool init)
: vector_(DenseVector<T>(numElements, init)), numNonZeroWeights_(0) {
}
template<class T>
typename DenseWeightVector<T>::iterator DenseWeightVector<T>::begin() {
return vector_.begin();
}
template<class T>
typename DenseWeightVector<T>::iterator DenseWeightVector<T>::end() {
return vector_.end();
}
template<class T>
typename DenseWeightVector<T>::const_iterator DenseWeightVector<T>::cbegin() const {
return vector_.cbegin();
}
template<class T>
typename DenseWeightVector<T>::const_iterator DenseWeightVector<T>::cend() const {
return vector_.cend();
}
template<class T>
uint32 DenseWeightVector<T>::getNumElements() const {
return vector_.getNumElements();
}
template<class T>
uint32 DenseWeightVector<T>::getNumNonZeroWeights() const {
return numNonZeroWeights_;
}
template<class T>
void DenseWeightVector<T>::setNumNonZeroWeights(uint32 numNonZeroWeights) {
numNonZeroWeights_ = numNonZeroWeights;
}
template<class T>
bool DenseWeightVector<T>::hasZeroWeights() const {
return numNonZeroWeights_ < vector_.getNumElements();
}
template<class T>
float64 DenseWeightVector<T>::getWeight(uint32 pos) const {
return (float64) vector_[pos];
}
template class DenseWeightVector<uint8>;
template class DenseWeightVector<uint32>;
template class DenseWeightVector<float32>;
template class DenseWeightVector<float64>;
| 25.169231 | 84 | 0.76956 | mrapp-ke |