hexsha stringlengths 40 40 | size int64 19 11.4M | ext stringclasses 13
values | lang stringclasses 1
value | max_stars_repo_path stringlengths 3 270 | max_stars_repo_name stringlengths 5 110 | max_stars_repo_head_hexsha stringlengths 40 40 | max_stars_repo_licenses listlengths 1 9 | max_stars_count float64 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 3 270 | max_issues_repo_name stringlengths 5 116 | max_issues_repo_head_hexsha stringlengths 40 78 | max_issues_repo_licenses listlengths 1 9 | max_issues_count float64 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 3 270 | max_forks_repo_name stringlengths 5 116 | max_forks_repo_head_hexsha stringlengths 40 78 | max_forks_repo_licenses listlengths 1 9 | max_forks_count float64 1 105k ⌀ | max_forks_repo_forks_event_min_datetime stringlengths 24 24 ⌀ | max_forks_repo_forks_event_max_datetime stringlengths 24 24 ⌀ | content stringlengths 19 11.4M | avg_line_length float64 1.93 229k | max_line_length int64 12 688k | alphanum_fraction float64 0.07 0.99 | matches listlengths 1 10 |
|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|
1497bf3ba8d686001b0c5f00cd96fb73e8ce45dd | 1,532 | hpp | C++ | source/problem/Green-Naghdi/discretization_EHDG/kernels_preprocessor/ehdg_gn_pre_serial.hpp | kazbekkm/dgswemv2 | 69f12ec10372646052928bf1c94e6de5b0269300 | [
"MIT"
] | 5 | 2018-05-30T08:43:10.000Z | 2021-12-14T18:33:10.000Z | source/problem/Green-Naghdi/discretization_EHDG/kernels_preprocessor/ehdg_gn_pre_serial.hpp | kazbekkm/dgswemv2 | 69f12ec10372646052928bf1c94e6de5b0269300 | [
"MIT"
] | 57 | 2018-05-08T21:44:14.000Z | 2019-11-07T17:13:30.000Z | source/problem/Green-Naghdi/discretization_EHDG/kernels_preprocessor/ehdg_gn_pre_serial.hpp | kazbekkm/dgswemv2 | 69f12ec10372646052928bf1c94e6de5b0269300 | [
"MIT"
] | 7 | 2018-05-07T21:50:49.000Z | 2021-04-30T14:02:02.000Z | #ifndef EHDG_GN_PRE_SERIAL_HPP
#define EHDG_GN_PRE_SERIAL_HPP
#include "problem/Green-Naghdi/problem_preprocessor/gn_pre_init_data.hpp"
#include "ehdg_gn_pre_dbath_serial.hpp"
namespace GN {
namespace EHDG {
void Problem::preprocessor_serial(ProblemDiscretizationType& discretization,
ProblemGlobalDataType& global_data,
const ProblemStepperType& stepper,
const ProblemInputType& problem_specific_input) {
SWE_SIM::Problem::preprocessor_serial(
discretization, global_data, stepper.GetFirstStepper(), problem_specific_input);
GN::initialize_data_serial(discretization.mesh);
uint dc_global_dof_offset = 0;
Problem::initialize_global_dc_problem_serial(discretization, dc_global_dof_offset);
const uint n_global_dofs = (discretization.mesh.GetP() + 1) * GN::n_dimensions;
global_data.w1_hat_w1_hat.resize(n_global_dofs * dc_global_dof_offset, n_global_dofs * dc_global_dof_offset);
global_data.w1_hat_rhs.resize(n_global_dofs * dc_global_dof_offset);
Problem::compute_bathymetry_derivatives_serial(discretization, global_data);
uint n_stages = stepper.GetFirstStepper().GetNumStages() > stepper.GetSecondStepper().GetNumStages()
? stepper.GetFirstStepper().GetNumStages()
: stepper.GetSecondStepper().GetNumStages();
discretization.mesh.CallForEachElement([n_stages](auto& elt) { elt.data.resize(n_stages + 1); });
}
}
}
#endif | 42.555556 | 113 | 0.72389 | [
"mesh"
] |
149931e2c4ede82a86005b12b1436cc57bf5e227 | 1,041 | cc | C++ | src/comm/segment/bmm_segment.cc | jdisearch/isearch1 | 272bd4ab0dc82d9e33c8543474b1294569947bb3 | [
"Apache-2.0"
] | 3 | 2021-08-18T09:59:42.000Z | 2021-09-07T03:11:28.000Z | src/comm/segment/bmm_segment.cc | jdisearch/isearch1 | 272bd4ab0dc82d9e33c8543474b1294569947bb3 | [
"Apache-2.0"
] | null | null | null | src/comm/segment/bmm_segment.cc | jdisearch/isearch1 | 272bd4ab0dc82d9e33c8543474b1294569947bb3 | [
"Apache-2.0"
] | null | null | null | #include "bmm_segment.h"
BmmSegment::BmmSegment()
{
}
BmmSegment::~BmmSegment()
{
}
void BmmSegment::ConcreteSplit(const string& str, uint32_t appid, vector<string>& bmm_list){
iutf8string phrase(str);
int maxlen = MAX_WORD_LEN;
int len_phrase = phrase.length();
int i = len_phrase, j = 0;
while (i > 0) {
int start = i - maxlen;
if (start < 0)
start = 0;
iutf8string phrase_sub = phrase.utf8substr(start, i-start);
for (j = 0; j < phrase_sub.length(); j++) {
if (j == phrase_sub.length() - 1)
break;
iutf8string key = phrase_sub.utf8substr(j, phrase_sub.length()-j);
if (WordValid(key.stlstring(), appid) == true) {
bmm_list.insert(bmm_list.begin(), key.stlstring());
i -= key.length();
break;
}
}
if (j == phrase_sub.length() - 1) {
bmm_list.insert(bmm_list.begin(), "" + phrase_sub[j]);
i--;
}
}
return;
} | 27.394737 | 92 | 0.528338 | [
"vector"
] |
149aa77b4e08641ce1ac07a153126b80559ee035 | 6,057 | cpp | C++ | src/learn/reinforcement_learn.cpp | SakodaShintaro/Miacis | af3508076660cc6e19186f17fa436499e32164f5 | [
"BSD-3-Clause"
] | 10 | 2019-05-14T12:54:49.000Z | 2022-02-28T12:02:52.000Z | src/learn/reinforcement_learn.cpp | SakodaShintaro/Miacis | af3508076660cc6e19186f17fa436499e32164f5 | [
"BSD-3-Clause"
] | null | null | null | src/learn/reinforcement_learn.cpp | SakodaShintaro/Miacis | af3508076660cc6e19186f17fa436499e32164f5 | [
"BSD-3-Clause"
] | null | null | null | #include "../model/infer_model.hpp"
#include "game_generator.hpp"
#include "hyperparameter_loader.hpp"
#include "learn.hpp"
#include <torch/torch.h>
void reinforcementLearn() {
// clang-format off
SearchOptions search_options;
HyperparameterLoader settings("reinforcement_learn_settings.txt");
float lambda = settings.get<float>("lambda");
float per_alpha = settings.get<float>("per_alpha");
float Q_dist_lambda = settings.get<float>("Q_dist_lambda");
float noise_epsilon = settings.get<float>("noise_epsilon");
float noise_alpha = settings.get<float>("noise_alpha");
float train_rate_threshold = settings.get<float>("train_rate_threshold");
search_options.temperature_x1000 = settings.get<float>("Q_dist_temperature") * 1000;
search_options.C_PUCT_x1000 = settings.get<float>("C_PUCT") * 1000;
search_options.use_fp16 = settings.get<bool>("use_fp16");
search_options.draw_turn = settings.get<int64_t>("draw_turn");
search_options.random_turn = settings.get<int64_t>("random_turn");
search_options.thread_num_per_gpu = settings.get<int64_t>("thread_num_per_gpu");
search_options.search_limit = settings.get<int64_t>("search_limit");
search_options.search_batch_size = settings.get<int64_t>("search_batch_size");
int64_t batch_size = settings.get<int64_t>("batch_size");
int64_t max_step_num = settings.get<int64_t>("max_step_num");
int64_t update_interval = settings.get<int64_t>("update_interval");
int64_t batch_size_per_gen = settings.get<int64_t>("batch_size_per_gen");
int64_t worker_num_per_thread = settings.get<int64_t>("worker_num_per_thread");
int64_t max_stack_size = settings.get<int64_t>("max_stack_size");
int64_t first_wait = settings.get<int64_t>("first_wait");
int64_t output_interval = settings.get<int64_t>("output_interval");
int64_t sleep_msec = settings.get<int64_t>("sleep_msec");
int64_t init_buffer_by_kifu = settings.get<int64_t>("init_buffer_by_kifu");
int64_t noise_mode = settings.get<int64_t>("noise_mode");
int64_t wait_sec_per_load = settings.get<int64_t>("wait_sec_per_load");
bool data_augmentation = settings.get<bool>("data_augmentation");
bool Q_search = settings.get<bool>("Q_search");
std::string train_kifu_path = settings.get<std::string>("train_kifu_path");
search_options.calibration_kifu_path = settings.get<std::string>("calibration_kifu_path");
// clang-format on
const std::string prefix = "reinforcement";
int64_t curr_step_num = loadStepNumFromValidLog(prefix + "_valid_log.txt");
//学習クラスを生成
LearnManager<LearningModel> learn_manager(prefix, curr_step_num);
//カテゴリカルモデルでもQをもとに探索したい場合
if (Q_search) {
search_options.P_coeff_x1000 = 0;
search_options.Q_coeff_x1000 = 1000;
}
//リプレイバッファの生成
ReplayBuffer replay_buffer(first_wait, max_stack_size, output_interval, lambda, per_alpha, data_augmentation);
if (init_buffer_by_kifu) {
replay_buffer.fillByKifu(train_kifu_path, train_rate_threshold);
}
//時間計測開始
Timer timer;
timer.start();
//GPUの数だけネットワーク,自己対局生成器を生成
size_t gpu_num = torch::getNumGPUs();
std::vector<std::unique_ptr<GameGenerator>> generators(gpu_num);
std::vector<std::thread> gen_threads;
for (uint64_t i = 0; i < gpu_num; i++) {
generators[i] = std::make_unique<GameGenerator>(search_options, worker_num_per_thread, Q_dist_lambda, noise_mode,
noise_epsilon, noise_alpha, replay_buffer, i);
gen_threads.emplace_back([&generators, i]() { generators[i]->genGames(); });
}
//学習ループ
for (int64_t step_num = curr_step_num + 1; step_num <= max_step_num; step_num++) {
//バッチサイズ分データを選択
std::vector<LearningData> curr_data = replay_buffer.makeBatch(batch_size);
//1回目はmakeBatch内で十分棋譜が貯まるまで待ち時間が発生する.その生成速度を計算
if (step_num == 1) {
float gen_speed = (float)first_wait / timer.elapsedSeconds();
if (sleep_msec == -1) {
sleep_msec = (int64_t)(batch_size * 1000 / (batch_size_per_gen * gen_speed));
}
std::ofstream ofs("gen_speed.txt");
dout(std::cout, ofs) << "gen_speed = " << gen_speed << " pos / sec, sleep_msec = " << sleep_msec << std::endl;
}
//学習用ネットワークは生成用ネットワークの先頭とGPUを共有しているのでロックをかける
generators.front()->gpu_mutex.lock();
//1ステップ学習し、損失を取得
torch::Tensor loss_sum = learn_manager.learnOneStep(curr_data, step_num);
//GPUを解放
generators.front()->gpu_mutex.unlock();
//replay_bufferのpriorityを更新
std::vector<float> loss_vec(loss_sum.data_ptr<float>(), loss_sum.data_ptr<float>() + batch_size);
replay_buffer.update(loss_vec);
//一定間隔でActorのパラメータをLearnerと同期
if (step_num % update_interval == 0) {
//学習パラメータを保存
learn_manager.saveModelAsDefaultName();
//各ネットワークで保存されたパラメータを読み込み
for (uint64_t i = 0; i < gpu_num; i++) {
generators[i]->gpu_mutex.lock();
//パラメータをロードするべきというシグナルを出す
generators[i]->need_load = true;
generators[i]->gpu_mutex.unlock();
}
//int8の場合は特にloadで時間がかかるのでその期間スリープ
std::this_thread::sleep_for(std::chrono::seconds(wait_sec_per_load));
}
//学習スレッドを眠らせることで擬似的にActorの数を増やす
std::this_thread::sleep_for(std::chrono::milliseconds(sleep_msec));
}
//生成スレッドを止める
for (uint64_t i = 0; i < gpu_num; i++) {
generators[i]->stop_signal = true;
}
for (std::thread& th : gen_threads) {
th.join();
}
std::cout << "finish reinforcementLearn" << std::endl;
} | 44.211679 | 122 | 0.643223 | [
"vector",
"model"
] |
149d9f1198e2a721b2048a731dea3fc885c496e8 | 1,521 | cc | C++ | code/tests/mathtest/vectortest.cc | gscept/nebula-trifid | e7c0a0acb05eedad9ed37a72c1bdf2d658511b42 | [
"BSD-2-Clause"
] | 67 | 2015-03-30T19:56:16.000Z | 2022-03-11T13:52:17.000Z | code/tests/mathtest/vectortest.cc | gscept/nebula-trifid | e7c0a0acb05eedad9ed37a72c1bdf2d658511b42 | [
"BSD-2-Clause"
] | 5 | 2015-04-15T17:17:33.000Z | 2016-02-11T00:40:17.000Z | code/tests/mathtest/vectortest.cc | gscept/nebula-trifid | e7c0a0acb05eedad9ed37a72c1bdf2d658511b42 | [
"BSD-2-Clause"
] | 34 | 2015-03-30T15:08:00.000Z | 2021-09-23T05:55:10.000Z | //------------------------------------------------------------------------------
// vectortest.cc
// (C) 2009 Radon Labs GmbH
//------------------------------------------------------------------------------
#include "stdneb.h"
#include "vectortest.h"
#include "math/vector.h"
#include "mathtestutil.h"
#include "stackalignment.h"
#include "testbase/stackdebug.h"
using namespace Math;
namespace Test
{
__ImplementClass(Test::VectorTest, 'VCTS', Test::TestCase);
//------------------------------------------------------------------------------
/**
*/
void
VectorTest::Run()
{
STACK_CHECKPOINT("Test::VectorTest::Run()");
// construction
vector t;
this->Verify(float4equal(t, float4(0.0, 0.0, 0.0, 0.0)));
vector z(t);
this->Verify(float4equal(z, float4(0.0, 0.0, 0.0, 0.0)));
vector v(1.0, 2.0, 3.0);
this->Verify(float4equal(v, float4(1.0, 2.0, 3.0, 0.0)));
vector v0(1.0f, 2.0f, 3.0f);
vector v1(4.0f, 3.0f, 2.0f);
vector v2(v0);
vector v3(v1);
this->Verify(v0 == v2);
this->Verify(v1 == v3);
this->Verify(v0 != v1);
this->Verify(v2 != v3);
this->Verify(v0 == float4(1.0f, 2.0f, 3.0f, 0.0));
// assignemt
v2 = v1;
this->Verify(v2 == v1);
v2 = v0;
this->Verify(v2 == v0);
// test 16-byte alignment of embedded members on the stack, if we use SSE/SSE2 on windows or
// xbox or ps3
#if (__WIN32__ && !defined(_XM_NO_INTRINSICS_)) || __XBOX360__ || __PS3__
{
testStackAlignment16<vector>(this);
}
#endif
}
} | 25.779661 | 96 | 0.510191 | [
"vector"
] |
14a165a1ca3ffcf26aa152ff15ad9113ebf88bdd | 566 | hpp | C++ | xgcp/xgcp_gyro_scatter.hpp | dhyan1272/pumi-pic | 52fe63537720a7c767b789ddf124873f7517de96 | [
"BSD-3-Clause"
] | null | null | null | xgcp/xgcp_gyro_scatter.hpp | dhyan1272/pumi-pic | 52fe63537720a7c767b789ddf124873f7517de96 | [
"BSD-3-Clause"
] | null | null | null | xgcp/xgcp_gyro_scatter.hpp | dhyan1272/pumi-pic | 52fe63537720a7c767b789ddf124873f7517de96 | [
"BSD-3-Clause"
] | null | null | null | #pragma once
#include "xgcp_mesh.hpp"
namespace xgcp {
void setGyroConfig(Input& input);
void printGyroConfig();
void createIonGyroRingMappings(o::Mesh* mesh, o::LOs& forward_map,
o::LOs& backward_map);
void gyroScatter(Mesh& mesh, PS_I* ptcls);
void gyroScatter(Mesh& mesh, PS_E* ptcls);
void gyroScatter(Mesh& mesh, PS_I* ptcls, o::LOs v2v, std::string scatterTagName);
void gyroSync(Mesh& mesh, const std::string& fwdTagName,
const std::string& bkwdTagName, const std::string& syncTagName);
}
| 26.952381 | 84 | 0.666078 | [
"mesh"
] |
14a2666b55f89289cb7594172421cc6bfafaef73 | 7,045 | hpp | C++ | expressions/scalar/ScalarCaseExpression.hpp | Hacker0912/quickstep-datalog | 1de22e7ab787b5efa619861a167a097ff6a4f549 | [
"Apache-2.0"
] | 82 | 2016-04-18T03:59:06.000Z | 2019-02-04T11:46:08.000Z | expressions/scalar/ScalarCaseExpression.hpp | Hacker0912/quickstep-datalog | 1de22e7ab787b5efa619861a167a097ff6a4f549 | [
"Apache-2.0"
] | 265 | 2016-04-19T17:52:43.000Z | 2018-10-11T17:55:08.000Z | expressions/scalar/ScalarCaseExpression.hpp | Hacker0912/quickstep-datalog | 1de22e7ab787b5efa619861a167a097ff6a4f549 | [
"Apache-2.0"
] | 68 | 2016-04-18T05:00:34.000Z | 2018-10-30T12:41:02.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.
**/
#ifndef QUICKSTEP_EXPRESSIONS_SCALAR_SCALAR_CASE_EXPRESSION_HPP_
#define QUICKSTEP_EXPRESSIONS_SCALAR_SCALAR_CASE_EXPRESSION_HPP_
#include <cstddef>
#include <memory>
#include <string>
#include <utility>
#include <vector>
#include "catalog/CatalogTypedefs.hpp"
#include "expressions/Expressions.pb.h"
#include "expressions/predicate/Predicate.hpp"
#include "expressions/scalar/Scalar.hpp"
#include "storage/StorageBlockInfo.hpp"
#include "types/TypedValue.hpp"
#include "types/containers/ColumnVector.hpp"
#include "utility/Macros.hpp"
#include "glog/logging.h"
namespace quickstep {
class ColumnVectorCache;
class TupleIdSequence;
class Type;
class ValueAccessor;
struct SubBlocksReference;
/** \addtogroup Expressions
* @{
*/
/**
* @brief A SQL CASE expression, which consists of one or more Predicates from
* WHEN clauses that map to Scalars which are evaluated conditionally
* for the first matching WHEN predicate. Also contains a Scalar for the
* ELSE case where no WHEN predicate matches.
* @note This class implements the most general form of a SQL case expression,
* a "searched CASE" expression. For other forms of the CASE expression
* (e.g. "simple CASE") the optimizer is responsible for resolving into
* this general form.
**/
class ScalarCaseExpression : public Scalar {
public:
/**
* @brief Constructor.
*
* @param result_type The Type for values produced by this expression. Must
* subsume the types of all result_expressions and
* else_result_expression.
* @param when_predicates A vector of Predicates, one for each WHEN clause,
* in descending order of priority. Will be moved-from.
* @param result_expressions A vector of Scalars, each of which is a THEN
* expression corresponding to the WHEN clause in the same position in
* when_predicates. Will be moved-from.
* @param else_result_expression A Scalar whose value will be used when none
* of the when_predicates match. This is a required parameter. SQL
* allows the ELSE clause of a CASE expression to be ommitted, in
* which case it defaults to NULL. For compliance with the SQL
* standard, an explicit ScalarLiteral with a NULL value should be
* supplied here for such cases.
**/
ScalarCaseExpression(const Type &result_type,
std::vector<std::unique_ptr<Predicate>> &&when_predicates,
std::vector<std::unique_ptr<Scalar>> &&result_expressions,
Scalar *else_result_expression);
~ScalarCaseExpression() override {
}
serialization::Scalar getProto() const override;
Scalar* clone() const override;
ScalarDataSource getDataSource() const override {
return kCaseExpression;
}
TypedValue getValueForSingleTuple(const ValueAccessor &accessor,
const tuple_id tuple) const override;
TypedValue getValueForJoinedTuples(
const ValueAccessor &left_accessor,
const tuple_id left_tuple_id,
const ValueAccessor &right_accessor,
const tuple_id right_tuple_id) const override;
bool hasStaticValue() const override {
return has_static_value_;
}
const TypedValue& getStaticValue() const override {
DCHECK(has_static_value_);
return static_value_;
}
attribute_id getAttributeIdForValueAccessor() const override {
if (fixed_result_expression_ != nullptr) {
return fixed_result_expression_->getAttributeIdForValueAccessor();
} else {
return -1;
}
}
ColumnVectorPtr getAllValues(ValueAccessor *accessor,
const SubBlocksReference *sub_blocks_ref,
ColumnVectorCache *cv_cache) const override;
ColumnVectorPtr getAllValuesForJoin(
ValueAccessor *left_accessor,
ValueAccessor *right_accessor,
const std::vector<std::pair<tuple_id, tuple_id>> &joined_tuple_ids,
ColumnVectorCache *cv_cache) const override;
protected:
void getFieldStringItems(
std::vector<std::string> *inline_field_names,
std::vector<std::string> *inline_field_values,
std::vector<std::string> *non_container_child_field_names,
std::vector<const Expression*> *non_container_child_fields,
std::vector<std::string> *container_child_field_names,
std::vector<std::vector<const Expression*>> *container_child_fields) const override;
private:
// Create and return a new ColumnVector by multiplexing the ColumnVectors
// containing results for individual CASE branches at the appropriate
// positions. 'output_size' is the total number of values in the output.
// '*source_sequence' indicates which positions actually have tuples in the
// input (if NULL, it is assumed there are no holes in the input).
// 'case_matches' are the sequences of tuple_ids matching each WHEN clause in
// order. 'else_matches' indicates the tuple_ids that did not match any of
// the explicit WHEN clauses. Similarly, '*case_results' are the values
// generated for the tuples matching each WHEN clause, and '*else_results'
// are the values generated for the ELSE tuples.
ColumnVectorPtr multiplexColumnVectors(
const std::size_t output_size,
const TupleIdSequence *source_sequence,
const std::vector<std::unique_ptr<TupleIdSequence>> &case_matches,
const TupleIdSequence &else_matches,
const std::vector<ColumnVectorPtr> &case_results,
const ColumnVectorPtr &else_result) const;
std::vector<std::unique_ptr<Predicate>> when_predicates_;
std::vector<std::unique_ptr<Scalar>> result_expressions_;
std::unique_ptr<Scalar> else_result_expression_;
// If the CASE always evaluates to the same branch, this points to the result
// expression for that branch. Note that this is different from having a
// static value, because the result expression itself can have a
// tuple-dependent value.
const Scalar *fixed_result_expression_;
bool has_static_value_;
TypedValue static_value_;
DISALLOW_COPY_AND_ASSIGN(ScalarCaseExpression);
};
/** @} */
} // namespace quickstep
#endif // QUICKSTEP_EXPRESSIONS_SCALAR_SCALAR_CASE_EXPRESSION_HPP_
| 38.288043 | 90 | 0.729312 | [
"vector"
] |
14a3a339ad3319f1067495e0c0332b45362b2608 | 828 | hpp | C++ | NWNXLib/Encoding.hpp | GideonCrawle/unified | 2a310e0012badfcc9675bd8c8554613b5354e21a | [
"MIT"
] | null | null | null | NWNXLib/Encoding.hpp | GideonCrawle/unified | 2a310e0012badfcc9675bd8c8554613b5354e21a | [
"MIT"
] | null | null | null | NWNXLib/Encoding.hpp | GideonCrawle/unified | 2a310e0012badfcc9675bd8c8554613b5354e21a | [
"MIT"
] | null | null | null | //
// Helper library to encode/decode various streams
//
#include <string>
#include <vector>
namespace NWNXLib::Encoding {
enum Locale
{
Default,
Western,
Russian,
};
Locale GetDefaultLocale();
void SetDefaultLocale(Locale locale);
void SetDefaultLocale(const std::string& locale);
std::string ToUTF8(const char *str, Locale locale = Default);
std::string FromUTF8(const char *str, Locale locale = Default);
std::string ToBase64(const std::vector<uint8_t>& in);
std::vector<uint8_t> FromBase64(const std::string &in);
//
// Convenience wrappers
//
static inline std::string ToUTF8(const std::string& str, Locale locale = Default)
{
return ToUTF8(str.c_str(), locale);
}
static inline std::string FromUTF8(const std::string& str, Locale locale = Default)
{
return FromUTF8(str.c_str(), locale);
}
}
| 19.714286 | 83 | 0.716184 | [
"vector"
] |
14a541e6bb74565b7e20231bc05dfc4b175b6851 | 4,134 | cpp | C++ | Userland/Libraries/LibWeb/HTML/Scripting/WindowEnvironmentSettingsObject.cpp | densogiaichned/serenity | 99c0b895fed02949b528437d6b450d85befde7a5 | [
"BSD-2-Clause"
] | 2 | 2022-02-16T02:12:38.000Z | 2022-02-20T18:40:41.000Z | Userland/Libraries/LibWeb/HTML/Scripting/WindowEnvironmentSettingsObject.cpp | densogiaichned/serenity | 99c0b895fed02949b528437d6b450d85befde7a5 | [
"BSD-2-Clause"
] | null | null | null | Userland/Libraries/LibWeb/HTML/Scripting/WindowEnvironmentSettingsObject.cpp | densogiaichned/serenity | 99c0b895fed02949b528437d6b450d85befde7a5 | [
"BSD-2-Clause"
] | null | null | null | /*
* Copyright (c) 2021, Luke Wilde <lukew@serenityos.org>
*
* SPDX-License-Identifier: BSD-2-Clause
*/
#include <LibWeb/Bindings/WindowObject.h>
#include <LibWeb/DOM/Document.h>
#include <LibWeb/HTML/Scripting/WindowEnvironmentSettingsObject.h>
namespace Web::HTML {
WindowEnvironmentSettingsObject::WindowEnvironmentSettingsObject(Window& window, JS::ExecutionContext& execution_context)
: EnvironmentSettingsObject(execution_context)
, m_window(window)
{
}
// https://html.spec.whatwg.org/multipage/window-object.html#set-up-a-window-environment-settings-object
void WindowEnvironmentSettingsObject::setup(AK::URL& creation_url, JS::ExecutionContext& execution_context)
{
// 1. Let realm be the value of execution context's Realm component.
auto* realm = execution_context.realm;
VERIFY(realm);
// 2. Let window be realm's global object.
// NOTE: We want to store the Window impl rather than the WindowObject.
auto& window = verify_cast<Bindings::WindowObject>(realm->global_object()).impl();
// 3. Let settings object be a new environment settings object whose algorithms are defined as follows:
// NOTE: See the functions defined for this class.
auto settings_object = adopt_own(*new WindowEnvironmentSettingsObject(window, execution_context));
// FIXME: 4. If reservedEnvironment is non-null, then:
// FIXME: 1. Set settings object's id to reservedEnvironment's id, target browsing context to reservedEnvironment's target browsing context, and active service worker to reservedEnvironment's active service worker.
// FIXME: 2. Set reservedEnvironment's id to the empty string.
// FIXME: 5. Otherwise, set settings object's id to a new unique opaque string, settings object's target browsing context to null, and settings object's active service worker to null.
settings_object->target_browsing_context = nullptr;
// FIXME: 6. Set settings object's creation URL to creationURL, settings object's top-level creation URL to topLevelCreationURL, and settings object's top-level origin to topLevelOrigin.
settings_object->creation_url = creation_url;
// 7. Set realm's [[HostDefined]] field to settings object.
realm->set_host_defined(move(settings_object));
}
// https://html.spec.whatwg.org/multipage/window-object.html#script-settings-for-window-objects:responsible-document
RefPtr<DOM::Document> WindowEnvironmentSettingsObject::responsible_document()
{
// Return window's associated Document.
return m_window->associated_document();
}
// https://html.spec.whatwg.org/multipage/window-object.html#script-settings-for-window-objects:api-url-character-encoding
String WindowEnvironmentSettingsObject::api_url_character_encoding()
{
// Return the current character encoding of window's associated Document.
return m_window->associated_document().encoding_or_default();
}
// https://html.spec.whatwg.org/multipage/window-object.html#script-settings-for-window-objects:api-base-url
AK::URL WindowEnvironmentSettingsObject::api_base_url()
{
// FIXME: Return the current base URL of window's associated Document.
// (This currently just returns the current document URL, not accounting for <base> elements and such)
return m_window->associated_document().url();
}
// https://html.spec.whatwg.org/multipage/window-object.html#script-settings-for-window-objects:concept-settings-object-origin
Origin WindowEnvironmentSettingsObject::origin()
{
// Return the origin of window's associated Document.
return m_window->associated_document().origin();
}
// https://html.spec.whatwg.org/multipage/window-object.html#script-settings-for-window-objects:concept-settings-object-cross-origin-isolated-capability
CanUseCrossOriginIsolatedAPIs WindowEnvironmentSettingsObject::cross_origin_isolated_capability()
{
// FIXME: Return true if both of the following hold, and false otherwise:
// 1. realm's agent cluster's cross-origin-isolation mode is "concrete", and
// 2. window's associated Document is allowed to use the "cross-origin-isolated" feature.
TODO();
}
}
| 47.517241 | 221 | 0.764635 | [
"object"
] |
14a545ca056d1ee0990707f51ff586e98f91ff63 | 33,842 | cc | C++ | src/yajlpp/yajlpp.cc | rzadp/lnav | 853ef11435e04717249ad2f643afffa510cddfc7 | [
"BSD-2-Clause"
] | null | null | null | src/yajlpp/yajlpp.cc | rzadp/lnav | 853ef11435e04717249ad2f643afffa510cddfc7 | [
"BSD-2-Clause"
] | null | null | null | src/yajlpp/yajlpp.cc | rzadp/lnav | 853ef11435e04717249ad2f643afffa510cddfc7 | [
"BSD-2-Clause"
] | null | null | null | /**
* Copyright (c) 2015, Timothy Stack
*
* All rights reserved.
*
* Redistribution and use in source and binary forms, with or without
* modification, are permitted provided that the following conditions are met:
*
* * Redistributions of source code must retain the above copyright notice, this
* list of conditions and the following disclaimer.
* * Redistributions in binary form must reproduce the above copyright notice,
* this list of conditions and the following disclaimer in the documentation
* and/or other materials provided with the distribution.
* * Neither the name of Timothy Stack nor the names of its contributors
* may be used to endorse or promote products derived from this software
* without specific prior written permission.
*
* THIS SOFTWARE IS PROVIDED BY THE REGENTS AND CONTRIBUTORS ''AS IS'' AND ANY
* EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED
* WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE
* DISCLAIMED. IN NO EVENT SHALL THE REGENTS OR CONTRIBUTORS BE LIABLE FOR ANY
* DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES
* (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES;
* LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON
* ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT
* (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS
* SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
*
* @file yajlpp.cc
*/
#include "config.h"
#include <pcrecpp.h>
#include "fmt/format.h"
#include "yajlpp.hh"
#include "yajlpp_def.hh"
#include "yajl/api/yajl_parse.h"
using namespace std;
const json_path_handler_base::enum_value_t json_path_handler_base::ENUM_TERMINATOR((const char *) nullptr, 0);
json_path_handler_base::json_path_handler_base(const string &property)
: jph_property(property.back() == '#' ?
property.substr(0, property.size() - 1) :
property),
jph_regex(pcrecpp::RE::QuoteMeta(property), PCRE_ANCHORED),
jph_is_array(property.back() == '#')
{
memset(&this->jph_callbacks, 0, sizeof(this->jph_callbacks));
}
static std::string scrub_pattern(const std::string &pattern)
{
static pcrecpp::RE CAPTURE(R"(\(\?\<\w+\>)");
std::string retval = pattern;
CAPTURE.GlobalReplace("(", &retval);
return retval;
}
json_path_handler_base::json_path_handler_base(const pcrepp &property)
: jph_property(scrub_pattern(property.p_pattern)),
jph_regex(property),
jph_is_array(property.p_pattern.back() == '#'),
jph_is_pattern_property(true)
{
memset(&this->jph_callbacks, 0, sizeof(this->jph_callbacks));
}
json_path_handler_base::json_path_handler_base(const string &property,
const pcrepp &property_re)
: jph_property(property),
jph_regex(property_re),
jph_is_array(property_re.p_pattern.find('#') != string::npos)
{
memset(&this->jph_callbacks, 0, sizeof(this->jph_callbacks));
}
yajl_gen_status json_path_handler_base::gen(yajlpp_gen_context &ygc, yajl_gen handle) const
{
vector<string> local_paths;
if (this->jph_path_provider) {
this->jph_path_provider(ygc.ygc_obj_stack.top(), local_paths);
}
else {
local_paths.emplace_back(this->jph_property);
}
if (this->jph_children) {
for (const auto &lpath : local_paths) {
string full_path = lpath;
if (this->jph_path_provider) {
full_path += "/";
}
int start_depth = ygc.ygc_depth;
yajl_gen_string(handle, lpath);
yajl_gen_map_open(handle);
ygc.ygc_depth += 1;
if (this->jph_obj_provider) {
pcre_context_static<30> pc;
pcre_input pi(full_path);
this->jph_regex.match(pc, pi);
ygc.ygc_obj_stack.push(this->jph_obj_provider(
{{pc, pi}, -1}, ygc.ygc_obj_stack.top()
));
if (!ygc.ygc_default_stack.empty()) {
ygc.ygc_default_stack.push(this->jph_obj_provider(
{{pc, pi}, -1}, ygc.ygc_default_stack.top()
));
}
}
for (auto &jph : this->jph_children->jpc_children) {
yajl_gen_status status = jph.gen(ygc, handle);
const unsigned char *buf;
size_t len;
yajl_gen_get_buf(handle, &buf, &len);
if (status != yajl_gen_status_ok) {
return status;
}
}
if (this->jph_obj_provider) {
ygc.ygc_obj_stack.pop();
if (!ygc.ygc_default_stack.empty()) {
ygc.ygc_default_stack.pop();
}
}
while (ygc.ygc_depth > start_depth) {
yajl_gen_map_close(handle);
ygc.ygc_depth -= 1;
}
}
}
else if (this->jph_gen_callback != nullptr) {
return this->jph_gen_callback(ygc, *this, handle);
}
return yajl_gen_status_ok;
}
const char *SCHEMA_TYPE_STRINGS[] = {
"any",
"boolean",
"integer",
"number",
"string",
"array",
"object",
};
yajl_gen_status json_path_handler_base::gen_schema(yajlpp_gen_context &ygc) const
{
if (this->jph_children) {
{
yajlpp_map schema(ygc.ygc_handle);
if (this->jph_description && this->jph_description[0]) {
schema.gen("description");
schema.gen(this->jph_description);
}
if (this->jph_is_pattern_property) {
ygc.ygc_path.emplace_back(fmt::format("<{}>", this->jph_regex.name_for_capture(0)));
} else {
ygc.ygc_path.emplace_back(this->jph_property);
}
if (this->jph_children->jpc_definition_id.empty()) {
schema.gen("title");
schema.gen(fmt::format("/{}", fmt::join(ygc.ygc_path, "/")));
schema.gen("type");
if (this->jph_is_array) {
if (this->jph_regex.p_pattern.find("#?") == string::npos) {
schema.gen("array");
} else {
yajlpp_array type_array(ygc.ygc_handle);
type_array.gen("array");
for (auto schema_type: this->get_types()) {
type_array.gen(SCHEMA_TYPE_STRINGS[(int) schema_type]);
}
}
schema.gen("items");
yajl_gen_map_open(ygc.ygc_handle);
yajl_gen_string(ygc.ygc_handle, "type");
this->gen_schema_type(ygc);
} else {
this->gen_schema_type(ygc);
}
this->jph_children->gen_schema(ygc);
if (this->jph_is_array) {
yajl_gen_map_close(ygc.ygc_handle);
}
} else {
schema.gen("title");
schema.gen(fmt::format("/{}", fmt::join(ygc.ygc_path, "/")));
this->jph_children->gen_schema(ygc);
}
ygc.ygc_path.pop_back();
}
} else {
yajlpp_map schema(ygc.ygc_handle);
if (this->jph_is_pattern_property) {
ygc.ygc_path.emplace_back(fmt::format("<{}>", this->jph_regex.name_for_capture(0)));
} else {
ygc.ygc_path.emplace_back(this->jph_property);
}
schema.gen("title");
schema.gen(fmt::format("/{}", fmt::join(ygc.ygc_path, "/")));
if (this->jph_description && this->jph_description[0]) {
schema.gen("description");
schema.gen(this->jph_description);
}
schema.gen("type");
if (this->jph_is_array) {
if (this->jph_regex.p_pattern.find("#?") == string::npos) {
schema.gen("array");
} else {
yajlpp_array type_array(ygc.ygc_handle);
type_array.gen("array");
for (auto schema_type: this->get_types()) {
type_array.gen(SCHEMA_TYPE_STRINGS[(int) schema_type]);
}
}
yajl_gen_string(ygc.ygc_handle, "items");
yajl_gen_map_open(ygc.ygc_handle);
yajl_gen_string(ygc.ygc_handle, "type");
}
this->gen_schema_type(ygc);
if (!this->jph_examples.empty()) {
schema.gen("examples");
yajlpp_array example_array(ygc.ygc_handle);
for (auto &ex : this->jph_examples) {
example_array.gen(ex);
}
}
if (this->jph_is_array) {
yajl_gen_map_close(ygc.ygc_handle);
}
ygc.ygc_path.pop_back();
}
return yajl_gen_status_ok;
}
yajl_gen_status json_path_handler_base::gen_schema_type(yajlpp_gen_context &ygc) const
{
yajlpp_generator schema(ygc.ygc_handle);
auto types = this->get_types();
if (types.size() == 1) {
yajl_gen_string(ygc.ygc_handle, SCHEMA_TYPE_STRINGS[(int) types[0]]);
} else {
yajlpp_array type_array(ygc.ygc_handle);
for (auto schema_type: types) {
type_array.gen(SCHEMA_TYPE_STRINGS[(int) schema_type]);
}
}
for (auto &schema_type : types) {
switch (schema_type) {
case schema_type_t::STRING:
if (this->jph_min_length > 0) {
schema("minLength");
schema(this->jph_min_length);
}
if (this->jph_max_length < INT_MAX) {
schema("maxLength");
schema(this->jph_max_length);
}
if (this->jph_pattern_re) {
schema("pattern");
schema(this->jph_pattern_re);
}
if (this->jph_enum_values) {
schema("enum");
yajlpp_array enum_array(ygc.ygc_handle);
for (int lpc = 0; this->jph_enum_values[lpc].first; lpc++) {
enum_array.gen(this->jph_enum_values[lpc].first);
}
}
break;
case schema_type_t::INTEGER:
case schema_type_t::NUMBER:
if (this->jph_min_value > LLONG_MIN) {
schema("minimum");
schema(this->jph_min_value);
}
break;
default:
break;
}
}
return yajl_gen_keys_must_be_strings;
}
void json_path_handler_base::walk(
const std::function<void(const json_path_handler_base &,
const std::string &,
void *)> &cb,
void *root, const string &base) const
{
vector<string> local_paths;
if (this->jph_path_provider) {
this->jph_path_provider(root, local_paths);
for (auto &lpath : local_paths) {
cb(*this, lpath, nullptr);
}
}
else {
local_paths.emplace_back(this->jph_property);
string full_path = base + this->jph_property;
if (this->jph_children) {
full_path += "/";
}
cb(*this, full_path, nullptr);
}
if (this->jph_children) {
for (const auto &lpath : local_paths) {
for (auto &jph : this->jph_children->jpc_children) {
string full_path = base + lpath;
if (this->jph_children) {
full_path += "/";
}
json_path_container dummy = {
json_path_handler(this->jph_property)
};
dummy.jpc_children[0].jph_callbacks = this->jph_callbacks;
yajlpp_parse_context ypc("possibilities", &dummy);
void *child_root = root;
ypc.set_path(full_path)
.with_obj(root)
.update_callbacks();
if (this->jph_obj_provider) {
string full_path = lpath + "/";
pcre_input pi(full_path);
if (!this->jph_regex.match(ypc.ypc_pcre_context, pi)) {
ensure(false);
}
child_root = this->jph_obj_provider(
{{ypc.ypc_pcre_context, pi}, -1}, root);
}
jph.walk(cb, child_root, full_path);
}
}
}
else {
for (auto &lpath : local_paths) {
void *field = nullptr;
if (this->jph_field_getter) {
field = this->jph_field_getter(root, lpath);
}
cb(*this, base + lpath, field);
}
}
}
yajlpp_parse_context::yajlpp_parse_context(std::string source,
const struct json_path_container *handlers)
: ypc_source(std::move(source)),
ypc_handlers(handlers)
{
this->ypc_path.reserve(4096);
this->ypc_path.push_back('/');
this->ypc_path.push_back('\0');
this->ypc_callbacks = DEFAULT_CALLBACKS;
memset(&this->ypc_alt_callbacks, 0, sizeof(this->ypc_alt_callbacks));
}
int yajlpp_parse_context::map_start(void *ctx)
{
yajlpp_parse_context *ypc = (yajlpp_parse_context *)ctx;
int retval = 1;
require(ypc->ypc_path.size() >= 2);
ypc->ypc_path_index_stack.push_back(ypc->ypc_path.size() - 1);
if (ypc->ypc_path.size() > 1 &&
ypc->ypc_path[ypc->ypc_path.size() - 2] == '#') {
ypc->ypc_array_index.back() += 1;
}
if (ypc->ypc_alt_callbacks.yajl_start_map != nullptr) {
retval = ypc->ypc_alt_callbacks.yajl_start_map(ypc);
}
return retval;
}
int yajlpp_parse_context::map_key(void *ctx,
const unsigned char *key,
size_t len)
{
yajlpp_parse_context *ypc = (yajlpp_parse_context *)ctx;
int retval = 1;
require(ypc->ypc_path.size() >= 2);
ypc->ypc_path.resize(ypc->ypc_path_index_stack.back());
if (ypc->ypc_path.back() != '/') {
ypc->ypc_path.push_back('/');
}
if (ypc->ypc_handlers != nullptr) {
for (size_t lpc = 0; lpc < len; lpc++) {
switch (key[lpc]) {
case '~':
ypc->ypc_path.push_back('~');
ypc->ypc_path.push_back('0');
break;
case '/':
ypc->ypc_path.push_back('~');
ypc->ypc_path.push_back('1');
break;
case '#':
ypc->ypc_path.push_back('~');
ypc->ypc_path.push_back('2');
break;
default:
ypc->ypc_path.push_back(key[lpc]);
break;
}
}
}
else {
size_t start = ypc->ypc_path.size();
ypc->ypc_path.resize(ypc->ypc_path.size() + len);
memcpy(&ypc->ypc_path[start], key, len);
}
ypc->ypc_path.push_back('\0');
if (ypc->ypc_alt_callbacks.yajl_map_key != nullptr) {
retval = ypc->ypc_alt_callbacks.yajl_map_key(ctx, key, len);
}
if (ypc->ypc_handlers != nullptr) {
ypc->update_callbacks();
}
ensure(ypc->ypc_path.size() >= 2);
return retval;
}
void yajlpp_parse_context::update_callbacks(const json_path_container *orig_handlers, int child_start)
{
const json_path_container *handlers = orig_handlers;
this->ypc_current_handler = nullptr;
if (this->ypc_handlers == nullptr) {
return;
}
this->ypc_sibling_handlers = orig_handlers;
pcre_input pi(&this->ypc_path[0], 0, this->ypc_path.size() - 1);
this->ypc_callbacks = DEFAULT_CALLBACKS;
if (handlers == nullptr) {
handlers = this->ypc_handlers;
this->ypc_handler_stack.clear();
}
if (!this->ypc_active_paths.empty()) {
string curr_path(&this->ypc_path[0], this->ypc_path.size() - 1);
if (this->ypc_active_paths.find(curr_path) ==
this->ypc_active_paths.end()) {
return;
}
}
if (child_start == 0 && !this->ypc_obj_stack.empty()) {
while (this->ypc_obj_stack.size() > 1) {
this->ypc_obj_stack.pop();
}
}
for (auto &jph : handlers->jpc_children) {
pi.reset(&this->ypc_path[1 + child_start],
0,
this->ypc_path.size() - 2 - child_start);
if (jph.jph_regex.match(this->ypc_pcre_context, pi)) {
pcre_context::capture_t *cap = this->ypc_pcre_context.all();
if (jph.jph_obj_provider) {
int index = this->index_for_provider();
if ((1 + child_start + cap->c_end != (int)this->ypc_path.size() - 1) &&
(!jph.is_array() || index >= 0)) {
this->ypc_obj_stack.push(jph.jph_obj_provider(
{{this->ypc_pcre_context, pi}, index},
this->ypc_obj_stack.top()));
}
}
if (jph.jph_children) {
this->ypc_handler_stack.emplace_back(&jph);
if (1 + child_start + cap->c_end != (int)this->ypc_path.size() - 1) {
this->update_callbacks(jph.jph_children,
1 + child_start + cap->c_end);
return;
}
}
else {
if (1 + child_start + cap->c_end != (int)this->ypc_path.size() - 1) {
continue;
}
this->ypc_current_handler = &jph;
}
if (jph.jph_callbacks.yajl_null != nullptr)
this->ypc_callbacks.yajl_null = jph.jph_callbacks.yajl_null;
if (jph.jph_callbacks.yajl_boolean != nullptr)
this->ypc_callbacks.yajl_boolean = jph.jph_callbacks.yajl_boolean;
if (jph.jph_callbacks.yajl_integer != nullptr)
this->ypc_callbacks.yajl_integer = jph.jph_callbacks.yajl_integer;
if (jph.jph_callbacks.yajl_double != nullptr)
this->ypc_callbacks.yajl_double = jph.jph_callbacks.yajl_double;
if (jph.jph_callbacks.yajl_string != nullptr)
this->ypc_callbacks.yajl_string = jph.jph_callbacks.yajl_string;
return;
}
}
this->ypc_handler_stack.emplace_back(nullptr);
}
int yajlpp_parse_context::map_end(void *ctx)
{
yajlpp_parse_context *ypc = (yajlpp_parse_context *)ctx;
int retval = 1;
ypc->ypc_path.resize(ypc->ypc_path_index_stack.back());
ypc->ypc_path.push_back('\0');
ypc->ypc_path_index_stack.pop_back();
if (ypc->ypc_alt_callbacks.yajl_end_map != nullptr) {
retval = ypc->ypc_alt_callbacks.yajl_end_map(ctx);
}
ypc->update_callbacks();
ensure(ypc->ypc_path.size() >= 2);
return retval;
}
int yajlpp_parse_context::array_start(void *ctx)
{
yajlpp_parse_context *ypc = (yajlpp_parse_context *)ctx;
int retval = 1;
ypc->ypc_path_index_stack.push_back(ypc->ypc_path.size() - 1);
ypc->ypc_path[ypc->ypc_path.size() - 1] = '#';
ypc->ypc_path.push_back('\0');
ypc->ypc_array_index.push_back(-1);
if (ypc->ypc_alt_callbacks.yajl_start_array != nullptr) {
retval = ypc->ypc_alt_callbacks.yajl_start_array(ctx);
}
ypc->update_callbacks();
ensure(ypc->ypc_path.size() >= 2);
return retval;
}
int yajlpp_parse_context::array_end(void *ctx)
{
yajlpp_parse_context *ypc = (yajlpp_parse_context *)ctx;
int retval = 1;
ypc->ypc_path.resize(ypc->ypc_path_index_stack.back());
ypc->ypc_path.push_back('\0');
ypc->ypc_path_index_stack.pop_back();
ypc->ypc_array_index.pop_back();
if (ypc->ypc_alt_callbacks.yajl_end_array != nullptr) {
retval = ypc->ypc_alt_callbacks.yajl_end_array(ctx);
}
ypc->update_callbacks();
ensure(ypc->ypc_path.size() >= 2);
return retval;
}
int yajlpp_parse_context::handle_unused(void *ctx)
{
yajlpp_parse_context *ypc = (yajlpp_parse_context *)ctx;
if (ypc->ypc_ignore_unused) {
return 1;
}
const json_path_handler_base *handler = ypc->ypc_current_handler;
int line_number = ypc->get_line_number();
if (handler != nullptr && strlen(handler->jph_synopsis) > 0 &&
strlen(handler->jph_description) > 0) {
ypc->report_error(
lnav_log_level_t::WARNING,
"%s:line %d",
ypc->ypc_source.c_str(),
line_number);
ypc->report_error(lnav_log_level_t::WARNING, " unexpected data for path");
ypc->report_error(lnav_log_level_t::WARNING,
" %s %s -- %s",
&ypc->ypc_path[0],
handler->jph_synopsis,
handler->jph_description);
}
else if (ypc->ypc_path[1]) {
ypc->report_error(lnav_log_level_t::WARNING,
"%s:line %d",
ypc->ypc_source.c_str(),
line_number);
ypc->report_error(lnav_log_level_t::WARNING, " unexpected path --");
ypc->report_error(lnav_log_level_t::WARNING, " %s", &ypc->ypc_path[0]);
} else {
ypc->report_error(lnav_log_level_t::WARNING,
"%s:line %d\n unexpected JSON value",
ypc->ypc_source.c_str(),
line_number);
}
if (ypc->ypc_callbacks.yajl_boolean != (int (*)(void *, int))yajlpp_parse_context::handle_unused ||
ypc->ypc_callbacks.yajl_integer != (int (*)(void *, long long))yajlpp_parse_context::handle_unused ||
ypc->ypc_callbacks.yajl_double != (int (*)(void *, double))yajlpp_parse_context::handle_unused ||
ypc->ypc_callbacks.yajl_string != (int (*)(void *, const unsigned char *, size_t))yajlpp_parse_context::handle_unused) {
ypc->report_error(lnav_log_level_t::WARNING, " expecting one of the following data types --");
}
if (ypc->ypc_callbacks.yajl_boolean != (int (*)(void *, int))yajlpp_parse_context::handle_unused) {
ypc->report_error(lnav_log_level_t::WARNING, " boolean");
}
if (ypc->ypc_callbacks.yajl_integer != (int (*)(void *, long long))yajlpp_parse_context::handle_unused) {
ypc->report_error(lnav_log_level_t::WARNING, " integer");
}
if (ypc->ypc_callbacks.yajl_double != (int (*)(void *, double))yajlpp_parse_context::handle_unused) {
ypc->report_error(lnav_log_level_t::WARNING, " float");
}
if (ypc->ypc_callbacks.yajl_string != (int (*)(void *, const unsigned char *, size_t))yajlpp_parse_context::handle_unused) {
ypc->report_error(lnav_log_level_t::WARNING, " string");
}
if (handler == nullptr) {
const json_path_container *accepted_handlers;
if (ypc->ypc_sibling_handlers) {
accepted_handlers = ypc->ypc_sibling_handlers;
} else {
accepted_handlers = ypc->ypc_handlers;
}
ypc->report_error(lnav_log_level_t::WARNING, " accepted paths --");
for (auto &jph : accepted_handlers->jpc_children) {
ypc->report_error(lnav_log_level_t::WARNING, " %s %s -- %s",
jph.jph_property.c_str(),
jph.jph_synopsis,
jph.jph_description);
}
}
return 1;
}
const yajl_callbacks yajlpp_parse_context::DEFAULT_CALLBACKS = {
yajlpp_parse_context::handle_unused,
(int (*)(void *, int))yajlpp_parse_context::handle_unused,
(int (*)(void *, long long))yajlpp_parse_context::handle_unused,
(int (*)(void *, double))yajlpp_parse_context::handle_unused,
nullptr,
(int (*)(void *, const unsigned char *, size_t))
yajlpp_parse_context::handle_unused,
yajlpp_parse_context::map_start,
yajlpp_parse_context::map_key,
yajlpp_parse_context::map_end,
yajlpp_parse_context::array_start,
yajlpp_parse_context::array_end,
};
yajl_status
yajlpp_parse_context::parse(const unsigned char *jsonText, size_t jsonTextLen)
{
this->ypc_json_text = jsonText;
yajl_status retval = yajl_parse(this->ypc_handle, jsonText, jsonTextLen);
size_t consumed = yajl_get_bytes_consumed(this->ypc_handle);
this->ypc_line_number += std::count(&jsonText[0], &jsonText[consumed], '\n');
this->ypc_json_text = nullptr;
if (retval != yajl_status_ok && this->ypc_error_reporter) {
auto msg = yajl_get_error(this->ypc_handle, 1, jsonText, jsonTextLen);
this->ypc_error_reporter(
*this, lnav_log_level_t::ERROR,
fmt::format("error:{}:{}:invalid json -- {}",
this->ypc_source,
this->get_line_number(),
msg).c_str());
yajl_free_error(this->ypc_handle, msg);
}
return retval;
}
yajl_status yajlpp_parse_context::complete_parse()
{
yajl_status retval = yajl_complete_parse(this->ypc_handle);
if (retval != yajl_status_ok && this->ypc_error_reporter) {
auto msg = yajl_get_error(this->ypc_handle, 0, nullptr, 0);
this->ypc_error_reporter(
*this, lnav_log_level_t::ERROR,
fmt::format("error:{}:invalid json -- {}",
this->ypc_source,
msg).c_str());
yajl_free_error(this->ypc_handle, msg);
}
return retval;
}
const intern_string_t yajlpp_parse_context::get_path() const
{
if (this->ypc_path.size() <= 1) {
return intern_string_t();
}
return intern_string::lookup(&this->ypc_path[1],
this->ypc_path.size() - 2);
}
const intern_string_t yajlpp_parse_context::get_full_path() const
{
if (this->ypc_path.size() <= 1) {
static intern_string_t SLASH = intern_string::lookup("/");
return SLASH;
}
return intern_string::lookup(&this->ypc_path[0],
this->ypc_path.size() - 1);
}
void yajlpp_parse_context::reset(const struct json_path_container *handlers)
{
this->ypc_handlers = handlers;
this->ypc_path.clear();
this->ypc_path.push_back('/');
this->ypc_path.push_back('\0');
this->ypc_path_index_stack.clear();
this->ypc_array_index.clear();
this->ypc_callbacks = DEFAULT_CALLBACKS;
memset(&this->ypc_alt_callbacks, 0, sizeof(this->ypc_alt_callbacks));
this->ypc_sibling_handlers = nullptr;
this->ypc_current_handler = nullptr;
while (!this->ypc_obj_stack.empty()) {
this->ypc_obj_stack.pop();
}
}
void yajlpp_parse_context::set_static_handler(json_path_handler_base &jph)
{
this->ypc_path.clear();
this->ypc_path.push_back('/');
this->ypc_path.push_back('\0');
this->ypc_path_index_stack.clear();
this->ypc_array_index.clear();
if (jph.jph_callbacks.yajl_null != nullptr)
this->ypc_callbacks.yajl_null = jph.jph_callbacks.yajl_null;
if (jph.jph_callbacks.yajl_boolean != nullptr)
this->ypc_callbacks.yajl_boolean = jph.jph_callbacks.yajl_boolean;
if (jph.jph_callbacks.yajl_integer != nullptr)
this->ypc_callbacks.yajl_integer = jph.jph_callbacks.yajl_integer;
if (jph.jph_callbacks.yajl_double != nullptr)
this->ypc_callbacks.yajl_double = jph.jph_callbacks.yajl_double;
if (jph.jph_callbacks.yajl_string != nullptr)
this->ypc_callbacks.yajl_string = jph.jph_callbacks.yajl_string;
}
yajlpp_parse_context &yajlpp_parse_context::set_path(const string &path)
{
this->ypc_path.resize(path.size() + 1);
std::copy(path.begin(), path.end(), this->ypc_path.begin());
this->ypc_path[path.size()] = '\0';
for (size_t lpc = 0; lpc < path.size(); lpc++) {
switch (path[lpc]) {
case '/':
this->ypc_path_index_stack.push_back(1 + lpc);
break;
}
}
return *this;
}
const char *yajlpp_parse_context::get_path_fragment(int offset, char *frag_in,
size_t &len_out) const
{
const char *retval;
size_t start, end;
if (offset < 0) {
offset = this->ypc_path_index_stack.size() + offset;
}
start = this->ypc_path_index_stack[offset] + ((offset == 0) ? 0 : 1);
if ((offset + 1) < (int)this->ypc_path_index_stack.size()) {
end = this->ypc_path_index_stack[offset + 1];
}
else {
end = this->ypc_path.size() - 1;
}
if (this->ypc_handlers) {
len_out = json_ptr::decode(frag_in, &this->ypc_path[start], end - start);
retval = frag_in;
}
else {
retval = &this->ypc_path[start];
len_out = end - start;
}
return retval;
}
int yajlpp_parse_context::get_line_number() const
{
if (this->ypc_handle != NULL && this->ypc_json_text) {
size_t consumed = yajl_get_bytes_consumed(this->ypc_handle);
long current_count = std::count(&this->ypc_json_text[0],
&this->ypc_json_text[consumed],
'\n');
return this->ypc_line_number + current_count;
}
else {
return this->ypc_line_number;
}
}
void yajlpp_gen_context::gen()
{
yajlpp_map root(this->ygc_handle);
for (auto &jph : this->ygc_handlers->jpc_children) {
jph.gen(*this, this->ygc_handle);
}
}
void yajlpp_gen_context::gen_schema(const json_path_container *handlers)
{
if (handlers == nullptr) {
handlers = this->ygc_handlers;
}
{
yajlpp_map schema(this->ygc_handle);
if (!handlers->jpc_schema_id.empty()) {
schema.gen("$id");
schema.gen(handlers->jpc_schema_id);
}
schema.gen("$schema");
schema.gen("http://json-schema.org/draft-07/schema#");
handlers->gen_schema(*this);
if (!this->ygc_schema_definitions.empty()) {
schema.gen("definitions");
yajlpp_map defs(this->ygc_handle);
for (auto &container : this->ygc_schema_definitions) {
defs.gen(container.first);
yajlpp_map def(this->ygc_handle);
def.gen("title");
def.gen(container.first);
def.gen("type");
def.gen("object");
def.gen("$$target");
def.gen(fmt::format("#/definitions/{}", container.first));
container.second->gen_properties(*this);
}
}
}
}
yajlpp_gen_context &yajlpp_gen_context::with_context(yajlpp_parse_context &ypc)
{
this->ygc_obj_stack = ypc.ypc_obj_stack;
if (ypc.ypc_current_handler == nullptr &&
!ypc.ypc_handler_stack.empty() &&
ypc.ypc_handler_stack.back() != nullptr) {
this->ygc_handlers = ypc.ypc_handler_stack.back()->jph_children;
this->ygc_depth += 1;
}
return *this;
}
json_path_handler &json_path_handler::with_children(const json_path_container &container) {
this->jph_children = &container;
return *this;
}
void json_path_container::gen_schema(yajlpp_gen_context &ygc) const
{
if (!this->jpc_definition_id.empty()) {
ygc.ygc_schema_definitions[this->jpc_definition_id] = this;
yajl_gen_string(ygc.ygc_handle, "$ref");
yajl_gen_string(ygc.ygc_handle, fmt::format("#/definitions/{}", this->jpc_definition_id));
return;
}
this->gen_properties(ygc);
}
void json_path_container::gen_properties(yajlpp_gen_context &ygc) const
{
auto pattern_count = count_if(this->jpc_children.begin(),
this->jpc_children.end(),
[](auto &jph) {
return jph.jph_is_pattern_property;
});
auto plain_count = this->jpc_children.size() - pattern_count;
if (plain_count > 0) {
yajl_gen_string(ygc.ygc_handle, "properties");
{
yajlpp_map properties(ygc.ygc_handle);
for (auto &child_handler : this->jpc_children) {
if (child_handler.jph_is_pattern_property) {
continue;
}
properties.gen(child_handler.jph_property);
child_handler.gen_schema(ygc);
}
}
}
if (pattern_count > 0) {
yajl_gen_string(ygc.ygc_handle, "patternProperties");
{
yajlpp_map properties(ygc.ygc_handle);
for (auto &child_handler : this->jpc_children) {
if (!child_handler.jph_is_pattern_property) {
continue;
}
properties.gen(child_handler.jph_property);
child_handler.gen_schema(ygc);
}
}
}
yajl_gen_string(ygc.ygc_handle, "additionalProperties");
yajl_gen_bool(ygc.ygc_handle, false);
}
static void schema_printer(FILE *file, const char *str, size_t len)
{
fwrite(str, len, 1, file);
}
void dump_schema_to(const json_path_container &jpc, const char *internals_dir, const char *name)
{
yajlpp_gen genner;
yajlpp_gen_context ygc(genner, jpc);
auto schema_path = fmt::format("{}/{}", internals_dir, name);
auto file = unique_ptr<FILE, decltype(&fclose)>(fopen(schema_path.c_str(), "w+"), fclose);
if (!file.get()) {
return;
}
yajl_gen_config(genner, yajl_gen_beautify, true);
yajl_gen_config(genner, yajl_gen_print_callback, schema_printer, file.get());
ygc.gen_schema();
}
| 32.952288 | 128 | 0.574316 | [
"object",
"vector"
] |
14a936198e0c1c89c15b0d2eb81cf0aa909ff848 | 1,532 | cpp | C++ | tests/test.cpp | Beenv12/BSTTree | b91dfb9563c75449d3143d31edb6209305bef1b8 | [
"MIT"
] | null | null | null | tests/test.cpp | Beenv12/BSTTree | b91dfb9563c75449d3143d31edb6209305bef1b8 | [
"MIT"
] | null | null | null | tests/test.cpp | Beenv12/BSTTree | b91dfb9563c75449d3143d31edb6209305bef1b8 | [
"MIT"
] | null | null | null | #include "catch.hpp"
#include <tree.hpp>
using namespace AVLTree;
TEST_CASE("output values should match input values", "[file]")
{
TUI obj;
std::vector<int> a = {3, 4, 4, 2, 6, 8, 7};
a = obj.CorrectFunction(a);
REQUIRE(a[2] == 2);
Tree *tree = new Tree(a);
Tree tree1 = {3, 4, 4, 2, 6, 8, 7};
Tree *tree2 = new Tree();
Tree tree3(a);
obj.outStars();
obj.MakeDecisionTree(1, tree);
obj.MakeDecisionTree(2, tree);
obj.MakeDecisionTree(3, tree);
obj.MakeDecisionTree(4, tree);
obj.MakeDecisionTree(5, tree);
obj.MakeDecisionTree(6, tree);
obj.MakeDecisionTree(7, tree);
obj.MakeDecisionTree(8, tree);
obj.MakeDecisionTree(9, tree);
obj.ChosenFunction();
tree->show();
std::cout << "Pre: ";
tree->print("pre");
std::cout << "In: ";
tree->print("in");
std::cout << "Post: ";
tree->print("post");
bool isInsert = tree->insert(5);
REQUIRE(isInsert == true);
REQUIRE(tree->exists(5) == true);
bool isDelete = tree->remove(3);
REQUIRE(isDelete == true);
REQUIRE(tree->exists(3) == false);
bool isDelete4 = tree->remove(7);
REQUIRE(isDelete == true);
REQUIRE(tree->exists(7) == false);
std::string path = "test.txt";
REQUIRE(tree->fileExist("not_file.txt") == false);
bool isWrite = tree->save("test.txt");
REQUIRE(isWrite == true);
bool isRead = tree->load(path);
REQUIRE(isRead == true);
tree->save("");
tree->load("");
delete tree;
tree->show();
}
| 24.709677 | 62 | 0.585509 | [
"vector"
] |
14afa80c40bac6f70949f0d46d89940bb43e9e6e | 19,715 | hh | C++ | perception_oru-port-kinetic/ndt_visualisation/include/ndt_visualisation/NDTVizGlut.hh | lllray/ndt-loam | 331867941e0764b40e1a980dd85d2174f861e9c8 | [
"BSD-3-Clause"
] | 1 | 2020-11-14T08:21:13.000Z | 2020-11-14T08:21:13.000Z | perception_oru-port-kinetic/ndt_visualisation/include/ndt_visualisation/NDTVizGlut.hh | lllray/ndt-loam | 331867941e0764b40e1a980dd85d2174f861e9c8 | [
"BSD-3-Clause"
] | 1 | 2021-07-28T04:47:56.000Z | 2021-07-28T04:47:56.000Z | perception_oru-port-kinetic/ndt_visualisation/include/ndt_visualisation/NDTVizGlut.hh | lllray/ndt-loam | 331867941e0764b40e1a980dd85d2174f861e9c8 | [
"BSD-3-Clause"
] | 2 | 2020-12-18T11:25:53.000Z | 2022-02-19T12:59:59.000Z | #ifndef NDTVIZGLUT_HH
#define NDTVIZGLUT_HH
#include <GL/freeglut.h>
#include <vector>
#include <string>
#include <math.h>
#include <iostream>
#include <deque>
#include <Eigen/Core>
#include <Eigen/Eigenvalues>
#include <boost/thread.hpp>
#include <assert.h>
#include <unistd.h>
#include <math.h>
#include <iostream>
inline void checkOpenGLError()
{
int openglErr;
if ( ( openglErr= glGetError()) != GL_NO_ERROR )
{
const std::string sErr = std::string("OpenGL error: ") + std::string( (char*)gluErrorString(openglErr) );
std::cerr << "[checkOpenGLError] " << sErr << std::endl;
}
}
// typedef struct
// {
// float x;
// float y;
// } glut3d_vector2_t;
// typedef struct
// {
// float x;
// float y;
// float z;
// } glut3d_vector3_t;
static int win;
//static void * glthread( void * pParam );
void * glthread( void * pParam );
static int create_gl_thread( void ) {
pthread_t thread1;
int iRet = pthread_create( &thread1, NULL, glthread, NULL );
return iRet;
}
class NDTVizGlutColorPoint {
public:
NDTVizGlutColorPoint() { }
NDTVizGlutColorPoint(float x, float y, float z, float R, float G, float B) {
pos[0] = x; pos[1] = y; pos[2] = z;
col[0] = R; col[1] = G; col[2] = B;
}
GLfloat pos[3];
GLfloat col[3];
};
class NDTVizGlutLine {
public:
NDTVizGlutLine() { }
NDTVizGlutLine(float x1, float y1, float z1, float x2, float y2, float z2) {
pos1[0] = x1; pos1[1] = y1; pos1[2] = z1;
pos2[0] = x2; pos2[1] = y2; pos2[2] = z2;
}
GLfloat pos1[3];
GLfloat pos2[3];
};
class NDTVizGlutColor4f {
public:
GLfloat R,G,B,A;
};
//! Interface class for all drawable objects
class NDTVizGlutObject
{
public:
//! Draw
virtual void draw() = 0;
};
class NDTVizGlutPointCloudColor : public NDTVizGlutObject
{
public:
NDTVizGlutPointCloudColor() {
//m_pointSize = -1;
}
void draw() {
//glEnable(GL_POINT_SMOOTH);
//if (m_pointSize > 0.)
// glPointSize( m_pointSize );
glBegin(GL_POINTS);
for (size_t i = 0; i < pts.size(); i++) {
glColor3fv(pts[i].col);
glVertex3fv(pts[i].pos);
}
glEnd();
checkOpenGLError();
}
void setPointSize(float size) { m_pointSize = size; }
void clear() { pts.clear(); }
void push_back(float x, float y, float z, float R, float G, float B) {
pts.push_back(NDTVizGlutColorPoint(x,y,z,R,G,B));
}
NDTVizGlutColorPoint& getPoint(size_t i) { return pts[i]; }
private:
float m_pointSize;
std::vector<NDTVizGlutColorPoint> pts;
};
class NDTVizGlutSetOfLines : public NDTVizGlutObject
{
public:
NDTVizGlutSetOfLines() {
setColor4(1.0, 0.4, 0.0, 0.8);
m_antiAliasing = true;
}
void draw() {
glPushAttrib( GL_COLOR_BUFFER_BIT | GL_LINE_BIT );
if (m_antiAliasing)
glEnable(GL_LINE_SMOOTH);
// glLineWidth(m_lineWidth);
checkOpenGLError();
glDisable(GL_LIGHTING); // Disable lights when drawing lines
glBegin(GL_LINES);
glColor4f(m_color.R,m_color.G,m_color.B,m_color.A);
for (size_t i = 0; i < lines.size(); i++)
{
glVertex3fv(lines[i].pos1);
glVertex3fv(lines[i].pos2);
}
glEnd();
checkOpenGLError();
glEnable(GL_LIGHTING); // Disable lights when drawing lines
// End of antialiasing:
glPopAttrib();
}
void setPointSize(float size) { m_pointSize = size; }
void clear() { lines.clear(); }
void push_back(float x1, float y1, float z1, float x2, float y2, float z2) {
lines.push_back(NDTVizGlutLine(x1, y1, z1, x2, y2, z2));
}
void appendLine(float x1, float y1, float z1, float x2, float y2, float z2) {
this->push_back(x1, y1, z1, x2, y2, z2);
}
NDTVizGlutLine& getLine(size_t i) { return lines[i]; }
void setColor(float R, float G, float B) {
m_color.R = R;
m_color.G = G;
m_color.B = B;
}
void setColor4(float R, float G, float B, float A) {
m_color.R = R; m_color.G = G; m_color.B = B; m_color.A = A;
}
void setThickness(float thickness) {
m_thickness = thickness;
}
private:
float m_lineWidth;
NDTVizGlutColor4f m_color;
bool m_antiAliasing;
float m_pointSize;
float m_thickness;
std::vector<NDTVizGlutLine> lines;
};
class NDTVizGlutEllipsoid : public NDTVizGlutObject
{
public:
NDTVizGlutEllipsoid() {
m_quantiles = 3;
m_lineWidth = 1;;
m_drawSolid3D = true;
m_3D_segments = 20;
this->setColor4(0.5, 1.0, 0.1, 0.8);
}
NDTVizGlutEllipsoid(float quantiles, float lineWidth, bool drawSolid, int segments) {
m_quantiles = quantiles;
m_lineWidth = lineWidth;
m_drawSolid3D = drawSolid;
m_3D_segments = segments;
this->setColor4(0.5, 1.0, 0.1, 0.8);
}
~NDTVizGlutEllipsoid() { }
void setLocation(double x, double y, double z) {
Eigen::Vector3d p(x,y,z);
this->setPos(p);
}
void enableDrawSolid3D(bool s) { m_drawSolid3D = s; }
void setPos(const Eigen::Vector3d &pos) { m_mean = pos; }
void setCovMatrix(const Eigen::Matrix3d &cov) { this->setCov(cov); }
void setCov(const Eigen::Matrix3d &cov) {
m_cov = cov;
const double d=m_cov.determinant();
if (d==0 || d!=d) // Note: "d!=d" is a great test for invalid numbers, don't remove!
{
// All zeros:
m_prevComputedCov = m_cov;
m_eigVec = Eigen::Matrix3d::Zero(3,3);
m_eigVal = Eigen::Matrix3d::Zero(3,3);
}
else
{
// Not null matrix: compute the eigen-vectors & values:
m_prevComputedCov = m_cov;
Eigen::EigenSolver<Eigen::Matrix3d> es(m_cov);
//m_eigVal = es.eigenvalues();
//m_eigVec = es.eigenvectors();
m_eigVal = es.pseudoEigenvalueMatrix();
m_eigVec = es.pseudoEigenvectors();
m_eigVal = m_eigVal.cwiseSqrt();
// Do the scale at render to avoid recomputing the m_eigVal for different m_quantiles
}
}
void setColor4(float R, float G, float B, float A) {
m_color.R = R; m_color.G = G; m_color.B = B; m_color.A = A;
}
void setColor(float R, float G, float B, float A) { setColor4(R, G, B, A); }
void draw() {
glPushMatrix();
glTranslatef(m_mean(0), m_mean(1), m_mean(2));
const size_t dim = m_cov.cols();
if(m_eigVal(0,0) != 0.0 && m_eigVal(1,1) != 0.0 && (dim==2 || m_eigVal(2,2) != 0.0) && m_quantiles!=0.0)
{
glEnable(GL_BLEND);
checkOpenGLError();
glColor4f(m_color.R, m_color.G, m_color.B, m_color.A);
glBlendFunc(GL_SRC_ALPHA, GL_ONE_MINUS_SRC_ALPHA);
checkOpenGLError();
glLineWidth(m_lineWidth);
checkOpenGLError();
if (dim==2)
{
// // ---------------------
// // 2D ellipse
// // ---------------------
// /* Equivalent MATLAB code:
// *
// * q=1;
// * [vec val]=eig(C);
// * M=(q*val*vec)';
// * R=M*[x;y];
// * xx=R(1,:);yy=R(2,:);
// * plot(xx,yy), axis equal;
// */
// double ang;
// unsigned int i;
// // Compute the new vectors for the ellipsoid:
// Eigen::Matrix3d M;
// M.noalias() = double(m_quantiles) * m_eigVal * m_eigVec.adjoint();
// glBegin( GL_LINE_LOOP );
// // Compute the points of the 2D ellipse:
// for (i=0,ang=0;i<m_2D_segments;i++,ang+= (M_2PI/m_2D_segments))
// {
// double ccos = cos(ang);
// double ssin = sin(ang);
// const float x = ccos * M.get_unsafe(0,0) + ssin * M.get_unsafe(1,0);
// const float y = ccos * M.get_unsafe(0,1) + ssin * M.get_unsafe(1,1);
// glVertex2f( x,y );
// } // end for points on ellipse
// glEnd();
}
else
{
// ---------------------
// 3D ellipsoid
// ---------------------
GLfloat mat[16];
// A homogeneous transformation matrix, in this order:
//
// 0 4 8 12
// 1 5 9 13
// 2 6 10 14
// 3 7 11 15
//
mat[3] = mat[7] = mat[11] = 0;
mat[15] = 1;
mat[12] = mat[13] = mat[14] = 0;
mat[0] = m_eigVec(0,0); mat[1] = m_eigVec(1,0); mat[2] = m_eigVec(2,0); // New X-axis
mat[4] = m_eigVec(0,1); mat[5] = m_eigVec(1,1); mat[6] = m_eigVec(2,1); // New X-axis
mat[8] = m_eigVec(0,2); mat[9] = m_eigVec(1,2); mat[10] = m_eigVec(2,2); // New X-axis
glDisable(GL_LIGHTING);
//glEnable(GL_LIGHTING);
//glEnable(GL_LIGHT0);
glEnable(GL_COLOR_MATERIAL);
glShadeModel(GL_SMOOTH);
GLUquadricObj *obj = gluNewQuadric();
checkOpenGLError();
gluQuadricDrawStyle( obj, m_drawSolid3D ? GLU_FILL : GLU_LINE);
glPushMatrix();
glMultMatrixf( mat );
glScalef(m_eigVal(0,0)*m_quantiles,m_eigVal(1,1)*m_quantiles,m_eigVal(2,2)*m_quantiles);
gluSphere( obj, 1,m_3D_segments,m_3D_segments);
checkOpenGLError();
glPopMatrix();
gluDeleteQuadric(obj);
checkOpenGLError();
glDisable(GL_LIGHTING);
glDisable(GL_LIGHT0);
}
glLineWidth(1.0f);
glDisable(GL_BLEND);
}
glPopMatrix();
}
private:
Eigen::Matrix3d m_cov, m_prevComputedCov, m_eigVal, m_eigVec;
Eigen::Vector3d m_mean;
NDTVizGlutColor4f m_color;
float m_quantiles;
float m_lineWidth;
bool m_drawSolid3D;
int m_3D_segments;
public:
EIGEN_MAKE_ALIGNED_OPERATOR_NEW
};
class NDTVizGlutEllipsoids : public NDTVizGlutObject {
public:
void draw() {
for (size_t i = 0; i < objs.size(); i++) {
objs[i].draw();
}
}
void push_back(const NDTVizGlutEllipsoid &obj) { objs.push_back(obj); }
void clear() { objs.clear(); objs.resize(0); }
private:
std::vector<NDTVizGlutEllipsoid, Eigen::aligned_allocator<NDTVizGlutEllipsoid> > objs;
};
//! Interface class
class NDTVizGlutCamera {
public:
virtual Eigen::Vector3f getPosition() const = 0;
virtual Eigen::Vector3f getFocalPoint() const = 0;
virtual Eigen::Vector3f getUpVector() const = 0;
virtual void setFocalPoint(const Eigen::Vector3f &fp) = 0;
virtual void setPosition(const Eigen::Vector3f &p) = 0;
virtual void update_mouse(int button, int state, int x, int y) = 0;
virtual void update_motion(int x, int y) = 0;
};
//! Implements a camera without (mouse)interaction
class NDTVizGlutFixedCamera : public NDTVizGlutCamera {
private:
Eigen::Vector3f position_;
Eigen::Vector3f focal_point_;
public:
NDTVizGlutFixedCamera() {
position_ = Eigen::Vector3f(0., 0., 1.);
focal_point_ = Eigen::Vector3f(1., 0., 0.);
}
Eigen::Vector3f getPosition() const {
return position_;
}
Eigen::Vector3f getFocalPoint() const {
return focal_point_;
}
Eigen::Vector3f getUpVector() const {
return Eigen::Vector3f(0., 0., 1.);
}
void setFocalPoint(const Eigen::Vector3f &fp) {
focal_point_ = fp;
}
void setPosition(const Eigen::Vector3f &p) {
position_ = p;
}
void update_mouse(int button, int state, int x, int y) {
// Nothing
}
void update_motion(int x, int y) {
// Nothing
}
};
//! This implements a XY-orbit camera movement
class NDTVizGlutXYOrbitCamera : public NDTVizGlutCamera {
private:
int last_button_;
int last_state_;
Eigen::Vector2i last_point_;
Eigen::Vector3f focal_point_;
float distance;
float yaw;
float pitch;
public:
NDTVizGlutXYOrbitCamera() {
last_button_ = -1;
last_state_ = -1;
distance = 30.;
yaw = 1.;
pitch = 0.7;
focal_point_ = Eigen::Vector3f(0., 0., 0.);
}
Eigen::Vector3f getPosition() const {
Eigen::Vector3f p = Eigen::Vector3f(distance*sin(pitch)*cos(yaw),
distance*sin(pitch)*sin(yaw),
distance*cos(pitch));
return p + getFocalPoint();
}
Eigen::Vector3f getFocalPoint() const {
return focal_point_;
}
void setFocalPoint(const Eigen::Vector3f &fp) {
focal_point_ = fp;
}
void setPosition(const Eigen::Vector3f &p) {
Eigen::Vector3f diff = p-getFocalPoint();
distance = diff.norm();
yaw = atan2(diff(1),diff(0));
pitch = acos(diff(2) / distance);
while (pitch > M_PI/2.) {
pitch -= M_PI;
}
while (pitch < -M_PI/2.) {
pitch += M_PI;
}
// std::cout << "distance : " << distance << std::endl;
// std::cout << "yaw : " << yaw << std::endl;
// std::cout << "pitch : " << pitch << std::endl;
}
Eigen::Vector3f getUpVector() const {
return Eigen::Vector3f(0., 0., 1.);
}
float getPitchAngle() const { return pitch; }
void setPitchAngle(double p) { pitch = p; }
void update_mouse(int button, int state, int x, int y) {
last_button_ = button;
last_state_ = state;
last_point_[0] = x;
last_point_[1] = y;
// Wheel reports as button 3(scroll up) and button 4(scroll down)
if ((button == 3) || (button == 4)) // It's a wheel event
{
// Each wheel event reports like a button click, GLUT_DOWN then GLUT_UP
if (state != GLUT_UP) { // Disregard redundant GLUT_UP events
if (button == 3)
distance *= 0.9;
else
distance *= 1.1;
}
}
}
void update_motion(int x, int y) {
// Left button in x -> change the yaw
// Middle button -> move the position in x-dir,y-dir.
// Rigth button in y -> move the position along z-dir.
float dx = (x - last_point_[0])*0.01;
float dy = (y - last_point_[1])*0.01;
switch(last_button_) {
case GLUT_LEFT_BUTTON:
yaw += -dx;
pitch += dy;
if (pitch > M_PI/2.)
pitch = M_PI/2.- 0.0001;
if (pitch < -M_PI/2.)
pitch = -M_PI/2.+ 0.0001;
break;
case GLUT_MIDDLE_BUTTON:
dx *= distance*0.15;
dy *= distance*0.15;
focal_point_[1] += -cos(-yaw) * dx -sin(yaw) * dy;
focal_point_[0] += -sin(-yaw) * dx -cos(yaw) * dy;
//focal_point_[1] -= cos(yaw) * dx; // - sin(yaw) * dy;
break;
case GLUT_RIGHT_BUTTON:
if (dy > 0)
distance *= 1.05;
else
distance *= 0.95;
break;
default:
break;
};
last_point_[0] = x;
last_point_[1] = y;
}
};
//! An OpenGL class to draw 3D stuff.
/*!
* Based on the glut library. NOTE, this requires freeglut, not
* the ordinary GLUT, since it requires glutMainLoopEvent() function.
*/
class NDTVizGlut {
public:
//! Constructor
NDTVizGlut();
//! Destructor
virtual ~NDTVizGlut();
//! Run the GUI
virtual int win_run(int *argc, char **argv);
//! Key callback function
virtual void win_key(unsigned char key, int x, int y);
//! Mouse callback
virtual void win_mouse(int button, int state, int x, int y);
//! Mouse callback
virtual void win_motion(int x, int y);
//! Reshape events
virtual void win_reshape(int width, int height);
//! Redraw the window
virtual void win_redraw();
//! Idle callback
virtual void win_idle();
//! Close windo callback
virtual void win_close();
//! Process events
virtual void process_events();
virtual void start_main_loop() {
glutMainLoop();
}
virtual void start_main_loop_own_thread() {
// boost::thread workerThread(workerFunc);
create_gl_thread();
// if(pthread_create(&glut_event_processing_thread, NULL, ndt_viz_event_loop_thread, this)) {
// std::cerr << "Error creating thread\n";
// }
}
virtual void draw_origin();
void setFullScreen(bool fs);
bool getFullScreen() const;
void setMotionBlurFrames(int f);
int getMotionBlurFrames() const;
//! Save an image (screenshot) of current view.
int save(const std::string &fileName);
//! Start/stop saving incrementally (to create movies).
void set_save_inc_flag(bool flag) { do_save_inc = flag; }
//! Add an object to draw.
void addObject(NDTVizGlutObject* object) {
// Only add objects if they are NOT in the objects.
if ( std::find(objects.begin(), objects.end(), object)==objects.end() ) {
objects.push_back(object);
}
}
//! Set the drawing style
// void setDrawingStyle();
//!
void repaint();
void clearScene();
void setCameraPointingToPoint(double x, double y, double z);
void setCameraPosition(double x, double y, double z); //Not used?
bool isOpen() const;
bool keyHit() const;
unsigned char getPushedKey();
void update_cam();
void switchCamera(const std::string &type);
void setAspectRatioFactor(float ratio);
const NDTVizGlutCamera* getCameraConstPtr() const;
NDTVizGlutCamera* getCameraPtr();
protected:
//! Put the code to draw here.
/*!
* This is called from the win_redraw function, which's also
* draws the origin (0,0) of the 2D space.
*/
virtual void draw();
void cam_rotate();
//! Saves a set of images.
int save_inc();
pthread_t glut_event_processing_thread;
// GUI settings
// int win;
int gui_pause;
// int viewport_width;
// int viewport_height;
int show_samples;
int show_grid;
double start_time;
Eigen::Vector3f cam_pos;
Eigen::Vector3f cam_dir;
// float cam_radius;
// float cam_sweep_ang;
// float cam_azim;
// float cam_sweep_speed;
// bool cam_sweep;
int save_inc_counter;
bool do_save_inc;
bool open;
// // Objects to draw
std::vector<NDTVizGlutObject*> objects;
NDTVizGlutCamera* camera;
NDTVizGlutXYOrbitCamera orbit_camera;
NDTVizGlutFixedCamera fixed_camera;
std::deque<unsigned char> pressed_keys;
float aspect_ratio_factor;
bool full_screen;
int motion_blur_frames;
};
////////////////////////////////////////////////////////////////////////////////////////////////////////
// // // Needed for the wrapper calls.
// static NDTVizGlut* glut3d_ptr = 0x0;
// // Need some wrapper functions to handle the callbacks functions.
// void win_reshape_(int w, int h) { glut3d_ptr->win_reshape (w,h); }
// void win_redraw_() { glut3d_ptr->win_redraw(); }
// void win_key_(unsigned char key, int x, int y) { glut3d_ptr->win_key(key, x, y); }
// void win_mouse_(int button, int state, int x, int y) { glut3d_ptr->win_mouse(button, state, x, y); }
// void win_motion_(int x, int y) { glut3d_ptr->win_motion(x, y); }
// void win_idle_() { glut3d_ptr->win_idle(); }
// void win_close_() { glut3d_ptr->win_close(); }
// void * glthread(void * pParam)
// {
// int argc=0;
// char** argv = NULL;
// glutInit(&argc, argv);
// // Create a window
// glutInitDisplayMode(GLUT_RGBA | GLUT_DEPTH | GLUT_DOUBLE);
// glutInitWindowSize(640,480);
// win = glutCreateWindow("NDTVizGlut");
// glEnable(GL_DEPTH_TEST);
// glEnable(GL_LIGHTING);
// glEnable(GL_LIGHT0);
// // Create light components
// GLfloat ambientLight[] = { 0.2f, 0.2f, 0.2f, 1.0f };
// GLfloat diffuseLight[] = { 0.8f, 0.8f, 0.8, 1.0f };
// GLfloat specularLight[] = { 0.5f, 0.5f, 0.5f, 1.0f };
// GLfloat position[] = { -1.5f, 1.0f, -4.0f, 1.0f };
// // Assign created components to GL_LIGHT0
// glLightfv(GL_LIGHT0, GL_AMBIENT, ambientLight);
// glLightfv(GL_LIGHT0, GL_DIFFUSE, diffuseLight);
// glLightfv(GL_LIGHT0, GL_SPECULAR, specularLight);
// glLightfv(GL_LIGHT0, GL_POSITION, position);
// // enable color tracking
// glEnable(GL_COLOR_MATERIAL);
// // set material properties which will be assigned by glColor
// glColorMaterial(GL_FRONT, GL_AMBIENT_AND_DIFFUSE);
// glutReshapeFunc(win_reshape_);
// glutDisplayFunc(win_redraw_);
// glutKeyboardFunc(win_key_);
// glutMouseFunc(win_mouse_);
// glutMotionFunc(win_motion_);
// glutPassiveMotionFunc(NULL);
// // Idle loop callback
// glutIdleFunc(win_idle_);
// // Window close function
// glutCloseFunc(win_close_);
// /* Thread will loop here */
// while (true) {
// usleep(1000);
// for (int i = 0; i < 10; i++)
// glutMainLoopEvent();
// glut3d_ptr->update_cam();
// win_redraw_();
// }
// //glutMainLoop();
// return NULL;
// }
#endif
| 25.771242 | 111 | 0.61892 | [
"render",
"object",
"vector",
"3d"
] |
14b1dca273ab33f402648caa816882b3df44e2c8 | 13,843 | cpp | C++ | cpp/src/binaryop/binaryop.cpp | williamBlazing/cudf | 072785e24fd59b6f4eeaad3b54592a8c803ee96b | [
"Apache-2.0"
] | 2 | 2019-12-25T14:20:17.000Z | 2019-12-25T14:33:02.000Z | cpp/src/binaryop/binaryop.cpp | williamBlazing/cudf | 072785e24fd59b6f4eeaad3b54592a8c803ee96b | [
"Apache-2.0"
] | null | null | null | cpp/src/binaryop/binaryop.cpp | williamBlazing/cudf | 072785e24fd59b6f4eeaad3b54592a8c803ee96b | [
"Apache-2.0"
] | null | null | null | /*
* Copyright (c) 2019, NVIDIA CORPORATION.
*
* Copyright 2018-2019 BlazingDB, Inc.
* Copyright 2018 Christian Noboa Mardini <christian@blazingdb.com>
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
#include <cudf/column/column_factories.hpp>
#include <cudf/detail/binaryop.hpp>
#include <cudf/null_mask.hpp>
#include <cudf/utilities/error.hpp>
#include <cudf/utilities/traits.hpp>
#include <binaryop/jit/code/code.h>
#include <jit/launcher.h>
#include <jit/parser.h>
#include <jit/type.h>
#include <binaryop/jit/util.hpp>
#include <cudf/datetime.hpp> // replace eventually
#include <string>
#include <timestamps.hpp.jit>
#include <types.hpp.jit>
namespace cudf {
namespace experimental {
namespace binops {
namespace jit {
#ifndef LIBCUDF_INCLUDE_DIR
#define LIBCUDF_INCLUDE_DIR \
std::string{std::getenv("CONDA_PREFIX")} + "/include/libcudf"
#endif
// env var always overrides the default value of LIBCUDF_INCLUDE_DIR
const char* env_dir = std::getenv("LIBCUDF_INCLUDE_DIR");
const std::string libcudf_include_dir =
env_dir != NULL ? env_dir : LIBCUDF_INCLUDE_DIR;
const std::string hash = "prog_binop.experimental";
const std::vector<std::string> compiler_flags{
"-std=c++14",
// suppress all NVRTC warnings
"-w",
// force libcudacxx to not include system headers
"-D__CUDACC_RTC__",
// __CHAR_BIT__ is from GCC, but libcxx uses it
"-D__CHAR_BIT__=" + std::to_string(__CHAR_BIT__),
// enable temporary workarounds to compile libcudacxx with nvrtc
"-D_LIBCUDACXX_HAS_NO_CTIME",
"-D_LIBCUDACXX_HAS_NO_WCHAR",
"-D_LIBCUDACXX_HAS_NO_CFLOAT",
"-D_LIBCUDACXX_HAS_NO_STDINT",
"-D_LIBCUDACXX_HAS_NO_CSTDDEF",
"-D_LIBCUDACXX_HAS_NO_CLIMITS",
"-D_LIBCPP_DISABLE_VISIBILITY_ANNOTATIONS",
"-I" + libcudf_include_dir + "/libcudacxx",
};
const std::vector<std::string> header_names{
"operation.h", "traits.h", cudf_types_hpp, cudf_wrappers_timestamps_hpp};
std::istream* headers_code(std::string filename, std::iostream& stream) {
if (filename == "operation.h") {
stream << code::operation;
return &stream;
}
if (filename == "traits.h") {
stream << code::traits;
return &stream;
}
return nullptr;
}
void binary_operation(mutable_column_view& out,
scalar const& lhs,
column_view const& rhs,
binary_operator op,
cudaStream_t stream) {
cudf::jit::launcher(hash, code::kernel, header_names, compiler_flags,
headers_code, stream)
.set_kernel_inst(
"cudf::experimental::kernel_v_s", // name of the kernel we are
// launching
{cudf::jit::get_type_name(out.type()), // list of template arguments
cudf::jit::get_type_name(rhs.type()),
cudf::jit::get_type_name(lhs.type()),
get_operator_name(op, OperatorType::Reverse)})
.launch(out.size(), cudf::jit::get_data_ptr(out),
cudf::jit::get_data_ptr(rhs), cudf::jit::get_data_ptr(lhs));
}
void binary_operation(mutable_column_view& out,
column_view const& lhs,
scalar const& rhs,
binary_operator op,
cudaStream_t stream) {
cudf::jit::launcher(hash, code::kernel, header_names, compiler_flags,
headers_code, stream)
.set_kernel_inst(
"cudf::experimental::kernel_v_s", // name of the kernel we are
// launching
{cudf::jit::get_type_name(out.type()), // list of template arguments
cudf::jit::get_type_name(lhs.type()),
cudf::jit::get_type_name(rhs.type()),
get_operator_name(op, OperatorType::Direct)})
.launch(out.size(), cudf::jit::get_data_ptr(out),
cudf::jit::get_data_ptr(lhs), cudf::jit::get_data_ptr(rhs));
}
void binary_operation(mutable_column_view& out,
column_view const& lhs,
column_view const& rhs,
binary_operator op,
cudaStream_t stream) {
cudf::jit::launcher(hash, code::kernel, header_names, compiler_flags,
headers_code, stream)
.set_kernel_inst(
"cudf::experimental::kernel_v_v", // name of the kernel we are
// launching
{cudf::jit::get_type_name(out.type()), // list of template arguments
cudf::jit::get_type_name(lhs.type()),
cudf::jit::get_type_name(rhs.type()),
get_operator_name(op, OperatorType::Direct)})
.launch(out.size(), cudf::jit::get_data_ptr(out),
cudf::jit::get_data_ptr(lhs), cudf::jit::get_data_ptr(rhs));
}
void binary_operation(mutable_column_view& out,
column_view const& lhs,
column_view const& rhs,
const std::string& ptx,
cudaStream_t stream) {
std::string const output_type_name = cudf::jit::get_type_name(out.type());
std::string ptx_hash =
hash + "." +
std::to_string(std::hash<std::string>{}(ptx + output_type_name));
std::string cuda_source = "\n#include <cudf/types.hpp>\n" +
cudf::jit::parse_single_function_ptx(
ptx, "GENERIC_BINARY_OP", output_type_name) +
code::kernel;
cudf::jit::launcher(ptx_hash, cuda_source, header_names, compiler_flags,
headers_code, stream)
.set_kernel_inst("cudf::experimental::kernel_v_v", // name of the kernel
// we are launching
{output_type_name, // list of template arguments
cudf::jit::get_type_name(lhs.type()),
cudf::jit::get_type_name(rhs.type()),
get_operator_name(binary_operator::GENERIC_BINARY,
OperatorType::Direct)})
.launch(out.size(), cudf::jit::get_data_ptr(out),
cudf::jit::get_data_ptr(lhs), cudf::jit::get_data_ptr(rhs));
}
} // namespace jit
} // namespace binops
namespace {
/**
* @brief Computes output valid mask for op between a column and a scalar
*/
auto scalar_col_valid_mask_and(column_view const& col,
scalar const& s,
cudaStream_t stream,
rmm::mr::device_memory_resource* mr) {
if (col.size() == 0) {
return rmm::device_buffer{};
}
if (not s.is_valid()) {
return create_null_mask(col.size(), mask_state::ALL_NULL, stream, mr);
} else if (s.is_valid() && col.nullable()) {
return copy_bitmask(col, stream, mr);
} else if (s.is_valid() && not col.nullable()) {
return rmm::device_buffer{};
}
}
} // namespace
namespace detail {
std::unique_ptr<column> binary_operation(scalar const& lhs,
column_view const& rhs,
binary_operator op,
data_type output_type,
rmm::mr::device_memory_resource* mr,
cudaStream_t stream) {
// Check for datatype
CUDF_EXPECTS(is_fixed_width(lhs.type()), "Invalid/Unsupported lhs datatype");
CUDF_EXPECTS(is_fixed_width(rhs.type()), "Invalid/Unsupported rhs datatype");
CUDF_EXPECTS(is_fixed_width(output_type), "Invalid/Unsupported output datatype");
auto new_mask = scalar_col_valid_mask_and(rhs, lhs, stream, mr);
auto out = make_numeric_column(output_type, rhs.size(), new_mask,
cudf::UNKNOWN_NULL_COUNT, stream, mr);
if (rhs.size() == 0) {
return out;
}
auto out_view = out->mutable_view();
binops::jit::binary_operation(out_view, lhs, rhs, op, stream);
return out;
}
std::unique_ptr<column> binary_operation(column_view const& lhs,
scalar const& rhs,
binary_operator op,
data_type output_type,
rmm::mr::device_memory_resource* mr,
cudaStream_t stream) {
// Check for datatype
CUDF_EXPECTS(is_fixed_width(lhs.type()), "Invalid/Unsupported lhs datatype");
CUDF_EXPECTS(is_fixed_width(rhs.type()), "Invalid/Unsupported rhs datatype");
CUDF_EXPECTS(is_fixed_width(output_type), "Invalid/Unsupported output datatype");
auto new_mask = scalar_col_valid_mask_and(lhs, rhs, stream, mr);
auto out = make_numeric_column(output_type, lhs.size(), new_mask,
cudf::UNKNOWN_NULL_COUNT, stream, mr);
if (lhs.size() == 0) {
return out;
}
auto out_view = out->mutable_view();
binops::jit::binary_operation(out_view, lhs, rhs, op, stream);
return out;
}
std::unique_ptr<column> binary_operation(column_view const& lhs,
column_view const& rhs,
binary_operator op,
data_type output_type,
rmm::mr::device_memory_resource* mr,
cudaStream_t stream) {
// Check for datatype
CUDF_EXPECTS(is_fixed_width(lhs.type()), "Invalid/Unsupported lhs datatype");
CUDF_EXPECTS(is_fixed_width(rhs.type()), "Invalid/Unsupported rhs datatype");
CUDF_EXPECTS(is_fixed_width(output_type),
"Invalid/Unsupported output datatype");
CUDF_EXPECTS((lhs.size() == rhs.size()), "Column sizes don't match");
auto new_mask = bitmask_and(lhs, rhs, stream, mr);
auto out = make_fixed_width_column(output_type, lhs.size(), new_mask,
cudf::UNKNOWN_NULL_COUNT, stream, mr);
// Check for 0 sized data
if (lhs.size() == 0 || rhs.size() == 0) {
return out;
}
auto out_view = out->mutable_view();
binops::jit::binary_operation(out_view, lhs, rhs, op, stream);
return out;
}
std::unique_ptr<column> binary_operation(column_view const& lhs,
column_view const& rhs,
std::string const& ptx,
data_type output_type,
rmm::mr::device_memory_resource* mr,
cudaStream_t stream) {
// Check for datatype
auto is_type_supported_ptx = [](data_type type) -> bool {
return is_fixed_width(type) and
type.id() != type_id::INT8; // Numba PTX doesn't support int8
};
CUDF_EXPECTS(is_type_supported_ptx(lhs.type()),
"Invalid/Unsupported lhs datatype");
CUDF_EXPECTS(is_type_supported_ptx(rhs.type()),
"Invalid/Unsupported rhs datatype");
CUDF_EXPECTS(is_type_supported_ptx(output_type),
"Invalid/Unsupported output datatype");
CUDF_EXPECTS((lhs.size() == rhs.size()), "Column sizes don't match");
auto new_mask = bitmask_and(lhs, rhs, stream, mr);
auto out = make_fixed_width_column(output_type, lhs.size(), new_mask,
cudf::UNKNOWN_NULL_COUNT, stream, mr);
// Check for 0 sized data
if (lhs.size() == 0 || rhs.size() == 0) {
return out;
}
auto out_view = out->mutable_view();
binops::jit::binary_operation(out_view, lhs, rhs, ptx, stream);
return out;
}
} // namespace detail
std::unique_ptr<column> binary_operation(scalar const& lhs,
column_view const& rhs,
binary_operator op,
data_type output_type,
rmm::mr::device_memory_resource* mr) {
return detail::binary_operation(lhs, rhs, op, output_type, mr);
}
std::unique_ptr<column> binary_operation(column_view const& lhs,
scalar const& rhs,
binary_operator op,
data_type output_type,
rmm::mr::device_memory_resource* mr) {
return detail::binary_operation(lhs, rhs, op, output_type, mr);
}
std::unique_ptr<column> binary_operation(column_view const& lhs,
column_view const& rhs,
binary_operator op,
data_type output_type,
rmm::mr::device_memory_resource* mr) {
return detail::binary_operation(lhs, rhs, op, output_type, mr);
}
std::unique_ptr<column> binary_operation(column_view const& lhs,
column_view const& rhs,
std::string const& ptx,
data_type output_type,
rmm::mr::device_memory_resource* mr) {
return detail::binary_operation(lhs, rhs, ptx, output_type, mr);
}
} // namespace experimental
} // namespace cudf
| 40.241279 | 83 | 0.57921 | [
"vector"
] |
14b96dd01acce1fc53e60196fdfdba15cd924542 | 167,990 | cc | C++ | src/ifmap/test/ifmap_xmpp_test.cc | Mirantis/contrail-controller | 6a8ce71bde9f30e14241027dc89fcd9ca6ac0673 | [
"Apache-2.0"
] | 3 | 2019-01-11T06:16:40.000Z | 2021-02-24T23:48:21.000Z | src/ifmap/test/ifmap_xmpp_test.cc | Mirantis/contrail-controller | 6a8ce71bde9f30e14241027dc89fcd9ca6ac0673 | [
"Apache-2.0"
] | null | null | null | src/ifmap/test/ifmap_xmpp_test.cc | Mirantis/contrail-controller | 6a8ce71bde9f30e14241027dc89fcd9ca6ac0673 | [
"Apache-2.0"
] | 2 | 2019-02-06T12:52:00.000Z | 2019-04-11T23:19:28.000Z | /*
* Copyright (c) 2013 Juniper Networks, Inc. All rights reserved.
*/
#include "base/logging.h"
#include "base/timer_impl.h"
#include "base/test/task_test_util.h"
#include "control-node/control_node.h"
#include "db/db.h"
#include "db/db_graph.h"
#include "ifmap/ifmap_client.h"
#include "ifmap/ifmap_exporter.h"
#include "ifmap/ifmap_link.h"
#include "ifmap/ifmap_link_table.h"
#include "ifmap/ifmap_node.h"
#include "ifmap/ifmap_server.h"
#include "ifmap/ifmap_server_parser.h"
#include "ifmap/ifmap_server_table.h"
#include "ifmap/ifmap_update.h"
#include "ifmap/ifmap_update_sender.h"
#include "ifmap/ifmap_util.h"
#include "ifmap/ifmap_uuid_mapper.h"
#include "ifmap/ifmap_xmpp.h"
#include "ifmap/test/ifmap_xmpp_client_mock.h"
#include "schema/vnc_cfg_types.h"
#include "io/event_manager.h"
#include "io/test/event_manager_test.h"
#include "xmpp/xmpp_server.h"
#include "xmpp/xmpp_client.h"
#include "testing/gunit.h"
#include <stdlib.h>
#include <iostream>
#include <fstream>
using namespace std;
class XmppIfmapTest : public ::testing::Test {
protected:
static const string kDefaultClientName;
static const string kDefaultXmppServerAddress;
static const string kDefaultXmppServerName;
static const string kDefaultXmppServerConfigName;
XmppIfmapTest()
: ifmap_server_(&db_, &graph_, evm_.io_service()),
exporter_(ifmap_server_.exporter()), parser_(NULL),
xmpp_server_(NULL), vm_uuid_mapper_(NULL) {
}
virtual void SetUp() {
IFMap_Initialize();
xmpp_server_ = new XmppServer(&evm_, kDefaultXmppServerName);
thread_.reset(new ServerThread(&evm_));
xmpp_server_->Initialize(0, false);
LOG(DEBUG, "Created Xmpp Server at port " << xmpp_server_->GetPort());
ifmap_channel_mgr_.reset(new IFMapChannelManager(xmpp_server_,
&ifmap_server_));
ifmap_server_.set_ifmap_channel_manager(ifmap_channel_mgr_.get());
thread_->Start();
}
virtual void TearDown() {
ifmap_server_.Shutdown();
task_util::WaitForIdle();
IFMapLinkTable_Clear(&db_);
IFMapTable::ClearTables(&db_);
task_util::WaitForIdle();
db_.Clear();
DB::ClearFactoryRegistry();
parser_->MetadataClear("vnc_cfg");
xmpp_server_->Shutdown();
task_util::WaitForIdle();
TcpServerManager::DeleteServer(xmpp_server_);
xmpp_server_ = NULL;
evm_.Shutdown();
if (thread_.get() != NULL) {
thread_->Join();
}
}
void IFMap_Initialize() {
IFMapLinkTable_Init(ifmap_server_.database(), ifmap_server_.graph());
parser_ = IFMapServerParser::GetInstance("vnc_cfg");
vnc_cfg_ParserInit(parser_);
vnc_cfg_Server_ModuleInit(ifmap_server_.database(),
ifmap_server_.graph());
ifmap_server_.Initialize();
vm_uuid_mapper_ = ifmap_server_.vm_uuid_mapper();
}
IFMapNode *TableLookup(const string &type, const string &name) {
IFMapTable *tbl = IFMapTable::FindTable(&db_, type);
if (tbl == NULL) {
return NULL;
}
return tbl->FindNode(name);
}
IFMapLink *LinkLookup(IFMapNode *lhs, IFMapNode *rhs) {
IFMapLink *link = static_cast<IFMapLink *>(graph_.GetEdge(lhs, rhs));
return link;
}
bool LinkOriginLookup(IFMapLink *link, IFMapOrigin::Origin orig) {
return link->HasOrigin(orig);
}
bool NodeOriginLookup(IFMapNode *node, IFMapOrigin::Origin orig) {
if (node->Find(orig) == NULL) {
return false;
} else {
return true;
}
}
void ConfigUpdate(XmppServer *server, const XmppConfigData *config) {
}
void ConfigUpdate(XmppClient *client, const XmppConfigData *config) {
client->ConfigUpdate(config);
}
static void on_timeout(const boost::system::error_code &error,
bool *trigger) {
if (error) {
LOG(DEBUG, "Error is " << error.message());
return;
}
*trigger = true;
}
// Usage of this causes the thread to be blocked at RunOnce()
// waiting for an event to be triggered
void EventWait(boost::function<bool()> condition, int timeout) {
if (condition()) {
return;
}
bool is_expired = false;
TimerImpl timer(*evm_.io_service());
boost::system::error_code ec;
timer.expires_from_now(timeout * 1000, ec);
timer.async_wait(boost::bind(&XmppIfmapTest::on_timeout,
boost::asio::placeholders::error, &is_expired));
while (!is_expired) {
evm_.RunOnce();
task_util::WaitForIdle();
if ((condition)()) {
timer.cancel(ec);
break;
}
}
ASSERT_TRUE((condition)());
}
int GetSentMsgs(XmppServer *server, const string &client_name) {
IFMapXmppChannel *scli = ifmap_channel_mgr_->FindChannel(client_name);
return ((scli == NULL) ? 0 : scli->msgs_sent());
}
IFMapClient *GetIfmapClientFromChannel(const string &client_name) {
XmppConnection *connection = xmpp_server_->FindConnection(client_name);
assert(connection);
XmppChannel *xchannel = connection->ChannelMux();
assert(xchannel);
IFMapXmppChannel *ixchannel = ifmap_channel_mgr_->FindChannel(xchannel);
assert(ixchannel);
return ixchannel->Sender();
}
void QueueClientAddToIFMapServer(const string &client_name) {
IFMapXmppChannel *scli = ifmap_channel_mgr_->FindChannel(client_name);
scli->ProcessVrSubscribe(client_name);
}
void TriggerNotReady(const string &client_name) {
IFMapXmppChannel *scli = ifmap_channel_mgr_->FindChannel(client_name);
XmppChannel *channel = scli->channel();
ifmap_channel_mgr_->ProcessChannelNotReady(channel);
}
void CheckLinkBits(DBGraphEdge *edge, int index, bool binterest,
bool badvertised) {
IFMapLink *link = static_cast<IFMapLink *>(edge);
IFMapLinkState *state = exporter_->LinkStateLookup(link);
TASK_UTIL_EXPECT_TRUE(state->interest().test(index) == binterest);
TASK_UTIL_EXPECT_TRUE(state->advertised().test(index) == badvertised);
}
void CheckNodeBits(DBGraphVertex *vertex, int index, bool binterest,
bool badvertised) {
IFMapNode *node = static_cast<IFMapNode *>(vertex);
IFMapNodeState *state = exporter_->NodeStateLookup(node);
TASK_UTIL_EXPECT_TRUE(state->interest().test(index) == binterest);
TASK_UTIL_EXPECT_TRUE(state->advertised().test(index) == badvertised);
}
void CheckClientBits(const string &client_name, size_t index,
bool binterest, bool badvertised) {
IFMapNode *node = TableLookup("virtual-router", client_name);
if (node) {
IFMapNodeState *state = exporter_->NodeStateLookup(node);
TASK_UTIL_EXPECT_TRUE(state->interest().test(index) == binterest);
TASK_UTIL_EXPECT_TRUE(state->advertised().test(index)
== badvertised);
graph_.Visit(node,
boost::bind(&XmppIfmapTest::CheckNodeBits, this, _1,
index, binterest, badvertised),
boost::bind(&XmppIfmapTest::CheckLinkBits, this, _1,
index, binterest, badvertised));
}
}
void CheckNodeBitsAndCount(DBGraphVertex *vertex, int index, bool binterest,
bool badvertised, int *count) {
IFMapNode *node = static_cast<IFMapNode *>(vertex);
IFMapNodeState *state = exporter_->NodeStateLookup(node);
TASK_UTIL_EXPECT_TRUE(state->interest().test(index) == binterest);
TASK_UTIL_EXPECT_TRUE(state->advertised().test(index) == badvertised);
++(*count);
}
void CheckLinkBitsAndCount(DBGraphEdge *edge, int index, bool binterest,
bool badvertised, int *count) {
IFMapLink *link = static_cast<IFMapLink *>(edge);
IFMapLinkState *state = exporter_->LinkStateLookup(link);
TASK_UTIL_EXPECT_TRUE(state->interest().test(index) == binterest);
TASK_UTIL_EXPECT_TRUE(state->advertised().test(index) == badvertised);
++(*count);
}
int ClientGraphWalkVerify(const string &client_name, size_t index,
bool binterest, bool badvertised) {
int count = 0;
IFMapNode *node = TableLookup("virtual-router", client_name);
if (node) {
IFMapNodeState *state = exporter_->NodeStateLookup(node);
TASK_UTIL_EXPECT_TRUE(state->interest().test(index) == binterest);
TASK_UTIL_EXPECT_TRUE(state->advertised().test(index)
== badvertised);
graph_.Visit(node,
boost::bind(&XmppIfmapTest::CheckNodeBitsAndCount, this, _1,
index, binterest, badvertised, &count),
boost::bind(&XmppIfmapTest::CheckLinkBitsAndCount, this, _1,
index, binterest, badvertised, &count),
exporter_->get_traversal_white_list());
}
return count;
}
void SetObjectsPerMessage(int num) {
ifmap_server_.sender()->SetObjectsPerMessage(num);
}
// This will also release the IFMapClient and IfmapXmppChannel. When the
// channel goes down due to tcp-close, we will not find the
// IFMapXmppChannel in channel_map_ and wont try to redo everything again.
void TriggerDeleteClient(IFMapClient *client, string client_name) {
IFMapXmppChannel *scli =ifmap_channel_mgr_->FindChannel(client_name);
ifmap_server_.SimulateDeleteClient(client);
ifmap_channel_mgr_->DeleteIFMapXmppChannel(scli);
}
void TriggerLinkDeleteToExporter(IFMapLink *link, IFMapNode *left,
IFMapNode *right) {
link->MarkDelete();
graph_.Unlink(left, right);
IFMapLinkTable *link_table = static_cast<IFMapLinkTable *>(
db_.FindTable("__ifmap_metadata__.0"));
DBTablePartBase *partition = link_table->GetTablePartition(0);
exporter_->LinkTableExport(partition, link);
}
size_t InterestConfigTrackerSize(int index) {
return exporter_->ClientConfigTrackerSize(IFMapExporter::INTEREST,
index);
}
DB db_;
DBGraph graph_;
EventManager evm_;
IFMapServer ifmap_server_;
IFMapExporter *exporter_;
IFMapServerParser *parser_;
auto_ptr<ServerThread> thread_;
XmppServer *xmpp_server_;
auto_ptr<IFMapChannelManager> ifmap_channel_mgr_;
IFMapVmUuidMapper *vm_uuid_mapper_;
};
const string XmppIfmapTest::kDefaultClientName = "phys-host-1";
const string XmppIfmapTest::kDefaultXmppServerAddress = "127.0.0.1";
const string XmppIfmapTest::kDefaultXmppServerName = "bgp.contrail.com";
const string XmppIfmapTest::kDefaultXmppServerConfigName =
"bgp.contrail.com/config";
namespace {
static string GetUserName() {
return string(getenv("LOGNAME"));
}
static XmppChannel* GetXmppChannel(XmppServer *server,
const string &client_name) {
XmppConnection *connection = server->FindConnection(client_name);
if (connection) {
return connection->ChannelMux();
}
return NULL;
}
static bool ServerIsEstablished(XmppServer *server, const string &client_name) {
XmppConnection *connection = server->FindConnection(client_name);
if (connection == NULL) {
return false;
}
return (connection->GetStateMcState() == xmsm::ESTABLISHED);
}
static string FileRead(const string &filename) {
ifstream file(filename.c_str());
string content((istreambuf_iterator<char>(file)),
istreambuf_iterator<char>());
return content;
}
bool IsIFMapClientUnregistered(IFMapServer *ifmap_server,
const string &client_name) {
if (ifmap_server->FindClient(client_name) == NULL) {
return true;
}
return false;
}
TEST_F(XmppIfmapTest, Connection) {
string host_vm_name = "aad4c946-9390-4a53-8bbd-09d346f5ba6c";
// Read the ifmap data from file
string content(FileRead("controller/src/ifmap/testdata/two-vn-connection"));
assert(content.size() != 0);
// Give the read file to the parser
parser_->Receive(&db_, content.data(), content.size(), 0);
task_util::WaitForIdle();
// create the mock client
string client_name(kDefaultClientName);
string filename("/tmp/" + GetUserName() + "_connection.output");
IFMapXmppClientMock *vnsw_client =
new IFMapXmppClientMock(&evm_, xmpp_server_->GetPort(), client_name,
filename);
TASK_UTIL_EXPECT_EQ(true, vnsw_client->IsEstablished());
vnsw_client->RegisterWithXmpp();
// server connection
TASK_UTIL_EXPECT_TRUE(ServerIsEstablished(xmpp_server_, client_name)
== true);
// verify ifmap_server client is not created until config subscribe
TASK_UTIL_EXPECT_TRUE(ifmap_server_.FindClient(client_name) == NULL);
// no config messages sent until config subscribe
TASK_UTIL_EXPECT_EQ(0, vnsw_client->Count());
// subscribe to config
vnsw_client->SendConfigSubscribe();
TASK_UTIL_EXPECT_TRUE(ifmap_server_.FindClient(client_name) != NULL);
vnsw_client->SendVmConfigSubscribe(host_vm_name);
TASK_UTIL_EXPECT_EQ(true, vnsw_client->Has2Messages());
TASK_UTIL_EXPECT_EQ(2, vnsw_client->Count());
cout << "Rx msgs " << vnsw_client->Count() << endl;
cout << "Sent msgs " << GetSentMsgs(xmpp_server_, client_name) << endl;
// verify ifmap_server client creation
TASK_UTIL_EXPECT_TRUE(ifmap_server_.FindClient(client_name) != NULL);
vnsw_client->OutputRecvBufferToFile();
EXPECT_EQ(ifmap_server_.GetClientMapSize(), 1);
// client close generates a TcpClose event on server
ConfigUpdate(vnsw_client, new XmppConfigData());
TASK_UTIL_EXPECT_EQ(ifmap_server_.GetClientMapSize(), 0);
// verify ifmap_server client cleanup
EXPECT_EQ(true, IsIFMapClientUnregistered(&ifmap_server_, client_name));
vnsw_client->UnRegisterWithXmpp();
vnsw_client->Shutdown();
task_util::WaitForIdle();
TcpServerManager::DeleteServer(vnsw_client);
vnsw_client = NULL;
//Delete xmpp-channel explicitly
XmppConnection *sconnection = xmpp_server_->FindConnection(client_name);
if (sconnection) {
sconnection->Shutdown();
}
TASK_UTIL_EXPECT_EQ(xmpp_server_->ConnectionCount(), 0);
EXPECT_TRUE(xmpp_server_->FindConnection(client_name) == NULL);
}
// Create 2 client connections back2back with the same client name
TEST_F(XmppIfmapTest, CheckClientGraphCleanupTest) {
string host_vm_name = "aad4c946-9390-4a53-8bbd-09d346f5ba6c";
// Read the ifmap data from file
string content(FileRead("controller/src/ifmap/testdata/two-vn-connection"));
assert(content.size() != 0);
// Give the read file to the parser
parser_->Receive(&db_, content.data(), content.size(), 0);
task_util::WaitForIdle();
// create the mock client
string client_name(kDefaultClientName);
string filename("/tmp/" + GetUserName() + "_graph_cleanup_1.output");
IFMapXmppClientMock *vnsw_client =
new IFMapXmppClientMock(&evm_, xmpp_server_->GetPort(), client_name,
filename);
TASK_UTIL_EXPECT_EQ(true, vnsw_client->IsEstablished());
vnsw_client->RegisterWithXmpp();
usleep(1000);
// server connection
TASK_UTIL_EXPECT_TRUE(ServerIsEstablished(xmpp_server_, client_name)
== true);
// verify ifmap_server client is not created until config subscribe
TASK_UTIL_EXPECT_TRUE(ifmap_server_.FindClient(client_name) == NULL);
// no config messages sent until config subscribe
TASK_UTIL_EXPECT_EQ(0, vnsw_client->Count());
// subscribe to config
vnsw_client->SendConfigSubscribe();
TASK_UTIL_EXPECT_TRUE(ifmap_server_.FindClient(client_name) != NULL);
vnsw_client->SendVmConfigSubscribe(host_vm_name);
TASK_UTIL_EXPECT_EQ(true, vnsw_client->Has2Messages());
TASK_UTIL_EXPECT_NE(0, vnsw_client->Count());
// verify ifmap_server client creation
IFMapClient *client = ifmap_server_.FindClient(client_name);
EXPECT_TRUE(client != NULL);
size_t cli_index = static_cast<size_t>(client->index());
vnsw_client->OutputRecvBufferToFile();
EXPECT_EQ(ifmap_server_.GetClientMapSize(), 1);
// client close generates a TcpClose event on server
ConfigUpdate(vnsw_client, new XmppConfigData());
TASK_UTIL_EXPECT_EQ(ifmap_server_.GetClientMapSize(), 0);
// verify ifmap_server client cleanup
EXPECT_EQ(true, IsIFMapClientUnregistered(&ifmap_server_, client_name));
// interest and advertised must be false since the client is gone
CheckClientBits(client_name, cli_index, false, false);
vnsw_client->UnRegisterWithXmpp();
vnsw_client->Shutdown();
task_util::WaitForIdle();
TcpServerManager::DeleteServer(vnsw_client);
vnsw_client = NULL;
//Delete xmpp-channel explicitly
XmppConnection *sconnection = xmpp_server_->FindConnection(client_name);
if (sconnection) {
sconnection->Shutdown();
}
TASK_UTIL_EXPECT_TRUE(xmpp_server_->FindConnection(client_name) == NULL);
/////////////////////////////////////////////////////////
// repeat the whole thing by creating one more connection
/////////////////////////////////////////////////////////
// create the mock client
filename = "/tmp/" + GetUserName() + "_graph_cleanup_2.output";
vnsw_client =
new IFMapXmppClientMock(&evm_, xmpp_server_->GetPort(), client_name,
filename);
TASK_UTIL_EXPECT_EQ(true, vnsw_client->IsEstablished());
vnsw_client->RegisterWithXmpp();
usleep(1000);
// server connection
TASK_UTIL_EXPECT_TRUE(ServerIsEstablished(xmpp_server_, client_name)
== true);
// verify ifmap_server client is not created until config subscribe
TASK_UTIL_EXPECT_TRUE(ifmap_server_.FindClient(client_name) == NULL);
// no config messages sent until config subscribe
TASK_UTIL_EXPECT_EQ(0, vnsw_client->Count());
// subscribe to config
vnsw_client->SendConfigSubscribe();
TASK_UTIL_EXPECT_TRUE(ifmap_server_.FindClient(client_name) != NULL);
vnsw_client->SendVmConfigSubscribe(host_vm_name);
TASK_UTIL_EXPECT_EQ(true, vnsw_client->Has2Messages());
TASK_UTIL_EXPECT_NE(0, vnsw_client->Count());
// verify ifmap_server client creation
client = ifmap_server_.FindClient(client_name);
TASK_UTIL_EXPECT_TRUE(client != NULL);
size_t cli_index1 = static_cast<size_t>(client->index());
TASK_UTIL_EXPECT_EQ(cli_index1, cli_index);
vnsw_client->OutputRecvBufferToFile();
EXPECT_EQ(ifmap_server_.GetClientMapSize(), 1);
// client close generates a TcpClose event on server
vnsw_client->ConfigUpdate(new XmppConfigData());
TASK_UTIL_EXPECT_EQ(ifmap_server_.GetClientMapSize(), 0);
// verify ifmap_server client cleanup
EXPECT_EQ(true, IsIFMapClientUnregistered(&ifmap_server_, client_name));
// interest and advertised must be false since the client is gone
CheckClientBits(vnsw_client->name(), cli_index, false, false);
vnsw_client->UnRegisterWithXmpp();
vnsw_client->Shutdown();
task_util::WaitForIdle();
TcpServerManager::DeleteServer(vnsw_client);
vnsw_client = NULL;
//Delete xmpp-channel explicitly
sconnection = xmpp_server_->FindConnection(client_name);
if (sconnection) {
sconnection->Shutdown();
}
TASK_UTIL_EXPECT_EQ(xmpp_server_->ConnectionCount(), 0);
EXPECT_TRUE(xmpp_server_->FindConnection(client_name) == NULL);
}
TEST_F(XmppIfmapTest, DeleteProperty) {
string host_vm_name = "aad4c946-9390-4a53-8bbd-09d346f5ba6c";
// Read the ifmap data from file and give it to the parser
string content(FileRead("controller/src/ifmap/testdata/two-vn-connection"));
assert(content.size() != 0);
parser_->Receive(&db_, content.data(), content.size(), 0);
task_util::WaitForIdle();
// create the mock client
string client_name(kDefaultClientName);
string filename("/tmp/" + GetUserName() + "_delete_property.output");
IFMapXmppClientMock *vnsw_client =
new IFMapXmppClientMock(&evm_, xmpp_server_->GetPort(), client_name,
filename);
TASK_UTIL_EXPECT_EQ(true, vnsw_client->IsEstablished());
vnsw_client->RegisterWithXmpp();
usleep(1000);
// server connection
TASK_UTIL_EXPECT_TRUE(ServerIsEstablished(xmpp_server_, client_name)
== true);
// verify ifmap_server client is not created until config subscribe
TASK_UTIL_EXPECT_TRUE(ifmap_server_.FindClient(client_name) == NULL);
// no config messages sent until config subscribe
TASK_UTIL_EXPECT_EQ(0, vnsw_client->Count());
//subscribe to config
vnsw_client->SendConfigSubscribe();
TASK_UTIL_EXPECT_TRUE(ifmap_server_.FindClient(client_name) != NULL);
vnsw_client->SendVmConfigSubscribe(host_vm_name);
TASK_UTIL_EXPECT_EQ(true, vnsw_client->Has2Messages());
TASK_UTIL_EXPECT_EQ(2, vnsw_client->Count());
// verify ifmap_server client creation
IFMapClient *client = ifmap_server_.FindClient(client_name);
EXPECT_TRUE(client != NULL);
size_t cli_index = static_cast<size_t>(client->index());
// Deleting one property
content = FileRead("controller/src/ifmap/testdata/vn_prop_del.xml");
assert(content.size() != 0);
parser_->Receive(&db_, content.data(), content.size(), 0);
task_util::WaitForIdle();
TASK_UTIL_EXPECT_EQ(3, vnsw_client->Count());
vnsw_client->OutputRecvBufferToFile();
EXPECT_EQ(ifmap_server_.GetClientMapSize(), 1);
// client close generates a TcpClose event on server
ConfigUpdate(vnsw_client, new XmppConfigData());
TASK_UTIL_EXPECT_EQ(ifmap_server_.GetClientMapSize(), 0);
// verify ifmap_server client cleanup
EXPECT_EQ(true, IsIFMapClientUnregistered(&ifmap_server_, client_name));
// interest and advertised must be false since the client is gone
CheckClientBits(vnsw_client->name(), cli_index, false, false);
vnsw_client->UnRegisterWithXmpp();
vnsw_client->Shutdown();
task_util::WaitForIdle();
TcpServerManager::DeleteServer(vnsw_client);
vnsw_client = NULL;
//Delete xmpp-channel explicitly
XmppConnection *sconnection = xmpp_server_->FindConnection(client_name);
if (sconnection) {
sconnection->Shutdown();
}
TASK_UTIL_EXPECT_EQ(xmpp_server_->ConnectionCount(), 0);
EXPECT_TRUE(xmpp_server_->FindConnection(client_name) == NULL);
}
TEST_F(XmppIfmapTest, VrVmSubUnsub) {
string host_vm_name = "aad4c946-9390-4a53-8bbd-09d346f5ba6c";
// Give the read file to the parser
string content(FileRead("controller/src/ifmap/testdata/two-vn-connection"));
assert(content.size() != 0);
parser_->Receive(&db_, content.data(), content.size(), 0);
task_util::WaitForIdle();
// Create the mock client
string client_name(kDefaultClientName);
string filename("/tmp/" + GetUserName() + "_vr_vm_sub_unsub.output");
IFMapXmppClientMock *vnsw_client =
new IFMapXmppClientMock(&evm_, xmpp_server_->GetPort(), client_name,
filename);
TASK_UTIL_EXPECT_EQ(true, vnsw_client->IsEstablished());
vnsw_client->RegisterWithXmpp();
usleep(1000);
// Server connection
TASK_UTIL_EXPECT_TRUE(ServerIsEstablished(xmpp_server_, client_name)
== true);
// Verify ifmap_server client is not created until config subscribe
TASK_UTIL_EXPECT_TRUE(ifmap_server_.FindClient(kDefaultClientName) == NULL);
// No config messages sent until config subscribe
TASK_UTIL_EXPECT_EQ(0, vnsw_client->Count());
// Subscribe to config
vnsw_client->SendConfigSubscribe();
TASK_UTIL_EXPECT_TRUE(ifmap_server_.FindClient(client_name) != NULL);
TASK_UTIL_EXPECT_EQ(0, vnsw_client->Count());
IFMapClient *client = ifmap_server_.FindClient(client_name);
EXPECT_TRUE(client != NULL);
// The link between VR-VM should not exist
IFMapNode *vr = TableLookup("virtual-router", kDefaultClientName);
EXPECT_TRUE(vr != NULL);
IFMapNode *vm = TableLookup("virtual-machine", host_vm_name);
EXPECT_TRUE(vm != NULL);
IFMapLink *link = LinkLookup(vr, vm);
EXPECT_TRUE(link == NULL);
// After sending subscribe, client should get all the nodes.
// The link should not exist before the subscribe and should exist after.
size_t num_msgs = vnsw_client->Count();
vnsw_client->SendVmConfigSubscribe(host_vm_name);
usleep(1000);
TASK_UTIL_EXPECT_EQ(client->msgs_sent(), vnsw_client->Count());
TASK_UTIL_EXPECT_EQ(true, vnsw_client->HasNMessages(num_msgs + 2));
cout << "Rx msgs " << vnsw_client->Count() << endl;
cout << "Sent msgs " << GetSentMsgs(xmpp_server_, client_name) << endl;
link = LinkLookup(vr, vm);
EXPECT_TRUE(link != NULL);
bool link_origin = LinkOriginLookup(link, IFMapOrigin::XMPP);
EXPECT_TRUE(link_origin);
TASK_UTIL_EXPECT_TRUE(NodeOriginLookup(vr, IFMapOrigin::MAP_SERVER));
TASK_UTIL_EXPECT_TRUE(NodeOriginLookup(vr, IFMapOrigin::XMPP));
TASK_UTIL_EXPECT_TRUE(NodeOriginLookup(vm, IFMapOrigin::MAP_SERVER));
TASK_UTIL_EXPECT_TRUE(NodeOriginLookup(vm, IFMapOrigin::XMPP));
size_t cli_index = static_cast<size_t>(client->index());
CheckLinkBits(link, cli_index, true, true);
CheckNodeBits(vr, cli_index, true, true);
CheckNodeBits(vm, cli_index, true, true);
// After sending unsubscribe, client should get a delete for the vr-vm
// link. The link should not have XMPP as origin anymore.
num_msgs = vnsw_client->Count();
vnsw_client->SendVmConfigUnsubscribe(host_vm_name);
usleep(1000);
TASK_UTIL_EXPECT_EQ(true, vnsw_client->HasNMessages(num_msgs + 3));
cout << "Rx msgs " << vnsw_client->Count() << endl;
cout << "Sent msgs " << GetSentMsgs(xmpp_server_, client_name) << endl;
link = LinkLookup(vr, vm);
EXPECT_TRUE(link == NULL);
CheckNodeBits(vr, cli_index, true, true);
CheckNodeBits(vm, cli_index, false, false);
TASK_UTIL_EXPECT_TRUE(NodeOriginLookup(vr, IFMapOrigin::MAP_SERVER));
TASK_UTIL_EXPECT_FALSE(NodeOriginLookup(vr, IFMapOrigin::XMPP));
TASK_UTIL_EXPECT_TRUE(NodeOriginLookup(vm, IFMapOrigin::MAP_SERVER));
TASK_UTIL_EXPECT_FALSE(NodeOriginLookup(vm, IFMapOrigin::XMPP));
vnsw_client->OutputRecvBufferToFile();
EXPECT_EQ(ifmap_server_.GetClientMapSize(), 1);
// Client close generates a TcpClose event on server
ConfigUpdate(vnsw_client, new XmppConfigData());
TASK_UTIL_EXPECT_EQ(ifmap_server_.GetClientMapSize(), 0);
// Verify ifmap_server client cleanup
EXPECT_EQ(true, IsIFMapClientUnregistered(&ifmap_server_, client_name));
// interest and advertised must be false since the client is gone
CheckClientBits(vnsw_client->name(), cli_index, false, false);
vnsw_client->UnRegisterWithXmpp();
vnsw_client->Shutdown();
task_util::WaitForIdle();
TcpServerManager::DeleteServer(vnsw_client);
vnsw_client = NULL;
// Delete xmpp-channel explicitly
XmppConnection *sconnection = xmpp_server_->FindConnection(client_name);
if (sconnection) {
sconnection->Shutdown();
}
TASK_UTIL_EXPECT_EQ(xmpp_server_->ConnectionCount(), 0);
EXPECT_TRUE(xmpp_server_->FindConnection(client_name) == NULL);
}
TEST_F(XmppIfmapTest, VrVmSubUnsubTwice) {
string host_vm_name = "aad4c946-9390-4a53-8bbd-09d346f5ba6c";
// Read the ifmap data from file
string content(FileRead("controller/src/ifmap/testdata/two-vn-connection"));
assert(content.size() != 0);
parser_->Receive(&db_, content.data(), content.size(), 0);
task_util::WaitForIdle();
// Create the mock client
string client_name(kDefaultClientName);
string filename("/tmp/" + GetUserName() + "_vr_vm_sub_unsub_twice.output");
IFMapXmppClientMock *vnsw_client =
new IFMapXmppClientMock(&evm_, xmpp_server_->GetPort(), client_name,
filename);
TASK_UTIL_EXPECT_EQ(true, vnsw_client->IsEstablished());
vnsw_client->RegisterWithXmpp();
usleep(1000);
// Server connection
TASK_UTIL_EXPECT_TRUE(ServerIsEstablished(xmpp_server_, client_name)
== true);
// verify ifmap_server client is not created until config subscribe
TASK_UTIL_EXPECT_TRUE(ifmap_server_.FindClient(client_name) == NULL);
// no config messages sent until config subscribe
TASK_UTIL_EXPECT_EQ(0, vnsw_client->Count());
// Subscribe to config
vnsw_client->SendConfigSubscribe();
TASK_UTIL_EXPECT_TRUE(ifmap_server_.FindClient(client_name) != NULL);
TASK_UTIL_EXPECT_EQ(0, vnsw_client->Count());
// Verify ifmap_server client creation
IFMapClient *client = ifmap_server_.FindClient(kDefaultClientName);
EXPECT_TRUE(client != NULL);
// The link between VR-VM should not exist
IFMapNode *vr = TableLookup("virtual-router", kDefaultClientName);
EXPECT_TRUE(vr != NULL);
IFMapNode *vm = TableLookup("virtual-machine", host_vm_name);
EXPECT_TRUE(vm != NULL);
IFMapLink *link = LinkLookup(vr, vm);
EXPECT_TRUE(link == NULL);
// After sending subscribe, client should get an add for the vr-vm link.
// The link should not exist before the subscribe and should exist after.
size_t num_msgs = vnsw_client->Count();
vnsw_client->SendVmConfigSubscribe(host_vm_name);
usleep(1000);
TASK_UTIL_EXPECT_EQ(client->msgs_sent(), vnsw_client->Count());
TASK_UTIL_EXPECT_EQ(true, vnsw_client->HasNMessages(num_msgs + 2));
cout << "Rx msgs " << vnsw_client->Count() << endl;
cout << "Sent msgs " << GetSentMsgs(xmpp_server_, client_name) << endl;
link = LinkLookup(vr, vm);
EXPECT_TRUE(link != NULL);
bool link_origin = LinkOriginLookup(link, IFMapOrigin::XMPP);
EXPECT_TRUE(link_origin);
TASK_UTIL_EXPECT_TRUE(NodeOriginLookup(vr, IFMapOrigin::MAP_SERVER));
TASK_UTIL_EXPECT_TRUE(NodeOriginLookup(vr, IFMapOrigin::XMPP));
TASK_UTIL_EXPECT_TRUE(NodeOriginLookup(vm, IFMapOrigin::MAP_SERVER));
TASK_UTIL_EXPECT_TRUE(NodeOriginLookup(vm, IFMapOrigin::XMPP));
size_t cli_index = static_cast<size_t>(client->index());
CheckLinkBits(link, cli_index, true, true);
CheckNodeBits(vr, cli_index, true, true);
CheckNodeBits(vm, cli_index, true, true);
// After sending unsubscribe, client should get a delete for the vr-vm
// link. The link should not exist in the ctrl-node db anymore.
num_msgs = vnsw_client->Count();
vnsw_client->SendVmConfigUnsubscribe(host_vm_name);
usleep(1000);
TASK_UTIL_EXPECT_EQ(true, vnsw_client->HasNMessages(num_msgs + 3));
cout << "Rx msgs " << vnsw_client->Count() << endl;
cout << "Sent msgs " << GetSentMsgs(xmpp_server_, client_name) << endl;
link = LinkLookup(vr, vm);
EXPECT_TRUE(link == NULL);
CheckNodeBits(vr, cli_index, true, true);
CheckNodeBits(vm, cli_index, false, false);
TASK_UTIL_EXPECT_TRUE(NodeOriginLookup(vr, IFMapOrigin::MAP_SERVER));
TASK_UTIL_EXPECT_FALSE(NodeOriginLookup(vr, IFMapOrigin::XMPP));
TASK_UTIL_EXPECT_TRUE(NodeOriginLookup(vm, IFMapOrigin::MAP_SERVER));
TASK_UTIL_EXPECT_FALSE(NodeOriginLookup(vm, IFMapOrigin::XMPP));
// Send a subscribe-unsubscribe again.
num_msgs = vnsw_client->Count();
vnsw_client->SendVmConfigSubscribe(host_vm_name);
usleep(1000);
TASK_UTIL_EXPECT_EQ(client->msgs_sent(), vnsw_client->Count());
// We should download everything since Unsubscribe above would have reset
// interest/advertised.
TASK_UTIL_EXPECT_EQ(true, vnsw_client->HasNMessages(num_msgs + 2));
cout << "Rx msgs " << vnsw_client->Count() << endl;
cout << "Sent msgs " << GetSentMsgs(xmpp_server_, client_name) << endl;
link = LinkLookup(vr, vm);
EXPECT_TRUE(link != NULL);
link_origin = LinkOriginLookup(link, IFMapOrigin::XMPP);
EXPECT_TRUE(link_origin);
TASK_UTIL_EXPECT_TRUE(NodeOriginLookup(vr, IFMapOrigin::MAP_SERVER));
TASK_UTIL_EXPECT_TRUE(NodeOriginLookup(vr, IFMapOrigin::XMPP));
TASK_UTIL_EXPECT_TRUE(NodeOriginLookup(vm, IFMapOrigin::MAP_SERVER));
TASK_UTIL_EXPECT_TRUE(NodeOriginLookup(vm, IFMapOrigin::XMPP));
CheckLinkBits(link, cli_index, true, true);
CheckNodeBits(vr, cli_index, true, true);
CheckNodeBits(vm, cli_index, true, true);
num_msgs = vnsw_client->Count();
vnsw_client->SendVmConfigUnsubscribe(host_vm_name);
usleep(1000);
// Should get a delete for the link
TASK_UTIL_EXPECT_EQ(true, vnsw_client->HasNMessages(num_msgs + 3));
cout << "Rx msgs " << vnsw_client->Count() << endl;
cout << "Sent msgs " << GetSentMsgs(xmpp_server_, client_name) << endl;
link = LinkLookup(vr, vm);
EXPECT_TRUE(link == NULL);
CheckNodeBits(vr, cli_index, true, true);
CheckNodeBits(vm, cli_index, false, false);
TASK_UTIL_EXPECT_TRUE(NodeOriginLookup(vr, IFMapOrigin::MAP_SERVER));
TASK_UTIL_EXPECT_FALSE(NodeOriginLookup(vr, IFMapOrigin::XMPP));
TASK_UTIL_EXPECT_TRUE(NodeOriginLookup(vm, IFMapOrigin::MAP_SERVER));
TASK_UTIL_EXPECT_FALSE(NodeOriginLookup(vm, IFMapOrigin::XMPP));
vnsw_client->OutputRecvBufferToFile();
EXPECT_EQ(ifmap_server_.GetClientMapSize(), 1);
// Client close generates a TcpClose event on server
ConfigUpdate(vnsw_client, new XmppConfigData());
TASK_UTIL_EXPECT_EQ(ifmap_server_.GetClientMapSize(), 0);
// Verify ifmap_server client cleanup
EXPECT_EQ(true, IsIFMapClientUnregistered(&ifmap_server_, client_name));
// interest and advertised must be false since the client is gone
CheckClientBits(vnsw_client->name(), cli_index, false, false);
vnsw_client->UnRegisterWithXmpp();
vnsw_client->Shutdown();
task_util::WaitForIdle();
TcpServerManager::DeleteServer(vnsw_client);
vnsw_client = NULL;
//Delete xmpp-channel explicitly
XmppConnection *sconnection = xmpp_server_->FindConnection(client_name);
if (sconnection) {
sconnection->Shutdown();
}
TASK_UTIL_EXPECT_EQ(xmpp_server_->ConnectionCount(), 0);
EXPECT_TRUE(xmpp_server_->FindConnection(client_name) == NULL);
}
// 3 consecutive subscribe requests with no unsubscribe in between
TEST_F(XmppIfmapTest, VrVmSubThrice) {
string host_vm_name = "aad4c946-9390-4a53-8bbd-09d346f5ba6c";
// Read the ifmap data from file
string content(FileRead("controller/src/ifmap/testdata/two-vn-connection"));
assert(content.size() != 0);
parser_->Receive(&db_, content.data(), content.size(), 0);
task_util::WaitForIdle();
// Create the mock client
string client_name(kDefaultClientName);
string filename("/tmp/" + GetUserName() + "_vr_vm_sub_thrice.output");
IFMapXmppClientMock *vnsw_client =
new IFMapXmppClientMock(&evm_, xmpp_server_->GetPort(), client_name,
filename);
TASK_UTIL_EXPECT_EQ(true, vnsw_client->IsEstablished());
vnsw_client->RegisterWithXmpp();
usleep(1000);
// server connection
TASK_UTIL_EXPECT_TRUE(ServerIsEstablished(xmpp_server_, client_name)
== true);
// Verify ifmap_server client is not created until config subscribe
TASK_UTIL_EXPECT_TRUE(ifmap_server_.FindClient(client_name) == NULL);
// No config messages sent until config subscribe
TASK_UTIL_EXPECT_EQ(0, vnsw_client->Count());
// Subscribe to config
vnsw_client->SendConfigSubscribe();
TASK_UTIL_EXPECT_TRUE(ifmap_server_.FindClient(client_name) != NULL);
TASK_UTIL_EXPECT_EQ(0, vnsw_client->Count());
// Verify ifmap_server client creation
IFMapClient *client = ifmap_server_.FindClient(kDefaultClientName);
EXPECT_TRUE(client != NULL);
// The link between VR-VM should not exist
IFMapNode *vr = TableLookup("virtual-router", kDefaultClientName);
EXPECT_TRUE(vr != NULL);
IFMapNode *vm = TableLookup("virtual-machine", host_vm_name);
EXPECT_TRUE(vm != NULL);
IFMapLink *link = LinkLookup(vr, vm);
EXPECT_TRUE(link == NULL);
// After sending subscribe, client should get an add for the vr-vm link.
// The link should not exist before the subscribe and should exist after.
size_t num_msgs = vnsw_client->Count();
vnsw_client->SendVmConfigSubscribe(host_vm_name);
usleep(1000);
TASK_UTIL_EXPECT_EQ(client->msgs_sent(), vnsw_client->Count());
TASK_UTIL_EXPECT_EQ(true, vnsw_client->HasNMessages(num_msgs + 2));
cout << "Rx msgs " << vnsw_client->Count() << endl;
cout << "Sent msgs " << GetSentMsgs(xmpp_server_, client_name) << endl;
EXPECT_EQ(ifmap_channel_mgr_->get_dupicate_vmsub_messages(), 0);
link = LinkLookup(vr, vm);
EXPECT_TRUE(link != NULL);
bool link_origin = LinkOriginLookup(link, IFMapOrigin::XMPP);
EXPECT_TRUE(link_origin);
TASK_UTIL_EXPECT_TRUE(NodeOriginLookup(vr, IFMapOrigin::MAP_SERVER));
TASK_UTIL_EXPECT_TRUE(NodeOriginLookup(vr, IFMapOrigin::XMPP));
TASK_UTIL_EXPECT_TRUE(NodeOriginLookup(vm, IFMapOrigin::MAP_SERVER));
TASK_UTIL_EXPECT_TRUE(NodeOriginLookup(vm, IFMapOrigin::XMPP));
size_t cli_index = static_cast<size_t>(client->index());
CheckLinkBits(link, cli_index, true, true);
CheckNodeBits(vr, cli_index, true, true);
CheckNodeBits(vm, cli_index, true, true);
// 2nd spurious subscribe
num_msgs = vnsw_client->Count();
vnsw_client->SendVmConfigSubscribe(host_vm_name);
task_util::WaitForIdle();
usleep(1000);
TASK_UTIL_EXPECT_EQ(ifmap_channel_mgr_->get_dupicate_vmsub_messages(), 1);
EXPECT_EQ(vnsw_client->HasNMessages(num_msgs), true);
link = LinkLookup(vr, vm);
EXPECT_TRUE(link != NULL);
link_origin = LinkOriginLookup(link, IFMapOrigin::XMPP);
EXPECT_TRUE(link_origin);
CheckLinkBits(link, cli_index, true, true);
CheckNodeBits(vr, cli_index, true, true);
CheckNodeBits(vm, cli_index, true, true);
// 3rd spurious subscribe
num_msgs = vnsw_client->Count();
vnsw_client->SendVmConfigSubscribe(host_vm_name);
usleep(1000);
TASK_UTIL_EXPECT_EQ(ifmap_channel_mgr_->get_dupicate_vmsub_messages(), 2);
EXPECT_EQ(vnsw_client->HasNMessages(num_msgs), true);
link = LinkLookup(vr, vm);
EXPECT_TRUE(link != NULL);
link_origin = LinkOriginLookup(link, IFMapOrigin::XMPP);
EXPECT_TRUE(link_origin);
CheckLinkBits(link, cli_index, true, true);
CheckNodeBits(vr, cli_index, true, true);
CheckNodeBits(vm, cli_index, true, true);
// Unsubscribe
num_msgs = vnsw_client->Count();
vnsw_client->SendVmConfigUnsubscribe(host_vm_name);
usleep(1000);
// Should get a delete for the link
TASK_UTIL_EXPECT_EQ(true, vnsw_client->HasNMessages(num_msgs + 3));
cout << "Rx msgs " << vnsw_client->Count() << endl;
cout << "Sent msgs " << GetSentMsgs(xmpp_server_, client_name) << endl;
link = LinkLookup(vr, vm);
EXPECT_TRUE(link == NULL);
CheckNodeBits(vr, cli_index, true, true);
CheckNodeBits(vm, cli_index, false, false);
TASK_UTIL_EXPECT_TRUE(NodeOriginLookup(vr, IFMapOrigin::MAP_SERVER));
TASK_UTIL_EXPECT_FALSE(NodeOriginLookup(vr, IFMapOrigin::XMPP));
TASK_UTIL_EXPECT_TRUE(NodeOriginLookup(vm, IFMapOrigin::MAP_SERVER));
TASK_UTIL_EXPECT_FALSE(NodeOriginLookup(vm, IFMapOrigin::XMPP));
vnsw_client->OutputRecvBufferToFile();
EXPECT_EQ(ifmap_server_.GetClientMapSize(), 1);
// Client close generates a TcpClose event on server
ConfigUpdate(vnsw_client, new XmppConfigData());
TASK_UTIL_EXPECT_EQ(ifmap_server_.GetClientMapSize(), 0);
// Verify ifmap_server client cleanup
EXPECT_EQ(true, IsIFMapClientUnregistered(&ifmap_server_, client_name));
// interest and advertised must be false since the client is gone
CheckClientBits(vnsw_client->name(), cli_index, false, false);
vnsw_client->UnRegisterWithXmpp();
vnsw_client->Shutdown();
task_util::WaitForIdle();
TcpServerManager::DeleteServer(vnsw_client);
vnsw_client = NULL;
//Delete xmpp-channel explicitly
XmppConnection *sconnection = xmpp_server_->FindConnection(client_name);
if (sconnection) {
sconnection->Shutdown();
}
TASK_UTIL_EXPECT_EQ(xmpp_server_->ConnectionCount(), 0);
EXPECT_TRUE(xmpp_server_->FindConnection(client_name) == NULL);
}
// 1 subscribe followed by 3 consecutive unsubscribe requests
TEST_F(XmppIfmapTest, VrVmUnsubThrice) {
string host_vm_name = "aad4c946-9390-4a53-8bbd-09d346f5ba6c";
// Read the ifmap data from file
string content(FileRead("controller/src/ifmap/testdata/two-vn-connection"));
assert(content.size() != 0);
parser_->Receive(&db_, content.data(), content.size(), 0);
task_util::WaitForIdle();
// Create the mock client
string client_name(kDefaultClientName);
string filename("/tmp/" + GetUserName() + "_vr_vm_unsub_thrice.output");
IFMapXmppClientMock *vnsw_client =
new IFMapXmppClientMock(&evm_, xmpp_server_->GetPort(), client_name,
filename);
TASK_UTIL_EXPECT_EQ(true, vnsw_client->IsEstablished());
vnsw_client->RegisterWithXmpp();
usleep(1000);
// server connection
TASK_UTIL_EXPECT_TRUE(ServerIsEstablished(xmpp_server_, client_name)
== true);
// Verify ifmap_server client is not created until config subscribe
TASK_UTIL_EXPECT_TRUE(ifmap_server_.FindClient(client_name) == NULL);
// No config messages sent until config subscribe
TASK_UTIL_EXPECT_EQ(0, vnsw_client->Count());
// Subscribe to config
vnsw_client->SendConfigSubscribe();
TASK_UTIL_EXPECT_TRUE(ifmap_server_.FindClient(client_name) != NULL);
TASK_UTIL_EXPECT_EQ(0, vnsw_client->Count());
// Verify ifmap_server client creation
IFMapClient *client = ifmap_server_.FindClient(kDefaultClientName);
EXPECT_TRUE(client != NULL);
// The link between VR-VM should not exist
IFMapNode *vr = TableLookup("virtual-router", kDefaultClientName);
EXPECT_TRUE(vr != NULL);
IFMapNode *vm = TableLookup("virtual-machine", host_vm_name);
EXPECT_TRUE(vm != NULL);
IFMapLink *link = LinkLookup(vr, vm);
EXPECT_TRUE(link == NULL);
// After sending subscribe, client should get an add for the vr-vm link.
// The link should not exist before the subscribe and should exist after.
size_t num_msgs = vnsw_client->Count();
vnsw_client->SendVmConfigSubscribe(host_vm_name);
usleep(1000);
TASK_UTIL_EXPECT_EQ(client->msgs_sent(), vnsw_client->Count());
TASK_UTIL_EXPECT_EQ(true, vnsw_client->HasNMessages(num_msgs + 2));
cout << "Rx msgs " << vnsw_client->Count() << endl;
cout << "Sent msgs " << GetSentMsgs(xmpp_server_, client_name) << endl;
link = LinkLookup(vr, vm);
EXPECT_TRUE(link != NULL);
bool link_origin = LinkOriginLookup(link, IFMapOrigin::XMPP);
EXPECT_TRUE(link_origin);
TASK_UTIL_EXPECT_TRUE(NodeOriginLookup(vr, IFMapOrigin::MAP_SERVER));
TASK_UTIL_EXPECT_TRUE(NodeOriginLookup(vr, IFMapOrigin::XMPP));
TASK_UTIL_EXPECT_TRUE(NodeOriginLookup(vm, IFMapOrigin::MAP_SERVER));
TASK_UTIL_EXPECT_TRUE(NodeOriginLookup(vm, IFMapOrigin::XMPP));
size_t cli_index = static_cast<size_t>(client->index());
CheckLinkBits(link, cli_index, true, true);
CheckNodeBits(vr, cli_index, true, true);
CheckNodeBits(vm, cli_index, true, true);
// Unsubscribe
num_msgs = vnsw_client->Count();
vnsw_client->SendVmConfigUnsubscribe(host_vm_name);
usleep(1000);
// Should get a delete for the link
TASK_UTIL_EXPECT_EQ(true, vnsw_client->HasNMessages(num_msgs + 3));
cout << "Rx msgs " << vnsw_client->Count() << endl;
cout << "Sent msgs " << GetSentMsgs(xmpp_server_, client_name) << endl;
link = LinkLookup(vr, vm);
EXPECT_TRUE(link == NULL);
CheckNodeBits(vr, cli_index, true, true);
CheckNodeBits(vm, cli_index, false, false);
TASK_UTIL_EXPECT_TRUE(NodeOriginLookup(vr, IFMapOrigin::MAP_SERVER));
TASK_UTIL_EXPECT_FALSE(NodeOriginLookup(vr, IFMapOrigin::XMPP));
TASK_UTIL_EXPECT_TRUE(NodeOriginLookup(vm, IFMapOrigin::MAP_SERVER));
TASK_UTIL_EXPECT_FALSE(NodeOriginLookup(vm, IFMapOrigin::XMPP));
EXPECT_EQ(ifmap_channel_mgr_->get_vmunsub_novmsub_messages(), 0);
// 2nd spurious unsubscribe
num_msgs = vnsw_client->Count();
vnsw_client->SendVmConfigUnsubscribe(host_vm_name);
TASK_UTIL_EXPECT_EQ(true, vnsw_client->HasNMessages(num_msgs));
link = LinkLookup(vr, vm);
EXPECT_TRUE(link == NULL);
CheckNodeBits(vr, cli_index, true, true);
CheckNodeBits(vm, cli_index, false, false);
TASK_UTIL_EXPECT_TRUE(NodeOriginLookup(vr, IFMapOrigin::MAP_SERVER));
TASK_UTIL_EXPECT_FALSE(NodeOriginLookup(vr, IFMapOrigin::XMPP));
TASK_UTIL_EXPECT_TRUE(NodeOriginLookup(vm, IFMapOrigin::MAP_SERVER));
TASK_UTIL_EXPECT_FALSE(NodeOriginLookup(vm, IFMapOrigin::XMPP));
TASK_UTIL_EXPECT_EQ(ifmap_channel_mgr_->get_vmunsub_novmsub_messages(), 1);
// 3rd spurious unsubscribe
num_msgs = vnsw_client->Count();
vnsw_client->SendVmConfigUnsubscribe(host_vm_name);
TASK_UTIL_EXPECT_EQ(true, vnsw_client->HasNMessages(num_msgs));
link = LinkLookup(vr, vm);
EXPECT_TRUE(link == NULL);
CheckNodeBits(vr, cli_index, true, true);
CheckNodeBits(vm, cli_index, false, false);
TASK_UTIL_EXPECT_TRUE(NodeOriginLookup(vr, IFMapOrigin::MAP_SERVER));
TASK_UTIL_EXPECT_FALSE(NodeOriginLookup(vr, IFMapOrigin::XMPP));
TASK_UTIL_EXPECT_TRUE(NodeOriginLookup(vm, IFMapOrigin::MAP_SERVER));
TASK_UTIL_EXPECT_FALSE(NodeOriginLookup(vm, IFMapOrigin::XMPP));
TASK_UTIL_EXPECT_EQ(ifmap_channel_mgr_->get_vmunsub_novmsub_messages(), 2);
vnsw_client->OutputRecvBufferToFile();
EXPECT_EQ(ifmap_server_.GetClientMapSize(), 1);
// Client close generates a TcpClose event on server
ConfigUpdate(vnsw_client, new XmppConfigData());
TASK_UTIL_EXPECT_EQ(ifmap_server_.GetClientMapSize(), 0);
// Verify ifmap_server client cleanup
EXPECT_EQ(true, IsIFMapClientUnregistered(&ifmap_server_, client_name));
// Interest and advertised must be false since the client is gone
CheckClientBits(vnsw_client->name(), cli_index, false, false);
vnsw_client->UnRegisterWithXmpp();
vnsw_client->Shutdown();
task_util::WaitForIdle();
TcpServerManager::DeleteServer(vnsw_client);
vnsw_client = NULL;
// Delete xmpp-channel explicitly
XmppConnection *sconnection = xmpp_server_->FindConnection(client_name);
if (sconnection) {
sconnection->Shutdown();
}
TASK_UTIL_EXPECT_EQ(xmpp_server_->ConnectionCount(), 0);
EXPECT_TRUE(xmpp_server_->FindConnection(client_name) == NULL);
}
// subscribe followed by connection close - no unsubscribe
TEST_F(XmppIfmapTest, VrVmSubConnClose) {
string host_vm_name = "aad4c946-9390-4a53-8bbd-09d346f5ba6c";
string unknown_vm_name = "aad4c946-9390-4a53-8bbd-09d346f5baaa";
// Give the read file to the parser
string content(FileRead("controller/src/ifmap/testdata/two-vn-connection"));
assert(content.size() != 0);
parser_->Receive(&db_, content.data(), content.size(), 0);
task_util::WaitForIdle();
// Create the mock client
string client_name(kDefaultClientName);
string filename("/tmp/" + GetUserName() + "_vr_vm_sub_conn_close.output");
IFMapXmppClientMock *vnsw_client =
new IFMapXmppClientMock(&evm_, xmpp_server_->GetPort(), client_name,
filename);
TASK_UTIL_EXPECT_EQ(true, vnsw_client->IsEstablished());
vnsw_client->RegisterWithXmpp();
usleep(1000);
// Server connection
TASK_UTIL_EXPECT_TRUE(ServerIsEstablished(xmpp_server_, client_name)
== true);
// Verify ifmap_server client is not created until config subscribe
TASK_UTIL_EXPECT_TRUE(ifmap_server_.FindClient(client_name) == NULL);
// No config messages sent until config subscribe
TASK_UTIL_EXPECT_EQ(0, vnsw_client->Count());
// Subscribe to config
vnsw_client->SendConfigSubscribe();
TASK_UTIL_EXPECT_TRUE(ifmap_server_.FindClient(client_name) != NULL);
TASK_UTIL_EXPECT_EQ(0, vnsw_client->Count());
// Verify ifmap_server client creation
IFMapClient *client = ifmap_server_.FindClient(kDefaultClientName);
EXPECT_TRUE(client != NULL);
// The link between VR-VM should not exist
IFMapNode *vr = TableLookup("virtual-router", kDefaultClientName);
EXPECT_TRUE(vr != NULL);
IFMapNode *vm = TableLookup("virtual-machine", host_vm_name);
EXPECT_TRUE(vm != NULL);
IFMapLink *link = LinkLookup(vr, vm);
EXPECT_TRUE(link == NULL);
// After sending subscribe, client should get an add for the vr-vm link.
// The link should not exist before the subscribe and should exist after.
size_t num_msgs = vnsw_client->Count();
vnsw_client->SendVmConfigSubscribe(host_vm_name);
usleep(1000);
TASK_UTIL_EXPECT_EQ(client->msgs_sent(), vnsw_client->Count());
TASK_UTIL_EXPECT_EQ(true, vnsw_client->HasNMessages(num_msgs + 2));
cout << "Rx msgs " << vnsw_client->Count() << endl;
cout << "Sent msgs " << GetSentMsgs(xmpp_server_, client_name) << endl;
link = LinkLookup(vr, vm);
EXPECT_TRUE(link != NULL);
bool link_origin = LinkOriginLookup(link, IFMapOrigin::XMPP);
EXPECT_TRUE(link_origin);
TASK_UTIL_EXPECT_TRUE(NodeOriginLookup(vr, IFMapOrigin::MAP_SERVER));
TASK_UTIL_EXPECT_TRUE(NodeOriginLookup(vr, IFMapOrigin::XMPP));
TASK_UTIL_EXPECT_TRUE(NodeOriginLookup(vm, IFMapOrigin::MAP_SERVER));
TASK_UTIL_EXPECT_TRUE(NodeOriginLookup(vm, IFMapOrigin::XMPP));
size_t cli_index = static_cast<size_t>(client->index());
CheckLinkBits(link, cli_index, true, true);
CheckNodeBits(vr, cli_index, true, true);
CheckNodeBits(vm, cli_index, true, true);
vnsw_client->OutputRecvBufferToFile();
// unknown_vm_name does not exist in config.
vnsw_client->SendVmConfigSubscribe(unknown_vm_name);
usleep(1000);
TASK_UTIL_EXPECT_EQ(ifmap_server_.vm_uuid_mapper()->PendingVmRegCount(), 1);
EXPECT_EQ(ifmap_server_.GetClientMapSize(), 1);
// Client close generates a TcpClose event on server
ConfigUpdate(vnsw_client, new XmppConfigData());
TASK_UTIL_EXPECT_EQ(ifmap_server_.GetClientMapSize(), 0);
TASK_UTIL_EXPECT_EQ(ifmap_server_.vm_uuid_mapper()->PendingVmRegCount(), 0);
TASK_UTIL_EXPECT_TRUE(NodeOriginLookup(vr, IFMapOrigin::MAP_SERVER));
TASK_UTIL_EXPECT_FALSE(NodeOriginLookup(vr, IFMapOrigin::XMPP));
TASK_UTIL_EXPECT_TRUE(NodeOriginLookup(vm, IFMapOrigin::MAP_SERVER));
TASK_UTIL_EXPECT_FALSE(NodeOriginLookup(vm, IFMapOrigin::XMPP));
// Verify ifmap_server client cleanup
EXPECT_EQ(true, IsIFMapClientUnregistered(&ifmap_server_, client_name));
// Interest and advertised must be false since the client is gone
CheckClientBits(vnsw_client->name(), cli_index, false, false);
vnsw_client->UnRegisterWithXmpp();
vnsw_client->Shutdown();
task_util::WaitForIdle();
TcpServerManager::DeleteServer(vnsw_client);
vnsw_client = NULL;
// Delete xmpp-channel explicitly
XmppConnection *sconnection = xmpp_server_->FindConnection(client_name);
if (sconnection) {
sconnection->Shutdown();
}
TASK_UTIL_EXPECT_EQ(xmpp_server_->ConnectionCount(), 0);
EXPECT_TRUE(xmpp_server_->FindConnection(client_name) == NULL);
}
TEST_F(XmppIfmapTest, RegBeforeConfig) {
string host_vm_name = "aad4c946-9390-4a53-8bbd-09d346f5ba6c";
// Read the ifmap data from file
string content(FileRead("controller/src/ifmap/testdata/two-vn-connection"));
assert(content.size() != 0);
// Create the mock client
string client_name(kDefaultClientName);
string filename("/tmp/" + GetUserName() + "_reg_before_config.output");
IFMapXmppClientMock *vnsw_client =
new IFMapXmppClientMock(&evm_, xmpp_server_->GetPort(), client_name,
filename);
TASK_UTIL_EXPECT_EQ(true, vnsw_client->IsEstablished());
vnsw_client->RegisterWithXmpp();
usleep(1000);
// Server connection
TASK_UTIL_EXPECT_TRUE(ServerIsEstablished(xmpp_server_, client_name)
== true);
// Verify ifmap_server client is not created until config subscribe
TASK_UTIL_EXPECT_TRUE(ifmap_server_.FindClient(client_name) == NULL);
// No config messages sent until config subscribe
TASK_UTIL_EXPECT_EQ(0, vnsw_client->Count());
// Subscribe to config
vnsw_client->SendConfigSubscribe();
TASK_UTIL_EXPECT_TRUE(ifmap_server_.FindClient(client_name) != NULL);
// The nodes should not exist since the config has not been read yet
IFMapNode *vr = TableLookup("virtual-router", kDefaultClientName);
EXPECT_TRUE(vr == NULL);
IFMapNode *vm = TableLookup("virtual-machine", host_vm_name);
EXPECT_TRUE(vm == NULL);
// The parser has not been given the data yet and so nothing to download
vnsw_client->SendVmConfigSubscribe(host_vm_name);
usleep(1000);
EXPECT_EQ(vnsw_client->Count(), 0);
// The nodes should not exist since the config has not been read yet
EXPECT_TRUE(TableLookup("virtual-router", kDefaultClientName) == NULL);
EXPECT_TRUE(TableLookup("virtual-machine", host_vm_name) == NULL);
// Verify ifmap_server client creation
IFMapClient *client = ifmap_server_.FindClient(kDefaultClientName);
EXPECT_TRUE(client != NULL);
size_t cli_index = static_cast<size_t>(client->index());
// Give the read file to the parser
size_t num_msgs = vnsw_client->Count();
parser_->Receive(&db_, content.data(), content.size(), 0);
task_util::WaitForIdle();
TASK_UTIL_EXPECT_EQ(true, vnsw_client->HasNMessages(num_msgs + 2));
TASK_UTIL_EXPECT_TRUE(TableLookup("virtual-router", kDefaultClientName)
!= NULL);
vr = TableLookup("virtual-router", kDefaultClientName);
TASK_UTIL_EXPECT_TRUE(TableLookup("virtual-machine", host_vm_name) != NULL);
vm = TableLookup("virtual-machine", host_vm_name);
TASK_UTIL_EXPECT_TRUE(LinkLookup(vr, vm) != NULL);
IFMapLink *link = LinkLookup(vr, vm);
bool link_origin = LinkOriginLookup(link, IFMapOrigin::XMPP);
EXPECT_TRUE(link_origin);
TASK_UTIL_EXPECT_TRUE(NodeOriginLookup(vr, IFMapOrigin::MAP_SERVER));
TASK_UTIL_EXPECT_TRUE(NodeOriginLookup(vr, IFMapOrigin::XMPP));
TASK_UTIL_EXPECT_TRUE(NodeOriginLookup(vm, IFMapOrigin::MAP_SERVER));
TASK_UTIL_EXPECT_TRUE(NodeOriginLookup(vm, IFMapOrigin::XMPP));
cout << "Rx msgs " << vnsw_client->Count() << endl;
cout << "Sent msgs " << GetSentMsgs(xmpp_server_, client_name) << endl;
CheckLinkBits(link, cli_index, true, true);
CheckNodeBits(vr, cli_index, true, true);
CheckNodeBits(vm, cli_index, true, true);
num_msgs = vnsw_client->Count();
vnsw_client->SendVmConfigUnsubscribe(host_vm_name);
usleep(1000);
TASK_UTIL_EXPECT_EQ(true, vnsw_client->HasNMessages(num_msgs + 3));
cout << "Rx msgs " << vnsw_client->Count() << endl;
cout << "Sent msgs " << GetSentMsgs(xmpp_server_, client_name) << endl;
link = LinkLookup(vr, vm);
EXPECT_TRUE(link == NULL);
CheckNodeBits(vr, cli_index, true, true);
CheckNodeBits(vm, cli_index, false, false);
TASK_UTIL_EXPECT_TRUE(NodeOriginLookup(vr, IFMapOrigin::MAP_SERVER));
TASK_UTIL_EXPECT_FALSE(NodeOriginLookup(vr, IFMapOrigin::XMPP));
TASK_UTIL_EXPECT_TRUE(NodeOriginLookup(vm, IFMapOrigin::MAP_SERVER));
TASK_UTIL_EXPECT_FALSE(NodeOriginLookup(vm, IFMapOrigin::XMPP));
vnsw_client->OutputRecvBufferToFile();
EXPECT_EQ(ifmap_server_.GetClientMapSize(), 1);
// Client close generates a TcpClose event on server
ConfigUpdate(vnsw_client, new XmppConfigData());
TASK_UTIL_EXPECT_EQ(ifmap_server_.GetClientMapSize(), 0);
// Verify ifmap_server client cleanup
EXPECT_EQ(true, IsIFMapClientUnregistered(&ifmap_server_, client_name));
// Interest and advertised must be false since the client is gone
CheckClientBits(vnsw_client->name(), cli_index, false, false);
vnsw_client->UnRegisterWithXmpp();
vnsw_client->Shutdown();
task_util::WaitForIdle();
TcpServerManager::DeleteServer(vnsw_client);
vnsw_client = NULL;
// Delete xmpp-channel explicitly
XmppConnection *sconnection = xmpp_server_->FindConnection(client_name);
if (sconnection) {
sconnection->Shutdown();
}
TASK_UTIL_EXPECT_EQ(xmpp_server_->ConnectionCount(), 0);
EXPECT_TRUE(xmpp_server_->FindConnection(client_name) == NULL);
}
TEST_F(XmppIfmapTest, Cli1Vn1Vm3Add) {
SetObjectsPerMessage(1);
// Read the ifmap data from file and give it to the parser
string content =
FileRead("controller/src/ifmap/testdata/cli1_vn1_vm3_add.xml");
assert(content.size() != 0);
parser_->Receive(&db_, content.data(), content.size(), 0);
task_util::WaitForIdle();
// create the mock client
string client_name =
string("default-global-system-config:a1s27.contrail.juniper.net");
string filename("/tmp/" + GetUserName() + "_cli1_vn1_vm3_add.output");
IFMapXmppClientMock *vnsw_client =
new IFMapXmppClientMock(&evm_, xmpp_server_->GetPort(), client_name,
filename);
TASK_UTIL_EXPECT_EQ(true, vnsw_client->IsEstablished());
vnsw_client->RegisterWithXmpp();
usleep(1000);
// Server connection
TASK_UTIL_EXPECT_TRUE(ServerIsEstablished(xmpp_server_, client_name)
== true);
// verify ifmap_server client is not created until config subscribe
TASK_UTIL_EXPECT_TRUE(ifmap_server_.FindClient(client_name) == NULL);
// no config messages sent until config subscribe
TASK_UTIL_EXPECT_EQ(0, vnsw_client->Count());
// Subscribe to config and wait until we receive atleast one msg before we
// verify ifmap_server client creation
vnsw_client->SendConfigSubscribe();
TASK_UTIL_EXPECT_TRUE(ifmap_server_.FindClient(client_name) != NULL);
vnsw_client->SendVmConfigSubscribe("2d308482-c7b3-4e05-af14-e732b7b50117");
usleep(1000);
vnsw_client->SendVmConfigSubscribe("93e76278-1990-4905-a472-8e9188f41b2c");
usleep(1000);
vnsw_client->SendVmConfigSubscribe("43d086ab-52c4-4a1f-8c3d-63b321e36e8a");
usleep(1000);
TASK_UTIL_EXPECT_NE(0, vnsw_client->Count());
IFMapClient *client = ifmap_server_.FindClient(client_name);
EXPECT_TRUE(client != NULL);
// Allow sender to run and send all the config
TASK_UTIL_EXPECT_EQ(32, vnsw_client->Count());
TASK_UTIL_EXPECT_EQ(client->msgs_sent(), vnsw_client->Count());
size_t cli_index = static_cast<size_t>(client->index());
int walk_count = ClientGraphWalkVerify(client_name, cli_index, true, true);
EXPECT_EQ(InterestConfigTrackerSize(client->index()), walk_count);
EXPECT_EQ(InterestConfigTrackerSize(client->index()), 32);
EXPECT_EQ(ifmap_server_.GetClientMapSize(), 1);
// client close generates a TcpClose event on server
ConfigUpdate(vnsw_client, new XmppConfigData());
TASK_UTIL_EXPECT_EQ(ifmap_server_.GetClientMapSize(), 0);
// verify ifmap_server client cleanup
EXPECT_EQ(true, IsIFMapClientUnregistered(&ifmap_server_, client_name));
// interest and advertised must be false since the client is gone
CheckClientBits(vnsw_client->name(), cli_index, false, false);
// Compare the contents of the received buffer with master_file_path
bool bresult = vnsw_client->OutputFileCompare(
"controller/src/ifmap/testdata/cli1_vn1_vm3_add.master_output");
EXPECT_EQ(true, bresult);
vnsw_client->UnRegisterWithXmpp();
vnsw_client->Shutdown();
task_util::WaitForIdle();
TcpServerManager::DeleteServer(vnsw_client);
vnsw_client = NULL;
//Delete xmpp-channel explicitly
XmppConnection *sconnection = xmpp_server_->FindConnection(client_name);
if (sconnection) {
sconnection->Shutdown();
}
TASK_UTIL_EXPECT_EQ(xmpp_server_->ConnectionCount(), 0);
EXPECT_TRUE(xmpp_server_->FindConnection(client_name) == NULL);
}
TEST_F(XmppIfmapTest, Cli1Vn2Np1Add) {
SetObjectsPerMessage(1);
// Read the ifmap data from file and give it to the parser
string content =
FileRead("controller/src/ifmap/testdata/cli1_vn2_np1_add.xml");
assert(content.size() != 0);
parser_->Receive(&db_, content.data(), content.size(), 0);
task_util::WaitForIdle();
// create the mock client
string client_name =
string("default-global-system-config:a1s27.contrail.juniper.net");
string filename("/tmp/" + GetUserName() + "_cli1_vn2_np1_add.output");
IFMapXmppClientMock *vnsw_client =
new IFMapXmppClientMock(&evm_, xmpp_server_->GetPort(), client_name,
filename);
TASK_UTIL_EXPECT_EQ(true, vnsw_client->IsEstablished());
vnsw_client->RegisterWithXmpp();
usleep(1000);
// server connection
TASK_UTIL_EXPECT_TRUE(ServerIsEstablished(xmpp_server_, client_name)
== true);
// verify ifmap_server client is not created until config subscribe
TASK_UTIL_EXPECT_TRUE(ifmap_server_.FindClient(client_name) == NULL);
// no config messages sent until config subscribe
TASK_UTIL_EXPECT_EQ(0, vnsw_client->Count());
// Subscribe to config and wait until we receive atleast one msg before we
// verify ifmap_server client creation
vnsw_client->SendConfigSubscribe();
TASK_UTIL_EXPECT_TRUE(ifmap_server_.FindClient(client_name) != NULL);
vnsw_client->SendVmConfigSubscribe("ae85ef17-1bff-4303-b1a0-980e0e9b0705");
usleep(1000);
vnsw_client->SendVmConfigSubscribe("fd6e78d3-a4fb-400f-94a7-c367c232a56c");
usleep(1000);
TASK_UTIL_EXPECT_NE(0, vnsw_client->Count());
IFMapClient *client = ifmap_server_.FindClient(client_name);
EXPECT_TRUE(client != NULL);
// Allow sender to run and send all the config
TASK_UTIL_EXPECT_EQ(32, vnsw_client->Count());
TASK_UTIL_EXPECT_EQ(client->msgs_sent(), vnsw_client->Count());
size_t cli_index = static_cast<size_t>(client->index());
EXPECT_EQ(ifmap_server_.GetClientMapSize(), 1);
// client close generates a TcpClose event on server
ConfigUpdate(vnsw_client, new XmppConfigData());
TASK_UTIL_EXPECT_EQ(ifmap_server_.GetClientMapSize(), 0);
// verify ifmap_server client cleanup
EXPECT_EQ(true, IsIFMapClientUnregistered(&ifmap_server_, client_name));
// interest and advertised must be false since the client is gone
CheckClientBits(vnsw_client->name(), cli_index, false, false);
// Compare the contents of the received buffer with master_file_path
bool bresult = vnsw_client->OutputFileCompare(
"controller/src/ifmap/testdata/cli1_vn2_np1_add.master_output");
EXPECT_EQ(true, bresult);
vnsw_client->UnRegisterWithXmpp();
vnsw_client->Shutdown();
task_util::WaitForIdle();
TcpServerManager::DeleteServer(vnsw_client);
vnsw_client = NULL;
//Delete xmpp-channel explicitly
XmppConnection *sconnection = xmpp_server_->FindConnection(client_name);
if (sconnection) {
sconnection->Shutdown();
}
TASK_UTIL_EXPECT_EQ(xmpp_server_->ConnectionCount(), 0);
EXPECT_TRUE(xmpp_server_->FindConnection(client_name) == NULL);
}
TEST_F(XmppIfmapTest, Cli1Vn2Np2Add) {
SetObjectsPerMessage(1);
// Read the ifmap data from file and give it to the parser
string content =
FileRead("controller/src/ifmap/testdata/cli1_vn2_np2_add.xml");
assert(content.size() != 0);
parser_->Receive(&db_, content.data(), content.size(), 0);
task_util::WaitForIdle();
// create the mock client
string client_name =
string("default-global-system-config:a1s27.contrail.juniper.net");
string filename("/tmp/" + GetUserName() + "_cli1_vn2_np2_add.output");
IFMapXmppClientMock *vnsw_client =
new IFMapXmppClientMock(&evm_, xmpp_server_->GetPort(), client_name,
filename);
TASK_UTIL_EXPECT_EQ(true, vnsw_client->IsEstablished());
vnsw_client->RegisterWithXmpp();
usleep(1000);
// server connection
TASK_UTIL_EXPECT_TRUE(ServerIsEstablished(xmpp_server_, client_name)
== true);
// verify ifmap_server client is not created until config subscribe
TASK_UTIL_EXPECT_TRUE(ifmap_server_.FindClient(client_name) == NULL);
// no config messages sent until config subscribe
TASK_UTIL_EXPECT_EQ(0, vnsw_client->Count());
// Subscribe to config and wait until we receive atleast one msg before we
// verify ifmap_server client creation
vnsw_client->SendConfigSubscribe();
TASK_UTIL_EXPECT_TRUE(ifmap_server_.FindClient(client_name) != NULL);
vnsw_client->SendVmConfigSubscribe("695d391b-65e6-4091-bea5-78e5eae32e66");
usleep(1000);
vnsw_client->SendVmConfigSubscribe("5f25dd5e-5442-4edf-89d1-6a318c0d213b");
usleep(1000);
TASK_UTIL_EXPECT_NE(0, vnsw_client->Count());
IFMapClient *client = ifmap_server_.FindClient(client_name);
EXPECT_TRUE(client != NULL);
// Allow sender to run and send all the config
TASK_UTIL_EXPECT_EQ(32, vnsw_client->Count());
TASK_UTIL_EXPECT_EQ(client->msgs_sent(), vnsw_client->Count());
size_t cli_index = static_cast<size_t>(client->index());
EXPECT_EQ(ifmap_server_.GetClientMapSize(), 1);
// client close generates a TcpClose event on server
ConfigUpdate(vnsw_client, new XmppConfigData());
TASK_UTIL_EXPECT_EQ(ifmap_server_.GetClientMapSize(), 0);
// verify ifmap_server client cleanup
EXPECT_EQ(true, IsIFMapClientUnregistered(&ifmap_server_, client_name));
// interest and advertised must be false since the client is gone
CheckClientBits(vnsw_client->name(), cli_index, false, false);
// Compare the contents of the received buffer with master_file_path
bool bresult = vnsw_client->OutputFileCompare(
"controller/src/ifmap/testdata/cli1_vn2_np2_add.master_output");
EXPECT_EQ(true, bresult);
vnsw_client->UnRegisterWithXmpp();
vnsw_client->Shutdown();
task_util::WaitForIdle();
TcpServerManager::DeleteServer(vnsw_client);
vnsw_client = NULL;
//Delete xmpp-channel explicitly
XmppConnection *sconnection = xmpp_server_->FindConnection(client_name);
if (sconnection) {
sconnection->Shutdown();
}
TASK_UTIL_EXPECT_EQ(xmpp_server_->ConnectionCount(), 0);
EXPECT_TRUE(xmpp_server_->FindConnection(client_name) == NULL);
}
TEST_F(XmppIfmapTest, Cli2Vn2Np2Add) {
SetObjectsPerMessage(1);
// Read the ifmap data from file and give it to the parser
string content =
FileRead("controller/src/ifmap/testdata/cli2_vn2_np2_add.xml");
assert(content.size() != 0);
parser_->Receive(&db_, content.data(), content.size(), 0);
task_util::WaitForIdle();
// Establish client a1s27
string cli_name1 =
string("default-global-system-config:a1s27.contrail.juniper.net");
string filename1("/tmp/" + GetUserName() + "_cli2_vn2_np2_add_s27.output");
IFMapXmppClientMock *vnsw_cli1 =
new IFMapXmppClientMock(&evm_, xmpp_server_->GetPort(), cli_name1,
filename1);
TASK_UTIL_EXPECT_EQ(true, vnsw_cli1->IsEstablished());
// Establish client a1s28
string cli_name2 =
string("default-global-system-config:a1s28.contrail.juniper.net");
string filename2("/tmp/" + GetUserName() + "_cli2_vn2_np2_add_s28.output");
IFMapXmppClientMock *vnsw_cli2 =
new IFMapXmppClientMock(&evm_, xmpp_server_->GetPort(), cli_name2,
filename2);
TASK_UTIL_EXPECT_EQ(true, vnsw_cli2->IsEstablished());
vnsw_cli1->RegisterWithXmpp();
usleep(1000);
vnsw_cli2->RegisterWithXmpp();
usleep(1000);
// server connection
TASK_UTIL_EXPECT_TRUE(ServerIsEstablished(xmpp_server_, cli_name1)
== true);
TASK_UTIL_EXPECT_TRUE(ServerIsEstablished(xmpp_server_, cli_name2)
== true);
// verify ifmap_server client is not created until config subscribe
TASK_UTIL_EXPECT_TRUE(ifmap_server_.FindClient(cli_name1) == NULL);
TASK_UTIL_EXPECT_TRUE(ifmap_server_.FindClient(cli_name2) == NULL);
// no config messages sent until config subscribe
TASK_UTIL_EXPECT_EQ(0, vnsw_cli1->Count());
TASK_UTIL_EXPECT_EQ(0, vnsw_cli2->Count());
// Subscribe to config and wait until we receive atleast one msg before we
// verify ifmap_server client creation
vnsw_cli1->SendConfigSubscribe();
TASK_UTIL_EXPECT_TRUE(ifmap_server_.FindClient(cli_name1) != NULL);
vnsw_cli1->SendVmConfigSubscribe("29fe5698-d04b-47ca-acf0-199b21c0a6ee");
usleep(1000);
vnsw_cli2->SendConfigSubscribe();
TASK_UTIL_EXPECT_TRUE(ifmap_server_.FindClient(cli_name2) != NULL);
vnsw_cli2->SendVmConfigSubscribe("39ed8f81-cf9c-4789-a118-e71f53abdf85");
usleep(1000);
TASK_UTIL_EXPECT_NE(0, vnsw_cli1->Count());
TASK_UTIL_EXPECT_NE(0, vnsw_cli2->Count());
IFMapClient *cli1 = ifmap_server_.FindClient(cli_name1);
IFMapClient *cli2 = ifmap_server_.FindClient(cli_name2);
EXPECT_TRUE(cli1 != NULL);
EXPECT_TRUE(cli2 != NULL);
// Allow senders to run and send all the config.
TASK_UTIL_EXPECT_EQ(18, vnsw_cli1->Count());
TASK_UTIL_EXPECT_EQ(cli1->msgs_sent(), vnsw_cli1->Count());
TASK_UTIL_EXPECT_EQ(18, vnsw_cli2->Count());
TASK_UTIL_EXPECT_EQ(cli2->msgs_sent(), vnsw_cli2->Count());
size_t cli_index1 = static_cast<size_t>(cli1->index());
size_t cli_index2 = static_cast<size_t>(cli2->index());
EXPECT_EQ(ifmap_server_.GetClientMapSize(), 2);
// client close generates a TcpClose event on server
ConfigUpdate(vnsw_cli1, new XmppConfigData());
TASK_UTIL_EXPECT_EQ(ifmap_server_.GetClientMapSize(), 1);
ConfigUpdate(vnsw_cli2, new XmppConfigData());
TASK_UTIL_EXPECT_EQ(ifmap_server_.GetClientMapSize(), 0);
// verify ifmap_server client cleanup
EXPECT_EQ(true, IsIFMapClientUnregistered(&ifmap_server_, cli_name1));
EXPECT_EQ(true, IsIFMapClientUnregistered(&ifmap_server_, cli_name2));
// interest and advertised must be false since the client is gone
CheckClientBits(vnsw_cli1->name(), cli_index1, false, false);
CheckClientBits(vnsw_cli2->name(), cli_index2, false, false);
// Compare the contents of the received buffer with master_file_path
bool bresult = vnsw_cli1->OutputFileCompare(
"controller/src/ifmap/testdata/cli2_vn2_np2_add_a1s27.master_output");
EXPECT_EQ(true, bresult);
bresult = vnsw_cli2->OutputFileCompare(
"controller/src/ifmap/testdata/cli2_vn2_np2_add_a1s28.master_output");
EXPECT_EQ(true, bresult);
vnsw_cli1->UnRegisterWithXmpp();
vnsw_cli1->Shutdown();
task_util::WaitForIdle();
TcpServerManager::DeleteServer(vnsw_cli1);
vnsw_cli1 = NULL;
vnsw_cli2->UnRegisterWithXmpp();
vnsw_cli2->Shutdown();
task_util::WaitForIdle();
TcpServerManager::DeleteServer(vnsw_cli2);
vnsw_cli2 = NULL;
//Delete xmpp-channel explicitly
XmppConnection *sconnection = xmpp_server_->FindConnection(cli_name1);
if (sconnection) {
sconnection->Shutdown();
}
sconnection = xmpp_server_->FindConnection(cli_name2);
if (sconnection) {
sconnection->Shutdown();
}
TASK_UTIL_EXPECT_EQ(xmpp_server_->ConnectionCount(), 0);
EXPECT_TRUE(xmpp_server_->FindConnection(cli_name1) == NULL);
EXPECT_TRUE(xmpp_server_->FindConnection(cli_name2) == NULL);
}
TEST_F(XmppIfmapTest, Cli2Vn2Vm2Add) {
SetObjectsPerMessage(1);
// Read the ifmap data from file and give it to the parser
string content=
FileRead("controller/src/ifmap/testdata/cli2_vn2_vm2_add.xml");
assert(content.size() != 0);
parser_->Receive(&db_, content.data(), content.size(), 0);
task_util::WaitForIdle();
// Establish client a1s27
string cli_name1 =
string("default-global-system-config:a1s27.contrail.juniper.net");
string filename1("/tmp/" + GetUserName() + "_cli2_vn2_vm2_add_s27.output");
IFMapXmppClientMock *vnsw_cli1 =
new IFMapXmppClientMock(&evm_, xmpp_server_->GetPort(), cli_name1,
filename1);
TASK_UTIL_EXPECT_EQ(true, vnsw_cli1->IsEstablished());
// Establish client a1s28
string cli_name2 =
string("default-global-system-config:a1s28.contrail.juniper.net");
string filename2("/tmp/" + GetUserName() + "_cli2_vn2_vm2_add_s28.output");
IFMapXmppClientMock *vnsw_cli2 =
new IFMapXmppClientMock(&evm_, xmpp_server_->GetPort(), cli_name2,
filename2);
TASK_UTIL_EXPECT_EQ(true, vnsw_cli2->IsEstablished());
vnsw_cli1->RegisterWithXmpp();
usleep(1000);
vnsw_cli2->RegisterWithXmpp();
usleep(1000);
// server connection
TASK_UTIL_EXPECT_TRUE(ServerIsEstablished(xmpp_server_, cli_name1)
== true);
TASK_UTIL_EXPECT_TRUE(ServerIsEstablished(xmpp_server_, cli_name2)
== true);
// verify ifmap_server client is not created until config subscribe
TASK_UTIL_EXPECT_TRUE(ifmap_server_.FindClient(cli_name1) == NULL);
TASK_UTIL_EXPECT_TRUE(ifmap_server_.FindClient(cli_name2) == NULL);
// no config messages sent until config subscribe
TASK_UTIL_EXPECT_EQ(0, vnsw_cli1->Count());
TASK_UTIL_EXPECT_EQ(0, vnsw_cli2->Count());
// Subscribe to config and wait until we receive atleast one msg before we
// verify ifmap_server client creation
vnsw_cli1->SendConfigSubscribe();
TASK_UTIL_EXPECT_TRUE(ifmap_server_.FindClient(cli_name1) != NULL);
vnsw_cli1->SendVmConfigSubscribe("0af0866c-08c9-49ae-856b-0f4a58179920");
usleep(1000);
vnsw_cli2->SendConfigSubscribe();
TASK_UTIL_EXPECT_TRUE(ifmap_server_.FindClient(cli_name2) != NULL);
vnsw_cli2->SendVmConfigSubscribe("0d9dd007-b25a-4d86-bf68-dc0e85e317e3");
usleep(1000);
TASK_UTIL_EXPECT_NE(0, vnsw_cli1->Count());
TASK_UTIL_EXPECT_NE(0, vnsw_cli2->Count());
IFMapClient *cli1 = ifmap_server_.FindClient(cli_name1);
IFMapClient *cli2 = ifmap_server_.FindClient(cli_name2);
EXPECT_TRUE(cli1 != NULL);
EXPECT_TRUE(cli2 != NULL);
// Allow senders to run and send all the config
TASK_UTIL_EXPECT_EQ(18, vnsw_cli1->Count());
TASK_UTIL_EXPECT_EQ(cli1->msgs_sent(), vnsw_cli1->Count());
TASK_UTIL_EXPECT_EQ(18, vnsw_cli2->Count());
TASK_UTIL_EXPECT_EQ(cli2->msgs_sent(), vnsw_cli2->Count());
size_t cli_index1 = static_cast<size_t>(cli1->index());
size_t cli_index2 = static_cast<size_t>(cli2->index());
EXPECT_EQ(ifmap_server_.GetClientMapSize(), 2);
// client close generates a TcpClose event on server
ConfigUpdate(vnsw_cli1, new XmppConfigData());
TASK_UTIL_EXPECT_EQ(ifmap_server_.GetClientMapSize(), 1);
ConfigUpdate(vnsw_cli2, new XmppConfigData());
TASK_UTIL_EXPECT_EQ(ifmap_server_.GetClientMapSize(), 0);
// verify ifmap_server client cleanup
EXPECT_EQ(true, IsIFMapClientUnregistered(&ifmap_server_, cli_name1));
EXPECT_EQ(true, IsIFMapClientUnregistered(&ifmap_server_, cli_name2));
// interest and advertised must be false since the client is gone
CheckClientBits(vnsw_cli1->name(), cli_index1, false, false);
CheckClientBits(vnsw_cli2->name(), cli_index2, false, false);
// Compare the contents of the received buffer with master_file_path
bool bresult = vnsw_cli1->OutputFileCompare(
"controller/src/ifmap/testdata/cli2_vn2_vm2_add_a1s27.master_output");
EXPECT_EQ(true, bresult);
bresult = vnsw_cli2->OutputFileCompare(
"controller/src/ifmap/testdata/cli2_vn2_vm2_add_a1s28.master_output");
EXPECT_EQ(true, bresult);
vnsw_cli1->UnRegisterWithXmpp();
vnsw_cli1->Shutdown();
task_util::WaitForIdle();
TcpServerManager::DeleteServer(vnsw_cli1);
vnsw_cli1 = NULL;
vnsw_cli2->UnRegisterWithXmpp();
vnsw_cli2->Shutdown();
task_util::WaitForIdle();
TcpServerManager::DeleteServer(vnsw_cli2);
vnsw_cli2 = NULL;
//Delete xmpp-channel explicitly
XmppConnection *sconnection = xmpp_server_->FindConnection(cli_name1);
if (sconnection) {
sconnection->Shutdown();
}
sconnection = xmpp_server_->FindConnection(cli_name2);
if (sconnection) {
sconnection->Shutdown();
}
TASK_UTIL_EXPECT_EQ(xmpp_server_->ConnectionCount(), 0);
EXPECT_TRUE(xmpp_server_->FindConnection(cli_name1) == NULL);
EXPECT_TRUE(xmpp_server_->FindConnection(cli_name2) == NULL);
}
TEST_F(XmppIfmapTest, Cli2Vn3Vm6Np2Add) {
SetObjectsPerMessage(1);
// Read the ifmap data from file and give it to the parser
string content =
FileRead("controller/src/ifmap/testdata/cli2_vn3_vm6_np2_add.xml");
assert(content.size() != 0);
parser_->Receive(&db_, content.data(), content.size(), 0);
task_util::WaitForIdle();
// Establish client a1s27
string cli_name1 =
string("default-global-system-config:a1s27.contrail.juniper.net");
string filename1("/tmp/" + GetUserName() +
"_cli2_vn3_vm6_np2_add_s27.output");
IFMapXmppClientMock *vnsw_cli1 =
new IFMapXmppClientMock(&evm_, xmpp_server_->GetPort(), cli_name1,
filename1);
TASK_UTIL_EXPECT_EQ(true, vnsw_cli1->IsEstablished());
// Establish client a1s28
string cli_name2 =
string("default-global-system-config:a1s28.contrail.juniper.net");
string filename2("/tmp/" + GetUserName() +
"_cli2_vn3_vm6_np2_add_s28.output");
IFMapXmppClientMock *vnsw_cli2 =
new IFMapXmppClientMock(&evm_, xmpp_server_->GetPort(), cli_name2,
filename2);
TASK_UTIL_EXPECT_EQ(true, vnsw_cli2->IsEstablished());
vnsw_cli1->RegisterWithXmpp();
usleep(1000);
vnsw_cli2->RegisterWithXmpp();
usleep(1000);
// server connection
TASK_UTIL_EXPECT_TRUE(ServerIsEstablished(xmpp_server_, cli_name1)
== true);
TASK_UTIL_EXPECT_TRUE(ServerIsEstablished(xmpp_server_, cli_name2)
== true);
// verify ifmap_server client is not created until config subscribe
TASK_UTIL_EXPECT_TRUE(ifmap_server_.FindClient(cli_name1) == NULL);
TASK_UTIL_EXPECT_TRUE(ifmap_server_.FindClient(cli_name2) == NULL);
// no config messages sent until config subscribe
TASK_UTIL_EXPECT_EQ(0, vnsw_cli1->Count());
TASK_UTIL_EXPECT_EQ(0, vnsw_cli2->Count());
// Subscribe to config and wait until we receive atleast one msg before we
// verify ifmap_server client creation
vnsw_cli1->SendConfigSubscribe();
TASK_UTIL_EXPECT_TRUE(ifmap_server_.FindClient(cli_name1) != NULL);
vnsw_cli1->SendVmConfigSubscribe("7285b8b4-63e7-4251-8690-bbef70c2ccc1");
usleep(1000);
vnsw_cli1->SendVmConfigSubscribe("98e60d70-460a-4618-b334-1dbd6333e599");
usleep(1000);
vnsw_cli1->SendVmConfigSubscribe("7e87e01a-6847-4e24-b668-4a1ad24cef1c");
usleep(1000);
vnsw_cli1->SendVmConfigSubscribe("34a09a89-823a-4934-bf3d-f2cd9513e121");
usleep(1000);
vnsw_cli2->SendConfigSubscribe();
TASK_UTIL_EXPECT_TRUE(ifmap_server_.FindClient(cli_name2) != NULL);
vnsw_cli2->SendVmConfigSubscribe("2af8952f-ee66-444b-be63-67e8c6efaf74");
usleep(1000);
vnsw_cli2->SendVmConfigSubscribe("9afa046f-743c-42e0-ab63-2786a81d5731");
usleep(1000);
TASK_UTIL_EXPECT_NE(0, vnsw_cli1->Count());
TASK_UTIL_EXPECT_NE(0, vnsw_cli2->Count());
IFMapClient *cli1 = ifmap_server_.FindClient(cli_name1);
IFMapClient *cli2 = ifmap_server_.FindClient(cli_name2);
EXPECT_TRUE(cli1 != NULL);
EXPECT_TRUE(cli2 != NULL);
// Allow senders to run and send all the config. GSC and NwIpam dups to cli1
TASK_UTIL_EXPECT_EQ(48, vnsw_cli1->Count());
TASK_UTIL_EXPECT_EQ(cli1->msgs_sent(), vnsw_cli1->Count());
TASK_UTIL_EXPECT_EQ(26, vnsw_cli2->Count());
TASK_UTIL_EXPECT_EQ(cli2->msgs_sent(), vnsw_cli2->Count());
size_t cli_index1 = static_cast<size_t>(cli1->index());
size_t cli_index2 = static_cast<size_t>(cli2->index());
EXPECT_EQ(ifmap_server_.GetClientMapSize(), 2);
// client close generates a TcpClose event on server
ConfigUpdate(vnsw_cli1, new XmppConfigData());
TASK_UTIL_EXPECT_EQ(ifmap_server_.GetClientMapSize(), 1);
ConfigUpdate(vnsw_cli2, new XmppConfigData());
TASK_UTIL_EXPECT_EQ(ifmap_server_.GetClientMapSize(), 0);
// verify ifmap_server client cleanup
EXPECT_EQ(true, IsIFMapClientUnregistered(&ifmap_server_, cli_name1));
EXPECT_EQ(true, IsIFMapClientUnregistered(&ifmap_server_, cli_name2));
// interest and advertised must be false since the client is gone
CheckClientBits(vnsw_cli1->name(), cli_index1, false, false);
CheckClientBits(vnsw_cli2->name(), cli_index2, false, false);
// Compare the contents of the received buffer with master_file_path
bool bresult = vnsw_cli1->OutputFileCompare(
"controller/src/ifmap/testdata/cli2_vn3_vm6_np2_add_a1s27.master_output");
EXPECT_EQ(true, bresult);
bresult = vnsw_cli2->OutputFileCompare(
"controller/src/ifmap/testdata/cli2_vn3_vm6_np2_add_a1s28.master_output");
EXPECT_EQ(true, bresult);
vnsw_cli1->UnRegisterWithXmpp();
vnsw_cli1->Shutdown();
task_util::WaitForIdle();
TcpServerManager::DeleteServer(vnsw_cli1);
vnsw_cli1 = NULL;
vnsw_cli2->UnRegisterWithXmpp();
vnsw_cli2->Shutdown();
task_util::WaitForIdle();
TcpServerManager::DeleteServer(vnsw_cli2);
vnsw_cli2 = NULL;
//Delete xmpp-channel explicitly
XmppConnection *sconnection = xmpp_server_->FindConnection(cli_name1);
if (sconnection) {
sconnection->Shutdown();
}
sconnection = xmpp_server_->FindConnection(cli_name2);
if (sconnection) {
sconnection->Shutdown();
}
TASK_UTIL_EXPECT_EQ(xmpp_server_->ConnectionCount(), 0);
EXPECT_TRUE(xmpp_server_->FindConnection(cli_name1) == NULL);
EXPECT_TRUE(xmpp_server_->FindConnection(cli_name2) == NULL);
}
// Read config, then vm-sub followed by vm-unsub followed by close
TEST_F(XmppIfmapTest, CfgSubUnsub) {
SetObjectsPerMessage(1);
// Read the ifmap data from file and give it to the parser
string content =
FileRead("controller/src/ifmap/testdata/vr_3vm_add.xml");
assert(content.size() != 0);
parser_->Receive(&db_, content.data(), content.size(), 0);
task_util::WaitForIdle();
// create the mock client
string client_name =
string("default-global-system-config:a1s27.contrail.juniper.net");
string filename("/tmp/" + GetUserName() + "_cfg_reg_unreg.output");
IFMapXmppClientMock *vnsw_client =
new IFMapXmppClientMock(&evm_, xmpp_server_->GetPort(), client_name,
filename);
TASK_UTIL_EXPECT_EQ(true, vnsw_client->IsEstablished());
vnsw_client->RegisterWithXmpp();
usleep(1000);
// Server connection
TASK_UTIL_EXPECT_TRUE(ServerIsEstablished(xmpp_server_, client_name)
== true);
// verify ifmap_server client is not created until config subscribe
EXPECT_TRUE(ifmap_server_.FindClient(client_name) == NULL);
// no config messages sent until config subscribe
EXPECT_EQ(0, vnsw_client->Count());
vnsw_client->SendConfigSubscribe();
TASK_UTIL_EXPECT_TRUE(ifmap_server_.FindClient(client_name) != NULL);
// Allow sender to run and send all the config
IFMapClient *client = ifmap_server_.FindClient(client_name);
EXPECT_TRUE(client != NULL);
TASK_UTIL_EXPECT_EQ(client->msgs_sent(), vnsw_client->Count());
TASK_UTIL_EXPECT_TRUE(TableLookup("virtual-router", client_name) != NULL);
IFMapNode *vr = TableLookup("virtual-router", client_name);
TASK_UTIL_EXPECT_TRUE(TableLookup("virtual-machine",
"2d308482-c7b3-4e05-af14-e732b7b50117") != NULL);
IFMapNode *vm1 = TableLookup("virtual-machine",
"2d308482-c7b3-4e05-af14-e732b7b50117");
TASK_UTIL_EXPECT_TRUE(TableLookup("virtual-machine",
"93e76278-1990-4905-a472-8e9188f41b2c") != NULL);
IFMapNode *vm2 = TableLookup("virtual-machine",
"93e76278-1990-4905-a472-8e9188f41b2c");
TASK_UTIL_EXPECT_TRUE(TableLookup("virtual-machine",
"43d086ab-52c4-4a1f-8c3d-63b321e36e8a") != NULL);
IFMapNode *vm3 = TableLookup("virtual-machine",
"43d086ab-52c4-4a1f-8c3d-63b321e36e8a");
EXPECT_TRUE(NodeOriginLookup(vr, IFMapOrigin::MAP_SERVER));
EXPECT_FALSE(NodeOriginLookup(vr, IFMapOrigin::XMPP));
EXPECT_TRUE(NodeOriginLookup(vm1, IFMapOrigin::MAP_SERVER));
EXPECT_FALSE(NodeOriginLookup(vm1, IFMapOrigin::XMPP));
EXPECT_TRUE(NodeOriginLookup(vm2, IFMapOrigin::MAP_SERVER));
EXPECT_FALSE(NodeOriginLookup(vm2, IFMapOrigin::XMPP));
EXPECT_TRUE(NodeOriginLookup(vm3, IFMapOrigin::MAP_SERVER));
EXPECT_FALSE(NodeOriginLookup(vm3, IFMapOrigin::XMPP));
vnsw_client->SendVmConfigSubscribe("2d308482-c7b3-4e05-af14-e732b7b50117");
usleep(1000);
vnsw_client->SendVmConfigSubscribe("93e76278-1990-4905-a472-8e9188f41b2c");
usleep(1000);
vnsw_client->SendVmConfigSubscribe("43d086ab-52c4-4a1f-8c3d-63b321e36e8a");
usleep(1000);
TASK_UTIL_EXPECT_NE(0, vnsw_client->Count());
EXPECT_TRUE(NodeOriginLookup(vr, IFMapOrigin::MAP_SERVER));
TASK_UTIL_EXPECT_TRUE(NodeOriginLookup(vr, IFMapOrigin::XMPP));
EXPECT_TRUE(NodeOriginLookup(vm1, IFMapOrigin::MAP_SERVER));
TASK_UTIL_EXPECT_TRUE(NodeOriginLookup(vm1, IFMapOrigin::XMPP));
EXPECT_TRUE(NodeOriginLookup(vm2, IFMapOrigin::MAP_SERVER));
TASK_UTIL_EXPECT_TRUE(NodeOriginLookup(vm2, IFMapOrigin::XMPP));
EXPECT_TRUE(NodeOriginLookup(vm3, IFMapOrigin::MAP_SERVER));
TASK_UTIL_EXPECT_TRUE(NodeOriginLookup(vm3, IFMapOrigin::XMPP));
TASK_UTIL_EXPECT_TRUE(LinkLookup(vr, vm1) != NULL);
IFMapLink *link = LinkLookup(vr, vm1);
EXPECT_FALSE(LinkOriginLookup(link, IFMapOrigin::MAP_SERVER));
EXPECT_TRUE(LinkOriginLookup(link, IFMapOrigin::XMPP));
TASK_UTIL_EXPECT_TRUE(LinkLookup(vr, vm2) != NULL);
link = LinkLookup(vr, vm2);
EXPECT_FALSE(LinkOriginLookup(link, IFMapOrigin::MAP_SERVER));
EXPECT_TRUE(LinkOriginLookup(link, IFMapOrigin::XMPP));
TASK_UTIL_EXPECT_TRUE(LinkLookup(vr, vm3) != NULL);
link = LinkLookup(vr, vm3);
EXPECT_FALSE(LinkOriginLookup(link, IFMapOrigin::MAP_SERVER));
EXPECT_TRUE(LinkOriginLookup(link, IFMapOrigin::XMPP));
// Send unreg only for vm1 and vm2
vnsw_client->SendVmConfigUnsubscribe(
"2d308482-c7b3-4e05-af14-e732b7b50117");
usleep(1000);
vnsw_client->SendVmConfigUnsubscribe(
"93e76278-1990-4905-a472-8e9188f41b2c");
usleep(1000);
EXPECT_TRUE(TableLookup("virtual-router", client_name) != NULL);
EXPECT_TRUE(TableLookup("virtual-machine",
"2d308482-c7b3-4e05-af14-e732b7b50117") != NULL);
EXPECT_TRUE(TableLookup("virtual-machine",
"93e76278-1990-4905-a472-8e9188f41b2c") != NULL);
EXPECT_TRUE(TableLookup("virtual-machine",
"43d086ab-52c4-4a1f-8c3d-63b321e36e8a") != NULL);
// vm3 unreg is still pending. vr and vm3 should have xmpp origin.
EXPECT_TRUE(NodeOriginLookup(vr, IFMapOrigin::MAP_SERVER));
EXPECT_TRUE(NodeOriginLookup(vr, IFMapOrigin::XMPP));
EXPECT_TRUE(NodeOriginLookup(vm1, IFMapOrigin::MAP_SERVER));
TASK_UTIL_EXPECT_FALSE(NodeOriginLookup(vm1, IFMapOrigin::XMPP));
EXPECT_TRUE(NodeOriginLookup(vm2, IFMapOrigin::MAP_SERVER));
TASK_UTIL_EXPECT_FALSE(NodeOriginLookup(vm2, IFMapOrigin::XMPP));
EXPECT_TRUE(NodeOriginLookup(vm3, IFMapOrigin::MAP_SERVER));
EXPECT_TRUE(NodeOriginLookup(vm3, IFMapOrigin::XMPP));
vnsw_client->SendVmConfigUnsubscribe(
"43d086ab-52c4-4a1f-8c3d-63b321e36e8a");
usleep(1000);
EXPECT_TRUE(NodeOriginLookup(vr, IFMapOrigin::MAP_SERVER));
TASK_UTIL_EXPECT_FALSE(NodeOriginLookup(vr, IFMapOrigin::XMPP));
EXPECT_TRUE(NodeOriginLookup(vm3, IFMapOrigin::MAP_SERVER));
TASK_UTIL_EXPECT_FALSE(NodeOriginLookup(vm3, IFMapOrigin::XMPP));
size_t cli_index = static_cast<size_t>(client->index());
EXPECT_EQ(ifmap_server_.GetClientMapSize(), 1);
// Client close generates a TcpClose event on server
ConfigUpdate(vnsw_client, new XmppConfigData());
TASK_UTIL_EXPECT_EQ(ifmap_server_.GetClientMapSize(), 0);
// Verify ifmap_server client cleanup
EXPECT_EQ(true, IsIFMapClientUnregistered(&ifmap_server_, client_name));
// interest and advertised must be false since the client is gone
CheckClientBits(vnsw_client->name(), cli_index, false, false);
vnsw_client->UnRegisterWithXmpp();
vnsw_client->Shutdown();
task_util::WaitForIdle();
TcpServerManager::DeleteServer(vnsw_client);
vnsw_client = NULL;
// Delete xmpp-channel explicitly
XmppConnection *sconnection = xmpp_server_->FindConnection(client_name);
if (sconnection) {
sconnection->Shutdown();
}
TASK_UTIL_EXPECT_EQ(xmpp_server_->ConnectionCount(), 0);
EXPECT_TRUE(xmpp_server_->FindConnection(client_name) == NULL);
}
// Config-add followed by vm-reg followed by config-delete followed by vm-unreg
// followed by close
TEST_F(XmppIfmapTest, CfgAdd_Reg_CfgDel_Unreg) {
SetObjectsPerMessage(1);
// Read the ifmap data from file and give it to the parser
string content(FileRead("controller/src/ifmap/testdata/vr_3vm_add.xml"));
assert(content.size() != 0);
parser_->Receive(&db_, content.data(), content.size(), 0);
task_util::WaitForIdle();
// create the mock client
string client_name =
string("default-global-system-config:a1s27.contrail.juniper.net");
string filename("/tmp/" + GetUserName() +
"_cfgadd_reg_cfgdel_unreg.output");
IFMapXmppClientMock *vnsw_client =
new IFMapXmppClientMock(&evm_, xmpp_server_->GetPort(), client_name,
filename);
TASK_UTIL_EXPECT_EQ(true, vnsw_client->IsEstablished());
vnsw_client->RegisterWithXmpp();
usleep(1000);
// Server connection
TASK_UTIL_EXPECT_TRUE(ServerIsEstablished(xmpp_server_, client_name)
== true);
// verify ifmap_server client is not created until config subscribe
EXPECT_TRUE(ifmap_server_.FindClient(client_name) == NULL);
// no config messages sent until config subscribe
EXPECT_EQ(0, vnsw_client->Count());
vnsw_client->SendConfigSubscribe();
TASK_UTIL_EXPECT_TRUE(ifmap_server_.FindClient(client_name) != NULL);
// Allow sender to run and send all the config
IFMapClient *client = ifmap_server_.FindClient(client_name);
EXPECT_TRUE(client != NULL);
TASK_UTIL_EXPECT_EQ(client->msgs_sent(), vnsw_client->Count());
TASK_UTIL_EXPECT_TRUE(TableLookup("virtual-router", client_name) != NULL);
IFMapNode *vr = TableLookup("virtual-router", client_name);
TASK_UTIL_EXPECT_TRUE(TableLookup("virtual-machine",
"2d308482-c7b3-4e05-af14-e732b7b50117") != NULL);
IFMapNode *vm1 = TableLookup("virtual-machine",
"2d308482-c7b3-4e05-af14-e732b7b50117");
TASK_UTIL_EXPECT_TRUE(TableLookup("virtual-machine",
"93e76278-1990-4905-a472-8e9188f41b2c") != NULL);
IFMapNode *vm2 = TableLookup("virtual-machine",
"93e76278-1990-4905-a472-8e9188f41b2c");
TASK_UTIL_EXPECT_TRUE(TableLookup("virtual-machine",
"43d086ab-52c4-4a1f-8c3d-63b321e36e8a") != NULL);
IFMapNode *vm3 = TableLookup("virtual-machine",
"43d086ab-52c4-4a1f-8c3d-63b321e36e8a");
EXPECT_TRUE(NodeOriginLookup(vr, IFMapOrigin::MAP_SERVER));
EXPECT_FALSE(NodeOriginLookup(vr, IFMapOrigin::XMPP));
EXPECT_TRUE(NodeOriginLookup(vm1, IFMapOrigin::MAP_SERVER));
EXPECT_FALSE(NodeOriginLookup(vm1, IFMapOrigin::XMPP));
EXPECT_TRUE(NodeOriginLookup(vm2, IFMapOrigin::MAP_SERVER));
EXPECT_FALSE(NodeOriginLookup(vm2, IFMapOrigin::XMPP));
EXPECT_TRUE(NodeOriginLookup(vm3, IFMapOrigin::MAP_SERVER));
EXPECT_FALSE(NodeOriginLookup(vm3, IFMapOrigin::XMPP));
vnsw_client->SendVmConfigSubscribe("2d308482-c7b3-4e05-af14-e732b7b50117");
usleep(1000);
vnsw_client->SendVmConfigSubscribe("93e76278-1990-4905-a472-8e9188f41b2c");
usleep(1000);
vnsw_client->SendVmConfigSubscribe("43d086ab-52c4-4a1f-8c3d-63b321e36e8a");
usleep(1000);
TASK_UTIL_EXPECT_NE(0, vnsw_client->Count());
EXPECT_TRUE(NodeOriginLookup(vr, IFMapOrigin::MAP_SERVER));
TASK_UTIL_EXPECT_TRUE(NodeOriginLookup(vr, IFMapOrigin::XMPP));
EXPECT_TRUE(NodeOriginLookup(vm1, IFMapOrigin::MAP_SERVER));
TASK_UTIL_EXPECT_TRUE(NodeOriginLookup(vm1, IFMapOrigin::XMPP));
EXPECT_TRUE(NodeOriginLookup(vm2, IFMapOrigin::MAP_SERVER));
TASK_UTIL_EXPECT_TRUE(NodeOriginLookup(vm2, IFMapOrigin::XMPP));
EXPECT_TRUE(NodeOriginLookup(vm3, IFMapOrigin::MAP_SERVER));
TASK_UTIL_EXPECT_TRUE(NodeOriginLookup(vm3, IFMapOrigin::XMPP));
TASK_UTIL_EXPECT_TRUE(LinkLookup(vr, vm1) != NULL);
IFMapLink *link = LinkLookup(vr, vm1);
EXPECT_FALSE(LinkOriginLookup(link, IFMapOrigin::MAP_SERVER));
EXPECT_TRUE(LinkOriginLookup(link, IFMapOrigin::XMPP));
TASK_UTIL_EXPECT_TRUE(LinkLookup(vr, vm2) != NULL);
link = LinkLookup(vr, vm2);
EXPECT_FALSE(LinkOriginLookup(link, IFMapOrigin::MAP_SERVER));
EXPECT_TRUE(LinkOriginLookup(link, IFMapOrigin::XMPP));
TASK_UTIL_EXPECT_TRUE(LinkLookup(vr, vm3) != NULL);
link = LinkLookup(vr, vm3);
EXPECT_FALSE(LinkOriginLookup(link, IFMapOrigin::MAP_SERVER));
EXPECT_TRUE(LinkOriginLookup(link, IFMapOrigin::XMPP));
// Delete the vr and all the vms via config
string content1 =
FileRead("controller/src/ifmap/testdata/vr_3vm_delete.xml");
assert(content1.size() != 0);
parser_->Receive(&db_, content1.data(), content1.size(), 0);
task_util::WaitForIdle();
usleep(1000);
EXPECT_TRUE(TableLookup("virtual-router", client_name) != NULL);
EXPECT_TRUE(TableLookup("virtual-machine",
"2d308482-c7b3-4e05-af14-e732b7b50117") != NULL);
EXPECT_TRUE(TableLookup("virtual-machine",
"93e76278-1990-4905-a472-8e9188f41b2c") != NULL);
EXPECT_TRUE(TableLookup("virtual-machine",
"43d086ab-52c4-4a1f-8c3d-63b321e36e8a") != NULL);
EXPECT_FALSE(NodeOriginLookup(vr, IFMapOrigin::MAP_SERVER));
EXPECT_TRUE(NodeOriginLookup(vr, IFMapOrigin::XMPP));
EXPECT_FALSE(NodeOriginLookup(vm1, IFMapOrigin::MAP_SERVER));
EXPECT_TRUE(NodeOriginLookup(vm1, IFMapOrigin::XMPP));
EXPECT_FALSE(NodeOriginLookup(vm2, IFMapOrigin::MAP_SERVER));
EXPECT_TRUE(NodeOriginLookup(vm2, IFMapOrigin::XMPP));
EXPECT_FALSE(NodeOriginLookup(vm3, IFMapOrigin::MAP_SERVER));
EXPECT_TRUE(NodeOriginLookup(vm3, IFMapOrigin::XMPP));
TASK_UTIL_EXPECT_TRUE(LinkLookup(vr, vm1) != NULL);
link = LinkLookup(vr, vm1);
EXPECT_FALSE(LinkOriginLookup(link, IFMapOrigin::MAP_SERVER));
EXPECT_TRUE(LinkOriginLookup(link, IFMapOrigin::XMPP));
TASK_UTIL_EXPECT_TRUE(LinkLookup(vr, vm2) != NULL);
link = LinkLookup(vr, vm2);
EXPECT_FALSE(LinkOriginLookup(link, IFMapOrigin::MAP_SERVER));
EXPECT_TRUE(LinkOriginLookup(link, IFMapOrigin::XMPP));
TASK_UTIL_EXPECT_TRUE(LinkLookup(vr, vm3) != NULL);
link = LinkLookup(vr, vm3);
EXPECT_FALSE(LinkOriginLookup(link, IFMapOrigin::MAP_SERVER));
EXPECT_TRUE(LinkOriginLookup(link, IFMapOrigin::XMPP));
vnsw_client->SendVmConfigUnsubscribe(
"2d308482-c7b3-4e05-af14-e732b7b50117");
usleep(1000);
vnsw_client->SendVmConfigUnsubscribe(
"93e76278-1990-4905-a472-8e9188f41b2c");
usleep(1000);
vnsw_client->SendVmConfigUnsubscribe(
"43d086ab-52c4-4a1f-8c3d-63b321e36e8a");
usleep(1000);
TASK_UTIL_EXPECT_TRUE(TableLookup("virtual-router", client_name) == NULL);
TASK_UTIL_EXPECT_TRUE(TableLookup("virtual-machine",
"2d308482-c7b3-4e05-af14-e732b7b50117") == NULL);;
TASK_UTIL_EXPECT_TRUE(TableLookup("virtual-machine",
"93e76278-1990-4905-a472-8e9188f41b2c") == NULL);
TASK_UTIL_EXPECT_TRUE(TableLookup("virtual-machine",
"43d086ab-52c4-4a1f-8c3d-63b321e36e8a") == NULL);
EXPECT_EQ(ifmap_server_.GetClientMapSize(), 1);
// Client close generates a TcpClose event on server
ConfigUpdate(vnsw_client, new XmppConfigData());
TASK_UTIL_EXPECT_EQ(ifmap_server_.GetClientMapSize(), 0);
// Verify ifmap_server client cleanup
EXPECT_EQ(true, IsIFMapClientUnregistered(&ifmap_server_, client_name));
vnsw_client->UnRegisterWithXmpp();
vnsw_client->Shutdown();
task_util::WaitForIdle();
TcpServerManager::DeleteServer(vnsw_client);
vnsw_client = NULL;
// Delete xmpp-channel explicitly
XmppConnection *sconnection = xmpp_server_->FindConnection(client_name);
if (sconnection) {
sconnection->Shutdown();
}
TASK_UTIL_EXPECT_EQ(xmpp_server_->ConnectionCount(), 0);
EXPECT_TRUE(xmpp_server_->FindConnection(client_name) == NULL);
}
// Vm-reg followed by config-add followed by config-delete followed by vm-unreg
// followed by close
TEST_F(XmppIfmapTest, Reg_CfgAdd_CfgDel_Unreg) {
SetObjectsPerMessage(1);
// create the mock client
string client_name =
string("default-global-system-config:a1s27.contrail.juniper.net");
string filename("/tmp/" + GetUserName() +
"_reg_cfgadd_cfgdel_unreg.output");
IFMapXmppClientMock *vnsw_client =
new IFMapXmppClientMock(&evm_, xmpp_server_->GetPort(), client_name,
filename);
TASK_UTIL_EXPECT_EQ(true, vnsw_client->IsEstablished());
vnsw_client->RegisterWithXmpp();
usleep(1000);
// Server connection
TASK_UTIL_EXPECT_TRUE(ServerIsEstablished(xmpp_server_, client_name)
== true);
// verify ifmap_server client is not created until config subscribe
EXPECT_TRUE(ifmap_server_.FindClient(client_name) == NULL);
// no config messages sent until config subscribe
EXPECT_EQ(0, vnsw_client->Count());
vnsw_client->SendConfigSubscribe();
TASK_UTIL_EXPECT_TRUE(ifmap_server_.FindClient(client_name) != NULL);
// Allow sender to run
usleep(1000);
IFMapClient *client = ifmap_server_.FindClient(client_name);
EXPECT_TRUE(client != NULL);
EXPECT_EQ(client->msgs_sent(), vnsw_client->Count());
EXPECT_EQ(vnsw_client->Count(), 0);
IFMapNode *vr = TableLookup("virtual-router", client_name);
EXPECT_TRUE(vr == NULL);
IFMapNode *vm1 = TableLookup("virtual-machine",
"2d308482-c7b3-4e05-af14-e732b7b50117");
EXPECT_TRUE(vm1 == NULL);
IFMapNode *vm2 = TableLookup("virtual-machine",
"93e76278-1990-4905-a472-8e9188f41b2c");
EXPECT_TRUE(vm2 == NULL);
IFMapNode *vm3 = TableLookup("virtual-machine",
"43d086ab-52c4-4a1f-8c3d-63b321e36e8a");
EXPECT_TRUE(vm3 == NULL);
vnsw_client->SendVmConfigSubscribe("2d308482-c7b3-4e05-af14-e732b7b50117");
usleep(1000);
vnsw_client->SendVmConfigSubscribe("93e76278-1990-4905-a472-8e9188f41b2c");
usleep(1000);
vnsw_client->SendVmConfigSubscribe("43d086ab-52c4-4a1f-8c3d-63b321e36e8a");
usleep(1000);
EXPECT_EQ(0, vnsw_client->Count());
EXPECT_TRUE(TableLookup("virtual-router", client_name) == NULL);
EXPECT_TRUE(TableLookup("virtual-machine",
"2d308482-c7b3-4e05-af14-e732b7b50117") == NULL);
EXPECT_TRUE(TableLookup("virtual-machine",
"93e76278-1990-4905-a472-8e9188f41b2c") == NULL);
EXPECT_TRUE(TableLookup("virtual-machine",
"43d086ab-52c4-4a1f-8c3d-63b321e36e8a") == NULL);
// Read the ifmap data from file and give it to the parser
string content(FileRead("controller/src/ifmap/testdata/vr_3vm_add.xml"));
assert(content.size() != 0);
parser_->Receive(&db_, content.data(), content.size(), 0);
task_util::WaitForIdle();
usleep(1000);
TASK_UTIL_EXPECT_TRUE(TableLookup("virtual-router", client_name) != NULL);
vr = TableLookup("virtual-router", client_name);
TASK_UTIL_EXPECT_TRUE(TableLookup("virtual-machine",
"2d308482-c7b3-4e05-af14-e732b7b50117") != NULL);
vm1 = TableLookup("virtual-machine",
"2d308482-c7b3-4e05-af14-e732b7b50117");
TASK_UTIL_EXPECT_TRUE(TableLookup("virtual-machine",
"93e76278-1990-4905-a472-8e9188f41b2c") != NULL);
vm2 = TableLookup("virtual-machine",
"93e76278-1990-4905-a472-8e9188f41b2c");
TASK_UTIL_EXPECT_TRUE(TableLookup("virtual-machine",
"43d086ab-52c4-4a1f-8c3d-63b321e36e8a") != NULL);
vm3 = TableLookup("virtual-machine",
"43d086ab-52c4-4a1f-8c3d-63b321e36e8a");
TASK_UTIL_EXPECT_TRUE(LinkLookup(vr, vm1) != NULL);
IFMapLink *link = LinkLookup(vr, vm1);
EXPECT_FALSE(LinkOriginLookup(link, IFMapOrigin::MAP_SERVER));
EXPECT_TRUE(LinkOriginLookup(link, IFMapOrigin::XMPP));
TASK_UTIL_EXPECT_TRUE(LinkLookup(vr, vm2) != NULL);
link = LinkLookup(vr, vm2);
EXPECT_FALSE(LinkOriginLookup(link, IFMapOrigin::MAP_SERVER));
EXPECT_TRUE(LinkOriginLookup(link, IFMapOrigin::XMPP));
TASK_UTIL_EXPECT_TRUE(LinkLookup(vr, vm3) != NULL);
link = LinkLookup(vr, vm3);
EXPECT_FALSE(LinkOriginLookup(link, IFMapOrigin::MAP_SERVER));
EXPECT_TRUE(LinkOriginLookup(link, IFMapOrigin::XMPP));
EXPECT_TRUE(NodeOriginLookup(vr, IFMapOrigin::MAP_SERVER));
EXPECT_TRUE(NodeOriginLookup(vr, IFMapOrigin::XMPP));
EXPECT_TRUE(NodeOriginLookup(vm1, IFMapOrigin::MAP_SERVER));
EXPECT_TRUE(NodeOriginLookup(vm1, IFMapOrigin::XMPP));
EXPECT_TRUE(NodeOriginLookup(vm2, IFMapOrigin::MAP_SERVER));
EXPECT_TRUE(NodeOriginLookup(vm2, IFMapOrigin::XMPP));
EXPECT_TRUE(NodeOriginLookup(vm3, IFMapOrigin::MAP_SERVER));
EXPECT_TRUE(NodeOriginLookup(vm3, IFMapOrigin::XMPP));
// Delete the vr and all the vms via config
string content1 =
FileRead("controller/src/ifmap/testdata/vr_3vm_delete.xml");
assert(content1.size() != 0);
parser_->Receive(&db_, content1.data(), content1.size(), 0);
task_util::WaitForIdle();
usleep(1000);
EXPECT_TRUE(TableLookup("virtual-router", client_name) != NULL);
EXPECT_TRUE(TableLookup("virtual-machine",
"2d308482-c7b3-4e05-af14-e732b7b50117") != NULL);
EXPECT_TRUE(TableLookup("virtual-machine",
"93e76278-1990-4905-a472-8e9188f41b2c") != NULL);
EXPECT_TRUE(TableLookup("virtual-machine",
"43d086ab-52c4-4a1f-8c3d-63b321e36e8a") != NULL);
TASK_UTIL_EXPECT_FALSE(NodeOriginLookup(vr, IFMapOrigin::MAP_SERVER));
EXPECT_TRUE(NodeOriginLookup(vr, IFMapOrigin::XMPP));
TASK_UTIL_EXPECT_FALSE(NodeOriginLookup(vm1, IFMapOrigin::MAP_SERVER));
EXPECT_TRUE(NodeOriginLookup(vm1, IFMapOrigin::XMPP));
TASK_UTIL_EXPECT_FALSE(NodeOriginLookup(vm2, IFMapOrigin::MAP_SERVER));
EXPECT_TRUE(NodeOriginLookup(vm2, IFMapOrigin::XMPP));
TASK_UTIL_EXPECT_FALSE(NodeOriginLookup(vm3, IFMapOrigin::MAP_SERVER));
EXPECT_TRUE(NodeOriginLookup(vm3, IFMapOrigin::XMPP));
TASK_UTIL_EXPECT_TRUE(LinkLookup(vr, vm1) != NULL);
link = LinkLookup(vr, vm1);
EXPECT_FALSE(LinkOriginLookup(link, IFMapOrigin::MAP_SERVER));
EXPECT_TRUE(LinkOriginLookup(link, IFMapOrigin::XMPP));
TASK_UTIL_EXPECT_TRUE(LinkLookup(vr, vm2) != NULL);
link = LinkLookup(vr, vm2);
EXPECT_FALSE(LinkOriginLookup(link, IFMapOrigin::MAP_SERVER));
EXPECT_TRUE(LinkOriginLookup(link, IFMapOrigin::XMPP));
TASK_UTIL_EXPECT_TRUE(LinkLookup(vr, vm3) != NULL);
link = LinkLookup(vr, vm3);
EXPECT_FALSE(LinkOriginLookup(link, IFMapOrigin::MAP_SERVER));
EXPECT_TRUE(LinkOriginLookup(link, IFMapOrigin::XMPP));
vnsw_client->SendVmConfigUnsubscribe(
"2d308482-c7b3-4e05-af14-e732b7b50117");
usleep(1000);
vnsw_client->SendVmConfigUnsubscribe(
"93e76278-1990-4905-a472-8e9188f41b2c");
usleep(1000);
vnsw_client->SendVmConfigUnsubscribe(
"43d086ab-52c4-4a1f-8c3d-63b321e36e8a");
usleep(1000);
TASK_UTIL_EXPECT_TRUE(TableLookup("virtual-router", client_name) == NULL);
TASK_UTIL_EXPECT_TRUE(TableLookup("virtual-machine",
"2d308482-c7b3-4e05-af14-e732b7b50117") == NULL);;
TASK_UTIL_EXPECT_TRUE(TableLookup("virtual-machine",
"93e76278-1990-4905-a472-8e9188f41b2c") == NULL);
TASK_UTIL_EXPECT_TRUE(TableLookup("virtual-machine",
"43d086ab-52c4-4a1f-8c3d-63b321e36e8a") == NULL);
EXPECT_EQ(ifmap_server_.GetClientMapSize(), 1);
// Client close generates a TcpClose event on server
ConfigUpdate(vnsw_client, new XmppConfigData());
TASK_UTIL_EXPECT_EQ(ifmap_server_.GetClientMapSize(), 0);
// Verify ifmap_server client cleanup
EXPECT_EQ(true, IsIFMapClientUnregistered(&ifmap_server_, client_name));
vnsw_client->UnRegisterWithXmpp();
vnsw_client->Shutdown();
task_util::WaitForIdle();
TcpServerManager::DeleteServer(vnsw_client);
vnsw_client = NULL;
// Delete xmpp-channel explicitly
XmppConnection *sconnection = xmpp_server_->FindConnection(client_name);
if (sconnection) {
sconnection->Shutdown();
}
TASK_UTIL_EXPECT_EQ(xmpp_server_->ConnectionCount(), 0);
EXPECT_TRUE(xmpp_server_->FindConnection(client_name) == NULL);
}
// Vm-reg followed by config-add followed by vm-unreg followed by config-delete
// followed by close
TEST_F(XmppIfmapTest, Reg_CfgAdd_Unreg_CfgDel) {
SetObjectsPerMessage(1);
// create the mock client
string client_name =
string("default-global-system-config:a1s27.contrail.juniper.net");
string filename("/tmp/" + GetUserName() +
"_reg_cfgadd_unreg_cfgdel.output");
IFMapXmppClientMock *vnsw_client =
new IFMapXmppClientMock(&evm_, xmpp_server_->GetPort(), client_name,
filename);
TASK_UTIL_EXPECT_EQ(true, vnsw_client->IsEstablished());
vnsw_client->RegisterWithXmpp();
usleep(1000);
// Server connection
TASK_UTIL_EXPECT_TRUE(ServerIsEstablished(xmpp_server_, client_name)
== true);
// verify ifmap_server client is not created until config subscribe
EXPECT_TRUE(ifmap_server_.FindClient(client_name) == NULL);
// no config messages sent until config subscribe
EXPECT_EQ(0, vnsw_client->Count());
vnsw_client->SendConfigSubscribe();
TASK_UTIL_EXPECT_TRUE(ifmap_server_.FindClient(client_name) != NULL);
// Allow sender to run
usleep(1000);
IFMapClient *client = ifmap_server_.FindClient(client_name);
EXPECT_TRUE(client != NULL);
EXPECT_EQ(client->msgs_sent(), vnsw_client->Count());
EXPECT_EQ(vnsw_client->Count(), 0);
// Config not read yet
IFMapNode *vr = TableLookup("virtual-router", client_name);
EXPECT_TRUE(vr == NULL);
IFMapNode *vm1 = TableLookup("virtual-machine",
"2d308482-c7b3-4e05-af14-e732b7b50117");
EXPECT_TRUE(vm1 == NULL);
IFMapNode *vm2 = TableLookup("virtual-machine",
"93e76278-1990-4905-a472-8e9188f41b2c");
EXPECT_TRUE(vm2 == NULL);
IFMapNode *vm3 = TableLookup("virtual-machine",
"43d086ab-52c4-4a1f-8c3d-63b321e36e8a");
EXPECT_TRUE(vm3 == NULL);
vnsw_client->SendVmConfigSubscribe("2d308482-c7b3-4e05-af14-e732b7b50117");
usleep(1000);
vnsw_client->SendVmConfigSubscribe("93e76278-1990-4905-a472-8e9188f41b2c");
usleep(1000);
vnsw_client->SendVmConfigSubscribe("43d086ab-52c4-4a1f-8c3d-63b321e36e8a");
usleep(1000);
TASK_UTIL_EXPECT_EQ(0, vnsw_client->Count());
TASK_UTIL_EXPECT_TRUE(TableLookup("virtual-router", client_name) == NULL);
TASK_UTIL_EXPECT_TRUE(TableLookup("virtual-machine",
"2d308482-c7b3-4e05-af14-e732b7b50117") == NULL);
TASK_UTIL_EXPECT_TRUE(TableLookup("virtual-machine",
"93e76278-1990-4905-a472-8e9188f41b2c") == NULL);
TASK_UTIL_EXPECT_TRUE(TableLookup("virtual-machine",
"43d086ab-52c4-4a1f-8c3d-63b321e36e8a") == NULL);
// Read the ifmap data from file and give it to the parser
string content =
FileRead("controller/src/ifmap/testdata/vr_3vm_add.xml");
assert(content.size() != 0);
parser_->Receive(&db_, content.data(), content.size(), 0);
task_util::WaitForIdle();
usleep(1000);
TASK_UTIL_EXPECT_TRUE(TableLookup("virtual-router", client_name) != NULL);
vr = TableLookup("virtual-router", client_name);
TASK_UTIL_EXPECT_TRUE(TableLookup("virtual-machine",
"2d308482-c7b3-4e05-af14-e732b7b50117") != NULL);
vm1 = TableLookup("virtual-machine",
"2d308482-c7b3-4e05-af14-e732b7b50117");
TASK_UTIL_EXPECT_TRUE(TableLookup("virtual-machine",
"93e76278-1990-4905-a472-8e9188f41b2c") != NULL);
vm2 = TableLookup("virtual-machine",
"93e76278-1990-4905-a472-8e9188f41b2c");
TASK_UTIL_EXPECT_TRUE(TableLookup("virtual-machine",
"43d086ab-52c4-4a1f-8c3d-63b321e36e8a") != NULL);
vm3 = TableLookup("virtual-machine",
"43d086ab-52c4-4a1f-8c3d-63b321e36e8a");
TASK_UTIL_EXPECT_TRUE(LinkLookup(vr, vm1) != NULL);
IFMapLink *link = LinkLookup(vr, vm1);
EXPECT_FALSE(LinkOriginLookup(link, IFMapOrigin::MAP_SERVER));
EXPECT_TRUE(LinkOriginLookup(link, IFMapOrigin::XMPP));
TASK_UTIL_EXPECT_TRUE(LinkLookup(vr, vm2) != NULL);
link = LinkLookup(vr, vm2);
EXPECT_FALSE(LinkOriginLookup(link, IFMapOrigin::MAP_SERVER));
EXPECT_TRUE(LinkOriginLookup(link, IFMapOrigin::XMPP));
TASK_UTIL_EXPECT_TRUE(LinkLookup(vr, vm3) != NULL);
link = LinkLookup(vr, vm3);
EXPECT_FALSE(LinkOriginLookup(link, IFMapOrigin::MAP_SERVER));
EXPECT_TRUE(LinkOriginLookup(link, IFMapOrigin::XMPP));
EXPECT_TRUE(NodeOriginLookup(vr, IFMapOrigin::MAP_SERVER));
EXPECT_TRUE(NodeOriginLookup(vr, IFMapOrigin::XMPP));
EXPECT_TRUE(NodeOriginLookup(vm1, IFMapOrigin::MAP_SERVER));
EXPECT_TRUE(NodeOriginLookup(vm1, IFMapOrigin::XMPP));
EXPECT_TRUE(NodeOriginLookup(vm2, IFMapOrigin::MAP_SERVER));
EXPECT_TRUE(NodeOriginLookup(vm2, IFMapOrigin::XMPP));
EXPECT_TRUE(NodeOriginLookup(vm3, IFMapOrigin::MAP_SERVER));
EXPECT_TRUE(NodeOriginLookup(vm3, IFMapOrigin::XMPP));
vnsw_client->SendVmConfigUnsubscribe(
"2d308482-c7b3-4e05-af14-e732b7b50117");
usleep(1000);
vnsw_client->SendVmConfigUnsubscribe(
"93e76278-1990-4905-a472-8e9188f41b2c");
usleep(1000);
vnsw_client->SendVmConfigUnsubscribe(
"43d086ab-52c4-4a1f-8c3d-63b321e36e8a");
usleep(1000);
TASK_UTIL_EXPECT_TRUE(TableLookup("virtual-router", client_name) != NULL);
TASK_UTIL_EXPECT_TRUE(TableLookup("virtual-machine",
"2d308482-c7b3-4e05-af14-e732b7b50117") != NULL);;
TASK_UTIL_EXPECT_TRUE(TableLookup("virtual-machine",
"93e76278-1990-4905-a472-8e9188f41b2c") != NULL);
TASK_UTIL_EXPECT_TRUE(TableLookup("virtual-machine",
"43d086ab-52c4-4a1f-8c3d-63b321e36e8a") != NULL);
EXPECT_TRUE(NodeOriginLookup(vr, IFMapOrigin::MAP_SERVER));
TASK_UTIL_EXPECT_FALSE(NodeOriginLookup(vr, IFMapOrigin::XMPP));
EXPECT_TRUE(NodeOriginLookup(vm1, IFMapOrigin::MAP_SERVER));
TASK_UTIL_EXPECT_FALSE(NodeOriginLookup(vm1, IFMapOrigin::XMPP));
EXPECT_TRUE(NodeOriginLookup(vm2, IFMapOrigin::MAP_SERVER));
TASK_UTIL_EXPECT_FALSE(NodeOriginLookup(vm2, IFMapOrigin::XMPP));
EXPECT_TRUE(NodeOriginLookup(vm3, IFMapOrigin::MAP_SERVER));
TASK_UTIL_EXPECT_FALSE(NodeOriginLookup(vm3, IFMapOrigin::XMPP));
TASK_UTIL_EXPECT_TRUE(LinkLookup(vr, vm1) == NULL);
TASK_UTIL_EXPECT_TRUE(LinkLookup(vr, vm2) == NULL);
TASK_UTIL_EXPECT_TRUE(LinkLookup(vr, vm3) == NULL);
// Delete the vr and all the vms via config
string content1 =
FileRead("controller/src/ifmap/testdata/vr_3vm_delete.xml");
assert(content1.size() != 0);
parser_->Receive(&db_, content1.data(), content1.size(), 0);
task_util::WaitForIdle();
usleep(1000);
TASK_UTIL_EXPECT_TRUE(TableLookup("virtual-router", client_name) == NULL);
TASK_UTIL_EXPECT_TRUE(TableLookup("virtual-machine",
"2d308482-c7b3-4e05-af14-e732b7b50117") == NULL);
TASK_UTIL_EXPECT_TRUE(TableLookup("virtual-machine",
"93e76278-1990-4905-a472-8e9188f41b2c") == NULL);
TASK_UTIL_EXPECT_TRUE(TableLookup("virtual-machine",
"43d086ab-52c4-4a1f-8c3d-63b321e36e8a") == NULL);
EXPECT_EQ(ifmap_server_.GetClientMapSize(), 1);
// Client close generates a TcpClose event on server
ConfigUpdate(vnsw_client, new XmppConfigData());
TASK_UTIL_EXPECT_EQ(ifmap_server_.GetClientMapSize(), 0);
// Verify ifmap_server client cleanup
EXPECT_EQ(true, IsIFMapClientUnregistered(&ifmap_server_, client_name));
vnsw_client->UnRegisterWithXmpp();
vnsw_client->Shutdown();
task_util::WaitForIdle();
TcpServerManager::DeleteServer(vnsw_client);
vnsw_client = NULL;
// Delete xmpp-channel explicitly
XmppConnection *sconnection = xmpp_server_->FindConnection(client_name);
if (sconnection) {
sconnection->Shutdown();
}
TASK_UTIL_EXPECT_EQ(xmpp_server_->ConnectionCount(), 0);
EXPECT_TRUE(xmpp_server_->FindConnection(client_name) == NULL);
}
// Vm-reg followed by config-add followed by vm-unreg followed by close
TEST_F(XmppIfmapTest, Reg_CfgAdd_Unreg_Close) {
SetObjectsPerMessage(1);
// create the mock client
string client_name =
string("default-global-system-config:a1s27.contrail.juniper.net");
string filename("/tmp/" + GetUserName() + "_reg_cfgadd_unreg_close.output");
IFMapXmppClientMock *vnsw_client =
new IFMapXmppClientMock(&evm_, xmpp_server_->GetPort(), client_name,
filename);
TASK_UTIL_EXPECT_EQ(true, vnsw_client->IsEstablished());
vnsw_client->RegisterWithXmpp();
usleep(1000);
// Server connection
TASK_UTIL_EXPECT_TRUE(ServerIsEstablished(xmpp_server_, client_name)
== true);
// verify ifmap_server client is not created until config subscribe
EXPECT_TRUE(ifmap_server_.FindClient(client_name) == NULL);
// no config messages sent until config subscribe
EXPECT_EQ(0, vnsw_client->Count());
vnsw_client->SendConfigSubscribe();
TASK_UTIL_EXPECT_TRUE(ifmap_server_.FindClient(client_name) != NULL);
// Allow sender to run
usleep(1000);
IFMapClient *client = ifmap_server_.FindClient(client_name);
EXPECT_TRUE(client != NULL);
EXPECT_EQ(client->msgs_sent(), vnsw_client->Count());
EXPECT_EQ(vnsw_client->Count(), 0);
// Config not read yet
IFMapNode *vr = TableLookup("virtual-router", client_name);
EXPECT_TRUE(vr == NULL);
IFMapNode *vm1 = TableLookup("virtual-machine",
"2d308482-c7b3-4e05-af14-e732b7b50117");
EXPECT_TRUE(vm1 == NULL);
IFMapNode *vm2 = TableLookup("virtual-machine",
"93e76278-1990-4905-a472-8e9188f41b2c");
EXPECT_TRUE(vm2 == NULL);
IFMapNode *vm3 = TableLookup("virtual-machine",
"43d086ab-52c4-4a1f-8c3d-63b321e36e8a");
EXPECT_TRUE(vm3 == NULL);
vnsw_client->SendVmConfigSubscribe("2d308482-c7b3-4e05-af14-e732b7b50117");
usleep(1000);
vnsw_client->SendVmConfigSubscribe("93e76278-1990-4905-a472-8e9188f41b2c");
usleep(1000);
vnsw_client->SendVmConfigSubscribe("43d086ab-52c4-4a1f-8c3d-63b321e36e8a");
usleep(1000);
TASK_UTIL_EXPECT_EQ(0, vnsw_client->Count());
TASK_UTIL_EXPECT_TRUE(TableLookup("virtual-router", client_name) == NULL);
TASK_UTIL_EXPECT_TRUE(TableLookup("virtual-machine",
"2d308482-c7b3-4e05-af14-e732b7b50117") == NULL);
TASK_UTIL_EXPECT_TRUE(TableLookup("virtual-machine",
"93e76278-1990-4905-a472-8e9188f41b2c") == NULL);
TASK_UTIL_EXPECT_TRUE(TableLookup("virtual-machine",
"43d086ab-52c4-4a1f-8c3d-63b321e36e8a") == NULL);
// Read the ifmap data from file and give it to the parser
string content(FileRead("controller/src/ifmap/testdata/vr_3vm_add.xml"));
assert(content.size() != 0);
parser_->Receive(&db_, content.data(), content.size(), 0);
task_util::WaitForIdle();
usleep(1000);
TASK_UTIL_EXPECT_NE(0, vnsw_client->Count());
TASK_UTIL_EXPECT_TRUE(TableLookup("virtual-router", client_name) != NULL);
vr = TableLookup("virtual-router", client_name);
TASK_UTIL_EXPECT_TRUE(TableLookup("virtual-machine",
"2d308482-c7b3-4e05-af14-e732b7b50117") != NULL);
vm1 = TableLookup("virtual-machine",
"2d308482-c7b3-4e05-af14-e732b7b50117");
TASK_UTIL_EXPECT_TRUE(TableLookup("virtual-machine",
"93e76278-1990-4905-a472-8e9188f41b2c") != NULL);
vm2 = TableLookup("virtual-machine",
"93e76278-1990-4905-a472-8e9188f41b2c");
TASK_UTIL_EXPECT_TRUE(TableLookup("virtual-machine",
"43d086ab-52c4-4a1f-8c3d-63b321e36e8a") != NULL);
vm3 = TableLookup("virtual-machine",
"43d086ab-52c4-4a1f-8c3d-63b321e36e8a");
TASK_UTIL_EXPECT_TRUE(LinkLookup(vr, vm1) != NULL);
IFMapLink *link = LinkLookup(vr, vm1);
EXPECT_FALSE(LinkOriginLookup(link, IFMapOrigin::MAP_SERVER));
EXPECT_TRUE(LinkOriginLookup(link, IFMapOrigin::XMPP));
TASK_UTIL_EXPECT_TRUE(LinkLookup(vr, vm2) != NULL);
link = LinkLookup(vr, vm2);
EXPECT_FALSE(LinkOriginLookup(link, IFMapOrigin::MAP_SERVER));
EXPECT_TRUE(LinkOriginLookup(link, IFMapOrigin::XMPP));
TASK_UTIL_EXPECT_TRUE(LinkLookup(vr, vm3) != NULL);
link = LinkLookup(vr, vm3);
EXPECT_FALSE(LinkOriginLookup(link, IFMapOrigin::MAP_SERVER));
EXPECT_TRUE(LinkOriginLookup(link, IFMapOrigin::XMPP));
EXPECT_TRUE(NodeOriginLookup(vr, IFMapOrigin::MAP_SERVER));
EXPECT_TRUE(NodeOriginLookup(vr, IFMapOrigin::XMPP));
EXPECT_TRUE(NodeOriginLookup(vm1, IFMapOrigin::MAP_SERVER));
EXPECT_TRUE(NodeOriginLookup(vm1, IFMapOrigin::XMPP));
EXPECT_TRUE(NodeOriginLookup(vm2, IFMapOrigin::MAP_SERVER));
EXPECT_TRUE(NodeOriginLookup(vm2, IFMapOrigin::XMPP));
EXPECT_TRUE(NodeOriginLookup(vm3, IFMapOrigin::MAP_SERVER));
EXPECT_TRUE(NodeOriginLookup(vm3, IFMapOrigin::XMPP));
vnsw_client->SendVmConfigUnsubscribe(
"2d308482-c7b3-4e05-af14-e732b7b50117");
usleep(1000);
TASK_UTIL_EXPECT_FALSE(NodeOriginLookup(vm1, IFMapOrigin::XMPP));
EXPECT_TRUE(NodeOriginLookup(vm1, IFMapOrigin::MAP_SERVER));
EXPECT_TRUE(NodeOriginLookup(vr, IFMapOrigin::XMPP));
EXPECT_TRUE(NodeOriginLookup(vr, IFMapOrigin::MAP_SERVER));
EXPECT_TRUE(NodeOriginLookup(vm2, IFMapOrigin::XMPP));
EXPECT_TRUE(NodeOriginLookup(vm2, IFMapOrigin::MAP_SERVER));
EXPECT_TRUE(NodeOriginLookup(vm3, IFMapOrigin::XMPP));
EXPECT_TRUE(NodeOriginLookup(vm3, IFMapOrigin::MAP_SERVER));
vnsw_client->SendVmConfigUnsubscribe(
"93e76278-1990-4905-a472-8e9188f41b2c");
usleep(1000);
TASK_UTIL_EXPECT_FALSE(NodeOriginLookup(vm2, IFMapOrigin::XMPP));
EXPECT_TRUE(NodeOriginLookup(vm2, IFMapOrigin::MAP_SERVER));
EXPECT_TRUE(NodeOriginLookup(vr, IFMapOrigin::XMPP));
EXPECT_TRUE(NodeOriginLookup(vr, IFMapOrigin::MAP_SERVER));
EXPECT_FALSE(NodeOriginLookup(vm1, IFMapOrigin::XMPP));
EXPECT_TRUE(NodeOriginLookup(vm1, IFMapOrigin::MAP_SERVER));
EXPECT_TRUE(NodeOriginLookup(vm3, IFMapOrigin::XMPP));
EXPECT_TRUE(NodeOriginLookup(vm3, IFMapOrigin::MAP_SERVER));
vnsw_client->SendVmConfigUnsubscribe(
"43d086ab-52c4-4a1f-8c3d-63b321e36e8a");
usleep(1000);
TASK_UTIL_EXPECT_FALSE(NodeOriginLookup(vm3, IFMapOrigin::XMPP));
EXPECT_TRUE(NodeOriginLookup(vm3, IFMapOrigin::MAP_SERVER));
EXPECT_FALSE(NodeOriginLookup(vr, IFMapOrigin::XMPP));
EXPECT_TRUE(NodeOriginLookup(vr, IFMapOrigin::MAP_SERVER));
EXPECT_FALSE(NodeOriginLookup(vm1, IFMapOrigin::XMPP));
EXPECT_TRUE(NodeOriginLookup(vm1, IFMapOrigin::MAP_SERVER));
EXPECT_FALSE(NodeOriginLookup(vm2, IFMapOrigin::XMPP));
EXPECT_TRUE(NodeOriginLookup(vm2, IFMapOrigin::MAP_SERVER));
TASK_UTIL_EXPECT_TRUE(TableLookup("virtual-router", client_name) != NULL);
TASK_UTIL_EXPECT_TRUE(TableLookup("virtual-machine",
"2d308482-c7b3-4e05-af14-e732b7b50117") != NULL);;
TASK_UTIL_EXPECT_TRUE(TableLookup("virtual-machine",
"93e76278-1990-4905-a472-8e9188f41b2c") != NULL);
TASK_UTIL_EXPECT_TRUE(TableLookup("virtual-machine",
"43d086ab-52c4-4a1f-8c3d-63b321e36e8a") != NULL);
EXPECT_TRUE(NodeOriginLookup(vr, IFMapOrigin::MAP_SERVER));
TASK_UTIL_EXPECT_FALSE(NodeOriginLookup(vr, IFMapOrigin::XMPP));
EXPECT_TRUE(NodeOriginLookup(vm1, IFMapOrigin::MAP_SERVER));
TASK_UTIL_EXPECT_FALSE(NodeOriginLookup(vm1, IFMapOrigin::XMPP));
EXPECT_TRUE(NodeOriginLookup(vm2, IFMapOrigin::MAP_SERVER));
TASK_UTIL_EXPECT_FALSE(NodeOriginLookup(vm2, IFMapOrigin::XMPP));
EXPECT_TRUE(NodeOriginLookup(vm3, IFMapOrigin::MAP_SERVER));
TASK_UTIL_EXPECT_FALSE(NodeOriginLookup(vm3, IFMapOrigin::XMPP));
TASK_UTIL_EXPECT_TRUE(LinkLookup(vr, vm1) == NULL);
TASK_UTIL_EXPECT_TRUE(LinkLookup(vr, vm2) == NULL);
TASK_UTIL_EXPECT_TRUE(LinkLookup(vr, vm3) == NULL);
EXPECT_EQ(ifmap_server_.GetClientMapSize(), 1);
// Client close generates a TcpClose event on server
ConfigUpdate(vnsw_client, new XmppConfigData());
TASK_UTIL_EXPECT_EQ(ifmap_server_.GetClientMapSize(), 0);
// Verify ifmap_server client cleanup
EXPECT_EQ(true, IsIFMapClientUnregistered(&ifmap_server_, client_name));
vnsw_client->UnRegisterWithXmpp();
vnsw_client->Shutdown();
task_util::WaitForIdle();
TcpServerManager::DeleteServer(vnsw_client);
vnsw_client = NULL;
// Delete xmpp-channel explicitly
XmppConnection *sconnection = xmpp_server_->FindConnection(client_name);
if (sconnection) {
sconnection->Shutdown();
}
TASK_UTIL_EXPECT_EQ(xmpp_server_->ConnectionCount(), 0);
EXPECT_TRUE(xmpp_server_->FindConnection(client_name) == NULL);
}
// vm-sub then cfg-add then vm-unsub then vm-sub then cfg-del then cfg-add and
// vm-sub
TEST_F(XmppIfmapTest, CheckIFMapObjectSeqInList) {
SetObjectsPerMessage(1);
// create the mock client
string client_name =
string("default-global-system-config:a1s27.contrail.juniper.net");
string filename("/tmp/" + GetUserName() +
"_check_ifmap_object_seq_in_list.output");
IFMapXmppClientMock *vnsw_client =
new IFMapXmppClientMock(&evm_, xmpp_server_->GetPort(), client_name,
filename);
TASK_UTIL_EXPECT_EQ(true, vnsw_client->IsEstablished());
vnsw_client->RegisterWithXmpp();
usleep(1000);
// Server connection
TASK_UTIL_EXPECT_TRUE(ServerIsEstablished(xmpp_server_, client_name)
== true);
// Verify ifmap_server client is not created until config subscribe
EXPECT_TRUE(ifmap_server_.FindClient(client_name) == NULL);
// No config messages sent until config subscribe
EXPECT_EQ(0, vnsw_client->Count());
vnsw_client->SendConfigSubscribe();
TASK_UTIL_EXPECT_TRUE(ifmap_server_.FindClient(client_name) != NULL);
// Allow sender to run
usleep(1000);
IFMapClient *client = ifmap_server_.FindClient(client_name);
EXPECT_TRUE(client != NULL);
EXPECT_EQ(client->msgs_sent(), vnsw_client->Count());
EXPECT_EQ(vnsw_client->Count(), 0);
// Vm Subscribe
vnsw_client->SendVmConfigSubscribe("2d308482-c7b3-4e05-af14-e732b7b50117");
usleep(1000);
TASK_UTIL_EXPECT_TRUE(vm_uuid_mapper_->PendingVmRegCount() > 0);
EXPECT_TRUE(TableLookup("virtual-router", client_name) == NULL);
EXPECT_TRUE(TableLookup("virtual-machine",
"2d308482-c7b3-4e05-af14-e732b7b50117") == NULL);
EXPECT_EQ(vnsw_client->Count(), 0);
vm_uuid_mapper_->PrintAllPendingVmRegEntries();
// Read the ifmap data from file and give it to the parser
string content(FileRead("controller/src/ifmap/testdata/vr_3vm_add.xml"));
assert(content.size() != 0);
parser_->Receive(&db_, content.data(), content.size(), 0);
task_util::WaitForIdle();
usleep(1000);
TASK_UTIL_EXPECT_TRUE(TableLookup("virtual-router", client_name) != NULL);
IFMapNode *vr = TableLookup("virtual-router", client_name);
TASK_UTIL_EXPECT_TRUE(NodeOriginLookup(vr, IFMapOrigin::MAP_SERVER));
TASK_UTIL_EXPECT_TRUE(NodeOriginLookup(vr, IFMapOrigin::XMPP));
EXPECT_EQ(vr->get_object_list_size(), 2);
TASK_UTIL_EXPECT_TRUE(TableLookup("virtual-machine",
"2d308482-c7b3-4e05-af14-e732b7b50117") != NULL);
IFMapNode *vm1 = TableLookup("virtual-machine",
"2d308482-c7b3-4e05-af14-e732b7b50117");
TASK_UTIL_EXPECT_TRUE(NodeOriginLookup(vm1, IFMapOrigin::MAP_SERVER));
TASK_UTIL_EXPECT_TRUE(NodeOriginLookup(vm1, IFMapOrigin::XMPP));
EXPECT_EQ(vm1->get_object_list_size(), 2);
TASK_UTIL_EXPECT_TRUE(vm_uuid_mapper_->UuidMapperCount() == 3);
TASK_UTIL_EXPECT_TRUE(vm_uuid_mapper_->NodeUuidMapCount() == 3);
TASK_UTIL_EXPECT_TRUE(vm_uuid_mapper_->PendingVmRegCount() == 0);
vr->PrintAllObjects();
vm1->PrintAllObjects();
// Wait for the other 2 VMs just to sequence events
TASK_UTIL_EXPECT_TRUE(TableLookup("virtual-machine",
"93e76278-1990-4905-a472-8e9188f41b2c") != NULL);
TASK_UTIL_EXPECT_TRUE(TableLookup("virtual-machine",
"43d086ab-52c4-4a1f-8c3d-63b321e36e8a") != NULL);
TASK_UTIL_EXPECT_TRUE(LinkLookup(vr, vm1) != NULL);
IFMapLink *link = LinkLookup(vr, vm1);
EXPECT_FALSE(LinkOriginLookup(link, IFMapOrigin::MAP_SERVER));
EXPECT_TRUE(LinkOriginLookup(link, IFMapOrigin::XMPP));
TASK_UTIL_EXPECT_EQ(vnsw_client->Count(), 3);
// Vm Unsubscribe
vnsw_client->SendVmConfigUnsubscribe(
"2d308482-c7b3-4e05-af14-e732b7b50117");
usleep(1000);
TASK_UTIL_EXPECT_FALSE(NodeOriginLookup(vr, IFMapOrigin::XMPP));
EXPECT_TRUE(NodeOriginLookup(vr, IFMapOrigin::MAP_SERVER));
EXPECT_EQ(vr->get_object_list_size(), 1);
TASK_UTIL_EXPECT_FALSE(NodeOriginLookup(vm1, IFMapOrigin::XMPP));
EXPECT_TRUE(NodeOriginLookup(vm1, IFMapOrigin::MAP_SERVER));
EXPECT_EQ(vm1->get_object_list_size(), 1);
EXPECT_TRUE(vm_uuid_mapper_->UuidMapperCount() == 3);
EXPECT_TRUE(vm_uuid_mapper_->NodeUuidMapCount() == 3);
EXPECT_TRUE(vm_uuid_mapper_->PendingVmRegCount() == 0);
vr->PrintAllObjects();
vm1->PrintAllObjects();
// should receive vr-vm link delete and vm-delete since the link is gone
TASK_UTIL_EXPECT_EQ(vnsw_client->Count(), 5);
// Vm Subscribe
vnsw_client->SendVmConfigSubscribe("2d308482-c7b3-4e05-af14-e732b7b50117");
usleep(1000);
TASK_UTIL_EXPECT_TRUE(NodeOriginLookup(vr, IFMapOrigin::XMPP));
EXPECT_TRUE(NodeOriginLookup(vr, IFMapOrigin::MAP_SERVER));
EXPECT_EQ(vr->get_object_list_size(), 2);
TASK_UTIL_EXPECT_TRUE(NodeOriginLookup(vm1, IFMapOrigin::XMPP));
EXPECT_TRUE(NodeOriginLookup(vm1, IFMapOrigin::MAP_SERVER));
EXPECT_EQ(vm1->get_object_list_size(), 2);
EXPECT_TRUE(vm_uuid_mapper_->UuidMapperCount() == 3);
EXPECT_TRUE(vm_uuid_mapper_->NodeUuidMapCount() == 3);
EXPECT_TRUE(vm_uuid_mapper_->PendingVmRegCount() == 0);
vr->PrintAllObjects();
vm1->PrintAllObjects();
// should receive vr-vm link add and vm-add since the link was added
TASK_UTIL_EXPECT_EQ(vnsw_client->Count(), 7);
// Delete the vr and all the vms via config
string content1 =
FileRead("controller/src/ifmap/testdata/vr_3vm_delete.xml");
assert(content1.size() != 0);
parser_->Receive(&db_, content1.data(), content1.size(), 0);
task_util::WaitForIdle();
usleep(1000);
// Wait for the other 2 VMs just to sequence events
TASK_UTIL_EXPECT_TRUE(TableLookup("virtual-machine",
"93e76278-1990-4905-a472-8e9188f41b2c") == NULL);
TASK_UTIL_EXPECT_TRUE(TableLookup("virtual-machine",
"43d086ab-52c4-4a1f-8c3d-63b321e36e8a") == NULL);
TASK_UTIL_EXPECT_TRUE(TableLookup("virtual-router", client_name) != NULL);
TASK_UTIL_EXPECT_TRUE(TableLookup("virtual-machine",
"2d308482-c7b3-4e05-af14-e732b7b50117") != NULL);
TASK_UTIL_EXPECT_FALSE(NodeOriginLookup(vr, IFMapOrigin::MAP_SERVER));
TASK_UTIL_EXPECT_TRUE(NodeOriginLookup(vr, IFMapOrigin::XMPP));
EXPECT_EQ(vr->get_object_list_size(), 1);
TASK_UTIL_EXPECT_FALSE(NodeOriginLookup(vm1, IFMapOrigin::MAP_SERVER));
TASK_UTIL_EXPECT_TRUE(NodeOriginLookup(vm1, IFMapOrigin::XMPP));
EXPECT_EQ(vm1->get_object_list_size(), 1);
TASK_UTIL_EXPECT_TRUE(vm_uuid_mapper_->UuidMapperCount() == 1);
TASK_UTIL_EXPECT_TRUE(vm_uuid_mapper_->NodeUuidMapCount() == 1);
TASK_UTIL_EXPECT_TRUE(vm_uuid_mapper_->PendingVmRegCount() == 0);
vr->PrintAllObjects();
vm1->PrintAllObjects();
// although the vr/vm are not 'marked' deleted, client will get updates for
// them since the config-delete will trigger a change for the client.
TASK_UTIL_EXPECT_EQ(vnsw_client->Count(), 9);
vm_uuid_mapper_->PrintAllUuidMapperEntries();
vm_uuid_mapper_->PrintAllNodeUuidMappedEntries();
// Vm Unsubscribe
vnsw_client->SendVmConfigUnsubscribe(
"2d308482-c7b3-4e05-af14-e732b7b50117");
usleep(1000);
TASK_UTIL_EXPECT_TRUE(TableLookup("virtual-router", client_name) == NULL);
TASK_UTIL_EXPECT_TRUE(TableLookup("virtual-machine",
"2d308482-c7b3-4e05-af14-e732b7b50117") == NULL);
TASK_UTIL_EXPECT_EQ(vm_uuid_mapper_->UuidMapperCount(), 0);
TASK_UTIL_EXPECT_EQ(vm_uuid_mapper_->NodeUuidMapCount(), 0);
TASK_UTIL_EXPECT_EQ(vm_uuid_mapper_->PendingVmRegCount(), 0);
// Should get deletes for vr/vm and link(vr,vm)
TASK_UTIL_EXPECT_EQ(vnsw_client->Count(), 12);
vm_uuid_mapper_->PrintAllUuidMapperEntries();
vm_uuid_mapper_->PrintAllNodeUuidMappedEntries();
// New cycle - the nodes do not exist right now
// Read from config first
content1 = string(FileRead("controller/src/ifmap/testdata/vr_3vm_add.xml"));
assert(content1.size() != 0);
parser_->Receive(&db_, content1.data(), content1.size(), 0);
task_util::WaitForIdle();
usleep(1000);
// Wait for the other 2 VMs just to sequence events
TASK_UTIL_EXPECT_TRUE(TableLookup("virtual-machine",
"93e76278-1990-4905-a472-8e9188f41b2c") != NULL);
TASK_UTIL_EXPECT_TRUE(TableLookup("virtual-machine",
"43d086ab-52c4-4a1f-8c3d-63b321e36e8a") != NULL);
TASK_UTIL_EXPECT_TRUE(TableLookup("virtual-router", client_name) != NULL);
vr = TableLookup("virtual-router", client_name);
TASK_UTIL_EXPECT_TRUE(TableLookup("virtual-machine",
"2d308482-c7b3-4e05-af14-e732b7b50117") != NULL);
vm1 = TableLookup("virtual-machine",
"2d308482-c7b3-4e05-af14-e732b7b50117");
TASK_UTIL_EXPECT_TRUE(NodeOriginLookup(vr, IFMapOrigin::MAP_SERVER));
EXPECT_FALSE(NodeOriginLookup(vr, IFMapOrigin::XMPP));
EXPECT_EQ(vr->get_object_list_size(), 1);
TASK_UTIL_EXPECT_TRUE(NodeOriginLookup(vm1, IFMapOrigin::MAP_SERVER));
EXPECT_FALSE(NodeOriginLookup(vm1, IFMapOrigin::XMPP));
EXPECT_EQ(vm1->get_object_list_size(), 1);
TASK_UTIL_EXPECT_TRUE(vm_uuid_mapper_->UuidMapperCount() == 3);
TASK_UTIL_EXPECT_TRUE(vm_uuid_mapper_->NodeUuidMapCount() == 3);
TASK_UTIL_EXPECT_TRUE(vm_uuid_mapper_->PendingVmRegCount() == 0);
vr->PrintAllObjects();
vm1->PrintAllObjects();
// Nothing should get downloaded until we receive the vm-sub
EXPECT_EQ(vnsw_client->Count(), 12);
vm_uuid_mapper_->PrintAllUuidMapperEntries();
vm_uuid_mapper_->PrintAllNodeUuidMappedEntries();
// Add the vm-sub
vnsw_client->SendVmConfigSubscribe("2d308482-c7b3-4e05-af14-e732b7b50117");
usleep(1000);
TASK_UTIL_EXPECT_TRUE(NodeOriginLookup(vr, IFMapOrigin::XMPP));
EXPECT_TRUE(NodeOriginLookup(vr, IFMapOrigin::MAP_SERVER));
EXPECT_EQ(vr->get_object_list_size(), 2);
TASK_UTIL_EXPECT_TRUE(NodeOriginLookup(vm1, IFMapOrigin::XMPP));
EXPECT_TRUE(NodeOriginLookup(vm1, IFMapOrigin::MAP_SERVER));
EXPECT_EQ(vm1->get_object_list_size(), 2);
EXPECT_TRUE(vm_uuid_mapper_->UuidMapperCount() == 3);
EXPECT_TRUE(vm_uuid_mapper_->NodeUuidMapCount() == 3);
EXPECT_TRUE(vm_uuid_mapper_->PendingVmRegCount() == 0);
vr->PrintAllObjects();
vm1->PrintAllObjects();
// Should get adds for vr/vm and link(vr,vm)
TASK_UTIL_EXPECT_EQ(vnsw_client->Count(), 15);
EXPECT_EQ(ifmap_server_.GetClientMapSize(), 1);
// Client close generates a TcpClose event on server
ConfigUpdate(vnsw_client, new XmppConfigData());
TASK_UTIL_EXPECT_EQ(ifmap_server_.GetClientMapSize(), 0);
// Verify ifmap_server client cleanup
EXPECT_EQ(true, IsIFMapClientUnregistered(&ifmap_server_, client_name));
vnsw_client->UnRegisterWithXmpp();
vnsw_client->Shutdown();
task_util::WaitForIdle();
TcpServerManager::DeleteServer(vnsw_client);
vnsw_client = NULL;
// Delete xmpp-channel explicitly
XmppConnection *sconnection = xmpp_server_->FindConnection(client_name);
if (sconnection) {
sconnection->Shutdown();
}
TASK_UTIL_EXPECT_EQ(xmpp_server_->ConnectionCount(), 0);
EXPECT_TRUE(xmpp_server_->FindConnection(client_name) == NULL);
}
// Get a READY and then a NOT_READY
TEST_F(XmppIfmapTest, ReadyNotready) {
// create the mock client
string client_name =
string("default-global-system-config:a1s27.contrail.juniper.net");
string filename("/tmp/" + GetUserName() + "_ready_not_ready.output");
IFMapXmppClientMock *vnsw_client =
new IFMapXmppClientMock(&evm_, xmpp_server_->GetPort(), client_name,
filename);
TASK_UTIL_EXPECT_EQ(true, vnsw_client->IsEstablished());
vnsw_client->RegisterWithXmpp();
// Wait until server is established and until we have an XmppChannel.
usleep(1000);
TASK_UTIL_EXPECT_TRUE(ServerIsEstablished(xmpp_server_, client_name)
== true);
TASK_UTIL_EXPECT_TRUE(GetXmppChannel(xmpp_server_, client_name) != NULL);
// Give a chance to others to run
usleep(1000);
vnsw_client->UnRegisterWithXmpp();
vnsw_client->Shutdown();
task_util::WaitForIdle();
TcpServerManager::DeleteServer(vnsw_client);
vnsw_client = NULL;
// Give a chance to others to run
usleep(1000);
// Delete xmpp-channel explicitly
XmppConnection *sconnection = xmpp_server_->FindConnection(client_name);
if (sconnection) {
sconnection->Shutdown();
}
TASK_UTIL_EXPECT_EQ(xmpp_server_->ConnectionCount(), 0);
EXPECT_TRUE(xmpp_server_->FindConnection(client_name) == NULL);
}
TEST_F(XmppIfmapTest, Bug788) {
SetObjectsPerMessage(1);
// Read the ifmap data from file and give it to the parser
string content(FileRead("controller/src/ifmap/testdata/vr_3vm_add.xml"));
assert(content.size() != 0);
parser_->Receive(&db_, content.data(), content.size(), 0);
task_util::WaitForIdle();
usleep(1000);
// Create the mock client
string client_name =
string("default-global-system-config:a1s27.contrail.juniper.net");
string filename("/tmp/" + GetUserName() + "_bug788.output");
IFMapXmppClientMock *vnsw_client =
new IFMapXmppClientMock(&evm_, xmpp_server_->GetPort(), client_name,
filename);
TASK_UTIL_EXPECT_EQ(true, vnsw_client->IsEstablished());
vnsw_client->RegisterWithXmpp();
usleep(1000);
// Server connection
TASK_UTIL_EXPECT_TRUE(ServerIsEstablished(xmpp_server_, client_name)
== true);
// Verify ifmap_server client is not created until config subscribe
EXPECT_TRUE(ifmap_server_.FindClient(client_name) == NULL);
// No config messages sent until config subscribe
EXPECT_EQ(0, vnsw_client->Count());
// Send vr-subscribe and wait until server processes it
vnsw_client->SendConfigSubscribe();
TASK_UTIL_EXPECT_TRUE(ifmap_server_.FindClient(client_name) != NULL);
usleep(1000);
IFMapClient *client = ifmap_server_.FindClient(client_name);
EXPECT_TRUE(client != NULL);
EXPECT_EQ(client->msgs_sent(), vnsw_client->Count());
EXPECT_EQ(vnsw_client->Count(), 0);
// Send vm-subscribe for this vm. Object-list-size for vm1 should become 2
vnsw_client->SendVmConfigSubscribe("2d308482-c7b3-4e05-af14-e732b7b50117");
usleep(1000);
// vr
TASK_UTIL_EXPECT_TRUE(TableLookup("virtual-router", client_name) != NULL);
IFMapNode *vr = TableLookup("virtual-router", client_name);
TASK_UTIL_EXPECT_EQ(vr->get_object_list_size(), 2);
EXPECT_TRUE(NodeOriginLookup(vr, IFMapOrigin::MAP_SERVER));
EXPECT_TRUE(NodeOriginLookup(vr, IFMapOrigin::XMPP));
// vm1
TASK_UTIL_EXPECT_TRUE(TableLookup("virtual-machine",
"2d308482-c7b3-4e05-af14-e732b7b50117") != NULL);
IFMapNode *vm1 = TableLookup("virtual-machine",
"2d308482-c7b3-4e05-af14-e732b7b50117");
TASK_UTIL_EXPECT_EQ(vm1->get_object_list_size(), 2);
EXPECT_TRUE(NodeOriginLookup(vm1, IFMapOrigin::MAP_SERVER));
EXPECT_TRUE(NodeOriginLookup(vm1, IFMapOrigin::XMPP));
// link(vr, vm1)
TASK_UTIL_EXPECT_TRUE(LinkLookup(vr, vm1) != NULL);
IFMapLink *link = LinkLookup(vr, vm1);
EXPECT_FALSE(LinkOriginLookup(link, IFMapOrigin::MAP_SERVER));
EXPECT_TRUE(LinkOriginLookup(link, IFMapOrigin::XMPP));
// No vm-config for this vm. Object-list-size should be 1 (config)
TASK_UTIL_EXPECT_TRUE(TableLookup("virtual-machine",
"93e76278-1990-4905-a472-8e9188f41b2c") != NULL);
IFMapNode *vm2 = TableLookup("virtual-machine",
"93e76278-1990-4905-a472-8e9188f41b2c");
EXPECT_EQ(vm2->get_object_list_size(), 1);
EXPECT_TRUE(NodeOriginLookup(vm2, IFMapOrigin::MAP_SERVER));
EXPECT_FALSE(NodeOriginLookup(vm2, IFMapOrigin::XMPP));
// No vm-config for this vm. Object-list-size should be 1 (config)
TASK_UTIL_EXPECT_TRUE(TableLookup("virtual-machine",
"43d086ab-52c4-4a1f-8c3d-63b321e36e8a") != NULL);
IFMapNode *vm3 = TableLookup("virtual-machine",
"43d086ab-52c4-4a1f-8c3d-63b321e36e8a");
EXPECT_EQ(vm3->get_object_list_size(), 1);
EXPECT_TRUE(NodeOriginLookup(vm3, IFMapOrigin::MAP_SERVER));
EXPECT_FALSE(NodeOriginLookup(vm3, IFMapOrigin::XMPP));
// We are sending one object/message. We will send vr, vm1 and link(vr,vm1)
usleep(1000);
TASK_UTIL_EXPECT_EQ(vnsw_client->Count(), 3);
// Simulate the condition where we get a link delete. Exporter has finished
// processing it and before the sender sends the update, we process a
// client-delete
EXPECT_EQ(ifmap_server_.GetClientMapSize(), 1);
EXPECT_EQ(ifmap_server_.GetIndexMapSize(), 1);
task_util::TaskSchedulerStop();
TriggerLinkDeleteToExporter(link, vr, vm1);
TASK_UTIL_EXPECT_TRUE(LinkLookup(vr, vm1) == NULL);
TriggerDeleteClient(client, client_name);
task_util::TaskSchedulerStart();
// Allow others to run
usleep(1000);
TASK_UTIL_EXPECT_EQ(ifmap_server_.GetClientMapSize(), 0);
TASK_UTIL_EXPECT_EQ(ifmap_server_.GetIndexMapSize(), 0);
// Client close generates a TcpClose event on server
ConfigUpdate(vnsw_client, new XmppConfigData());
EXPECT_EQ(ifmap_server_.GetClientMapSize(), 0);
// Verify ifmap_server client cleanup
EXPECT_EQ(true, IsIFMapClientUnregistered(&ifmap_server_, client_name));
// Give a chance for the xmpp channel to get deleted
usleep(1000);
vnsw_client->UnRegisterWithXmpp();
vnsw_client->Shutdown();
task_util::WaitForIdle();
TcpServerManager::DeleteServer(vnsw_client);
vnsw_client = NULL;
// Delete xmpp-channel explicitly
XmppConnection *sconnection = xmpp_server_->FindConnection(client_name);
if (sconnection) {
sconnection->Shutdown();
}
TASK_UTIL_EXPECT_EQ(xmpp_server_->ConnectionCount(), 0);
EXPECT_TRUE(xmpp_server_->FindConnection(client_name) == NULL);
}
// 2 consecutive vr subscribe requests with no unsubscribe in between
TEST_F(XmppIfmapTest, SpuriousVrSub) {
// Read the ifmap data from file
string content(FileRead("controller/src/ifmap/testdata/two-vn-connection"));
assert(content.size() != 0);
// Give the read file to the parser
parser_->Receive(&db_, content.data(), content.size(), 0);
task_util::WaitForIdle();
// Create the mock client
string client_name(kDefaultClientName);
string filename("/tmp/" + GetUserName() + "_spurious_vr_sub.output");
IFMapXmppClientMock *vnsw_client =
new IFMapXmppClientMock(&evm_, xmpp_server_->GetPort(), client_name,
filename);
TASK_UTIL_EXPECT_EQ(true, vnsw_client->IsEstablished());
vnsw_client->RegisterWithXmpp();
// Server connection
TASK_UTIL_EXPECT_TRUE(ServerIsEstablished(xmpp_server_, client_name)
== true);
// verify ifmap_server client is not created until config subscribe
TASK_UTIL_EXPECT_TRUE(ifmap_server_.FindClient(client_name) == NULL);
// No config messages sent until config subscribe
TASK_UTIL_EXPECT_EQ(0, vnsw_client->Count());
// Subscribe to config
vnsw_client->SendConfigSubscribe();
TASK_UTIL_EXPECT_TRUE(ifmap_server_.FindClient(client_name) != NULL);
IFMapClient *client1 = ifmap_server_.FindClient(client_name);
size_t index1 = client1->index();
task_util::WaitForIdle();
EXPECT_EQ(ifmap_channel_mgr_->get_dupicate_vrsub_messages(), 0);
// Subscribe to config again to simulate a spurious vr-subscribe
vnsw_client->SendConfigSubscribe();
usleep(1000);
TASK_UTIL_EXPECT_EQ(ifmap_channel_mgr_->get_dupicate_vrsub_messages(), 1);
IFMapClient *client2 = ifmap_server_.FindClient(client_name);
size_t index2 = client2->index();
EXPECT_EQ(index1, index2);
EXPECT_EQ(ifmap_server_.GetClientMapSize(), 1);
// Client close generates a TcpClose event on server
ConfigUpdate(vnsw_client, new XmppConfigData());
TASK_UTIL_EXPECT_EQ(ifmap_server_.GetClientMapSize(), 0);
// Verify ifmap_server client cleanup
EXPECT_EQ(true, IsIFMapClientUnregistered(&ifmap_server_, client_name));
// Give a chance for the xmpp channel to get deleted
usleep(1000);
vnsw_client->UnRegisterWithXmpp();
vnsw_client->Shutdown();
task_util::WaitForIdle();
TcpServerManager::DeleteServer(vnsw_client);
vnsw_client = NULL;
// Delete xmpp-channel explicitly
XmppConnection *sconnection = xmpp_server_->FindConnection(client_name);
if (sconnection) {
sconnection->Shutdown();
}
TASK_UTIL_EXPECT_TRUE(xmpp_server_->FindConnection(client_name) == NULL);
}
TEST_F(XmppIfmapTest, VmSubUnsubWithNoVrSub) {
// Read the ifmap data from file
string content(FileRead("controller/src/ifmap/testdata/two-vn-connection"));
assert(content.size() != 0);
// Give the read file to the parser
parser_->Receive(&db_, content.data(), content.size(), 0);
task_util::WaitForIdle();
// Create the mock client
string client_name(kDefaultClientName);
string filename("/tmp/" + GetUserName() +
"_vm_subunsub_with_novrsub.output");
IFMapXmppClientMock *vnsw_client =
new IFMapXmppClientMock(&evm_, xmpp_server_->GetPort(), client_name,
filename);
TASK_UTIL_EXPECT_EQ(true, vnsw_client->IsEstablished());
vnsw_client->RegisterWithXmpp();
// Server connection
TASK_UTIL_EXPECT_TRUE(ServerIsEstablished(xmpp_server_, client_name)
== true);
// verify ifmap_server client is not created until config subscribe
TASK_UTIL_EXPECT_TRUE(ifmap_server_.FindClient(client_name) == NULL);
// No config messages sent until config subscribe
TASK_UTIL_EXPECT_EQ(0, vnsw_client->Count());
// Subscribe to config
vnsw_client->SendVmConfigSubscribe("aad4c946-9390-4a53-8bbd-09d346f5ba6c");
usleep(1000);
EXPECT_TRUE(ifmap_server_.FindClient(client_name) == NULL);
TASK_UTIL_EXPECT_EQ(ifmap_channel_mgr_->get_vmsub_novrsub_messages(), 1);
// Unsubscribe from config
vnsw_client->SendVmConfigUnsubscribe(
"aad4c946-9390-4a53-8bbd-09d346f5ba6c");
usleep(1000);
EXPECT_TRUE(ifmap_server_.FindClient(client_name) == NULL);
TASK_UTIL_EXPECT_EQ(ifmap_channel_mgr_->get_vmunsub_novrsub_messages(), 1);
EXPECT_EQ(ifmap_server_.GetClientMapSize(), 0);
// Client close generates a TcpClose event on server
ConfigUpdate(vnsw_client, new XmppConfigData());
TASK_UTIL_EXPECT_EQ(ifmap_server_.GetClientMapSize(), 0);
// Give a chance for the xmpp channel to get deleted
usleep(1000);
vnsw_client->UnRegisterWithXmpp();
vnsw_client->Shutdown();
task_util::WaitForIdle();
TcpServerManager::DeleteServer(vnsw_client);
vnsw_client = NULL;
// Delete xmpp-channel explicitly
XmppConnection *sconnection = xmpp_server_->FindConnection(client_name);
if (sconnection) {
sconnection->Shutdown();
}
TASK_UTIL_EXPECT_TRUE(xmpp_server_->FindConnection(client_name) == NULL);
}
// Receive config and then VR-subscribe
TEST_F(XmppIfmapTest, ConfigVrsubVrUnsub) {
// Read the ifmap data from file
string content(FileRead("controller/src/ifmap/testdata/vr_gsc_config.xml"));
assert(content.size() != 0);
// Give the read file to the parser
parser_->Receive(&db_, content.data(), content.size(), 0);
task_util::WaitForIdle();
string client_name("vr1");
string gsc_str("gsc1");
TASK_UTIL_EXPECT_TRUE(TableLookup("virtual-router", client_name) != NULL);
IFMapNode *vr = TableLookup("virtual-router", client_name);
EXPECT_TRUE(vr != NULL);
TASK_UTIL_EXPECT_TRUE(TableLookup("global-system-config", gsc_str) != NULL);
IFMapNode *gsc = TableLookup("global-system-config", gsc_str);
EXPECT_TRUE(gsc != NULL);
IFMapLink *link = LinkLookup(vr, gsc);
TASK_UTIL_EXPECT_TRUE(link != NULL);
// Create the mock client
string filename("/tmp/" + GetUserName() + "_config_vrsub_vrunsub.output");
IFMapXmppClientMock *vnsw_client =
new IFMapXmppClientMock(&evm_, xmpp_server_->GetPort(), client_name,
filename);
TASK_UTIL_EXPECT_EQ(true, vnsw_client->IsEstablished());
vnsw_client->RegisterWithXmpp();
TASK_UTIL_EXPECT_TRUE(ServerIsEstablished(xmpp_server_, client_name)
== true);
// verify ifmap_server client is not created until config subscribe
TASK_UTIL_EXPECT_TRUE(ifmap_server_.FindClient(client_name) == NULL);
// No config messages sent until config subscribe
TASK_UTIL_EXPECT_EQ(0, vnsw_client->Count());
// subscribe to config
vnsw_client->SendConfigSubscribe();
usleep(1000);
TASK_UTIL_EXPECT_TRUE(ifmap_server_.FindClient(client_name) != NULL);
TASK_UTIL_EXPECT_EQ(1, vnsw_client->Count());
// Client close generates a TcpClose event on server
ConfigUpdate(vnsw_client, new XmppConfigData());
TASK_UTIL_EXPECT_EQ(ifmap_server_.GetClientMapSize(), 0);
// Give a chance for the xmpp channel to get deleted
usleep(1000);
vnsw_client->UnRegisterWithXmpp();
vnsw_client->Shutdown();
task_util::WaitForIdle();
TcpServerManager::DeleteServer(vnsw_client);
vnsw_client = NULL;
// Delete xmpp-channel explicitly
XmppConnection *sconnection = xmpp_server_->FindConnection(client_name);
if (sconnection) {
sconnection->Shutdown();
}
TASK_UTIL_EXPECT_TRUE(xmpp_server_->FindConnection(client_name) == NULL);
}
// Receive VR-subscribe and then config
TEST_F(XmppIfmapTest, VrsubConfigVrunsub) {
string client_name("vr1");
string gsc_str("gsc1");
// Create the mock client
string filename("/tmp/" + GetUserName() + "_vrsub_config_vrunsub.output");
IFMapXmppClientMock *vnsw_client =
new IFMapXmppClientMock(&evm_, xmpp_server_->GetPort(), client_name,
filename);
TASK_UTIL_EXPECT_EQ(true, vnsw_client->IsEstablished());
vnsw_client->RegisterWithXmpp();
TASK_UTIL_EXPECT_TRUE(ServerIsEstablished(xmpp_server_, client_name)
== true);
// verify ifmap_server client is not created until config subscribe
TASK_UTIL_EXPECT_TRUE(ifmap_server_.FindClient(client_name) == NULL);
// No config messages sent until config subscribe
TASK_UTIL_EXPECT_EQ(0, vnsw_client->Count());
// subscribe to config
vnsw_client->SendConfigSubscribe();
usleep(1000);
TASK_UTIL_EXPECT_TRUE(ifmap_server_.FindClient(client_name) != NULL);
TASK_UTIL_EXPECT_EQ(0, vnsw_client->Count());
// Read the ifmap data from file
string content(FileRead("controller/src/ifmap/testdata/vr_gsc_config.xml"));
assert(content.size() != 0);
// Give the read file to the parser
parser_->Receive(&db_, content.data(), content.size(), 0);
task_util::WaitForIdle();
TASK_UTIL_EXPECT_TRUE(TableLookup("virtual-router", client_name) != NULL);
IFMapNode *vr = TableLookup("virtual-router", client_name);
EXPECT_TRUE(vr != NULL);
TASK_UTIL_EXPECT_TRUE(TableLookup("global-system-config", gsc_str) != NULL);
IFMapNode *gsc = TableLookup("global-system-config", gsc_str);
EXPECT_TRUE(gsc != NULL);
IFMapLink *link = LinkLookup(vr, gsc);
TASK_UTIL_EXPECT_TRUE(link != NULL);
TASK_UTIL_EXPECT_EQ(1, vnsw_client->Count());
// Client close generates a TcpClose event on server
ConfigUpdate(vnsw_client, new XmppConfigData());
TASK_UTIL_EXPECT_EQ(ifmap_server_.GetClientMapSize(), 0);
// Give a chance for the xmpp channel to get deleted
usleep(1000);
vnsw_client->UnRegisterWithXmpp();
vnsw_client->Shutdown();
task_util::WaitForIdle();
TcpServerManager::DeleteServer(vnsw_client);
vnsw_client = NULL;
// Delete xmpp-channel explicitly
XmppConnection *sconnection = xmpp_server_->FindConnection(client_name);
if (sconnection) {
sconnection->Shutdown();
}
TASK_UTIL_EXPECT_TRUE(xmpp_server_->FindConnection(client_name) == NULL);
}
// Receive config where nodes have no properties and then VR-subscribe
// Then receive config where the nodes have properties
TEST_F(XmppIfmapTest, ConfignopropVrsub) {
// Read the ifmap data from file
string content(FileRead(
"controller/src/ifmap/testdata/vr_gsc_config_no_prop.xml"));
assert(content.size() != 0);
// Give the read file to the parser
parser_->Receive(&db_, content.data(), content.size(), 0);
task_util::WaitForIdle();
string client_name("vr1");
string gsc_str("gsc1");
TASK_UTIL_EXPECT_TRUE(TableLookup("virtual-router", client_name) != NULL);
IFMapNode *vr = TableLookup("virtual-router", client_name);
EXPECT_TRUE(vr != NULL);
TASK_UTIL_EXPECT_TRUE(TableLookup("global-system-config", gsc_str) != NULL);
IFMapNode *gsc = TableLookup("global-system-config", gsc_str);
EXPECT_TRUE(gsc != NULL);
IFMapLink *link = LinkLookup(vr, gsc);
TASK_UTIL_EXPECT_TRUE(link != NULL);
// Create the mock client
string filename("/tmp/" + GetUserName() + "_config_noprop_vrsub.output");
IFMapXmppClientMock *vnsw_client =
new IFMapXmppClientMock(&evm_, xmpp_server_->GetPort(), client_name,
filename);
TASK_UTIL_EXPECT_EQ(true, vnsw_client->IsEstablished());
vnsw_client->RegisterWithXmpp();
TASK_UTIL_EXPECT_TRUE(ServerIsEstablished(xmpp_server_, client_name)
== true);
// verify ifmap_server client is not created until config subscribe
TASK_UTIL_EXPECT_TRUE(ifmap_server_.FindClient(client_name) == NULL);
// No config messages sent until config subscribe
TASK_UTIL_EXPECT_EQ(0, vnsw_client->Count());
// subscribe to config
vnsw_client->SendConfigSubscribe();
usleep(1000);
TASK_UTIL_EXPECT_TRUE(ifmap_server_.FindClient(client_name) != NULL);
TASK_UTIL_EXPECT_EQ(1, vnsw_client->Count());
// Now read the properties and another link update with no real change.
// Client should receive one more message.
content = FileRead("controller/src/ifmap/testdata/vr_gsc_config.xml");
assert(content.size() != 0);
parser_->Receive(&db_, content.data(), content.size(), 0);
usleep(10000);
TASK_UTIL_EXPECT_EQ(2, vnsw_client->Count());
// Client close generates a TcpClose event on server
ConfigUpdate(vnsw_client, new XmppConfigData());
TASK_UTIL_EXPECT_EQ(ifmap_server_.GetClientMapSize(), 0);
// Give a chance for the xmpp channel to get deleted
usleep(1000);
vnsw_client->UnRegisterWithXmpp();
vnsw_client->Shutdown();
task_util::WaitForIdle();
TcpServerManager::DeleteServer(vnsw_client);
vnsw_client = NULL;
// Delete xmpp-channel explicitly
XmppConnection *sconnection = xmpp_server_->FindConnection(client_name);
if (sconnection) {
sconnection->Shutdown();
}
TASK_UTIL_EXPECT_TRUE(xmpp_server_->FindConnection(client_name) == NULL);
}
// Receive VR-subscribe and then config where nodes have no properties
// Then receive config where the nodes have properties
TEST_F(XmppIfmapTest, VrsubConfignoprop) {
string client_name("vr1");
string gsc_str("gsc1");
// Create the mock client
string filename("/tmp/" + GetUserName() + "_vrsub_config_noprop.output");
IFMapXmppClientMock *vnsw_client =
new IFMapXmppClientMock(&evm_, xmpp_server_->GetPort(), client_name,
filename);
TASK_UTIL_EXPECT_EQ(true, vnsw_client->IsEstablished());
vnsw_client->RegisterWithXmpp();
TASK_UTIL_EXPECT_TRUE(ServerIsEstablished(xmpp_server_, client_name)
== true);
// verify ifmap_server client is not created until config subscribe
TASK_UTIL_EXPECT_TRUE(ifmap_server_.FindClient(client_name) == NULL);
// No config messages sent until config subscribe
TASK_UTIL_EXPECT_EQ(0, vnsw_client->Count());
// subscribe to config
vnsw_client->SendConfigSubscribe();
usleep(1000);
TASK_UTIL_EXPECT_TRUE(ifmap_server_.FindClient(client_name) != NULL);
TASK_UTIL_EXPECT_EQ(0, vnsw_client->Count());
// Read the ifmap data from file
string content(FileRead(
"controller/src/ifmap/testdata/vr_gsc_config_no_prop.xml"));
assert(content.size() != 0);
// Give the read file to the parser
parser_->Receive(&db_, content.data(), content.size(), 0);
task_util::WaitForIdle();
TASK_UTIL_EXPECT_TRUE(TableLookup("virtual-router", client_name) != NULL);
IFMapNode *vr = TableLookup("virtual-router", client_name);
EXPECT_TRUE(vr != NULL);
TASK_UTIL_EXPECT_TRUE(TableLookup("global-system-config", gsc_str) != NULL);
IFMapNode *gsc = TableLookup("global-system-config", gsc_str);
EXPECT_TRUE(gsc != NULL);
IFMapLink *link = LinkLookup(vr, gsc);
TASK_UTIL_EXPECT_TRUE(link != NULL);
TASK_UTIL_EXPECT_EQ(1, vnsw_client->Count());
// Now read the properties and another link update with no real change.
// Client should receive one more message.
content = FileRead("controller/src/ifmap/testdata/vr_gsc_config.xml");
assert(content.size() != 0);
parser_->Receive(&db_, content.data(), content.size(), 0);
usleep(10000);
TASK_UTIL_EXPECT_EQ(2, vnsw_client->Count());
// Client close generates a TcpClose event on server
ConfigUpdate(vnsw_client, new XmppConfigData());
TASK_UTIL_EXPECT_EQ(ifmap_server_.GetClientMapSize(), 0);
// Give a chance for the xmpp channel to get deleted
usleep(1000);
vnsw_client->UnRegisterWithXmpp();
vnsw_client->Shutdown();
task_util::WaitForIdle();
TcpServerManager::DeleteServer(vnsw_client);
vnsw_client = NULL;
// Delete xmpp-channel explicitly
XmppConnection *sconnection = xmpp_server_->FindConnection(client_name);
if (sconnection) {
sconnection->Shutdown();
}
TASK_UTIL_EXPECT_TRUE(xmpp_server_->FindConnection(client_name) == NULL);
}
TEST_F(XmppIfmapTest, NodePropertyChanges) {
string client_name("vr1");
// Create the mock client
string filename("/tmp/" + GetUserName() + "_node_prop_changes.output");
IFMapXmppClientMock *vnsw_client =
new IFMapXmppClientMock(&evm_, xmpp_server_->GetPort(), client_name,
filename);
TASK_UTIL_EXPECT_EQ(true, vnsw_client->IsEstablished());
vnsw_client->RegisterWithXmpp();
TASK_UTIL_EXPECT_TRUE(ServerIsEstablished(xmpp_server_, client_name)
== true);
// verify ifmap_server client is not created until config subscribe
TASK_UTIL_EXPECT_TRUE(ifmap_server_.FindClient(client_name) == NULL);
// No config messages sent until config subscribe
TASK_UTIL_EXPECT_EQ(0, vnsw_client->Count());
// Read the ifmap data from file
string content(FileRead(
"controller/src/ifmap/testdata/vr_gsc_config_no_prop.xml"));
assert(content.size() != 0);
// Give the read file to the parser
parser_->Receive(&db_, content.data(), content.size(), 0);
task_util::WaitForIdle();
// subscribe to config
vnsw_client->SendConfigSubscribe();
usleep(1000);
TASK_UTIL_EXPECT_TRUE(ifmap_server_.FindClient(client_name) != NULL);
TASK_UTIL_EXPECT_TRUE(TableLookup("virtual-router", client_name) != NULL);
IFMapNode *vrnode = TableLookup("virtual-router", client_name);
EXPECT_TRUE(vrnode != NULL);
usleep(1000);
TASK_UTIL_EXPECT_EQ(vnsw_client->Count(), 1);
// Add the 'id-perms' property
content = (FileRead("controller/src/ifmap/testdata/vr_with_1prop.xml"));
assert(content.size() != 0);
parser_->Receive(&db_, content.data(), content.size(), 0);
task_util::WaitForIdle();
// Checks. Only 'id-perms' should be set.
vrnode = TableLookup("virtual-router", client_name);
ASSERT_TRUE(vrnode != NULL);
EXPECT_TRUE(vrnode->Find(IFMapOrigin(IFMapOrigin::MAP_SERVER)) != NULL);
IFMapObject *obj = vrnode->Find(IFMapOrigin(IFMapOrigin::MAP_SERVER));
ASSERT_TRUE(obj != NULL);
autogen::VirtualRouter *vr = dynamic_cast<autogen::VirtualRouter *>(obj);
ASSERT_TRUE(vr !=NULL);
EXPECT_TRUE(vr->IsPropertySet(autogen::VirtualRouter::ID_PERMS));
EXPECT_FALSE(vr->IsPropertySet(autogen::VirtualRouter::DISPLAY_NAME));
EXPECT_FALSE(vr->IsPropertySet(autogen::VirtualRouter::IP_ADDRESS));
TASK_UTIL_EXPECT_EQ(vnsw_client->Count(), 2);
// Add 'id-perms' and 'display-name' to the vrnode
content = (FileRead("controller/src/ifmap/testdata/vr_with_2prop.xml"));
assert(content.size() != 0);
parser_->Receive(&db_, content.data(), content.size(), 0);
task_util::WaitForIdle();
// Checks. 'id-perms' and 'display-name' should be set.
vrnode = TableLookup("virtual-router", client_name);
ASSERT_TRUE(vrnode != NULL);
EXPECT_TRUE(vrnode->Find(IFMapOrigin(IFMapOrigin::MAP_SERVER)) != NULL);
obj = vrnode->Find(IFMapOrigin(IFMapOrigin::MAP_SERVER));
ASSERT_TRUE(obj != NULL);
vr = dynamic_cast<autogen::VirtualRouter *>(obj);
ASSERT_TRUE(vr !=NULL);
EXPECT_TRUE(vr->IsPropertySet(autogen::VirtualRouter::ID_PERMS));
EXPECT_TRUE(vr->IsPropertySet(autogen::VirtualRouter::DISPLAY_NAME));
EXPECT_FALSE(vr->IsPropertySet(autogen::VirtualRouter::IP_ADDRESS));
TASK_UTIL_EXPECT_EQ(vnsw_client->Count(), 3);
// Remove 'display-name' from the vrnode
content = (FileRead("controller/src/ifmap/testdata/vr_del_1prop.xml"));
assert(content.size() != 0);
parser_->Receive(&db_, content.data(), content.size(), 0);
task_util::WaitForIdle();
// Checks. Only 'id-perms' should be set.
vrnode = TableLookup("virtual-router", client_name);
ASSERT_TRUE(vrnode != NULL);
EXPECT_TRUE(vrnode->Find(IFMapOrigin(IFMapOrigin::MAP_SERVER)) != NULL);
obj = vrnode->Find(IFMapOrigin(IFMapOrigin::MAP_SERVER));
ASSERT_TRUE(obj != NULL);
vr = dynamic_cast<autogen::VirtualRouter *>(obj);
ASSERT_TRUE(vr !=NULL);
EXPECT_TRUE(vr->IsPropertySet(autogen::VirtualRouter::ID_PERMS));
EXPECT_FALSE(vr->IsPropertySet(autogen::VirtualRouter::DISPLAY_NAME));
EXPECT_FALSE(vr->IsPropertySet(autogen::VirtualRouter::IP_ADDRESS));
TASK_UTIL_EXPECT_EQ(vnsw_client->Count(), 4);
// Add 'id-perms' and 'display-name' to the vrnode
content = (FileRead("controller/src/ifmap/testdata/vr_with_2prop.xml"));
assert(content.size() != 0);
parser_->Receive(&db_, content.data(), content.size(), 0);
task_util::WaitForIdle();
// Checks. 'id-perms' and 'display-name' should be set.
vrnode = TableLookup("virtual-router", client_name);
ASSERT_TRUE(vrnode != NULL);
EXPECT_TRUE(vrnode->Find(IFMapOrigin(IFMapOrigin::MAP_SERVER)) != NULL);
obj = vrnode->Find(IFMapOrigin(IFMapOrigin::MAP_SERVER));
ASSERT_TRUE(obj != NULL);
vr = dynamic_cast<autogen::VirtualRouter *>(obj);
ASSERT_TRUE(vr !=NULL);
EXPECT_TRUE(vr->IsPropertySet(autogen::VirtualRouter::ID_PERMS));
EXPECT_TRUE(vr->IsPropertySet(autogen::VirtualRouter::DISPLAY_NAME));
EXPECT_FALSE(vr->IsPropertySet(autogen::VirtualRouter::IP_ADDRESS));
TASK_UTIL_EXPECT_EQ(vnsw_client->Count(), 5);
// Remove both properties from the vrnode
content = (FileRead("controller/src/ifmap/testdata/vr_del_2prop.xml"));
assert(content.size() != 0);
parser_->Receive(&db_, content.data(), content.size(), 0);
task_util::WaitForIdle();
// Checks. The node should exist since it has a neighbor. But, the object
// should be gone since all the properties are gone.
vrnode = TableLookup("virtual-router", client_name);
ASSERT_TRUE(vrnode != NULL);
TASK_UTIL_ASSERT_TRUE(vrnode->GetObject() == NULL);
TASK_UTIL_EXPECT_EQ(vnsw_client->Count(), 6);
// Client close generates a TcpClose event on server
ConfigUpdate(vnsw_client, new XmppConfigData());
TASK_UTIL_EXPECT_EQ(ifmap_server_.GetClientMapSize(), 0);
// Give a chance for the xmpp channel to get deleted
usleep(1000);
vnsw_client->UnRegisterWithXmpp();
vnsw_client->Shutdown();
task_util::WaitForIdle();
TcpServerManager::DeleteServer(vnsw_client);
vnsw_client = NULL;
// Delete xmpp-channel explicitly
XmppConnection *sconnection = xmpp_server_->FindConnection(client_name);
if (sconnection) {
sconnection->Shutdown();
}
TASK_UTIL_EXPECT_TRUE(xmpp_server_->FindConnection(client_name) == NULL);
}
TEST_F(XmppIfmapTest, DeleteClientPendingVmregCleanup) {
SetObjectsPerMessage(1);
// Read the ifmap data from file and give it to the parser
string content(FileRead("controller/src/ifmap/testdata/vr_3vm_add.xml"));
assert(content.size() != 0);
parser_->Receive(&db_, content.data(), content.size(), 0);
task_util::WaitForIdle();
// create the mock client
string client_name =
string("default-global-system-config:a1s27.contrail.juniper.net");
string filename("/tmp/" + GetUserName() +
"_cfgadd_reg_cfgdel_unreg.output");
IFMapXmppClientMock *vnsw_client =
new IFMapXmppClientMock(&evm_, xmpp_server_->GetPort(), client_name,
filename);
TASK_UTIL_EXPECT_EQ(true, vnsw_client->IsEstablished());
vnsw_client->RegisterWithXmpp();
usleep(1000);
// Server connection
TASK_UTIL_EXPECT_TRUE(ServerIsEstablished(xmpp_server_, client_name)
== true);
// verify ifmap_server client is not created until config subscribe
EXPECT_TRUE(ifmap_server_.FindClient(client_name) == NULL);
// no config messages sent until config subscribe
EXPECT_EQ(0, vnsw_client->Count());
vnsw_client->SendConfigSubscribe();
TASK_UTIL_EXPECT_TRUE(ifmap_server_.FindClient(client_name) != NULL);
// Send a VM subscribe for a VM that does not exist in the config. This
// should create a pending vm-reg entry.
TASK_UTIL_EXPECT_EQ(vm_uuid_mapper_->PendingVmRegCount(), 0);
vnsw_client->SendVmConfigSubscribe("aaaaaaaa-bbbb-cccc-dddd-eeeeeeeeeeee");
TASK_UTIL_EXPECT_EQ(vm_uuid_mapper_->PendingVmRegCount(), 1);
// Cleanup the client. This should clean up the pending vm-reg list too.
ConfigUpdate(vnsw_client, new XmppConfigData());
TASK_UTIL_EXPECT_EQ(ifmap_server_.GetClientMapSize(), 0);
// Verify ifmap_server client cleanup
EXPECT_EQ(true, IsIFMapClientUnregistered(&ifmap_server_, client_name));
vnsw_client->UnRegisterWithXmpp();
vnsw_client->Shutdown();
task_util::WaitForIdle();
TcpServerManager::DeleteServer(vnsw_client);
// Delete xmpp-channel explicitly
XmppConnection *sconnection = xmpp_server_->FindConnection(client_name);
if (sconnection) {
sconnection->Shutdown();
}
TASK_UTIL_EXPECT_EQ(xmpp_server_->ConnectionCount(), 0);
EXPECT_TRUE(xmpp_server_->FindConnection(client_name) == NULL);
// The pending vm-reg should be cleaned up when the client dies
TASK_UTIL_EXPECT_EQ(vm_uuid_mapper_->PendingVmRegCount(), 0);
}
}
static void SetUp() {
LoggingInit();
ControlNode::SetDefaultSchedulingPolicy();
}
static void TearDown() {
task_util::WaitForIdle();
TaskScheduler *scheduler = TaskScheduler::GetInstance();
scheduler->Terminate();
}
int main(int argc, char **argv) {
::testing::InitGoogleTest(&argc, argv);
SetUp();
int result = RUN_ALL_TESTS();
TearDown();
return result;
}
| 41.778165 | 80 | 0.702417 | [
"object"
] |
14b99a300ebcb089518e766ede7a8112e4d321e1 | 2,594 | cc | C++ | src/copy/tasks/compact_gpu.cc | marcinz/legate.pandas | 94c21c436f59c06cfba454c6569e9f5d7109d839 | [
"Apache-2.0"
] | 67 | 2021-04-12T18:06:55.000Z | 2022-03-28T06:51:05.000Z | src/copy/tasks/compact_gpu.cc | marcinz/legate.pandas | 94c21c436f59c06cfba454c6569e9f5d7109d839 | [
"Apache-2.0"
] | 2 | 2021-06-22T00:30:36.000Z | 2021-07-01T22:12:43.000Z | src/copy/tasks/compact_gpu.cc | marcinz/legate.pandas | 94c21c436f59c06cfba454c6569e9f5d7109d839 | [
"Apache-2.0"
] | 6 | 2021-04-14T21:28:00.000Z | 2022-03-22T09:45:25.000Z | /* Copyright 2021 NVIDIA Corporation
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*
*/
#include "copy/tasks/compact.h"
#include "copy/materialize.cuh"
#include "cudf_util/allocators.h"
#include "cudf_util/column.h"
#include "util/gpu_task_context.h"
#include "util/zip_for_each.h"
#include <cudf/table/table.hpp>
#include <cudf/table/table_view.hpp>
#include <cudf/detail/stream_compaction.hpp>
#include <thrust/device_vector.h>
namespace legate {
namespace pandas {
namespace copy {
using namespace Legion;
using CompactArg = CompactTask::CompactTaskArgs::CompactArg;
/*static*/ int64_t CompactTask::gpu_variant(const Task *task,
const std::vector<PhysicalRegion> ®ions,
Context context,
Runtime *runtime)
{
Deserializer ctx{task, regions};
CompactTaskArgs args;
deserialize(ctx, args);
const Rect<1> in_rect = args.pairs[0].second.shape();
GPUTaskContext gpu_ctx{};
auto stream = gpu_ctx.stream();
DeferredBufferAllocator mr;
std::vector<cudf::column_view> input_columns;
std::unique_ptr<cudf::column> materialized{nullptr};
for (auto &pair : args.pairs) {
if (pair.second.valid())
input_columns.push_back(to_cudf_column(pair.second, stream));
else {
materialized =
materialize(in_rect, args.range_start.value(), args.range_step.value(), stream, &mr);
input_columns.push_back(materialized->view());
}
}
cudf::table_view input_table{std::move(input_columns)};
auto mask = to_cudf_column(args.mask, stream);
auto cudf_output = cudf::detail::apply_boolean_mask(input_table, mask, stream, &mr);
auto output_size = static_cast<int64_t>(cudf_output->num_rows());
auto cudf_outputs = cudf_output->release();
util::for_each(args.pairs, cudf_outputs, [&](auto &pair, auto &cudf_output) {
from_cudf_column(pair.first, std::move(cudf_output), stream, mr);
});
return output_size;
}
} // namespace copy
} // namespace pandas
} // namespace legate
| 30.880952 | 93 | 0.692367 | [
"shape",
"vector"
] |
14c9c5ac4ab5330b02bd2c638c4e05fd299802f7 | 106,221 | cc | C++ | tests/wintrospection/test_modlist_i386.cc | MarkMankins/libosi | 2d67ed8066098bc798a53c06dffb5ba257d89bde | [
"BSD-3-Clause"
] | 3 | 2021-02-23T09:13:07.000Z | 2021-08-13T14:15:06.000Z | tests/wintrospection/test_modlist_i386.cc | MarkMankins/libosi | 2d67ed8066098bc798a53c06dffb5ba257d89bde | [
"BSD-3-Clause"
] | 3 | 2021-12-02T17:51:48.000Z | 2022-03-04T20:02:32.000Z | tests/wintrospection/test_modlist_i386.cc | MarkMankins/libosi | 2d67ed8066098bc798a53c06dffb5ba257d89bde | [
"BSD-3-Clause"
] | 2 | 2021-12-07T00:42:31.000Z | 2022-03-04T15:42:12.000Z | #include "iohal/memory/virtual_memory.h"
#include "offset/offset.h"
#include "osi/windows/manager.h"
#include "osi/windows/wintrospection.h"
#include "gtest/gtest.h"
#include <set>
#include <unistd.h>
#include <iostream>
#include <map>
#include <vector>
char* testfile = nullptr;
struct ModuleInfo {
uint64_t base;
uint32_t size;
uint16_t loadcount;
std::string path;
};
std::map<uint64_t, std::vector<struct ModuleInfo>> EXPECTED_RESULTS = {
{4, {}}, // None
{212,
{{0x48290000, 0x13000, 0xffff, "\\SystemRoot\\System32\\smss.exe"},
{0x77ae0000, 0x13c000, 0xffff, "C:\\Windows\\SYSTEM32\\ntdll.dll"}}},
{296,
{{0x49850000, 0x5000, 0xffff, "C:\\Windows\\system32\\csrss.exe"},
{0x77ae0000, 0x13c000, 0xffff, "C:\\Windows\\SYSTEM32\\ntdll.dll"},
{0x75c90000, 0xd000, 0xffff, "C:\\Windows\\system32\\CSRSRV.dll"},
{0x75c80000, 0xe000, 0x4, "C:\\Windows\\system32\\basesrv.DLL"},
{0x75c50000, 0x2c000, 0x2, "C:\\Windows\\system32\\winsrv.DLL"},
{0x77c40000, 0xc9000, 0xb, "C:\\Windows\\system32\\USER32.dll"},
{0x75f50000, 0x4e000, 0xc, "C:\\Windows\\system32\\GDI32.dll"},
{0x76480000, 0xd4000, 0x45, "C:\\Windows\\SYSTEM32\\kernel32.dll"},
{0x75cb0000, 0x4a000, 0xe0, "C:\\Windows\\system32\\KERNELBASE.dll"},
{0x76560000, 0xa000, 0x3, "C:\\Windows\\system32\\LPK.dll"},
{0x77930000, 0x9d000, 0x3, "C:\\Windows\\system32\\USP10.dll"},
{0x779d0000, 0xac000, 0x3, "C:\\Windows\\system32\\msvcrt.dll"},
{0x75c40000, 0x9000, 0x1, "C:\\Windows\\system32\\sxssrv.DLL"},
{0x75b90000, 0x5f000, 0x1, "C:\\Windows\\system32\\sxs.dll"},
{0x762a0000, 0xa1000, 0x1, "C:\\Windows\\system32\\RPCRT4.dll"},
{0x75b80000, 0xc000, 0x1, "C:\\Windows\\system32\\CRYPTBASE.dll"}}},
{344,
{{0x00830000, 0x1a000, 0xffff, "C:\\Windows\\system32\\wininit.exe"},
{0x77ae0000, 0x13c000, 0xffff, "C:\\Windows\\SYSTEM32\\ntdll.dll"},
{0x76480000, 0xd4000, 0xffff, "C:\\Windows\\system32\\kernel32.dll"},
{0x75cb0000, 0x4a000, 0xffff, "C:\\Windows\\system32\\KERNELBASE.dll"},
{0x77c40000, 0xc9000, 0xffff, "C:\\Windows\\system32\\USER32.dll"},
{0x75f50000, 0x4e000, 0xffff, "C:\\Windows\\system32\\GDI32.dll"},
{0x76560000, 0xa000, 0xffff, "C:\\Windows\\system32\\LPK.dll"},
{0x77930000, 0x9d000, 0xffff, "C:\\Windows\\system32\\USP10.dll"},
{0x779d0000, 0xac000, 0xffff, "C:\\Windows\\system32\\msvcrt.dll"},
{0x762a0000, 0xa1000, 0xffff, "C:\\Windows\\system32\\RPCRT4.dll"},
{0x75fa0000, 0x19000, 0xffff, "C:\\Windows\\SYSTEM32\\sechost.dll"},
{0x75c30000, 0xb000, 0xffff, "C:\\Windows\\system32\\profapi.dll"},
{0x75f30000, 0x1f000, 0x2, "C:\\Windows\\system32\\IMM32.DLL"},
{0x77860000, 0xcc000, 0x1, "C:\\Windows\\system32\\MSCTF.dll"},
{0x75bf0000, 0xe000, 0x1, "C:\\Windows\\system32\\RpcRtRemote.dll"},
{0x75b30000, 0x4c000, 0xffff, "C:\\Windows\\system32\\apphelp.dll"},
{0x75b80000, 0xc000, 0x1, "C:\\Windows\\system32\\CRYPTBASE.dll"},
{0x763a0000, 0x35000, 0x6, "C:\\Windows\\system32\\WS2_32.dll"},
{0x77c30000, 0x6000, 0x6, "C:\\Windows\\system32\\NSI.dll"},
{0x756e0000, 0x3c000, 0x3, "C:\\Windows\\system32\\mswsock.dll"},
{0x751c0000, 0x5000, 0x1, "C:\\Windows\\System32\\wshtcpip.dll"},
{0x756d0000, 0x6000, 0x1, "C:\\Windows\\System32\\wship6.dll"},
{0x757d0000, 0x8000, 0x1, "C:\\Windows\\system32\\secur32.dll"},
{0x75b10000, 0x1b000, 0x2, "C:\\Windows\\system32\\SSPICLI.DLL"},
{0x75360000, 0x8000, 0x1, "C:\\Windows\\system32\\credssp.dll"},
{0x77350000, 0xa0000, 0x1, "C:\\Windows\\system32\\ADVAPI32.dll"}}},
{356,
{{0x49850000, 0x5000, 0xffff, "C:\\Windows\\system32\\csrss.exe"},
{0x77ae0000, 0x13c000, 0xffff, "C:\\Windows\\SYSTEM32\\ntdll.dll"},
{0x75c90000, 0xd000, 0xffff, "C:\\Windows\\system32\\CSRSRV.dll"},
{0x75c80000, 0xe000, 0x4, "C:\\Windows\\system32\\basesrv.DLL"},
{0x75c50000, 0x2c000, 0x2, "C:\\Windows\\system32\\winsrv.DLL"},
{0x77c40000, 0xc9000, 0xb, "C:\\Windows\\system32\\USER32.dll"},
{0x75f50000, 0x4e000, 0xc, "C:\\Windows\\system32\\GDI32.dll"},
{0x76480000, 0xd4000, 0x45, "C:\\Windows\\SYSTEM32\\kernel32.dll"},
{0x75cb0000, 0x4a000, 0xe0, "C:\\Windows\\system32\\KERNELBASE.dll"},
{0x76560000, 0xa000, 0x3, "C:\\Windows\\system32\\LPK.dll"},
{0x77930000, 0x9d000, 0x3, "C:\\Windows\\system32\\USP10.dll"},
{0x779d0000, 0xac000, 0x3, "C:\\Windows\\system32\\msvcrt.dll"},
{0x75c40000, 0x9000, 0x1, "C:\\Windows\\system32\\sxssrv.DLL"},
{0x75b90000, 0x5f000, 0x1, "C:\\Windows\\system32\\sxs.dll"},
{0x762a0000, 0xa1000, 0x1, "C:\\Windows\\system32\\RPCRT4.dll"},
{0x75b80000, 0xc000, 0x1, "C:\\Windows\\system32\\CRYPTBASE.dll"}}},
{384,
{{0x003d0000, 0x48000, 0xffff, "C:\\Windows\\system32\\winlogon.exe"},
{0x77ae0000, 0x13c000, 0xffff, "C:\\Windows\\SYSTEM32\\ntdll.dll"},
{0x76480000, 0xd4000, 0xffff, "C:\\Windows\\system32\\kernel32.dll"},
{0x75cb0000, 0x4a000, 0xffff, "C:\\Windows\\system32\\KERNELBASE.dll"},
{0x77c40000, 0xc9000, 0xffff, "C:\\Windows\\system32\\USER32.dll"},
{0x75f50000, 0x4e000, 0xffff, "C:\\Windows\\system32\\GDI32.dll"},
{0x76560000, 0xa000, 0xffff, "C:\\Windows\\system32\\LPK.dll"},
{0x77930000, 0x9d000, 0xffff, "C:\\Windows\\system32\\USP10.dll"},
{0x779d0000, 0xac000, 0xffff, "C:\\Windows\\system32\\msvcrt.dll"},
{0x75c00000, 0x29000, 0xffff, "C:\\Windows\\system32\\WINSTA.dll"},
{0x762a0000, 0xa1000, 0xffff, "C:\\Windows\\system32\\RPCRT4.dll"},
{0x75f30000, 0x1f000, 0x2, "C:\\Windows\\system32\\IMM32.DLL"},
{0x77860000, 0xcc000, 0x1, "C:\\Windows\\system32\\MSCTF.dll"},
{0x77350000, 0xa0000, 0x6, "C:\\Windows\\system32\\ADVAPI32.dll"},
{0x75fa0000, 0x19000, 0x22, "C:\\Windows\\SYSTEM32\\sechost.dll"},
{0x75c30000, 0xb000, 0x1, "C:\\Windows\\system32\\profapi.dll"},
{0x75bf0000, 0xe000, 0x1, "C:\\Windows\\system32\\RpcRtRemote.dll"},
{0x75b30000, 0x4c000, 0xffff, "C:\\Windows\\system32\\apphelp.dll"},
{0x73f30000, 0x8000, 0x1, "C:\\Windows\\system32\\UXINIT.dll"},
{0x74b50000, 0x40000, 0x3, "C:\\Windows\\system32\\UxTheme.dll"},
{0x75720000, 0x16000, 0x1, "C:\\Windows\\system32\\CRYPTSP.dll"},
{0x75470000, 0x3b000, 0x1, "C:\\Windows\\system32\\rsaenh.dll"},
{0x75b80000, 0xc000, 0x1, "C:\\Windows\\system32\\CRYPTBASE.dll"},
{0x746f0000, 0xfb000, 0x1, "C:\\Windows\\system32\\WindowsCodecs.dll"},
{0x77670000, 0x15c000, 0x1, "C:\\Windows\\system32\\ole32.dll"},
{0x745b0000, 0xf000, 0x1, "C:\\Windows\\system32\\wkscli.dll"},
{0x75800000, 0x2b000, 0x1, "C:\\Windows\\system32\\netjoin.dll"},
{0x745c0000, 0x9000, 0x2, "C:\\Windows\\system32\\netutils.dll"},
{0x75b10000, 0x1b000, 0x1, "C:\\Windows\\system32\\SspiCli.dll"},
{0x73f40000, 0xa000, 0x1, "C:\\Windows\\system32\\slc.dll"},
{0x72020000, 0x12000, 0x1, "C:\\Windows\\system32\\MPR.dll"}}},
{428,
{{0x00c40000, 0x41000, 0xffff, "C:\\Windows\\system32\\services.exe"},
{0x77ae0000, 0x13c000, 0xffff, "C:\\Windows\\SYSTEM32\\ntdll.dll"},
{0x76480000, 0xd4000, 0xffff, "C:\\Windows\\system32\\kernel32.dll"},
{0x75cb0000, 0x4a000, 0xffff, "C:\\Windows\\system32\\KERNELBASE.dll"},
{0x779d0000, 0xac000, 0xffff, "C:\\Windows\\system32\\msvcrt.dll"},
{0x762a0000, 0xa1000, 0xffff, "C:\\Windows\\system32\\RPCRT4.dll"},
{0x75b10000, 0x1b000, 0xffff, "C:\\Windows\\system32\\SspiCli.dll"},
{0x75c30000, 0xb000, 0xffff, "C:\\Windows\\system32\\profapi.dll"},
{0x75fa0000, 0x19000, 0xffff, "C:\\Windows\\SYSTEM32\\sechost.dll"},
{0x75b80000, 0xc000, 0xffff, "C:\\Windows\\system32\\CRYPTBASE.dll"},
{0x75840000, 0xf000, 0x1, "C:\\Windows\\system32\\scext.dll"},
{0x77c40000, 0xc9000, 0x18, "C:\\Windows\\system32\\USER32.dll"},
{0x75f50000, 0x4e000, 0x15, "C:\\Windows\\system32\\GDI32.dll"},
{0x76560000, 0xa000, 0x6, "C:\\Windows\\system32\\LPK.dll"},
{0x77930000, 0x9d000, 0x6, "C:\\Windows\\system32\\USP10.dll"},
{0x757d0000, 0x8000, 0x2, "C:\\Windows\\system32\\Secur32.dll"},
{0x75550000, 0x4e000, 0x1, "C:\\Windows\\system32\\SCESRV.dll"},
{0x75450000, 0x19000, 0x1, "C:\\Windows\\system32\\srvcli.dll"},
{0x75f30000, 0x1f000, 0x2, "C:\\Windows\\system32\\IMM32.DLL"},
{0x77860000, 0xcc000, 0x1, "C:\\Windows\\system32\\MSCTF.dll"},
{0x75bf0000, 0xe000, 0x1, "C:\\Windows\\system32\\RpcRtRemote.dll"},
{0x75360000, 0x8000, 0x1, "C:\\Windows\\system32\\credssp.dll"},
{0x758b0000, 0x1b000, 0x1, "C:\\Windows\\system32\\AUTHZ.dll"},
{0x75330000, 0x2c000, 0x1, "C:\\Windows\\system32\\UBPM.dll"},
{0x77350000, 0xa0000, 0x2, "C:\\Windows\\system32\\ADVAPI32.dll"},
{0x75b30000, 0x4c000, 0xffff, "C:\\Windows\\system32\\apphelp.dll"},
{0x746d0000, 0xd000, 0x1, "C:\\Windows\\system32\\WTSAPI32.dll"},
{0x75c00000, 0x29000, 0x1, "C:\\Windows\\system32\\WINSTA.dll"},
{0x763a0000, 0x35000, 0x6, "C:\\Windows\\system32\\WS2_32.dll"},
{0x77c30000, 0x6000, 0x6, "C:\\Windows\\system32\\NSI.dll"},
{0x756e0000, 0x3c000, 0x3, "C:\\Windows\\system32\\mswsock.dll"},
{0x751c0000, 0x5000, 0x1, "C:\\Windows\\System32\\wshtcpip.dll"},
{0x756d0000, 0x6000, 0x1, "C:\\Windows\\System32\\wship6.dll"}}},
{440,
{{0x00900000, 0x9000, 0xffff, "C:\\Windows\\system32\\lsass.exe"},
{0x77ae0000, 0x13c000, 0xffff, "C:\\Windows\\SYSTEM32\\ntdll.dll"},
{0x76480000, 0xd4000, 0xffff, "C:\\Windows\\system32\\kernel32.dll"},
{0x75cb0000, 0x4a000, 0xffff, "C:\\Windows\\system32\\KERNELBASE.dll"},
{0x779d0000, 0xac000, 0xffff, "C:\\Windows\\system32\\msvcrt.dll"},
{0x762a0000, 0xa1000, 0xffff, "C:\\Windows\\system32\\RPCRT4.dll"},
{0x75b00000, 0x7000, 0xffff, "C:\\Windows\\system32\\SspiSrv.dll"},
{0x75a00000, 0x100000, 0x13, "C:\\Windows\\system32\\lsasrv.dll"},
{0x75fa0000, 0x19000, 0x9c, "C:\\Windows\\SYSTEM32\\sechost.dll"},
{0x75b10000, 0x1b000, 0x13, "C:\\Windows\\system32\\SspiCli.dll"},
{0x77350000, 0xa0000, 0x17, "C:\\Windows\\system32\\ADVAPI32.dll"},
{0x77c40000, 0xc9000, 0x3c, "C:\\Windows\\system32\\USER32.dll"},
{0x75f50000, 0x4e000, 0x30, "C:\\Windows\\system32\\GDI32.dll"},
{0x76560000, 0xa000, 0xf, "C:\\Windows\\system32\\LPK.dll"},
{0x77930000, 0x9d000, 0xf, "C:\\Windows\\system32\\USP10.dll"},
{0x75970000, 0x8b000, 0xd, "C:\\Windows\\system32\\SAMSRV.dll"},
{0x75950000, 0x11000, 0x15, "C:\\Windows\\system32\\cryptdll.dll"},
{0x75ca0000, 0xc000, 0x10, "C:\\Windows\\system32\\MSASN1.dll"},
{0x75900000, 0x42000, 0xb, "C:\\Windows\\system32\\wevtapi.dll"},
{0x75f30000, 0x1f000, 0x2, "C:\\Windows\\system32\\IMM32.DLL"},
{0x77860000, 0xcc000, 0x1, "C:\\Windows\\system32\\MSCTF.dll"},
{0x758d0000, 0x6000, 0x1, "C:\\Windows\\system32\\cngaudit.dll"},
{0x758b0000, 0x1b000, 0x1, "C:\\Windows\\system32\\AUTHZ.dll"},
{0x75870000, 0x38000, 0x1, "C:\\Windows\\system32\\ncrypt.dll"},
{0x75850000, 0x17000, 0x10, "C:\\Windows\\system32\\bcrypt.dll"},
{0x75830000, 0x2000, 0x1, "C:\\Windows\\system32\\msprivs.DLL"},
{0x75800000, 0x2b000, 0x1, "C:\\Windows\\system32\\netjoin.dll"},
{0x757e0000, 0x1b000, 0x1, "C:\\Windows\\system32\\negoexts.DLL"},
{0x757d0000, 0x8000, 0x3, "C:\\Windows\\system32\\Secur32.dll"},
{0x75b80000, 0xc000, 0x5, "C:\\Windows\\system32\\cryptbase.dll"},
{0x75740000, 0x88000, 0x2, "C:\\Windows\\system32\\kerberos.DLL"},
{0x75720000, 0x16000, 0x4, "C:\\Windows\\system32\\CRYPTSP.dll"},
{0x763a0000, 0x35000, 0xb, "C:\\Windows\\system32\\WS2_32.dll"},
{0x77c30000, 0x6000, 0x10, "C:\\Windows\\system32\\NSI.dll"},
{0x756e0000, 0x3c000, 0x3, "C:\\Windows\\system32\\mswsock.dll"},
{0x756d0000, 0x6000, 0x1, "C:\\Windows\\System32\\wship6.dll"},
{0x75680000, 0x42000, 0x5, "C:\\Windows\\system32\\msv1_0.DLL"},
{0x755f0000, 0x8c000, 0x2, "C:\\Windows\\system32\\netlogon.DLL"},
{0x755a0000, 0x44000, 0x3, "C:\\Windows\\system32\\DNSAPI.dll"},
{0x75520000, 0x22000, 0x2, "C:\\Windows\\system32\\logoncli.dll"},
{0x754e0000, 0x3a000, 0x1, "C:\\Windows\\system32\\schannel.DLL"},
{0x75d00000, 0x11d000, 0x1, "C:\\Windows\\system32\\CRYPT32.dll"},
{0x754b0000, 0x2c000, 0x1, "C:\\Windows\\system32\\wdigest.DLL"},
{0x75470000, 0x3b000, 0x1, "C:\\Windows\\system32\\rsaenh.dll"},
{0x75430000, 0x12000, 0x1, "C:\\Windows\\system32\\tspkg.DLL"},
{0x753f0000, 0x34000, 0x1, "C:\\Windows\\system32\\pku2u.DLL"},
{0x753b0000, 0x3d000, 0x1, "C:\\Windows\\system32\\bcryptprimitives.dll"},
{0x75bf0000, 0xe000, 0x1, "C:\\Windows\\system32\\RpcRtRemote.dll"},
{0x753a0000, 0xd000, 0x1, "C:\\Windows\\system32\\efslsaext.dll"},
{0x75370000, 0x2e000, 0x1, "C:\\Windows\\system32\\scecli.DLL"},
{0x75360000, 0x8000, 0x1, "C:\\Windows\\system32\\credssp.dll"},
{0x75c00000, 0x29000, 0x1, "C:\\Windows\\system32\\WINSTA.dll"},
{0x751c0000, 0x5000, 0x1, "C:\\Windows\\System32\\wshtcpip.dll"},
{0x72b80000, 0x1c000, 0x1, "C:\\Windows\\system32\\IPHLPAPI.DLL"},
{0x72b70000, 0x7000, 0x1, "C:\\Windows\\system32\\WINNSI.DLL"},
{0x745c0000, 0x9000, 0x1, "C:\\Windows\\system32\\netutils.dll"},
{0x75290000, 0x17000, 0x1, "C:\\Windows\\system32\\USERENV.dll"},
{0x75c30000, 0xb000, 0x1, "C:\\Windows\\system32\\profapi.dll"}}},
{452,
{{0x00da0000, 0x44000, 0xffff, "C:\\Windows\\system32\\lsm.exe"},
{0x77ae0000, 0x13c000, 0xffff, "C:\\Windows\\SYSTEM32\\ntdll.dll"},
{0x76480000, 0xd4000, 0xffff, "C:\\Windows\\system32\\kernel32.dll"},
{0x75cb0000, 0x4a000, 0xffff, "C:\\Windows\\system32\\KERNELBASE.dll"},
{0x779d0000, 0xac000, 0xffff, "C:\\Windows\\system32\\msvcrt.dll"},
{0x75fa0000, 0x19000, 0xffff, "C:\\Windows\\SYSTEM32\\sechost.dll"},
{0x762a0000, 0xa1000, 0xffff, "C:\\Windows\\system32\\RPCRT4.dll"},
{0x758f0000, 0x7000, 0xffff, "C:\\Windows\\system32\\SYSNTFY.dll"},
{0x758e0000, 0x6000, 0xffff, "C:\\Windows\\system32\\WMsgAPI.dll"},
{0x75b80000, 0xc000, 0x1, "C:\\Windows\\system32\\CRYPTBASE.dll"},
{0x75240000, 0xb000, 0x1, "C:\\Windows\\system32\\pcwum.dll"},
{0x75bf0000, 0xe000, 0x1, "C:\\Windows\\system32\\RpcRtRemote.dll"},
{0x757d0000, 0x8000, 0x1, "C:\\Windows\\system32\\secur32.dll"},
{0x75b10000, 0x1b000, 0x2, "C:\\Windows\\system32\\SSPICLI.DLL"},
{0x75360000, 0x8000, 0x1, "C:\\Windows\\system32\\credssp.dll"},
{0x77350000, 0xa0000, 0x1, "C:\\Windows\\system32\\ADVAPI32.dll"}}},
{552,
{{0x00dd0000, 0x8000, 0xffff, "C:\\Windows\\system32\\svchost.exe"},
{0x77ae0000, 0x13c000, 0xffff, "C:\\Windows\\SYSTEM32\\ntdll.dll"},
{0x76480000, 0xd4000, 0xffff, "C:\\Windows\\system32\\kernel32.dll"},
{0x75cb0000, 0x4a000, 0xffff, "C:\\Windows\\system32\\KERNELBASE.dll"},
{0x779d0000, 0xac000, 0xffff, "C:\\Windows\\system32\\msvcrt.dll"},
{0x75fa0000, 0x19000, 0xffff, "C:\\Windows\\SYSTEM32\\sechost.dll"},
{0x762a0000, 0xa1000, 0xffff, "C:\\Windows\\system32\\RPCRT4.dll"},
{0x752e0000, 0x49000, 0x1, "c:\\windows\\system32\\umpnpmgr.dll"},
{0x752c0000, 0x15000, 0x1, "c:\\windows\\system32\\SPINF.dll"},
{0x77c40000, 0xc9000, 0x48, "C:\\Windows\\system32\\USER32.dll"},
{0x75f50000, 0x4e000, 0x41, "C:\\Windows\\system32\\GDI32.dll"},
{0x76560000, 0xa000, 0xe, "C:\\Windows\\system32\\LPK.dll"},
{0x77930000, 0x9d000, 0xe, "C:\\Windows\\system32\\USP10.dll"},
{0x752b0000, 0xe000, 0x1, "c:\\windows\\system32\\DEVRTL.dll"},
{0x75f30000, 0x1f000, 0x2, "C:\\Windows\\system32\\IMM32.DLL"},
{0x77860000, 0xcc000, 0x1, "C:\\Windows\\system32\\MSCTF.dll"},
{0x75bf0000, 0xe000, 0x1, "C:\\Windows\\system32\\RpcRtRemote.dll"},
{0x75290000, 0x17000, 0x2, "C:\\Windows\\system32\\USERENV.dll"},
{0x75c30000, 0xb000, 0x2, "C:\\Windows\\system32\\profapi.dll"},
{0x75270000, 0x16000, 0x4, "C:\\Windows\\system32\\GPAPI.dll"},
{0x75b80000, 0xc000, 0x2, "C:\\Windows\\system32\\CRYPTBASE.dll"},
{0x75250000, 0x20000, 0x1, "c:\\windows\\system32\\umpo.dll"},
{0x75c00000, 0x29000, 0x3, "c:\\windows\\system32\\WINSTA.dll"},
{0x75fc0000, 0x19d000, 0x1, "C:\\Windows\\system32\\SETUPAPI.dll"},
{0x75e70000, 0x27000, 0x19, "C:\\Windows\\system32\\CFGMGR32.dll"},
{0x77350000, 0xa0000, 0x25, "C:\\Windows\\system32\\ADVAPI32.dll"},
{0x777d0000, 0x8f000, 0xd, "C:\\Windows\\system32\\OLEAUT32.dll"},
{0x77670000, 0x15c000, 0x16, "C:\\Windows\\system32\\ole32.dll"},
{0x75e50000, 0x12000, 0x1, "C:\\Windows\\system32\\DEVOBJ.dll"},
{0x75240000, 0xb000, 0x7, "c:\\windows\\system32\\pcwum.DLL"},
{0x751e0000, 0x5f000, 0xffff, "c:\\windows\\system32\\rpcss.dll"},
{0x75b10000, 0x1b000, 0xffff, "c:\\windows\\system32\\SspiCli.dll"},
{0x75360000, 0x8000, 0x1, "C:\\Windows\\system32\\credssp.dll"},
{0x763f0000, 0x83000, 0x2, "C:\\Windows\\system32\\CLBCatQ.DLL"},
{0x75b30000, 0x4c000, 0xffff, "C:\\Windows\\system32\\apphelp.dll"},
{0x72800000, 0x21000, 0x1, "C:\\Windows\\system32\\ntmarta.dll"},
{0x76350000, 0x45000, 0x1, "C:\\Windows\\system32\\WLDAP32.dll"},
{0x721d0000, 0x23000, 0x1, "C:\\Windows\\system32\\wbem\\wmidcprv.dll"},
{0x71790000, 0x96000, 0x2, "C:\\Windows\\system32\\wbem\\FastProx.dll"},
{0x718f0000, 0x5c000, 0x5, "C:\\Windows\\system32\\wbemcomn.dll"},
{0x763a0000, 0x35000, 0x7, "C:\\Windows\\system32\\WS2_32.dll"},
{0x77c30000, 0x6000, 0x4, "C:\\Windows\\system32\\NSI.dll"},
{0x71730000, 0x18000, 0x2, "C:\\Windows\\system32\\NTDSAPI.dll"},
{0x721a0000, 0xa000, 0x1, "C:\\Windows\\system32\\wbem\\wbemprox.dll"},
{0x75720000, 0x16000, 0x1, "C:\\Windows\\system32\\CRYPTSP.dll"},
{0x75470000, 0x3b000, 0x1, "C:\\Windows\\system32\\rsaenh.dll"},
{0x71490000, 0xf000, 0x1, "C:\\Windows\\system32\\wbem\\wbemsvc.dll"},
{0x71450000, 0x17000, 0x1, "C:\\Windows\\system32\\wbem\\wmiutils.dll"},
{0x75e20000, 0x2d000, 0x1, "C:\\Windows\\system32\\WINTRUST.dll"},
{0x75d00000, 0x11d000, 0x1, "C:\\Windows\\system32\\CRYPT32.dll"},
{0x75ca0000, 0xc000, 0x2, "C:\\Windows\\system32\\MSASN1.dll"},
{0x746d0000, 0xd000, 0x1, "C:\\Windows\\system32\\WTSAPI32.dll"}}},
{632,
{{0x00dd0000, 0x8000, 0xffff, "C:\\Windows\\system32\\svchost.exe"},
{0x77ae0000, 0x13c000, 0xffff, "C:\\Windows\\SYSTEM32\\ntdll.dll"},
{0x76480000, 0xd4000, 0xffff, "C:\\Windows\\system32\\kernel32.dll"},
{0x75cb0000, 0x4a000, 0xffff, "C:\\Windows\\system32\\KERNELBASE.dll"},
{0x779d0000, 0xac000, 0xffff, "C:\\Windows\\system32\\msvcrt.dll"},
{0x75fa0000, 0x19000, 0xffff, "C:\\Windows\\SYSTEM32\\sechost.dll"},
{0x762a0000, 0xa1000, 0xffff, "C:\\Windows\\system32\\RPCRT4.dll"},
{0x751d0000, 0xe000, 0x1, "c:\\windows\\system32\\rpcepmap.dll"},
{0x75bf0000, 0xe000, 0x3, "C:\\Windows\\system32\\RpcRtRemote.dll"},
{0x757d0000, 0x8000, 0x1, "C:\\Windows\\system32\\secur32.dll"},
{0x75b10000, 0x1b000, 0xffff, "C:\\Windows\\system32\\SSPICLI.DLL"},
{0x75360000, 0x8000, 0x1, "C:\\Windows\\system32\\credssp.dll"},
{0x75b80000, 0xc000, 0x2, "C:\\Windows\\system32\\CRYPTBASE.dll"},
{0x751e0000, 0x5f000, 0xffff, "c:\\windows\\system32\\rpcss.dll"},
{0x77350000, 0xa0000, 0x5, "C:\\Windows\\system32\\ADVAPI32.dll"},
{0x75720000, 0x16000, 0x1, "C:\\Windows\\system32\\CRYPTSP.dll"},
{0x75470000, 0x3b000, 0x1, "C:\\Windows\\system32\\rsaenh.dll"},
{0x763a0000, 0x35000, 0x7, "C:\\Windows\\system32\\WS2_32.dll"},
{0x77c30000, 0x6000, 0x7, "C:\\Windows\\system32\\NSI.dll"},
{0x756e0000, 0x3c000, 0x3, "C:\\Windows\\system32\\mswsock.dll"},
{0x77c40000, 0xc9000, 0x1e, "C:\\Windows\\system32\\user32.dll"},
{0x75f50000, 0x4e000, 0x1b, "C:\\Windows\\system32\\GDI32.dll"},
{0x76560000, 0xa000, 0x7, "C:\\Windows\\system32\\LPK.dll"},
{0x77930000, 0x9d000, 0x7, "C:\\Windows\\system32\\USP10.dll"},
{0x75f30000, 0x1f000, 0x2, "C:\\Windows\\system32\\IMM32.DLL"},
{0x77860000, 0xcc000, 0x1, "C:\\Windows\\system32\\MSCTF.dll"},
{0x751c0000, 0x5000, 0x1, "C:\\Windows\\System32\\wshtcpip.dll"},
{0x756d0000, 0x6000, 0x1, "C:\\Windows\\System32\\wship6.dll"},
{0x75140000, 0x76000, 0x1, "C:\\Windows\\system32\\FirewallAPI.dll"},
{0x75130000, 0x9000, 0x1, "C:\\Windows\\system32\\VERSION.dll"},
{0x763f0000, 0x83000, 0x1, "C:\\Windows\\system32\\CLBCatQ.DLL"},
{0x77670000, 0x15c000, 0x3, "C:\\Windows\\system32\\ole32.dll"},
{0x777d0000, 0x8f000, 0x1, "C:\\Windows\\system32\\OLEAUT32.dll"},
{0x72a40000, 0x38000, 0x1, "C:\\Windows\\system32\\fwpuclnt.dll"},
{0x746d0000, 0xd000, 0x1, "C:\\Windows\\system32\\WTSAPI32.dll"},
{0x75c00000, 0x29000, 0x1, "C:\\Windows\\system32\\WINSTA.dll"}}},
{676,
{{0x00dd0000, 0x8000, 0xffff, "C:\\Windows\\System32\\svchost.exe"},
{0x77ae0000, 0x13c000, 0xffff, "C:\\Windows\\SYSTEM32\\ntdll.dll"},
{0x76480000, 0xd4000, 0xffff, "C:\\Windows\\system32\\kernel32.dll"},
{0x75cb0000, 0x4a000, 0xffff, "C:\\Windows\\system32\\KERNELBASE.dll"},
{0x779d0000, 0xac000, 0xffff, "C:\\Windows\\system32\\msvcrt.dll"},
{0x75fa0000, 0x19000, 0xffff, "C:\\Windows\\SYSTEM32\\sechost.dll"},
{0x762a0000, 0xa1000, 0xffff, "C:\\Windows\\system32\\RPCRT4.dll"},
{0x77670000, 0x15c000, 0x1a, "C:\\Windows\\system32\\ole32.dll"},
{0x75f50000, 0x4e000, 0x64, "C:\\Windows\\system32\\GDI32.dll"},
{0x77c40000, 0xc9000, 0x6f, "C:\\Windows\\system32\\USER32.dll"},
{0x76560000, 0xa000, 0x16, "C:\\Windows\\system32\\LPK.dll"},
{0x77930000, 0x9d000, 0x16, "C:\\Windows\\system32\\USP10.dll"},
{0x75f30000, 0x1f000, 0x2, "C:\\Windows\\system32\\IMM32.DLL"},
{0x77860000, 0xcc000, 0x1, "C:\\Windows\\system32\\MSCTF.dll"},
{0x75b80000, 0xc000, 0x4, "C:\\Windows\\System32\\CRYPTBASE.dll"},
{0x77350000, 0xa0000, 0x46, "C:\\Windows\\system32\\ADVAPI32.dll"},
{0x74490000, 0x10c000, 0x36, "c:\\windows\\system32\\wevtsvc.dll"},
{0x75bf0000, 0xe000, 0x1, "C:\\Windows\\System32\\RpcRtRemote.dll"},
{0x757d0000, 0x8000, 0x1, "C:\\Windows\\System32\\secur32.dll"},
{0x75b10000, 0x1b000, 0x3, "C:\\Windows\\System32\\SSPICLI.DLL"},
{0x75360000, 0x8000, 0x1, "C:\\Windows\\System32\\credssp.dll"},
{0x763a0000, 0x35000, 0x12, "C:\\Windows\\system32\\WS2_32.dll"},
{0x77c30000, 0x6000, 0x1e, "C:\\Windows\\system32\\NSI.dll"},
{0x756e0000, 0x3c000, 0x3, "C:\\Windows\\system32\\mswsock.dll"},
{0x751c0000, 0x5000, 0x1, "C:\\Windows\\System32\\wshtcpip.dll"},
{0x756d0000, 0x6000, 0x1, "C:\\Windows\\System32\\wship6.dll"},
{0x75270000, 0x16000, 0x4, "C:\\Windows\\System32\\GPAPI.dll"},
{0x742b0000, 0x7a000, 0x1, "c:\\windows\\system32\\audiosrv.dll"},
{0x74330000, 0x25000, 0x1, "c:\\windows\\system32\\POWRPROF.dll"},
{0x75fc0000, 0x19d000, 0x2, "C:\\Windows\\system32\\SETUPAPI.dll"},
{0x75e70000, 0x27000, 0x8, "C:\\Windows\\system32\\CFGMGR32.dll"},
{0x777d0000, 0x8f000, 0xf, "C:\\Windows\\system32\\OLEAUT32.dll"},
{0x75e50000, 0x12000, 0x2, "C:\\Windows\\system32\\DEVOBJ.dll"},
{0x74840000, 0x39000, 0x2, "c:\\windows\\system32\\MMDevAPI.DLL"},
{0x74b90000, 0xf5000, 0x3, "c:\\windows\\system32\\PROPSYS.dll"},
{0x74290000, 0x7000, 0x1, "c:\\windows\\system32\\AVRT.dll"},
{0x763f0000, 0x83000, 0x1, "C:\\Windows\\system32\\CLBCatQ.DLL"},
{0x75c00000, 0x29000, 0x1, "C:\\Windows\\System32\\WINSTA.dll"},
{0x72bb0000, 0x8000, 0x1, "c:\\windows\\system32\\lmhsvc.dll"},
{0x72b80000, 0x1c000, 0x5, "c:\\windows\\system32\\IPHLPAPI.DLL"},
{0x72b70000, 0x7000, 0x7, "c:\\windows\\system32\\WINNSI.DLL"},
{0x72b60000, 0x6000, 0x1, "c:\\windows\\system32\\nrpsrv.DLL"},
{0x72b20000, 0x40000, 0x1, "c:\\windows\\system32\\dhcpcore.dll"},
{0x755a0000, 0x44000, 0x2, "c:\\windows\\system32\\DNSAPI.dll"},
{0x75140000, 0x76000, 0x3, "C:\\Windows\\System32\\firewallapi.dll"},
{0x75130000, 0x9000, 0x3, "C:\\Windows\\System32\\VERSION.dll"},
{0x72ab0000, 0x31000, 0x1, "C:\\Windows\\System32\\dhcpcore6.dll"},
{0x72aa0000, 0xd000, 0x1, "C:\\Windows\\System32\\dhcpcsvc6.DLL"},
{0x72a20000, 0x12000, 0x1, "C:\\Windows\\System32\\dhcpcsvc.DLL"},
{0x700a0000, 0x14000, 0x1, "c:\\windows\\system32\\wscsvc.dll"},
{0x6fd50000, 0xeb000, 0x1, "c:\\windows\\system32\\dbghelp.dll"},
{0x75720000, 0x16000, 0x1, "C:\\Windows\\System32\\CRYPTSP.dll"},
{0x75470000, 0x3b000, 0x1, "C:\\Windows\\system32\\rsaenh.dll"},
{0x721a0000, 0xa000, 0x1, "C:\\Windows\\system32\\wbem\\wbemprox.dll"},
{0x718f0000, 0x5c000, 0x2, "C:\\Windows\\system32\\wbemcomn.dll"},
{0x71490000, 0xf000, 0x1, "C:\\Windows\\system32\\wbem\\wbemsvc.dll"},
{0x71790000, 0x96000, 0x1, "C:\\Windows\\system32\\wbem\\fastprox.dll"},
{0x71730000, 0x18000, 0x1, "C:\\Windows\\system32\\NTDSAPI.dll"},
{0x6f350000, 0x8c000, 0x1, "C:\\Windows\\system32\\wuapi.dll"},
{0x75d00000, 0x11d000, 0x2, "C:\\Windows\\system32\\CRYPT32.dll"},
{0x75ca0000, 0xc000, 0x2, "C:\\Windows\\system32\\MSASN1.dll"},
{0x711f0000, 0x15000, 0x1, "C:\\Windows\\system32\\Cabinet.dll"},
{0x772f0000, 0x57000, 0x1, "C:\\Windows\\system32\\SHLWAPI.dll"},
{0x75e20000, 0x2d000, 0x1, "C:\\Windows\\system32\\WINTRUST.dll"},
{0x75c30000, 0xb000, 0x2, "C:\\Windows\\System32\\profapi.dll"},
{0x75290000, 0x17000, 0x1, "C:\\Windows\\System32\\USERENV.dll"},
{0x745b0000, 0xf000, 0x1, "C:\\Windows\\System32\\wkscli.dll"},
{0x745c0000, 0x9000, 0x1, "C:\\Windows\\System32\\netutils.dll"}}},
{788,
{{0x00dd0000, 0x8000, 0xffff, "C:\\Windows\\System32\\svchost.exe"},
{0x77ae0000, 0x13c000, 0xffff, "C:\\Windows\\SYSTEM32\\ntdll.dll"},
{0x76480000, 0xd4000, 0xffff, "C:\\Windows\\system32\\kernel32.dll"},
{0x75cb0000, 0x4a000, 0xffff, "C:\\Windows\\system32\\KERNELBASE.dll"},
{0x779d0000, 0xac000, 0xffff, "C:\\Windows\\system32\\msvcrt.dll"},
{0x75fa0000, 0x19000, 0xffff, "C:\\Windows\\SYSTEM32\\sechost.dll"},
{0x762a0000, 0xa1000, 0xffff, "C:\\Windows\\system32\\RPCRT4.dll"},
{0x77670000, 0x15c000, 0x2c, "C:\\Windows\\system32\\ole32.dll"},
{0x75f50000, 0x4e000, 0xf4, "C:\\Windows\\system32\\GDI32.dll"},
{0x77c40000, 0xc9000, 0x108, "C:\\Windows\\system32\\USER32.dll"},
{0x76560000, 0xa000, 0x35, "C:\\Windows\\system32\\LPK.dll"},
{0x77930000, 0x9d000, 0x35, "C:\\Windows\\system32\\USP10.dll"},
{0x75f30000, 0x1f000, 0x2, "C:\\Windows\\system32\\IMM32.DLL"},
{0x77860000, 0xcc000, 0x1, "C:\\Windows\\system32\\MSCTF.dll"},
{0x75b80000, 0xc000, 0x2, "C:\\Windows\\System32\\CRYPTBASE.dll"},
{0x77350000, 0xa0000, 0x23, "C:\\Windows\\system32\\ADVAPI32.dll"},
{0x742b0000, 0x7a000, 0x1, "c:\\windows\\system32\\audiosrv.dll"},
{0x74330000, 0x25000, 0x1, "c:\\windows\\system32\\POWRPROF.dll"},
{0x75fc0000, 0x19d000, 0x8, "C:\\Windows\\system32\\SETUPAPI.dll"},
{0x75e70000, 0x27000, 0x16, "C:\\Windows\\system32\\CFGMGR32.dll"},
{0x777d0000, 0x8f000, 0x1a, "C:\\Windows\\system32\\OLEAUT32.dll"},
{0x75e50000, 0x12000, 0x8, "C:\\Windows\\system32\\DEVOBJ.dll"},
{0x74840000, 0x39000, 0x2, "c:\\windows\\system32\\MMDevAPI.DLL"},
{0x74b90000, 0xf5000, 0x3, "c:\\windows\\system32\\PROPSYS.dll"},
{0x74290000, 0x7000, 0x1, "c:\\windows\\system32\\AVRT.dll"},
{0x763f0000, 0x83000, 0x1, "C:\\Windows\\system32\\CLBCatQ.DLL"},
{0x741a0000, 0x88000, 0x1, "c:\\windows\\system32\\cscsvc.dll"},
{0x75290000, 0x17000, 0x7, "c:\\windows\\system32\\USERENV.dll"},
{0x75c30000, 0xb000, 0x8, "c:\\windows\\system32\\profapi.dll"},
{0x75240000, 0xb000, 0x1, "C:\\Windows\\System32\\pcwum.dll"},
{0x740d0000, 0x25000, 0x1, "C:\\Windows\\System32\\PeerDist.dll"},
{0x758b0000, 0x1b000, 0x1, "C:\\Windows\\System32\\AUTHZ.dll"},
{0x73ff0000, 0x7d000, 0x1, "C:\\Windows\\system32\\taskschd.dll"},
{0x75b10000, 0x1b000, 0x5, "C:\\Windows\\System32\\SspiCli.dll"},
{0x73fa0000, 0x35000, 0x1, "C:\\Windows\\System32\\mstask.dll"},
{0x74cd0000, 0x19e000, 0x1,
"C:\\Windows\\WinSxS\\x86_microsoft.windows.common-"
"controls_6595b64144ccf1df_6.0.7601.17514_none_"
"41e6975e2bd6f2b2\\COMCTL32.dll"},
{0x772f0000, 0x57000, 0x9, "C:\\Windows\\system32\\SHLWAPI.dll"},
{0x75720000, 0x16000, 0x1, "C:\\Windows\\System32\\CRYPTSP.dll"},
{0x75470000, 0x3b000, 0x1, "C:\\Windows\\system32\\rsaenh.dll"},
{0x75bf0000, 0xe000, 0x1, "C:\\Windows\\System32\\RpcRtRemote.dll"},
{0x746d0000, 0xd000, 0x5, "C:\\Windows\\System32\\WTSAPI32.dll"},
{0x75c00000, 0x29000, 0x1, "C:\\Windows\\System32\\WINSTA.dll"},
{0x75270000, 0x16000, 0x5, "C:\\Windows\\System32\\GPAPI.dll"},
{0x72bc0000, 0xb000, 0x2, "c:\\windows\\system32\\uxsms.dll"},
{0x75b30000, 0x4c000, 0xffff, "C:\\Windows\\system32\\apphelp.dll"},
{0x71950000, 0x11e000, 0x1, "c:\\windows\\system32\\sysmain.dll"},
{0x766a0000, 0xc4a000, 0x4, "C:\\Windows\\system32\\SHELL32.dll"},
{0x72800000, 0x21000, 0x1, "C:\\Windows\\System32\\ntmarta.dll"},
{0x76350000, 0x45000, 0x1, "C:\\Windows\\system32\\WLDAP32.dll"},
{0x72230000, 0x15000, 0x1, "c:\\windows\\system32\\trkwks.dll"},
{0x71210000, 0x15000, 0x2, "c:\\windows\\system32\\wdi.dll"},
{0x70d80000, 0xa000, 0x1, "C:\\Windows\\SYSTEM32\\APPHLPDM.DLL"},
{0x70dc0000, 0x61000, 0x1, "C:\\Windows\\System32\\wer.dll"},
{0x70ca0000, 0x89000, 0x1, "C:\\Windows\\system32\\PortableDeviceApi.dll"},
{0x70c70000, 0x12000, 0x1, "C:\\Windows\\System32\\portabledeviceconnectapi.dll"},
{0x75e20000, 0x2d000, 0x1, "C:\\Windows\\system32\\WINTRUST.dll"},
{0x75d00000, 0x11d000, 0x1, "C:\\Windows\\system32\\CRYPT32.dll"},
{0x75ca0000, 0xc000, 0x2, "C:\\Windows\\system32\\MSASN1.dll"},
{0x73980000, 0x25000, 0x1, "C:\\Windows\\system32\\cscobj.dll"},
{0x73d40000, 0x47000, 0x1, "c:\\windows\\system32\\netman.dll"},
{0x77c30000, 0x6000, 0xe, "C:\\Windows\\system32\\NSI.dll"},
{0x72b70000, 0x7000, 0x5, "c:\\windows\\system32\\WINNSI.DLL"},
{0x739b0000, 0x265000, 0x1, "C:\\Windows\\System32\\netshell.dll"},
{0x72b80000, 0x1c000, 0x3, "C:\\Windows\\System32\\IPHLPAPI.DLL"},
{0x742a0000, 0x10000, 0x1, "C:\\Windows\\System32\\nlaapi.dll"},
{0x70260000, 0xc1000, 0x1, "C:\\Windows\\System32\\RASDLG.dll"},
{0x72bd0000, 0x29000, 0x1, "C:\\Windows\\System32\\MPRAPI.dll"},
{0x70200000, 0x52000, 0x2, "C:\\Windows\\System32\\RASAPI32.dll"},
{0x701e0000, 0x15000, 0x3, "C:\\Windows\\System32\\rasman.dll"},
{0x763a0000, 0x35000, 0x6, "C:\\Windows\\system32\\WS2_32.dll"},
{0x74360000, 0xd000, 0x1, "C:\\Windows\\System32\\rtutils.dll"},
{0x73fe0000, 0x9000, 0x2, "C:\\Windows\\System32\\dsrole.dll"},
{0x71670000, 0x67000, 0x1, "C:\\Windows\\system32\\netcfgx.dll"},
{0x73f40000, 0xa000, 0x2, "C:\\Windows\\system32\\slc.dll"},
{0x752b0000, 0xe000, 0x2, "C:\\Windows\\System32\\devrtl.DLL"},
{0x757d0000, 0x8000, 0x1, "C:\\Windows\\System32\\secur32.dll"},
{0x75360000, 0x8000, 0x1, "C:\\Windows\\System32\\credssp.dll"},
{0x714a0000, 0x4a000, 0x1, "C:\\Windows\\system32\\hnetcfg.dll"},
{0x74080000, 0x14000, 0x1, "C:\\Windows\\system32\\ATL.DLL"},
{0x721a0000, 0xa000, 0x1, "C:\\Windows\\system32\\wbem\\wbemprox.dll"},
{0x718f0000, 0x5c000, 0x2, "C:\\Windows\\system32\\wbemcomn.dll"},
{0x71490000, 0xf000, 0x1, "C:\\Windows\\system32\\wbem\\wbemsvc.dll"},
{0x71790000, 0x96000, 0x1, "C:\\Windows\\system32\\wbem\\fastprox.dll"},
{0x71730000, 0x18000, 0x1, "C:\\Windows\\system32\\NTDSAPI.dll"}}},
{832,
{{0x00dd0000, 0x8000, 0xffff, "C:\\Windows\\system32\\svchost.exe"},
{0x77ae0000, 0x13c000, 0xffff, "C:\\Windows\\SYSTEM32\\ntdll.dll"},
{0x76480000, 0xd4000, 0xffff, "C:\\Windows\\system32\\kernel32.dll"},
{0x75cb0000, 0x4a000, 0xffff, "C:\\Windows\\system32\\KERNELBASE.dll"},
{0x779d0000, 0xac000, 0xffff, "C:\\Windows\\system32\\msvcrt.dll"},
{0x75fa0000, 0x19000, 0xffff, "C:\\Windows\\SYSTEM32\\sechost.dll"},
{0x762a0000, 0xa1000, 0xffff, "C:\\Windows\\system32\\RPCRT4.dll"},
{0x77670000, 0x15c000, 0x66, "C:\\Windows\\system32\\ole32.dll"},
{0x75f50000, 0x4e000, 0x1b0, "C:\\Windows\\system32\\GDI32.dll"},
{0x77c40000, 0xc9000, 0x1dd, "C:\\Windows\\system32\\USER32.dll"},
{0x76560000, 0xa000, 0x5f, "C:\\Windows\\system32\\LPK.dll"},
{0x77930000, 0x9d000, 0x5f, "C:\\Windows\\system32\\USP10.dll"},
{0x75f30000, 0x1f000, 0x2, "C:\\Windows\\system32\\IMM32.DLL"},
{0x77860000, 0xcc000, 0x1, "C:\\Windows\\system32\\MSCTF.dll"},
{0x75b80000, 0xc000, 0x2, "C:\\Windows\\system32\\CRYPTBASE.dll"},
{0x77350000, 0xa0000, 0x4c, "C:\\Windows\\system32\\ADVAPI32.dll"},
{0x74270000, 0x12000, 0x1, "c:\\windows\\system32\\mmcss.dll"},
{0x74290000, 0x7000, 0x1, "c:\\windows\\system32\\AVRT.dll"},
{0x74100000, 0x93000, 0x8, "c:\\windows\\system32\\gpsvc.dll"},
{0x75270000, 0x16000, 0xd, "c:\\windows\\system32\\GPAPI.dll"},
{0x76350000, 0x45000, 0x9, "C:\\Windows\\system32\\WLDAP32.dll"},
{0x757d0000, 0x8000, 0x9, "c:\\windows\\system32\\Secur32.dll"},
{0x75b10000, 0x1b000, 0x11, "c:\\windows\\system32\\SSPICLI.DLL"},
{0x77c30000, 0x6000, 0x44, "C:\\Windows\\system32\\NSI.dll"},
{0x758f0000, 0x7000, 0xa, "c:\\windows\\system32\\SYSNTFY.dll"},
{0x742a0000, 0x10000, 0x9, "c:\\windows\\system32\\nlaapi.dll"},
{0x740a0000, 0x2b000, 0x1, "c:\\windows\\system32\\profsvc.dll"},
{0x777d0000, 0x8f000, 0x3b, "C:\\Windows\\system32\\OLEAUT32.dll"},
{0x75290000, 0x17000, 0x6, "c:\\windows\\system32\\USERENV.dll"},
{0x75c30000, 0xb000, 0x9, "c:\\windows\\system32\\profapi.dll"},
{0x772f0000, 0x57000, 0xc, "C:\\Windows\\system32\\SHLWAPI.dll"},
{0x74080000, 0x14000, 0x5, "c:\\windows\\system32\\ATL.DLL"},
{0x74070000, 0xc000, 0x1, "c:\\windows\\system32\\themeservice.dll"},
{0x75c00000, 0x29000, 0x3, "C:\\Windows\\system32\\WINSTA.dll"},
{0x75bf0000, 0xe000, 0x1, "C:\\Windows\\system32\\RpcRtRemote.dll"},
{0x763f0000, 0x83000, 0x1, "C:\\Windows\\system32\\CLBCatQ.DLL"},
{0x75720000, 0x16000, 0x5, "C:\\Windows\\system32\\CRYPTSP.dll"},
{0x75470000, 0x3b000, 0x1, "C:\\Windows\\system32\\rsaenh.dll"},
{0x73fe0000, 0x9000, 0x2, "C:\\Windows\\system32\\dsrole.dll"},
{0x73f40000, 0xa000, 0x6, "C:\\Windows\\system32\\slc.dll"},
{0x74b50000, 0x40000, 0x1, "C:\\Windows\\system32\\UxTheme.dll"},
{0x72a80000, 0xf000, 0x1, "c:\\windows\\system32\\sens.dll"},
{0x763a0000, 0x35000, 0x24, "C:\\Windows\\system32\\WS2_32.dll"},
{0x74c90000, 0x12000, 0x2, "C:\\Windows\\system32\\SAMLIB.dll"},
{0x729c0000, 0x52000, 0x1, "c:\\windows\\system32\\shsvcs.dll"},
{0x75e70000, 0x27000, 0x23, "C:\\Windows\\system32\\CFGMGR32.dll"},
{0x75fc0000, 0x19d000, 0x6, "C:\\Windows\\system32\\SETUPAPI.dll"},
{0x75e50000, 0x12000, 0x6, "C:\\Windows\\system32\\DEVOBJ.dll"},
{0x75e20000, 0x2d000, 0x2, "C:\\Windows\\system32\\WINTRUST.dll"},
{0x75d00000, 0x11d000, 0x5, "C:\\Windows\\system32\\CRYPT32.dll"},
{0x75ca0000, 0xc000, 0x6, "C:\\Windows\\system32\\MSASN1.dll"},
{0x72900000, 0xba000, 0x1, "c:\\windows\\system32\\schedsvc.dll"},
{0x75240000, 0xb000, 0x2, "c:\\windows\\system32\\pcwum.dll"},
{0x766a0000, 0xc4a000, 0x5, "C:\\Windows\\system32\\SHELL32.dll"},
{0x745d0000, 0x11000, 0x3, "c:\\windows\\system32\\NETAPI32.dll"},
{0x745c0000, 0x9000, 0xa, "c:\\windows\\system32\\netutils.dll"},
{0x75450000, 0x19000, 0x3, "c:\\windows\\system32\\srvcli.dll"},
{0x745b0000, 0xf000, 0x5, "c:\\windows\\system32\\wkscli.dll"},
{0x75900000, 0x42000, 0xe, "c:\\windows\\system32\\wevtapi.dll"},
{0x758b0000, 0x1b000, 0x3, "c:\\windows\\system32\\AUTHZ.dll"},
{0x75330000, 0x2c000, 0x1, "c:\\windows\\system32\\UBPM.dll"},
{0x728f0000, 0x9000, 0x2, "c:\\windows\\system32\\ktmw32.dll"},
{0x747f0000, 0x2f000, 0x1, "c:\\windows\\system32\\XmlLite.dll"},
{0x75360000, 0x8000, 0x1, "C:\\Windows\\system32\\credssp.dll"},
{0x728a0000, 0x43000, 0x2, "C:\\Windows\\system32\\FVEAPI.dll"},
{0x72890000, 0x7000, 0x2, "C:\\Windows\\system32\\tbs.dll"},
{0x72880000, 0x8000, 0x2, "C:\\Windows\\system32\\FVECERTS.dll"},
{0x75520000, 0x22000, 0x2, "C:\\Windows\\system32\\LOGONCLI.DLL"},
{0x72830000, 0x4d000, 0x1, "C:\\Windows\\system32\\taskcomp.dll"},
{0x75130000, 0x9000, 0x6, "C:\\Windows\\system32\\VERSION.dll"},
{0x72800000, 0x21000, 0x1, "C:\\Windows\\system32\\ntmarta.dll"},
{0x756e0000, 0x3c000, 0x5, "C:\\Windows\\system32\\mswsock.dll"},
{0x727f0000, 0xb000, 0x1, "C:\\Windows\\system32\\wiarpc.dll"},
{0x751c0000, 0x5000, 0x1, "C:\\Windows\\System32\\wshtcpip.dll"},
{0x756d0000, 0x6000, 0x1, "C:\\Windows\\System32\\wship6.dll"},
{0x75800000, 0x2b000, 0x1, "C:\\Windows\\system32\\netjoin.dll"},
{0x746d0000, 0xd000, 0x5, "C:\\Windows\\system32\\WTSAPI32.dll"},
{0x74cd0000, 0x19e000, 0x2,
"C:\\Windows\\WinSxS\\x86_microsoft.windows.common-"
"controls_6595b64144ccf1df_6.0.7601.17514_none_"
"41e6975e2bd6f2b2\\comctl32.dll"},
{0x74b90000, 0xf5000, 0x4, "C:\\Windows\\system32\\PROPSYS.dll"},
{0x73f50000, 0x47000, 0x2, "C:\\Windows\\system32\\ES.DLL"},
{0x75b90000, 0x5f000, 0x1, "C:\\Windows\\system32\\SXS.DLL"},
{0x72200000, 0x2b000, 0x1, "c:\\windows\\system32\\wbem\\wmisvc.dll"},
{0x718f0000, 0x5c000, 0x10, "C:\\Windows\\system32\\wbemcomn.dll"},
{0x71870000, 0x7d000, 0x1, "c:\\windows\\system32\\iphlpsvc.dll"},
{0x72b70000, 0x7000, 0xe, "c:\\windows\\system32\\WINNSI.DLL"},
{0x75140000, 0x76000, 0x4, "c:\\windows\\system32\\FirewallAPI.dll"},
{0x72b80000, 0x1c000, 0xc, "c:\\windows\\system32\\IPHLPAPI.DLL"},
{0x72a40000, 0x38000, 0x2, "c:\\windows\\system32\\fwpuclnt.dll"},
{0x74360000, 0xd000, 0x1, "c:\\windows\\system32\\rtutils.dll"},
{0x71830000, 0x33000, 0x1, "c:\\windows\\system32\\sqmapi.dll"},
{0x71750000, 0x32000, 0x1, "c:\\windows\\system32\\WDSCORE.dll"},
{0x71700000, 0x2c000, 0x1, "c:\\windows\\system32\\srvsvc.dll"},
{0x716e0000, 0x1b000, 0x1, "c:\\windows\\system32\\browser.dll"},
{0x72520000, 0x116000, 0x2, "C:\\Windows\\system32\\VSSAPI.DLL"},
{0x72510000, 0x10000, 0x3, "C:\\Windows\\system32\\VssTrace.DLL"},
{0x745a0000, 0xf000, 0x1, "C:\\Windows\\system32\\samcli.dll"},
{0x71670000, 0x67000, 0x1, "C:\\Windows\\system32\\netcfgx.dll"},
{0x752b0000, 0xe000, 0x6, "C:\\Windows\\system32\\devrtl.DLL"},
{0x721c0000, 0x6000, 0x1, "C:\\Windows\\system32\\SSCORE.DLL"},
{0x715a0000, 0xc2000, 0x1, "C:\\Windows\\system32\\wbem\\wbemcore.dll"},
{0x71550000, 0x44000, 0x3, "C:\\Windows\\system32\\wbem\\esscli.dll"},
{0x71790000, 0x96000, 0x7, "C:\\Windows\\system32\\wbem\\FastProx.dll"},
{0x71730000, 0x18000, 0x5, "C:\\Windows\\system32\\NTDSAPI.dll"},
{0x71510000, 0x3b000, 0x2, "C:\\Windows\\system32\\CLUSAPI.DLL"},
{0x75950000, 0x11000, 0x2, "C:\\Windows\\system32\\cryptdll.dll"},
{0x714f0000, 0x14000, 0x1, "C:\\Windows\\system32\\RESUTILS.DLL"},
{0x714a0000, 0x4a000, 0x1, "C:\\Windows\\system32\\hnetcfg.dll"},
{0x721a0000, 0xa000, 0x1, "C:\\Windows\\system32\\wbem\\wbemprox.dll"},
{0x71490000, 0xf000, 0x1, "C:\\Windows\\system32\\wbem\\wbemsvc.dll"},
{0x71450000, 0x17000, 0x1, "C:\\Windows\\system32\\wbem\\wmiutils.dll"},
{0x71430000, 0x16000, 0x1, "C:\\Windows\\system32\\NCI.dll"},
{0x71300000, 0x5a000, 0x1, "C:\\Windows\\System32\\netprofm.dll"},
{0x712b0000, 0x4c000, 0x1, "C:\\Windows\\system32\\wbem\\repdrvfs.dll"},
{0x72aa0000, 0xd000, 0x1, "C:\\Windows\\system32\\dhcpcsvc6.DLL"},
{0x72a20000, 0x12000, 0x1, "C:\\Windows\\system32\\dhcpcsvc.DLL"},
{0x755a0000, 0x44000, 0x1, "C:\\Windows\\system32\\DNSAPI.dll"},
{0x71480000, 0x6000, 0x1, "C:\\Windows\\system32\\rasadhlp.dll"},
{0x71230000, 0xf000, 0x1, "c:\\windows\\system32\\appinfo.dll"},
{0x71140000, 0x81000, 0x1, "C:\\Windows\\system32\\wbem\\wmiprvsd.dll"},
{0x71130000, 0xf000, 0x2, "C:\\Windows\\system32\\NCObjAPI.DLL"},
{0x711d0000, 0x8000, 0x1, "C:\\Windows\\System32\\npmproxy.dll"},
{0x70e80000, 0x56000, 0x1, "C:\\Windows\\system32\\wbem\\wbemess.dll"},
{0x75b30000, 0x4c000, 0xffff, "C:\\Windows\\system32\\apphelp.dll"},
{0x70ae0000, 0x12000, 0x1, "c:\\windows\\system32\\aelupsvc.dll"},
{0x6fe60000, 0x4e000, 0x1, "C:\\Windows\\system32\\actxprxy.dll"},
{0x701d0000, 0x10000, 0x1, "C:\\Windows\\system32\\wbem\\ncprov.dll"},
{0x6f960000, 0x92000, 0x1, "c:\\windows\\system32\\qmgr.dll"},
{0x73d20000, 0x8000, 0x1, "c:\\windows\\system32\\bitsperf.dll"},
{0x70370000, 0xd000, 0x1, "C:\\Windows\\system32\\bitsigd.dll"},
{0x70330000, 0x36000, 0x1, "C:\\Windows\\system32\\upnp.dll"},
{0x72290000, 0x58000, 0x3, "C:\\Windows\\system32\\WINHTTP.dll"},
{0x72490000, 0x4f000, 0x3, "C:\\Windows\\system32\\webio.dll"},
{0x72250000, 0xd000, 0x1, "C:\\Windows\\system32\\SSDPAPI.dll"},
{0x6f0c0000, 0x1d6000, 0x1, "c:\\windows\\system32\\wuaueng.dll"},
{0x70380000, 0x1a3000, 0x1, "c:\\windows\\system32\\ESENT.dll"},
{0x71250000, 0x51000, 0x1, "c:\\windows\\system32\\WINSPOOL.DRV"},
{0x711f0000, 0x15000, 0x1, "c:\\windows\\system32\\Cabinet.dll"},
{0x70100000, 0xc000, 0x1, "c:\\windows\\system32\\mspatcha.dll"},
{0x77c20000, 0x5000, 0x1, "C:\\Windows\\system32\\psapi.dll"},
{0x758e0000, 0x6000, 0x1, "C:\\Windows\\system32\\WMsgAPI.dll"}}},
{920,
{{0x00dd0000, 0x8000, 0xffff, "C:\\Windows\\system32\\svchost.exe"},
{0x77ae0000, 0x13c000, 0xffff, "C:\\Windows\\SYSTEM32\\ntdll.dll"},
{0x76480000, 0xd4000, 0xffff, "C:\\Windows\\system32\\kernel32.dll"},
{0x75cb0000, 0x4a000, 0xffff, "C:\\Windows\\system32\\KERNELBASE.dll"},
{0x779d0000, 0xac000, 0xffff, "C:\\Windows\\system32\\msvcrt.dll"},
{0x75fa0000, 0x19000, 0xffff, "C:\\Windows\\SYSTEM32\\sechost.dll"},
{0x762a0000, 0xa1000, 0xffff, "C:\\Windows\\system32\\RPCRT4.dll"},
{0x77670000, 0x15c000, 0xf, "C:\\Windows\\system32\\ole32.dll"},
{0x75f50000, 0x4e000, 0x57, "C:\\Windows\\system32\\GDI32.dll"},
{0x77c40000, 0xc9000, 0x61, "C:\\Windows\\system32\\USER32.dll"},
{0x76560000, 0xa000, 0x15, "C:\\Windows\\system32\\LPK.dll"},
{0x77930000, 0x9d000, 0x15, "C:\\Windows\\system32\\USP10.dll"},
{0x75f30000, 0x1f000, 0x2, "C:\\Windows\\system32\\IMM32.DLL"},
{0x77860000, 0xcc000, 0x1, "C:\\Windows\\system32\\MSCTF.dll"},
{0x75b80000, 0xc000, 0x2, "C:\\Windows\\system32\\CRYPTBASE.dll"},
{0x77350000, 0xa0000, 0x8, "C:\\Windows\\system32\\ADVAPI32.dll"},
{0x73f50000, 0x47000, 0x2, "c:\\windows\\system32\\es.dll"},
{0x777d0000, 0x8f000, 0x8, "C:\\Windows\\system32\\OLEAUT32.dll"},
{0x75720000, 0x16000, 0x1, "C:\\Windows\\system32\\CRYPTSP.dll"},
{0x75470000, 0x3b000, 0x1, "C:\\Windows\\system32\\rsaenh.dll"},
{0x75bf0000, 0xe000, 0x1, "C:\\Windows\\system32\\RpcRtRemote.dll"},
{0x763f0000, 0x83000, 0x1, "C:\\Windows\\system32\\CLBCatQ.DLL"},
{0x72ba0000, 0x8000, 0x1, "c:\\windows\\system32\\nsisvc.dll"},
{0x77c30000, 0x6000, 0x1f, "C:\\Windows\\system32\\NSI.dll"},
{0x75b90000, 0x5f000, 0x1, "C:\\Windows\\system32\\SXS.DLL"},
{0x71300000, 0x5a000, 0x1, "c:\\windows\\system32\\netprofm.dll"},
{0x742a0000, 0x10000, 0x2, "c:\\windows\\system32\\nlaapi.dll"},
{0x71210000, 0x15000, 0x2, "c:\\windows\\system32\\wdi.dll"},
{0x711d0000, 0x8000, 0x1, "C:\\Windows\\System32\\npmproxy.dll"},
{0x70f30000, 0x90000, 0x1, "C:\\Windows\\system32\\perftrack.dll"},
{0x70dc0000, 0x61000, 0x1, "C:\\Windows\\system32\\wer.dll"},
{0x74820000, 0x13000, 0x1, "C:\\Windows\\system32\\dwmapi.dll"},
{0x757d0000, 0x8000, 0x1, "C:\\Windows\\system32\\Secur32.dll"},
{0x75b10000, 0x1b000, 0x5, "C:\\Windows\\system32\\SSPICLI.DLL"},
{0x70da0000, 0x12000, 0x1, "C:\\Windows\\system32\\AEPIC.dll"},
{0x70d90000, 0x3000, 0x1, "C:\\Windows\\system32\\sfc.dll"},
{0x70d70000, 0xd000, 0x1, "C:\\Windows\\system32\\sfc_os.DLL"},
{0x75130000, 0x9000, 0x1, "C:\\Windows\\system32\\VERSION.dll"},
{0x75b30000, 0x4c000, 0x1, "C:\\Windows\\system32\\apphelp.dll"},
{0x763a0000, 0x35000, 0xf, "C:\\Windows\\system32\\WS2_32.dll"},
{0x72b80000, 0x1c000, 0x5, "C:\\Windows\\system32\\IPHLPAPI.DLL"},
{0x72b70000, 0x7000, 0x5, "C:\\Windows\\system32\\WINNSI.DLL"},
{0x72290000, 0x58000, 0x2, "C:\\Windows\\system32\\winhttp.dll"},
{0x72490000, 0x4f000, 0x2, "C:\\Windows\\system32\\webio.dll"},
{0x75270000, 0x16000, 0x2, "C:\\Windows\\system32\\GPAPI.dll"},
{0x772f0000, 0x57000, 0x1, "C:\\Windows\\system32\\SHLWAPI.dll"},
{0x75360000, 0x8000, 0x1, "C:\\Windows\\system32\\credssp.dll"},
{0x755a0000, 0x44000, 0x2, "C:\\Windows\\system32\\DNSAPI.dll"},
{0x70c10000, 0x10000, 0x1, "C:\\Windows\\system32\\napinsp.dll"},
{0x70000000, 0x12000, 0x2, "C:\\Windows\\system32\\pnrpnsp.dll"},
{0x756e0000, 0x3c000, 0x4, "C:\\Windows\\System32\\mswsock.dll"},
{0x70c00000, 0x8000, 0x1, "C:\\Windows\\System32\\winrnr.dll"},
{0x751c0000, 0x5000, 0x1, "C:\\Windows\\System32\\wshtcpip.dll"},
{0x756d0000, 0x6000, 0x1, "C:\\Windows\\System32\\wship6.dll"},
{0x71480000, 0x6000, 0x1, "C:\\Windows\\system32\\rasadhlp.dll"},
{0x72a40000, 0x38000, 0x1, "C:\\Windows\\System32\\fwpuclnt.dll"},
{0x72aa0000, 0xd000, 0x1, "C:\\Windows\\system32\\dhcpcsvc6.DLL"},
{0x72a20000, 0x12000, 0x2, "C:\\Windows\\system32\\dhcpcsvc.DLL"}}},
{1036,
{{0x00dd0000, 0x8000, 0xffff, "C:\\Windows\\system32\\svchost.exe"},
{0x77ae0000, 0x13c000, 0xffff, "C:\\Windows\\SYSTEM32\\ntdll.dll"},
{0x76480000, 0xd4000, 0xffff, "C:\\Windows\\system32\\kernel32.dll"},
{0x75cb0000, 0x4a000, 0xffff, "C:\\Windows\\system32\\KERNELBASE.dll"},
{0x779d0000, 0xac000, 0xffff, "C:\\Windows\\system32\\msvcrt.dll"},
{0x75fa0000, 0x19000, 0xffff, "C:\\Windows\\SYSTEM32\\sechost.dll"},
{0x762a0000, 0xa1000, 0xffff, "C:\\Windows\\system32\\RPCRT4.dll"},
{0x77670000, 0x15c000, 0xf, "C:\\Windows\\system32\\ole32.dll"},
{0x75f50000, 0x4e000, 0x4f, "C:\\Windows\\system32\\GDI32.dll"},
{0x77c40000, 0xc9000, 0x56, "C:\\Windows\\system32\\USER32.dll"},
{0x76560000, 0xa000, 0x13, "C:\\Windows\\system32\\LPK.dll"},
{0x77930000, 0x9d000, 0x13, "C:\\Windows\\system32\\USP10.dll"},
{0x75f30000, 0x1f000, 0x2, "C:\\Windows\\system32\\IMM32.DLL"},
{0x77860000, 0xcc000, 0x1, "C:\\Windows\\system32\\MSCTF.dll"},
{0x75b80000, 0xc000, 0x3, "C:\\Windows\\system32\\CRYPTBASE.dll"},
{0x77350000, 0xa0000, 0xf, "C:\\Windows\\system32\\ADVAPI32.dll"},
{0x72af0000, 0x23000, 0x2, "c:\\windows\\system32\\dnsrslvr.dll"},
{0x763a0000, 0x35000, 0x17, "C:\\Windows\\system32\\WS2_32.dll"},
{0x77c30000, 0x6000, 0x43, "C:\\Windows\\system32\\NSI.dll"},
{0x755a0000, 0x44000, 0x5, "c:\\windows\\system32\\DNSAPI.dll"},
{0x72b70000, 0x7000, 0x11, "c:\\windows\\system32\\WINNSI.DLL"},
{0x72a40000, 0x38000, 0x4, "C:\\Windows\\system32\\Fwpuclnt.dll"},
{0x72a90000, 0x5000, 0x1, "C:\\Windows\\System32\\dnsext.dll"},
{0x75290000, 0x17000, 0x1, "C:\\Windows\\system32\\USERENV.dll"},
{0x75c30000, 0xb000, 0x1, "C:\\Windows\\system32\\profapi.dll"},
{0x75270000, 0x16000, 0x2, "C:\\Windows\\system32\\GPAPI.dll"},
{0x75bf0000, 0xe000, 0x1, "C:\\Windows\\system32\\RpcRtRemote.dll"},
{0x756e0000, 0x3c000, 0x4, "C:\\Windows\\system32\\mswsock.dll"},
{0x756d0000, 0x6000, 0x1, "C:\\Windows\\System32\\wship6.dll"},
{0x72b80000, 0x1c000, 0xe, "C:\\Windows\\system32\\iphlpapi.dll"},
{0x72aa0000, 0xd000, 0x2, "C:\\Windows\\system32\\dhcpcsvc6.DLL"},
{0x72a20000, 0x12000, 0x5, "C:\\Windows\\system32\\dhcpcsvc.DLL"},
{0x751c0000, 0x5000, 0x1, "C:\\Windows\\System32\\wshtcpip.dll"},
{0x726c0000, 0x17000, 0x1, "c:\\windows\\system32\\wkssvc.dll"},
{0x745c0000, 0x9000, 0x4, "c:\\windows\\system32\\netutils.dll"},
{0x75800000, 0x2b000, 0x1, "c:\\windows\\system32\\netjoin.dll"},
{0x75b10000, 0x1b000, 0x4, "C:\\Windows\\system32\\SspiCli.dll"},
{0x72680000, 0x24000, 0x1, "c:\\windows\\system32\\cryptsvc.dll"},
{0x75d00000, 0x11d000, 0x1, "C:\\Windows\\system32\\CRYPT32.dll"},
{0x75ca0000, 0xc000, 0x1, "C:\\Windows\\system32\\MSASN1.dll"},
{0x72520000, 0x116000, 0x1, "C:\\Windows\\system32\\VSSAPI.DLL"},
{0x74080000, 0x14000, 0x1, "C:\\Windows\\system32\\ATL.DLL"},
{0x72510000, 0x10000, 0x2, "C:\\Windows\\system32\\VssTrace.DLL"},
{0x777d0000, 0x8f000, 0x6, "C:\\Windows\\system32\\OLEAUT32.dll"},
{0x745a0000, 0xf000, 0x1, "C:\\Windows\\system32\\samcli.dll"},
{0x74c90000, 0x12000, 0x1, "C:\\Windows\\system32\\SAMLIB.dll"},
{0x75720000, 0x16000, 0x1, "C:\\Windows\\system32\\CRYPTSP.dll"},
{0x72440000, 0x3e000, 0x2, "c:\\windows\\system32\\nlasvc.dll"},
{0x75900000, 0x42000, 0xa, "c:\\windows\\system32\\wevtapi.dll"},
{0x724e0000, 0x28000, 0x2, "c:\\windows\\system32\\ncsi.dll"},
{0x72290000, 0x58000, 0x3, "c:\\windows\\system32\\WINHTTP.dll"},
{0x72490000, 0x4f000, 0x3, "c:\\windows\\system32\\webio.dll"},
{0x75e70000, 0x27000, 0x2, "C:\\Windows\\system32\\CFGMGR32.dll"},
{0x75470000, 0x3b000, 0x1, "C:\\Windows\\system32\\rsaenh.dll"},
{0x763f0000, 0x83000, 0x1, "C:\\Windows\\system32\\CLBCatQ.DLL"},
{0x73f50000, 0x47000, 0x1, "C:\\Windows\\system32\\es.dll"},
{0x757d0000, 0x8000, 0x1, "C:\\Windows\\system32\\secur32.dll"},
{0x75360000, 0x8000, 0x1, "C:\\Windows\\system32\\credssp.dll"},
{0x72250000, 0xd000, 0x1, "C:\\Windows\\system32\\ssdpapi.dll"},
{0x74b90000, 0xf5000, 0x2, "C:\\Windows\\system32\\PROPSYS.dll"},
{0x745b0000, 0xf000, 0x1, "C:\\Windows\\system32\\wkscli.dll"},
{0x75850000, 0x17000, 0x2, "C:\\Windows\\system32\\bcrypt.dll"},
{0x753b0000, 0x3d000, 0x1, "C:\\Windows\\system32\\bcryptprimitives.dll"},
{0x772f0000, 0x57000, 0x1, "C:\\Windows\\system32\\SHLWAPI.dll"},
{0x70380000, 0x1a3000, 0x1, "C:\\Windows\\system32\\ESENT.dll"},
{0x77c20000, 0x5000, 0x1, "C:\\Windows\\system32\\psapi.dll"},
{0x71480000, 0x6000, 0x1, "C:\\Windows\\system32\\rasadhlp.dll"}}},
{1132,
{{0x00b70000, 0x50000, 0xffff, "C:\\Windows\\System32\\spoolsv.exe"},
{0x77ae0000, 0x13c000, 0xffff, "C:\\Windows\\SYSTEM32\\ntdll.dll"},
{0x76480000, 0xd4000, 0xffff, "C:\\Windows\\system32\\kernel32.dll"},
{0x75cb0000, 0x4a000, 0xffff, "C:\\Windows\\system32\\KERNELBASE.dll"},
{0x779d0000, 0xac000, 0xffff, "C:\\Windows\\system32\\msvcrt.dll"},
{0x75fa0000, 0x19000, 0xffff, "C:\\Windows\\SYSTEM32\\sechost.dll"},
{0x762a0000, 0xa1000, 0xffff, "C:\\Windows\\system32\\RPCRT4.dll"},
{0x77c40000, 0xc9000, 0xffff, "C:\\Windows\\system32\\USER32.dll"},
{0x75f50000, 0x4e000, 0xffff, "C:\\Windows\\system32\\GDI32.dll"},
{0x76560000, 0xa000, 0xffff, "C:\\Windows\\system32\\LPK.dll"},
{0x77930000, 0x9d000, 0xffff, "C:\\Windows\\system32\\USP10.dll"},
{0x74330000, 0x25000, 0xffff, "C:\\Windows\\System32\\POWRPROF.dll"},
{0x75fc0000, 0x19d000, 0xffff, "C:\\Windows\\system32\\SETUPAPI.dll"},
{0x75e70000, 0x27000, 0xffff, "C:\\Windows\\system32\\CFGMGR32.dll"},
{0x77350000, 0xa0000, 0xffff, "C:\\Windows\\system32\\ADVAPI32.dll"},
{0x777d0000, 0x8f000, 0xffff, "C:\\Windows\\system32\\OLEAUT32.dll"},
{0x77670000, 0x15c000, 0xffff, "C:\\Windows\\system32\\ole32.dll"},
{0x75e50000, 0x12000, 0xffff, "C:\\Windows\\system32\\DEVOBJ.dll"},
{0x755a0000, 0x44000, 0xffff, "C:\\Windows\\System32\\DNSAPI.dll"},
{0x763a0000, 0x35000, 0xffff, "C:\\Windows\\system32\\WS2_32.dll"},
{0x77c30000, 0x6000, 0xffff, "C:\\Windows\\system32\\NSI.dll"},
{0x75f30000, 0x1f000, 0x2, "C:\\Windows\\system32\\IMM32.DLL"},
{0x77860000, 0xcc000, 0x1, "C:\\Windows\\system32\\MSCTF.dll"},
{0x75b80000, 0xc000, 0x2, "C:\\Windows\\System32\\CRYPTBASE.dll"},
{0x73f40000, 0xa000, 0x1, "C:\\Windows\\System32\\slc.dll"},
{0x75bf0000, 0xe000, 0x1, "C:\\Windows\\System32\\RpcRtRemote.dll"},
{0x757d0000, 0x8000, 0x1, "C:\\Windows\\System32\\secur32.dll"},
{0x75b10000, 0x1b000, 0x2, "C:\\Windows\\System32\\SSPICLI.DLL"},
{0x75360000, 0x8000, 0x1, "C:\\Windows\\System32\\credssp.dll"},
{0x746d0000, 0xd000, 0x1, "C:\\Windows\\System32\\WTSAPI32.dll"},
{0x75c00000, 0x29000, 0x2, "C:\\Windows\\System32\\WINSTA.dll"},
{0x72b80000, 0x1c000, 0x4, "C:\\Windows\\System32\\IPHLPAPI.DLL"},
{0x72b70000, 0x7000, 0x4, "C:\\Windows\\System32\\WINNSI.DLL"},
{0x756e0000, 0x3c000, 0x4, "C:\\Windows\\system32\\mswsock.dll"},
{0x751c0000, 0x5000, 0x1, "C:\\Windows\\System32\\wshtcpip.dll"},
{0x756d0000, 0x6000, 0x1, "C:\\Windows\\System32\\wship6.dll"},
{0x71480000, 0x6000, 0x1, "C:\\Windows\\System32\\rasadhlp.dll"},
{0x72a40000, 0x38000, 0x1, "C:\\Windows\\System32\\fwpuclnt.dll"},
{0x763f0000, 0x83000, 0x1, "C:\\Windows\\system32\\CLBCatQ.DLL"},
{0x71470000, 0xf000, 0x1, "C:\\Windows\\system32\\umb.dll"},
{0x74080000, 0x14000, 0x4, "C:\\Windows\\system32\\ATL.DLL"},
{0x75e20000, 0x2d000, 0x1, "C:\\Windows\\system32\\WINTRUST.dll"},
{0x75d00000, 0x11d000, 0x1, "C:\\Windows\\system32\\CRYPT32.dll"},
{0x75ca0000, 0xc000, 0x2, "C:\\Windows\\system32\\MSASN1.dll"},
{0x71370000, 0xbf000, 0x3, "C:\\Windows\\System32\\localspl.dll"},
{0x71360000, 0xe000, 0xb, "C:\\Windows\\System32\\SPOOLSS.DLL"},
{0x75450000, 0x19000, 0x3, "C:\\Windows\\System32\\srvcli.dll"},
{0x71250000, 0x51000, 0x4, "C:\\Windows\\system32\\winspool.drv"},
{0x71240000, 0xc000, 0x1, "C:\\Windows\\System32\\PrintIsolationProxy.dll"},
{0x711e0000, 0xd000, 0x1, "C:\\Windows\\System32\\FXSMON.DLL"},
{0x70f00000, 0x27000, 0x1, "C:\\Windows\\System32\\tcpmon.dll"},
{0x70ef0000, 0x9000, 0x1, "C:\\Windows\\System32\\snmpapi.dll"},
{0x70ee0000, 0xf000, 0x1, "C:\\Windows\\System32\\wsnmp32.dll"},
{0x72040000, 0x158000, 0x1, "C:\\Windows\\System32\\msxml6.dll"},
{0x772f0000, 0x57000, 0x1, "C:\\Windows\\system32\\SHLWAPI.dll"},
{0x70e50000, 0xb000, 0x1, "C:\\Windows\\System32\\usbmon.dll"},
{0x70d60000, 0x6000, 0x1, "C:\\Windows\\system32\\wls0wndh.dll"},
{0x70d30000, 0x2f000, 0x1, "C:\\Windows\\System32\\WSDMon.dll"},
{0x723c0000, 0x73000, 0x1, "C:\\Windows\\System32\\wsdapi.dll"},
{0x722f0000, 0xc2000, 0x1, "C:\\Windows\\System32\\webservices.dll"},
{0x75140000, 0x76000, 0x1, "C:\\Windows\\System32\\FirewallAPI.dll"},
{0x75130000, 0x9000, 0x2, "C:\\Windows\\System32\\VERSION.dll"},
{0x72260000, 0x2b000, 0x2, "C:\\Windows\\system32\\FunDisc.dll"},
{0x70c90000, 0xd000, 0x1, "C:\\Windows\\system32\\fdPnp.dll"},
{0x70c60000, 0xb000, 0x1,
"C:\\Windows\\system32\\spool\\PRTPROCS\\W32X86\\winprint.dll"},
{0x75290000, 0x17000, 0x2, "C:\\Windows\\System32\\USERENV.dll"},
{0x75c30000, 0xb000, 0x2, "C:\\Windows\\System32\\profapi.dll"},
{0x75270000, 0x16000, 0x3, "C:\\Windows\\System32\\GPAPI.dll"},
{0x73fe0000, 0x9000, 0x1, "C:\\Windows\\System32\\dsrole.dll"},
{0x70b80000, 0x7c000, 0x1, "C:\\Windows\\System32\\win32spl.dll"},
{0x752b0000, 0xe000, 0x1, "C:\\Windows\\System32\\DEVRTL.dll"},
{0x752c0000, 0x15000, 0x1, "C:\\Windows\\System32\\SPINF.dll"},
{0x70c20000, 0x22000, 0x1, "C:\\Windows\\System32\\inetpp.dll"},
{0x75720000, 0x16000, 0x1, "C:\\Windows\\System32\\CRYPTSP.dll"},
{0x75470000, 0x3b000, 0x1, "C:\\Windows\\system32\\rsaenh.dll"},
{0x71af0000, 0xb000, 0x1, "C:\\Windows\\System32\\cscapi.dll"},
{0x745c0000, 0x9000, 0x1, "C:\\Windows\\System32\\netutils.dll"}}},
{1168,
{
{0x00dd0000, 0x8000, 0xffff, "C:\\Windows\\system32\\svchost.exe"},
{0x77ae0000, 0x13c000, 0xffff, "C:\\Windows\\SYSTEM32\\ntdll.dll"},
{0x76480000, 0xd4000, 0xffff, "C:\\Windows\\system32\\kernel32.dll"},
{0x75cb0000, 0x4a000, 0xffff, "C:\\Windows\\system32\\KERNELBASE.dll"},
{0x779d0000, 0xac000, 0xffff, "C:\\Windows\\system32\\msvcrt.dll"},
{0x75fa0000, 0x19000, 0xffff, "C:\\Windows\\SYSTEM32\\sechost.dll"},
{0x762a0000, 0xa1000, 0xffff, "C:\\Windows\\system32\\RPCRT4.dll"},
{0x77670000, 0x15c000, 0xa, "C:\\Windows\\system32\\ole32.dll"},
{0x75f50000, 0x4e000, 0x70, "C:\\Windows\\system32\\GDI32.dll"},
{0x77c40000, 0xc9000, 0x7a, "C:\\Windows\\system32\\USER32.dll"},
{0x76560000, 0xa000, 0x1e, "C:\\Windows\\system32\\LPK.dll"},
{0x77930000, 0x9d000, 0x1e, "C:\\Windows\\system32\\USP10.dll"},
{0x75f30000, 0x1f000, 0x2, "C:\\Windows\\system32\\IMM32.DLL"},
{0x77860000, 0xcc000, 0x1, "C:\\Windows\\system32\\MSCTF.dll"},
{0x75b80000, 0xc000, 0x2, "C:\\Windows\\system32\\CRYPTBASE.dll"},
{0x77350000, 0xa0000, 0x10, "C:\\Windows\\system32\\ADVAPI32.dll"},
{0x72770000, 0x7e000, 0x1, "c:\\windows\\system32\\bfe.dll"},
{0x758b0000, 0x1b000, 0x4, "c:\\windows\\system32\\AUTHZ.dll"},
{0x73f40000, 0xa000, 0x1, "c:\\windows\\system32\\slc.dll"},
{0x75b10000, 0x1b000, 0x4, "C:\\Windows\\system32\\SspiCli.dll"},
{0x75240000, 0xb000, 0x1, "C:\\Windows\\system32\\pcwum.dll"},
{0x75bf0000, 0xe000, 0x2, "C:\\Windows\\system32\\RpcRtRemote.dll"},
{0x726e0000, 0x8d000, 0x1, "c:\\windows\\system32\\mpssvc.dll"},
{0x75140000, 0x76000, 0x4, "c:\\windows\\system32\\FirewallAPI.dll"},
{0x75130000, 0x9000, 0x7, "c:\\windows\\system32\\VERSION.dll"},
{0x72a40000, 0x38000, 0x1, "c:\\windows\\system32\\fwpuclnt.dll"},
{0x77c30000, 0x6000, 0x12, "C:\\Windows\\system32\\NSI.dll"},
{0x75e70000, 0x27000, 0x1, "C:\\Windows\\system32\\CFGMGR32.dll"},
{0x772f0000, 0x57000, 0x3, "C:\\Windows\\system32\\SHLWAPI.dll"},
{0x757d0000, 0x8000, 0x1, "C:\\Windows\\system32\\secur32.dll"},
{0x75360000, 0x8000, 0x1, "C:\\Windows\\system32\\credssp.dll"},
{0x75290000, 0x17000, 0x3, "C:\\Windows\\system32\\USERENV.dll"},
{0x75c30000, 0xb000, 0x3, "C:\\Windows\\system32\\profapi.dll"},
{0x75270000, 0x16000, 0x4, "C:\\Windows\\system32\\GPAPI.dll"},
{0x763a0000, 0x35000, 0x9, "C:\\Windows\\system32\\WS2_32.dll"},
{0x72b80000, 0x1c000, 0x3, "C:\\Windows\\system32\\IPHLPAPI.DLL"},
{0x72b70000, 0x7000, 0x3, "C:\\Windows\\system32\\WINNSI.DLL"},
{0x72aa0000, 0xd000, 0x1, "C:\\Windows\\system32\\dhcpcsvc6.DLL"},
{0x72a20000, 0x12000, 0x1, "C:\\Windows\\system32\\dhcpcsvc.DLL"},
{0x756e0000, 0x3c000, 0x3, "C:\\Windows\\system32\\mswsock.dll"},
{0x726b0000, 0x6000, 0x1, "C:\\Windows\\System32\\wshqos.dll"},
{0x751c0000, 0x5000, 0x1, "C:\\Windows\\system32\\wshtcpip.DLL"},
{0x756d0000, 0x6000, 0x1, "C:\\Windows\\system32\\wship6.dll"},
{0x72670000, 0x8000, 0x1, "C:\\Windows\\system32\\wfapigp.dll"},
{0x72640000, 0x25000, 0x1, "c:\\windows\\system32\\dps.dll"},
{0x777d0000, 0x8f000, 0x4, "C:\\Windows\\system32\\OLEAUT32.dll"},
{0x763f0000, 0x83000, 0x1, "C:\\Windows\\system32\\CLBCatQ.DLL"},
{0x73ff0000, 0x7d000, 0x1, "C:\\Windows\\system32\\taskschd.dll"},
{0x72800000, 0x21000, 0x2, "C:\\Windows\\system32\\ntmarta.dll"},
{0x76350000, 0x45000, 0x2, "C:\\Windows\\system32\\WLDAP32.dll"},
{0x75850000, 0x17000, 0x1, "C:\\Windows\\system32\\bcrypt.dll"},
{0x71210000, 0x15000, 0x6, "C:\\Windows\\system32\\wdi.dll"},
{0x71050000, 0xd6000, 0x3, "C:\\Windows\\system32\\diagperf.dll"},
{0x71300000, 0x5a000, 0x1, "C:\\Windows\\System32\\netprofm.dll"},
{0x742a0000, 0x10000, 0x1, "C:\\Windows\\System32\\nlaapi.dll"},
{0x75720000, 0x16000, 0x1, "C:\\Windows\\system32\\CRYPTSP.dll"},
{0x70e70000, 0x6000, 0x1, "C:\\Windows\\system32\\pnpts.dll"},
{0x70e60000, 0xb000, 0x1, "C:\\Windows\\system32\\wdiasqmmodule.dll"},
{0x75470000, 0x3b000, 0x1, "C:\\Windows\\system32\\rsaenh.dll"},
{0x70e30000, 0x18000, 0x2, "C:\\Windows\\system32\\radardt.dll"},
{0x746d0000, 0xd000, 0x2, "C:\\Windows\\system32\\WTSAPI32.dll"},
{0x711d0000, 0x8000, 0x1, "C:\\Windows\\System32\\npmproxy.dll"},
}},
{1276,
{
{0x00dd0000, 0x8000, 0xffff, "C:\\Windows\\system32\\svchost.exe"},
{0x77ae0000, 0x13c000, 0xffff, "C:\\Windows\\SYSTEM32\\ntdll.dll"},
{0x76480000, 0xd4000, 0xffff, "C:\\Windows\\system32\\kernel32.dll"},
{0x75cb0000, 0x4a000, 0xffff, "C:\\Windows\\system32\\KERNELBASE.dll"},
{0x779d0000, 0xac000, 0xffff, "C:\\Windows\\system32\\msvcrt.dll"},
{0x75fa0000, 0x19000, 0xffff, "C:\\Windows\\SYSTEM32\\sechost.dll"},
{0x762a0000, 0xa1000, 0xffff, "C:\\Windows\\system32\\RPCRT4.dll"},
{0x77670000, 0x15c000, 0x8, "C:\\Windows\\system32\\ole32.dll"},
{0x75f50000, 0x4e000, 0x3e, "C:\\Windows\\system32\\GDI32.dll"},
{0x77c40000, 0xc9000, 0x43, "C:\\Windows\\system32\\USER32.dll"},
{0x76560000, 0xa000, 0xf, "C:\\Windows\\system32\\LPK.dll"},
{0x77930000, 0x9d000, 0xf, "C:\\Windows\\system32\\USP10.dll"},
{0x75f30000, 0x1f000, 0x2, "C:\\Windows\\system32\\IMM32.DLL"},
{0x77860000, 0xcc000, 0x1, "C:\\Windows\\system32\\MSCTF.dll"},
{0x75b80000, 0xc000, 0x2, "C:\\Windows\\system32\\CRYPTBASE.dll"},
{0x77350000, 0xa0000, 0x8, "C:\\Windows\\system32\\ADVAPI32.dll"},
{0x72480000, 0xa000, 0x1, "c:\\windows\\system32\\fdrespub.dll"},
{0x723c0000, 0x73000, 0x2, "c:\\windows\\system32\\wsdapi.dll"},
{0x763a0000, 0x35000, 0xd, "C:\\Windows\\system32\\WS2_32.dll"},
{0x77c30000, 0x6000, 0x1b, "C:\\Windows\\system32\\NSI.dll"},
{0x72b80000, 0x1c000, 0x5, "c:\\windows\\system32\\IPHLPAPI.DLL"},
{0x72b70000, 0x7000, 0x5, "c:\\windows\\system32\\WINNSI.DLL"},
{0x722f0000, 0xc2000, 0x2, "c:\\windows\\system32\\webservices.dll"},
{0x75140000, 0x76000, 0x4, "c:\\windows\\system32\\FirewallAPI.dll"},
{0x75130000, 0x9000, 0x4, "c:\\windows\\system32\\VERSION.dll"},
{0x763f0000, 0x83000, 0x1, "C:\\Windows\\system32\\CLBCatQ.DLL"},
{0x777d0000, 0x8f000, 0x3, "C:\\Windows\\system32\\OLEAUT32.dll"},
{0x72260000, 0x2b000, 0x2, "C:\\Windows\\system32\\FunDisc.dll"},
{0x74080000, 0x14000, 0x2, "C:\\Windows\\system32\\ATL.DLL"},
{0x772f0000, 0x57000, 0x3, "C:\\Windows\\system32\\SHLWAPI.dll"},
{0x72aa0000, 0xd000, 0x1, "C:\\Windows\\system32\\dhcpcsvc6.DLL"},
{0x72a20000, 0x12000, 0x1, "C:\\Windows\\system32\\dhcpcsvc.DLL"},
{0x756e0000, 0x3c000, 0x3, "C:\\Windows\\system32\\mswsock.dll"},
{0x756d0000, 0x6000, 0x2, "C:\\Windows\\System32\\wship6.dll"},
{0x726b0000, 0x6000, 0x1, "C:\\Windows\\System32\\wshqos.dll"},
{0x751c0000, 0x5000, 0x2, "C:\\Windows\\system32\\wshtcpip.DLL"},
{0x72290000, 0x58000, 0x1, "C:\\Windows\\system32\\WINHTTP.dll"},
{0x72490000, 0x4f000, 0x1, "C:\\Windows\\system32\\webio.dll"},
{0x721b0000, 0xb000, 0x1, "C:\\Windows\\system32\\HTTPAPI.dll"},
{0x75240000, 0xb000, 0x1, "C:\\Windows\\system32\\pcwum.dll"},
{0x745b0000, 0xf000, 0x1, "C:\\Windows\\system32\\wkscli.dll"},
{0x745c0000, 0x9000, 0x1, "C:\\Windows\\system32\\netutils.dll"},
{0x72040000, 0x158000, 0x1, "C:\\Windows\\System32\\msxml6.dll"},
{0x75720000, 0x16000, 0x2, "C:\\Windows\\system32\\CRYPTSP.dll"},
{0x75470000, 0x3b000, 0x1, "C:\\Windows\\system32\\rsaenh.dll"},
{0x747f0000, 0x2f000, 0x1, "C:\\Windows\\system32\\XmlLite.dll"},
{0x6f5d0000, 0x2a000, 0x1, "c:\\windows\\system32\\ssdpsrv.dll"},
{0x6f500000, 0xc8000, 0x1, "c:\\windows\\system32\\fntcache.dll"},
{0x728f0000, 0x9000, 0x1, "c:\\windows\\system32\\ktmw32.dll"},
{0x72800000, 0x21000, 0x1, "C:\\Windows\\system32\\ntmarta.dll"},
{0x76350000, 0x45000, 0x1, "C:\\Windows\\system32\\WLDAP32.dll"},
{0x757d0000, 0x8000, 0x1, "C:\\Windows\\system32\\secur32.dll"},
{0x75b10000, 0x1b000, 0x2, "C:\\Windows\\system32\\SSPICLI.DLL"},
{0x75360000, 0x8000, 0x1, "C:\\Windows\\system32\\credssp.dll"},
{0x75bf0000, 0xe000, 0x1, "C:\\Windows\\system32\\RpcRtRemote.dll"},
}},
{1424,
{{0x00350000, 0xf000, 0xffff, "C:\\Windows\\system32\\taskhost.exe"},
{0x77ae0000, 0x13c000, 0xffff, "C:\\Windows\\SYSTEM32\\ntdll.dll"},
{0x76480000, 0xd4000, 0xffff, "C:\\Windows\\system32\\kernel32.dll"},
{0x75cb0000, 0x4a000, 0xffff, "C:\\Windows\\system32\\KERNELBASE.dll"},
{0x779d0000, 0xac000, 0xffff, "C:\\Windows\\system32\\msvcrt.dll"},
{0x77670000, 0x15c000, 0xffff, "C:\\Windows\\system32\\ole32.dll"},
{0x75f50000, 0x4e000, 0xffff, "C:\\Windows\\system32\\GDI32.dll"},
{0x77c40000, 0xc9000, 0xffff, "C:\\Windows\\system32\\USER32.dll"},
{0x76560000, 0xa000, 0xffff, "C:\\Windows\\system32\\LPK.dll"},
{0x77930000, 0x9d000, 0xffff, "C:\\Windows\\system32\\USP10.dll"},
{0x762a0000, 0xa1000, 0xffff, "C:\\Windows\\system32\\RPCRT4.dll"},
{0x777d0000, 0x8f000, 0xffff, "C:\\Windows\\system32\\OLEAUT32.dll"},
{0x75f30000, 0x1f000, 0x4, "C:\\Windows\\system32\\IMM32.DLL"},
{0x77860000, 0xcc000, 0x7, "C:\\Windows\\system32\\MSCTF.dll"},
{0x75b80000, 0xc000, 0x2, "C:\\Windows\\system32\\CRYPTBASE.dll"},
{0x75fa0000, 0x19000, 0x1e, "C:\\Windows\\SYSTEM32\\sechost.dll"},
{0x77350000, 0xa0000, 0x5, "C:\\Windows\\system32\\ADVAPI32.dll"},
{0x74b50000, 0x40000, 0x2, "C:\\Windows\\system32\\uxtheme.dll"},
{0x74820000, 0x13000, 0x1, "C:\\Windows\\system32\\dwmapi.dll"},
{0x763f0000, 0x83000, 0x1, "C:\\Windows\\system32\\CLBCatQ.DLL"},
{0x72010000, 0x9000, 0x1, "C:\\Windows\\System32\\HotStartUserAgent.dll"},
{0x72000000, 0x8000, 0x2, "C:\\Windows\\system32\\MsCtfMonitor.dll"},
{0x71fd0000, 0x2c000, 0x2, "C:\\Windows\\system32\\MSUTB.dll"},
{0x75c00000, 0x29000, 0x2, "C:\\Windows\\system32\\WINSTA.dll"},
{0x746d0000, 0xd000, 0x2, "C:\\Windows\\system32\\WTSAPI32.dll"},
{0x71fb0000, 0x16000, 0x2, "C:\\Windows\\System32\\PlaySndSrv.dll"},
{0x73f40000, 0xa000, 0x1, "C:\\Windows\\system32\\slc.dll"},
{0x75bf0000, 0xe000, 0x1, "C:\\Windows\\system32\\RpcRtRemote.dll"},
{0x74230000, 0x32000, 0x2, "C:\\Windows\\system32\\WINMM.dll"},
{0x746e0000, 0xb000, 0x1, "C:\\Windows\\system32\\dimsjob.dll"},
{0x772f0000, 0x57000, 0x1, "C:\\Windows\\system32\\SHLWAPI.dll"},
{0x73ff0000, 0x7d000, 0x1, "C:\\Windows\\system32\\taskschd.dll"},
{0x75b10000, 0x1b000, 0x1, "C:\\Windows\\system32\\SspiCli.dll"},
{0x71300000, 0x5a000, 0x1, "C:\\Windows\\System32\\netprofm.dll"},
{0x77c30000, 0x6000, 0x1, "C:\\Windows\\system32\\NSI.dll"},
{0x742a0000, 0x10000, 0x1, "C:\\Windows\\System32\\nlaapi.dll"},
{0x75720000, 0x16000, 0x1, "C:\\Windows\\system32\\CRYPTSP.dll"},
{0x75470000, 0x3b000, 0x1, "C:\\Windows\\system32\\rsaenh.dll"},
{0x711d0000, 0x8000, 0x1, "C:\\Windows\\System32\\npmproxy.dll"},
{0x73fe0000, 0x9000, 0x1, "C:\\Windows\\system32\\dsrole.dll"}}},
{1520,
{{0x00630000, 0x1a000, 0xffff, "C:\\Windows\\system32\\Dwm.exe"},
{0x77ae0000, 0x13c000, 0xffff, "C:\\Windows\\SYSTEM32\\ntdll.dll"},
{0x76480000, 0xd4000, 0xffff, "C:\\Windows\\system32\\kernel32.dll"},
{0x75cb0000, 0x4a000, 0xffff, "C:\\Windows\\system32\\KERNELBASE.dll"},
{0x75f50000, 0x4e000, 0xffff, "C:\\Windows\\system32\\GDI32.dll"},
{0x77c40000, 0xc9000, 0xffff, "C:\\Windows\\system32\\USER32.dll"},
{0x76560000, 0xa000, 0xffff, "C:\\Windows\\system32\\LPK.dll"},
{0x77930000, 0x9d000, 0xffff, "C:\\Windows\\system32\\USP10.dll"},
{0x779d0000, 0xac000, 0xffff, "C:\\Windows\\system32\\msvcrt.dll"},
{0x74b50000, 0x40000, 0xffff, "C:\\Windows\\system32\\UxTheme.dll"},
{0x75f30000, 0x1f000, 0xffff, "C:\\Windows\\system32\\IMM32.dll"},
{0x77860000, 0xcc000, 0xffff, "C:\\Windows\\system32\\MSCTF.dll"},
{0x71f90000, 0x1b000, 0xffff, "C:\\Windows\\system32\\dwmredir.dll"},
{0x71e30000, 0x151000, 0xffff, "C:\\Windows\\system32\\dwmcore.dll"},
{0x77350000, 0xa0000, 0xffff, "C:\\Windows\\system32\\ADVAPI32.dll"},
{0x75fa0000, 0x19000, 0xffff, "C:\\Windows\\SYSTEM32\\sechost.dll"},
{0x762a0000, 0xa1000, 0xffff, "C:\\Windows\\system32\\RPCRT4.dll"},
{0x746f0000, 0xfb000, 0xffff, "C:\\Windows\\system32\\WindowsCodecs.dll"},
{0x77670000, 0x15c000, 0xffff, "C:\\Windows\\system32\\ole32.dll"},
{0x71e00000, 0x2c000, 0xffff, "C:\\Windows\\system32\\d3d10_1.dll"},
{0x71c50000, 0x3a000, 0xffff, "C:\\Windows\\system32\\d3d10_1core.dll"},
{0x71bc0000, 0x83000, 0xffff, "C:\\Windows\\system32\\dxgi.dll"},
{0x75130000, 0x9000, 0xffff, "C:\\Windows\\system32\\VERSION.dll"},
{0x74820000, 0x13000, 0xffff, "C:\\Windows\\system32\\dwmapi.dll"},
{0x77c20000, 0x5000, 0xffff, "C:\\Windows\\system32\\PSAPI.DLL"},
{0x75e20000, 0x2d000, 0x2, "C:\\Windows\\system32\\WINTRUST.dll"},
{0x75d00000, 0x11d000, 0x2, "C:\\Windows\\system32\\CRYPT32.dll"},
{0x75ca0000, 0xc000, 0x4, "C:\\Windows\\system32\\MSASN1.dll"}}},
{1528,
{{0x00120000, 0x281000, 0xffff, "C:\\Windows\\Explorer.EXE"},
{0x77ae0000, 0x13c000, 0xffff, "C:\\Windows\\SYSTEM32\\ntdll.dll"},
{0x76480000, 0xd4000, 0xffff, "C:\\Windows\\system32\\kernel32.dll"},
{0x75cb0000, 0x4a000, 0xffff, "C:\\Windows\\system32\\KERNELBASE.dll"},
{0x77350000, 0xa0000, 0xffff, "C:\\Windows\\system32\\ADVAPI32.dll"},
{0x779d0000, 0xac000, 0xffff, "C:\\Windows\\system32\\msvcrt.dll"},
{0x75fa0000, 0x19000, 0xffff, "C:\\Windows\\SYSTEM32\\sechost.dll"},
{0x762a0000, 0xa1000, 0xffff, "C:\\Windows\\system32\\RPCRT4.dll"},
{0x75f50000, 0x4e000, 0xffff, "C:\\Windows\\system32\\GDI32.dll"},
{0x77c40000, 0xc9000, 0xffff, "C:\\Windows\\system32\\USER32.dll"},
{0x76560000, 0xa000, 0xffff, "C:\\Windows\\system32\\LPK.dll"},
{0x77930000, 0x9d000, 0xffff, "C:\\Windows\\system32\\USP10.dll"},
{0x772f0000, 0x57000, 0xffff, "C:\\Windows\\system32\\SHLWAPI.dll"},
{0x766a0000, 0xc4a000, 0xffff, "C:\\Windows\\system32\\SHELL32.dll"},
{0x77670000, 0x15c000, 0xffff, "C:\\Windows\\system32\\ole32.dll"},
{0x777d0000, 0x8f000, 0xffff, "C:\\Windows\\system32\\OLEAUT32.dll"},
{0x71c90000, 0x16f000, 0xffff, "C:\\Windows\\system32\\EXPLORERFRAME.dll"},
{0x748d0000, 0x2f000, 0xffff, "C:\\Windows\\system32\\DUser.dll"},
{0x74900000, 0xb2000, 0xffff, "C:\\Windows\\system32\\DUI70.dll"},
{0x75f30000, 0x1f000, 0xffff, "C:\\Windows\\system32\\IMM32.dll"},
{0x77860000, 0xcc000, 0xffff, "C:\\Windows\\system32\\MSCTF.dll"},
{0x74b50000, 0x40000, 0xffff, "C:\\Windows\\system32\\UxTheme.dll"},
{0x74330000, 0x25000, 0xffff, "C:\\Windows\\system32\\POWRPROF.dll"},
{0x75fc0000, 0x19d000, 0xffff, "C:\\Windows\\system32\\SETUPAPI.dll"},
{0x75e70000, 0x27000, 0xffff, "C:\\Windows\\system32\\CFGMGR32.dll"},
{0x75e50000, 0x12000, 0xffff, "C:\\Windows\\system32\\DEVOBJ.dll"},
{0x74820000, 0x13000, 0xffff, "C:\\Windows\\system32\\dwmapi.dll"},
{0x73f40000, 0xa000, 0xffff, "C:\\Windows\\system32\\slc.dll"},
{0x749c0000, 0x190000, 0xffff,
"C:\\Windows\\WinSxS\\x86_microsoft.windows.gdiplus_"
"6595b64144ccf1df_1.1.7601.17514_none_"
"72d18a4386696c80\\gdiplus.dll"},
{0x757d0000, 0x8000, 0xffff, "C:\\Windows\\system32\\Secur32.dll"},
{0x75b10000, 0x1b000, 0xffff, "C:\\Windows\\system32\\SSPICLI.DLL"},
{0x74b90000, 0xf5000, 0xffff, "C:\\Windows\\system32\\PROPSYS.dll"},
{0x75c00000, 0x29000, 0x4, "C:\\Windows\\system32\\WINSTA.dll"},
{0x75b80000, 0xc000, 0x2, "C:\\Windows\\system32\\CRYPTBASE.dll"},
{0x74cd0000, 0x19e000, 0x35,
"C:\\Windows\\WinSxS\\x86_microsoft.windows.common-"
"controls_6595b64144ccf1df_6.0.7601.17514_none_"
"41e6975e2bd6f2b2\\comctl32.dll"},
{0x746f0000, 0xfb000, 0x2, "C:\\Windows\\system32\\WindowsCodecs.dll"},
{0x75c30000, 0xb000, 0x5, "C:\\Windows\\system32\\profapi.dll"},
{0x75b30000, 0x4c000, 0x1, "C:\\Windows\\system32\\apphelp.dll"},
{0x763f0000, 0x83000, 0x1, "C:\\Windows\\system32\\CLBCatQ.DLL"},
{0x71b80000, 0x31000, 0x2, "C:\\Windows\\system32\\EhStorShell.dll"},
{0x71b10000, 0x6a000, 0x2, "C:\\Windows\\System32\\cscui.dll"},
{0x71b00000, 0x9000, 0x2, "C:\\Windows\\System32\\CSCDLL.dll"},
{0x71af0000, 0xb000, 0x3, "C:\\Windows\\system32\\CSCAPI.dll"},
{0x71a80000, 0x70000, 0x3, "C:\\Windows\\system32\\ntshrui.dll"},
{0x75450000, 0x19000, 0x1, "C:\\Windows\\system32\\srvcli.dll"},
{0x71a70000, 0x6000, 0x1, "C:\\Windows\\system32\\IconCodecService.dll"},
{0x75720000, 0x16000, 0x1, "C:\\Windows\\system32\\CRYPTSP.dll"},
{0x75470000, 0x3b000, 0x1, "C:\\Windows\\system32\\rsaenh.dll"},
{0x75bf0000, 0xe000, 0x1, "C:\\Windows\\system32\\RpcRtRemote.dll"},
{0x74890000, 0x38000, 0x3, "C:\\Windows\\system32\\SndVolSSO.DLL"},
{0x74880000, 0x9000, 0x4, "C:\\Windows\\system32\\HID.DLL"},
{0x74840000, 0x39000, 0x2, "C:\\Windows\\System32\\MMDevApi.dll"},
{0x6feb0000, 0x78000, 0x1, "C:\\Windows\\system32\\timedate.cpl"},
{0x74080000, 0x14000, 0x1, "C:\\Windows\\system32\\ATL.DLL"},
{0x6fe60000, 0x4e000, 0x1, "C:\\Windows\\system32\\actxprxy.dll"},
{0x70aa0000, 0x2e000, 0x3, "C:\\Windows\\System32\\shdocvw.dll"},
{0x70b20000, 0x9000, 0x1, "C:\\Windows\\system32\\LINKINFO.dll"},
{0x75290000, 0x17000, 0x4, "C:\\Windows\\system32\\USERENV.dll"},
{0x6fad0000, 0x278000, 0x1, "C:\\Windows\\System32\\gameux.dll"},
{0x747f0000, 0x2f000, 0x2, "C:\\Windows\\System32\\XmlLite.dll"},
{0x75d00000, 0x11d000, 0x9, "C:\\Windows\\system32\\CRYPT32.dll"},
{0x75ca0000, 0xc000, 0x9, "C:\\Windows\\system32\\MSASN1.dll"},
{0x70dc0000, 0x61000, 0x1, "C:\\Windows\\System32\\wer.dll"},
{0x74cb0000, 0x1e000, 0x1, "C:\\Windows\\System32\\shacct.dll"},
{0x74c90000, 0x12000, 0x2, "C:\\Windows\\system32\\SAMLIB.dll"},
{0x745a0000, 0xf000, 0x1, "C:\\Windows\\system32\\samcli.dll"},
{0x745c0000, 0x9000, 0x3, "C:\\Windows\\system32\\netutils.dll"},
{0x6fa30000, 0x94000, 0x1, "C:\\Windows\\system32\\MsftEdit.dll"},
{0x6fa00000, 0x2a000, 0x1, "C:\\Windows\\system32\\msls31.dll"},
{0x74670000, 0x58000, 0x1,
"C:\\Program Files\\Common Files\\microsoft shared\\ink\\tiptsf.dll"},
{0x74f70000, 0x1b7000, 0x1, "C:\\Windows\\system32\\authui.dll"},
{0x74e70000, 0xf8000, 0x1, "C:\\Windows\\system32\\CRYPTUI.dll"},
{0x74650000, 0x16000, 0x1, "C:\\Windows\\system32\\thumbcache.dll"},
{0x77c20000, 0x5000, 0x2, "C:\\Windows\\system32\\PSAPI.DLL"},
{0x73d90000, 0x198000, 0x1, "C:\\Windows\\system32\\NetworkExplorer.dll"},
{0x72800000, 0x21000, 0x1, "C:\\Windows\\system32\\ntmarta.dll"},
{0x76350000, 0x45000, 0x1, "C:\\Windows\\system32\\WLDAP32.dll"},
{0x74610000, 0x3a000, 0x5, "C:\\Windows\\system32\\stobject.dll"},
{0x743d0000, 0xb7000, 0x5, "C:\\Windows\\system32\\BatMeter.dll"},
{0x74230000, 0x32000, 0x3, "C:\\Windows\\system32\\WINMM.dll"},
{0x746d0000, 0xd000, 0x1, "C:\\Windows\\system32\\WTSAPI32.dll"},
{0x73c90000, 0x64000, 0x1, "C:\\Windows\\system32\\prnfldr.dll"},
{0x71250000, 0x51000, 0x2, "C:\\Windows\\system32\\WINSPOOL.DRV"},
{0x73f50000, 0x47000, 0x1, "C:\\Windows\\system32\\es.dll"},
{0x73c20000, 0x64000, 0x1, "C:\\Windows\\system32\\dxp.dll"},
{0x76160000, 0x136000, 0x4, "C:\\Windows\\system32\\urlmon.dll"},
{0x76570000, 0xf5000, 0x2, "C:\\Windows\\system32\\WININET.dll"},
{0x77470000, 0x1fb000, 0x5, "C:\\Windows\\system32\\iertutil.dll"},
{0x74600000, 0x10000, 0x1, "C:\\Windows\\system32\\Syncreg.dll"},
{0x745f0000, 0x8000, 0x1, "C:\\Windows\\ehome\\ehSSO.dll"},
{0x739b0000, 0x265000, 0x1, "C:\\Windows\\System32\\netshell.dll"},
{0x72b80000, 0x1c000, 0x4, "C:\\Windows\\System32\\IPHLPAPI.DLL"},
{0x77c30000, 0x6000, 0x11, "C:\\Windows\\system32\\NSI.dll"},
{0x72b70000, 0x7000, 0x4, "C:\\Windows\\System32\\WINNSI.DLL"},
{0x742a0000, 0x10000, 0x2, "C:\\Windows\\System32\\nlaapi.dll"},
{0x743b0000, 0x1d000, 0x1, "C:\\Windows\\system32\\wpdshserviceobj.dll"},
{0x74380000, 0x2b000, 0x1, "C:\\Windows\\system32\\PortableDeviceTypes.dll"},
{0x70ca0000, 0x89000, 0x1, "C:\\Windows\\system32\\PortableDeviceApi.dll"},
{0x74370000, 0xe000, 0x2, "C:\\Windows\\System32\\AltTab.dll"},
{0x73980000, 0x25000, 0x2, "C:\\Windows\\System32\\cscobj.dll"},
{0x737d0000, 0x1ae000, 0x1, "C:\\Windows\\System32\\pnidui.dll"},
{0x737b0000, 0x17000, 0x2, "C:\\Windows\\System32\\QUtil.dll"},
{0x75900000, 0x42000, 0x6, "C:\\Windows\\System32\\wevtapi.dll"},
{0x73700000, 0xb0000, 0x1, "C:\\Windows\\System32\\bthprops.cpl"},
{0x75e20000, 0x2d000, 0x1, "C:\\Windows\\system32\\WINTRUST.dll"},
{0x72c80000, 0xa80000, 0x1, "C:\\Windows\\System32\\ieframe.dll"},
{0x72c40000, 0x3c000, 0x1, "C:\\Windows\\System32\\OLEACC.dll"},
{0x709e0000, 0xba000, 0x2, "C:\\Windows\\System32\\Actioncenter.dll"},
{0x72aa0000, 0xd000, 0x1, "C:\\Windows\\system32\\dhcpcsvc6.DLL"},
{0x763a0000, 0x35000, 0x6, "C:\\Windows\\system32\\WS2_32.dll"},
{0x73ff0000, 0x7d000, 0x1, "C:\\Windows\\system32\\taskschd.dll"},
{0x72a20000, 0x12000, 0x1, "C:\\Windows\\system32\\dhcpcsvc.DLL"},
{0x70900000, 0xd2000, 0x1, "C:\\Windows\\system32\\fxsst.dll"},
{0x72c00000, 0x3a000, 0x1, "C:\\Windows\\system32\\FXSAPI.dll"},
{0x70810000, 0xe3000, 0x1, "C:\\Windows\\system32\\FXSRESM.DLL"},
{0x75360000, 0x8000, 0x1, "C:\\Windows\\system32\\credssp.dll"},
{0x75130000, 0x9000, 0x1, "C:\\Windows\\system32\\VERSION.dll"},
{0x70b30000, 0x4d000, 0x1, "C:\\Windows\\System32\\srchadmin.dll"},
{0x711d0000, 0x8000, 0x1, "C:\\Windows\\System32\\npmproxy.dll"},
{0x73d00000, 0xc000, 0x1, "C:\\Windows\\system32\\mssprxy.dll"},
{0x701b0000, 0x16000, 0x1, "C:\\Windows\\system32\\Wlanapi.dll"},
{0x701a0000, 0x6000, 0x1, "C:\\Windows\\system32\\wlanutil.dll"},
{0x70150000, 0x48000, 0x1, "C:\\Windows\\system32\\wwanapi.dll"},
{0x70140000, 0xa000, 0x1, "C:\\Windows\\system32\\wwapi.dll"},
{0x70110000, 0x2e000, 0x1, "C:\\Windows\\System32\\QAgent.dll"},
{0x6f6a0000, 0x20e000, 0x1, "C:\\Windows\\System32\\SyncCenter.dll"},
{0x6f630000, 0x64000, 0x1, "C:\\Windows\\system32\\imapi2.dll"},
{0x6ffb0000, 0x4f000, 0x1, "C:\\Windows\\System32\\hgcpl.dll"},
{0x6f600000, 0x2b000, 0x1, "C:\\Windows\\System32\\provsvc.dll"},
{0x71300000, 0x5a000, 0x1, "C:\\Windows\\System32\\netprofm.dll"},
{0x745b0000, 0xf000, 0x1, "C:\\Windows\\system32\\wkscli.dll"},
{0x75b90000, 0x5f000, 0x1, "C:\\Windows\\system32\\SXS.DLL"}}},
{312,
{{0x00f90000, 0x5000, 0xffff, "C:\\Windows\\System32\\dinotify.exe"},
{0x77ae0000, 0x13c000, 0xffff, "C:\\Windows\\SYSTEM32\\ntdll.dll"},
{0x76480000, 0xd4000, 0xffff, "C:\\Windows\\system32\\kernel32.dll"},
{0x75cb0000, 0x4a000, 0xffff, "C:\\Windows\\system32\\KERNELBASE.dll"},
{0x779d0000, 0xac000, 0xffff, "C:\\Windows\\system32\\msvcrt.dll"},
{0x6ff30000, 0x76000, 0xffff, "C:\\Windows\\System32\\pnpui.dll"},
{0x77350000, 0xa0000, 0xffff, "C:\\Windows\\system32\\ADVAPI32.dll"},
{0x75fa0000, 0x19000, 0xffff, "C:\\Windows\\SYSTEM32\\sechost.dll"},
{0x762a0000, 0xa1000, 0xffff, "C:\\Windows\\system32\\RPCRT4.dll"},
{0x77c40000, 0xc9000, 0xffff, "C:\\Windows\\system32\\USER32.dll"},
{0x75f50000, 0x4e000, 0xffff, "C:\\Windows\\system32\\GDI32.dll"},
{0x76560000, 0xa000, 0xffff, "C:\\Windows\\system32\\LPK.dll"},
{0x77930000, 0x9d000, 0xffff, "C:\\Windows\\system32\\USP10.dll"},
{0x75fc0000, 0x19d000, 0xffff, "C:\\Windows\\system32\\SETUPAPI.dll"},
{0x75e70000, 0x27000, 0xffff, "C:\\Windows\\system32\\CFGMGR32.dll"},
{0x777d0000, 0x8f000, 0xffff, "C:\\Windows\\system32\\OLEAUT32.dll"},
{0x77670000, 0x15c000, 0xffff, "C:\\Windows\\system32\\ole32.dll"},
{0x75e50000, 0x12000, 0xffff, "C:\\Windows\\system32\\DEVOBJ.dll"},
{0x766a0000, 0xc4a000, 0xffff, "C:\\Windows\\system32\\SHELL32.dll"},
{0x772f0000, 0x57000, 0xffff, "C:\\Windows\\system32\\SHLWAPI.dll"},
{0x75d00000, 0x11d000, 0xffff, "C:\\Windows\\system32\\CRYPT32.dll"},
{0x75ca0000, 0xc000, 0xffff, "C:\\Windows\\system32\\MSASN1.dll"},
{0x75e20000, 0x2d000, 0xffff, "C:\\Windows\\system32\\WINTRUST.dll"},
{0x74900000, 0xb2000, 0xffff, "C:\\Windows\\System32\\DUI70.dll"},
{0x75f30000, 0x1f000, 0x2, "C:\\Windows\\system32\\IMM32.DLL"},
{0x77860000, 0xcc000, 0x1, "C:\\Windows\\system32\\MSCTF.dll"},
{0x75b80000, 0xc000, 0x1, "C:\\Windows\\System32\\CRYPTBASE.dll"},
{0x74b50000, 0x40000, 0x2, "C:\\Windows\\system32\\uxtheme.dll"},
{0x74cd0000, 0x19e000, 0x4,
"C:\\Windows\\WinSxS\\x86_microsoft.windows.common-"
"controls_6595b64144ccf1df_6.0.7601.17514_none_"
"41e6975e2bd6f2b2\\Comctl32.dll"},
{0x74820000, 0x13000, 0x1, "C:\\Windows\\System32\\dwmapi.dll"}}},
{288,
{{0x008b0000, 0xe000, 0xffff, "C:\\Windows\\system32\\rundll32.exe"},
{0x77ae0000, 0x13c000, 0xffff, "C:\\Windows\\SYSTEM32\\ntdll.dll"},
{0x76480000, 0xd4000, 0xffff, "C:\\Windows\\system32\\kernel32.dll"},
{0x75cb0000, 0x4a000, 0xffff, "C:\\Windows\\system32\\KERNELBASE.dll"},
{0x77c40000, 0xc9000, 0xffff, "C:\\Windows\\system32\\USER32.dll"},
{0x75f50000, 0x4e000, 0xffff, "C:\\Windows\\system32\\GDI32.dll"},
{0x76560000, 0xa000, 0xffff, "C:\\Windows\\system32\\LPK.dll"},
{0x77930000, 0x9d000, 0xffff, "C:\\Windows\\system32\\USP10.dll"},
{0x779d0000, 0xac000, 0xffff, "C:\\Windows\\system32\\msvcrt.dll"},
{0x76670000, 0x2a000, 0xffff, "C:\\Windows\\system32\\imagehlp.dll"},
{0x75b30000, 0x4c000, 0xffff, "C:\\Windows\\system32\\apphelp.dll"},
{0x70fc0000, 0x8d000, 0xffff, "C:\\Windows\\AppPatch\\AcLayers.DLL"},
{0x75b10000, 0x1b000, 0x1, "C:\\Windows\\system32\\SspiCli.dll"},
{0x762a0000, 0xa1000, 0x8, "C:\\Windows\\system32\\RPCRT4.dll"},
{0x766a0000, 0xc4a000, 0x2, "C:\\Windows\\system32\\SHELL32.dll"},
{0x772f0000, 0x57000, 0x3, "C:\\Windows\\system32\\SHLWAPI.dll"},
{0x77670000, 0x15c000, 0x2, "C:\\Windows\\system32\\ole32.dll"},
{0x777d0000, 0x8f000, 0x1, "C:\\Windows\\system32\\OLEAUT32.dll"},
{0x75290000, 0x17000, 0x1, "C:\\Windows\\system32\\USERENV.dll"},
{0x75c30000, 0xb000, 0x1, "C:\\Windows\\system32\\profapi.dll"},
{0x71250000, 0x51000, 0x1, "C:\\Windows\\system32\\WINSPOOL.DRV"},
{0x72020000, 0x12000, 0x1, "C:\\Windows\\system32\\MPR.dll"},
{0x75f30000, 0x1f000, 0x2, "C:\\Windows\\system32\\IMM32.DLL"},
{0x77860000, 0xcc000, 0x1, "C:\\Windows\\system32\\MSCTF.dll"},
{0x70b10000, 0x8000, 0x1, "C:\\Windows\\ehome\\ehssetup.dll"},
{0x6fd50000, 0xeb000, 0x1, "C:\\Windows\\system32\\dbghelp.dll"},
{0x70b00000, 0x3000, 0x1, "C:\\Windows\\system32\\LZ32.dll"},
{0x77350000, 0xa0000, 0x1, "C:\\Windows\\system32\\ADVAPI32.dll"},
{0x75fa0000, 0x19000, 0x4, "C:\\Windows\\SYSTEM32\\sechost.dll"},
{0x74b50000, 0x40000, 0x2, "C:\\Windows\\system32\\uxtheme.dll"},
{0x74820000, 0x13000, 0x1, "C:\\Windows\\system32\\dwmapi.dll"}}},
{276,
{
{0x008b0000, 0xe000, 0xffff, "C:\\Windows\\system32\\rundll32.exe"},
{0x77ae0000, 0x13c000, 0xffff, "C:\\Windows\\SYSTEM32\\ntdll.dll"},
{0x76480000, 0xd4000, 0xffff, "C:\\Windows\\system32\\kernel32.dll"},
{0x75cb0000, 0x4a000, 0xffff, "C:\\Windows\\system32\\KERNELBASE.dll"},
{0x77c40000, 0xc9000, 0xffff, "C:\\Windows\\system32\\USER32.dll"},
{0x75f50000, 0x4e000, 0xffff, "C:\\Windows\\system32\\GDI32.dll"},
{0x76560000, 0xa000, 0xffff, "C:\\Windows\\system32\\LPK.dll"},
{0x77930000, 0x9d000, 0xffff, "C:\\Windows\\system32\\USP10.dll"},
{0x779d0000, 0xac000, 0xffff, "C:\\Windows\\system32\\msvcrt.dll"},
{0x76670000, 0x2a000, 0xffff, "C:\\Windows\\system32\\imagehlp.dll"},
{0x75b30000, 0x4c000, 0xffff, "C:\\Windows\\system32\\apphelp.dll"},
{0x70fc0000, 0x8d000, 0xffff, "C:\\Windows\\AppPatch\\AcLayers.DLL"},
{0x75b10000, 0x1b000, 0x1, "C:\\Windows\\system32\\SspiCli.dll"},
{0x762a0000, 0xa1000, 0x8, "C:\\Windows\\system32\\RPCRT4.dll"},
{0x766a0000, 0xc4a000, 0x2, "C:\\Windows\\system32\\SHELL32.dll"},
{0x772f0000, 0x57000, 0x3, "C:\\Windows\\system32\\SHLWAPI.dll"},
{0x77670000, 0x15c000, 0x2, "C:\\Windows\\system32\\ole32.dll"},
{0x777d0000, 0x8f000, 0x1, "C:\\Windows\\system32\\OLEAUT32.dll"},
{0x75290000, 0x17000, 0x1, "C:\\Windows\\system32\\USERENV.dll"},
{0x75c30000, 0xb000, 0x1, "C:\\Windows\\system32\\profapi.dll"},
{0x71250000, 0x51000, 0x1, "C:\\Windows\\system32\\WINSPOOL.DRV"},
{0x72020000, 0x12000, 0x1, "C:\\Windows\\system32\\MPR.dll"},
{0x75f30000, 0x1f000, 0x2, "C:\\Windows\\system32\\IMM32.DLL"},
{0x77860000, 0xcc000, 0x1, "C:\\Windows\\system32\\MSCTF.dll"},
{0x70ad0000, 0x8000, 0x1,
"C:\\Program Files\\Windows Media Player\\wmssetup.dll"},
{0x6fd50000, 0xeb000, 0x1, "C:\\Windows\\system32\\dbghelp.dll"},
{0x70b00000, 0x3000, 0x1, "C:\\Windows\\system32\\LZ32.dll"},
{0x77350000, 0xa0000, 0x1, "C:\\Windows\\system32\\ADVAPI32.dll"},
{0x75fa0000, 0x19000, 0x4, "C:\\Windows\\SYSTEM32\\sechost.dll"},
{0x74b50000, 0x40000, 0x2, "C:\\Windows\\system32\\uxtheme.dll"},
{0x74820000, 0x13000, 0x1, "C:\\Windows\\system32\\dwmapi.dll"},
}},
{1736,
{{0x00290000, 0x6a000, 0xffff, "C:\\Windows\\system32\\SearchIndexer.exe"},
{0x77ae0000, 0x13c000, 0xffff, "C:\\Windows\\SYSTEM32\\ntdll.dll"},
{0x76480000, 0xd4000, 0xffff, "C:\\Windows\\system32\\kernel32.dll"},
{0x75cb0000, 0x4a000, 0xffff, "C:\\Windows\\system32\\KERNELBASE.dll"},
{0x77350000, 0xa0000, 0xffff, "C:\\Windows\\system32\\ADVAPI32.dll"},
{0x779d0000, 0xac000, 0xffff, "C:\\Windows\\system32\\msvcrt.dll"},
{0x75fa0000, 0x19000, 0xffff, "C:\\Windows\\SYSTEM32\\sechost.dll"},
{0x762a0000, 0xa1000, 0xffff, "C:\\Windows\\system32\\RPCRT4.dll"},
{0x77c40000, 0xc9000, 0xffff, "C:\\Windows\\system32\\USER32.dll"},
{0x75f50000, 0x4e000, 0xffff, "C:\\Windows\\system32\\GDI32.dll"},
{0x76560000, 0xa000, 0xffff, "C:\\Windows\\system32\\LPK.dll"},
{0x77930000, 0x9d000, 0xffff, "C:\\Windows\\system32\\USP10.dll"},
{0x77670000, 0x15c000, 0xffff, "C:\\Windows\\system32\\ole32.dll"},
{0x777d0000, 0x8f000, 0xffff, "C:\\Windows\\system32\\OLEAUT32.dll"},
{0x70690000, 0x17c000, 0xffff, "C:\\Windows\\system32\\TQUERY.DLL"},
{0x772f0000, 0x57000, 0xffff, "C:\\Windows\\system32\\SHLWAPI.dll"},
{0x70530000, 0x159000, 0xffff, "C:\\Windows\\system32\\MSSRCH.DLL"},
{0x70380000, 0x1a3000, 0xffff, "C:\\Windows\\system32\\ESENT.dll"},
{0x75f30000, 0x1f000, 0xffff, "C:\\Windows\\system32\\IMM32.dll"},
{0x77860000, 0xcc000, 0xffff, "C:\\Windows\\system32\\MSCTF.dll"},
{0x77c20000, 0x5000, 0x1, "C:\\Windows\\system32\\psapi.dll"},
{0x766a0000, 0xc4a000, 0x1, "C:\\Windows\\system32\\SHELL32.dll"},
{0x75c30000, 0xb000, 0x2, "C:\\Windows\\system32\\profapi.dll"},
{0x75b80000, 0xc000, 0x2, "C:\\Windows\\system32\\CRYPTBASE.dll"},
{0x757d0000, 0x8000, 0x1, "C:\\Windows\\system32\\secur32.dll"},
{0x75b10000, 0x1b000, 0x2, "C:\\Windows\\system32\\SSPICLI.DLL"},
{0x75360000, 0x8000, 0x1, "C:\\Windows\\system32\\credssp.dll"},
{0x763f0000, 0x83000, 0x1, "C:\\Windows\\system32\\CLBCatQ.DLL"},
{0x73d10000, 0x5000, 0x1, "C:\\Windows\\system32\\Msidle.dll"},
{0x75720000, 0x16000, 0x1, "C:\\Windows\\system32\\CRYPTSP.dll"},
{0x75470000, 0x3b000, 0x1, "C:\\Windows\\system32\\rsaenh.dll"},
{0x75bf0000, 0xe000, 0x1, "C:\\Windows\\system32\\RpcRtRemote.dll"},
{0x73d00000, 0xc000, 0x1, "C:\\Windows\\system32\\mssprxy.dll"},
{0x74b90000, 0xf5000, 0x4, "C:\\Windows\\system32\\propsys.dll"},
{0x700c0000, 0x31000, 0x1, "C:\\Windows\\system32\\en-us\\tQuery.dll.mui"},
{0x72800000, 0x21000, 0x1, "C:\\Windows\\system32\\ntmarta.dll"},
{0x76350000, 0x45000, 0x1, "C:\\Windows\\system32\\WLDAP32.dll"},
{0x72520000, 0x116000, 0x1, "C:\\Windows\\system32\\VSSAPI.DLL"},
{0x74080000, 0x14000, 0x1, "C:\\Windows\\system32\\ATL.DLL"},
{0x72510000, 0x10000, 0x2, "C:\\Windows\\system32\\VssTrace.DLL"},
{0x745a0000, 0xf000, 0x1, "C:\\Windows\\system32\\samcli.dll"},
{0x74c90000, 0x12000, 0x1, "C:\\Windows\\system32\\SAMLIB.dll"},
{0x745c0000, 0x9000, 0x1, "C:\\Windows\\system32\\netutils.dll"},
{0x73f50000, 0x47000, 0x1, "C:\\Windows\\system32\\es.dll"},
{0x75e70000, 0x27000, 0x1, "C:\\Windows\\system32\\CFGMGR32.dll"},
{0x746d0000, 0xd000, 0x1, "C:\\Windows\\system32\\WTSAPI32.dll"},
{0x75c00000, 0x29000, 0x1, "C:\\Windows\\system32\\WINSTA.dll"},
{0x75290000, 0x17000, 0x1, "C:\\Windows\\system32\\USERENV.dll"},
{0x75b30000, 0x4c000, 0xffff, "C:\\Windows\\system32\\apphelp.dll"},
{0x75b90000, 0x5f000, 0x1, "C:\\Windows\\system32\\SXS.DLL"}}},
{1316,
{{0x00890000, 0x2b000, 0xffff, "C:\\Windows\\system32\\SearchProtocolHost.exe"},
{0x77ae0000, 0x13c000, 0xffff, "C:\\Windows\\SYSTEM32\\ntdll.dll"},
{0x76480000, 0xd4000, 0xffff, "C:\\Windows\\system32\\kernel32.dll"},
{0x75cb0000, 0x4a000, 0xffff, "C:\\Windows\\system32\\KERNELBASE.dll"},
{0x77350000, 0xa0000, 0xffff, "C:\\Windows\\system32\\ADVAPI32.dll"},
{0x779d0000, 0xac000, 0xffff, "C:\\Windows\\system32\\msvcrt.dll"},
{0x75fa0000, 0x19000, 0xffff, "C:\\Windows\\SYSTEM32\\sechost.dll"},
{0x762a0000, 0xa1000, 0xffff, "C:\\Windows\\system32\\RPCRT4.dll"},
{0x77c40000, 0xc9000, 0xffff, "C:\\Windows\\system32\\USER32.dll"},
{0x75f50000, 0x4e000, 0xffff, "C:\\Windows\\system32\\GDI32.dll"},
{0x76560000, 0xa000, 0xffff, "C:\\Windows\\system32\\LPK.dll"},
{0x77930000, 0x9d000, 0xffff, "C:\\Windows\\system32\\USP10.dll"},
{0x77670000, 0x15c000, 0xffff, "C:\\Windows\\system32\\ole32.dll"},
{0x777d0000, 0x8f000, 0xffff, "C:\\Windows\\system32\\OLEAUT32.dll"},
{0x70690000, 0x17c000, 0xffff, "C:\\Windows\\system32\\TQUERY.DLL"},
{0x772f0000, 0x57000, 0xffff, "C:\\Windows\\system32\\SHLWAPI.dll"},
{0x73d30000, 0x6000, 0xffff, "C:\\Windows\\system32\\MSSHooks.dll"},
{0x75f30000, 0x1f000, 0xffff, "C:\\Windows\\system32\\IMM32.dll"},
{0x77860000, 0xcc000, 0xffff, "C:\\Windows\\system32\\MSCTF.dll"},
{0x75b80000, 0xc000, 0x2, "C:\\Windows\\system32\\CRYPTBASE.dll"},
{0x73d10000, 0x5000, 0x20, "C:\\Windows\\system32\\Msidle.dll"},
{0x763f0000, 0x83000, 0x1, "C:\\Windows\\system32\\CLBCatQ.DLL"},
{0x75720000, 0x16000, 0x1, "C:\\Windows\\system32\\CRYPTSP.dll"},
{0x75470000, 0x3b000, 0x1, "C:\\Windows\\system32\\rsaenh.dll"},
{0x75bf0000, 0xe000, 0x1, "C:\\Windows\\system32\\RpcRtRemote.dll"},
{0x73d00000, 0xc000, 0x1, "C:\\Windows\\system32\\mssprxy.dll"},
{0x70040000, 0x55000, 0x1, "C:\\Windows\\system32\\mssph.dll"},
{0x6fe40000, 0x16000, 0x1, "C:\\Windows\\system32\\MAPI32.dll"},
{0x758b0000, 0x1b000, 0x1, "C:\\Windows\\system32\\AUTHZ.dll"},
{0x72800000, 0x21000, 0x1, "C:\\Windows\\system32\\ntmarta.dll"},
{0x76350000, 0x45000, 0x1, "C:\\Windows\\system32\\WLDAP32.dll"},
{0x766a0000, 0xc4a000, 0x3, "C:\\Windows\\system32\\SHELL32.dll"},
{0x74cd0000, 0x19e000, 0x2,
"C:\\Windows\\WinSxS\\x86_microsoft.windows.common-"
"controls_6595b64144ccf1df_6.0.7601.17514_none_"
"41e6975e2bd6f2b2\\comctl32.dll"},
{0x74b90000, 0xf5000, 0x5, "C:\\Windows\\system32\\propsys.dll"},
{0x75fc0000, 0x19d000, 0x1, "C:\\Windows\\system32\\SETUPAPI.dll"},
{0x75e70000, 0x27000, 0x4, "C:\\Windows\\system32\\CFGMGR32.dll"},
{0x75e50000, 0x12000, 0x1, "C:\\Windows\\system32\\DEVOBJ.dll"},
{0x75c30000, 0xb000, 0x1, "C:\\Windows\\system32\\profapi.dll"},
{0x71a80000, 0x70000, 0x1, "C:\\Windows\\system32\\ntshrui.dll"},
{0x75450000, 0x19000, 0x1, "C:\\Windows\\system32\\srvcli.dll"},
{0x71af0000, 0xb000, 0x1, "C:\\Windows\\system32\\cscapi.dll"},
{0x73f40000, 0xa000, 0x1, "C:\\Windows\\system32\\slc.dll"}}},
{1392,
{{0x00b70000, 0x18000, 0xffff, "C:\\Windows\\system32\\SearchFilterHost.exe"},
{0x77ae0000, 0x13c000, 0xffff, "C:\\Windows\\SYSTEM32\\ntdll.dll"},
{0x76480000, 0xd4000, 0xffff, "C:\\Windows\\system32\\kernel32.dll"},
{0x75cb0000, 0x4a000, 0xffff, "C:\\Windows\\system32\\KERNELBASE.dll"},
{0x77350000, 0xa0000, 0xffff, "C:\\Windows\\system32\\ADVAPI32.dll"},
{0x779d0000, 0xac000, 0xffff, "C:\\Windows\\system32\\msvcrt.dll"},
{0x75fa0000, 0x19000, 0xffff, "C:\\Windows\\SYSTEM32\\sechost.dll"},
{0x762a0000, 0xa1000, 0xffff, "C:\\Windows\\system32\\RPCRT4.dll"},
{0x77c40000, 0xc9000, 0xffff, "C:\\Windows\\system32\\USER32.dll"},
{0x75f50000, 0x4e000, 0xffff, "C:\\Windows\\system32\\GDI32.dll"},
{0x76560000, 0xa000, 0xffff, "C:\\Windows\\system32\\LPK.dll"},
{0x77930000, 0x9d000, 0xffff, "C:\\Windows\\system32\\USP10.dll"},
{0x77670000, 0x15c000, 0xffff, "C:\\Windows\\system32\\ole32.dll"},
{0x777d0000, 0x8f000, 0xffff, "C:\\Windows\\system32\\OLEAUT32.dll"},
{0x70690000, 0x17c000, 0xffff, "C:\\Windows\\system32\\TQUERY.DLL"},
{0x772f0000, 0x57000, 0xffff, "C:\\Windows\\system32\\SHLWAPI.dll"},
{0x75f30000, 0x1f000, 0xffff, "C:\\Windows\\system32\\IMM32.dll"},
{0x77860000, 0xcc000, 0xffff, "C:\\Windows\\system32\\MSCTF.dll"},
{0x73d30000, 0x6000, 0xffff, "C:\\Windows\\system32\\MSSHooks.dll"},
{0x6f2a0000, 0x4a000, 0xffff, "C:\\Windows\\system32\\mscoree.dll"},
{0x75b80000, 0xc000, 0x2, "C:\\Windows\\system32\\CRYPTBASE.dll"},
{0x763f0000, 0x83000, 0x1, "C:\\Windows\\system32\\CLBCatQ.DLL"},
{0x75720000, 0x16000, 0x1, "C:\\Windows\\system32\\CRYPTSP.dll"},
{0x75470000, 0x3b000, 0x1, "C:\\Windows\\system32\\rsaenh.dll"},
{0x75bf0000, 0xe000, 0x1, "C:\\Windows\\system32\\RpcRtRemote.dll"},
{0x73d00000, 0xc000, 0x1, "C:\\Windows\\system32\\mssprxy.dll"}}},
{1100,
{{0x10000000, 0x11000, 0xffff,
"C:\\Windows\\Microsoft.NET\\Framework\\v2.0.50727\\mscorsvw.exe"},
{0x77ae0000, 0x13c000, 0xffff, "C:\\Windows\\SYSTEM32\\ntdll.dll"},
{0x76480000, 0xd4000, 0xffff, "C:\\Windows\\system32\\kernel32.dll"},
{0x75cb0000, 0x4a000, 0xffff, "C:\\Windows\\system32\\KERNELBASE.dll"},
{0x6f2a0000, 0x4a000, 0xffff, "C:\\Windows\\system32\\mscoree.dll"},
{0x6f8c0000, 0x9b000, 0xffff,
"C:\\Windows\\WinSxS\\x86_microsoft.vc80.crt_"
"1fc8b3b9a1e18e3b_8.0.50727.4940_none_"
"d08cc06a442b34fc\\MSVCR80.dll"},
{0x779d0000, 0xac000, 0xffff, "C:\\Windows\\system32\\msvcrt.dll"},
{0x77350000, 0xa0000, 0xffff, "C:\\Windows\\system32\\ADVAPI32.dll"},
{0x75fa0000, 0x19000, 0xffff, "C:\\Windows\\SYSTEM32\\sechost.dll"},
{0x762a0000, 0xa1000, 0xffff, "C:\\Windows\\system32\\RPCRT4.dll"},
{0x77c40000, 0xc9000, 0xffff, "C:\\Windows\\system32\\USER32.dll"},
{0x75f50000, 0x4e000, 0xffff, "C:\\Windows\\system32\\GDI32.dll"},
{0x76560000, 0xa000, 0xffff, "C:\\Windows\\system32\\LPK.dll"},
{0x77930000, 0x9d000, 0xffff, "C:\\Windows\\system32\\USP10.dll"},
{0x77670000, 0x15c000, 0xffff, "C:\\Windows\\system32\\ole32.dll"},
{0x777d0000, 0x8f000, 0xffff, "C:\\Windows\\system32\\OLEAUT32.dll"},
{0x75f30000, 0x1f000, 0x2, "C:\\Windows\\system32\\IMM32.DLL"},
{0x77860000, 0xcc000, 0x1, "C:\\Windows\\system32\\MSCTF.dll"},
{0x64050000, 0x3a000, 0x1,
"C:\\Windows\\Microsoft.NET\\Framework\\v2.0.50727\\mscorsvc.dll"},
{0x75b80000, 0xc000, 0x1, "C:\\Windows\\system32\\CRYPTBASE.dll"},
{0x772f0000, 0x57000, 0x1, "C:\\Windows\\system32\\SHLWAPI.dll"},
{0x73d10000, 0x5000, 0x1, "C:\\Windows\\system32\\msidle.dll"},
{0x746d0000, 0xd000, 0x3, "C:\\Windows\\system32\\Wtsapi32.dll"},
{0x75c00000, 0x29000, 0x1, "C:\\Windows\\system32\\WINSTA.dll"},
{0x74330000, 0x25000, 0x1, "C:\\Windows\\system32\\powrprof.dll"},
{0x75fc0000, 0x19d000, 0x1, "C:\\Windows\\system32\\SETUPAPI.dll"},
{0x75e70000, 0x27000, 0x4, "C:\\Windows\\system32\\CFGMGR32.dll"},
{0x75e50000, 0x12000, 0x1, "C:\\Windows\\system32\\DEVOBJ.dll"}}},
{184,
{{0x00430000, 0x30b000, 0xffff, "C:\\Windows\\system32\\sppsvc.exe"},
{0x77ae0000, 0x13c000, 0xffff, "C:\\Windows\\SYSTEM32\\ntdll.dll"},
{0x76480000, 0xd4000, 0xffff, "C:\\Windows\\system32\\kernel32.dll"},
{0x75cb0000, 0x4a000, 0xffff, "C:\\Windows\\system32\\KERNELBASE.dll"},
{0x77350000, 0xa0000, 0xffff, "C:\\Windows\\system32\\ADVAPI32.dll"},
{0x779d0000, 0xac000, 0xffff, "C:\\Windows\\system32\\msvcrt.dll"},
{0x75fa0000, 0x19000, 0xffff, "C:\\Windows\\SYSTEM32\\sechost.dll"},
{0x762a0000, 0xa1000, 0xffff, "C:\\Windows\\system32\\RPCRT4.dll"},
{0x77670000, 0x15c000, 0xffff, "C:\\Windows\\system32\\ole32.dll"},
{0x75f50000, 0x4e000, 0xffff, "C:\\Windows\\system32\\GDI32.dll"},
{0x77c40000, 0xc9000, 0xffff, "C:\\Windows\\system32\\USER32.dll"},
{0x76560000, 0xa000, 0xffff, "C:\\Windows\\system32\\LPK.dll"},
{0x77930000, 0x9d000, 0xffff, "C:\\Windows\\system32\\USP10.dll"},
{0x75f30000, 0x1f000, 0x2, "C:\\Windows\\system32\\IMM32.DLL"},
{0x77860000, 0xcc000, 0x1, "C:\\Windows\\system32\\MSCTF.dll"},
{0x75b80000, 0xc000, 0x2, "C:\\Windows\\system32\\CRYPTBASE.dll"},
{0x75bf0000, 0xe000, 0x1, "C:\\Windows\\system32\\RpcRtRemote.dll"},
{0x75720000, 0x16000, 0x1, "C:\\Windows\\system32\\CRYPTSP.dll"},
{0x75470000, 0x3b000, 0x1, "C:\\Windows\\system32\\rsaenh.dll"}}},
{1072,
{{0x00dd0000, 0x8000, 0xffff, "C:\\Windows\\System32\\svchost.exe"},
{0x77ae0000, 0x13c000, 0xffff, "C:\\Windows\\SYSTEM32\\ntdll.dll"},
{0x76480000, 0xd4000, 0xffff, "C:\\Windows\\system32\\kernel32.dll"},
{0x75cb0000, 0x4a000, 0xffff, "C:\\Windows\\system32\\KERNELBASE.dll"},
{0x779d0000, 0xac000, 0xffff, "C:\\Windows\\system32\\msvcrt.dll"},
{0x75fa0000, 0x19000, 0xffff, "C:\\Windows\\SYSTEM32\\sechost.dll"},
{0x762a0000, 0xa1000, 0xffff, "C:\\Windows\\system32\\RPCRT4.dll"},
{0x6f450000, 0xa9000, 0x1, "c:\\program files\\windows defender\\mpsvc.dll"},
{0x77350000, 0xa0000, 0x7, "C:\\Windows\\system32\\ADVAPI32.dll"},
{0x77670000, 0x15c000, 0x4, "C:\\Windows\\system32\\ole32.dll"},
{0x75f50000, 0x4e000, 0x17, "C:\\Windows\\system32\\GDI32.dll"},
{0x77c40000, 0xc9000, 0x18, "C:\\Windows\\system32\\USER32.dll"},
{0x76560000, 0xa000, 0x5, "C:\\Windows\\system32\\LPK.dll"},
{0x77930000, 0x9d000, 0x5, "C:\\Windows\\system32\\USP10.dll"},
{0x746d0000, 0xd000, 0x1, "C:\\Windows\\system32\\WTSAPI32.dll"},
{0x70d90000, 0x3000, 0x1, "C:\\Windows\\system32\\sfc.dll"},
{0x70d70000, 0xd000, 0x1, "C:\\Windows\\system32\\sfc_os.DLL"},
{0x6f3e0000, 0x63000, 0x1, "c:\\program files\\windows defender\\MpClient.dll"},
{0x777d0000, 0x8f000, 0x2, "C:\\Windows\\system32\\OLEAUT32.dll"},
{0x75290000, 0x17000, 0x2, "C:\\Windows\\system32\\USERENV.dll"},
{0x75c30000, 0xb000, 0x3, "C:\\Windows\\system32\\profapi.dll"},
{0x75e20000, 0x2d000, 0x2, "C:\\Windows\\system32\\WINTRUST.dll"},
{0x75d00000, 0x11d000, 0x4, "C:\\Windows\\system32\\CRYPT32.dll"},
{0x75ca0000, 0xc000, 0x6, "C:\\Windows\\system32\\MSASN1.dll"},
{0x75130000, 0x9000, 0x2, "C:\\Windows\\system32\\VERSION.dll"},
{0x766a0000, 0xc4a000, 0x1, "C:\\Windows\\system32\\SHELL32.dll"},
{0x772f0000, 0x57000, 0x1, "C:\\Windows\\system32\\SHLWAPI.dll"},
{0x75f30000, 0x1f000, 0x2, "C:\\Windows\\system32\\IMM32.DLL"},
{0x77860000, 0xcc000, 0x1, "C:\\Windows\\system32\\MSCTF.dll"},
{0x75270000, 0x16000, 0x4, "C:\\Windows\\System32\\GPAPI.dll"},
{0x75720000, 0x16000, 0x3, "C:\\Windows\\System32\\CRYPTSP.dll"},
{0x75470000, 0x3b000, 0x1, "C:\\Windows\\system32\\rsaenh.dll"},
{0x75b80000, 0xc000, 0x1, "C:\\Windows\\System32\\CRYPTBASE.dll"},
{0x76670000, 0x2a000, 0x1, "C:\\Windows\\system32\\imagehlp.dll"},
{0x75850000, 0x17000, 0x9, "C:\\Windows\\System32\\bcrypt.dll"},
{0x753b0000, 0x3d000, 0x1, "C:\\Windows\\system32\\bcryptprimitives.dll"},
{0x75870000, 0x38000, 0x1, "C:\\Windows\\System32\\ncrypt.dll"}}}};
bool find_match(struct WindowsModuleEntry* me, std::vector<struct ModuleInfo>& mi)
{
uint64_t base_addr = module_entry_get_base_address(me);
for (auto& entry : mi) {
if (base_addr == entry.base) {
EXPECT_EQ(module_entry_get_modulesize(me), entry.size)
<< "ModuleSize mismatch";
EXPECT_EQ(module_entry_get_loadcount(me), entry.loadcount)
<< "LoadCount mismatch";
EXPECT_EQ(std::string(module_entry_get_dllpath(me)), entry.path)
<< "dllpath mismatch at address " << module_entry_get_base_address(me);
return true;
}
}
return false;
}
void handle_proces_modlist(struct WindowsKernelOSI* wintro, struct WindowsProcess* p)
{
auto pid = process_get_pid(p);
auto candidate = EXPECTED_RESULTS.find(pid);
ASSERT_TRUE(candidate != EXPECTED_RESULTS.end()) << "Failed to find PID";
auto& entry = candidate->second;
uint32_t module_count = 0;
auto modlist = get_module_list(wintro, process_get_eprocess(p), process_is_wow64(p));
if (modlist) {
auto me = module_list_next(modlist);
while (me) {
EXPECT_TRUE(find_match(me, entry))
<< "Did not find a match for " << module_entry_get_base_address(me);
module_count++;
free_module_entry(me);
me = module_list_next(modlist);
}
} else {
ASSERT_TRUE(entry.size() == 0)
<< "Didn't find a module list where one was expected.";
}
fprintf(stderr, "%u vs %lu\n", module_count, entry.size());
ASSERT_EQ(module_count, entry.size())
<< "Found an unexpected number of modules for PID: " << pid;
free_module_list(modlist);
}
TEST(Testi386Plist, Win7SP1i386)
{
ASSERT_TRUE(testfile) << "Couldn't load input test file!";
ASSERT_TRUE(access(testfile, R_OK) == 0) << "Could not read input file";
WindowsKernelManager manager = WindowsKernelManager("windows-32-7sp1");
auto pmem = load_physical_memory_snapshot(testfile);
ASSERT_TRUE(pmem != nullptr) << "failed to load physical memory snapshot";
struct WindowsKernelOSI* kosi = manager.get_kernel_object();
ASSERT_TRUE(manager.initialize(pmem, 4, 0x185000, 0x82933c00))
<< "Failed to initialize kernel osi";
auto plist = get_process_list(kosi);
ASSERT_TRUE(plist != nullptr) << "Failed to get process list";
for (unsigned int ix = 0; ix < EXPECTED_RESULTS.size(); ++ix) {
auto process = process_list_next(plist);
ASSERT_TRUE(process != nullptr) << "Didn't find enough processes";
handle_proces_modlist(kosi, process);
free_process(process);
}
ASSERT_TRUE(process_list_next(plist) == nullptr) << "Found too many processes";
free_process_list(plist);
pmem->free(pmem);
}
int main(int argc, char** argv)
{
::testing::InitGoogleTest(&argc, argv);
if (argc != 2) {
fprintf(stderr, "usage: %s i386.raw\n", argv[0]);
return 3;
}
testfile = argv[1];
return RUN_ALL_TESTS();
}
| 67.786216 | 89 | 0.637285 | [
"vector"
] |
14d2cd76cffe16b565b5f4ec0b6103aa816a4da6 | 3,518 | cpp | C++ | Hazel/src/Hazel/Renderer/Renderer.cpp | diplodocus33/Hazel | 609d105946ae04a747cb0f2813d796a1ad3d03f4 | [
"Apache-2.0"
] | null | null | null | Hazel/src/Hazel/Renderer/Renderer.cpp | diplodocus33/Hazel | 609d105946ae04a747cb0f2813d796a1ad3d03f4 | [
"Apache-2.0"
] | null | null | null | Hazel/src/Hazel/Renderer/Renderer.cpp | diplodocus33/Hazel | 609d105946ae04a747cb0f2813d796a1ad3d03f4 | [
"Apache-2.0"
] | null | null | null | #include "hzpch.h"
#include "Renderer.h"
#include "Platform/OpenGL/OpenGLShader.h"
#include "Renderer2D.h"
#include "glm/gtc/matrix_transform.hpp"
namespace Hazel {
Ref<VertexArray> Renderer::s_VertexArray;
ShaderLibrary Renderer::s_ShaderLibrary;
Renderer::SceneData* Renderer::s_SceneData = new Renderer::SceneData;
void Renderer::Init()
{
HZ_PROFILE_FUNCTION();
RenderCommand::Init();
Renderer2D::Init();
s_VertexArray = Hazel::VertexArray::Create();
float vertecies[] = {
-1.0f, -1.0f, -1.0f, // 0 front bottom left
1.0f, -1.0f, -1.0f, // 1 front bottom right
1.0f, 1.0f, -1.0f, // 2 front top right
-1.0f, 1.0f, -1.0f, // 3 front top left
-1.0f, -1.0f, 1.0f, // 4 rear bottom left
1.0f, -1.0f, 1.0f, // 5 rear bottom right
1.0f, 1.0f, 1.0f, // 6 rear top right
-1.0f, 1.0f, 1.0f // 7 rear top left
};
auto vertexBuffer = Hazel::VertexBuffer::Create(vertecies, sizeof(vertecies));
vertexBuffer->SetLayout({
{Hazel::ShaderDataType::Float3, "a_Position"}
});
s_VertexArray->AddVertexBuffer(vertexBuffer);
uint32_t indices[36] = {
0, 1, 2, 2, 3, 0, // front
4, 5, 6, 6, 7, 4, // rear
2, 3, 6, 6, 7, 3, // top
1, 0, 5, 5, 4, 0, // bottom
0, 3, 4, 4, 7, 3, // left
1, 2, 5, 5, 6, 2 // right
};
auto indexBuffer = Hazel::IndexBuffer::Create(indices, sizeof(indices) / sizeof(uint32_t));
s_VertexArray->SetIndexBuffer(indexBuffer);
s_ShaderLibrary.Load("assets/shaders/VertexPos.glsl");
s_ShaderLibrary.Load("assets/shaders/Skybox.glsl");
s_ShaderLibrary.Load("assets/shaders/Textured3D.glsl");
}
void Renderer::OnWindowResize(uint32_t width, uint32_t height)
{
RenderCommand::SetViewport(0, 0, width, height);
}
void Renderer::BeginScene(const PerspectiveCamera& camera)
{
s_SceneData->ProjectionViewMatrix = camera.GetProjectionViewMatrix();
s_SceneData->ProjectionMatrix = camera.GetProjectionMatrix();
s_SceneData->ViewMatrix = camera.GetViewMatrix();
}
void Renderer::EndScene()
{
DrawSkybox(s_SceneData->Skybox);
}
void Renderer::Submit(const Ref<Shader>& shader, const Ref<VertexArray>& vertexArray, const glm::mat4 transform)
{
shader->Bind();
shader->SetMat4("u_ProjectionView", s_SceneData->ProjectionViewMatrix);
shader->SetMat4("u_Transform", transform);
vertexArray->Bind();
RenderCommand::DrawIndexed(vertexArray);
}
void Renderer::DrawColoredCube(const glm::vec3& position, const glm::vec4& color, const glm::vec3& size)
{
auto shader = s_ShaderLibrary.Get("VertexPos");
shader->Bind();
shader->SetFloat4("u_Color", color);
// T * S
auto tranform = glm::translate(glm::mat4(1.0f), position) * glm::scale(glm::mat4(1.0f), size);
Submit(shader, s_VertexArray, tranform);
}
void Renderer::DrawTexturedCube(const glm::vec3& position, const Ref<TextureCubeMap>& texture, const glm::vec3& size)
{
texture->Bind(0);
glm::mat4 transform = glm::translate(glm::mat4(1.0f), position);
Submit(s_ShaderLibrary.Get("Textured3D"), s_VertexArray, transform);
}
void Renderer::DrawSkybox(const Ref<TextureCubeMap>& texture)
{
RenderCommand::SetDepthFuncLessThanOrEqualTo();
auto shader = s_ShaderLibrary.Get("Skybox");
shader->Bind();
shader->SetMat4("u_Projection", s_SceneData->ProjectionMatrix);
shader->SetMat4("u_View", glm::mat4(glm::mat3(s_SceneData->ViewMatrix)));
s_VertexArray->Bind();
texture->Bind();
RenderCommand::DrawIndexed(s_VertexArray);
RenderCommand::SetDepthFuncLessThan();
}
} | 30.068376 | 118 | 0.687891 | [
"transform"
] |
14d3343b616e1f821dfed81aa00d0fed7c52fedb | 10,101 | cpp | C++ | src/world.cpp | tcosmo/cqca | 47dcbf439a9e6658d8e055f584372d096683a196 | [
"MIT"
] | 3 | 2020-06-26T21:34:20.000Z | 2021-08-03T08:11:24.000Z | src/world.cpp | tcosmo/cqca | 47dcbf439a9e6658d8e055f584372d096683a196 | [
"MIT"
] | null | null | null | src/world.cpp | tcosmo/cqca | 47dcbf439a9e6658d8e055f584372d096683a196 | [
"MIT"
] | null | null | null | #include "world.h"
std::vector<CellPosAndCell> World::findCarryPropUpdates() {
std::vector<CellPosAndCell> toRet;
for (const sf::Vector2i &cellPos : cellsOnEdge) {
assert(doesCellExists(cellPos));
if (cells[cellPos].getStatus() != HALF_DEFINED)
continue;
if (doesCellExists(cellPos + EAST) &&
cells[cellPos + EAST].getStatus() == DEFINED) {
AtomicInfo bit = cells[cellPos].bit;
AtomicInfo newCarry =
static_cast<AtomicInfo>((bit + cells[cellPos + EAST].sum()) >= 2);
Cell updatedCell = Cell(bit, newCarry);
toRet.push_back(std::make_pair(cellPos, updatedCell));
// Because we do a finite simulation of an infinite process
// we have some edge cases to deal with.
manageEdgeCases(toRet, cellPos, updatedCell);
}
}
return toRet;
}
std::vector<CellPosAndCell> World::findForwardDeductionUpdates() {
std::vector<CellPosAndCell> toRet;
for (const sf::Vector2i &cellPos : cellsOnEdge) {
assert(doesCellExists(cellPos) &&
cells[cellPos].getStatus() == HALF_DEFINED);
if (doesCellExists(cellPos + EAST) &&
cells[cellPos + EAST].getStatus() == DEFINED) {
AtomicInfo southBit = static_cast<AtomicInfo>(
(static_cast<int>(cells[cellPos].bit) + cells[cellPos + EAST].sum()) %
2);
toRet.push_back(std::make_pair(cellPos + SOUTH, Cell(southBit, UNDEF)));
}
}
return toRet;
}
std::vector<CellPosAndCell> World::findBackwardDeductionUpdates() {
std::vector<CellPosAndCell> toRet;
for (const sf::Vector2i &cellPos : cellsOnEdge) {
assert(doesCellExists(cellPos));
if (!doesCellExists(cellPos + NORTH) &&
doesCellExists(cellPos + NORTH + EAST) &&
cells[cellPos + NORTH + EAST].getStatus() == DEFINED) {
AtomicInfo northBit =
static_cast<AtomicInfo>((cells[cellPos + NORTH + EAST].sum()) % 2 !=
static_cast<int>(cells[cellPos].bit));
toRet.push_back(std::make_pair(cellPos + NORTH, Cell(northBit, UNDEF)));
}
}
return toRet;
}
void World::cleanCellsOnEdge() {
/**
* Remove the cells which are not anymore on edge from the edge.
*/
std::vector<sf::Vector2i> toRemove;
for (const auto &cellPos : cellsOnEdge)
if (!isCellOnEdge(cellPos))
toRemove.push_back(cellPos);
for (const auto &cellPos : toRemove)
cellsOnEdge.erase(cellPos);
}
bool World::isCellOnEdge(const sf::Vector2i &cellPos) {
/**
* Determines whether a cell is on the edge of the computing region or not.
*/
if (!doesCellExists(cellPos))
return false;
if (inputType == LINE || inputType == COL) {
if (cells[cellPos].getStatus() == DEFINED)
return false;
if (inputType == LINE &&
(cellPos.y == 0 && doesCellExists(cellPos + EAST) &&
cells[cellPos + EAST].getStatus() == HALF_DEFINED))
return false;
// Remove trailing 0s from edge
bool isTrailingZero = true;
if (cells[cellPos].bit == ZERO && doesCellExists(cellPos + WEST) &&
cells[cellPos + WEST].getStatus() == HALF_DEFINED) {
sf::Vector2i pos = cellPos + EAST;
while (doesCellExists(pos)) {
if (cells[pos].bit == ONE)
isTrailingZero = false;
pos += EAST;
}
} else {
isTrailingZero = false;
}
return cells[cellPos].getStatus() == HALF_DEFINED && !isTrailingZero;
}
if (inputType == BORDER || inputType == CYCLE) {
if ((inputType == BORDER || (inputType == CYCLE && constructCycleInLine)) &&
cellPos.y == ORIGIN_BORDER_MODE.y)
return cells[cellPos].getStatus() == HALF_DEFINED;
return !doesCellExists(cellPos + NORTH);
}
return false;
}
void World::applyUpdates(const std::vector<CellPosAndCell> &updates) {
for (const auto &info : updates) {
const sf::Vector2i &cellPos = info.first;
const Cell &cell = info.second;
cells[cellPos] = cell;
cellGraphicBuffer.push_back(cellPos);
if (isCellOnEdge(cellPos))
cellsOnEdge.insert(cellPos);
if (inputType == LINE || inputType == COL)
if (isCellOnEdge(cellPos + WEST))
cellsOnEdge.insert(cellPos + WEST);
}
cleanCellsOnEdge();
}
void World::nextLocal() {
/**
* Applies one pass of the local rule.
*/
// In LINE and COL mode, the local rule is
// carry propagation followed by forward deduction
if (inputType == LINE || inputType == COL) {
// First find the update then apply them
// Do not apply some updates before they were all found
// That would break the CA logic
auto carryPropUpdates = findCarryPropUpdates();
auto forwardDeductionUpdates = findForwardDeductionUpdates();
applyUpdates(carryPropUpdates);
applyUpdates(forwardDeductionUpdates);
}
// In BORDER/CYCLE mode, the local rule is
// carry propagation followed by backward deduction
if (inputType == BORDER || inputType == CYCLE) {
auto carryPropUpdates = findCarryPropUpdates();
auto backwardDeductionUpdates = findBackwardDeductionUpdates();
applyUpdates(carryPropUpdates);
applyUpdates(backwardDeductionUpdates);
// In cycle mode we need to enforce the equivalence relation on
// cells of the world in order to compute
if (inputType == CYCLE) {
auto cyclicUpdates = findCyclicUpdates(carryPropUpdates);
applyUpdates(cyclicUpdates);
cyclicUpdates = findCyclicUpdates(backwardDeductionUpdates);
applyUpdates(cyclicUpdates);
}
// Tweak to get the right amount of 0s on the south
// Deprecated
// auto tweakUpdates = findTweakSouthBorderUpdates();
// applyUpdates(tweakUpdates);
}
}
void World::next() {
nextNonLocal();
nextLocal();
}
std::vector<CellPosAndCell> World::findNonLocalUpdates() {
/**
* Finding candidate cells for applying the non-local rule of the 2D CQCA.
*/
std::vector<CellPosAndCell> toRet;
for (const sf::Vector2i &cellPos : cellsOnEdge) {
if (inputType == CYCLE && !constructCycleInLine)
if (cellPos.x == ORIGIN_BORDER_MODE.x)
continue;
assert(doesCellExists(cellPos));
// Detect if bootstrapping needed
if (cells[cellPos].bit == ONE) {
bool lastOneOnLine = true;
sf::Vector2i currPos = cellPos + EAST;
while (doesCellExists(currPos)) {
if (cells[currPos].bit == ONE)
lastOneOnLine = false;
currPos += EAST;
}
if (lastOneOnLine) {
if (!doesCellExists(cellPos + EAST) ||
cells[cellPos + EAST].getStatus() == HALF_DEFINED) {
toRet.push_back(
std::make_pair(cellPos + EAST, Cell(ZERO, ONE, true)));
if (inputType == CYCLE &&
doesCellExists(cellPos + EAST + cyclicForwardVector))
toRet.push_back(std::make_pair(cellPos + EAST + cyclicForwardVector,
Cell(ZERO, ONE, true)));
sf::Vector2i newPos = cellPos + EAST + EAST;
while (doesCellExists(newPos)) {
toRet.push_back(std::make_pair(newPos, Cell(ZERO, ZERO)));
if (inputType == CYCLE &&
doesCellExists(newPos + cyclicForwardVector))
toRet.push_back(std::make_pair(newPos + cyclicForwardVector,
Cell(ZERO, ZERO)));
newPos += EAST;
}
if (inputType == CYCLE) {
while (doesCellExists(newPos + cyclicForwardVector)) {
toRet.push_back(std::make_pair(newPos + cyclicForwardVector,
Cell(ZERO, ZERO)));
newPos += EAST;
}
}
}
}
}
}
return toRet;
}
void World::nextNonLocal() {
auto nonLocalUpdates = findNonLocalUpdates();
applyUpdates(nonLocalUpdates);
if (inputType == CYCLE) {
auto cyclicUpdates = findCyclicUpdates(nonLocalUpdates);
applyUpdates(cyclicUpdates);
}
}
bool World::doesCellExists(const sf::Vector2i &cellPos) {
return cells.find(cellPos) != cells.end();
}
std::vector<sf::Vector2i> World::getAndFlushGraphicBuffer() {
std::vector<sf::Vector2i> toRet = cellGraphicBuffer;
cellGraphicBuffer.clear();
return toRet;
}
std::vector<int> World::base3To3p(std::string base3) {
/***
* Base 3 to base 3' conversion. See paper for more details.
*/
std::reverse(base3.begin(), base3.end());
std::vector<int> toReturn;
bool lastSeenZero = true;
int i = 0;
for (char c : base3) {
switch (c) {
case '0':
toReturn.push_back(0);
lastSeenZero = true;
break;
case '1':
if (lastSeenZero)
toReturn.push_back(1);
else
toReturn.push_back(2);
break;
case '2':
toReturn.push_back(3);
lastSeenZero = false;
break;
default:
printf("Character `%c` is invalid base 3 digit. Abort.\n", c);
exit(1);
break;
}
i += 1;
}
std::reverse(toReturn.begin(), toReturn.end());
return toReturn;
}
void World::setInputCells() {
switch (inputType) {
case NONE:
printf("Cannot input nothing to the world, you probably used a wrong "
"command line argument. Abort. Please run `./simcqca --help` for "
"help.\n");
exit(0);
break;
case LINE:
setInputCellsLine();
break;
case COL:
setInputCellsCol();
break;
case BORDER:
setInputCellsBorder();
break;
case CYCLE:
setInputCellsCycle();
break;
default:
printf("Not implemented yet. Abort.\n");
exit(0);
break;
}
}
void World::reset() {
cells.clear();
cellsOnEdge.clear();
cellGraphicBuffer.clear();
parityVectorCells.clear();
setInputCells();
}
std::string rotateStr(std::string toRotate, int offset) {
std::string toRet = toRotate;
for (int i = 0; i < toRotate.size(); i += 1)
toRet[i] = toRotate[(toRotate.size() + offset + i) % (toRotate.size())];
return toRet;
}
void World::rotate(int direction) {
/**
* In cycle mode rotates the input parity vector.
*/
assert(inputType == CYCLE || inputType == BORDER);
inputStr = rotateStr(inputStr, direction);
reset();
} | 29.025862 | 80 | 0.626968 | [
"vector"
] |
14d98dd5ad0068709ba85945fff4ad32b593d09d | 6,750 | ipp | C++ | code/contrafold/src/LBFGS.ipp | jialiasus2/RNA-Contest-2021 | d8cd340061ac7a70e1c2bba67d36c89cbde2555c | [
"Apache-2.0"
] | null | null | null | code/contrafold/src/LBFGS.ipp | jialiasus2/RNA-Contest-2021 | d8cd340061ac7a70e1c2bba67d36c89cbde2555c | [
"Apache-2.0"
] | null | null | null | code/contrafold/src/LBFGS.ipp | jialiasus2/RNA-Contest-2021 | d8cd340061ac7a70e1c2bba67d36c89cbde2555c | [
"Apache-2.0"
] | null | null | null | //////////////////////////////////////////////////////////////////////
// LBFGS.ipp
//
// This file contains an implementation of the standard
// limited-memory BFGS optimization algorithm.
//////////////////////////////////////////////////////////////////////
//////////////////////////////////////////////////////////////////////
// LBFGS::LBFGS()
//
// Constructor.
//////////////////////////////////////////////////////////////////////
template<class Real>
LBFGS<Real>::LBFGS
(
const int M, // number of previous gradients to remember
const Real TERMINATION_RATIO, // required ratio of gradient norm to parameter norm for termination
const int MAX_ITERATIONS, // maximum number of iterations to run L-BFGS
const Real SMALL_STEP_RATIO, // ratio beneath which steps are considered "small"
const int MAX_SMALL_STEPS, // maximum number of small steps before we quit
const Real MAX_STEP_NORM // maximum norm for a single step
) :
LineSearch<Real>(),
M(M),
TERMINATION_RATIO(TERMINATION_RATIO),
MAX_ITERATIONS(MAX_ITERATIONS),
SMALL_STEP_RATIO(SMALL_STEP_RATIO),
MAX_SMALL_STEPS(MAX_SMALL_STEPS),
MAX_STEP_NORM(MAX_STEP_NORM)
{}
//////////////////////////////////////////////////////////////////////
// LBFGS::Minimize()
//
// Implementation of L-BFGS optimization routine.
//////////////////////////////////////////////////////////////////////
template<class Real>
Real LBFGS<Real>::Minimize(std::vector<Real> &x0)
{
// initialize
const int n = int(x0.size());
std::vector<Real> f(2);
std::vector<Real> gamma(2);
std::vector<std::vector<Real> > x(2, std::vector<Real>(n));
std::vector<std::vector<Real> > g(2, std::vector<Real>(n));
std::vector<std::vector<Real> > s(M, std::vector<Real>(n));
std::vector<std::vector<Real> > y(M, std::vector<Real>(n));
std::vector<Real> rho(M);
Real gradient_ratio;
Real f0;
// check for termination criteria at beginning
x[0] = x0;
f[0] = f0 = ComputeFunction(x[0]);
if (f[0] > Real(1e20))
{
Report(SPrintF("Termination before optimization: function value too big (%lf > %lf)", f[0], 1e20));
return f[0];
}
ComputeGradient(g[0], x[0]);
gradient_ratio = Norm(g[0]) / std::max(Real(1), Norm(x[0]));
if (gradient_ratio < TERMINATION_RATIO)
{
Report(SPrintF("Termination before optimization: gradient vector small (%lf < %lf)", gradient_ratio, TERMINATION_RATIO));
return f[0];
}
// initial scaling
gamma[0] = Real(1) / Norm(g[0]);
// report initial iteration
Report(0, x[0], f[0], 0);
// main loop
bool progress_made = false;
int num_consecutive_small_steps = 0;
int k = 0;
while (true)
{
// compute search direction, d = -H[k] g[k]
std::vector<Real> d(-g[k%2]);
std::vector<Real> a(M);
for (int i = k-1; i >= k-M; i--)
{
a[(i+M)%M] = rho[(i+M)%M] * DotProduct(s[(i+M)%M], d);
d -= a[(i+M)%M] * y[(i+M)%M];
}
d *= gamma[k%2];
for (int i = k-M; i <= k-1; i++)
{
Real b = rho[(i+M)%M] * DotProduct(y[(i+M)%M], d);
d += (a[(i+M)%M] - b) * s[(i+M)%M];
}
// perform line search, update f, and take step
Real step = this->DoLineSearch(x[k%2], f[k%2], g[k%2], d,
x[(k+1)%2], f[(k+1)%2], g[(k+1)%2],
Real(0), std::min(Real(10), MAX_STEP_NORM / std::max(Real(1), Norm(d))));
Report(k+1, x[(k+1)%2], f[(k+1)%2], step);
// check termination conditions
if (k+1 >= MAX_ITERATIONS)
{
Report("Termination condition: maximum number of iterations reached");
break;
}
// check gradient termination condition
gradient_ratio = Norm(g[(k+1)%2]) / std::max(Real(1), Norm(x[(k+1)%2]));
if (gradient_ratio < TERMINATION_RATIO)
{
Report(SPrintF("Termination condition: gradient vector small (%lf < %lf)", gradient_ratio, TERMINATION_RATIO));
break;
}
// heuristics for detecting slow progress (needed for large-scale
// problems due to floating-point precision problems in gradient
// computation)
// check for slow progress
if (step == Real(0))
num_consecutive_small_steps = MAX_SMALL_STEPS;
else if ((f[k%2] - f[(k+1)%2]) / std::max(Real(1), f0 - f[(k+1)%2]) < SMALL_STEP_RATIO)
num_consecutive_small_steps++;
else
{
num_consecutive_small_steps = 0;
progress_made = true;
}
// if we're making slow progress
if (num_consecutive_small_steps == MAX_SMALL_STEPS)
{
// give us a second chance if we made some
// progress since the last restart
if (M > 0 && progress_made)
{
progress_made = false;
num_consecutive_small_steps = 0;
Report("Restart: Too many consecutive small steps");
for (int i = 0; i < M; i++)
{
std::fill(s[i].begin(), s[i].end(), Real(0));
std::fill(y[i].begin(), y[i].end(), Real(0));
rho[i] = Real(0);
}
}
else
{
Report("Termination: Too many consecutive small steps");
break;
}
}
// update iterates
s[k%M] = x[(k+1)%2] - x[k%2];
y[k%M] = g[(k+1)%2] - g[k%2];
rho[k%M] = Real(1) / DotProduct(y[k%M], s[k%M]);
// skip update if non-positive-definite Hessian update
// (setting all of these quantities to zero is equivalent
// to skipping the update, based on the BFGS recursions)
if (!std::isfinite(rho[k%M]) || rho[k%M] <= Real(0))
{
std::fill(s[k%M].begin(), s[k%M].end(), Real(0));
std::fill(y[k%M].begin(), y[k%M].end(), Real(0));
rho[k%M] = Real(0);
}
// update scaling factor
gamma[(k+1)%2] = DotProduct(s[(k-1+M)%M], y[(k-1+M)%M]) / DotProduct(y[(k-1+M)%M], y[(k-1+M)%M]);
if (!std::isfinite(gamma[(k+1)%2]))
{
gamma[(k+1)%2] = gamma[k%2];
}
++k;
}
x0 = x[(k+1)%2];
return f[(k+1)%2];
}
| 32.451923 | 129 | 0.473185 | [
"vector"
] |
14d9fc18ed19e421932ab204633f0a790ed3e065 | 14,378 | cpp | C++ | 3rdparty/wxWidgets/src/msw/calctrl.cpp | mikiec84/winsparkle | e73db4ddb3be830b36b58e2f90f4bee6a0c684b7 | [
"MIT"
] | 2 | 2015-01-10T09:15:16.000Z | 2018-01-03T21:21:46.000Z | 3rdparty/wxWidgets/src/msw/calctrl.cpp | mikiec84/winsparkle | e73db4ddb3be830b36b58e2f90f4bee6a0c684b7 | [
"MIT"
] | null | null | null | 3rdparty/wxWidgets/src/msw/calctrl.cpp | mikiec84/winsparkle | e73db4ddb3be830b36b58e2f90f4bee6a0c684b7 | [
"MIT"
] | 1 | 2019-01-20T12:55:33.000Z | 2019-01-20T12:55:33.000Z | /////////////////////////////////////////////////////////////////////////////
// Name: src/msw/calctrl.cpp
// Purpose: wxCalendarCtrl implementation
// Author: Vadim Zeitlin
// Created: 2008-04-04
// RCS-ID: $Id: calctrl.cpp 61724 2009-08-21 10:41:26Z VZ $
// Copyright: (C) 2008 Vadim Zeitlin <vadim@wxwidgets.org>
// Licence: wxWindows licence
/////////////////////////////////////////////////////////////////////////////
// ============================================================================
// declarations
// ============================================================================
// ----------------------------------------------------------------------------
// headers
// ----------------------------------------------------------------------------
#include "wx/wxprec.h"
#ifdef __BORLANDC__
#pragma hdrstop
#endif
#if wxUSE_CALENDARCTRL
#ifndef WX_PRECOMP
#include "wx/msw/wrapwin.h"
#include "wx/msw/wrapcctl.h" // include <commctrl.h> "properly"
#include "wx/msw/private.h"
#endif
#include "wx/calctrl.h"
#include "wx/msw/private/datecontrols.h"
IMPLEMENT_DYNAMIC_CLASS(wxCalendarCtrl, wxControl)
// ----------------------------------------------------------------------------
// constants
// ----------------------------------------------------------------------------
namespace
{
// values of week days used by the native control
enum
{
MonthCal_Monday,
MonthCal_Tuesday,
MonthCal_Wednesday,
MonthCal_Thursday,
MonthCal_Friday,
MonthCal_Saturday,
MonthCal_Sunday
};
} // anonymous namespace
// ============================================================================
// implementation
// ============================================================================
// ----------------------------------------------------------------------------
// wxCalendarCtrl creation
// ----------------------------------------------------------------------------
void wxCalendarCtrl::Init()
{
m_marks =
m_holidays = 0;
}
bool
wxCalendarCtrl::Create(wxWindow *parent,
wxWindowID id,
const wxDateTime& dt,
const wxPoint& pos,
const wxSize& size,
long style,
const wxString& name)
{
if ( !wxMSWDateControls::CheckInitialization() )
return false;
// we need the arrows for the navigation
style |= wxWANTS_CHARS;
// initialize the base class
if ( !CreateControl(parent, id, pos, size, style, wxDefaultValidator, name) )
return false;
// create the native control: this is a bit tricky as we want to receive
// double click events but the MONTHCAL_CLASS doesn't use CS_DBLCLKS style
// and so we create our own copy of it which does
static ClassRegistrar s_clsMonthCal;
if ( !s_clsMonthCal.IsInitialized() )
{
// get a copy of standard class and modify it
WNDCLASS wc;
if ( ::GetClassInfo(NULL, MONTHCAL_CLASS, &wc) )
{
wc.lpszClassName = wxT("_wx_SysMonthCtl32");
wc.style |= CS_DBLCLKS;
s_clsMonthCal.Register(wc);
}
else
{
wxLogLastError(wxT("GetClassInfoEx(SysMonthCal32)"));
}
}
const wxChar * const clsname = s_clsMonthCal.IsRegistered()
? s_clsMonthCal.GetName().wx_str()
: MONTHCAL_CLASS;
if ( !MSWCreateControl(clsname, wxEmptyString, pos, size) )
return false;
// initialize the control
UpdateFirstDayOfWeek();
SetDate(dt.IsValid() ? dt : wxDateTime::Today());
if ( SetHolidayAttrs() )
UpdateMarks();
Connect(wxEVT_LEFT_DOWN,
wxMouseEventHandler(wxCalendarCtrl::MSWOnClick));
Connect(wxEVT_LEFT_DCLICK,
wxMouseEventHandler(wxCalendarCtrl::MSWOnDoubleClick));
return true;
}
WXDWORD wxCalendarCtrl::MSWGetStyle(long style, WXDWORD *exstyle) const
{
WXDWORD styleMSW = wxCalendarCtrlBase::MSWGetStyle(style, exstyle);
// right now we don't support all native styles but we should add wx styles
// corresponding to MCS_NOTODAY and MCS_NOTODAYCIRCLE probably (TODO)
// for compatibility with the other versions, just turn off today display
// unconditionally for now
styleMSW |= MCS_NOTODAY;
// we also need this style for Mark() to work
styleMSW |= MCS_DAYSTATE;
if ( style & wxCAL_SHOW_WEEK_NUMBERS )
styleMSW |= MCS_WEEKNUMBERS;
return styleMSW;
}
void wxCalendarCtrl::SetWindowStyleFlag(long style)
{
const bool hadMondayFirst = HasFlag(wxCAL_MONDAY_FIRST);
wxCalendarCtrlBase::SetWindowStyleFlag(style);
if ( HasFlag(wxCAL_MONDAY_FIRST) != hadMondayFirst )
UpdateFirstDayOfWeek();
}
// ----------------------------------------------------------------------------
// wxCalendarCtrl geometry
// ----------------------------------------------------------------------------
// TODO: handle WM_WININICHANGE
wxSize wxCalendarCtrl::DoGetBestSize() const
{
RECT rc;
if ( !GetHwnd() || !MonthCal_GetMinReqRect(GetHwnd(), &rc) )
{
return wxCalendarCtrlBase::DoGetBestSize();
}
const wxSize best = wxRectFromRECT(rc).GetSize() + GetWindowBorderSize();
CacheBestSize(best);
return best;
}
wxCalendarHitTestResult
wxCalendarCtrl::HitTest(const wxPoint& pos,
wxDateTime *date,
wxDateTime::WeekDay *wd)
{
WinStruct<MCHITTESTINFO> hti;
// Vista and later SDKs add a few extra fields to MCHITTESTINFO which are
// not supported by the previous versions, as we don't use them anyhow we
// should pretend that we always use the old struct format to make the call
// below work on pre-Vista systems (see #11057)
#ifdef MCHITTESTINFO_V1_SIZE
hti.cbSize = MCHITTESTINFO_V1_SIZE;
#endif
hti.pt.x = pos.x;
hti.pt.y = pos.y;
switch ( MonthCal_HitTest(GetHwnd(), &hti) )
{
default:
case MCHT_CALENDARWEEKNUM:
wxFAIL_MSG( "unexpected" );
// fall through
case MCHT_NOWHERE:
case MCHT_CALENDARBK:
case MCHT_TITLEBK:
case MCHT_TITLEMONTH:
case MCHT_TITLEYEAR:
return wxCAL_HITTEST_NOWHERE;
case MCHT_CALENDARDATE:
if ( date )
date->SetFromMSWSysTime(hti.st);
return wxCAL_HITTEST_DAY;
case MCHT_CALENDARDAY:
if ( wd )
{
int day = hti.st.wDayOfWeek;
// the native control returns incorrect day of the week when
// the first day isn't Monday, i.e. the first column is always
// "Monday" even if its label is "Sunday", compensate for it
const int first = LOWORD(MonthCal_GetFirstDayOfWeek(GetHwnd()));
if ( first == MonthCal_Monday )
{
// as MonthCal_Monday is 0 while wxDateTime::Mon is 1,
// normally we need to do this to transform from MSW
// convention to wx one
day++;
day %= 7;
}
//else: but when the first day is MonthCal_Sunday, the native
// control still returns 0 (i.e. MonthCal_Monday) for the
// first column which looks like a bug in it but to work
// around it it's enough to not apply the correction above
*wd = static_cast<wxDateTime::WeekDay>(day);
}
return wxCAL_HITTEST_HEADER;
case MCHT_TITLEBTNNEXT:
return wxCAL_HITTEST_INCMONTH;
case MCHT_TITLEBTNPREV:
return wxCAL_HITTEST_DECMONTH;
case MCHT_CALENDARDATENEXT:
case MCHT_CALENDARDATEPREV:
return wxCAL_HITTEST_SURROUNDING_WEEK;
}
}
// ----------------------------------------------------------------------------
// wxCalendarCtrl operations
// ----------------------------------------------------------------------------
bool wxCalendarCtrl::SetDate(const wxDateTime& dt)
{
wxCHECK_MSG( dt.IsValid(), false, "invalid date" );
SYSTEMTIME st;
dt.GetAsMSWSysTime(&st);
if ( !MonthCal_SetCurSel(GetHwnd(), &st) )
{
wxLogDebug(wxT("DateTime_SetSystemtime() failed"));
return false;
}
m_date = dt;
return true;
}
wxDateTime wxCalendarCtrl::GetDate() const
{
#if wxDEBUG_LEVEL
SYSTEMTIME st;
if ( !MonthCal_GetCurSel(GetHwnd(), &st) )
{
wxASSERT_MSG( !m_date.IsValid(), "mismatch between data and control" );
return wxDefaultDateTime;
}
wxDateTime dt(st);
wxASSERT_MSG( dt == m_date, "mismatch between data and control" );
#endif // wxDEBUG_LEVEL
return m_date;
}
bool wxCalendarCtrl::SetDateRange(const wxDateTime& dt1, const wxDateTime& dt2)
{
SYSTEMTIME st[2];
DWORD flags = 0;
if ( dt1.IsValid() )
{
dt1.GetAsMSWSysTime(st + 0);
flags |= GDTR_MIN;
}
if ( dt2.IsValid() )
{
dt2.GetAsMSWSysTime(st + 1);
flags |= GDTR_MAX;
}
if ( !MonthCal_SetRange(GetHwnd(), flags, st) )
{
wxLogDebug(wxT("MonthCal_SetRange() failed"));
}
return flags != 0;
}
bool wxCalendarCtrl::GetDateRange(wxDateTime *dt1, wxDateTime *dt2) const
{
SYSTEMTIME st[2];
DWORD flags = MonthCal_GetRange(GetHwnd(), st);
if ( dt1 )
{
if ( flags & GDTR_MIN )
dt1->SetFromMSWSysTime(st[0]);
else
*dt1 = wxDefaultDateTime;
}
if ( dt2 )
{
if ( flags & GDTR_MAX )
dt2->SetFromMSWSysTime(st[1]);
else
*dt2 = wxDefaultDateTime;
}
return flags != 0;
}
// ----------------------------------------------------------------------------
// other wxCalendarCtrl operations
// ----------------------------------------------------------------------------
bool wxCalendarCtrl::EnableMonthChange(bool enable)
{
if ( !wxCalendarCtrlBase::EnableMonthChange(enable) )
return false;
wxDateTime dtStart, dtEnd;
if ( !enable )
{
dtStart = GetDate();
dtStart.SetDay(1);
dtEnd = dtStart.GetLastMonthDay();
}
//else: leave them invalid to remove the restriction
SetDateRange(dtStart, dtEnd);
return true;
}
void wxCalendarCtrl::Mark(size_t day, bool mark)
{
wxCHECK_RET( day > 0 && day < 32, "invalid day" );
int mask = 1 << (day - 1);
if ( mark )
m_marks |= mask;
else
m_marks &= ~mask;
// calling Refresh() here is not enough to change the day appearance
UpdateMarks();
}
void wxCalendarCtrl::SetHoliday(size_t day)
{
wxCHECK_RET( day > 0 && day < 32, "invalid day" );
m_holidays |= 1 << (day - 1);
}
void wxCalendarCtrl::UpdateMarks()
{
// we show only one full month but there can be some days from the month
// before it and from the one after it so days from 3 different months can
// be partially shown
MONTHDAYSTATE states[3] = { 0 };
const int nMonths = MonthCal_GetMonthRange(GetHwnd(), GMR_DAYSTATE, NULL);
// although in principle the calendar might not show any days from the
// preceding months, it seems like it always does, consider e.g. Feb 2010
// which starts on Monday and ends on Sunday and so could fit on 4 lines
// without showing any subsequent months -- the standard control still
// shows it on 6 lines and the number of visible months is still 3
wxCHECK_RET( nMonths == (int)WXSIZEOF(states), "unexpected months range" );
// the fully visible month is the one in the middle
states[1] = m_marks | m_holidays;
if ( !MonthCal_SetDayState(GetHwnd(), nMonths, states) )
{
wxLogLastError(wxT("MonthCal_SetDayState"));
}
}
void wxCalendarCtrl::UpdateFirstDayOfWeek()
{
MonthCal_SetFirstDayOfWeek(GetHwnd(),
HasFlag(wxCAL_MONDAY_FIRST) ? MonthCal_Monday
: MonthCal_Sunday);
}
// ----------------------------------------------------------------------------
// wxCalendarCtrl events
// ----------------------------------------------------------------------------
bool wxCalendarCtrl::MSWOnNotify(int idCtrl, WXLPARAM lParam, WXLPARAM *result)
{
NMHDR* hdr = (NMHDR *)lParam;
switch ( hdr->code )
{
case MCN_SELCHANGE:
{
// we need to update m_date first, before calling the user code
// which expects GetDate() to return the new date
const wxDateTime dateOld = m_date;
const NMSELCHANGE * const sch = (NMSELCHANGE *)lParam;
m_date.SetFromMSWSysTime(sch->stSelStart);
// changing the year or the month results in a second dummy
// MCN_SELCHANGE event on this system which doesn't really
// change anything -- filter it out
if ( m_date != dateOld )
{
if ( GenerateAllChangeEvents(dateOld) )
{
// month changed, need to update the holidays if we use
// them
if ( SetHolidayAttrs() )
UpdateMarks();
}
}
}
break;
case MCN_GETDAYSTATE:
{
const NMDAYSTATE * const ds = (NMDAYSTATE *)lParam;
for ( int i = 0; i < ds->cDayState; i++ )
{
ds->prgDayState[i] = m_marks | m_holidays;
}
}
break;
default:
return wxCalendarCtrlBase::MSWOnNotify(idCtrl, lParam, result);
}
*result = 0;
return true;
}
void wxCalendarCtrl::MSWOnDoubleClick(wxMouseEvent& event)
{
if ( HitTest(event.GetPosition()) == wxCAL_HITTEST_DAY )
{
if ( GenerateEvent(wxEVT_CALENDAR_DOUBLECLICKED) )
return; // skip event.Skip() below
}
event.Skip();
}
void wxCalendarCtrl::MSWOnClick(wxMouseEvent& event)
{
// for some reason, the control doesn't get focus on its own when the user
// clicks in it
SetFocus();
event.Skip();
}
#endif // wxUSE_CALENDARCTRL
| 28.987903 | 81 | 0.536445 | [
"geometry",
"transform"
] |
14db3fb86265604ef235eb025d466a369f00ffdf | 872 | cpp | C++ | leetcode/friend_circle.cpp | sandeepjindal/algos | e649c82bfb6b986c8462b09d28e07c2069e48792 | [
"MIT"
] | 1 | 2019-09-10T17:45:58.000Z | 2019-09-10T17:45:58.000Z | leetcode/friend_circle.cpp | sandeepjindal/algos | e649c82bfb6b986c8462b09d28e07c2069e48792 | [
"MIT"
] | null | null | null | leetcode/friend_circle.cpp | sandeepjindal/algos | e649c82bfb6b986c8462b09d28e07c2069e48792 | [
"MIT"
] | null | null | null | #include <bits/stdc++.h>
using namespace std;
void doDfs(vector<string>&related, int ind, vector<bool>&vis) {
if(vis[ind]){
return;
}
vis[ind] = true;
string relation = related[ind];
for(int i = 0;i<relation.size();i++) {
if(relation[i] == '1' and vis[i]== false) {
doDfs(related, i, vis);
}
}
}
int countGroups(vector<string> related) {
int n = related.size();
vector<bool> vis(n, false);
int gp = 0;
for(int i=0;i<n;i++) {
if(!vis[i]) {
gp++;
doDfs(related, i, vis);
}
}
return gp;
}
int main() {
vector<string> arr = {"1100", "1110", "0110", "0001"};
vector<string> arr2 = {"110", "110", "011"};
vector<string> arr3 = {"10000", "01000", "00100", "00010", "00001"};
cout << countGroups(arr3);
return 0;
}
| 18.553191 | 72 | 0.5 | [
"vector"
] |
14e0f0f4cd3c3a0aada2674a0dd5f56504493f5e | 12,105 | cpp | C++ | src/cfg.cpp | giag3/peng-utils | f0883ffbf3b422de2e0ea326861114b1f5809037 | [
"MIT"
] | 1 | 2022-03-28T11:20:50.000Z | 2022-03-28T11:20:50.000Z | src/cfg.cpp | giag3/peng-utils | f0883ffbf3b422de2e0ea326861114b1f5809037 | [
"MIT"
] | null | null | null | src/cfg.cpp | giag3/peng-utils | f0883ffbf3b422de2e0ea326861114b1f5809037 | [
"MIT"
] | null | null | null | #include "error_handler/error_handler.hpp"
#include "vars.hpp"
// Retuns an ANSI escape sequence for background with color
extern std::string bkg(color_code ccode, graphic_rendition);
// Retuns an ANSI escape sequence for foreground with color
extern std::string frg(color_code ccode, graphic_rendition gr);
// Reset color to original
extern std::string clr();
// Set bold text
extern std::string bld();
// ****************************************************************
// CONFIGURATION OBJECTS
// ****************************************************************
// The pointer to the argument vector
char** argv;
// The argument count
int argc;
// The argument index
int arg_in = 0;
// The command index
int cmd_in = 0;
/**
* @brief is_number Checks whether the string is a number
* @param token the token to check
* @return
*/
num_sys is_number(const std::string& token) {
if (token.empty())
return (num_sys) -1;
int i = 0;
// If negative, ignore -
if (token[0] == '-')
i++;
if (token.size() >= 2 + i) {
// Parse hexadecimal number
if (token[i] == '0' && (token[i+1] == 'x' || token[i+1] == 'X')) {
// Increment index
i += 2;
// Check if number is a hexadecimal number
for (; i < token.size(); i++) {
if (!std::isdigit(token[i])
&& token[i] != 'a' && token[i] != 'b'
&& token[i] != 'c' && token[i] != 'd'
&& token[i] != 'e' && token[i] != 'f'
&& token[i] != 'A' && token[i] != 'B'
&& token[i] != 'C' && token[i] != 'D'
&& token[i] != 'E' && token[i] != 'F') {
return (num_sys) -1;
}
}
return num_sys::HEX;
}
}
// Check if it's a number
for (; i < token.size(); i++)
if (!std::isdigit(token[i]))
return (num_sys) -1;
return num_sys::DEC;
}
#if UTILITY == ASSEMBLER
extern void assembler_configure_option();
extern void assembler_configure_argument();
// The path to the source code vector of paths
std::vector<std::string> source_code_path_vector, output_path_vector;
// Get assembler format
extern assembler_format aformat;
#elif UTILITY == LINKER
extern void linker_configure_option();
extern void linker_configure_argument();
// The path to the source code vector of paths
std::vector<std::string> source_code_path_vector;
// The path to the output file
std::string output_path;
// Get linker format
extern linker_format lformat;
#elif UTILITY == COMPILER
// Compiler defines functions from ASSEMBLER + LINKER
extern void compiler_configure_option();
extern void compiler_configure_argument();
// The path to the source code vector of paths (for assembler / linker)
std::vector<std::string> source_code_path_vector, output_path_vector;
// The path to the output file
std::string output_path;
// Get compiler format
extern compiler_format cformat;
#endif
// ****************************************************************
// PATHS
// ****************************************************************
// The path to the utility program
std::string utility_path;
// Case insensitive equal
bool iequal(const std::string& str1, const std::string& str2) {
// If sizes are not equal, return false
if (str1.size() != str2.size())
return false;
// We have 2 options, either one is bigger and one is smaller
// or the other way around
for (int i = 0; i < str1.size(); i++) {
char c1 = str1[i], c2 = str2[i];
// If not equal, check the 2 options
if (c1 != c2) {
if (c1 <= 90) {
// Increment by the offset of 'a' and 'Z'
if (c1 + 32 != c2)
return false;
} else if (c2 <= 90) {
// Increment by the offset of 'a' and 'Z'
if (c1 != c2 + 32)
return false;
}
// Not letters => not equal, so we return false
else {
return false;
}
}
}
return true;
}
// Gets the extension from format
std::string get_ext() {
#if UTILITY == ASSEMBLER
if (aformat == assembler_format::BIN)
return ".bin";
else if (aformat == assembler_format::ELF64)
return ".o";
else if (aformat == assembler_format::WIN64)
return ".obj";
#elif UTILITY == LINKER
if (lformat == linker_format::ELF64)
return ".out";
else if (lformat == linker_format::BIN)
return ".bin";
else if (lformat == linker_format::WIN64)
return ".exe";
#elif UTILITY == COMPILER
if (cformat == compiler_format::EXECUTABLE_ELF64)
return ".out";
else if (cformat == compiler_format::FLAT_BINARY)
return ".bin";
else if (cformat == compiler_format::EXECUTABLE_WIN64)
return ".exe";
else if (cformat == compiler_format::OBJECT_ELF64)
return ".o";
#endif
}
// ****************************************************************
// CONFIGURE ARGUMENTS
// ****************************************************************
// Parses an argument
void parse_argument() {
// Whether the argument is an option
bool option = false;
// Checks whether we're parsing an option
// Size is guaranteed to be > 0
if (argv[arg_in][0] == '-') {
// Configure option
#if UTILITY == ASSEMBLER
assembler_configure_option();
#elif UTILITY == LINKER
linker_configure_option();
#elif UTILITY == COMPILER
compiler_configure_option();
#endif
} else {
// Configure argument
#if UTILITY == ASSEMBLER
assembler_configure_argument();
#elif UTILITY == LINKER
linker_configure_argument();
#elif UTILITY == COMPILER
compiler_configure_argument();
#endif
}
}
// Argument config
void configure_arguments(int argc, char* argv[]) {
debug("Configuring arguments...");
/*
Operating systems differ in command line arguments.
Windows:
Only user defined arguments
Linux:
First argument is the path to the program, followed by user defined arguments
*/
// Set utility name for error handler
error_handler::set_utility();
// Save argv, argc
::argv = argv, ::argc = argc;
// DEBUG
#ifdef DEBUG
std::cout << argc << std::endl;
for (int i = 0; i < argc; i++) {
std::cout << "Argument number(" << i << "): " << argv[i] << std::endl;
}
#endif
// OS-Specific configuration
#if RUNNING_OS == _LINUX
// If running on LINUX
// The first argument is the path to the compiler
utility_path = std::experimental::filesystem::path(argv[0]).parent_path();
// Increment argument index
arg_in++;
// Parse remaining arguments
while (arg_in < argc) {
parse_argument();
}
#elif RUNNING_OS == _WINDOWS
// If running on WINDOWS
// Gets the path to the compiler
GetWindowsDirectoryA(&compiler_path, MAX_PATH);
// Parse remaining arguments
while (arg_in <= argc) {
parse_argument();
}
#endif
// Check whether all non-optional arguments have been set-up
#if (UTILITY == ASSEMBLER || UTILITY == COMPILER || UTILITY == LINKER)
// VALIDATE
if (source_code_path_vector.empty()) {
// Source files not specified
error_handler::argument_error("source file(s) not specified");
}
// Validate source code paths
for (std::string& source_code_path : source_code_path_vector) {
if (!std::experimental::filesystem::exists(source_code_path)) {
// Throw an error if invalid path
error_handler::argument_error("source file '" + frg(color_code::GREEN, graphic_rendition::NORMAL) + source_code_path + clr() + "' does not exist");
}
// Check if it's a relative path -> convert to the absolute path
else if (std::experimental::filesystem::path(source_code_path).is_relative())
source_code_path = std::experimental::filesystem::absolute(source_code_path).string();
}
#endif
// Non-optional (sort of)
// The path to the output file
#if UTILITY == ASSEMBLER
// Change the extension of the source file
if (output_path_vector.size() != source_code_path_vector.size()) {
// Check if output.size > input.size
if (output_path_vector.size() > source_code_path_vector.size())
error_handler::argument_error("too many output files ("
+ frg(color_code::CYAN, graphic_rendition::BOLD) +
std::to_string(output_path_vector.size()) + clr() +
") compared to input files (" + frg(color_code::CYAN, graphic_rendition::BOLD) +
std::to_string(source_code_path_vector.size()) + clr() + ")");
// For every input file -> generate an output file
for (int i = output_path_vector.size(); i < source_code_path_vector.size(); i++) {
// Get default output file name
std::string file_name = std::experimental::filesystem::path(source_code_path_vector[i]).replace_extension(get_ext()).filename().string();
// Set to current path
std::string output_file = std::experimental::filesystem::current_path().string() + "/" + file_name;
// Check if default output path is equal to input -> if so, set to something else
if (output_file == source_code_path_vector[i]) {
// Set num for output name
std::string num;
if (i != 0)
num = "-" + std::to_string(i);
// Create the new output path
output_file = std::experimental::filesystem::current_path().string() + "/pasm" + num + ".out";
// Warn user
error_handler::warning("default output file name same as input; setting to '" + output_file + "'");
} else {
// Warn the user if no output path specified
error_handler::warning("output file not specified, setting to '" + frg(color_code::GREEN, graphic_rendition::NORMAL) + output_file + clr() + "'");
}
// Set appropriate output file name
output_path_vector.push_back(output_file);
}
}
#elif (UTILITY == LINKER || UTILITY == COMPILER)
if (output_path.empty()) {
// Change the extension of the source file
output_path = std::experimental::filesystem::path(source_code_path_vector[0]).replace_extension(get_ext());
// Warn the user if no output path specified
error_handler::warning("output file not specified, setting to '" + frg(color_code::GREEN, graphic_rendition::NORMAL) + output_path + clr() + "'");
}
// Check if it's a relative path -> convert to the absolute path
else if (std::experimental::filesystem::path(output_path).is_relative())
output_path = std::experimental::filesystem::absolute(output_path).string();
#endif
}
| 35.086957 | 170 | 0.530938 | [
"vector"
] |
14e167bd2c74b543559cc90c32170eb84fbd6c62 | 13,595 | cpp | C++ | docker/cytnx/src/RegularNetwork.cpp | j9263178/Cytnx | cf7fb1cff75c1cea14fbbc370fd8e4d86d0ddc8b | [
"Apache-2.0"
] | 11 | 2020-04-14T15:45:42.000Z | 2022-03-31T14:37:03.000Z | docker/cytnx/src/RegularNetwork.cpp | j9263178/Cytnx | cf7fb1cff75c1cea14fbbc370fd8e4d86d0ddc8b | [
"Apache-2.0"
] | 38 | 2019-08-02T15:15:51.000Z | 2022-03-04T19:07:02.000Z | docker/cytnx/src/RegularNetwork.cpp | j9263178/Cytnx | cf7fb1cff75c1cea14fbbc370fd8e4d86d0ddc8b | [
"Apache-2.0"
] | 7 | 2019-07-17T07:50:55.000Z | 2021-07-03T06:44:52.000Z | #include <typeinfo>
#include "Network.hpp"
#include "utils/utils_internal_interface.hpp"
#include <stack>
#include <algorithm>
#include <iostream>
using namespace std;
namespace cytnx{
// these two are internal functions:
void _parse_ORDER_line_(vector<string> &tokens, const string &line){
cytnx_error_msg((line.find_first_of("\t;\n:") != string::npos),
"[ERROR][Network][Fromfile] invalid ORDER line format.%s",
"\n");
cytnx_error_msg((line.find_first_of("(),") == string::npos),
"[ERROR][Network][Fromfile] invalid ORDER line format.%s",
" tensors should be seperate by delimiter \',\' (comma), and/or wrapped with \'(\' and \')\'");
//check mismatch:
size_t lbrac_n = std::count(line.begin(),line.end(),'(');
size_t rbrac_n = std::count(line.begin(),line.end(),')');
cytnx_error_msg(lbrac_n != rbrac_n,
"[ERROR][Network][Fromfile] parentheses mismatch.%s","\n");
// slice the line into pieces by parentheses and comma
tokens = str_findall(line,"(),");
cytnx_error_msg(tokens.size()==0,"[ERROR][Network][Fromfile] invalid ORDER line.%s","\n");
}
void _parse_TOUT_line_(vector<cytnx_int64> &lbls, cytnx_uint64 &TOUT_iBondNum, const string &line){
lbls.clear();
vector<string> tmp = str_split(line,false,";");
cytnx_error_msg(tmp.size()!=2,"[ERROR][Network] Fromfile: %s\n","Invalid TOUT line");
// handle col-space lbl
vector<string> ket_lbls = str_split(tmp[0],false,",");
if(ket_lbls.size()==1) if(ket_lbls[0].length()==0) ket_lbls.clear();
for(cytnx_uint64 i=0;i<ket_lbls.size();i++){
string tmp = str_strip(ket_lbls[i]);
cytnx_error_msg(tmp.length()==0,"[ERROR][Network][Fromfile] Invalid labels for TOUT line.%s","\n");
cytnx_error_msg((tmp.find_first_not_of("0123456789-") != string::npos),
"[ERROR][Network] Fromfile: %s\n","Invalid TOUT line. label contain non integer.");
lbls.push_back(stoi(tmp,nullptr));
}
TOUT_iBondNum = lbls.size();
// handle row-space lbl
vector<string> bra_lbls = str_split(tmp[1],false,",");
if(bra_lbls.size()==1) if(bra_lbls[0].length()==0) bra_lbls.clear();
for(cytnx_uint64 i=0;i<bra_lbls.size();i++){
string tmp = str_strip(bra_lbls[i]);
cytnx_error_msg(tmp.length()==0,"[ERROR][Network][Fromfile] Invalid labels for TOUT line.%s","\n");
cytnx_error_msg((tmp.find_first_not_of("0123456789-") != string::npos),
"[ERROR][Network] Fromfile: %s\n","Invalid TOUT line. label contain non integer.");
lbls.push_back(stoi(tmp,nullptr));
}
}
void _parse_TN_line_(vector<cytnx_int64> &lbls, cytnx_uint64 &TN_iBondNum, const string &line){
lbls.clear();
vector<string> tmp = str_split(line,false,";");
cytnx_error_msg(tmp.size()!=2,"[ERROR][Network] Fromfile: %s\n","Invalid TN line");
// handle col-space lbl
vector<string> ket_lbls = str_split(tmp[0],false,",");
if(ket_lbls.size()==1) if(ket_lbls[0].length()==0) ket_lbls.clear();
for(cytnx_uint64 i=0;i<ket_lbls.size();i++){
string tmp = str_strip(ket_lbls[i]);
cytnx_error_msg(tmp.length()==0,"[ERROR][Network][Fromfile] Invalid labels for TN line.%s","\n");
cytnx_error_msg((tmp.find_first_not_of("0123456789-") != string::npos),
"[ERROR][Network] Fromfile: %s\n","Invalid TN line. label contain non integer.");
lbls.push_back(stoi(tmp,nullptr));
}
TN_iBondNum = lbls.size();
// handle row-space lbl
vector<string> bra_lbls = str_split(tmp[1],false,",");
if(bra_lbls.size()==1) if(bra_lbls[0].length()==0) bra_lbls.clear();
for(cytnx_uint64 i=0;i<bra_lbls.size();i++){
string tmp = str_strip(bra_lbls[i]);
cytnx_error_msg(tmp.length()==0,"[ERROR][Network][Fromfile] Invalid labels for TOUT line.%s","\n");
cytnx_error_msg((tmp.find_first_not_of("0123456789-") != string::npos),
"[ERROR][Network] Fromfile: %s\n","Invalid TN line. label contain non integer.");
lbls.push_back(stoi(tmp,nullptr));
}
cytnx_error_msg(lbls.size()==0,"[ERROR][Network][Fromfile] %s\n","Invalid TN line. no label present in this line, which is invalid.%s","\n");
}
void RegularNetwork::Fromfile(const std::string &fname){
const cytnx_uint64 MAXLINES = 1024;
// empty all
this->Clear();
// open file
std::ifstream infile;
infile.open (fname.c_str());
if(!(infile.is_open())) {
cytnx_error_msg(true,"[Network] Error in opening file \'",fname.c_str(),"\'.\n");
}
string line;
cytnx_uint64 lnum = 0;
vector<string> tmpvs;
//read each line:
while(lnum < MAXLINES) {
lnum++;
getline(infile, line);
line = str_strip(line,"\n"); // remove \n on each end.
line = str_strip(line); // remove space on each end
if(infile.eof())
break;
// check :
//cout << "line:" << lnum << "|" << line <<"|"<< endl;
if(line.length()==0) continue; // blank line
if(line.at(0)=='#') continue; // comment whole line.
// remove any comment at eol :
line = str_split(line,true,"#")[0]; // remove comment on end.
// A valid line should contain ':':
cytnx_error_msg(line.find_first_of(":") == string::npos,
"[ERROR][Network][Fromfile] invalid line in network file at line: %d. should contain \':\'",lnum);
tmpvs = str_split(line,false,":"); //note that checking empty string!
cytnx_error_msg(tmpvs.size()!=2,"[ERROR][Network] invalid line in network file at line: %d. \n",lnum);
string name = str_strip(tmpvs[0]);
string content = str_strip(tmpvs[1]);
//check if name contain invalid keyword or not assigned.
cytnx_error_msg(name.length()==0,"[ERROR][Network][Fromfile] invalid tensor name at line: %d\n",lnum);
cytnx_error_msg(name.find_first_of(" ;,") != string::npos,"[ERROR] invalid Tensor name at line %d\n",lnum);
//dispatch:
if(name == "ORDER"){
if(content.length()){
//cut the line into tokens,
//and leave it to process by CtTree after read all lines.
_parse_ORDER_line_(this->ORDER_tokens,content);
}
}else if(name == "TOUT"){
//if content has length, then pass to process.
if(content.length()){
// this is an internal function that is defined in this cpp file.
_parse_TOUT_line_(this->TOUT_labels,this->TOUT_iBondNum,content);
}
}else{
this->names.push_back(name);
//check if name is valid:
if(name2pos.find(name)!= name2pos.end()){
cytnx_error_msg(true,"[ERROR][Network][Fromfile] tensor name: [%s] has already exist. Cannot have duplicated tensor name in a network.",name.c_str());
}
cytnx_error_msg(name.find_first_of("\t;\n: ")!=string::npos,"[ERROR][Network][Fromfile] invalid tensor name. cannot contain [' '] or [';'] or [':'] or ['\\t'] .%s","\n");
//check exists content:
cytnx_error_msg(content.length()==0,"[ERROR][Network][Fromfile] invalid tensor labelsat line %d. cannot have empty labels for input tensor. \n",lnum);
this->name2pos[name] = names.size() - 1; // register
this->label_arr.push_back(vector<cytnx_int64>());
cytnx_uint64 tmp_iBN;
// this is an internal function that is defined in this cpp file.
_parse_TN_line_(this->label_arr.back(),tmp_iBN,content);
this->iBondNums.push_back(tmp_iBN);
}
}// end readlines
infile.close();
cytnx_error_msg(lnum>=MAXLINES,"[ERROR][Network][Fromfile] network file exceed the maxinum allowed lines, MAXLINES=2048%s","\n");
cytnx_error_msg(this->names.size()<2,"[ERROR][Network][Fromfile] invalid network file. Should have at least 2 tensors defined.%s","\n");
this->tensors.resize(this->names.size());
this->CtTree.base_nodes.resize(this->names.size());
//contraction order:
if(ORDER_tokens.size()!=0){
CtTree.build_contraction_order_by_tokens(this->name2pos,ORDER_tokens);
}else{
CtTree.build_default_contraction_order();
}
}
void RegularNetwork::PutUniTensor(const cytnx_uint64 &idx, const UniTensor &utensor, const bool &is_clone){
cytnx_error_msg(idx>=this->CtTree.base_nodes.size(),"[ERROR][RegularNetwork][PutUniTensor] index=%d out of range.\n",idx);
//check shape:
cytnx_error_msg(this->label_arr[idx].size()!=utensor.rank(),"[ERROR][RegularNetwork][PutUniTensor] tensor name: [%s], the rank of input UniTensor does not match the definition in network file.\n",this->names[idx].c_str());
cytnx_error_msg(this->iBondNums[idx]!=utensor.Rowrank(),"[ERROR][RegularNetwork][PutUniTensor] tensor name: [%s], the row-rank of input UniTensor does not match the semicolon defined in network file.\n",this->names[idx].c_str());
if(is_clone){
this->tensors[idx] = utensor.clone();
}else{
this->tensors[idx] = utensor;
}
}
void RegularNetwork::PutUniTensor(const std::string &name, const UniTensor &utensor, const bool &is_clone){
cytnx_uint64 idx;
try{idx=this->name2pos.at(name);}
catch(std::out_of_range){
cytnx_error_msg(true,"[ERROR][RegularNetwork][PutUniTensor] cannot find the tensor name: [%s] in current network.\n", name.c_str());
}
this->PutUniTensor(idx,utensor,is_clone);
}
UniTensor RegularNetwork::Launch(){
//1. check tensors are all set, and put all unitensor on node for contraction:
cytnx_error_msg(this->tensors.size()==0,"[ERROR][Launch][RegularNetwork] cannot launch an un-initialize network.%s","\n");
vector<vector<cytnx_int64> > old_labels;
for(cytnx_uint64 idx=0;idx<this->tensors.size();idx++){
cytnx_error_msg(this->tensors[idx].uten_type()==UTenType.Void,"[ERROR][Launch][RegularNetwork] tensor at [%d], name: [%s] is not set.\n",idx,this->names[idx].c_str());
//transion save old labels:
old_labels.push_back(this->tensors[idx].labels());
//modify the label of unitensor (shared):
this->tensors[idx].set_labels(this->label_arr[idx]);
this->CtTree.base_nodes[idx].utensor = this->tensors[idx];
this->CtTree.base_nodes[idx].is_assigned = true;
}
//2. contract using postorder traversal:
//cout << this->CtTree.nodes_container.size() << endl;
stack<Node*> stk;
Node *root = &(this->CtTree.nodes_container.back());
int ly = 0;
bool ict;
do{
//move the lmost
while((root!=nullptr)){
if(root->right!=nullptr) stk.push(root->right);
stk.push(root);
root = root->left;
}
root = stk.top(); stk.pop();
//cytnx_error_msg(stk.size()==0,"[eRROR]","\n");
ict = true;
if((root->right!=nullptr) && !stk.empty()){
if(stk.top() == root->right){
stk.pop();
stk.push(root);
root = root->right;
ict = false;
}
}
if(ict){
//process!
//cout << "OK" << endl;
if((root->right!=nullptr) && (root->left!=nullptr)){
root->utensor = Contract(root->left->utensor,root->right->utensor);
root->left->clear_utensor(); //remove intermediate unitensor to save heap space
root->right->clear_utensor(); //remove intermediate unitensor to save heap space
root->is_assigned = true;
//cout << "contract!" << endl;
}
root = nullptr;
}
//cout.flush();
//break;
}while(!stk.empty());
//3. get result:
UniTensor out = this->CtTree.nodes_container.back().utensor;
//4. reset nodes:
this->CtTree.reset_nodes();
//5. reset back the original labels:
for(cytnx_uint64 i=0;i<this->tensors.size();i++){
this->tensors[i].set_labels(old_labels[i]);
}
//6. permute accroding to pre-set labels:
if(TOUT_labels.size()){
out.permute_(TOUT_labels,TOUT_iBondNum,true);
}
//UniTensor out;
return out;
}
}//namespace cytnx
| 42.484375 | 237 | 0.556381 | [
"shape",
"vector"
] |
14e70570c68143e84e2d392ec53ceb0291e5f190 | 2,390 | hpp | C++ | source/common/Camera.hpp | Zainrax/COSC342-OpenGL | 223c45c763a82e543c62e3bc3b22e1220e20fe7d | [
"MIT"
] | null | null | null | source/common/Camera.hpp | Zainrax/COSC342-OpenGL | 223c45c763a82e543c62e3bc3b22e1220e20fe7d | [
"MIT"
] | null | null | null | source/common/Camera.hpp | Zainrax/COSC342-OpenGL | 223c45c763a82e543c62e3bc3b22e1220e20fe7d | [
"MIT"
] | null | null | null | /*
* Camera.hpp
*
* by Stefanie Zollmann
*
* Camera class.
*
*/
#ifndef CAMERA_HPP
#define CAMERA_HPP
// Include GLM
#include <glm/glm.hpp>
#include <glm/gtc/matrix_transform.hpp>
//! Camera.
/*!
Contains decriptions for a setting up a render camera.
*/
class Camera{
public:
//! Default constructor
/*! Setting up default camera. */
Camera();
//! Constructor
/*! Setting up camera with certain parameters. */
Camera(glm::mat4 projectionMat, glm::mat4 viewMat);
//! Access viewprojection matrix
/*! Access viewprojection matrix. */
glm::mat4 getViewProjectionMatrix();
//! getViewMatrix
/*! Access view matrix. */
glm::mat4 getViewMatrix();
//! getProjectionatrix
/*! Access projection matrix. */
glm::mat4 getProjectionatrix();
//! Access camera position
/*! Access camera position. Retruns a vec3 */
glm::vec3 getPosition();
//! Set camera orientation
/*! Set camera orientation based on vertical and horizontal angle */
void setCameraOrientation(float vertAngle, float horzAngle);
//! Set lookat vector
/*! Set lookat vector only. */
void setLookAt(glm::vec3 lookAt);
//! Set lookat vector
/*! Set lookat configuration by setting position, lookat vector and up vector. */
void setLookAt(glm::vec3 pos,glm::vec3 lookAt, glm::vec3 up);
//! Set position
/*! Set position. */
void setPosition(glm::vec3 pos);
//! Update angles.
/*! Set after setting the angles the camera settings neeed to be updated. */
void updateAngles();
private:
glm::mat4 m_projectionMatrix; //!< Contains only projectionMatrix
glm::mat4 m_viewMatrix; //!< Contains only viewMatrix
// camera pose parameters
// Initial position : on +Z
glm::vec3 m_position; //!< Position of camera
glm::vec3 m_lookat; //!< Lookat vector of camera
glm::vec3 m_up; //!< Up vector of camera
//orienation of the camera
float m_horizontalAngle; //!< Initial horizontal angle : toward -Z
float m_verticalAngle; //!< Initial vertical angle : none
// camera intrinsics
float m_foV; //!< Field of View
};
#endif
| 27.471264 | 87 | 0.596653 | [
"render",
"vector"
] |
14e796be9ef05a712bfaa9565ee263a004310a09 | 4,003 | cpp | C++ | TAO/orbsvcs/tests/FT_Naming/Load_Balancing/server.cpp | cflowe/ACE | 5ff60b41adbe1772372d1a43bcc1f2726ff8f810 | [
"DOC"
] | 36 | 2015-01-10T07:27:33.000Z | 2022-03-07T03:32:08.000Z | TAO/orbsvcs/tests/FT_Naming/Load_Balancing/server.cpp | cflowe/ACE | 5ff60b41adbe1772372d1a43bcc1f2726ff8f810 | [
"DOC"
] | 2 | 2018-08-13T07:30:51.000Z | 2019-02-25T03:04:31.000Z | TAO/orbsvcs/tests/FT_Naming/Load_Balancing/server.cpp | cflowe/ACE | 5ff60b41adbe1772372d1a43bcc1f2726ff8f810 | [
"DOC"
] | 38 | 2015-01-08T14:12:06.000Z | 2022-01-19T08:33:00.000Z | // $Id: server.cpp 96320 2012-11-21 16:37:03Z mesnier_p $
#include "LB_server.h"
#include "Basic.h"
int
ACE_TMAIN(int argc, ACE_TCHAR *argv[])
{
try
{
const char *location1 = "MyLocation 1";
const char *location2 = "MyLocation 2";
const char *location3 = "MyLocation 3";
const char *location4 = "MyLocation 4";
const char *location5 = "MyLocation 5";
const char *location6 = "MyLocation 6";
LB_server lb_server (argc, argv);
if (lb_server.start_orb_and_poa () != 0)
return 1;
if (lb_server.create_object_group () != 0)
return 1;
CosNaming::Name name (1);
name.length (1);
name[0].id = CORBA::string_dup ("basic_name");
try {
(lb_server.name_svc ())->rebind (name, lb_server.object_group ());
}
catch (const CORBA::Exception& ex)
{
ex._tao_print_exception ("Unable to bind object group in name service.\n");
return 1;
}
Basic *basic_servant1;
Basic *basic_servant2;
Basic *basic_servant3;
Basic *basic_servant4;
Basic *basic_servant5;
Basic *basic_servant6;
ACE_NEW_RETURN (basic_servant1,
Basic (lb_server.object_group (),
lb_server.naming_manager (),
lb_server.orb (),
location1),
1);
PortableServer::ServantBase_var owner_transfer1(basic_servant1);
ACE_NEW_RETURN (basic_servant2,
Basic (lb_server.object_group (),
lb_server.naming_manager (),
lb_server.orb (),
location2),
1);
PortableServer::ServantBase_var owner_transfer2(basic_servant2);
ACE_NEW_RETURN (basic_servant3,
Basic (lb_server.object_group (),
lb_server.naming_manager (),
lb_server.orb (),
location3),
1);
PortableServer::ServantBase_var owner_transfer3(basic_servant3);
ACE_NEW_RETURN (basic_servant4,
Basic (lb_server.object_group (),
lb_server.naming_manager (),
lb_server.orb (),
location4),
1);
PortableServer::ServantBase_var owner_transfer4(basic_servant4);
ACE_NEW_RETURN (basic_servant5,
Basic (lb_server.object_group (),
lb_server.naming_manager (),
lb_server.orb (),
location5),
1);
PortableServer::ServantBase_var owner_transfer5(basic_servant5);
ACE_NEW_RETURN (basic_servant6,
Basic (lb_server.object_group (),
lb_server.naming_manager (),
lb_server.orb (),
location6),
1);
PortableServer::ServantBase_var owner_transfer6(basic_servant6);
if (lb_server.register_servant (basic_servant1, location1) == -1
|| lb_server.register_servant (basic_servant2, location2) == -1
|| lb_server.register_servant (basic_servant3, location3) == -1
|| lb_server.register_servant (basic_servant4, location4) == -1
|| lb_server.register_servant (basic_servant5, location5) == -1
|| lb_server.register_servant (basic_servant6, location6) == -1)
{
(void) lb_server.destroy ();
return 1;
}
lb_server.orb ()->run ();
ACE_DEBUG ((LM_DEBUG, "(%P|%t) server - event loop finished\n"));
if (lb_server.destroy () == -1)
return 1;
}
catch (const CORBA::Exception& ex)
{
ex._tao_print_exception ("lb_server exception");
return 1;
}
return 0;
}
| 33.358333 | 83 | 0.531102 | [
"object"
] |
14e7d2aed3d953bb2287612b06e4aec359a1d71a | 5,033 | cpp | C++ | P0267_RefImpl/Samples/svg/external/svgpp/third_party/agg/examples/alpha_mask.cpp | zmm-Embedded/io2d | 2e53612d60692d70700b4f7d0f9e4e34dbe11388 | [
"BSL-1.0"
] | 17 | 2017-05-13T03:49:06.000Z | 2020-04-18T17:11:27.000Z | examples/alpha_mask.cpp | Sineaggi/Anti-Grain-Geometry | 37290a1526268898f7314eaca6369c907e2bc7b5 | [
"BSD-3-Clause"
] | 23 | 2017-03-17T03:20:46.000Z | 2020-08-28T09:49:42.000Z | examples/alpha_mask.cpp | Sineaggi/Anti-Grain-Geometry | 37290a1526268898f7314eaca6369c907e2bc7b5 | [
"BSD-3-Clause"
] | 3 | 2016-10-09T16:36:03.000Z | 2022-02-22T08:39:16.000Z | #include <stdlib.h>
#include <ctype.h>
#include <stdio.h>
#include "agg_basics.h"
#include "agg_rendering_buffer.h"
#include "agg_rasterizer_scanline_aa.h"
#include "agg_path_storage.h"
#include "agg_conv_transform.h"
#include "agg_bounding_rect.h"
#include "agg_renderer_scanline.h"
#include "agg_pixfmt_rgb.h"
#include "agg_pixfmt_gray.h"
#include "agg_alpha_mask_u8.h"
#include "agg_scanline_u.h"
#include "agg_scanline_p.h"
#include "agg_ellipse.h"
#include "platform/agg_platform_support.h"
enum flip_y_e { flip_y = true };
agg::path_storage g_path;
agg::rgba8 g_colors[100];
unsigned g_path_idx[100];
unsigned g_npaths = 0;
double g_x1 = 0;
double g_y1 = 0;
double g_x2 = 0;
double g_y2 = 0;
double g_base_dx = 0;
double g_base_dy = 0;
double g_angle = 0;
double g_scale = 1.0;
double g_skew_x = 0;
double g_skew_y = 0;
int g_nclick = 0;
unsigned parse_lion(agg::path_storage& ps, agg::rgba8* colors, unsigned* path_idx);
void parse_lion()
{
g_npaths = parse_lion(g_path, g_colors, g_path_idx);
agg::pod_array_adaptor<unsigned> path_idx(g_path_idx, 100);
agg::bounding_rect(g_path, path_idx, 0, g_npaths, &g_x1, &g_y1, &g_x2, &g_y2);
g_base_dx = (g_x2 - g_x1) / 2.0;
g_base_dy = (g_y2 - g_y1) / 2.0;
}
agg::rendering_buffer g_alpha_mask_rbuf;
agg::alpha_mask_gray8 g_alpha_mask(g_alpha_mask_rbuf);
agg::rasterizer_scanline_aa<> g_rasterizer;
class the_application : public agg::platform_support
{
unsigned char* m_alpha_buf;
agg::rendering_buffer m_alpha_rbuf;
public:
virtual ~the_application()
{
delete [] m_alpha_buf;
}
the_application(agg::pix_format_e format, bool flip_y) :
agg::platform_support(format, flip_y),
m_alpha_buf(0)
{
parse_lion();
}
void generate_alpha_mask(int cx, int cy)
{
delete [] m_alpha_buf;
m_alpha_buf = new unsigned char[cx * cy];
g_alpha_mask_rbuf.attach(m_alpha_buf, cx, cy, cx);
typedef agg::renderer_base<agg::pixfmt_gray8> ren_base;
typedef agg::renderer_scanline_aa_solid<ren_base> renderer;
agg::pixfmt_gray8 pixf(g_alpha_mask_rbuf);
ren_base rb(pixf);
renderer r(rb);
agg::scanline_p8 sl;
rb.clear(agg::gray8(0));
agg::ellipse ell;
int i;
for(i = 0; i < 10; i++)
{
ell.init(rand() % cx,
rand() % cy,
rand() % 100 + 20,
rand() % 100 + 20,
100);
g_rasterizer.add_path(ell);
r.color(agg::gray8(rand() & 0xFF, rand() & 0xFF));
agg::render_scanlines(g_rasterizer, sl, r);
}
}
virtual void on_resize(int cx, int cy)
{
generate_alpha_mask(cx, cy);
}
virtual void on_draw()
{
int width = rbuf_window().width();
int height = rbuf_window().height();
typedef agg::scanline_u8_am<agg::alpha_mask_gray8> scanline_type;
typedef agg::renderer_base<agg::pixfmt_bgr24> ren_base;
typedef agg::renderer_scanline_aa_solid<ren_base> renderer;
agg::pixfmt_bgr24 pixf(rbuf_window());
ren_base rb(pixf);
renderer r(rb);
scanline_type sl(g_alpha_mask);
rb.clear(agg::rgba8(255, 255, 255));
agg::trans_affine mtx;
mtx *= agg::trans_affine_translation(-g_base_dx, -g_base_dy);
mtx *= agg::trans_affine_scaling(g_scale, g_scale);
mtx *= agg::trans_affine_rotation(g_angle + agg::pi);
mtx *= agg::trans_affine_skewing(g_skew_x/1000.0, g_skew_y/1000.0);
mtx *= agg::trans_affine_translation(width/2, height/2);
agg::conv_transform<agg::path_storage, agg::trans_affine> trans(g_path, mtx);
agg::render_all_paths(g_rasterizer, sl, r, trans, g_colors, g_path_idx, g_npaths);
}
void transform(double width, double height, double x, double y)
{
x -= width / 2;
y -= height / 2;
g_angle = atan2(y, x);
g_scale = sqrt(y * y + x * x) / 100.0;
}
virtual void on_mouse_button_down(int x, int y, unsigned flags)
{
if(flags & agg::mouse_left)
{
int width = rbuf_window().width();
int height = rbuf_window().height();
transform(width, height, x, y);
force_redraw();
}
if(flags & agg::mouse_right)
{
g_skew_x = x;
g_skew_y = y;
force_redraw();
}
}
virtual void on_mouse_move(int x, int y, unsigned flags)
{
on_mouse_button_down(x, y, flags);
}
};
int agg_main(int argc, char* argv[])
{
the_application app(agg::pix_format_bgr24, flip_y);
app.caption("AGG Example. Lion with Alpha-Masking");
if(app.init(512, 400, agg::window_resize))
{
return app.run();
}
return 1;
}
| 25.291457 | 90 | 0.598848 | [
"transform"
] |
14e80bc8d7c6748286e76a6c537eabc037168bc6 | 4,044 | cpp | C++ | examples/future_reduce/rnd_future_reduce.cpp | biddisco/pika | 6900b19b5bd0feea491c21f7557a863c0cf2b904 | [
"BSL-1.0"
] | 13 | 2022-01-17T12:01:48.000Z | 2022-03-16T10:03:14.000Z | examples/future_reduce/rnd_future_reduce.cpp | biddisco/pika | 6900b19b5bd0feea491c21f7557a863c0cf2b904 | [
"BSL-1.0"
] | 163 | 2022-01-17T17:36:45.000Z | 2022-03-31T17:42:57.000Z | examples/future_reduce/rnd_future_reduce.cpp | biddisco/pika | 6900b19b5bd0feea491c21f7557a863c0cf2b904 | [
"BSL-1.0"
] | 4 | 2022-01-19T08:44:22.000Z | 2022-01-31T23:16:21.000Z | // Copyright (c) 2014 John Biddiscombe
//
// SPDX-License-Identifier: BSL-1.0
// Distributed under the Boost Software License, Version 1.0. (See accompanying
// file LICENSE_1_0.txt or copy at http://www.boost.org/LICENSE_1_0.txt)
#include <pika/chrono.hpp>
#include <pika/future.hpp>
#include <pika/init.hpp>
#include <pika/runtime.hpp>
//
#include <iostream>
#include <random>
#include <utility>
#include <vector>
//
// This is a simple example which generates random numbers and returns
// pass or fail from a routine.
// When called by many threads returning a vector of futures - if the user wants to
// reduce the vector of pass/fails into a single pass fail based on a simple
// any fail = !pass rule, then this example shows how to do it.
// The user can experiment with the failure rate to see if the statistics match
// their expectations.
// Also. Routine can use either a lambda, or a function under control of USE_LAMBDA
#define TEST_SUCCESS 1
#define TEST_FAIL 0
//
#define FAILURE_RATE_PERCENT 5
#define SAMPLES_PER_LOOP 10
#define TEST_LOOPS 1000
//
std::random_device rseed;
std::mt19937 gen(rseed());
std::uniform_int_distribution<int> dist(0, 99); // interval [0,100)
#define USE_LAMBDA
//----------------------------------------------------------------------------
int reduce(pika::future<std::vector<pika::future<int>>>&& futvec)
{
int res = TEST_SUCCESS;
std::vector<pika::future<int>> vfs = futvec.get();
for (pika::future<int>& f : vfs)
{
if (f.get() == TEST_FAIL)
return TEST_FAIL;
}
return res;
}
//----------------------------------------------------------------------------
int generate_one()
{
// generate roughly x% fails
int result = TEST_SUCCESS;
if (dist(gen) >= (100 - FAILURE_RATE_PERCENT))
{
result = TEST_FAIL;
}
return result;
}
//----------------------------------------------------------------------------
pika::future<int> test_reduce()
{
std::vector<pika::future<int>> req_futures;
//
for (int i = 0; i < SAMPLES_PER_LOOP; i++)
{
// generate random sequence of pass/fails using % fail rate per incident
pika::future<int> result = pika::async(generate_one);
req_futures.push_back(std::move(result));
}
pika::future<std::vector<pika::future<int>>> all_ready =
pika::when_all(req_futures);
#ifdef USE_LAMBDA
pika::future<int> result = all_ready.then(
[](pika::future<std::vector<pika::future<int>>>&& futvec) -> int {
// futvec is ready or the lambda would not be called
std::vector<pika::future<int>> vfs = futvec.get();
// all futures in v are ready as fut is ready
int res = TEST_SUCCESS;
for (pika::future<int>& f : vfs)
{
if (f.get() == TEST_FAIL)
return TEST_FAIL;
}
return res;
});
#else
pika::future<int> result = all_ready.then(reduce);
#endif
//
return result;
}
//----------------------------------------------------------------------------
int pika_main()
{
pika::chrono::high_resolution_timer htimer;
// run N times and see if we get approximately the right amount of fails
int count = 0;
for (int i = 0; i < TEST_LOOPS; i++)
{
int result = test_reduce().get();
count += result;
}
double pr_pass =
std::pow(1.0 - FAILURE_RATE_PERCENT / 100.0, SAMPLES_PER_LOOP);
double exp_pass = TEST_LOOPS * pr_pass;
std::cout << "From " << TEST_LOOPS << " tests, we got "
<< "\n " << count << " passes"
<< "\n " << exp_pass << " expected \n"
<< "\n " << htimer.elapsed() << " seconds \n"
<< std::flush;
// Initiate shutdown of the runtime system.
return pika::finalize();
}
//----------------------------------------------------------------------------
int main(int argc, char* argv[])
{
// Initialize and run pika.
return pika::init(pika_main, argc, argv);
}
| 31.107692 | 83 | 0.560336 | [
"vector"
] |
14edbc8986ec2cc534b0d34584aabe2703c9004a | 13,751 | cpp | C++ | pxr/base/lib/tf/testenv/notice.cpp | unity3d-jp/USD | 0f146383613e1efe872ea7c85aa3536f170fcda2 | [
"BSD-3-Clause"
] | 7 | 2016-12-13T00:53:38.000Z | 2020-04-02T13:25:50.000Z | pxr/base/lib/tf/testenv/notice.cpp | unity3d-jp/USD | 0f146383613e1efe872ea7c85aa3536f170fcda2 | [
"BSD-3-Clause"
] | null | null | null | pxr/base/lib/tf/testenv/notice.cpp | unity3d-jp/USD | 0f146383613e1efe872ea7c85aa3536f170fcda2 | [
"BSD-3-Clause"
] | 2 | 2016-12-13T00:53:40.000Z | 2020-05-04T07:32:53.000Z | //
// Copyright 2016 Pixar
//
// Licensed under the Apache License, Version 2.0 (the "Apache License")
// with the following modification; you may not use this file except in
// compliance with the Apache License and the following modification to it:
// Section 6. Trademarks. is deleted and replaced with:
//
// 6. Trademarks. This License does not grant permission to use the trade
// names, trademarks, service marks, or product names of the Licensor
// and its affiliates, except as required to comply with Section 4(c) of
// the License and to reproduce the content of the NOTICE file.
//
// You may obtain a copy of the Apache License at
//
// http://www.apache.org/licenses/LICENSE-2.0
//
// Unless required by applicable law or agreed to in writing, software
// distributed under the Apache License with the above modification is
// distributed on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
// KIND, either express or implied. See the Apache License for the specific
// language governing permissions and limitations under the Apache License.
//
#include "pxr/base/tf/regTest.h"
#include "pxr/base/tf/notice.h"
#include "pxr/base/tf/type.h"
#include "pxr/base/tf/diagnosticLite.h"
#include "pxr/base/tf/weakBase.h"
#include "pxr/base/tf/weakPtr.h"
#include "pxr/base/arch/nap.h"
#include "pxr/base/arch/systemInfo.h"
#include <boost/function.hpp>
#include <cstdio>
#include <iostream>
#include <mutex>
#include <sstream>
#include <string>
#include <thread>
#include <vector>
using std::cout;
using std::endl;
using std::ostream;
using std::string;
using std::stringstream;
using std::vector;
class TestNotice : public TfNotice {
public:
TestNotice(const string& what)
: _what(what) {
}
~TestNotice();
const string& GetWhat() const {
return _what;
}
private:
const string _what;
};
TestNotice::~TestNotice() { }
class TestListener : public TfWeakBase {
public:
explicit TestListener(int identity)
: _identity(identity)
{
}
//! Called when a notice of any type is sent
void ProcessNotice(const TfNotice&) {
printf("Listener #%d: ProcessNotice got a notice\n", _identity);
}
void ProcessTestNotice(const TestNotice& n) {
printf("Listener #%d: ProcessTestNotice got %s\n", _identity,
n.GetWhat().c_str());
}
void ProcessMyTestNotice(const TestNotice& n,
TfWeakPtr<TestListener> const &sender) {
if ( ! sender ) {
printf("Listener #%d: ProcessMyTestNotice got %s from unknown sender\n", _identity,
n.GetWhat().c_str());
} else {
printf("Listener #%d: ProcessMyTestNotice got %s from Sender #%d\n", _identity,
n.GetWhat().c_str(), sender->_identity);
}
}
private:
int _identity;
};
//=================================================================
// test of threaded notices
stringstream workerThreadLog;
stringstream mainThreadLog;
vector<string> workerThreadList;
vector<string> mainThreadList;
std::mutex workerThreadLock;
std::mutex mainThreadLock;
static void
_DumpLog(ostream *log, vector<string> *li, std::mutex *mutex) {
std::lock_guard<std::mutex> lock(*mutex);
sort(li->begin(), li->end());
for(vector<string>::const_iterator n = li->begin();
n != li->end(); ++ n) {
*log << *n << endl;
}
li->clear();
}
class BaseNotice : public TfNotice {
public:
BaseNotice(const string& what) : _what(what) {}
~BaseNotice();
const string& GetWhat() const {
return _what;
}
protected:
const string _what;
};
BaseNotice::~BaseNotice() { }
class MainNotice : public BaseNotice {
public:
MainNotice(const string& what) : BaseNotice(what) {}
};
class WorkerNotice : public BaseNotice {
public:
WorkerNotice(const string& what) : BaseNotice(what) {}
};
class MainListener : public TfWeakBase {
public:
MainListener() {
// Register for invokation in any thread
TfWeakPtr<MainListener> me(this);
TfNotice::Register(me, &MainListener::ProcessNotice);
_processMainKey =
TfNotice::Register(me, &MainListener::ProcessMainNotice);
}
void Revoke() {
TfNotice::Revoke(_processMainKey);
}
void ProcessNotice(const TfNotice &n) {
std::lock_guard<std::mutex> lock(mainThreadLock);
mainThreadList.push_back("MainListener::ProcessNotice got notice of"
" type " + TfType::Find(n).GetTypeName());
}
void ProcessMainNotice(const MainNotice &n) {
std::lock_guard<std::mutex> lock(mainThreadLock);
mainThreadList.push_back("MainListener::ProcessMainNotice got " +
n.GetWhat());
}
private:
TfNotice::Key _processMainKey;
};
class WorkListener : public TfWeakBase {
public:
WorkListener() {
// Register for exclusive invokation in the worker (current) thread
TfWeakPtr<WorkListener> me(this);
_key = TfNotice::Register(me, &WorkListener::ProcessWorkerNotice);
}
void Revoke() {
TfNotice::Revoke(_key);
}
void ProcessWorkerNotice(const WorkerNotice &n) {
std::lock_guard<std::mutex> lock(workerThreadLock);
workerThreadList.push_back("WorkListener::ProcessWorkerNotice got " +
n.GetWhat());
}
private:
TfNotice::Key _key;
};
void WorkTask() {
// Create a listener for exclusive execution in the worker thread
WorkListener *workListener = new WorkListener();
// Send some notifications
workerThreadLog << "// WorkListener should respond once\n";
WorkerNotice("WorkerNotice 1").Send();
ArchNap(10);
::_DumpLog(&workerThreadLog, &workerThreadList, &workerThreadLock);
workListener->Revoke();
workerThreadLog << "// WorkListener should not respond\n";
WorkerNotice("WorkerNotice 2").Send();
::_DumpLog(&workerThreadLog, &workerThreadList, &workerThreadLock);
delete workListener;
}
static bool
_TestThreadedNotices()
{
// Create and register the main listener
MainListener *mainListener = new MainListener();
mainThreadLog << "// MainListener should respond four times\n";
// start the worker thread
std::thread workerThread(WorkTask);
MainNotice("Main notice 1").Send();
workerThread.join();
mainListener->Revoke();
::_DumpLog(&mainThreadLog, &mainThreadList, &mainThreadLock);
mainThreadLog << "// MainListener::ProcessNotice should respond once\n";
MainNotice("Main notice 2").Send();
::_DumpLog(&mainThreadLog, &mainThreadList, &mainThreadLock);
delete mainListener;
mainThreadLog << "// MainListener should not respond\n";
MainNotice("main: Error!").Send();
::_DumpLog(&mainThreadLog, &mainThreadList, &mainThreadLock);
cout << "\n--- Main Thread Log ---\n";
cout << mainThreadLog.str();
cout << "\n--- Work Thread Log ---\n";
cout << workerThreadLog.str();
return true;
}
struct SpoofSender : public TfWeakBase {
};
struct SpoofCheckListener : public TfWeakBase {
void ListenA(const TfNotice&, TfWeakPtr<SpoofSender> const &) {
printf("SpoofCheckListener: A\n");
hits++;
}
void ListenB(const TfNotice&) {
printf("SpoofCheckListener: B\n");
hits++;
}
void ListenC(const TfNotice&, TfType const &,
TfWeakBase*, const void *, const std::type_info&) {
printf("SpoofCheckListener: C\n");
hits++;
}
SpoofCheckListener() {
hits = 0;
}
int hits;
};
static void
_TestSpoofedNotices()
{
SpoofCheckListener listener;
char rawSpace[1024];
SpoofSender* rawSender = new (rawSpace) SpoofSender;
TfWeakPtr<SpoofSender> sender = TfCreateWeakPtr(rawSender);
TfNotice::Register(TfCreateWeakPtr(&listener),
&SpoofCheckListener::ListenA, sender);
TfNotice::Register(TfCreateWeakPtr(&listener),
&SpoofCheckListener::ListenB, sender);
TfNotice::Register(TfCreateWeakPtr(&listener),
&SpoofCheckListener::ListenC,
TfType::Find<TfNotice>(),
TfAnyWeakPtr(sender));
TF_AXIOM(listener.hits == 0);
printf("Expecting no replies to send...\n");
TfNotice().Send();
TF_AXIOM(listener.hits == 0);
printf("Expecting 3 replies to send...\n");
TfNotice().Send(sender);
TF_AXIOM(listener.hits == 3);
listener.hits = 0;
sender->~SpoofSender();
TF_AXIOM(sender.IsInvalid());
SpoofSender* rawSender2 = new (rawSpace) SpoofSender;
TfWeakPtr<SpoofSender> sender2 = TfCreateWeakPtr(rawSender2);
printf("Expecting no replies to send...\n");
TfNotice().Send(sender2);
TF_AXIOM(listener.hits == 0);
TfNotice::Register(TfCreateWeakPtr(&listener),
&SpoofCheckListener::ListenA, TfWeakPtr<SpoofSender>(NULL));
TfNotice::Register(TfCreateWeakPtr(&listener),
&SpoofCheckListener::ListenB);
TfNotice::Register(TfCreateWeakPtr(&listener),
&SpoofCheckListener::ListenC,
TfType::Find<TfNotice>(),
TfAnyWeakPtr());
printf("Expecting 3 replies to send...\n");
TfNotice().Send(sender2);
TF_AXIOM(listener.hits == 3);
listener.hits = 0;
printf("Expecting 3 replies to send...\n");
TfNotice().Send();
TF_AXIOM(listener.hits == 3);
}
struct BlockListener : public TfWeakBase
{
BlockListener() : mainId(std::this_thread::get_id())
{
hits[0] = 0;
hits[1] = 0;
TfNotice::Register(TfCreateWeakPtr(this), &BlockListener::Listen);
}
void Listen(const TfNotice& n)
{
++hits[std::this_thread::get_id() == mainId ? 0 : 1];
}
const std::thread::id mainId;
size_t hits[2];
};
static void
_TestNoticeBlockWorker(std::thread::id mainId)
{
struct _Work {
static void Go()
{
for (int i = 0; i < 20; ++i) {
TestNotice(TfStringPrintf("Notice %d", i)).Send();
}
}
};
if (std::this_thread::get_id() == mainId) {
TfNotice::Block block;
_Work::Go();
}
else {
_Work::Go();
}
}
static void
_TestNoticeBlock()
{
BlockListener l;
TestNotice("should not be blocked").Send();
assert(l.hits[0] == 1);
assert(l.hits[1] == 0);
{
TfNotice::Block noticeBlock;
TestNotice("should be blocked").Send();
assert(l.hits[0] == 1);
assert(l.hits[1] == 0);
TestNotice("should be blocked too").Send();
assert(l.hits[0] == 1);
assert(l.hits[1] == 0);
}
TestNotice("should not be blocked").Send();
assert(l.hits[0] == 2);
assert(l.hits[1] == 0);
std::thread t(_TestNoticeBlockWorker, std::this_thread::get_id());
_TestNoticeBlockWorker(std::this_thread::get_id());
t.join();
assert(l.hits[0] == 2);
assert(l.hits[1] == 20);
}
static bool
Test_TfNotice()
{
TestListener *l1 = new TestListener(1);
TestListener *l2 = new TestListener(2);
TfWeakPtr<TestListener> wl1(l1),
wl2(l2);
TfNotice::Key l1Key1 = TfNotice::Register(wl1, &TestListener::ProcessNotice);
/*TfNotice::Key l1Key2 =*/ TfNotice::Register(wl1, &TestListener::ProcessTestNotice);
/*TfNotice::Key l2Key1 =*/ TfNotice::Register(wl2, &TestListener::ProcessNotice);
TfNotice::Key l2Key2 = TfNotice::Register(wl2, &TestListener::ProcessTestNotice);
TfNotice::Key l2Key4 = TfNotice::Register(wl2, &TestListener::ProcessMyTestNotice, wl2);
printf("// Expect: #1 ProcessNotice\n");
printf("// Expect: #1 ProcessTestNotice\n");
printf("// Expect: #2 ProcessNotice\n");
printf("// Expect: #2 ProcessTestNotice\n");
printf("// Expect: #2 ProcessMyTestNotice from unknown\n");
TestNotice("first").Send();
printf("// Expect: #1 ProcessNotice\n");
printf("// Expect: #1 ProcessTestNotice\n");
printf("// Expect: #2 ProcessNotice\n");
printf("// Expect: #2 ProcessTestNotice\n");
printf("// Expect: #2 ProcessMyTestNotice from #2\n");
printf("// Expect: #2 ProcessMyTestNotice from #2\n");
TestNotice("second").Send(wl2);
printf("// Expect: #1 ProcessNotice\n");
printf("// Expect: #1 ProcessTestNotice\n");
printf("// Expect: #2 ProcessNotice\n");
printf("// Expect: #2 ProcessMyTestNotice from #1\n");
TfNotice::Revoke(l2Key2);
TestNotice("third").Send(wl1);
printf("// Expect: #1 ProcessTestNotice\n");
printf("// Expect: #2 ProcessNotice\n");
printf("// Expect: #2 ProcessMyTestNotice from #2\n");
printf("// Expect: #2 ProcessMyTestNotice from #2\n");
TfNotice::Revoke(l1Key1);
TestNotice("fourth").Send(wl2);
printf("// Expect: #1 ProcessTestNotice\n");
printf("// Expect: #2 ProcessNotice\n");
printf("// Expect: #2 ProcessMyTestNotice from #2\n");
TfNotice::Revoke(l2Key4);
TestNotice("fifth").Send(wl2);
printf("// Expect: #1 ProcessTestNotice\n");
printf("// Expect: #2 ProcessNotice\n");
printf("// Expect: #2 ProcessMyTestNotice from #2\n");
TestNotice("sixth").SendWithWeakBase(&wl2->__GetTfWeakBase__(),
wl2.GetUniqueIdentifier(),
typeid(TestListener));
delete l2;
printf("// Expect: #1 ProcessTestNotice\n");
TestNotice("seventh").Send(wl2);
delete l1;
printf("// Expect: nothing\n");
TestNotice("error!").Send();
::_TestThreadedNotices();
::_TestSpoofedNotices();
::_TestNoticeBlock();
return true;
}
TF_REGISTRY_FUNCTION(TfType)
{
TfType::Define<TestNotice, TfType::Bases<TfNotice> >();
TfType::Define<MainNotice, TfType::Bases<TfNotice> >();
TfType::Define<WorkerNotice, TfType::Bases<TfNotice> >();
}
TF_ADD_REGTEST(TfNotice);
| 27.175889 | 92 | 0.640463 | [
"vector"
] |
14efd5f1f16b95964007e6902690dd6899cd5ea4 | 4,266 | cc | C++ | packager/media/formats/webm/webm_crypto_helpers.cc | koln67/shaka-packager | 5b9fd409a5de502e8af2e46ee12840bd2226874d | [
"BSD-3-Clause-No-Nuclear-License-2014",
"BSD-3-Clause"
] | 1,288 | 2016-05-25T01:20:31.000Z | 2022-03-02T23:56:56.000Z | packager/media/formats/webm/webm_crypto_helpers.cc | koln67/shaka-packager | 5b9fd409a5de502e8af2e46ee12840bd2226874d | [
"BSD-3-Clause-No-Nuclear-License-2014",
"BSD-3-Clause"
] | 894 | 2016-05-17T00:39:30.000Z | 2022-03-02T18:46:21.000Z | packager/media/formats/webm/webm_crypto_helpers.cc | koln67/shaka-packager | 5b9fd409a5de502e8af2e46ee12840bd2226874d | [
"BSD-3-Clause-No-Nuclear-License-2014",
"BSD-3-Clause"
] | 400 | 2016-05-25T01:20:35.000Z | 2022-03-03T02:12:00.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 "packager/media/formats/webm/webm_crypto_helpers.h"
#include "packager/base/logging.h"
#include "packager/base/sys_byteorder.h"
#include "packager/media/base/buffer_reader.h"
#include "packager/media/formats/webm/webm_constants.h"
namespace shaka {
namespace media {
namespace {
// Generates a 16 byte CTR counter block. The CTR counter block format is a
// CTR IV appended with a CTR block counter. |iv| is an 8 byte CTR IV.
// |iv_size| is the size of |iv| in btyes. Returns a string of
// kDecryptionKeySize bytes.
std::vector<uint8_t> GenerateWebMCounterBlock(const uint8_t* iv, int iv_size) {
std::vector<uint8_t> counter_block(iv, iv + iv_size);
counter_block.insert(counter_block.end(),
DecryptConfig::kDecryptionKeySize - iv_size, 0);
return counter_block;
}
} // namespace anonymous
// TODO(tinskip): Add unit test for this function.
bool WebMCreateDecryptConfig(const uint8_t* data,
int data_size,
const uint8_t* key_id,
size_t key_id_size,
std::unique_ptr<DecryptConfig>* decrypt_config,
int* data_offset) {
int header_size = kWebMSignalByteSize;
if (data_size < header_size) {
DVLOG(1) << "Empty WebM sample.";
return false;
}
uint8_t signal_byte = data[0];
if (signal_byte & kWebMEncryptedSignal) {
// Encrypted sample.
header_size += kWebMIvSize;
if (data_size < header_size) {
DVLOG(1) << "Encrypted WebM sample too small to hold IV: " << data_size;
return false;
}
std::vector<SubsampleEntry> subsamples;
if (signal_byte & kWebMPartitionedSignal) {
// Encrypted sample with subsamples / partitioning.
header_size += kWebMNumPartitionsSize;
if (data_size < header_size) {
DVLOG(1)
<< "Encrypted WebM sample too small to hold number of partitions: "
<< data_size;
return false;
}
uint8_t num_partitions = data[kWebMSignalByteSize + kWebMIvSize];
BufferReader offsets_buffer(data + header_size, data_size - header_size);
header_size += num_partitions * kWebMPartitionOffsetSize;
uint32_t subsample_offset = 0;
bool encrypted_subsample = false;
uint16_t clear_size = 0;
uint32_t encrypted_size = 0;
for (uint8_t partition_idx = 0; partition_idx < num_partitions;
++partition_idx) {
uint32_t partition_offset;
if (!offsets_buffer.Read4(&partition_offset)) {
DVLOG(1)
<< "Encrypted WebM sample too small to hold partition offsets: "
<< data_size;
return false;
}
if (partition_offset < subsample_offset) {
DVLOG(1) << "Partition offsets out of order.";
return false;
}
if (encrypted_subsample) {
encrypted_size = partition_offset - subsample_offset;
subsamples.push_back(SubsampleEntry(clear_size, encrypted_size));
} else {
clear_size = partition_offset - subsample_offset;
if (partition_idx == (num_partitions - 1)) {
encrypted_size = data_size - header_size - subsample_offset - clear_size;
subsamples.push_back(SubsampleEntry(clear_size, encrypted_size));
}
}
subsample_offset = partition_offset;
encrypted_subsample = !encrypted_subsample;
}
if (!(num_partitions % 2)) {
// Even number of partitions. Add one last all-clear subsample.
clear_size = data_size - header_size - subsample_offset;
encrypted_size = 0;
subsamples.push_back(SubsampleEntry(clear_size, encrypted_size));
}
}
decrypt_config->reset(new DecryptConfig(
std::vector<uint8_t>(key_id, key_id + key_id_size),
GenerateWebMCounterBlock(data + kWebMSignalByteSize, kWebMIvSize),
subsamples));
} else {
// Clear sample.
decrypt_config->reset();
}
*data_offset = header_size;
return true;
}
} // namespace media
} // namespace shaka
| 37.095652 | 85 | 0.650258 | [
"vector"
] |
14f777d20ec0eb3dcd9da0edde0458529859b54f | 9,304 | cpp | C++ | tests/Unit/Helpers/ApparentHorizons/StrahlkorperGrTestHelpers.cpp | geoffrey4444/spectre | 9350d61830b360e2d5b273fdd176dcc841dbefb0 | [
"MIT"
] | 1 | 2021-04-02T16:49:35.000Z | 2021-04-02T16:49:35.000Z | tests/Unit/Helpers/ApparentHorizons/StrahlkorperGrTestHelpers.cpp | GitHimanshuc/spectre | 4de4033ba36547113293fe4dbdd77591485a4aee | [
"MIT"
] | 19 | 2019-02-27T22:13:47.000Z | 2020-09-03T16:21:08.000Z | tests/Unit/Helpers/ApparentHorizons/StrahlkorperGrTestHelpers.cpp | geoffrey4444/spectre | 9350d61830b360e2d5b273fdd176dcc841dbefb0 | [
"MIT"
] | null | null | null | // Distributed under the MIT License.
// See LICENSE.txt for details.
#include "Helpers/ApparentHorizons/StrahlkorperGrTestHelpers.hpp"
#include <cmath>
#include <cstddef>
#include <vector>
#include "ApparentHorizons/YlmSpherepack.hpp"
#include "DataStructures/DataVector.hpp" // IWYU pragma: keep
#include "DataStructures/Tensor/EagerMath/Magnitude.hpp" // IWYU pragma: keep
#include "DataStructures/Tensor/Tensor.hpp"
#include "Utilities/ConstantExpressions.hpp"
#include "Utilities/GenerateInstantiations.hpp"
#include "Utilities/MakeWithValue.hpp"
#include "Utilities/StdArrayHelpers.hpp"
// IWYU pragma: no_forward_declare Tensor
namespace TestHelpers {
namespace Schwarzschild {
template <size_t SpatialDim, typename Frame, typename DataType>
tnsr::ii<DataType, SpatialDim, Frame> spatial_ricci(
const tnsr::I<DataType, SpatialDim, Frame>& x, const double mass) {
auto ricci = make_with_value<tnsr::ii<DataType, SpatialDim, Frame>>(x, 0.);
constexpr auto dimensionality = index_dim<0>(ricci);
const DataType r = get(magnitude(x));
for (size_t i = 0; i < dimensionality; ++i) {
for (size_t j = i; j < dimensionality; ++j) {
ricci.get(i, j) -= (8.0 * mass + 3.0 * r) * x.get(i) * x.get(j);
if (i == j) {
ricci.get(i, j) += square(r) * (4.0 * mass + r);
}
ricci.get(i, j) *= mass;
ricci.get(i, j) /= pow<4>(r) * square(2.0 * mass + r);
}
}
return ricci;
}
} // namespace Schwarzschild
namespace Minkowski {
template <size_t SpatialDim, typename Frame, typename DataType>
tnsr::ii<DataType, SpatialDim, Frame> extrinsic_curvature_sphere(
const tnsr::I<DataType, SpatialDim, Frame>& x) {
auto extrinsic_curvature =
make_with_value<tnsr::ii<DataType, SpatialDim, Frame>>(x, 0.);
constexpr auto dimensionality = index_dim<0>(extrinsic_curvature);
const DataType one_over_r = 1.0 / get(magnitude(x));
for (size_t i = 0; i < dimensionality; ++i) {
extrinsic_curvature.get(i, i) += 1.0;
for (size_t j = i; j < dimensionality; ++j) {
extrinsic_curvature.get(i, j) -= x.get(i) * x.get(j) * square(one_over_r);
extrinsic_curvature.get(i, j) *= one_over_r;
}
}
return extrinsic_curvature;
}
} // namespace Minkowski
namespace Kerr {
template <typename DataType>
Scalar<DataType> horizon_ricci_scalar(const Scalar<DataType>& horizon_radius,
const double mass,
const double dimensionless_spin_z) {
// Compute Kerr spin parameter a
// This is the magnitude of the dimensionless spin times the mass
double kerr_spin_a = mass * dimensionless_spin_z;
// Compute the Boyer-Lindquist horizon radius, r+
const double kerr_r_plus = mass + sqrt(square(mass) - square(kerr_spin_a));
// Get the Ricci scalar of the horizon, e.g. Eq. (119) of
// https://arxiv.org/abs/0706.0622
// The precise relation used here is derived in
// https://v2.overleaf.com/read/twdtxchyrtyv
Scalar<DataVector> ricci_scalar(
2.0 * (square(kerr_r_plus) + square(kerr_spin_a)) *
(3.0 * square(get(horizon_radius)) - 2.0 * square(kerr_r_plus) -
3.0 * square(kerr_spin_a)));
get(ricci_scalar) /= cube(-1.0 * square(get(horizon_radius)) +
square(kerr_spin_a) + 2.0 * square(kerr_r_plus));
return ricci_scalar;
}
template <typename DataType>
Scalar<DataType> horizon_ricci_scalar(
const Scalar<DataType>& horizon_radius_with_spin_on_z_axis,
const YlmSpherepack& ylm_with_spin_on_z_axis, const YlmSpherepack& ylm,
const double mass, const std::array<double, 3>& dimensionless_spin) {
// get the dimensionless spin magnitude and direction
const double spin_magnitude = magnitude(dimensionless_spin);
const double spin_theta =
atan2(sqrt(square(dimensionless_spin[0]) + square(dimensionless_spin[1])),
dimensionless_spin[2]);
// Return the aligned-spin result if spin is close enough to the z axis,
// to avoid a floating-point exception. The choice of eps here is arbitrary.
const double eps = 1.e-10;
// There are 2 YlmSpherepacks: i) ylm, for the actual black hole, with spin
// in a generic direction, and ii) ylm_with_spin_on_z_axis, for a black hole
// with the same spin magnitude but with the spin in the +z direction.
// To get the horizon Ricci scalar for the actual black hole, do this:
// 1. Find the horizon Ricci scalar for the aligned spin
// 2. Let the generic spin point in direction (spin_theta, spin_phi).
// Rotate the ylm.theta_phi_points by -spin_phi about the z axis and
// then by -spin_theta about the y axis, so the point
// (spin_theta, spin_phi) is mapped to (0, 0), the +z axis.
// 3. Interpolate the aligned-spin Ricci scalar from step 1 at each
// rotated point from step 2 to get the horizon Ricci scalar
// for the corresponding (unrotated) ylm_theta_phi_points.
// Get the ricci scalar for a Kerr black hole with spin in the +z direction
// but same mass and spin magnitude
auto ricci_scalar_with_spin_on_z_axis = horizon_ricci_scalar(
horizon_radius_with_spin_on_z_axis, mass, spin_magnitude);
// Is the spin aligned? If so, just return the aligned-spin scalar curvature
if (abs(spin_theta) < eps or abs(spin_theta - M_PI) < eps) {
return ricci_scalar_with_spin_on_z_axis;
}
const double spin_phi = atan2(dimensionless_spin[1], dimensionless_spin[0]);
// Get the theta and phi points on the original Strahlkorper, where the
// spin is not on the z axis
const auto theta_phi_points = ylm.theta_phi_points();
// Rotate each point
// Get thethas and phis on the actual horizon
const DataVector thetas = theta_phi_points[0];
const DataVector phis = theta_phi_points[1];
// Rotate the coordinates on the original Strahlkorper so that a point
// on the spin axis gets mapped to a point on the +z axis.
// This means the new coordinates are rotated from the old ones by
// -spin_phi about the z axis and then by -spin_theta about the y axis.
// The unrotated x,y,z coordinates are defined on the unit sphere:
// x = sin(theta)*cos(phi), y = sin(theta) * sin(phi), z = cos(theta)
const DataVector x_new =
cos(spin_theta) * cos(phis - spin_phi) * sin(thetas) -
cos(thetas) * sin(spin_theta);
const DataVector y_new = sin(thetas) * sin(phis - spin_phi);
const DataVector z_new = cos(thetas) * cos(spin_theta) +
cos(phis - spin_phi) * sin(thetas) * sin(spin_theta);
// Since I'm rotating on the unit sphere, the radius of the unrotated and
// new points is unity.
DataVector thetas_new = atan2(sqrt(square(x_new) + square(y_new)), z_new);
DataVector phis_new(thetas_new.size());
for (size_t i = 0; i < thetas_new.size(); ++i) {
double phi_new =
(abs(thetas_new[i]) > eps and abs(thetas_new[i] - M_PI) > eps)
? atan2(y_new[i], x_new[i])
: 0.0;
// Ensure phi_new is between 0 and 2 pi.
if (phi_new < 0.0) {
phi_new += 2.0 * M_PI;
}
phis_new[i] = phi_new;
}
std::array<DataVector, 2> points{std::move(thetas_new), std::move(phis_new)};
// Interpolate ricci_scalar_with_spin_on_z_axis onto the new points
auto interpolation_info =
ylm_with_spin_on_z_axis.set_up_interpolation_info(points);
DataVector ricci_scalar_interpolated(interpolation_info.size());
ylm_with_spin_on_z_axis.interpolate(
make_not_null(&ricci_scalar_interpolated),
get(ricci_scalar_with_spin_on_z_axis).data(), interpolation_info);
// Load the interpolated values into the DataVector ricci_scalar
Scalar<DataVector> ricci_scalar =
make_with_value<Scalar<DataVector>>(theta_phi_points[0], 0.0);
for (size_t i = 0; i < get(ricci_scalar_with_spin_on_z_axis).size(); ++i) {
get(ricci_scalar)[i] = ricci_scalar_interpolated[i];
}
return ricci_scalar;
}
} // namespace Kerr
} // namespace TestHelpers
#define DIM(data) BOOST_PP_TUPLE_ELEM(0, data)
#define DTYPE(data) BOOST_PP_TUPLE_ELEM(1, data)
#define FRAME(data) BOOST_PP_TUPLE_ELEM(2, data)
#define INDEXTYPE(data) BOOST_PP_TUPLE_ELEM(3, data)
#define INSTANTIATE(_, data) \
template tnsr::ii<DTYPE(data), DIM(data), FRAME(data)> \
TestHelpers::Schwarzschild::spatial_ricci( \
const tnsr::I<DTYPE(data), DIM(data), FRAME(data)>& x, \
const double mass); \
template tnsr::ii<DTYPE(data), DIM(data), FRAME(data)> \
TestHelpers::Minkowski::extrinsic_curvature_sphere( \
const tnsr::I<DTYPE(data), DIM(data), FRAME(data)>& x);
GENERATE_INSTANTIATIONS(INSTANTIATE, (3), (double, DataVector),
(Frame::Grid, Frame::Inertial))
#undef DIM
#undef DTYPE
#undef FRAME
#undef INDEXTYPE
#undef INSTANTIATE
template Scalar<DataVector> TestHelpers::Kerr::horizon_ricci_scalar(
const Scalar<DataVector>& horizon_radius, const double mass,
const double dimensionless_spin_z);
template Scalar<DataVector> TestHelpers::Kerr::horizon_ricci_scalar(
const Scalar<DataVector>& horizon_radius_with_spin_on_z_axis,
const YlmSpherepack& ylm_with_spin_on_z_axis, const YlmSpherepack& ylm,
const double mass, const std::array<double, 3>& spin);
| 40.986784 | 80 | 0.691638 | [
"vector"
] |
14fa598fd38104066243ea29964d94ac83181449 | 5,966 | cpp | C++ | src/hawck-inputd.cpp | aidanharris/Hawck | aab56e85fb7408d9020f6e387b93d9f18d902415 | [
"BSD-2-Clause"
] | null | null | null | src/hawck-inputd.cpp | aidanharris/Hawck | aab56e85fb7408d9020f6e387b93d9f18d902415 | [
"BSD-2-Clause"
] | null | null | null | src/hawck-inputd.cpp | aidanharris/Hawck | aab56e85fb7408d9020f6e387b93d9f18d902415 | [
"BSD-2-Clause"
] | null | null | null | #include <string>
#include <fstream>
#include "KBDDaemon.hpp"
#include "Daemon.hpp"
#include "utils.hpp"
#if MESON_COMPILE
#include <hawck_config.h>
#else
#define INPUTD_VERSION "unknown"
#endif
extern "C" {
#include <signal.h>
#include <getopt.h>
#include <syslog.h>
}
using namespace std;
static void handleSigPipe(int) {
// cout << "KBDDaemon aborting due to SIGPIPE" << endl;
// abort();
}
static int no_fork;
auto varToOption(string opt) {
replace(opt.begin(), opt.end(), '_', '-');
return opt;
}
#define VAR_TO_OPTION(_var) varToOption(#_var)
auto numOption(const string& name, int *num) {
return [num, name](const string& opt) {
try {
*num = stoi(opt);
} catch (const exception &e) {
cout << "--" << name << ": Require an integer" << endl;
exit(0);
}
};
}
auto strOption(const string&, string *str) {
return [str](const string& opt) {
*str = opt;
};
}
#define NUM_OPTION(_name) {VAR_TO_OPTION(_name), numOption(VAR_TO_OPTION(_name), &(_name))},
#define STR_OPTION(_name) {VAR_TO_OPTION(_name), strOption(VAR_TO_OPTION(_name), &(_name))}
int main(int argc, char *argv[]) {
signal(SIGPIPE, handleSigPipe);
string HELP =
"Usage: hawck-inputd [--udev-event-delay <us>] [--no-fork] [--socket-timeout] -k <device>\n"
"\n"
"Examples:\n"
" hawck-inputd --kbd-device /dev/input/event13 Listen on a single device.\n\n"
" hawck-inputd -k{/dev/input/event13,/dev/input/event15} Listen on multiple devices.\n\n"
" hawck-inputd $(/usr/share/hawck/bin/get-kbd-args.sh) Listen on all keyboard devices.\n\n"
"Options:\n"
" --no-fork Don't daemonize/fork.\n"
" -h, --help Display this help information.\n"
" --version Display version and exit.\n"
" -k, --kbd-device Add a keyboard to listen to.\n"
" --udev-event-delay Delay between events sent on the udevice in us.\n"
" --socket-timeout Time in milliseconds until timeout on sockets.\n"
;
//daemonize("/var/log/hawck-input/log");
static struct option long_options[] =
{
/* These options set a flag. */
{"no-fork", no_argument, &no_fork, 1},
{"udev-event-delay", required_argument, 0, 0},
{"socket-timeout", required_argument, 0, 0},
{"version", no_argument, 0, 0},
/* These options don’t set a flag.
We distinguish them by their indices. */
{"help", no_argument, 0, 'h'},
{"kbd-device", required_argument, 0, 'k'},
{"kbd-name", required_argument, 0, 'n'},
{0, 0, 0, 0}
};
/* getopt_long stores the option index here. */
int option_index = 0;
int udev_event_delay = 3800;
int socket_timeout = 1024;
vector<string> kbd_names;
vector<string> kbd_devices;
unordered_map<string, function<void(const string& opt)>> long_handlers = {
{"version", [&](const string&) {
cout << "Hawck InputD v" INPUTD_VERSION << endl;
exit(0);
}},
NUM_OPTION(udev_event_delay)
NUM_OPTION(socket_timeout)
};
do {
int c = getopt_long(argc, argv, "hk:n:",
long_options, &option_index);
/* Detect the end of the options. */
if (c == -1)
break;
switch (c) {
case 0: {
/* If this option set a flag, do nothing else now. */
if (long_options[option_index].flag != 0)
break;
string name(long_options[option_index].name);
string arg(optarg ? optarg : "");
if (long_handlers.find(name) != long_handlers.end())
long_handlers[name](arg);
break;
}
case 'k':
kbd_devices.push_back(string(optarg));
break;
// TODO: Implement lookup of keyboard names
case 'n':
cout << "Option -n/--kbd-name: Not implemented." << endl;
break;
case 'h':
cout << HELP;
exit(0);
case '?':
/* getopt_long already printed an error message. */
break;
default:
cout << "DEFAULT" << endl;
abort ();
}
} while (true);
if (kbd_devices.size() == 0) {
cout << "Unable to start Hawck InputD without any keyboard devices." << endl;
exit(0);
}
remove("/var/lib/hawck-input/pid");
cout << "Starting Hawck InputD v" INPUTD_VERSION " on:" << endl;
for (const auto& dev : kbd_devices)
cout << " - <" << dev << ">" << endl;
if (!no_fork) {
cout << "forking ..." << endl;
daemonize("/tmp/hawck-inputd.log");
}
// Write pid
try {
ofstream ostream("/var/lib/hawck-input/pid");
ostream << getpid();
} catch (const exception &e) {
throw SystemError("Unable to write pid: ", errno);
}
try {
cout << "Settin up daemon ..." << endl;
KBDDaemon daemon;
cout << "Adding devices ..." << endl;
for (const auto& dev : kbd_devices)
daemon.addDevice(dev);
daemon.setEventDelay(udev_event_delay);
daemon.setSocketTimeout(socket_timeout);
syslog(LOG_INFO, "Running Hawck InputD ...");
cout << "Running ..." << endl;
daemon.run();
} catch (const exception &e) {
syslog(LOG_CRIT, "Abort due to exception: %s", e.what());
cout << "Error: " << e.what() << endl;
remove("/var/lib/hawck-input/pid");
throw;
}
}
| 31.235602 | 103 | 0.519779 | [
"vector"
] |
14fb4b552fb120ed42d36c570a3bb24ad14c7adc | 1,101 | cpp | C++ | algorithms/cpp/522.cpp | viing937/leetcode | e21ca52c98bddf59e43522c0aace5e8cf84350eb | [
"MIT"
] | 3 | 2016-10-01T10:15:09.000Z | 2017-07-09T02:53:36.000Z | algorithms/cpp/522.cpp | viing937/leetcode | e21ca52c98bddf59e43522c0aace5e8cf84350eb | [
"MIT"
] | null | null | null | algorithms/cpp/522.cpp | viing937/leetcode | e21ca52c98bddf59e43522c0aace5e8cf84350eb | [
"MIT"
] | null | null | null | #include <iostream>
#include <vector>
#include <map>
#include <algorithm>
using namespace std;
class Solution {
private:
bool isSubSeq(const string &s, const string &q) {
if (s.size() < q.size())
return false;
int idx = 0;
for (int i = 0; i < s.size() && idx < q.size(); i++) {
if (s[i] == q[idx])
idx += 1;
}
return idx == q.size();
}
static bool compare(const string &a, const string &b) {
return a.size() > b.size();
}
public:
int findLUSlength(vector<string> &strs) {
sort(strs.begin(), strs.end(), compare);
for (int i = 0; i < strs.size(); i++) {
int flag = false;
for (int j = 0; j < strs.size(); j++)
if (i != j && isSubSeq(strs[j], strs[i]))
flag = true;
if (!flag)
return strs[i].size();
}
return -1;
}
};
int main() {
vector<string> strs = {"aabbcc", "aabbcc","c","e","aabbcd"};
Solution solution;
solution.findLUSlength(strs);
return 0;
}
| 25.604651 | 64 | 0.476839 | [
"vector"
] |
14fef47334a00933e62b79ea8cdb7ba528e3284c | 7,209 | cc | C++ | ocr-pfst/ocrofst-io.cc | michaelyin/ocropus-git | b2673354bbcfba38f7a807708f64cd33aaeb0f6d | [
"Apache-2.0"
] | 3 | 2016-06-24T10:48:36.000Z | 2020-07-04T16:00:41.000Z | ocr-pfst/ocrofst-io.cc | michaelyin/ocropus-git | b2673354bbcfba38f7a807708f64cd33aaeb0f6d | [
"Apache-2.0"
] | null | null | null | ocr-pfst/ocrofst-io.cc | michaelyin/ocropus-git | b2673354bbcfba38f7a807708f64cd33aaeb0f6d | [
"Apache-2.0"
] | 11 | 2016-06-24T09:35:57.000Z | 2020-12-01T21:26:43.000Z | // Copyright 2008 Deutsches Forschungszentrum fuer Kuenstliche Intelligenz
// or its licensors, as applicable.
//
// You may not use this file except under the terms of the accompanying license.
//
// 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.
//
// Project: ocrofst
// File: fst-io.cc
// Purpose: OpenFST-compatible I/O
// Responsible: mezhirov
// Reviewer:
// Primary Repository:
// Web Sites: www.iupr.org, www.dfki.de, www.ocropus.org
//
#include <stdio.h>
#include <stdint.h>
#include "ocr-pfst.h"
using namespace colib;
using namespace ocropus;
enum {
// They say it also encodes endianness. But I haven't seen any BE variant.
OPENFST_MAGIC = 2125659606,
OPENFST_SYMBOL_TABLE_MAGIC = 2125658996,
FLAG_HAS_ISYMBOLS = 1,
FLAG_HAS_OSYMBOLS = 2,
MIN_VERSION = 2,
PROPERTIES = 3 // expanded, mutable
};
static int32_t read_int32_LE(FILE *stream) {
int n = fgetc(stream);
n |= fgetc(stream) << 8;
n |= fgetc(stream) << 16;
n |= fgetc(stream) << 24;
return n;
}
static void write_int32_LE(FILE *stream, int32_t n) {
fputc(n, stream);
fputc(n >> 8, stream);
fputc(n >> 16, stream);
fputc(n >> 24, stream);
}
static int64_t read_int64_LE(FILE *stream) {
int64_t n = read_int32_LE(stream);
n |= int64_t(read_int32_LE(stream)) << 32;
return n;
}
static void write_int64_LE(FILE *stream, int64_t n) {
write_int32_LE(stream, n);
write_int32_LE(stream, n >> 32);
}
static bool read_magic_string(FILE *stream, const char *s) {
int n = read_int32_LE(stream);
if(strlen(s) != n)
return false;
for(int i = 0; i < n; i++) {
if(fgetc(stream) != s[i])
return false;
}
return true;
}
static void skip_string(FILE *stream) {
int n = read_int32_LE(stream);
fseek(stream, n, SEEK_CUR);
}
static void write_string(FILE *stream, const char *s) {
int n = strlen(s);
write_int32_LE(stream, n);
for(int i = 0; i < n; i++)
fputc(s[i], stream);
}
// This is probably not a good way but that's what OpenFST does anyway.
static bool write_float(FILE *stream, float f) {
return fwrite(&f, 1, sizeof(f), stream) == sizeof(f);
}
static float read_float(FILE *stream) {
float result;
if(fread(&result, 1, sizeof(result), stream) != sizeof(result)) {
// cry
}
return result;
}
// _______________________ high-level functions ___________________________
static bool skip_symbol_table(FILE *stream) {
if(read_int32_LE(stream) != OPENFST_SYMBOL_TABLE_MAGIC)
return false;
skip_string(stream); // name
read_int64_LE(stream); // available key
int64_t n = read_int64_LE(stream);
for(int i = 0; i < n; i++) {
skip_string(stream); // key
read_int64_LE(stream); // value
}
return !ferror(stream) && !feof(stream);
}
static const char *read_header_and_symbols(IGenericFst &fst, FILE *stream) {
if(read_int32_LE(stream) != OPENFST_MAGIC)
return "invalid magic number";
read_magic_string(stream, "vector");
read_magic_string(stream, "standard");
int version = read_int32_LE(stream);
if(version < MIN_VERSION)
return "file has too old version";
int flags = read_int32_LE(stream);
read_int64_LE(stream); // properties
int64_t start = read_int64_LE(stream);
int64_t nstates = read_int64_LE(stream);
if(nstates < 0)
return false; // to prevent creating 2^31 nodes in case of sudden EOF
fst.clear();
for(int i = 0; i < nstates; i++)
fst.newState();
fst.setStart(start);
read_int64_LE(stream); // narcs
if(flags & FLAG_HAS_ISYMBOLS)
skip_symbol_table(stream);
if(flags & FLAG_HAS_OSYMBOLS)
skip_symbol_table(stream);
if(ferror(stream))
return "error in the stream";
if(feof(stream))
return "unexpected EOF";
return NULL;
}
/*static int64_t narcs(IGenericFst &fst) {
intarray inputs;
intarray targets;
intarray outputs;
floatarray costs;
int64_t result = 0;
for(int i = 0; i < fst.nStates(); i++) {
fst.arcs(inputs, targets, outputs, costs, i);
result += targets.length();
}
return result;
}*/
static void write_header_and_symbols(FILE *stream, IGenericFst &fst) {
write_int32_LE(stream, OPENFST_MAGIC);
write_string(stream, "vector");
write_string(stream, "standard");
write_int32_LE(stream, MIN_VERSION);
write_int32_LE(stream, /* flags: */ 0);
write_int64_LE(stream, PROPERTIES);
write_int64_LE(stream, fst.getStart());
write_int64_LE(stream, fst.nStates());
write_int64_LE(stream, /* narcs (seems to be unused): */ 0);
}
static void write_node(FILE *stream, IGenericFst &fst, int index) {
intarray inputs;
intarray targets;
intarray outputs;
floatarray costs;
fst.arcs(inputs, targets, outputs, costs, index);
int narcs = targets.length();
// By convention, anything larger than 1e37 is treated
// as infinite accept cost (=no final state) in OCRopus.
// This makes such files look right in the OpenFST tools.
float cost = fst.getAcceptCost(index);
if(cost>1e37) cost = INFINITY;
write_float(stream,cost);
write_int64_LE(stream, narcs);
for(int i = 0; i < narcs; i++) {
write_int32_LE(stream, inputs[i]);
write_int32_LE(stream, outputs[i]);
write_float(stream, costs[i]);
write_int32_LE(stream, targets[i]);
}
}
static void read_node(FILE *stream, IGenericFst &fst, int index) {
// We don't bother undoing the "inf" from the binary FST files;
// the OCRopus search algorithms should deal fine with them.
fst.setAccept(index, read_float(stream));
int narcs = read_int64_LE(stream);
for(int i = 0; i < narcs; i++) {
int input = read_int32_LE(stream);
int output = read_int32_LE(stream);
float cost = read_float(stream);
int target = read_int32_LE(stream);
fst.addTransition(index, target, output, cost, input);
}
}
namespace ocropus {
void fst_write(FILE *stream, IGenericFst &fst) {
write_header_and_symbols(stream, fst);
for(int i = 0; i < fst.nStates(); i++)
write_node(stream, fst, i);
}
void fst_read(IGenericFst &fst, FILE *stream) {
const char *errmsg = read_header_and_symbols(fst, stream);
if(errmsg)
throw errmsg;
for(int i = 0; i < fst.nStates(); i++)
read_node(stream, fst, i);
}
void fst_write(const char *path, IGenericFst &fst) {
fst_write(stdio(path, "wb"), fst);
}
void fst_read(IGenericFst &fst, const char *path) {
fst_read(fst, stdio(path, "rb"));
}
}
| 29.545082 | 80 | 0.652102 | [
"vector"
] |
0901109925042ae3d4bb6525fafc542bdc22cd7d | 10,569 | cpp | C++ | src/gl/renderer/gl_renderstate.cpp | atsb/ReGLOOME | 2770853677513f204e9282c71d3fd38e4cd6c472 | [
"Unlicense"
] | 79 | 2015-07-07T00:54:33.000Z | 2022-01-31T05:26:12.000Z | src/gl/renderer/gl_renderstate.cpp | atsb/ReGLOOME | 2770853677513f204e9282c71d3fd38e4cd6c472 | [
"Unlicense"
] | 16 | 2015-07-02T20:10:02.000Z | 2016-04-15T14:58:45.000Z | src/gl/renderer/gl_renderstate.cpp | atsb/ReGLOOME | 2770853677513f204e9282c71d3fd38e4cd6c472 | [
"Unlicense"
] | 30 | 2015-07-02T08:13:14.000Z | 2021-11-22T08:32:51.000Z | /*
** gl_renderstate.cpp
** Render state maintenance
**
**---------------------------------------------------------------------------
** Copyright 2009 Christoph Oelckers
** All rights reserved.
**
** Redistribution and use in source and binary forms, with or without
** modification, are permitted provided that the following conditions
** are met:
**
** 1. Redistributions of source code must retain the above copyright
** notice, this list of conditions and the following disclaimer.
** 2. Redistributions in binary form must reproduce the above copyright
** notice, this list of conditions and the following disclaimer in the
** documentation and/or other materials provided with the distribution.
** 3. The name of the author may not be used to endorse or promote products
** derived from this software without specific prior written permission.
** 4. When not used as part of GZDoom or a GZDoom derivative, this code will be
** covered by the terms of the GNU Lesser General Public License as published
** by the Free Software Foundation; either version 2.1 of the License, or (at
** your option) any later version.
** 5. Full disclosure of the entire project's source code, except for third
** party libraries is mandatory. (NOTE: This clause is non-negotiable!)
**
** THIS SOFTWARE IS PROVIDED BY THE AUTHOR ``AS IS'' AND ANY EXPRESS OR
** IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED WARRANTIES
** OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE DISCLAIMED.
** IN NO EVENT SHALL THE AUTHOR BE LIABLE FOR ANY DIRECT, INDIRECT,
** INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT
** NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE,
** DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY
** THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT
** (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF
** THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
**---------------------------------------------------------------------------
**
*/
#include "gl/system/gl_system.h"
#include "gl/system/gl_interface.h"
#include "gl/data/gl_data.h"
#include "gl/system/gl_cvars.h"
#include "gl/shaders/gl_shader.h"
#include "gl/renderer/gl_renderer.h"
#include "gl/renderer/gl_renderstate.h"
#include "gl/renderer/gl_colormap.h"
void gl_SetTextureMode(int type);
FRenderState gl_RenderState;
int FStateAttr::ChangeCounter;
CVAR(Bool, gl_direct_state_change, true, 0)
//==========================================================================
//
//
//
//==========================================================================
void FRenderState::Reset()
{
mTextureEnabled = true;
mBrightmapEnabled = mFogEnabled = mGlowEnabled = mLightEnabled = false;
ffTextureEnabled = ffFogEnabled = false;
mSpecialEffect = ffSpecialEffect = EFF_NONE;
mFogColor.d = ffFogColor.d = -1;
mFogDensity = ffFogDensity = 0;
mTextureMode = ffTextureMode = -1;
mSrcBlend = GL_SRC_ALPHA;
mDstBlend = GL_ONE_MINUS_SRC_ALPHA;
glSrcBlend = glDstBlend = -1;
glAlphaFunc = -1;
mAlphaFunc = GL_GEQUAL;
mAlphaThreshold = 0.5f;
mBlendEquation = GL_FUNC_ADD;
glBlendEquation = -1;
m2D = true;
}
//==========================================================================
//
// Set texture shader info
//
//==========================================================================
int FRenderState::SetupShader(bool cameratexture, int &shaderindex, int &cm, float warptime)
{
bool usecmshader;
int softwarewarp = 0;
if (shaderindex == 3)
{
// Brightmap should not be used.
if (!mBrightmapEnabled || cm >= CM_FIRSTSPECIALCOLORMAP)
{
shaderindex = 0;
}
}
if (gl.shadermodel == 4)
{
usecmshader = cm > CM_DEFAULT && cm < CM_MAXCOLORMAP && mTextureMode != TM_MASK;
}
else if (gl.shadermodel == 3)
{
usecmshader = (cameratexture || gl_colormap_shader) &&
cm > CM_DEFAULT && cm < CM_MAXCOLORMAP && mTextureMode != TM_MASK;
if (!gl_brightmap_shader && shaderindex == 3)
{
shaderindex = 0;
}
else if (!gl_warp_shader && shaderindex !=3)
{
if (shaderindex <= 2) softwarewarp = shaderindex;
shaderindex = 0;
}
}
else
{
usecmshader = cameratexture;
softwarewarp = shaderindex > 0 && shaderindex < 3? shaderindex : 0;
shaderindex = 0;
}
mEffectState = shaderindex;
mColormapState = usecmshader? cm : CM_DEFAULT;
if (usecmshader) cm = CM_DEFAULT;
mWarpTime = warptime;
return softwarewarp;
}
//==========================================================================
//
// Apply shader settings
//
//==========================================================================
bool FRenderState::ApplyShader()
{
bool useshaders = false;
FShader *activeShader = NULL;
if (mSpecialEffect > 0 && gl.shadermodel > 2)
{
activeShader = GLRenderer->mShaderManager->BindEffect(mSpecialEffect);
}
else
{
switch (gl.shadermodel)
{
case 2:
useshaders = (mTextureEnabled && mColormapState != CM_DEFAULT);
break;
case 3:
useshaders = (
mEffectState != 0 || // special shaders
(mFogEnabled && (gl_fogmode == 2 || gl_fog_shader) && gl_fogmode != 0) || // fog requires a shader
(mTextureEnabled && (mEffectState != 0 || mColormapState)) || // colormap
mGlowEnabled // glow requires a shader
);
break;
case 4:
useshaders = (!m2D || mEffectState != 0 || mColormapState); // all 3D rendering and 2D with texture effects.
break;
default:
break;
}
if (useshaders)
{
FShaderContainer *shd = GLRenderer->mShaderManager->Get(mTextureEnabled? mEffectState : 4);
if (shd != NULL)
{
activeShader = shd->Bind(mColormapState, mGlowEnabled, mWarpTime, mLightEnabled);
}
}
}
if (activeShader)
{
int fogset = 0;
if (mFogEnabled)
{
if ((mFogColor & 0xffffff) == 0)
{
fogset = gl_fogmode;
}
else
{
fogset = -gl_fogmode;
}
}
if (fogset != activeShader->currentfogenabled)
{
glUniform1i(activeShader->fogenabled_index, (activeShader->currentfogenabled = fogset));
}
if (mTextureMode != activeShader->currenttexturemode)
{
glUniform1i(activeShader->texturemode_index, (activeShader->currenttexturemode = mTextureMode));
}
if (activeShader->currentcamerapos.Update(&mCameraPos))
{
glUniform3fv(activeShader->camerapos_index, 1, mCameraPos.vec);
}
/*if (mLightParms[0] != activeShader->currentlightfactor ||
mLightParms[1] != activeShader->currentlightdist ||
mFogDensity != activeShader->currentfogdensity)*/
{
const float LOG2E = 1.442692f; // = 1/log(2)
//activeShader->currentlightdist = mLightParms[1];
//activeShader->currentlightfactor = mLightParms[0];
//activeShader->currentfogdensity = mFogDensity;
// premultiply the density with as much as possible here to reduce shader
// execution time.
glVertexAttrib4f(VATTR_FOGPARAMS, mLightParms[0], mLightParms[1], mFogDensity * (-LOG2E / 64000.f), 0);
}
if (mFogColor != activeShader->currentfogcolor)
{
activeShader->currentfogcolor = mFogColor;
glUniform4f (activeShader->fogcolor_index, mFogColor.r/255.f, mFogColor.g/255.f,
mFogColor.b/255.f, 0);
}
if (mGlowEnabled)
{
glUniform1iv(activeShader->glowsubtracttop_index, 1, &mGlowSubtractTop);
glUniform1iv(activeShader->glowsubtractbottom_index, 1, &mGlowSubtractBottom);
glUniform4fv(activeShader->glowtopcolor_index, 1, mGlowTop.vec);
glUniform4fv(activeShader->glowbottomcolor_index, 1, mGlowBottom.vec);
glUniform4fv(activeShader->glowtopplane_index, 1, mGlowTopPlane.vec);
glUniform4fv(activeShader->glowbottomplane_index, 1, mGlowBottomPlane.vec);
activeShader->currentglowstate = 1;
}
else if (activeShader->currentglowstate)
{
// if glowing is on, disable it.
glUniform4f(activeShader->glowtopcolor_index, 0.f, 0.f, 0.f, 0.f);
glUniform4f(activeShader->glowbottomcolor_index, 0.f, 0.f, 0.f, 0.f);
activeShader->currentglowstate = 0;
}
if (mLightEnabled)
{
glUniform3iv(activeShader->lightrange_index, 1, mNumLights);
glUniform4fv(activeShader->lights_index, mNumLights[2], mLightData);
}
if (glset.lightmode == 8)
{
glUniform3fv(activeShader->dlightcolor_index, 1, mDynLight);
}
return true;
}
return false;
}
//==========================================================================
//
// Apply State
//
//==========================================================================
void FRenderState::Apply(bool forcenoshader)
{
if (!gl_direct_state_change)
{
if (mSrcBlend != glSrcBlend || mDstBlend != glDstBlend)
{
glSrcBlend = mSrcBlend;
glDstBlend = mDstBlend;
glBlendFunc(mSrcBlend, mDstBlend);
}
if (mAlphaFunc != glAlphaFunc || mAlphaThreshold != glAlphaThreshold)
{
glAlphaFunc = mAlphaFunc;
glAlphaThreshold = mAlphaThreshold;
::glAlphaFunc(mAlphaFunc, mAlphaThreshold);
}
if (mAlphaTest != glAlphaTest)
{
glAlphaTest = mAlphaTest;
if (mAlphaTest) glEnable(GL_ALPHA_TEST);
else glDisable(GL_ALPHA_TEST);
}
if (mBlendEquation != glBlendEquation)
{
glBlendEquation = mBlendEquation;
::glBlendEquation(mBlendEquation);
}
}
if (forcenoshader || !ApplyShader())
{
GLRenderer->mShaderManager->SetActiveShader(NULL);
if (mTextureMode != ffTextureMode)
{
gl_SetTextureMode((ffTextureMode = mTextureMode));
}
if (mTextureEnabled != ffTextureEnabled)
{
if ((ffTextureEnabled = mTextureEnabled)) glEnable(GL_TEXTURE_2D);
else glDisable(GL_TEXTURE_2D);
}
if (mFogEnabled != ffFogEnabled)
{
if ((ffFogEnabled = mFogEnabled))
{
glEnable(GL_FOG);
}
else glDisable(GL_FOG);
}
if (mFogEnabled)
{
if (ffFogColor != mFogColor)
{
ffFogColor = mFogColor;
GLfloat FogColor[4]={mFogColor.r/255.0f,mFogColor.g/255.0f,mFogColor.b/255.0f,0.0f};
glFogfv(GL_FOG_COLOR, FogColor);
}
if (ffFogDensity != mFogDensity)
{
glFogf(GL_FOG_DENSITY, mFogDensity/64000.f);
ffFogDensity=mFogDensity;
}
}
if (mSpecialEffect != ffSpecialEffect)
{
switch (ffSpecialEffect)
{
case EFF_SPHEREMAP:
glDisable(GL_TEXTURE_GEN_T);
glDisable(GL_TEXTURE_GEN_S);
default:
break;
}
switch (mSpecialEffect)
{
case EFF_SPHEREMAP:
// Use sphere mapping for this
glEnable(GL_TEXTURE_GEN_T);
glEnable(GL_TEXTURE_GEN_S);
glTexGeni(GL_S,GL_TEXTURE_GEN_MODE,GL_SPHERE_MAP);
glTexGeni(GL_T,GL_TEXTURE_GEN_MODE,GL_SPHERE_MAP);
break;
default:
break;
}
ffSpecialEffect = mSpecialEffect;
}
}
}
| 28.642276 | 111 | 0.656637 | [
"render",
"3d"
] |
090da8c932a9b73b4430264376112079b775722c | 4,540 | hpp | C++ | include/codegen/include/System/Collections/Queue.hpp | Futuremappermydud/Naluluna-Modifier-Quest | bfda34370764b275d90324b3879f1a429a10a873 | [
"MIT"
] | 1 | 2021-11-12T09:29:31.000Z | 2021-11-12T09:29:31.000Z | include/codegen/include/System/Collections/Queue.hpp | Futuremappermydud/Naluluna-Modifier-Quest | bfda34370764b275d90324b3879f1a429a10a873 | [
"MIT"
] | null | null | null | include/codegen/include/System/Collections/Queue.hpp | Futuremappermydud/Naluluna-Modifier-Quest | bfda34370764b275d90324b3879f1a429a10a873 | [
"MIT"
] | 2 | 2021-10-03T02:14:20.000Z | 2021-11-12T09:29:36.000Z | // Autogenerated from CppHeaderCreator on 7/27/2020 3:09:52 PM
// Created by Sc2ad
// =========================================================================
#pragma once
#pragma pack(push, 8)
// Begin includes
#include "utils/typedefs.h"
// Including type: System.Object
#include "System/Object.hpp"
// Including type: System.Collections.ICollection
#include "System/Collections/ICollection.hpp"
// Including type: System.ICloneable
#include "System/ICloneable.hpp"
#include "utils/il2cpp-utils.hpp"
// Completed includes
// Begin forward declares
// Forward declaring namespace: System::Collections
namespace System::Collections {
// Forward declaring type: IEnumerator
class IEnumerator;
}
// Forward declaring namespace: System
namespace System {
// Forward declaring type: Array
class Array;
}
// Completed forward declares
// Type namespace: System.Collections
namespace System::Collections {
// Autogenerated type: System.Collections.Queue
class Queue : public ::Il2CppObject, public System::Collections::ICollection, public System::Collections::IEnumerable, public System::ICloneable {
public:
// Nested type: System::Collections::Queue::QueueEnumerator
class QueueEnumerator;
// Nested type: System::Collections::Queue::QueueDebugView
class QueueDebugView;
// private System.Object[] _array
// Offset: 0x10
::Array<::Il2CppObject*>* array;
// private System.Int32 _head
// Offset: 0x18
int head;
// private System.Int32 _tail
// Offset: 0x1C
int tail;
// private System.Int32 _size
// Offset: 0x20
int size;
// private System.Int32 _growFactor
// Offset: 0x24
int growFactor;
// private System.Int32 _version
// Offset: 0x28
int version;
// public System.Void .ctor(System.Int32 capacity)
// Offset: 0x1326090
static Queue* New_ctor(int capacity);
// public System.Void .ctor(System.Int32 capacity, System.Single growFactor)
// Offset: 0x1325EA8
static Queue* New_ctor(int capacity, float growFactor);
// public System.Void .ctor(System.Collections.ICollection col)
// Offset: 0x1326098
static Queue* New_ctor(System::Collections::ICollection* col);
// public System.Void Enqueue(System.Object obj)
// Offset: 0x13265EC
void Enqueue(::Il2CppObject* obj);
// public System.Object Dequeue()
// Offset: 0x1326860
::Il2CppObject* Dequeue();
// public System.Object Peek()
// Offset: 0x132697C
::Il2CppObject* Peek();
// System.Object GetElement(System.Int32 i)
// Offset: 0x1326A50
::Il2CppObject* GetElement(int i);
// private System.Void SetCapacity(System.Int32 capacity)
// Offset: 0x13266FC
void SetCapacity(int capacity);
// public System.Void .ctor()
// Offset: 0x1325E9C
// Implemented from: System.Object
// Base method: System.Void Object::.ctor()
static Queue* New_ctor();
// public System.Int32 get_Count()
// Offset: 0x1326320
// Implemented from: System.Collections.ICollection
// Base method: System.Int32 ICollection::get_Count()
int get_Count();
// Creating proxy method: System_Collections_ICollection_get_Count
// Maps to method: get_Count
int System_Collections_ICollection_get_Count();
// public System.Object Clone()
// Offset: 0x1326328
// Implemented from: System.ICloneable
// Base method: System.Object ICloneable::Clone()
::Il2CppObject* Clone();
// public System.Void CopyTo(System.Array array, System.Int32 index)
// Offset: 0x132640C
// Implemented from: System.Collections.ICollection
// Base method: System.Void ICollection::CopyTo(System.Array array, System.Int32 index)
void CopyTo(System::Array* array, int index);
// Creating proxy method: System_Collections_ICollection_CopyTo
// Maps to method: CopyTo
void System_Collections_ICollection_CopyTo(System::Array* array, int index);
// public System.Collections.IEnumerator GetEnumerator()
// Offset: 0x13267FC
// Implemented from: System.Collections.IEnumerable
// Base method: System.Collections.IEnumerator IEnumerable::GetEnumerator()
System::Collections::IEnumerator* GetEnumerator();
// Creating proxy method: System_Collections_IEnumerable_GetEnumerator
// Maps to method: GetEnumerator
System::Collections::IEnumerator* System_Collections_IEnumerable_GetEnumerator();
}; // System.Collections.Queue
}
DEFINE_IL2CPP_ARG_TYPE(System::Collections::Queue*, "System.Collections", "Queue");
#pragma pack(pop)
| 38.803419 | 148 | 0.705727 | [
"object"
] |
0915597c276ef2f8e88baa557f1637216d54e1ed | 625 | cpp | C++ | crazyflie_cpp/test/sendPacket.cpp | diasdm/crazyf_ros | 93b8d4670df9f0766058e5d22e91f2f988f9676d | [
"MIT"
] | null | null | null | crazyflie_cpp/test/sendPacket.cpp | diasdm/crazyf_ros | 93b8d4670df9f0766058e5d22e91f2f988f9676d | [
"MIT"
] | null | null | null | crazyflie_cpp/test/sendPacket.cpp | diasdm/crazyf_ros | 93b8d4670df9f0766058e5d22e91f2f988f9676d | [
"MIT"
] | null | null | null | #include <iostream>
#include <crazyflie_cpp/Crazyradio.h>
int main()
{
Crazyradio radio(0); // Instantiate an object bound to the first Crazyflie found
radio.setChannel(100); // Update the base frequency to 2500 MHz
radio.setAddress(0xE7E7E7E701); // Set the address to send to
radio.setDatarate(Crazyradio::Datarate_2MPS);
// Send a packet
uint8_t data[] = {0xCA, 0xFE};
Crazyradio::Ack ack;
radio.sendPacket(data, sizeof(data), ack);
if (ack.ack) {
std::cout << "Ack of size " << ack.size << " received!" << std::endl;
} else {
std::cout << "No Ack received!" << std::endl;
}
return 0;
}
| 27.173913 | 82 | 0.664 | [
"object"
] |
091955a0fd74e546f293e7f63ff865105134d467 | 1,876 | cpp | C++ | eigen/test/product_small.cpp | tamasdzs/APPRSDK | 7a1f1c2a2f6994791bab760d01270eca62a5a946 | [
"MIT"
] | 36 | 2015-03-09T16:47:14.000Z | 2021-02-04T08:32:04.000Z | ScalableLSH/DiskE2LSH/Eigen/test/product_small.cpp | USCDataScience/cmu-fg-bg-similarity | d8fc9a53937551f7a052bc2c6f442bcc29ea2615 | [
"Apache-2.0"
] | 42 | 2017-02-11T11:15:51.000Z | 2019-12-28T16:00:44.000Z | ScalableLSH/DiskE2LSH/Eigen/test/product_small.cpp | USCDataScience/cmu-fg-bg-similarity | d8fc9a53937551f7a052bc2c6f442bcc29ea2615 | [
"Apache-2.0"
] | 5 | 2015-10-15T05:46:48.000Z | 2020-05-11T17:40:36.000Z | // This file is part of Eigen, a lightweight C++ template library
// for linear algebra.
//
// Copyright (C) 2006-2008 Benoit Jacob <jacob.benoit.1@gmail.com>
//
// This Source Code Form is subject to the terms of the Mozilla
// Public License v. 2.0. If a copy of the MPL was not distributed
// with this file, You can obtain one at http://mozilla.org/MPL/2.0/.
#define EIGEN_NO_STATIC_ASSERT
#include "product.h"
#include <Eigen/LU>
// regression test for bug 447
void product1x1()
{
Matrix<float,1,3> matAstatic;
Matrix<float,3,1> matBstatic;
matAstatic.setRandom();
matBstatic.setRandom();
VERIFY_IS_APPROX( (matAstatic * matBstatic).coeff(0,0),
matAstatic.cwiseProduct(matBstatic.transpose()).sum() );
MatrixXf matAdynamic(1,3);
MatrixXf matBdynamic(3,1);
matAdynamic.setRandom();
matBdynamic.setRandom();
VERIFY_IS_APPROX( (matAdynamic * matBdynamic).coeff(0,0),
matAdynamic.cwiseProduct(matBdynamic.transpose()).sum() );
}
void test_product_small()
{
for(int i = 0; i < g_repeat; i++) {
CALL_SUBTEST_1( product(Matrix<float, 3, 2>()) );
CALL_SUBTEST_2( product(Matrix<int, 3, 5>()) );
CALL_SUBTEST_3( product(Matrix3d()) );
CALL_SUBTEST_4( product(Matrix4d()) );
CALL_SUBTEST_5( product(Matrix4f()) );
CALL_SUBTEST_6( product1x1() );
}
#ifdef EIGEN_TEST_PART_6
{
// test compilation of (outer_product) * vector
Vector3f v = Vector3f::Random();
VERIFY_IS_APPROX( (v * v.transpose()) * v, (v * v.transpose()).eval() * v);
}
{
// regression test for pull-request #93
Eigen::Matrix<double, 1, 1> A; A.setRandom();
Eigen::Matrix<double, 18, 1> B; B.setRandom();
Eigen::Matrix<double, 1, 18> C; C.setRandom();
VERIFY_IS_APPROX(B * A.inverse(), B * A.inverse()[0]);
VERIFY_IS_APPROX(A.inverse() * C, A.inverse()[0] * C);
}
#endif
}
| 30.754098 | 79 | 0.658849 | [
"vector"
] |
091a5db8803f8c0d085485f471af5817a4ca667f | 4,623 | cpp | C++ | examples/car/carDBA.cpp | yinanl/rocs | bf2483903e39f4c0ea254a9ef56720a1259955ad | [
"BSD-3-Clause"
] | null | null | null | examples/car/carDBA.cpp | yinanl/rocs | bf2483903e39f4c0ea254a9ef56720a1259955ad | [
"BSD-3-Clause"
] | null | null | null | examples/car/carDBA.cpp | yinanl/rocs | bf2483903e39f4c0ea254a9ef56720a1259955ad | [
"BSD-3-Clause"
] | null | null | null | /**
* carDBA.cpp
*
* A general main program performing DBA control synthesis.
* Based on the T operator: U_{j} pre(W_i | O_ij)
*
* The input spec files are: dba1,2,3.txt,
* in which the propositions are not simplified.
*
* Created by Yinan Li on Jan. 30, 2020.
*
* Hybrid Systems Group, University of Waterloo.
*/
#include <iostream>
#include <fstream>
#include <sstream>
#include <cstdlib>
#include "src/DBAparser.h"
#include "src/system.hpp"
#include "src/csolver.h"
// #include "src/matlabio.h"
#include "src/hdf5io.h"
#include "car.hpp"
int main(int argc, char *argv[])
{
/**
* Default values
**/
std::string specfile;
double e[]{0.2, 0.2, 0.2}; /* partition precision */
/**
* Input arguments: (2<= argc <= 5)
* carAbst dbafile precision(e.g. 0.2 0.2 0.2)
*/
if (argc < 2 || argc > 5) {
std::cout << "Improper number of arguments.\n";
std::exit(1);
}
specfile = std::string(argv[1]);
if (argc > 2 && argc < 5) {
std::cout << "Input precision should be of 3-dim, e.g. 0.2 0.2 0.2.\n";
std::exit(1);
}
if (argc > 2) {
for(int i = 2; i < 5; ++i)
e[i-2] = std::atof(argv[i]);
}
std::cout << "Partition precision: " << e[0] << ' '
<< e[1] << ' ' << e[2] << '\n';
std::cout << "Not using preprocessing.\n";
/**
* Read specification file
**/
std::cout << "Loading the specification...\n";
std::vector<rocs::UintSmall> acc;
std::vector<std::vector<rocs::UintSmall>> arrayM;
rocs::UintSmall nAP = 0, nNodes = 0, q0 = 0;
if (!rocs::read_spec(specfile, nNodes, nAP, q0, arrayM, acc))
std::exit(1);
size_t nProps = arrayM.size();
/* Mark accepting states */
boost::dynamic_bitset<> isacc(nNodes, false);
for (rocs::UintSmall i = 0; i < acc.size(); ++i)
isacc[acc[i]] = true;
std::cout << "isacc= ";
for (boost::dynamic_bitset<>::size_type i = 0;
i < isacc.size(); ++i) {
std::cout << isacc[i] << ' ';
}
std::cout << '\n';
/**
* Workspace Setup
**/
/* State space */
const double theta = 3.5; // M_PI
double xlb[] = {0, 0, -theta};
double xub[] = {10, 10, theta};
/* Control values */
double ulb[] = {-1.0, -1.0};
double uub[] = {1.0, 1.0};
double mu[] = {0.3, 0.3};
/* Control system */
rocs::DTCntlSys<carde> carvf("DBA", h, carde::n, carde::m);
carvf.init_workspace(xlb, xub);
carvf.init_inputset(mu, ulb, uub);
/* Obstacles */
rocs::UintSmall nA = 4;
double olb[4][3] = {{1.6, 4.0, -theta},
{3.0, 5.0, -theta},
{4.3, 1.8, -theta},
{5.7, 1.8, -theta}};
double oub[4][3] = {{5.7, 5.0, theta},
{5.0, 8.0, theta},
{5.7, 4.0, theta},
{8.5, 2.5, theta}};
/* Goals */
rocs::UintSmall nG = 3; // # of goals
double glb[3][3]= {{1.0, 0.5, -theta},
{0.5, 7.5, -theta},
{7.1, 4.6, -theta}};
double gub[3][3]= {{2.0, 2.0, theta},
{2.5, 8.5, theta},
{9.1, 6.4, theta}};
/**
* DBA control synthesis
*/
/* Initialize the set of S-domains */
std::vector<rocs::CSolver*> w(nNodes);
std::vector<rocs::SPtree*> sdoms(nNodes);
rocs::UintSmall labels[]{4, 2, 1}; // corresponding to goal1,2,3.
auto init_w = [&carvf, &nProps, &labels, &arrayM,
&olb, &oub, &nA,
&glb, &gub, &nG](std::vector<rocs::CSolver*> &w,
rocs::UintSmall i,
rocs::UintSmall oid[]) {
w[i] = new rocs::CSolver(&carvf, nProps, rocs::RELMAX);
for (rocs::UintSmall j = 0; j < nA; ++j)
w[i]->init(rocs::AVOID, olb[j], oub[j]); // avoid areas
for (rocs::UintSmall j = 0; j < nG; ++j)
w[i]->labeling(glb[j], gub[j], labels[j]); // labeled areas
w[i]->set_M(arrayM[oid[i]]);
};
std::cout << "Start control synthesis...\n";
// std::vector<std::string> tokens;
// boost::split(tokens, specfile, boost::is_any_of("."));
rocs::UintSmall oid[nNodes];
for(int i = 0; i < nNodes; ++i)
oid[i] = i;
rocs::dba_control< rocs::DTCntlSys<carde> >(w, &carvf, sdoms, nNodes,
isacc, init_w, oid, e);
/**
* Display and save memoryless controllers.
*/
for (rocs::UintSmall i = 0; i < w.size(); ++i) {
std::cout << std::endl << "S-domain for q" << std::to_string(i) << '\n';
w[i]->print_controller_info();
}
// rocs::write_results_to_mat(carvf, specfile, w);
rocs::write_csolvers_to_h5(carvf, specfile, w);
/**
* Release dynamic memory
**/
for (rocs::UintSmall i = 0; i < nNodes; ++i)
delete w[i];
return 0;
}
| 27.682635 | 73 | 0.533204 | [
"vector"
] |
091e3d2825e276fd1ea06bca82f3767eb3933212 | 6,703 | cc | C++ | sssp/sssp.cc | rohany/Lux | 626371133ca088fc234d031cc5a4bc3ed713d479 | [
"Apache-2.0"
] | 56 | 2018-06-04T22:17:26.000Z | 2022-01-25T08:12:06.000Z | sssp/sssp.cc | rohany/Lux | 626371133ca088fc234d031cc5a4bc3ed713d479 | [
"Apache-2.0"
] | 13 | 2019-01-08T16:15:37.000Z | 2022-02-22T00:11:12.000Z | sssp/sssp.cc | rohany/Lux | 626371133ca088fc234d031cc5a4bc3ed713d479 | [
"Apache-2.0"
] | 9 | 2018-09-25T07:03:47.000Z | 2021-11-17T16:02:30.000Z | /* Copyright 2018 Stanford, UT Austin, LANL
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
#include <cstdio>
#include "../core/graph.h"
#include "../core/lux_mapper.h"
#include "legion.h"
#include <string.h>
LegionRuntime::Logger::Category log_sssp("sssp");
LegionRuntime::Logger::Category log_lux("lux");
void parse_input_args(char **argv, int argc, int &num_gpu, V_ID &startVtx,
std::string &file_name, bool &verbose, bool &check);
void top_level_task(const Task *task,
const std::vector<PhysicalRegion> ®ions,
Context ctx, HighLevelRuntime *runtime)
{
int numGPU = 0;
V_ID startVtx = 0;
std::string filename;
bool verbose = false;
bool check = false;
{
const InputArgs &command_args = HighLevelRuntime::get_input_args();
char **argv = command_args.argv;
int argc = command_args.argc;
parse_input_args(argv, argc, numGPU, startVtx, filename, verbose, check);
log_sssp.print("SSSP settings: numPartitions(%d) start(%u) filename(%s)",
numGPU, startVtx, filename.c_str());
if (numGPU <= 0) {
fprintf(stderr, "numGPU(%d) must be greater than zero.\n",
numGPU);
return;
}
size_t numNodes = Realm::Machine::get_machine().get_address_space_count();
assert(numNodes > 0);
numGPU = numGPU * numNodes;
}
Graph graph(ctx, runtime, numGPU, filename);
graph.startVtx = startVtx;
graph.verbose = verbose;
Rect<1> task_rect(0, graph.numParts - 1);
// First we compute and print memory requriements
size_t max_zc_usage = 0, max_fb_usage = 0, max_num_edges = 0;
for (PointInRectIterator<1> it(task_rect); it(); it++) {
size_t fb_usage = 0;
LogicalRegion col_idx = runtime->get_logical_subregion_by_color(
ctx, graph.pull_col_idx_lp, DomainPoint(*it));
LogicalRegion row_ptr = runtime->get_logical_subregion_by_color(
ctx, graph.pull_row_ptr_lp, DomainPoint(*it));
Rect<1> r = runtime->get_index_space_domain(ctx,
col_idx.get_index_space());
size_t myNumEdges = r.hi[0] - r.lo[0] + 1;
r = runtime->get_index_space_domain(ctx, row_ptr.get_index_space());
size_t myNumNodes = r.hi[0] - r.lo[0] + 1;
fb_usage = myNumEdges * sizeof(EdgeStruct2) //pull_col_idxs
+ myNumEdges * sizeof(EdgeStruct) //push_col_idxs
+ myNumNodes * sizeof(NodeStruct) //pull_raw_rows
+ graph.nv * sizeof(NodeStruct) //push_raw_rows
+ myNumNodes * 2 * sizeof(Vertex) //newPrFb+oldPrFb
+ graph.nv * sizeof(Vertex) //allPrFb
+ graph.frontierSize * 2; //newFqFb+oldFqFb
max_fb_usage = fb_usage > max_fb_usage ? fb_usage : max_fb_usage;
max_num_edges = myNumEdges > max_num_edges ? myNumEdges : max_num_edges;
}
max_zc_usage = graph.ne * sizeof(V_ID) //raw_cols
+ graph.nv * sizeof(E_ID) //raw_rows
+ graph.nv * 2 * sizeof(Vertex) //new_pr+old_pr
+ graph.frontierSize * 2 //new_fq+old_fq
+ graph.nv * sizeof(NodeStruct) //temp_memory
+ max_num_edges * sizeof(EdgeStruct); //temp_memory
printf("[Memory Setting] Set ll:fsize >= %zuMB and ll:zsize >= %zuMB\n",
max_fb_usage / 1024 / 1024 + 1, max_zc_usage / 1024 / 1024 + 1);
ArgumentMap local_args;
// Init phase
IndexSpaceT<1> task_is = runtime->create_index_space(ctx, task_rect);
PushLoadTask load_task(graph, task_is, local_args, filename);
FutureMap fm = runtime->execute_index_space(ctx, load_task);
fm.wait_all_results();
PushInitVtxTask init_vtx_task(graph);
Future f = runtime->execute_task(ctx, init_vtx_task);
f.get_void_result();
PushInitTask init_task(graph, task_is, local_args);
fm = runtime->execute_index_space(ctx, init_task);
fm.wait_all_results();
for (PointInRectIterator<1> it(task_rect); it(); it++) {
GraphPiece piece = fm.get_result<GraphPiece>(*it);
local_args.set_point(*it, TaskArgument(&piece, sizeof(GraphPiece)));
}
// CC phase
FutureMap fms[SLIDING_WINDOW];
int iter = 0;
log_sssp.print("Start SSSP computation...");
double ts_start = Realm::Clock::current_time_in_microseconds();
while (true) {
if (iter >= SLIDING_WINDOW) {
fm = fms[iter % SLIDING_WINDOW];
fm.wait_all_results();
bool halt = true;
for (PointInRectIterator<1> it(task_rect); it(); it++) {
V_ID numNodes = fm.get_result<V_ID>(*it);
if (numNodes > 0) halt = false;
}
if (halt) break;
}
PushAppTask app_task(graph, task_is, local_args, iter);
fms[iter % SLIDING_WINDOW] = runtime->execute_index_space(ctx, app_task);
iter ++;
}
double ts_end = Realm::Clock::current_time_in_microseconds();
double sim_time = 1e-6 * (ts_end - ts_start);
runtime->issue_execution_fence(ctx);
TimingLauncher timer(MEASURE_MICRO_SECONDS);
Future future = runtime->issue_timing_measurement(ctx, timer);
future.get_void_result();
log_sssp.print("Finish SSSP computation...");
printf("ELAPSED TIME = %7.7f s\n", sim_time);
//check tasks
if (check) {
CheckTask check_task(graph, task_is, local_args, iter);
fm = runtime->execute_index_space(ctx, check_task);
fm.wait_all_results();
log_sssp.print("Correctness check completed...");
}
}
void parse_input_args(char **argv, int argc, int &numGPU,
V_ID &startVtx, std::string &filename,
bool &verbose, bool &check)
{
for (int i = 1; i < argc; i++)
{
if ((!strcmp(argv[i], "-ng")) || (!strcmp(argv[i], "-ll:gpu")))
{
numGPU = atoi(argv[++i]);
continue;
}
if (!strcmp(argv[i], "-start"))
{
startVtx = atoll(argv[++i]);
continue;
}
if (!strcmp(argv[i], "-file"))
{
filename = std::string(argv[++i]);
continue;
}
if ((!strcmp(argv[i], "-verbose")) || (!strcmp(argv[i], "-v")))
{
verbose = true;
continue;
}
if ((!strcmp(argv[i], "-check")) || (!strcmp(argv[i], "-c")))
{
check = true;
continue;
}
}
}
#include "../core/push_model.inl"
| 36.628415 | 78 | 0.63852 | [
"vector"
] |
091e7ac18425145046d9be78e7ff125f05c1b6af | 23,862 | cpp | C++ | Kobold2D/__Kobold2D__/libs/cocos3d/cocos3d/cc3PVR/PVRT 2.09/PVRTVertex.cpp | LiamInJapan/Kobold2D | 8347f38b3d7fc39bbc265a9a414c27f3be280a45 | [
"Unlicense"
] | 1 | 2015-04-17T16:35:08.000Z | 2015-04-17T16:35:08.000Z | Kobold2D/__Kobold2D__/libs/cocos3d/cocos3d/cc3PVR/PVRT 2.09/PVRTVertex.cpp | LiamInJapan/Kobold2D | 8347f38b3d7fc39bbc265a9a414c27f3be280a45 | [
"Unlicense"
] | null | null | null | Kobold2D/__Kobold2D__/libs/cocos3d/cocos3d/cc3PVR/PVRT 2.09/PVRTVertex.cpp | LiamInJapan/Kobold2D | 8347f38b3d7fc39bbc265a9a414c27f3be280a45 | [
"Unlicense"
] | null | null | null | /******************************************************************************
@File PVRTVertex.cpp
@Title PVRTVertex
@Version
@Copyright Copyright (c) Imagination Technologies Limited.
@Platform ANSI compatible
@Description Utility functions which process vertices.
******************************************************************************/
/****************************************************************************
** Includes
****************************************************************************/
#include "PVRTGlobal.h"
#include "PVRTContext.h"
#include <stdlib.h>
#include <string.h>
#include "PVRTFixedPoint.h"
#include "PVRTMatrix.h"
#include "PVRTVertex.h"
/****************************************************************************
** Defines
****************************************************************************/
/****************************************************************************
** Macros
****************************************************************************/
#define MAX_VERTEX_OUT (3*nVtxNum)
/****************************************************************************
** Structures
****************************************************************************/
/****************************************************************************
** Constants
****************************************************************************/
/****************************************************************************
** Local function definitions
****************************************************************************/
/*****************************************************************************
** Functions
*****************************************************************************/
/*!***************************************************************************
@Function PVRTVertexRead
@Output pV
@Input pData
@Input eType
@Input nCnt
@Description Read a vector
*****************************************************************************/
void PVRTVertexRead(
PVRTVECTOR4f * const pV,
const void * const pData,
const EPVRTDataType eType,
const int nCnt)
{
int i;
float *pOut = (float*)pV;
pV->x = 0;
pV->y = 0;
pV->z = 0;
pV->w = 1;
switch(eType)
{
default:
_ASSERT(false);
break;
case EPODDataFloat:
for(i = 0; i < nCnt; ++i)
pOut[i] = ((float*)pData)[i];
break;
case EPODDataFixed16_16:
for(i = 0; i < nCnt; ++i)
pOut[i] = ((int*)pData)[i] * 1.0f / (float)(1 << 16);
break;
case EPODDataInt:
for(i = 0; i < nCnt; ++i)
pOut[i] = (float)((int*)pData)[i];
break;
case EPODDataUnsignedInt:
for(i = 0; i < nCnt; ++i)
pOut[i] = (float)((unsigned int*)pData)[i];
break;
case EPODDataByte:
for(i = 0; i < nCnt; ++i)
pOut[i] = (float)((char*)pData)[i];
break;
case EPODDataByteNorm:
for(i = 0; i < nCnt; ++i)
pOut[i] = (float)((char*)pData)[i] / (float)((1 << 7)-1);
break;
case EPODDataUnsignedByte:
for(i = 0; i < nCnt; ++i)
pOut[i] = (float)((unsigned char*)pData)[i];
break;
case EPODDataUnsignedByteNorm:
for(i = 0; i < nCnt; ++i)
pOut[i] = (float)((unsigned char*)pData)[i] / (float)((1 << 8)-1);
break;
case EPODDataShort:
for(i = 0; i < nCnt; ++i)
pOut[i] = (float)((short*)pData)[i];
break;
case EPODDataShortNorm:
for(i = 0; i < nCnt; ++i)
pOut[i] = (float)((short*)pData)[i] / (float)((1 << 15)-1);
break;
case EPODDataUnsignedShort:
for(i = 0; i < nCnt; ++i)
pOut[i] = (float)((unsigned short*)pData)[i];
break;
case EPODDataUnsignedShortNorm:
for(i = 0; i < nCnt; ++i)
pOut[i] = (float)((unsigned short*)pData)[i] / (float)((1 << 16)-1);
break;
case EPODDataRGBA:
{
unsigned int dwVal = *(unsigned int*)pData;
unsigned char v[4];
v[0] = (unsigned char) (dwVal >> 24);
v[1] = (unsigned char) (dwVal >> 16);
v[2] = (unsigned char) (dwVal >> 8);
v[3] = (unsigned char) (dwVal >> 0);
for(i = 0; i < 4; ++i)
pOut[i] = 1.0f / 255.0f * (float)v[i];
}
break;
case EPODDataARGB:
case EPODDataD3DCOLOR:
{
unsigned int dwVal = *(unsigned int*)pData;
unsigned char v[4];
v[0] = (unsigned char) (dwVal >> 16);
v[1] = (unsigned char) (dwVal >> 8);
v[2] = (unsigned char) (dwVal >> 0);
v[3] = (unsigned char) (dwVal >> 24);
for(i = 0; i < 4; ++i)
pOut[i] = 1.0f / 255.0f * (float)v[i];
}
break;
case EPODDataUBYTE4:
{
unsigned int dwVal = *(unsigned int*)pData;
unsigned char v[4];
v[0] = (unsigned char) (dwVal >> 0);
v[1] = (unsigned char) (dwVal >> 8);
v[2] = (unsigned char) (dwVal >> 16);
v[3] = (unsigned char) (dwVal >> 24);
for(i = 0; i < 4; ++i)
pOut[i] = v[i];
}
break;
case EPODDataDEC3N:
{
int dwVal = *(int*)pData;
int v[4];
v[0] = (dwVal << 22) >> 22;
v[1] = (dwVal << 12) >> 22;
v[2] = (dwVal << 2) >> 22;
v[3] = 0;
for(i = 0; i < 3; ++i)
pOut[i] = (float)v[i] * (1.0f / 511.0f);
}
break;
}
}
/*!***************************************************************************
@Function PVRTVertexRead
@Output pV
@Input pData
@Input eType
@Description Read an int
*****************************************************************************/
void PVRTVertexRead(
unsigned int * const pV,
const void * const pData,
const EPVRTDataType eType)
{
switch(eType)
{
default:
_ASSERT(false);
break;
case EPODDataUnsignedShort:
*pV = *(unsigned short*)pData;
break;
case EPODDataUnsignedInt:
*pV = *(unsigned int*)pData;
break;
}
}
/*!***************************************************************************
@Function PVRTVertexWrite
@Output pOut
@Input eType
@Input nCnt
@Input pV
@Description Write a vector
*****************************************************************************/
void PVRTVertexWrite(
void * const pOut,
const EPVRTDataType eType,
const int nCnt,
const PVRTVECTOR4f * const pV)
{
int i;
float *pData = (float*)pV;
switch(eType)
{
default:
_ASSERT(false);
break;
case EPODDataDEC3N:
{
int v[3];
for(i = 0; i < nCnt; ++i)
{
v[i] = (int)(pData[i] * 511.0f);
v[i] = PVRT_CLAMP(v[i], -511, 511);
v[i] &= 0x000003ff;
}
for(; i < 3; ++i)
{
v[i] = 0;
}
*(unsigned int*)pOut = (v[0] << 0) | (v[1] << 10) | (v[2] << 20);
}
break;
case EPODDataARGB:
case EPODDataD3DCOLOR:
{
unsigned char v[4];
for(i = 0; i < nCnt; ++i)
v[i] = (unsigned char)PVRT_CLAMP(pData[i] * 255.0f, 0.0f, 255.0f);
for(; i < 4; ++i)
v[i] = 0;
*(unsigned int*)pOut = (v[3] << 24) | (v[0] << 16) | (v[1] << 8) | v[2];
}
break;
case EPODDataRGBA:
{
unsigned char v[4];
for(i = 0; i < nCnt; ++i)
v[i] = (unsigned char)PVRT_CLAMP(pData[i] * 255.0f, 0.0f, 255.0f);
for(; i < 4; ++i)
v[i] = 0;
*(unsigned int*)pOut = (v[0] << 24) | (v[1] << 16) | (v[2] << 8) | v[3];
}
break;
case EPODDataUBYTE4:
{
unsigned char v[4];
for(i = 0; i < nCnt; ++i)
v[i] = (unsigned char)PVRT_CLAMP(pData[i], 0.0f, 255.0f);
for(; i < 4; ++i)
v[i] = 0;
*(unsigned int*)pOut = (v[3] << 24) | (v[2] << 16) | (v[1] << 8) | v[0];
}
break;
case EPODDataFloat:
for(i = 0; i < nCnt; ++i)
((float*)pOut)[i] = pData[i];
break;
case EPODDataFixed16_16:
for(i = 0; i < nCnt; ++i)
((int*)pOut)[i] = (int)(pData[i] * (float)(1 << 16));
break;
case EPODDataInt:
for(i = 0; i < nCnt; ++i)
((int*)pOut)[i] = (int)pData[i];
break;
case EPODDataUnsignedInt:
for(i = 0; i < nCnt; ++i)
((unsigned int*)pOut)[i] = (unsigned int)pData[i];
break;
case EPODDataByte:
for(i = 0; i < nCnt; ++i)
((char*)pOut)[i] = (char)pData[i];
break;
case EPODDataByteNorm:
for(i = 0; i < nCnt; ++i)
((char*)pOut)[i] = (char)(pData[i] * (float)((1 << 7)-1));
break;
case EPODDataUnsignedByte:
for(i = 0; i < nCnt; ++i)
((unsigned char*)pOut)[i] = (unsigned char)pData[i];
break;
case EPODDataUnsignedByteNorm:
for(i = 0; i < nCnt; ++i)
((char*)pOut)[i] = (unsigned char)(pData[i] * (float)((1 << 8)-1));
break;
case EPODDataShort:
for(i = 0; i < nCnt; ++i)
((short*)pOut)[i] = (short)pData[i];
break;
case EPODDataShortNorm:
for(i = 0; i < nCnt; ++i)
((short*)pOut)[i] = (short)(pData[i] * (float)((1 << 15)-1));
break;
case EPODDataUnsignedShort:
for(i = 0; i < nCnt; ++i)
((unsigned short*)pOut)[i] = (unsigned short)pData[i];
break;
case EPODDataUnsignedShortNorm:
for(i = 0; i < nCnt; ++i)
((unsigned short*)pOut)[i] = (unsigned short)(pData[i] * (float)((1 << 16)-1));
break;
}
}
/*!***************************************************************************
@Function PVRTVertexWrite
@Output pOut
@Input eType
@Input V
@Description Write an int
*****************************************************************************/
void PVRTVertexWrite(
void * const pOut,
const EPVRTDataType eType,
const unsigned int V)
{
switch(eType)
{
default:
_ASSERT(false);
break;
case EPODDataUnsignedShort:
*(unsigned short*)pOut = (unsigned short) V;
break;
case EPODDataUnsignedInt:
*(unsigned int*)pOut = V;
break;
}
}
/*!***************************************************************************
@Function PVRTVertexTangentBitangent
@Output pvTan
@Output pvBin
@Input pvNor
@Input pfPosA
@Input pfPosB
@Input pfPosC
@Input pfTexA
@Input pfTexB
@Input pfTexC
@Description Calculates the tangent and bitangent vectors for
vertex 'A' of the triangle defined by the 3 supplied
3D position coordinates (pfPosA) and 2D texture
coordinates (pfTexA).
*****************************************************************************/
void PVRTVertexTangentBitangent(
PVRTVECTOR3f * const pvTan,
PVRTVECTOR3f * const pvBin,
const PVRTVECTOR3f * const pvNor,
const float * const pfPosA,
const float * const pfPosB,
const float * const pfPosC,
const float * const pfTexA,
const float * const pfTexB,
const float * const pfTexC)
{
PVRTVECTOR3f BaseVector1, BaseVector2, AlignedVector;
if(PVRTMatrixVec3DotProductF(*pvNor, *pvNor) == 0)
{
pvTan->x = 0;
pvTan->y = 0;
pvTan->z = 0;
pvBin->x = 0;
pvBin->y = 0;
pvBin->z = 0;
return;
}
/* BaseVectors are A-B and A-C. */
BaseVector1.x = pfPosB[0] - pfPosA[0];
BaseVector1.y = pfPosB[1] - pfPosA[1];
BaseVector1.z = pfPosB[2] - pfPosA[2];
BaseVector2.x = pfPosC[0] - pfPosA[0];
BaseVector2.y = pfPosC[1] - pfPosA[1];
BaseVector2.z = pfPosC[2] - pfPosA[2];
if (pfTexB[0]==pfTexA[0] && pfTexC[0]==pfTexA[0])
{
// Degenerate tri
// _ASSERT(0);
pvTan->x = 0;
pvTan->y = 0;
pvTan->z = 0;
pvBin->x = 0;
pvBin->y = 0;
pvBin->z = 0;
}
else
{
/* Calc the vector that follows the V direction (it is not the tangent vector)*/
if(pfTexB[0]==pfTexA[0]) {
AlignedVector = BaseVector1;
if((pfTexB[1] - pfTexA[1]) < 0) {
AlignedVector.x = -AlignedVector.x;
AlignedVector.y = -AlignedVector.y;
AlignedVector.z = -AlignedVector.z;
}
} else if(pfTexC[0]==pfTexA[0]) {
AlignedVector = BaseVector2;
if((pfTexC[1] - pfTexA[1]) < 0) {
AlignedVector.x = -AlignedVector.x;
AlignedVector.y = -AlignedVector.y;
AlignedVector.z = -AlignedVector.z;
}
} else {
float fFac;
fFac = -(pfTexB[0] - pfTexA[0]) / (pfTexC[0] - pfTexA[0]);
/* This is the vector that follows the V direction (it is not the tangent vector)*/
AlignedVector.x = BaseVector1.x + BaseVector2.x * fFac;
AlignedVector.y = BaseVector1.y + BaseVector2.y * fFac;
AlignedVector.z = BaseVector1.z + BaseVector2.z * fFac;
if(((pfTexB[1] - pfTexA[1]) + (pfTexC[1] - pfTexA[1]) * fFac) < 0) {
AlignedVector.x = -AlignedVector.x;
AlignedVector.y = -AlignedVector.y;
AlignedVector.z = -AlignedVector.z;
}
}
PVRTMatrixVec3NormalizeF(AlignedVector, AlignedVector);
/* The Tangent vector is perpendicular to the plane defined by vAlignedVector and the Normal. */
PVRTMatrixVec3CrossProductF(*pvTan, *pvNor, AlignedVector);
/* The Bitangent vector is the vector perpendicular to the Normal and Tangent (and
that follows the vAlignedVector direction) */
PVRTMatrixVec3CrossProductF(*pvBin, *pvTan, *pvNor);
_ASSERT(PVRTMatrixVec3DotProductF(*pvBin, AlignedVector) > 0.0f);
// Worry about wrapping; this is esentially a 2D cross product on texture coords
if((pfTexC[0]-pfTexA[0])*(pfTexB[1]-pfTexA[1]) < (pfTexC[1]-pfTexA[1])*(pfTexB[0]-pfTexA[0])) {
pvTan->x = -pvTan->x;
pvTan->y = -pvTan->y;
pvTan->z = -pvTan->z;
}
/* Normalize results */
PVRTMatrixVec3NormalizeF(*pvTan, *pvTan);
PVRTMatrixVec3NormalizeF(*pvBin, *pvBin);
_ASSERT(PVRTMatrixVec3DotProductF(*pvNor, *pvNor) > 0.9f);
_ASSERT(PVRTMatrixVec3DotProductF(*pvTan, *pvTan) > 0.9f);
_ASSERT(PVRTMatrixVec3DotProductF(*pvBin, *pvBin) > 0.9f);
}
}
/*!***************************************************************************
@Function PVRTVertexGenerateTangentSpace
@Output pnVtxNumOut Output vertex count
@Output pVtxOut Output vertices (program must free() this)
@Modified pui32Idx input AND output; index array for triangle list
@Input nVtxNum Input vertex count
@Input pVtx Input vertices
@Input nStride Size of a vertex (in bytes)
@Input nOffsetPos Offset in bytes to the vertex position
@Input eTypePos Data type of the position
@Input nOffsetNor Offset in bytes to the vertex normal
@Input eTypeNor Data type of the normal
@Input nOffsetTex Offset in bytes to the vertex texture coordinate to use
@Input eTypeTex Data type of the texture coordinate
@Input nOffsetTan Offset in bytes to the vertex tangent
@Input eTypeTan Data type of the tangent
@Input nOffsetBin Offset in bytes to the vertex bitangent
@Input eTypeBin Data type of the bitangent
@Input nTriNum Number of triangles
@Input fSplitDifference Split a vertex if the DP3 of tangents/bitangents are below this (range -1..1)
@Return PVR_FAIL if there was a problem.
@Description Calculates the tangent space for all supplied vertices.
Writes tangent and bitangent vectors to the output
vertices, copies all other elements from input vertices.
Will split vertices if necessary - i.e. if two triangles
sharing a vertex want to assign it different
tangent-space matrices. The decision whether to split
uses fSplitDifference - of the DP3 of two desired
tangents or two desired bitangents is higher than this,
the vertex will be split.
*****************************************************************************/
EPVRTError PVRTVertexGenerateTangentSpace(
unsigned int * const pnVtxNumOut,
char ** const pVtxOut,
unsigned int * const pui32Idx,
const unsigned int nVtxNum,
const char * const pVtx,
const unsigned int nStride,
const unsigned int nOffsetPos,
EPVRTDataType eTypePos,
const unsigned int nOffsetNor,
EPVRTDataType eTypeNor,
const unsigned int nOffsetTex,
EPVRTDataType eTypeTex,
const unsigned int nOffsetTan,
EPVRTDataType eTypeTan,
const unsigned int nOffsetBin,
EPVRTDataType eTypeBin,
const unsigned int nTriNum,
const float fSplitDifference)
{
const int cnMaxSharedVtx = 32;
struct SVtxData
{
int n; // Number of items in following arrays, AKA number of tris using this vtx
PVRTVECTOR3f pvTan[cnMaxSharedVtx]; // Tangent (one per triangle referencing this vtx)
PVRTVECTOR3f pvBin[cnMaxSharedVtx]; // Bitangent (one per triangle referencing this vtx)
int pnTri[cnMaxSharedVtx]; // Triangle index (one per triangle referencing this vtx)
};
SVtxData *psVtxData; // Array of desired tangent spaces per vertex
SVtxData *psTSpass; // Array of *different* tangent spaces desired for current vertex
unsigned int nTSpassLen;
SVtxData *psVtx, *psCmp;
unsigned int nVert, nCurr, i, j; // Loop counters
unsigned int nIdx0, nIdx1, nIdx2;
float pfPos0[4], pfPos1[4], pfPos2[4];
float pfTex0[4], pfTex1[4], pfTex2[4];
float pfNor0[4], pfNor1[4], pfNor2[4];
unsigned int *pui32IdxNew; // New index array, this will be copied over the input array
// Initialise the outputs
*pnVtxNumOut = 0;
*pVtxOut = (char*)malloc(MAX_VERTEX_OUT * nStride);
if(!*pVtxOut)
{
return PVR_FAIL;
}
// Allocate some work space
pui32IdxNew = (unsigned int*)malloc(nTriNum * 3 * sizeof(*pui32IdxNew));
_ASSERT(pui32IdxNew);
psVtxData = (SVtxData*)calloc(nVtxNum, sizeof(*psVtxData));
_ASSERT(psVtxData);
psTSpass = (SVtxData*)calloc(cnMaxSharedVtx, sizeof(*psTSpass));
_ASSERT(psTSpass);
if(!pui32IdxNew || !psVtxData || !psTSpass)
{
return PVR_FAIL;
}
for(nCurr = 0; nCurr < nTriNum; ++nCurr) {
nIdx0 = pui32Idx[3*nCurr+0];
nIdx1 = pui32Idx[3*nCurr+1];
nIdx2 = pui32Idx[3*nCurr+2];
_ASSERT(nIdx0 < nVtxNum);
_ASSERT(nIdx1 < nVtxNum);
_ASSERT(nIdx2 < nVtxNum);
if(nIdx0 == nIdx1 || nIdx1 == nIdx2 || nIdx0 == nIdx2) {
_RPT0(_CRT_WARN,"GenerateTangentSpace(): Degenerate triangle found.\n");
return PVR_FAIL;
}
if(
psVtxData[nIdx0].n >= cnMaxSharedVtx ||
psVtxData[nIdx1].n >= cnMaxSharedVtx ||
psVtxData[nIdx2].n >= cnMaxSharedVtx)
{
_RPT0(_CRT_WARN,"GenerateTangentSpace(): Too many tris sharing a vtx.\n");
return PVR_FAIL;
}
PVRTVertexRead((PVRTVECTOR4f*) &pfPos0[0], (char*)&pVtx[nIdx0 * nStride] + nOffsetPos, eTypePos, 3);
PVRTVertexRead((PVRTVECTOR4f*) &pfPos1[0], (char*)&pVtx[nIdx1 * nStride] + nOffsetPos, eTypePos, 3);
PVRTVertexRead((PVRTVECTOR4f*) &pfPos2[0], (char*)&pVtx[nIdx2 * nStride] + nOffsetPos, eTypePos, 3);
PVRTVertexRead((PVRTVECTOR4f*) &pfNor0[0], (char*)&pVtx[nIdx0 * nStride] + nOffsetNor, eTypeNor, 3);
PVRTVertexRead((PVRTVECTOR4f*) &pfNor1[0], (char*)&pVtx[nIdx1 * nStride] + nOffsetNor, eTypeNor, 3);
PVRTVertexRead((PVRTVECTOR4f*) &pfNor2[0], (char*)&pVtx[nIdx2 * nStride] + nOffsetNor, eTypeNor, 3);
PVRTVertexRead((PVRTVECTOR4f*) &pfTex0[0], (char*)&pVtx[nIdx0 * nStride] + nOffsetTex, eTypeTex, 3);
PVRTVertexRead((PVRTVECTOR4f*) &pfTex1[0], (char*)&pVtx[nIdx1 * nStride] + nOffsetTex, eTypeTex, 3);
PVRTVertexRead((PVRTVECTOR4f*) &pfTex2[0], (char*)&pVtx[nIdx2 * nStride] + nOffsetTex, eTypeTex, 3);
PVRTVertexTangentBitangent(
&psVtxData[nIdx0].pvTan[psVtxData[nIdx0].n],
&psVtxData[nIdx0].pvBin[psVtxData[nIdx0].n],
(PVRTVECTOR3f*) &pfNor0[0],
pfPos0, pfPos1, pfPos2,
pfTex0, pfTex1, pfTex2);
PVRTVertexTangentBitangent(
&psVtxData[nIdx1].pvTan[psVtxData[nIdx1].n],
&psVtxData[nIdx1].pvBin[psVtxData[nIdx1].n],
(PVRTVECTOR3f*) &pfNor1[0],
pfPos1, pfPos2, pfPos0,
pfTex1, pfTex2, pfTex0);
PVRTVertexTangentBitangent(
&psVtxData[nIdx2].pvTan[psVtxData[nIdx2].n],
&psVtxData[nIdx2].pvBin[psVtxData[nIdx2].n],
(PVRTVECTOR3f*) &pfNor2[0],
pfPos2, pfPos0, pfPos1,
pfTex2, pfTex0, pfTex1);
psVtxData[nIdx0].pnTri[psVtxData[nIdx0].n] = nCurr;
psVtxData[nIdx1].pnTri[psVtxData[nIdx1].n] = nCurr;
psVtxData[nIdx2].pnTri[psVtxData[nIdx2].n] = nCurr;
++psVtxData[nIdx0].n;
++psVtxData[nIdx1].n;
++psVtxData[nIdx2].n;
}
// Now let's go through the vertices calculating avg tangent-spaces; create new vertices if necessary
for(nVert = 0; nVert < nVtxNum; ++nVert) {
psVtx = &psVtxData[nVert];
// Start out with no output vertices required for this input vertex
nTSpassLen = 0;
// Run through each desired tangent space for this vertex
for(nCurr = 0; nCurr < (unsigned int) psVtx->n; ++nCurr) {
// Run through the possible vertices we can share with to see if we match
for(i = 0; i < nTSpassLen; ++i) {
psCmp = &psTSpass[i];
// Check all the shared vertices which match
for(j = 0; j < (unsigned int) psCmp->n; ++j) {
if(PVRTMatrixVec3DotProductF(psVtx->pvTan[nCurr], psCmp->pvTan[j]) < fSplitDifference)
break;
if(PVRTMatrixVec3DotProductF(psVtx->pvBin[nCurr], psCmp->pvBin[j]) < fSplitDifference)
break;
}
// Did all the existing vertices match?
if(j == (unsigned int) psCmp->n) {
// Yes, so add to list
_ASSERT(psCmp->n < cnMaxSharedVtx);
psCmp->pvTan[psCmp->n] = psVtx->pvTan[nCurr];
psCmp->pvBin[psCmp->n] = psVtx->pvBin[nCurr];
psCmp->pnTri[psCmp->n] = psVtx->pnTri[nCurr];
++psCmp->n;
break;
}
}
if(i == nTSpassLen) {
// We never found another matching matrix, so let's add this as a different one
_ASSERT(nTSpassLen < cnMaxSharedVtx);
psTSpass[nTSpassLen].pvTan[0] = psVtx->pvTan[nCurr];
psTSpass[nTSpassLen].pvBin[0] = psVtx->pvBin[nCurr];
psTSpass[nTSpassLen].pnTri[0] = psVtx->pnTri[nCurr];
psTSpass[nTSpassLen].n = 1;
++nTSpassLen;
}
}
// OK, now we have 'nTSpassLen' different desired matrices, so we need to add that many to output
_ASSERT(nTSpassLen >= 1);
for(nCurr = 0; nCurr < nTSpassLen; ++nCurr) {
psVtx = &psTSpass[nCurr];
memset(&pfPos0, 0, sizeof(pfPos0));
memset(&pfPos1, 0, sizeof(pfPos1));
for(i = 0; i < (unsigned int) psVtx->n; ++i) {
// Sum the tangent & bitangents, so we can average them
pfPos0[0] += psVtx->pvTan[i].x;
pfPos0[1] += psVtx->pvTan[i].y;
pfPos0[2] += psVtx->pvTan[i].z;
pfPos1[0] += psVtx->pvBin[i].x;
pfPos1[1] += psVtx->pvBin[i].y;
pfPos1[2] += psVtx->pvBin[i].z;
// Update triangle indices to use this vtx
if(pui32Idx[3 * psVtx->pnTri[i] + 0] == nVert) {
pui32IdxNew[3 * psVtx->pnTri[i] + 0] = *pnVtxNumOut;
} else if(pui32Idx[3 * psVtx->pnTri[i] + 1] == nVert) {
pui32IdxNew[3 * psVtx->pnTri[i] + 1] = *pnVtxNumOut;
} else if(pui32Idx[3 * psVtx->pnTri[i] + 2] == nVert) {
pui32IdxNew[3 * psVtx->pnTri[i] + 2] = *pnVtxNumOut;
} else {
_ASSERT(0);
}
}
PVRTMatrixVec3NormalizeF(*(PVRTVECTOR3f*) &pfPos0[0], *(PVRTVECTOR3f*) &pfPos0[0]);
PVRTMatrixVec3NormalizeF(*(PVRTVECTOR3f*) &pfPos1[0], *(PVRTVECTOR3f*) &pfPos1[0]);
if(*pnVtxNumOut >= MAX_VERTEX_OUT) {
_RPT0(_CRT_WARN,"PVRTVertexGenerateTangentSpace() ran out of working space! (Too many split vertices)\n");
return PVR_FAIL;
}
memcpy(&(*pVtxOut)[(*pnVtxNumOut) * nStride], &pVtx[nVert*nStride], nStride);
PVRTVertexWrite((char*)&(*pVtxOut)[(*pnVtxNumOut) * nStride] + nOffsetTan, eTypeTan, 3, (PVRTVECTOR4f*) &pfPos0[0]);
PVRTVertexWrite((char*)&(*pVtxOut)[(*pnVtxNumOut) * nStride] + nOffsetBin, eTypeBin, 3, (PVRTVECTOR4f*) &pfPos1[0]);
++*pnVtxNumOut;
}
}
FREE(psTSpass);
FREE(psVtxData);
*pVtxOut = (char*)realloc(*pVtxOut, *pnVtxNumOut * nStride);
_ASSERT(*pVtxOut);
memcpy(pui32Idx, pui32IdxNew, nTriNum * 3 * sizeof(*pui32IdxNew));
FREE(pui32IdxNew);
_RPT3(_CRT_WARN, "GenerateTangentSpace(): %d tris, %d vtx in, %d vtx out\n", nTriNum, nVtxNum, *pnVtxNumOut);
_ASSERT(*pnVtxNumOut >= nVtxNum);
return PVR_SUCCESS;
}
/*****************************************************************************
End of file (PVRTVertex.cpp)
*****************************************************************************/
| 29.864831 | 120 | 0.554857 | [
"vector",
"3d"
] |
0920736ec3689f2366ed93473e572b6598ebde0f | 7,152 | cc | C++ | test/base/Range.test.cc | shefmarkh/celeritas | 01a16333a44c6fea4d374959f6c1bed4c18a34fa | [
"Apache-2.0",
"MIT"
] | null | null | null | test/base/Range.test.cc | shefmarkh/celeritas | 01a16333a44c6fea4d374959f6c1bed4c18a34fa | [
"Apache-2.0",
"MIT"
] | null | null | null | test/base/Range.test.cc | shefmarkh/celeritas | 01a16333a44c6fea4d374959f6c1bed4c18a34fa | [
"Apache-2.0",
"MIT"
] | null | null | null | //----------------------------------*-C++-*----------------------------------//
// Copyright 2020 UT-Battelle, LLC, and other Celeritas developers.
// See the top-level COPYRIGHT file for details.
// SPDX-License-Identifier: (Apache-2.0 OR MIT)
//---------------------------------------------------------------------------//
//! \file Range.test.cc
//---------------------------------------------------------------------------//
#include "base/Range.hh"
#include "celeritas_test.hh"
#include "Range.test.hh"
using namespace celeritas_test;
using celeritas::count;
using celeritas::range;
using VecInt = std::vector<int>;
using Vec_UInt = std::vector<unsigned int>;
enum class Colors : unsigned int
{
RED = 0,
GREEN,
BLUE,
YELLOW,
END_COLORS
};
enum Pokemon
{
CHARMANDER = 0,
BULBASAUR,
SQUIRTLE,
PIKACHU,
END_POKEMON
};
//---------------------------------------------------------------------------//
// TESTS
//---------------------------------------------------------------------------//
TEST(RangeTest, ints)
{
VecInt vals;
for (auto i : range(0, 4))
{
ASSERT_EQ(sizeof(int), sizeof(i));
vals.push_back(i);
}
// EXPECT_VEC_EQ((VecInt{0,1,2,3}), vals);
}
TEST(RangeTest, chars)
{
for (auto i : range('A', 'Z'))
{
cout << i;
}
cout << endl;
}
TEST(RangeTest, uint)
{
Vec_UInt vals;
for (auto u : range(20u, 25u).step(2u))
{
vals.push_back(u);
}
// EXPECT_VEC_EQ((Vec_UInt{20,22,24}), vals);
}
TEST(RangeTest, large)
{
using large_int = std::uint_least64_t;
// Note: you can't pass both 0 (int) and large_int(10) , because the range
// can't figure out T
for (auto i : range<large_int>(0, 10))
{
ASSERT_EQ(sizeof(large_int), sizeof(i));
}
}
TEST(RangeTest, just_end)
{
VecInt vals;
for (auto i : range(4))
{
vals.push_back(i);
ASSERT_LT(i, 10);
}
// EXPECT_VEC_EQ((VecInt{0,1,2,3}), vals);
}
TEST(RangeTest, vec_fill)
{
auto r = celeritas::range(1, 5);
EXPECT_EQ(5 - 1, r.size());
EXPECT_FALSE(r.empty());
VecInt vals(r.begin(), r.end());
// EXPECT_VEC_EQ((VecInt{1,2,3,4}), vals);
EXPECT_EQ(5 - 1, r.size());
EXPECT_FALSE(r.empty());
// Re-assign
vals.assign(r.begin(), r.end());
// EXPECT_VEC_EQ((VecInt{1,2,3,4}), vals);
r = celeritas::range(5, 5);
EXPECT_EQ(0, r.size());
EXPECT_TRUE(r.empty());
}
TEST(RangeTest, empty)
{
celeritas::FiniteRange<int> r;
EXPECT_TRUE(r.empty());
EXPECT_EQ(0, r.size());
}
TEST(RangeTest, enums)
{
int ctr = 0;
auto most_pokemon = celeritas::range(CHARMANDER, END_POKEMON);
for (Pokemon p : most_pokemon)
{
EXPECT_EQ(p, (Pokemon)ctr);
++ctr;
}
// Size of a range that returns enums
EXPECT_EQ(4, most_pokemon.size());
ctr = 0;
for (Pokemon p : celeritas::range(END_POKEMON))
{
EXPECT_EQ(p, (Pokemon)ctr);
++ctr;
}
}
TEST(RangeTest, enum_step)
{
// Since the result of enum + int is int, this is OK --
int ctr = 0;
for (auto p : celeritas::range(END_POKEMON).step(2))
{
static_assert(std::is_same<decltype(p), int>::value,
"Range result should be converted to int!");
EXPECT_EQ(p, ctr);
ctr += 2;
}
}
TEST(RangeTest, enum_classes)
{
int ctr = 0;
for (Colors c : celeritas::range(Colors::RED, Colors::END_COLORS))
{
EXPECT_EQ(c, (Colors)ctr);
++ctr;
}
/*!
* The following should fail to compile because there's no common type
* between int and enum class.
*/
#if 0
celeritas::range(Colors::END_COLORS).step(1);
#endif
}
TEST(RangeTest, backward)
{
VecInt vals;
for (auto i : range(5).step(-1))
{
vals.push_back(i);
if (i > 6 || i < -1)
break;
}
// EXPECT_VEC_EQ((VecInt{4, 3, 2, 1, 0}), vals);
vals.clear();
for (auto i : range(6).step(-2))
{
vals.push_back(i);
if (i > 7 || i < -3)
break;
}
// EXPECT_VEC_EQ((VecInt{4, 2, 0}), vals);
}
TEST(RangeTest, backward_conversion)
{
VecInt vals;
/*!
* Note that the static assertion evaluates to false because there is no
* integer type that encompasses the full range of both int and unsigned
* long
* https://stackoverflow.com/questions/15211463/why-isnt-common-typelong-unsigned-longtype-long-long
*/
#if 0
static_assert(
std::is_same<typename std::common_type<int, unsigned long long>::type,
long long>::value,
"Integer conversions are weird!");
#endif
/*!
* The following should raise an error: "non-constant-expression cannot be
* narrowed from type 'short' to 'unsigned int' in initializer list"
* rightly showing that you can't step an unsigned int backward with the
* current implementation of range.
*/
#if 0
range<unsigned int>(5).step<signed short>(-1);
#endif
// Result of 'step' should be common type of ULL and int
for (auto i : range<int>(5).step<signed short>(-1))
{
static_assert(std::is_same<decltype(i), int>::value,
"Range result should be converted to int!");
vals.push_back(i);
if (i > 7 || i < -2)
break;
}
// EXPECT_VEC_EQ((VecInt{4, 3, 2, 1, 0}), vals);
}
TEST(CountTest, infinite)
{
VecInt vals;
auto counter = count<int>().begin();
vals.push_back(*counter++);
vals.push_back(*counter++);
vals.push_back(*counter++);
// EXPECT_VEC_EQ((VecInt{0, 1, 2}), vals);
EXPECT_FALSE(count<int>().empty());
}
TEST(CountTest, start)
{
VecInt vals;
for (auto i : count(10).step(15))
{
if (i > 90)
break;
vals.push_back(i);
}
// EXPECT_VEC_EQ((VecInt{10, 25, 40, 55, 70, 85}), vals);
}
TEST(CountTest, backward)
{
VecInt vals;
// Count backward from 3 to -ininity
for (auto i : count(3).step(-1))
{
if (i > 5 || i < -1)
break;
vals.push_back(i);
}
// EXPECT_VEC_EQ((VecInt{3, 2, 1, 0, -1}), vals);
}
//---------------------------------------------------------------------------//
// DEVICE TESTS
//---------------------------------------------------------------------------//
#if CELERITAS_USE_CUDA
TEST(DeviceRangeTest, grid_stride)
{
// next prime after 1<<20 elements to avoid multiples of block/stride
unsigned int N = 1048583;
// Set Inputs
RangeTestInput input;
input.a = 3;
input.x.assign(N, 1);
// y varies with index so we can verify common order on CPU vs Device
input.y.assign(N, 0);
for (auto i : range(N))
{
input.y[i] = i;
}
input.num_threads = 32;
input.num_blocks = 256;
// Calculate saxpy using CPU
std::vector<int> z_cpu(N, 0.0);
for (auto i : range(N))
{
z_cpu[i] = input.a * input.x[i] + input.y[i];
}
// Calculate saxpy on Device
RangeTestOutput result = rangedev_test(input);
EXPECT_VEC_EQ(z_cpu, result.z);
}
#endif | 22.704762 | 104 | 0.533277 | [
"vector"
] |
0936337983b5776b533fb1d64ab195c944bfa742 | 7,640 | cpp | C++ | CPP/Shared/GuiProt/SearchPrintingPolicySwedish.cpp | wayfinder/Wayfinder-S60-Navigator | 14d1b729b2cea52f726874687e78f17492949585 | [
"BSD-3-Clause"
] | 6 | 2015-12-01T01:12:33.000Z | 2021-07-24T09:02:34.000Z | CPP/Shared/GuiProt/SearchPrintingPolicySwedish.cpp | wayfinder/Wayfinder-S60-Navigator | 14d1b729b2cea52f726874687e78f17492949585 | [
"BSD-3-Clause"
] | null | null | null | CPP/Shared/GuiProt/SearchPrintingPolicySwedish.cpp | wayfinder/Wayfinder-S60-Navigator | 14d1b729b2cea52f726874687e78f17492949585 | [
"BSD-3-Clause"
] | 2 | 2017-02-02T19:31:29.000Z | 2018-12-17T21:00:45.000Z | /*
Copyright (c) 1999 - 2010, Vodafone Group Services Ltd
All rights reserved.
Redistribution and use in source and binary forms, with or without modification, are permitted provided that the following conditions are met:
* Redistributions of source code must retain the above copyright notice, this list of conditions and the following disclaimer.
* Redistributions in binary form must reproduce the above copyright notice, this list of conditions and the following disclaimer in the documentation and/or other materials provided with the distribution.
* Neither the name of the Vodafone Group Services Ltd nor the names of its contributors may be used to endorse or promote products derived from this software without specific prior written permission.
THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT HOLDER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
*/
#include <arch.h>
#include <vector>
#include "nav2util.h"
#include "GuiProt/SearchPrintingPolicySwedish.h"
#include "GuiProt/Serializable.h"
#include "GuiProt/SearchRegion.h"
#include "GuiProt/SearchItem.h"
#include "GuiProt/SearchArea.h"
#include "GuiProt/AdditionalInfo.h"
#include "GuiProt/FullSearchItem.h"
#include "GuiProt/HelperEnums.h"
#include "DistancePrintingPolicy.h"
namespace isab {
char *
SearchPrintingPolicySwedish::parseSearchItem(const SearchItem* item,
bool tabs,
DistancePrintingPolicy::DistanceMode mode,
bool addName )
{
const char *city = "";
const char *address = "";
const char *streetNumber = "";
char *m_processedString;
/* Perform the formatting of the search match string */
#define MAX_STR_LEN 256
m_processedString = new char[MAX_STR_LEN];
/* Null termination. */
int curPos = 0;
if (tabs) {
m_processedString[curPos++] = '\t';
}
m_processedString[curPos] = 0;
bool addComma = true;
const char* tmp = NULL;
if ( addName ) {
/* 1. The search match name. */
tmp = item->getName();
if ( tmp && (signed int)strlen( tmp ) < (MAX_STR_LEN-curPos) ) {
strcat(m_processedString, tmp);
} else {
strncat( m_processedString, tmp, (MAX_STR_LEN-curPos-4) );
curPos += (MAX_STR_LEN-curPos-4);
if ( tabs ) {
m_processedString[curPos++] = '\t';
}
m_processedString[curPos++] = '\0';
return m_processedString;
}
curPos += strlen( tmp );
/* 2. Next line. */
if ( tabs ) {
m_processedString[ curPos++ ] = '\t';
} else {
m_processedString[ curPos++ ] = ',';
}
m_processedString[ curPos ] = '\0';
} else {
addComma = false;
}
/* 3. Add distance, if it's valid. */
if(item->getDistance() != MAX_UINT32){
char* tmp2 = DistancePrintingPolicy::convertDistance(item->getDistance(),
mode, DistancePrintingPolicy::Round);
if (tmp2 && (signed int)strlen(tmp2) < (MAX_STR_LEN-curPos)) {
strcat(m_processedString, tmp2);
delete[] tmp2;
curPos += strlen(tmp2);
} else {
return m_processedString;
}
} else {
addComma = false;
}
/* Check the regions. */
/* 4. We need to find the City first. */
unsigned int numRegions = item->noRegions();
unsigned int j = 0;
while (j < numRegions ) {
/* Is this the city region? */
const SearchRegion* region = item->getRegion(j);
if (region->getType() == GuiProtEnums::city) {
/* Yup, got it. */
if (addComma) {
tmp = ", ";
strcat(m_processedString, tmp);
} else {
addComma = true;
}
tmp = region->getName();
if (tmp && (signed int)strlen(tmp) < (MAX_STR_LEN-curPos)) {
strcat(m_processedString, tmp);
} else {
return m_processedString;
}
curPos += strlen(tmp);
city = tmp;
}
j++;
}
/* 5. Now we check for a street address. */
j=0;
while (j < numRegions ) {
/* Is this the street address region? */
const SearchRegion* region = item->getRegion(j);
if (region->getType() == GuiProtEnums::address) {
/* Yup, got it. */
if (addComma) {
tmp = ", ";
strcat(m_processedString, tmp);
} else {
addComma = true;
}
tmp = region->getName();
if (tmp && (signed int)strlen(tmp) < (MAX_STR_LEN-curPos)) {
strcat(m_processedString, tmp);
} else {
return m_processedString;
}
curPos += strlen(tmp);
address = tmp;
}
j++;
}
if (j == numRegions) {
/* No street address found. */
/* Don't care about street number. */
} else {
/* 6. Check for street number. */
j=0;
while (j < numRegions ) {
/* Is this the street number region? */
const SearchRegion* region = item->getRegion(j);
if (region->getType() == GuiProtEnums::streetNumber) {
/* Yup, got it. */
tmp = " ";
strcat(m_processedString, tmp);
tmp = region->getName();
if (tmp && (signed int)strlen(tmp) < (MAX_STR_LEN-curPos)) {
strcat(m_processedString, tmp);
} else {
return m_processedString;
}
curPos += strlen(tmp);
streetNumber = tmp;
}
j++;
}
}
/* 7. Ok, now add the rest of the regions in order. */
/* Two important things: */
/* a) We need to remove the strings already copied. */
/* b) No duplicates are allowed (including the already */
/* copied strings. */
for (j = 0; j < numRegions ; j++ ) {
const SearchRegion* region = item->getRegion(j);
/* Is this one of the previously written strings? */
if (strcaseequ(city, region->getName())) {
/* Ignore this value. */
continue;
}
if (strcaseequ(address, region->getName())) {
/* Ignore this value. */
continue;
}
if (strcaseequ(streetNumber, region->getName())) {
/* Ignore this value. */
continue;
}
/* The region is not one of the regions above, or any */
/* region that has the same name (when folded). */
/* We can add the region. */
if (addComma) {
tmp = ", ";
strcat(m_processedString, tmp);
} else {
addComma = true;
}
tmp = region->getName();
if (tmp && (signed int)strlen(tmp) < (MAX_STR_LEN-curPos)) {
strcat(m_processedString, tmp);
} else {
return m_processedString;
}
curPos += strlen(tmp);
}
return m_processedString;
}
}
| 35.37037 | 759 | 0.57788 | [
"vector"
] |
09394c0f37fe386d73934042c111c54394ef0392 | 4,459 | cc | C++ | RecoVertex/KinematicFit/src/KinematicParticleVertexFitter.cc | ckamtsikis/cmssw | ea19fe642bb7537cbf58451dcf73aa5fd1b66250 | [
"Apache-2.0"
] | 852 | 2015-01-11T21:03:51.000Z | 2022-03-25T21:14:00.000Z | RecoVertex/KinematicFit/src/KinematicParticleVertexFitter.cc | ckamtsikis/cmssw | ea19fe642bb7537cbf58451dcf73aa5fd1b66250 | [
"Apache-2.0"
] | 30,371 | 2015-01-02T00:14:40.000Z | 2022-03-31T23:26:05.000Z | RecoVertex/KinematicFit/src/KinematicParticleVertexFitter.cc | ckamtsikis/cmssw | ea19fe642bb7537cbf58451dcf73aa5fd1b66250 | [
"Apache-2.0"
] | 3,240 | 2015-01-02T05:53:18.000Z | 2022-03-31T17:24:21.000Z | #include "RecoVertex/KinematicFit/interface/KinematicParticleVertexFitter.h"
// #include "Vertex/LinearizationPointFinders/interface/LMSLinearizationPointFinder.h"
#include "RecoVertex/KinematicFit/interface/FinalTreeBuilder.h"
#include "RecoVertex/VertexTools/interface/SequentialVertexSmoother.h"
#include "RecoVertex/KalmanVertexFit/interface/KalmanVertexUpdator.h"
#include "RecoVertex/KalmanVertexFit/interface/KalmanVertexTrackUpdator.h"
#include "RecoVertex/KalmanVertexFit/interface/KalmanSmoothedVertexChi2Estimator.h"
#include "RecoVertex/KalmanVertexFit/interface/KalmanTrackToTrackCovCalculator.h"
#include "RecoVertex/VertexPrimitives/interface/VertexException.h"
#include "RecoVertex/LinearizationPointFinders/interface/DefaultLinearizationPointFinder.h"
#include "RecoVertex/VertexTools/interface/SequentialVertexFitter.h"
#include "DataFormats/CLHEP/interface/Migration.h"
#include "FWCore/MessageLogger/interface/MessageLogger.h"
KinematicParticleVertexFitter::KinematicParticleVertexFitter() {
edm::ParameterSet pSet = defaultParameters();
setup(pSet);
}
KinematicParticleVertexFitter::KinematicParticleVertexFitter(const edm::ParameterSet &pSet) { setup(pSet); }
void KinematicParticleVertexFitter::setup(const edm::ParameterSet &pSet) {
pointFinder = new DefaultLinearizationPointFinder();
vFactory = new VertexTrackFactory<6>();
KalmanVertexTrackUpdator<6> vtu;
KalmanSmoothedVertexChi2Estimator<6> vse;
KalmanTrackToTrackCovCalculator<6> covCalc;
SequentialVertexSmoother<6> smoother(vtu, vse, covCalc);
fitter = new SequentialVertexFitter<6>(
pSet, *pointFinder, KalmanVertexUpdator<6>(), smoother, ParticleKinematicLinearizedTrackStateFactory());
}
KinematicParticleVertexFitter::~KinematicParticleVertexFitter() {
delete vFactory;
delete pointFinder;
delete fitter;
}
edm::ParameterSet KinematicParticleVertexFitter::defaultParameters() const {
edm::ParameterSet pSet;
pSet.addParameter<double>("maxDistance", 0.01);
pSet.addParameter<int>("maxNbrOfIterations", 100); //10
return pSet;
}
RefCountedKinematicTree KinematicParticleVertexFitter::fit(
const std::vector<RefCountedKinematicParticle> &particles) const {
typedef ReferenceCountingPointer<VertexTrack<6> > RefCountedVertexTrack;
//sorting the input
if (particles.size() < 2)
throw VertexException("KinematicParticleVertexFitter::input states are less than 2");
InputSort iSort;
std::pair<std::vector<RefCountedKinematicParticle>, std::vector<FreeTrajectoryState> > input = iSort.sort(particles);
std::vector<RefCountedKinematicParticle> &newPart = input.first;
std::vector<FreeTrajectoryState> &freeStates = input.second;
GlobalPoint linPoint = pointFinder->getLinearizationPoint(freeStates);
// cout<<"Linearization point found"<<endl;
//making initial veretx seed with lin point as position and a fake error
AlgebraicSymMatrix33 we;
we(0, 0) = we(1, 1) = we(2, 2) = 10000.;
GlobalError error(we);
VertexState state(linPoint, error);
//vector of Vertex Tracks to fit
std::vector<RefCountedVertexTrack> ttf;
TrackKinematicStatePropagator propagator_;
for (auto const &i : newPart) {
if (!(i)->currentState().isValid() || !propagator_.willPropagateToTheTransversePCA((i)->currentState(), linPoint)) {
// std::cout << "Here's the bad state." << std::endl;
return ReferenceCountingPointer<KinematicTree>(new KinematicTree()); // return invalid vertex
}
ttf.push_back(vFactory->vertexTrack((i)->particleLinearizedTrackState(linPoint), state, 1.));
}
// //debugging code to check neutrals:
// for(std::vector<RefCountedVertexTrack>::const_iterator i = ttf.begin(); i!=ttf.end(); i++)
// {
// // cout<<"predicted state momentum error"<<(*i)->linearizedTrack()->predictedStateMomentumError()<<endl;
// // cout<<"Momentum jacobian"<<(*i)->linearizedTrack()->momentumJacobian() <<endl;
// // cout<<"predicted state momentum "<<(*i)->linearizedTrack()->predictedStateMomentum()<<endl;
// // cout<<"constant term"<<(*i)->linearizedTrack()->constantTerm()<<endl;
//
// }
CachingVertex<6> vtx = fitter->vertex(ttf);
if (!vtx.isValid()) {
LogDebug("RecoVertex/KinematicParticleVertexFitter") << "Fitted position is invalid. Returned Tree is invalid\n";
return ReferenceCountingPointer<KinematicTree>(new KinematicTree()); // return invalid vertex
}
FinalTreeBuilder tBuilder;
return tBuilder.buildTree(vtx, newPart);
}
| 45.969072 | 120 | 0.767437 | [
"vector"
] |
093a72b0020cef486c61ac648e0be84ec18c07f1 | 392 | cpp | C++ | C++/1. Introduction/8. Arrays Introduction/arrays-introduction.cpp | princeofpython/HakerRank-Practice | 510bc4230c5f704eb61721d9f420f76cdabf0bd2 | [
"MIT"
] | null | null | null | C++/1. Introduction/8. Arrays Introduction/arrays-introduction.cpp | princeofpython/HakerRank-Practice | 510bc4230c5f704eb61721d9f420f76cdabf0bd2 | [
"MIT"
] | null | null | null | C++/1. Introduction/8. Arrays Introduction/arrays-introduction.cpp | princeofpython/HakerRank-Practice | 510bc4230c5f704eb61721d9f420f76cdabf0bd2 | [
"MIT"
] | null | null | null | #include <cmath>
#include <cstdio>
#include <vector>
#include <iostream>
#include <algorithm>
using namespace std;
int main() {
/* Enter your code here. Read input from STDIN. Print output to STDOUT */
int n;
cin >> n;
int arr[n];
for(int j=0; j<n ; j++)
cin >> arr[j];
for(int i = n-1; i>=0 ; --i)
{
cout << arr[i]<<' ';
}
return 0;
} | 18.666667 | 80 | 0.528061 | [
"vector"
] |
093a95093f0ea25afc4a9358b32a754a1d231aa3 | 7,333 | cpp | C++ | core/src/db/snapshot/Snapshots.cpp | openhisilicon/milvus | 1b4e49a3f4b05fe684ebb2aa804de3d341eb289c | [
"Apache-2.0"
] | 4 | 2020-07-29T02:59:53.000Z | 2021-11-16T11:07:51.000Z | core/src/db/snapshot/Snapshots.cpp | openhisilicon/milvus | 1b4e49a3f4b05fe684ebb2aa804de3d341eb289c | [
"Apache-2.0"
] | null | null | null | core/src/db/snapshot/Snapshots.cpp | openhisilicon/milvus | 1b4e49a3f4b05fe684ebb2aa804de3d341eb289c | [
"Apache-2.0"
] | 2 | 2021-06-09T23:50:48.000Z | 2021-06-17T06:24:29.000Z | // Copyright (C) 2019-2020 Zilliz. 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 "db/snapshot/Snapshots.h"
#include "db/snapshot/CompoundOperations.h"
namespace milvus {
namespace engine {
namespace snapshot {
/* Status */
/* Snapshots::DropAll() { */
/* } */
Status
Snapshots::DropCollection(ID_TYPE collection_id, const LSN_TYPE& lsn) {
ScopedSnapshotT ss;
auto status = GetSnapshot(ss, collection_id);
if (!status.ok())
return status;
return DoDropCollection(ss, lsn);
}
Status
Snapshots::DropCollection(const std::string& name, const LSN_TYPE& lsn) {
ScopedSnapshotT ss;
auto status = GetSnapshot(ss, name);
if (!status.ok())
return status;
return DoDropCollection(ss, lsn);
}
Status
Snapshots::DoDropCollection(ScopedSnapshotT& ss, const LSN_TYPE& lsn) {
OperationContext context;
context.lsn = lsn;
context.collection = ss->GetCollection();
auto op = std::make_shared<DropCollectionOperation>(context, ss);
op->Push();
auto status = op->GetStatus();
std::unique_lock<std::shared_timed_mutex> lock(mutex_);
name_id_map_.erase(context.collection->GetName());
holders_.erase(context.collection->GetID());
return status;
}
Status
Snapshots::DropPartition(const ID_TYPE& collection_id, const ID_TYPE& partition_id, const LSN_TYPE& lsn) {
ScopedSnapshotT ss;
auto status = GetSnapshot(ss, collection_id);
if (!status.ok()) {
return status;
}
PartitionContext context;
context.id = partition_id;
context.lsn = lsn;
auto op = std::make_shared<DropPartitionOperation>(context, ss);
status = op->Push();
if (!status.ok()) {
return status;
}
status = op->GetSnapshot(ss);
if (!status.ok()) {
return status;
}
return op->GetStatus();
}
Status
Snapshots::LoadSnapshot(Store& store, ScopedSnapshotT& ss, ID_TYPE collection_id, ID_TYPE id, bool scoped) {
SnapshotHolderPtr holder;
auto status = LoadHolder(store, collection_id, holder);
if (!status.ok())
return status;
status = holder->Load(store, ss, id, scoped);
return status;
}
Status
Snapshots::GetSnapshot(ScopedSnapshotT& ss, ID_TYPE collection_id, ID_TYPE id, bool scoped) const {
SnapshotHolderPtr holder;
auto status = GetHolder(collection_id, holder);
if (!status.ok())
return status;
status = holder->Get(ss, id, scoped);
return status;
}
Status
Snapshots::GetSnapshot(ScopedSnapshotT& ss, const std::string& name, ID_TYPE id, bool scoped) const {
SnapshotHolderPtr holder;
auto status = GetHolder(name, holder);
if (!status.ok())
return status;
status = holder->Get(ss, id, scoped);
return status;
}
Status
Snapshots::GetCollectionIds(IDS_TYPE& ids) const {
std::shared_lock<std::shared_timed_mutex> lock(mutex_);
for (auto& kv : holders_) {
ids.push_back(kv.first);
}
return Status::OK();
}
Status
Snapshots::GetCollectionNames(std::vector<std::string>& names) const {
std::shared_lock<std::shared_timed_mutex> lock(mutex_);
for (auto& kv : name_id_map_) {
names.push_back(kv.first);
}
return Status::OK();
}
Status
Snapshots::LoadNoLock(Store& store, ID_TYPE collection_id, SnapshotHolderPtr& holder) {
auto op = std::make_shared<GetSnapshotIDsOperation>(collection_id, false);
/* op->Push(); */
(*op)(store);
auto& collection_commit_ids = op->GetIDs();
if (collection_commit_ids.size() == 0) {
std::stringstream emsg;
emsg << "Snapshots::LoadNoLock: No collection commit is found for collection " << collection_id;
return Status(SS_NOT_FOUND_ERROR, emsg.str());
}
holder = std::make_shared<SnapshotHolder>(collection_id,
std::bind(&Snapshots::SnapshotGCCallback, this, std::placeholders::_1));
for (auto c_c_id : collection_commit_ids) {
holder->Add(c_c_id);
}
return Status::OK();
}
void
Snapshots::Init() {
auto op = std::make_shared<GetCollectionIDsOperation>();
op->Push();
auto& collection_ids = op->GetIDs();
SnapshotHolderPtr holder;
// TODO
for (auto collection_id : collection_ids) {
/* GetHolder(collection_id, holder); */
auto& store = Store::GetInstance();
LoadHolder(store, collection_id, holder);
}
}
Status
Snapshots::GetHolder(const std::string& name, SnapshotHolderPtr& holder) const {
std::shared_lock<std::shared_timed_mutex> lock(mutex_);
auto kv = name_id_map_.find(name);
if (kv != name_id_map_.end()) {
lock.unlock();
return GetHolder(kv->second, holder);
}
std::stringstream emsg;
emsg << "Snapshots::GetHolderNoLock: Specified snapshot holder for collection ";
emsg << "\"" << name << "\""
<< " not found";
return Status(SS_NOT_FOUND_ERROR, emsg.str());
}
Status
Snapshots::GetHolder(const ID_TYPE& collection_id, SnapshotHolderPtr& holder) const {
Status status;
std::shared_lock<std::shared_timed_mutex> lock(mutex_);
status = GetHolderNoLock(collection_id, holder);
return status;
}
Status
Snapshots::LoadHolder(Store& store, const ID_TYPE& collection_id, SnapshotHolderPtr& holder) {
Status status;
{
std::shared_lock<std::shared_timed_mutex> lock(mutex_);
status = GetHolderNoLock(collection_id, holder);
if (status.ok() && holder)
return status;
}
status = LoadNoLock(store, collection_id, holder);
if (!status.ok())
return status;
std::unique_lock<std::shared_timed_mutex> lock(mutex_);
holders_[collection_id] = holder;
ScopedSnapshotT ss;
status = holder->Load(store, ss);
if (!status.ok())
return status;
name_id_map_[ss->GetName()] = collection_id;
return status;
}
Status
Snapshots::GetHolderNoLock(ID_TYPE collection_id, SnapshotHolderPtr& holder) const {
auto it = holders_.find(collection_id);
if (it == holders_.end()) {
std::stringstream emsg;
emsg << "Snapshots::GetHolderNoLock: Specified snapshot holder for collection " << collection_id;
emsg << " not found";
return Status(SS_NOT_FOUND_ERROR, emsg.str());
}
holder = it->second;
return Status::OK();
}
Status
Snapshots::Reset() {
std::unique_lock<std::shared_timed_mutex> lock(mutex_);
holders_.clear();
name_id_map_.clear();
to_release_.clear();
return Status::OK();
}
void
Snapshots::SnapshotGCCallback(Snapshot::Ptr ss_ptr) {
/* to_release_.push_back(ss_ptr); */
ss_ptr->UnRef();
std::cout << "Snapshot " << ss_ptr->GetID() << " ref_count = " << ss_ptr->ref_count() << " To be removed"
<< std::endl;
}
} // namespace snapshot
} // namespace engine
} // namespace milvus
| 30.176955 | 118 | 0.668349 | [
"vector"
] |
093cb01ad13c7eefbbfc2d9b7f59fa20fe087c72 | 101,389 | cc | C++ | client/clang_features.cc | xswz8015/goma_client | b0064de5f02694595792f4f38b5ec2ae81cf589d | [
"BSD-3-Clause"
] | null | null | null | client/clang_features.cc | xswz8015/goma_client | b0064de5f02694595792f4f38b5ec2ae81cf589d | [
"BSD-3-Clause"
] | null | null | null | client/clang_features.cc | xswz8015/goma_client | b0064de5f02694595792f4f38b5ec2ae81cf589d | [
"BSD-3-Clause"
] | null | null | null | // Copyright 2021 The Goma Authors. All rights reserved.
// Use of this source code is governed by a BSD-style license that can be
// found in the LICENSE file.
//
// This is auto-generated file by
// go run generate_feature_lists.go -r
// aee49255074fd4ef38d97e6e70cbfbf2f9fd0fa7 -o client/clang_features.cc.
//
// LLVM revison: aee49255074fd4ef38d97e6e70cbfbf2f9fd0fa7
// *** DO NOT EDIT ***
#include "absl/base/macros.h"
static const char* KNOWN_FEATURES[] = {
"address_sanitizer",
"arc_cf_code_audited",
"assume_nonnull",
"attribute_analyzer_noreturn",
"attribute_availability",
"attribute_availability_app_extension",
"attribute_availability_in_templates",
"attribute_availability_swift",
"attribute_availability_tvos",
"attribute_availability_watchos",
"attribute_availability_with_message",
"attribute_availability_with_replacement",
"attribute_availability_with_strict",
"attribute_availability_with_version_underscores",
"attribute_cf_consumed",
"attribute_cf_returns_not_retained",
"attribute_cf_returns_on_parameters",
"attribute_cf_returns_retained",
"attribute_deprecated_with_message",
"attribute_deprecated_with_replacement",
"attribute_diagnose_if_objc",
"attribute_ext_vector_type",
"attribute_ns_consumed",
"attribute_ns_consumes_self",
"attribute_ns_returns_not_retained",
"attribute_ns_returns_retained",
"attribute_objc_ivar_unused",
"attribute_objc_method_family",
"attribute_overloadable",
"attribute_unavailable_with_message",
"attribute_unused_on_fields",
"blocks",
"c_alignas",
"c_alignof",
"c_atomic",
"c_generic_selections",
"c_static_assert",
"c_thread_local",
"c_thread_safety_attributes",
"coverage_sanitizer",
"cxx_abi_relative_vtable",
"cxx_access_control_sfinae",
"cxx_aggregate_nsdmi",
"cxx_alias_templates",
"cxx_alignas",
"cxx_alignof",
"cxx_atomic",
"cxx_attributes",
"cxx_auto_type",
"cxx_binary_literals",
"cxx_constexpr",
"cxx_constexpr_string_builtins",
"cxx_contextual_conversions",
"cxx_decltype",
"cxx_decltype_auto",
"cxx_decltype_incomplete_return_types",
"cxx_default_function_template_args",
"cxx_defaulted_functions",
"cxx_delegating_constructors",
"cxx_deleted_functions",
"cxx_exceptions",
"cxx_explicit_conversions",
"cxx_generalized_initializers",
"cxx_generic_lambdas",
"cxx_implicit_moves",
"cxx_inheriting_constructors",
"cxx_init_captures",
"cxx_inline_namespaces",
"cxx_lambdas",
"cxx_local_type_template_args",
"cxx_noexcept",
"cxx_nonstatic_member_init",
"cxx_nullptr",
"cxx_override_control",
"cxx_range_for",
"cxx_raw_string_literals",
"cxx_reference_qualified_functions",
"cxx_relaxed_constexpr",
"cxx_return_type_deduction",
"cxx_rtti",
"cxx_rvalue_references",
"cxx_static_assert",
"cxx_strong_enums",
"cxx_thread_local",
"cxx_trailing_return",
"cxx_unicode_literals",
"cxx_unrestricted_unions",
"cxx_user_literals",
"cxx_variable_templates",
"cxx_variadic_templates",
"dataflow_sanitizer",
"enumerator_attributes",
"has_nothrow_assign",
"has_nothrow_constructor",
"has_nothrow_copy",
"has_trivial_assign",
"has_trivial_constructor",
"has_trivial_copy",
"has_trivial_destructor",
"has_virtual_destructor",
"hwaddress_sanitizer",
"is_abstract",
"is_base_of",
"is_class",
"is_constructible",
"is_convertible_to",
"is_empty",
"is_enum",
"is_final",
"is_literal",
"is_pod",
"is_polymorphic",
"is_sealed",
"is_standard_layout",
"is_trivial",
"is_trivially_assignable",
"is_trivially_constructible",
"is_trivially_copyable",
"is_union",
"leak_sanitizer",
"memory_sanitizer",
"memtag_sanitizer",
"modules",
"nullability",
"nullability_nullable_result",
"nullability_on_arrays",
"objc_arc",
"objc_arc_fields",
"objc_arc_weak",
"objc_arr",
"objc_array_literals",
"objc_bool",
"objc_boxed_expressions",
"objc_boxed_nsvalue_expressions",
"objc_bridge_id",
"objc_bridge_id_on_typedefs",
"objc_c_static_assert",
"objc_class_property",
"objc_cxx_static_assert",
"objc_default_synthesize_properties",
"objc_dictionary_literals",
"objc_fixed_enum",
"objc_generics",
"objc_generics_variance",
"objc_instancetype",
"objc_kindof",
"objc_modules",
"objc_nonfragile_abi",
"objc_property_explicit_atomic",
"objc_protocol_qualifier_mangling",
"objc_subscripting",
"objc_weak_class",
"ownership_holds",
"ownership_returns",
"ownership_takes",
"safe_stack",
"scudo",
"shadow_call_stack",
"speculative_load_hardening",
"swiftasynccc",
"thread_sanitizer",
"tls",
"undefined_behavior_sanitizer",
"underlying_type",
"xray_instrument",
};
static const unsigned long NUM_KNOWN_FEATURES = ABSL_ARRAYSIZE(KNOWN_FEATURES);
static const char* KNOWN_EXTENSIONS[] = {
"c_alignas",
"c_alignof",
"c_atomic",
"c_generic_selections",
"c_static_assert",
"c_thread_local",
"cxx_atomic",
"cxx_attributes_on_using_declarations",
"cxx_binary_literals",
"cxx_deleted_functions",
"cxx_explicit_conversions",
"cxx_fixed_enum",
"cxx_init_captures",
"cxx_inline_namespaces",
"cxx_local_type_template_args",
"cxx_nonstatic_member_init",
"cxx_override_control",
"cxx_range_for",
"cxx_reference_qualified_functions",
"cxx_rvalue_references",
"cxx_variable_templates",
"cxx_variadic_templates",
"gnu_asm",
"gnu_asm_goto_with_outputs",
"matrix_types",
"matrix_types_scalar_division",
"objc_c_static_assert",
"overloadable_unmarked",
"pragma_clang_attribute_external_declaration",
"pragma_clang_attribute_namespaces",
"statement_attributes_with_gnu_syntax",
};
static const unsigned long NUM_KNOWN_EXTENSIONS =
ABSL_ARRAYSIZE(KNOWN_EXTENSIONS);
static const char* KNOWN_ATTRIBUTES[] = {
"NSObject",
"Owner",
"Pointer",
"_Alignas",
"_Nonnull",
"_Noreturn",
"_Null_unspecified",
"_Nullable",
"_Nullable_result",
"__asm__",
"__cdecl",
"__clang_arm_builtin_alias",
"__clang_arm_mve_strict_polymorphism",
"__const",
"__constant",
"__constant__",
"__cudart_builtin__",
"__device__",
"__device_builtin__",
"__device_builtin_surface_type__",
"__device_builtin_texture_type__",
"__fastcall",
"__forceinline",
"__generic",
"__global",
"__global__",
"__host__",
"__kernel",
"__kindof",
"__launch_bounds__",
"__local",
"__managed__",
"__multiple_inheritance",
"__pascal",
"__private",
"__ptr32",
"__ptr64",
"__read_only",
"__read_write",
"__regcall",
"__shared__",
"__single_inheritance",
"__sptr",
"__stdcall",
"__thiscall",
"__unspecified_inheritance",
"__uptr",
"__vectorcall",
"__virtual_inheritance",
"__w64",
"__write_only",
"_cdecl",
"_fastcall",
"_pascal",
"_stdcall",
"_thiscall",
"_vectorcall",
"aarch64_vector_pcs",
"abi_tag",
"acquire_capability",
"acquire_handle",
"acquire_shared_capability",
"acquired_after",
"acquired_before",
"address_space",
"alias",
"align",
"align_value",
"alignas",
"aligned",
"alloc_align",
"alloc_size",
"allocate",
"allocator",
"always_destroy",
"always_inline",
"amdgpu_flat_work_group_size",
"amdgpu_num_sgpr",
"amdgpu_num_vgpr",
"amdgpu_waves_per_eu",
"analyzer_noreturn",
"annotate",
"argument_with_type_tag",
"arm_sve_vector_bits",
"artificial",
"asm",
"assert_capability",
"assert_exclusive_lock",
"assert_shared_capability",
"assert_shared_lock",
"assume",
"assume_aligned",
"availability",
"blocks",
"bounded",
"btf_decl_tag",
"builtin_alias",
"callable_when",
"callback",
"called_once",
"capability",
"carries_dependency",
"cdecl",
"cf_audited_transfer",
"cf_consumed",
"cf_returns_not_retained",
"cf_returns_retained",
"cf_unknown_transfer",
"cfi_canonical_jump_table",
"clang_builtin_alias",
"cleanup",
"cmse_nonsecure_call",
"cmse_nonsecure_entry",
"code_seg",
"cold",
"common",
"const",
"constant",
"constinit",
"constructor",
"consumable",
"consumable_auto_cast_state",
"consumable_set_state_on_read",
"convergent",
"cpu_dispatch",
"cpu_specific",
"cudart_builtin",
"deprecated",
"destructor",
"device",
"device_builtin",
"device_builtin_surface_type",
"device_builtin_texture_type",
"diagnose_if",
"disable_sanitizer_instrumentation",
"disable_tail_calls",
"dllexport",
"dllimport",
"empty_bases",
"enable_if",
"enforce_tcb",
"enforce_tcb_leaf",
"enum_extensibility",
"error",
"exclude_from_explicit_instantiation",
"exclusive_lock_function",
"exclusive_locks_required",
"exclusive_trylock_function",
"export_name",
"ext_vector_type",
"external_source_symbol",
"fallthrough",
"far",
"fastcall",
"final",
"flag_enum",
"flatten",
"force_align_arg_pointer",
"format",
"format_arg",
"generic",
"global",
"gnu_inline",
"guard",
"guarded_by",
"guarded_var",
"host",
"hot",
"ibaction",
"iboutlet",
"iboutletcollection",
"ifunc",
"import_module",
"import_name",
"init_priority",
"init_seg",
"intel_ocl_bicc",
"intel_reqd_sub_group_size",
"internal_linkage",
"interrupt",
"kernel",
"launch_bounds",
"layout_version",
"leaf",
"lifetimebound",
"likely",
"loader_uninitialized",
"local",
"lock_returned",
"lockable",
"locks_excluded",
"long_call",
"loop",
"lto_visibility_public",
"malloc",
"managed",
"matrix_type",
"may_alias",
"maybe_unused",
"micromips",
"mig_server_routine",
"min_vector_width",
"minsize",
"mips16",
"mode",
"ms_abi",
"ms_struct",
"musttail",
"naked",
"near",
"neon_polyvector_type",
"neon_vector_type",
"no_address_safety_analysis",
"no_builtin",
"no_caller_saved_registers",
"no_destroy",
"no_instrument_function",
"no_profile_instrument_function",
"no_sanitize",
"no_sanitize_address",
"no_sanitize_memory",
"no_sanitize_thread",
"no_speculative_load_hardening",
"no_split_stack",
"no_stack_protector",
"no_thread_safety_analysis",
"no_unique_address",
"noalias",
"nocf_check",
"nocommon",
"nodebug",
"noderef",
"nodiscard",
"noduplicate",
"noescape",
"noinline",
"nomerge",
"nomicromips",
"nomips16",
"nonnull",
"noreturn",
"nosvm",
"not_tail_called",
"nothrow",
"nounroll",
"nounroll_and_jam",
"novtable",
"ns_consumed",
"ns_consumes_self",
"ns_error_domain",
"ns_returns_autoreleased",
"ns_returns_not_retained",
"ns_returns_retained",
"nv_weak",
"objc_arc_weak_reference_unavailable",
"objc_boxable",
"objc_bridge",
"objc_bridge_mutable",
"objc_bridge_related",
"objc_class_stub",
"objc_designated_initializer",
"objc_direct",
"objc_direct_members",
"objc_exception",
"objc_externally_retained",
"objc_gc",
"objc_independent_class",
"objc_method_family",
"objc_non_runtime_protocol",
"objc_nonlazy_class",
"objc_ownership",
"objc_precise_lifetime",
"objc_protocol_requires_explicit_implementation",
"objc_requires_property_definitions",
"objc_requires_super",
"objc_returns_inner_pointer",
"objc_root_class",
"objc_runtime_name",
"objc_runtime_visible",
"objc_subclassing_restricted",
"opencl_constant",
"opencl_generic",
"opencl_global",
"opencl_global_device",
"opencl_global_host",
"opencl_local",
"opencl_private",
"opencl_unroll_hint",
"optnone",
"os_consumed",
"os_consumes_this",
"os_returns_not_retained",
"os_returns_retained",
"os_returns_retained_on_non_zero",
"os_returns_retained_on_zero",
"overloadable",
"override",
"ownership_holds",
"ownership_returns",
"ownership_takes",
"packed",
"param_typestate",
"pascal",
"pass_dynamic_object_size",
"pass_object_size",
"patchable_function_entry",
"pcs",
"pointer_with_type_tag",
"preferred_name",
"preserve_access_index",
"preserve_all",
"preserve_most",
"private",
"property",
"pt_guarded_by",
"pt_guarded_var",
"pure",
"read_only",
"read_write",
"regcall",
"regparm",
"reinitializes",
"release_capability",
"release_generic_capability",
"release_handle",
"release_shared_capability",
"reqd_work_group_size",
"require_constant_initialization",
"requires_capability",
"requires_shared_capability",
"restrict",
"retain",
"return_typestate",
"returns_nonnull",
"returns_twice",
"scoped_lockable",
"sealed",
"section",
"selectany",
"sentinel",
"set_typestate",
"shared",
"shared_capability",
"shared_lock_function",
"shared_locks_required",
"shared_trylock_function",
"short_call",
"signal",
"speculative_load_hardening",
"standalone_debug",
"stdcall",
"suppress",
"swift_async",
"swift_async_context",
"swift_async_error",
"swift_async_name",
"swift_attr",
"swift_bridge",
"swift_bridged_typedef",
"swift_context",
"swift_error",
"swift_error_result",
"swift_indirect_result",
"swift_name",
"swift_newtype",
"swift_objc_members",
"swift_private",
"swift_wrapper",
"swiftasynccall",
"swiftcall",
"sycl_kernel",
"sysv_abi",
"target",
"test_typestate",
"thiscall",
"thread",
"tls_model",
"transparent_union",
"trivial_abi",
"try_acquire_capability",
"try_acquire_shared_capability",
"type_tag_for_datatype",
"type_visibility",
"unavailable",
"uninitialized",
"unlikely",
"unlock_function",
"unroll",
"unroll_and_jam",
"unused",
"use_handle",
"used",
"using_if_exists",
"uuid",
"vec_type_hint",
"vecreturn",
"vector_size",
"vectorcall",
"visibility",
"warn_unused",
"warn_unused_result",
"warning",
"weak",
"weak_import",
"weakref",
"work_group_size_hint",
"write_only",
"xray_always_instrument",
"xray_log_args",
"xray_never_instrument",
};
static const unsigned long NUM_KNOWN_ATTRIBUTES =
ABSL_ARRAYSIZE(KNOWN_ATTRIBUTES);
static const char* KNOWN_CPP_ATTRIBUTES[] = {
"carries_dependency", "clang::builtin_alias",
"clang::fallthrough", "clang::warn_unused_result",
"deprecated", "fallthrough",
"gsl::Owner", "gsl::Pointer",
"gsl::suppress", "likely",
"maybe_unused", "no_unique_address",
"nodiscard", "noreturn",
"unlikely",
};
static const unsigned long NUM_KNOWN_CPP_ATTRIBUTES =
ABSL_ARRAYSIZE(KNOWN_CPP_ATTRIBUTES);
static const char* KNOWN_DECLSPEC_ATTRIBUTES[] = {
"__constant__",
"__cudart_builtin__",
"__device__",
"__device_builtin__",
"__device_builtin_surface_type__",
"__device_builtin_texture_type__",
"__global__",
"__host__",
"__launch_bounds__",
"__managed__",
"__shared__",
"align",
"align_value",
"allocate",
"allocator",
"code_seg",
"cpu_dispatch",
"cpu_specific",
"deprecated",
"dllexport",
"dllimport",
"empty_bases",
"guard",
"layout_version",
"naked",
"noalias",
"noinline",
"noreturn",
"nothrow",
"novtable",
"property",
"restrict",
"selectany",
"thread",
"uuid",
};
static const unsigned long NUM_KNOWN_DECLSPEC_ATTRIBUTES =
ABSL_ARRAYSIZE(KNOWN_DECLSPEC_ATTRIBUTES);
static const char* KNOWN_BUILTINS[] = {
"NSLog",
"NSLogv",
"_Block_object_assign",
"_Block_object_dispose",
"_Exit",
"_InterlockedAnd",
"_InterlockedAnd16",
"_InterlockedAnd8",
"_InterlockedCompareExchange",
"_InterlockedCompareExchange16",
"_InterlockedCompareExchange64",
"_InterlockedCompareExchange8",
"_InterlockedCompareExchangePointer",
"_InterlockedCompareExchangePointer_nf",
"_InterlockedDecrement",
"_InterlockedDecrement16",
"_InterlockedExchange",
"_InterlockedExchange16",
"_InterlockedExchange8",
"_InterlockedExchangeAdd",
"_InterlockedExchangeAdd16",
"_InterlockedExchangeAdd8",
"_InterlockedExchangePointer",
"_InterlockedExchangeSub",
"_InterlockedExchangeSub16",
"_InterlockedExchangeSub8",
"_InterlockedIncrement",
"_InterlockedIncrement16",
"_InterlockedOr",
"_InterlockedOr16",
"_InterlockedOr8",
"_InterlockedXor",
"_InterlockedXor16",
"_InterlockedXor8",
"_ReturnAddress",
"__GetExceptionInfo",
"__abnormal_termination",
"__annotation",
"__arithmetic_fence",
"__assume",
"__atomic_add_fetch",
"__atomic_always_lock_free",
"__atomic_and_fetch",
"__atomic_clear",
"__atomic_compare_exchange",
"__atomic_compare_exchange_n",
"__atomic_exchange",
"__atomic_exchange_n",
"__atomic_fetch_add",
"__atomic_fetch_and",
"__atomic_fetch_max",
"__atomic_fetch_min",
"__atomic_fetch_nand",
"__atomic_fetch_or",
"__atomic_fetch_sub",
"__atomic_fetch_xor",
"__atomic_is_lock_free",
"__atomic_load",
"__atomic_load_n",
"__atomic_max_fetch",
"__atomic_min_fetch",
"__atomic_nand_fetch",
"__atomic_or_fetch",
"__atomic_signal_fence",
"__atomic_store",
"__atomic_store_n",
"__atomic_sub_fetch",
"__atomic_test_and_set",
"__atomic_thread_fence",
"__atomic_xor_fetch",
"__builtin___CFStringMakeConstantString",
"__builtin___NSStringMakeConstantString",
"__builtin___clear_cache",
"__builtin___fprintf_chk",
"__builtin___get_unsafe_stack_bottom",
"__builtin___get_unsafe_stack_ptr",
"__builtin___get_unsafe_stack_start",
"__builtin___get_unsafe_stack_top",
"__builtin___memccpy_chk",
"__builtin___memcpy_chk",
"__builtin___memmove_chk",
"__builtin___mempcpy_chk",
"__builtin___memset_chk",
"__builtin___printf_chk",
"__builtin___snprintf_chk",
"__builtin___sprintf_chk",
"__builtin___stpcpy_chk",
"__builtin___stpncpy_chk",
"__builtin___strcat_chk",
"__builtin___strcpy_chk",
"__builtin___strlcat_chk",
"__builtin___strlcpy_chk",
"__builtin___strncat_chk",
"__builtin___strncpy_chk",
"__builtin___vfprintf_chk",
"__builtin___vprintf_chk",
"__builtin___vsnprintf_chk",
"__builtin___vsprintf_chk",
"__builtin_abort",
"__builtin_acosf",
"__builtin_acosf128",
"__builtin_acoshf",
"__builtin_acoshf128",
"__builtin_acoshl",
"__builtin_acosl",
"__builtin_add_overflow",
"__builtin_addc",
"__builtin_addcb",
"__builtin_addcl",
"__builtin_addcll",
"__builtin_addcs",
"__builtin_addressof",
"__builtin_align_down",
"__builtin_align_up",
"__builtin_alloca",
"__builtin_alloca_with_align",
"__builtin_annotation",
"__builtin_asinf",
"__builtin_asinf128",
"__builtin_asinhf",
"__builtin_asinhf128",
"__builtin_asinhl",
"__builtin_asinl",
"__builtin_assume",
"__builtin_assume_aligned",
"__builtin_atan2f",
"__builtin_atan2f128",
"__builtin_atan2l",
"__builtin_atanf",
"__builtin_atanf128",
"__builtin_atanhf",
"__builtin_atanhf128",
"__builtin_atanhl",
"__builtin_atanl",
"__builtin_bcmp",
"__builtin_bcopy",
"__builtin_bitreverse16",
"__builtin_bitreverse32",
"__builtin_bitreverse64",
"__builtin_bitreverse8",
"__builtin_bswap16",
"__builtin_bswap32",
"__builtin_bswap64",
"__builtin_bzero",
"__builtin_cabs",
"__builtin_cabsf",
"__builtin_cabsl",
"__builtin_cacos",
"__builtin_cacosf",
"__builtin_cacosh",
"__builtin_cacoshf",
"__builtin_cacoshl",
"__builtin_cacosl",
"__builtin_call_with_static_chain",
"__builtin_calloc",
"__builtin_canonicalize",
"__builtin_canonicalizef",
"__builtin_canonicalizef16",
"__builtin_canonicalizel",
"__builtin_carg",
"__builtin_cargf",
"__builtin_cargl",
"__builtin_casin",
"__builtin_casinf",
"__builtin_casinh",
"__builtin_casinhf",
"__builtin_casinhl",
"__builtin_casinl",
"__builtin_catan",
"__builtin_catanf",
"__builtin_catanh",
"__builtin_catanhf",
"__builtin_catanhl",
"__builtin_catanl",
"__builtin_cbrtf",
"__builtin_cbrtf128",
"__builtin_cbrtl",
"__builtin_ccos",
"__builtin_ccosf",
"__builtin_ccosh",
"__builtin_ccoshf",
"__builtin_ccoshl",
"__builtin_ccosl",
"__builtin_ceilf",
"__builtin_ceilf128",
"__builtin_ceilf16",
"__builtin_ceill",
"__builtin_cexp",
"__builtin_cexpf",
"__builtin_cexpl",
"__builtin_char_memchr",
"__builtin_cimag",
"__builtin_cimagf",
"__builtin_cimagl",
"__builtin_classify_type",
"__builtin_clog",
"__builtin_clogf",
"__builtin_clogl",
"__builtin_clrsbll",
"__builtin_clzll",
"__builtin_complex",
"__builtin_conj",
"__builtin_conjf",
"__builtin_conjl",
"__builtin_constant_p",
"__builtin_convertvector",
"__builtin_copysign",
"__builtin_copysignf",
"__builtin_copysignf128",
"__builtin_copysignf16",
"__builtin_copysignl",
"__builtin_coro_alloc",
"__builtin_coro_begin",
"__builtin_coro_destroy",
"__builtin_coro_done",
"__builtin_coro_end",
"__builtin_coro_frame",
"__builtin_coro_free",
"__builtin_coro_id",
"__builtin_coro_noop",
"__builtin_coro_param",
"__builtin_coro_promise",
"__builtin_coro_resume",
"__builtin_coro_size",
"__builtin_coro_suspend",
"__builtin_cosf",
"__builtin_cosf128",
"__builtin_cosf16",
"__builtin_coshf",
"__builtin_coshf128",
"__builtin_coshl",
"__builtin_cosl",
"__builtin_cpow",
"__builtin_cpowf",
"__builtin_cpowl",
"__builtin_cproj",
"__builtin_cprojf",
"__builtin_cprojl",
"__builtin_creal",
"__builtin_crealf",
"__builtin_creall",
"__builtin_csin",
"__builtin_csinf",
"__builtin_csinh",
"__builtin_csinhf",
"__builtin_csinhl",
"__builtin_csinl",
"__builtin_csqrt",
"__builtin_csqrtf",
"__builtin_csqrtl",
"__builtin_ctan",
"__builtin_ctanf",
"__builtin_ctanh",
"__builtin_ctanhf",
"__builtin_ctanhl",
"__builtin_ctanl",
"__builtin_ctzll",
"__builtin_debugtrap",
"__builtin_dump_struct",
"__builtin_dwarf_cfa",
"__builtin_dwarf_sp_column",
"__builtin_dynamic_object_size",
"__builtin_eh_return",
"__builtin_eh_return_data_regno",
"__builtin_erfcf",
"__builtin_erfcf128",
"__builtin_erfcl",
"__builtin_erff",
"__builtin_erff128",
"__builtin_erfl",
"__builtin_exp2f",
"__builtin_exp2f128",
"__builtin_exp2f16",
"__builtin_exp2l",
"__builtin_expect",
"__builtin_expect_with_probability",
"__builtin_expf",
"__builtin_expf128",
"__builtin_expf16",
"__builtin_expl",
"__builtin_expm1f",
"__builtin_expm1f128",
"__builtin_expm1l",
"__builtin_extend_pointer",
"__builtin_extract_return_addr",
"__builtin_fabsf",
"__builtin_fabsf128",
"__builtin_fabsf16",
"__builtin_fabsl",
"__builtin_fdim",
"__builtin_fdimf",
"__builtin_fdimf128",
"__builtin_fdiml",
"__builtin_ffsll",
"__builtin_floorf",
"__builtin_floorf128",
"__builtin_floorf16",
"__builtin_floorl",
"__builtin_flt_rounds",
"__builtin_fma",
"__builtin_fmaf",
"__builtin_fmaf128",
"__builtin_fmaf16",
"__builtin_fmal",
"__builtin_fmax",
"__builtin_fmaxf",
"__builtin_fmaxf128",
"__builtin_fmaxf16",
"__builtin_fmaxl",
"__builtin_fmin",
"__builtin_fminf",
"__builtin_fminf128",
"__builtin_fminf16",
"__builtin_fminl",
"__builtin_fmodf",
"__builtin_fmodf128",
"__builtin_fmodf16",
"__builtin_fmodl",
"__builtin_fpclassify",
"__builtin_fprintf",
"__builtin_frame_address",
"__builtin_free",
"__builtin_frexpf",
"__builtin_frexpf128",
"__builtin_frexpl",
"__builtin_frob_return_addr",
"__builtin_get_device_side_mangled_name",
"__builtin_huge_val",
"__builtin_huge_valf",
"__builtin_huge_valf128",
"__builtin_huge_vall",
"__builtin_hypotf",
"__builtin_hypotf128",
"__builtin_hypotl",
"__builtin_ilogbf",
"__builtin_ilogbf128",
"__builtin_ilogbl",
"__builtin_index",
"__builtin_init_dwarf_reg_size_table",
"__builtin_is_aligned",
"__builtin_is_constant_evaluated",
"__builtin_isfinite",
"__builtin_isgreaterequal",
"__builtin_isinf",
"__builtin_isinf_sign",
"__builtin_isnan",
"__builtin_isnormal",
"__builtin_launder",
"__builtin_ldexpf",
"__builtin_ldexpf128",
"__builtin_ldexpl",
"__builtin_lgammaf",
"__builtin_lgammaf128",
"__builtin_lgammal",
"__builtin_llabs",
"__builtin_llrint",
"__builtin_llrintf",
"__builtin_llrintf128",
"__builtin_llrintl",
"__builtin_llroundf",
"__builtin_llroundf128",
"__builtin_llroundl",
"__builtin_load_half",
"__builtin_load_halff",
"__builtin_log10f",
"__builtin_log10f128",
"__builtin_log10f16",
"__builtin_log10l",
"__builtin_log1pf",
"__builtin_log1pf128",
"__builtin_log1pl",
"__builtin_log2",
"__builtin_log2f",
"__builtin_log2f128",
"__builtin_log2f16",
"__builtin_log2l",
"__builtin_logbf",
"__builtin_logbf128",
"__builtin_logbl",
"__builtin_logf",
"__builtin_logf128",
"__builtin_logf16",
"__builtin_logl",
"__builtin_longjmp",
"__builtin_lrintf",
"__builtin_lrintf128",
"__builtin_lrintl",
"__builtin_lroundf",
"__builtin_lroundf128",
"__builtin_lroundl",
"__builtin_malloc",
"__builtin_matrix_column_major_load",
"__builtin_matrix_column_major_store",
"__builtin_matrix_transpose",
"__builtin_memchr",
"__builtin_memcmp",
"__builtin_memcpy",
"__builtin_memcpy_inline",
"__builtin_memmove",
"__builtin_mempcpy",
"__builtin_memset",
"__builtin_modff",
"__builtin_modff128",
"__builtin_modfl",
"__builtin_ms_va_copy",
"__builtin_ms_va_end",
"__builtin_ms_va_start",
"__builtin_mul_overflow",
"__builtin_nan",
"__builtin_nanf",
"__builtin_nanf128",
"__builtin_nanl",
"__builtin_nans",
"__builtin_nansf",
"__builtin_nansf128",
"__builtin_nansl",
"__builtin_nearbyintf",
"__builtin_nearbyintf128",
"__builtin_nearbyintl",
"__builtin_nextafterf",
"__builtin_nextafterf128",
"__builtin_nextafterl",
"__builtin_nexttowardf",
"__builtin_nexttowardf128",
"__builtin_nexttowardl",
"__builtin_nontemporal_load",
"__builtin_nontemporal_store",
"__builtin_objc_memmove_collectable",
"__builtin_object_size",
"__builtin_operator_delete",
"__builtin_operator_new",
"__builtin_os_log_format",
"__builtin_os_log_format_buffer_size",
"__builtin_parityll",
"__builtin_popcountll",
"__builtin_powf",
"__builtin_powf128",
"__builtin_powf16",
"__builtin_powif",
"__builtin_powil",
"__builtin_powl",
"__builtin_prefetch",
"__builtin_preserve_access_index",
"__builtin_printf",
"__builtin_readcyclecounter",
"__builtin_realloc",
"__builtin_remainderf",
"__builtin_remainderf128",
"__builtin_remainderl",
"__builtin_remquof",
"__builtin_remquof128",
"__builtin_remquol",
"__builtin_return_address",
"__builtin_rindex",
"__builtin_rintf",
"__builtin_rintf128",
"__builtin_rintf16",
"__builtin_rintl",
"__builtin_rotateleft16",
"__builtin_rotateleft32",
"__builtin_rotateleft64",
"__builtin_rotateleft8",
"__builtin_rotateright16",
"__builtin_rotateright32",
"__builtin_rotateright64",
"__builtin_rotateright8",
"__builtin_round",
"__builtin_roundf",
"__builtin_roundf128",
"__builtin_roundf16",
"__builtin_roundl",
"__builtin_sadd_overflow",
"__builtin_saddl_overflow",
"__builtin_saddll_overflow",
"__builtin_scalblnf",
"__builtin_scalblnf128",
"__builtin_scalblnl",
"__builtin_scalbnf",
"__builtin_scalbnf128",
"__builtin_scalbnl",
"__builtin_setjmp",
"__builtin_shufflevector",
"__builtin_signbit",
"__builtin_signbitf",
"__builtin_signbitl",
"__builtin_sinf",
"__builtin_sinf128",
"__builtin_sinf16",
"__builtin_sinhf",
"__builtin_sinhf128",
"__builtin_sinhl",
"__builtin_sinl",
"__builtin_smul_overflow",
"__builtin_smull_overflow",
"__builtin_smulll_overflow",
"__builtin_snprintf",
"__builtin_sprintf",
"__builtin_sqrtf",
"__builtin_sqrtf128",
"__builtin_sqrtf16",
"__builtin_sqrtl",
"__builtin_ssub_overflow",
"__builtin_ssubl_overflow",
"__builtin_ssubll_overflow",
"__builtin_stdarg_start",
"__builtin_store_half",
"__builtin_store_halff",
"__builtin_stpcpy",
"__builtin_stpncpy",
"__builtin_strcasecmp",
"__builtin_strcat",
"__builtin_strchr",
"__builtin_strcmp",
"__builtin_strcpy",
"__builtin_strcspn",
"__builtin_strdup",
"__builtin_strlen",
"__builtin_strncasecmp",
"__builtin_strncat",
"__builtin_strncmp",
"__builtin_strncpy",
"__builtin_strndup",
"__builtin_strpbrk",
"__builtin_strrchr",
"__builtin_strspn",
"__builtin_strstr",
"__builtin_sub_overflow",
"__builtin_subc",
"__builtin_subcb",
"__builtin_subcl",
"__builtin_subcll",
"__builtin_subcs",
"__builtin_tanf",
"__builtin_tanf128",
"__builtin_tanhf",
"__builtin_tanhf128",
"__builtin_tanhl",
"__builtin_tanl",
"__builtin_tgammaf",
"__builtin_tgammaf128",
"__builtin_tgammal",
"__builtin_thread_pointer",
"__builtin_trap",
"__builtin_truncf",
"__builtin_truncf128",
"__builtin_truncf16",
"__builtin_truncl",
"__builtin_uadd_overflow",
"__builtin_uaddl_overflow",
"__builtin_uaddll_overflow",
"__builtin_umul_overflow",
"__builtin_umull_overflow",
"__builtin_umulll_overflow",
"__builtin_unpredictable",
"__builtin_unreachable",
"__builtin_unwind_init",
"__builtin_usub_overflow",
"__builtin_usubl_overflow",
"__builtin_usubll_overflow",
"__builtin_va_copy",
"__builtin_va_end",
"__builtin_va_start",
"__builtin_vsnprintf",
"__builtin_vsprintf",
"__builtin_wcschr",
"__builtin_wcscmp",
"__builtin_wcslen",
"__builtin_wcsncmp",
"__builtin_wmemchr",
"__builtin_wmemcmp",
"__builtin_wmemcpy",
"__builtin_wmemmove",
"__c11_atomic_compare_exchange_strong",
"__c11_atomic_compare_exchange_weak",
"__c11_atomic_exchange",
"__c11_atomic_fetch_add",
"__c11_atomic_fetch_and",
"__c11_atomic_fetch_max",
"__c11_atomic_fetch_min",
"__c11_atomic_fetch_or",
"__c11_atomic_fetch_sub",
"__c11_atomic_fetch_xor",
"__c11_atomic_init",
"__c11_atomic_is_lock_free",
"__c11_atomic_load",
"__c11_atomic_signal_fence",
"__c11_atomic_store",
"__c11_atomic_thread_fence",
"__cospi",
"__cospif",
"__debugbreak",
"__exception_code",
"__exception_info",
"__exp10",
"__exp10f",
"__fastfail",
"__finite",
"__finitef",
"__finitel",
"__iso_volatile_load16",
"__iso_volatile_load32",
"__iso_volatile_load64",
"__iso_volatile_load8",
"__iso_volatile_store16",
"__iso_volatile_store32",
"__iso_volatile_store64",
"__iso_volatile_store8",
"__lzcnt",
"__lzcnt16",
"__lzcnt64",
"__noop",
"__opencl_atomic_compare_exchange_strong",
"__opencl_atomic_compare_exchange_weak",
"__opencl_atomic_exchange",
"__opencl_atomic_fetch_add",
"__opencl_atomic_fetch_and",
"__opencl_atomic_fetch_max",
"__opencl_atomic_fetch_min",
"__opencl_atomic_fetch_or",
"__opencl_atomic_fetch_sub",
"__opencl_atomic_fetch_xor",
"__opencl_atomic_init",
"__opencl_atomic_load",
"__opencl_atomic_store",
"__popcnt",
"__popcnt16",
"__popcnt64",
"__sigsetjmp",
"__sinpi",
"__sinpif",
"__sync_add_and_fetch",
"__sync_add_and_fetch_1",
"__sync_add_and_fetch_16",
"__sync_add_and_fetch_2",
"__sync_add_and_fetch_4",
"__sync_add_and_fetch_8",
"__sync_and_and_fetch",
"__sync_and_and_fetch_1",
"__sync_and_and_fetch_16",
"__sync_and_and_fetch_2",
"__sync_and_and_fetch_4",
"__sync_and_and_fetch_8",
"__sync_bool_compare_and_swap",
"__sync_bool_compare_and_swap_1",
"__sync_bool_compare_and_swap_16",
"__sync_bool_compare_and_swap_2",
"__sync_bool_compare_and_swap_4",
"__sync_bool_compare_and_swap_8",
"__sync_fetch_and_add",
"__sync_fetch_and_add_1",
"__sync_fetch_and_add_16",
"__sync_fetch_and_add_2",
"__sync_fetch_and_add_4",
"__sync_fetch_and_add_8",
"__sync_fetch_and_and",
"__sync_fetch_and_and_1",
"__sync_fetch_and_and_16",
"__sync_fetch_and_and_2",
"__sync_fetch_and_and_4",
"__sync_fetch_and_and_8",
"__sync_fetch_and_max",
"__sync_fetch_and_min",
"__sync_fetch_and_nand",
"__sync_fetch_and_nand_1",
"__sync_fetch_and_nand_16",
"__sync_fetch_and_nand_2",
"__sync_fetch_and_nand_4",
"__sync_fetch_and_nand_8",
"__sync_fetch_and_or",
"__sync_fetch_and_or_1",
"__sync_fetch_and_or_16",
"__sync_fetch_and_or_2",
"__sync_fetch_and_or_4",
"__sync_fetch_and_or_8",
"__sync_fetch_and_sub",
"__sync_fetch_and_sub_1",
"__sync_fetch_and_sub_16",
"__sync_fetch_and_sub_2",
"__sync_fetch_and_sub_4",
"__sync_fetch_and_sub_8",
"__sync_fetch_and_umax",
"__sync_fetch_and_umin",
"__sync_fetch_and_xor",
"__sync_fetch_and_xor_1",
"__sync_fetch_and_xor_16",
"__sync_fetch_and_xor_2",
"__sync_fetch_and_xor_4",
"__sync_fetch_and_xor_8",
"__sync_lock_release",
"__sync_lock_release_1",
"__sync_lock_release_16",
"__sync_lock_release_2",
"__sync_lock_release_4",
"__sync_lock_release_8",
"__sync_lock_test_and_set",
"__sync_lock_test_and_set_1",
"__sync_lock_test_and_set_16",
"__sync_lock_test_and_set_2",
"__sync_lock_test_and_set_4",
"__sync_lock_test_and_set_8",
"__sync_nand_and_fetch",
"__sync_nand_and_fetch_1",
"__sync_nand_and_fetch_16",
"__sync_nand_and_fetch_2",
"__sync_nand_and_fetch_4",
"__sync_nand_and_fetch_8",
"__sync_or_and_fetch",
"__sync_or_and_fetch_1",
"__sync_or_and_fetch_16",
"__sync_or_and_fetch_2",
"__sync_or_and_fetch_4",
"__sync_or_and_fetch_8",
"__sync_sub_and_fetch",
"__sync_sub_and_fetch_1",
"__sync_sub_and_fetch_16",
"__sync_sub_and_fetch_2",
"__sync_sub_and_fetch_4",
"__sync_sub_and_fetch_8",
"__sync_swap",
"__sync_swap_1",
"__sync_swap_16",
"__sync_swap_2",
"__sync_swap_4",
"__sync_swap_8",
"__sync_synchronize",
"__sync_val_compare_and_swap",
"__sync_val_compare_and_swap_1",
"__sync_val_compare_and_swap_16",
"__sync_val_compare_and_swap_2",
"__sync_val_compare_and_swap_4",
"__sync_val_compare_and_swap_8",
"__sync_xor_and_fetch",
"__sync_xor_and_fetch_1",
"__sync_xor_and_fetch_16",
"__sync_xor_and_fetch_2",
"__sync_xor_and_fetch_4",
"__sync_xor_and_fetch_8",
"__tanpi",
"__tanpif",
"__va_start",
"__warn_memset_zero_len",
"__xray_customevent",
"__xray_typedevent",
"_abnormal_termination",
"_alloca",
"_bittest",
"_bittest64",
"_bittestandcomplement",
"_bittestandcomplement64",
"_bittestandreset",
"_bittestandreset64",
"_bittestandset",
"_bittestandset64",
"_byteswap_uint64",
"_byteswap_ulong",
"_byteswap_ushort",
"_exception_code",
"_exception_info",
"_exit",
"_interlockedbittestandreset",
"_interlockedbittestandreset64",
"_interlockedbittestandreset_acq",
"_interlockedbittestandreset_nf",
"_interlockedbittestandreset_rel",
"_interlockedbittestandset",
"_interlockedbittestandset64",
"_interlockedbittestandset_acq",
"_interlockedbittestandset_nf",
"_interlockedbittestandset_rel",
"_longjmp",
"_lrotl",
"_lrotr",
"_rotl",
"_rotl16",
"_rotl64",
"_rotl8",
"_rotr",
"_rotr16",
"_rotr64",
"_rotr8",
"_setjmp",
"_setjmpex",
"abort",
"abs",
"acos",
"acosf",
"acosh",
"acoshf",
"acoshl",
"acosl",
"aligned_alloc",
"alloca",
"asin",
"asinf",
"asinh",
"asinhf",
"asinhl",
"asinl",
"atan",
"atan2",
"atan2f",
"atan2l",
"atanf",
"atanh",
"atanhf",
"atanhl",
"atanl",
"bcmp",
"bzero",
"cabs",
"cabsf",
"cabsl",
"cacos",
"cacosf",
"cacosh",
"cacoshf",
"cacoshl",
"cacosl",
"calloc",
"carg",
"cargf",
"cargl",
"casin",
"casinf",
"casinh",
"casinhf",
"casinhl",
"casinl",
"catan",
"catanf",
"catanh",
"catanhf",
"catanhl",
"catanl",
"cbrt",
"cbrtf",
"cbrtl",
"ccos",
"ccosf",
"ccosh",
"ccoshf",
"ccoshl",
"ccosl",
"ceil",
"ceilf",
"ceill",
"cexp",
"cexpf",
"cexpl",
"cimag",
"cimagf",
"cimagl",
"clog",
"clogf",
"clogl",
"commit_read_pipe",
"commit_write_pipe",
"conj",
"conjf",
"conjl",
"copysign",
"copysignf",
"copysignl",
"cos",
"cosf",
"cosh",
"coshf",
"coshl",
"cosl",
"cpow",
"cpowf",
"cpowl",
"cproj",
"cprojf",
"cprojl",
"creal",
"crealf",
"creall",
"csin",
"csinf",
"csinh",
"csinhf",
"csinhl",
"csinl",
"csqrt",
"csqrtf",
"csqrtl",
"ctan",
"ctanf",
"ctanh",
"ctanhf",
"ctanhl",
"ctanl",
"enqueue_kernel",
"erf",
"erfc",
"erfcf",
"erfcl",
"erff",
"erfl",
"exit",
"exp",
"exp2",
"exp2f",
"exp2l",
"expf",
"expl",
"expm1",
"expm1f",
"expm1l",
"fabs",
"fabsf",
"fabsl",
"fdim",
"fdimf",
"fdiml",
"finite",
"finitef",
"finitel",
"floor",
"floorf",
"floorl",
"fma",
"fmaf",
"fmal",
"fmax",
"fmaxf",
"fmaxl",
"fmin",
"fminf",
"fminl",
"fmod",
"fmodf",
"fmodl",
"fopen",
"fprintf",
"fread",
"free",
"frexp",
"frexpf",
"frexpl",
"fscanf",
"fwrite",
"get_kernel_max_sub_group_size_for_ndrange",
"get_kernel_preferred_work_group_size_multiple",
"get_kernel_sub_group_count_for_ndrange",
"get_kernel_work_group_size",
"get_pipe_max_packets",
"get_pipe_num_packets",
"getcontext",
"hypot",
"hypotf",
"hypotl",
"ilogb",
"ilogbf",
"ilogbl",
"index",
"isalnum",
"isalpha",
"isblank",
"iscntrl",
"isdigit",
"isgraph",
"islower",
"isprint",
"ispunct",
"isspace",
"isupper",
"isxdigit",
"labs",
"ldexp",
"ldexpf",
"ldexpl",
"lgamma",
"lgammaf",
"lgammal",
"llabs",
"llrint",
"llrintf",
"llrintl",
"llround",
"llroundf",
"llroundl",
"log",
"log10",
"log10f",
"log10l",
"log1p",
"log1pf",
"log1pl",
"log2",
"log2f",
"log2l",
"logb",
"logbf",
"logbl",
"logf",
"logl",
"longjmp",
"lrint",
"lrintf",
"lrintl",
"lround",
"lroundf",
"lroundl",
"malloc",
"memalign",
"memccpy",
"memchr",
"memcmp",
"memcpy",
"memmove",
"mempcpy",
"memset",
"modf",
"modff",
"modfl",
"nan",
"nanf",
"nanl",
"nearbyint",
"nearbyintf",
"nearbyintl",
"nextafter",
"nextafterf",
"nextafterl",
"nexttoward",
"nexttowardf",
"nexttowardl",
"objc_assign_global",
"objc_assign_ivar",
"objc_assign_strongCast",
"objc_assign_weak",
"objc_enumerationMutation",
"objc_exception_extract",
"objc_exception_match",
"objc_exception_throw",
"objc_exception_try_enter",
"objc_exception_try_exit",
"objc_getClass",
"objc_getMetaClass",
"objc_msgSend",
"objc_msgSendSuper",
"objc_msgSendSuper_stret",
"objc_msgSend_fp2ret",
"objc_msgSend_fpret",
"objc_msgSend_stret",
"objc_read_weak",
"objc_sync_enter",
"objc_sync_exit",
"pow",
"powf",
"powl",
"printf",
"pthread_create",
"read_pipe",
"realloc",
"remainder",
"remainderf",
"remainderl",
"remquo",
"remquof",
"remquol",
"reserve_read_pipe",
"reserve_write_pipe",
"rindex",
"rint",
"rintf",
"rintl",
"round",
"roundf",
"roundl",
"savectx",
"scalbln",
"scalblnf",
"scalblnl",
"scalbn",
"scalbnf",
"scalbnl",
"scanf",
"setjmp",
"siglongjmp",
"sigsetjmp",
"sin",
"sinf",
"sinh",
"sinhf",
"sinhl",
"sinl",
"snprintf",
"sprintf",
"sqrt",
"sqrtf",
"sqrtl",
"sscanf",
"stpcpy",
"stpncpy",
"strcasecmp",
"strcat",
"strchr",
"strcmp",
"strcpy",
"strcspn",
"strdup",
"strerror",
"strlcat",
"strlcpy",
"strlen",
"strncasecmp",
"strncat",
"strncmp",
"strncpy",
"strndup",
"strpbrk",
"strrchr",
"strspn",
"strstr",
"strtod",
"strtof",
"strtok",
"strtol",
"strtold",
"strtoll",
"strtoul",
"strtoull",
"strxfrm",
"sub_group_commit_read_pipe",
"sub_group_commit_write_pipe",
"sub_group_reserve_read_pipe",
"sub_group_reserve_write_pipe",
"tan",
"tanf",
"tanh",
"tanhf",
"tanhl",
"tanl",
"tgamma",
"tgammaf",
"tgammal",
"to_global",
"to_local",
"to_private",
"tolower",
"toupper",
"trunc",
"truncf",
"truncl",
"va_copy",
"va_end",
"va_start",
"vfork",
"vfprintf",
"vfscanf",
"vprintf",
"vscanf",
"vsnprintf",
"vsprintf",
"vsscanf",
"wcschr",
"wcscmp",
"wcslen",
"wcsncmp",
"wmemchr",
"wmemcmp",
"wmemcpy",
"wmemmove",
"work_group_commit_read_pipe",
"work_group_commit_write_pipe",
"work_group_reserve_read_pipe",
"work_group_reserve_write_pipe",
"write_pipe",
};
static const unsigned long NUM_KNOWN_BUILTINS = ABSL_ARRAYSIZE(KNOWN_BUILTINS);
static const char* KNOWN_WARNINGS[] = {
"-W#pragma-messages",
"-W#warnings",
"-WCFString-literal",
"-WCL4",
"-WIndependentClass-attribute",
"-WNSObject-attribute",
"-Wabi",
"-Wabsolute-value",
"-Wabstract-final-class",
"-Wabstract-vbase-init",
"-Waddress",
"-Waddress-of-packed-member",
"-Waddress-of-temporary",
"-Waggregate-return",
"-Waix-compat",
"-Walign-mismatch",
"-Wall",
"-Walloca",
"-Walloca-with-align-alignof",
"-Wambiguous-delete",
"-Wambiguous-ellipsis",
"-Wambiguous-macro",
"-Wambiguous-member-template",
"-Wambiguous-reversed-operator",
"-Wanalyzer-incompatible-plugin",
"-Wanon-enum-enum-conversion",
"-Wanonymous-pack-parens",
"-Warc",
"-Warc-bridge-casts-disallowed-in-nonarc",
"-Warc-maybe-repeated-use-of-weak",
"-Warc-non-pod-memaccess",
"-Warc-performSelector-leaks",
"-Warc-repeated-use-of-weak",
"-Warc-retain-cycles",
"-Warc-unsafe-retained-assign",
"-Wargument-outside-range",
"-Wargument-undefined-behaviour",
"-Warray-bounds",
"-Warray-bounds-pointer-arithmetic",
"-Wasm",
"-Wasm-operand-widths",
"-Wassign-enum",
"-Wassume",
"-Wat-protocol",
"-Watimport-in-framework-header",
"-Watomic-alignment",
"-Watomic-implicit-seq-cst",
"-Watomic-memory-ordering",
"-Watomic-properties",
"-Watomic-property-with-user-defined-accessor",
"-Wattribute-packed-for-bitfield",
"-Wattribute-warning",
"-Wattributes",
"-Wauto-disable-vptr-sanitizer",
"-Wauto-import",
"-Wauto-storage-class",
"-Wauto-var-id",
"-Wavailability",
"-Wavr-rtlib-linking-quirks",
"-Wbackend-plugin",
"-Wbackslash-newline-escape",
"-Wbad-function-cast",
"-Wbinary-literal",
"-Wbind-to-temporary-copy",
"-Wbinding-in-condition",
"-Wbitfield-constant-conversion",
"-Wbitfield-enum-conversion",
"-Wbitfield-width",
"-Wbitwise-conditional-parentheses",
"-Wbitwise-instead-of-logical",
"-Wbitwise-op-parentheses",
"-Wblock-capture-autoreleasing",
"-Wbool-conversion",
"-Wbool-conversions",
"-Wbool-operation",
"-Wbraced-scalar-init",
"-Wbridge-cast",
"-Wbuiltin-assume-aligned-alignment",
"-Wbuiltin-macro-redefined",
"-Wbuiltin-memcpy-chk-size",
"-Wbuiltin-requires-header",
"-Wc++-compat",
"-Wc++0x-compat",
"-Wc++0x-extensions",
"-Wc++0x-narrowing",
"-Wc++11-compat",
"-Wc++11-compat-deprecated-writable-strings",
"-Wc++11-compat-pedantic",
"-Wc++11-compat-reserved-user-defined-literal",
"-Wc++11-extensions",
"-Wc++11-extra-semi",
"-Wc++11-inline-namespace",
"-Wc++11-long-long",
"-Wc++11-narrowing",
"-Wc++14-binary-literal",
"-Wc++14-compat",
"-Wc++14-compat-pedantic",
"-Wc++14-extensions",
"-Wc++17-compat",
"-Wc++17-compat-mangling",
"-Wc++17-compat-pedantic",
"-Wc++17-extensions",
"-Wc++1y-extensions",
"-Wc++1z-compat",
"-Wc++1z-compat-mangling",
"-Wc++1z-extensions",
"-Wc++20-compat",
"-Wc++20-compat-pedantic",
"-Wc++20-designator",
"-Wc++20-extensions",
"-Wc++2a-compat",
"-Wc++2a-compat-pedantic",
"-Wc++2a-extensions",
"-Wc++2b-extensions",
"-Wc++98-c++11-c++14-c++17-compat",
"-Wc++98-c++11-c++14-c++17-compat-pedantic",
"-Wc++98-c++11-c++14-compat",
"-Wc++98-c++11-c++14-compat-pedantic",
"-Wc++98-c++11-compat",
"-Wc++98-c++11-compat-binary-literal",
"-Wc++98-c++11-compat-pedantic",
"-Wc++98-compat",
"-Wc++98-compat-bind-to-temporary-copy",
"-Wc++98-compat-extra-semi",
"-Wc++98-compat-local-type-template-args",
"-Wc++98-compat-pedantic",
"-Wc++98-compat-unnamed-type-template-args",
"-Wc11-extensions",
"-Wc2x-extensions",
"-Wc99-compat",
"-Wc99-designator",
"-Wc99-extensions",
"-Wcall-to-pure-virtual-from-ctor-dtor",
"-Wcalled-once-parameter",
"-Wcast-align",
"-Wcast-calling-convention",
"-Wcast-function-type",
"-Wcast-of-sel-type",
"-Wcast-qual",
"-Wcast-qual-unrelated",
"-Wchar-align",
"-Wchar-subscripts",
"-Wclang-cl-pch",
"-Wclass-conversion",
"-Wclass-varargs",
"-Wcmse-union-leak",
"-Wcomma",
"-Wcomment",
"-Wcomments",
"-Wcompare-distinct-pointer-types",
"-Wcompletion-handler",
"-Wcomplex-component-init",
"-Wcompound-token-split",
"-Wcompound-token-split-by-macro",
"-Wcompound-token-split-by-space",
"-Wconcepts-ts-compat",
"-Wconditional-type-mismatch",
"-Wconditional-uninitialized",
"-Wconfig-macros",
"-Wconstant-conversion",
"-Wconstant-evaluated",
"-Wconstant-logical-operand",
"-Wconstexpr-not-const",
"-Wconsumed",
"-Wconversion",
"-Wconversion-null",
"-Wcoroutine",
"-Wcoroutine-missing-unhandled-exception",
"-Wcovered-switch-default",
"-Wcpp",
"-Wcstring-format-directive",
"-Wctad-maybe-unsupported",
"-Wctor-dtor-privacy",
"-Wctu",
"-Wcuda-compat",
"-Wcustom-atomic-properties",
"-Wcxx-attribute-extension",
"-Wdangling",
"-Wdangling-else",
"-Wdangling-field",
"-Wdangling-gsl",
"-Wdangling-initializer-list",
"-Wdarwin-sdk-settings",
"-Wdate-time",
"-Wdealloc-in-category",
"-Wdebug-compression-unavailable",
"-Wdeclaration-after-statement",
"-Wdefaulted-function-deleted",
"-Wdelegating-ctor-cycles",
"-Wdelete-abstract-non-virtual-dtor",
"-Wdelete-incomplete",
"-Wdelete-non-abstract-non-virtual-dtor",
"-Wdelete-non-virtual-dtor",
"-Wdelimited-escape-sequence-extension",
"-Wdeprecated",
"-Wdeprecated-altivec-src-compat",
"-Wdeprecated-anon-enum-enum-conversion",
"-Wdeprecated-array-compare",
"-Wdeprecated-attributes",
"-Wdeprecated-comma-subscript",
"-Wdeprecated-copy",
"-Wdeprecated-copy-dtor",
"-Wdeprecated-copy-with-dtor",
"-Wdeprecated-copy-with-user-provided-copy",
"-Wdeprecated-copy-with-user-provided-dtor",
"-Wdeprecated-declarations",
"-Wdeprecated-dynamic-exception-spec",
"-Wdeprecated-enum-compare",
"-Wdeprecated-enum-compare-conditional",
"-Wdeprecated-enum-enum-conversion",
"-Wdeprecated-enum-float-conversion",
"-Wdeprecated-implementations",
"-Wdeprecated-increment-bool",
"-Wdeprecated-objc-isa-usage",
"-Wdeprecated-objc-pointer-introspection",
"-Wdeprecated-objc-pointer-introspection-performSelector",
"-Wdeprecated-pragma",
"-Wdeprecated-register",
"-Wdeprecated-this-capture",
"-Wdeprecated-volatile",
"-Wdeprecated-writable-strings",
"-Wdirect-ivar-access",
"-Wdisabled-macro-expansion",
"-Wdisabled-optimization",
"-Wdiscard-qual",
"-Wdistributed-object-modifiers",
"-Wdiv-by-zero",
"-Wdivision-by-zero",
"-Wdll-attribute-on-redeclaration",
"-Wdllexport-explicit-instantiation-decl",
"-Wdllimport-static-field-def",
"-Wdocumentation",
"-Wdocumentation-deprecated-sync",
"-Wdocumentation-html",
"-Wdocumentation-pedantic",
"-Wdocumentation-unknown-command",
"-Wdollar-in-identifier-extension",
"-Wdouble-promotion",
"-Wdtor-name",
"-Wdtor-typedef",
"-Wduplicate-decl-specifier",
"-Wduplicate-enum",
"-Wduplicate-method-arg",
"-Wduplicate-method-match",
"-Wduplicate-protocol",
"-Wdynamic-class-memaccess",
"-Wdynamic-exception-spec",
"-Weffc++",
"-Welaborated-enum-base",
"-Welaborated-enum-class",
"-Wembedded-directive",
"-Wempty-body",
"-Wempty-decomposition",
"-Wempty-init-stmt",
"-Wempty-translation-unit",
"-Wencode-type",
"-Wendif-labels",
"-Wenum-compare",
"-Wenum-compare-conditional",
"-Wenum-compare-switch",
"-Wenum-conversion",
"-Wenum-enum-conversion",
"-Wenum-float-conversion",
"-Wenum-too-large",
"-Wexceptions",
"-Wexcess-initializers",
"-Wexit-time-destructors",
"-Wexpansion-to-defined",
"-Wexplicit-initialize-call",
"-Wexplicit-ownership-type",
"-Wexport-unnamed",
"-Wexport-using-directive",
"-Wextern-c-compat",
"-Wextern-initializer",
"-Wextra",
"-Wextra-qualification",
"-Wextra-semi",
"-Wextra-semi-stmt",
"-Wextra-tokens",
"-Wfinal-dtor-non-final-class",
"-Wfinal-macro",
"-Wfixed-enum-extension",
"-Wfixed-point-overflow",
"-Wflag-enum",
"-Wflexible-array-extensions",
"-Wfloat-conversion",
"-Wfloat-equal",
"-Wfloat-overflow-conversion",
"-Wfloat-zero-conversion",
"-Wfor-loop-analysis",
"-Wformat",
"-Wformat-extra-args",
"-Wformat-insufficient-args",
"-Wformat-invalid-specifier",
"-Wformat-non-iso",
"-Wformat-nonliteral",
"-Wformat-pedantic",
"-Wformat-security",
"-Wformat-type-confusion",
"-Wformat-y2k",
"-Wformat-zero-length",
"-Wformat=2",
"-Wfortify-source",
"-Wfour-char-constants",
"-Wframe-address",
"-Wframe-larger-than",
"-Wframe-larger-than=",
"-Wframework-include-private-from-public",
"-Wfree-nonheap-object",
"-Wfunction-def-in-objc-container",
"-Wfunction-multiversion",
"-Wfuse-ld-path",
"-Wfuture-compat",
"-Wgcc-compat",
"-Wglobal-constructors",
"-Wglobal-isel",
"-Wgnu",
"-Wgnu-alignof-expression",
"-Wgnu-anonymous-struct",
"-Wgnu-array-member-paren-init",
"-Wgnu-auto-type",
"-Wgnu-binary-literal",
"-Wgnu-case-range",
"-Wgnu-complex-integer",
"-Wgnu-compound-literal-initializer",
"-Wgnu-conditional-omitted-operand",
"-Wgnu-designator",
"-Wgnu-empty-initializer",
"-Wgnu-empty-struct",
"-Wgnu-flexible-array-initializer",
"-Wgnu-flexible-array-union-member",
"-Wgnu-folding-constant",
"-Wgnu-imaginary-constant",
"-Wgnu-include-next",
"-Wgnu-inline-cpp-without-extern",
"-Wgnu-label-as-value",
"-Wgnu-redeclared-enum",
"-Wgnu-statement-expression",
"-Wgnu-static-float-init",
"-Wgnu-string-literal-operator-template",
"-Wgnu-union-cast",
"-Wgnu-variable-sized-type-not-at-end",
"-Wgnu-zero-line-directive",
"-Wgnu-zero-variadic-macro-arguments",
"-Wgpu-maybe-wrong-side",
"-Wheader-guard",
"-Wheader-hygiene",
"-Whip-only",
"-Widiomatic-parentheses",
"-Wignored-attributes",
"-Wignored-availability-without-sdk-settings",
"-Wignored-optimization-argument",
"-Wignored-pragma-intrinsic",
"-Wignored-pragma-optimize",
"-Wignored-pragmas",
"-Wignored-qualifiers",
"-Wignored-reference-qualifiers",
"-Wimplicit",
"-Wimplicit-atomic-properties",
"-Wimplicit-const-int-float-conversion",
"-Wimplicit-conversion-floating-point-to-bool",
"-Wimplicit-exception-spec-mismatch",
"-Wimplicit-fallthrough",
"-Wimplicit-fallthrough-per-function",
"-Wimplicit-fixed-point-conversion",
"-Wimplicit-float-conversion",
"-Wimplicit-function-declaration",
"-Wimplicit-int",
"-Wimplicit-int-conversion",
"-Wimplicit-int-float-conversion",
"-Wimplicit-retain-self",
"-Wimplicitly-unsigned-literal",
"-Wimport",
"-Wimport-preprocessor-directive-pedantic",
"-Winaccessible-base",
"-Winclude-next-absolute-path",
"-Winclude-next-outside-header",
"-Wincompatible-exception-spec",
"-Wincompatible-function-pointer-types",
"-Wincompatible-library-redeclaration",
"-Wincompatible-ms-struct",
"-Wincompatible-pointer-types",
"-Wincompatible-pointer-types-discards-qualifiers",
"-Wincompatible-property-type",
"-Wincompatible-sysroot",
"-Wincomplete-framework-module-declaration",
"-Wincomplete-implementation",
"-Wincomplete-module",
"-Wincomplete-setjmp-declaration",
"-Wincomplete-umbrella",
"-Winconsistent-dllimport",
"-Winconsistent-missing-destructor-override",
"-Winconsistent-missing-override",
"-Wincrement-bool",
"-Winfinite-recursion",
"-Winit-self",
"-Winitializer-overrides",
"-Winjected-class-name",
"-Winline",
"-Winline-asm",
"-Winline-namespace-reopened-noninline",
"-Winline-new-delete",
"-Winstantiation-after-specialization",
"-Wint-conversion",
"-Wint-conversions",
"-Wint-in-bool-context",
"-Wint-to-pointer-cast",
"-Wint-to-void-pointer-cast",
"-Winteger-overflow",
"-Winterrupt-service-routine",
"-Winvalid-command-line-argument",
"-Winvalid-constexpr",
"-Winvalid-iboutlet",
"-Winvalid-initializer-from-system-header",
"-Winvalid-ios-deployment-target",
"-Winvalid-no-builtin-names",
"-Winvalid-noreturn",
"-Winvalid-offsetof",
"-Winvalid-or-nonexistent-directory",
"-Winvalid-partial-specialization",
"-Winvalid-pch",
"-Winvalid-pp-token",
"-Winvalid-source-encoding",
"-Winvalid-token-paste",
"-Wjump-seh-finally",
"-Wkeyword-compat",
"-Wkeyword-macro",
"-Wknr-promoted-parameter",
"-Wlanguage-extension-token",
"-Wlarge-by-value-copy",
"-Wliblto",
"-Wlinker-warnings",
"-Wliteral-conversion",
"-Wliteral-range",
"-Wlocal-type-template-args",
"-Wlogical-not-parentheses",
"-Wlogical-op-parentheses",
"-Wlong-long",
"-Wloop-analysis",
"-Wmacro-redefined",
"-Wmain",
"-Wmain-return-type",
"-Wmalformed-warning-check",
"-Wmany-braces-around-scalar-init",
"-Wmax-tokens",
"-Wmax-unsigned-zero",
"-Wmemset-transposed-args",
"-Wmemsize-comparison",
"-Wmethod-signatures",
"-Wmicrosoft",
"-Wmicrosoft-abstract",
"-Wmicrosoft-anon-tag",
"-Wmicrosoft-cast",
"-Wmicrosoft-charize",
"-Wmicrosoft-comment-paste",
"-Wmicrosoft-const-init",
"-Wmicrosoft-cpp-macro",
"-Wmicrosoft-default-arg-redefinition",
"-Wmicrosoft-drectve-section",
"-Wmicrosoft-end-of-file",
"-Wmicrosoft-enum-forward-reference",
"-Wmicrosoft-enum-value",
"-Wmicrosoft-exception-spec",
"-Wmicrosoft-exists",
"-Wmicrosoft-extra-qualification",
"-Wmicrosoft-fixed-enum",
"-Wmicrosoft-flexible-array",
"-Wmicrosoft-goto",
"-Wmicrosoft-inaccessible-base",
"-Wmicrosoft-include",
"-Wmicrosoft-mutable-reference",
"-Wmicrosoft-pure-definition",
"-Wmicrosoft-redeclare-static",
"-Wmicrosoft-sealed",
"-Wmicrosoft-static-assert",
"-Wmicrosoft-template",
"-Wmicrosoft-template-shadow",
"-Wmicrosoft-unqualified-friend",
"-Wmicrosoft-using-decl",
"-Wmicrosoft-void-pseudo-dtor",
"-Wmisleading-indentation",
"-Wmismatched-new-delete",
"-Wmismatched-parameter-types",
"-Wmismatched-return-types",
"-Wmismatched-tags",
"-Wmissing-braces",
"-Wmissing-constinit",
"-Wmissing-declarations",
"-Wmissing-exception-spec",
"-Wmissing-field-initializers",
"-Wmissing-format-attribute",
"-Wmissing-include-dirs",
"-Wmissing-method-return-type",
"-Wmissing-noescape",
"-Wmissing-noreturn",
"-Wmissing-prototype-for-cc",
"-Wmissing-prototypes",
"-Wmissing-selector-name",
"-Wmissing-sysroot",
"-Wmissing-variable-declarations",
"-Wmisspelled-assumption",
"-Wmodule-build",
"-Wmodule-conflict",
"-Wmodule-file-config-mismatch",
"-Wmodule-file-extension",
"-Wmodule-import",
"-Wmodule-import-in-extern-c",
"-Wmodule-lock",
"-Wmodules-ambiguous-internal-linkage",
"-Wmodules-import-nested-redundant",
"-Wmost",
"-Wmove",
"-Wmsvc-include",
"-Wmsvc-not-found",
"-Wmultichar",
"-Wmultiple-move-vbase",
"-Wnarrowing",
"-Wnested-anon-types",
"-Wnested-externs",
"-Wnew-returns-null",
"-Wnewline-eof",
"-Wno-#pragma-messages",
"-Wno-#warnings",
"-Wno-CFString-literal",
"-Wno-CL4",
"-Wno-IndependentClass-attribute",
"-Wno-NSObject-attribute",
"-Wno-abi",
"-Wno-absolute-value",
"-Wno-abstract-final-class",
"-Wno-abstract-vbase-init",
"-Wno-address",
"-Wno-address-of-packed-member",
"-Wno-address-of-temporary",
"-Wno-aggregate-return",
"-Wno-aix-compat",
"-Wno-align-mismatch",
"-Wno-all",
"-Wno-alloca",
"-Wno-alloca-with-align-alignof",
"-Wno-ambiguous-delete",
"-Wno-ambiguous-ellipsis",
"-Wno-ambiguous-macro",
"-Wno-ambiguous-member-template",
"-Wno-ambiguous-reversed-operator",
"-Wno-analyzer-incompatible-plugin",
"-Wno-anon-enum-enum-conversion",
"-Wno-anonymous-pack-parens",
"-Wno-arc",
"-Wno-arc-bridge-casts-disallowed-in-nonarc",
"-Wno-arc-maybe-repeated-use-of-weak",
"-Wno-arc-non-pod-memaccess",
"-Wno-arc-performSelector-leaks",
"-Wno-arc-repeated-use-of-weak",
"-Wno-arc-retain-cycles",
"-Wno-arc-unsafe-retained-assign",
"-Wno-argument-outside-range",
"-Wno-argument-undefined-behaviour",
"-Wno-array-bounds",
"-Wno-array-bounds-pointer-arithmetic",
"-Wno-asm",
"-Wno-asm-operand-widths",
"-Wno-assign-enum",
"-Wno-assume",
"-Wno-at-protocol",
"-Wno-atimport-in-framework-header",
"-Wno-atomic-alignment",
"-Wno-atomic-implicit-seq-cst",
"-Wno-atomic-memory-ordering",
"-Wno-atomic-properties",
"-Wno-atomic-property-with-user-defined-accessor",
"-Wno-attribute-packed-for-bitfield",
"-Wno-attribute-warning",
"-Wno-attributes",
"-Wno-auto-disable-vptr-sanitizer",
"-Wno-auto-import",
"-Wno-auto-storage-class",
"-Wno-auto-var-id",
"-Wno-availability",
"-Wno-avr-rtlib-linking-quirks",
"-Wno-backend-plugin",
"-Wno-backslash-newline-escape",
"-Wno-bad-function-cast",
"-Wno-binary-literal",
"-Wno-bind-to-temporary-copy",
"-Wno-binding-in-condition",
"-Wno-bitfield-constant-conversion",
"-Wno-bitfield-enum-conversion",
"-Wno-bitfield-width",
"-Wno-bitwise-conditional-parentheses",
"-Wno-bitwise-instead-of-logical",
"-Wno-bitwise-op-parentheses",
"-Wno-block-capture-autoreleasing",
"-Wno-bool-conversion",
"-Wno-bool-conversions",
"-Wno-bool-operation",
"-Wno-braced-scalar-init",
"-Wno-bridge-cast",
"-Wno-builtin-assume-aligned-alignment",
"-Wno-builtin-macro-redefined",
"-Wno-builtin-memcpy-chk-size",
"-Wno-builtin-requires-header",
"-Wno-c++-compat",
"-Wno-c++0x-compat",
"-Wno-c++0x-extensions",
"-Wno-c++0x-narrowing",
"-Wno-c++11-compat",
"-Wno-c++11-compat-deprecated-writable-strings",
"-Wno-c++11-compat-pedantic",
"-Wno-c++11-compat-reserved-user-defined-literal",
"-Wno-c++11-extensions",
"-Wno-c++11-extra-semi",
"-Wno-c++11-inline-namespace",
"-Wno-c++11-long-long",
"-Wno-c++11-narrowing",
"-Wno-c++14-binary-literal",
"-Wno-c++14-compat",
"-Wno-c++14-compat-pedantic",
"-Wno-c++14-extensions",
"-Wno-c++17-compat",
"-Wno-c++17-compat-mangling",
"-Wno-c++17-compat-pedantic",
"-Wno-c++17-extensions",
"-Wno-c++1y-extensions",
"-Wno-c++1z-compat",
"-Wno-c++1z-compat-mangling",
"-Wno-c++1z-extensions",
"-Wno-c++20-compat",
"-Wno-c++20-compat-pedantic",
"-Wno-c++20-designator",
"-Wno-c++20-extensions",
"-Wno-c++2a-compat",
"-Wno-c++2a-compat-pedantic",
"-Wno-c++2a-extensions",
"-Wno-c++2b-extensions",
"-Wno-c++98-c++11-c++14-c++17-compat",
"-Wno-c++98-c++11-c++14-c++17-compat-pedantic",
"-Wno-c++98-c++11-c++14-compat",
"-Wno-c++98-c++11-c++14-compat-pedantic",
"-Wno-c++98-c++11-compat",
"-Wno-c++98-c++11-compat-binary-literal",
"-Wno-c++98-c++11-compat-pedantic",
"-Wno-c++98-compat",
"-Wno-c++98-compat-bind-to-temporary-copy",
"-Wno-c++98-compat-extra-semi",
"-Wno-c++98-compat-local-type-template-args",
"-Wno-c++98-compat-pedantic",
"-Wno-c++98-compat-unnamed-type-template-args",
"-Wno-c11-extensions",
"-Wno-c2x-extensions",
"-Wno-c99-compat",
"-Wno-c99-designator",
"-Wno-c99-extensions",
"-Wno-call-to-pure-virtual-from-ctor-dtor",
"-Wno-called-once-parameter",
"-Wno-cast-align",
"-Wno-cast-calling-convention",
"-Wno-cast-function-type",
"-Wno-cast-of-sel-type",
"-Wno-cast-qual",
"-Wno-cast-qual-unrelated",
"-Wno-char-align",
"-Wno-char-subscripts",
"-Wno-clang-cl-pch",
"-Wno-class-conversion",
"-Wno-class-varargs",
"-Wno-cmse-union-leak",
"-Wno-comma",
"-Wno-comment",
"-Wno-comments",
"-Wno-compare-distinct-pointer-types",
"-Wno-completion-handler",
"-Wno-complex-component-init",
"-Wno-compound-token-split",
"-Wno-compound-token-split-by-macro",
"-Wno-compound-token-split-by-space",
"-Wno-concepts-ts-compat",
"-Wno-conditional-type-mismatch",
"-Wno-conditional-uninitialized",
"-Wno-config-macros",
"-Wno-constant-conversion",
"-Wno-constant-evaluated",
"-Wno-constant-logical-operand",
"-Wno-constexpr-not-const",
"-Wno-consumed",
"-Wno-conversion",
"-Wno-conversion-null",
"-Wno-coroutine",
"-Wno-coroutine-missing-unhandled-exception",
"-Wno-covered-switch-default",
"-Wno-cpp",
"-Wno-cstring-format-directive",
"-Wno-ctad-maybe-unsupported",
"-Wno-ctor-dtor-privacy",
"-Wno-ctu",
"-Wno-cuda-compat",
"-Wno-custom-atomic-properties",
"-Wno-cxx-attribute-extension",
"-Wno-dangling",
"-Wno-dangling-else",
"-Wno-dangling-field",
"-Wno-dangling-gsl",
"-Wno-dangling-initializer-list",
"-Wno-darwin-sdk-settings",
"-Wno-date-time",
"-Wno-dealloc-in-category",
"-Wno-debug-compression-unavailable",
"-Wno-declaration-after-statement",
"-Wno-defaulted-function-deleted",
"-Wno-delegating-ctor-cycles",
"-Wno-delete-abstract-non-virtual-dtor",
"-Wno-delete-incomplete",
"-Wno-delete-non-abstract-non-virtual-dtor",
"-Wno-delete-non-virtual-dtor",
"-Wno-delimited-escape-sequence-extension",
"-Wno-deprecated",
"-Wno-deprecated-altivec-src-compat",
"-Wno-deprecated-anon-enum-enum-conversion",
"-Wno-deprecated-array-compare",
"-Wno-deprecated-attributes",
"-Wno-deprecated-comma-subscript",
"-Wno-deprecated-copy",
"-Wno-deprecated-copy-dtor",
"-Wno-deprecated-copy-with-dtor",
"-Wno-deprecated-copy-with-user-provided-copy",
"-Wno-deprecated-copy-with-user-provided-dtor",
"-Wno-deprecated-declarations",
"-Wno-deprecated-dynamic-exception-spec",
"-Wno-deprecated-enum-compare",
"-Wno-deprecated-enum-compare-conditional",
"-Wno-deprecated-enum-enum-conversion",
"-Wno-deprecated-enum-float-conversion",
"-Wno-deprecated-implementations",
"-Wno-deprecated-increment-bool",
"-Wno-deprecated-objc-isa-usage",
"-Wno-deprecated-objc-pointer-introspection",
"-Wno-deprecated-objc-pointer-introspection-performSelector",
"-Wno-deprecated-pragma",
"-Wno-deprecated-register",
"-Wno-deprecated-this-capture",
"-Wno-deprecated-volatile",
"-Wno-deprecated-writable-strings",
"-Wno-direct-ivar-access",
"-Wno-disabled-macro-expansion",
"-Wno-disabled-optimization",
"-Wno-discard-qual",
"-Wno-distributed-object-modifiers",
"-Wno-div-by-zero",
"-Wno-division-by-zero",
"-Wno-dll-attribute-on-redeclaration",
"-Wno-dllexport-explicit-instantiation-decl",
"-Wno-dllimport-static-field-def",
"-Wno-documentation",
"-Wno-documentation-deprecated-sync",
"-Wno-documentation-html",
"-Wno-documentation-pedantic",
"-Wno-documentation-unknown-command",
"-Wno-dollar-in-identifier-extension",
"-Wno-double-promotion",
"-Wno-dtor-name",
"-Wno-dtor-typedef",
"-Wno-duplicate-decl-specifier",
"-Wno-duplicate-enum",
"-Wno-duplicate-method-arg",
"-Wno-duplicate-method-match",
"-Wno-duplicate-protocol",
"-Wno-dynamic-class-memaccess",
"-Wno-dynamic-exception-spec",
"-Wno-effc++",
"-Wno-elaborated-enum-base",
"-Wno-elaborated-enum-class",
"-Wno-embedded-directive",
"-Wno-empty-body",
"-Wno-empty-decomposition",
"-Wno-empty-init-stmt",
"-Wno-empty-translation-unit",
"-Wno-encode-type",
"-Wno-endif-labels",
"-Wno-enum-compare",
"-Wno-enum-compare-conditional",
"-Wno-enum-compare-switch",
"-Wno-enum-conversion",
"-Wno-enum-enum-conversion",
"-Wno-enum-float-conversion",
"-Wno-enum-too-large",
"-Wno-exceptions",
"-Wno-excess-initializers",
"-Wno-exit-time-destructors",
"-Wno-expansion-to-defined",
"-Wno-explicit-initialize-call",
"-Wno-explicit-ownership-type",
"-Wno-export-unnamed",
"-Wno-export-using-directive",
"-Wno-extern-c-compat",
"-Wno-extern-initializer",
"-Wno-extra",
"-Wno-extra-qualification",
"-Wno-extra-semi",
"-Wno-extra-semi-stmt",
"-Wno-extra-tokens",
"-Wno-final-dtor-non-final-class",
"-Wno-final-macro",
"-Wno-fixed-enum-extension",
"-Wno-fixed-point-overflow",
"-Wno-flag-enum",
"-Wno-flexible-array-extensions",
"-Wno-float-conversion",
"-Wno-float-equal",
"-Wno-float-overflow-conversion",
"-Wno-float-zero-conversion",
"-Wno-for-loop-analysis",
"-Wno-format",
"-Wno-format-extra-args",
"-Wno-format-insufficient-args",
"-Wno-format-invalid-specifier",
"-Wno-format-non-iso",
"-Wno-format-nonliteral",
"-Wno-format-pedantic",
"-Wno-format-security",
"-Wno-format-type-confusion",
"-Wno-format-y2k",
"-Wno-format-zero-length",
"-Wno-format=2",
"-Wno-fortify-source",
"-Wno-four-char-constants",
"-Wno-frame-address",
"-Wno-frame-larger-than",
"-Wno-frame-larger-than=",
"-Wno-framework-include-private-from-public",
"-Wno-free-nonheap-object",
"-Wno-function-def-in-objc-container",
"-Wno-function-multiversion",
"-Wno-fuse-ld-path",
"-Wno-future-compat",
"-Wno-gcc-compat",
"-Wno-global-constructors",
"-Wno-global-isel",
"-Wno-gnu",
"-Wno-gnu-alignof-expression",
"-Wno-gnu-anonymous-struct",
"-Wno-gnu-array-member-paren-init",
"-Wno-gnu-auto-type",
"-Wno-gnu-binary-literal",
"-Wno-gnu-case-range",
"-Wno-gnu-complex-integer",
"-Wno-gnu-compound-literal-initializer",
"-Wno-gnu-conditional-omitted-operand",
"-Wno-gnu-designator",
"-Wno-gnu-empty-initializer",
"-Wno-gnu-empty-struct",
"-Wno-gnu-flexible-array-initializer",
"-Wno-gnu-flexible-array-union-member",
"-Wno-gnu-folding-constant",
"-Wno-gnu-imaginary-constant",
"-Wno-gnu-include-next",
"-Wno-gnu-inline-cpp-without-extern",
"-Wno-gnu-label-as-value",
"-Wno-gnu-redeclared-enum",
"-Wno-gnu-statement-expression",
"-Wno-gnu-static-float-init",
"-Wno-gnu-string-literal-operator-template",
"-Wno-gnu-union-cast",
"-Wno-gnu-variable-sized-type-not-at-end",
"-Wno-gnu-zero-line-directive",
"-Wno-gnu-zero-variadic-macro-arguments",
"-Wno-gpu-maybe-wrong-side",
"-Wno-header-guard",
"-Wno-header-hygiene",
"-Wno-hip-only",
"-Wno-idiomatic-parentheses",
"-Wno-ignored-attributes",
"-Wno-ignored-availability-without-sdk-settings",
"-Wno-ignored-optimization-argument",
"-Wno-ignored-pragma-intrinsic",
"-Wno-ignored-pragma-optimize",
"-Wno-ignored-pragmas",
"-Wno-ignored-qualifiers",
"-Wno-ignored-reference-qualifiers",
"-Wno-implicit",
"-Wno-implicit-atomic-properties",
"-Wno-implicit-const-int-float-conversion",
"-Wno-implicit-conversion-floating-point-to-bool",
"-Wno-implicit-exception-spec-mismatch",
"-Wno-implicit-fallthrough",
"-Wno-implicit-fallthrough-per-function",
"-Wno-implicit-fixed-point-conversion",
"-Wno-implicit-float-conversion",
"-Wno-implicit-function-declaration",
"-Wno-implicit-int",
"-Wno-implicit-int-conversion",
"-Wno-implicit-int-float-conversion",
"-Wno-implicit-retain-self",
"-Wno-implicitly-unsigned-literal",
"-Wno-import",
"-Wno-import-preprocessor-directive-pedantic",
"-Wno-inaccessible-base",
"-Wno-include-next-absolute-path",
"-Wno-include-next-outside-header",
"-Wno-incompatible-exception-spec",
"-Wno-incompatible-function-pointer-types",
"-Wno-incompatible-library-redeclaration",
"-Wno-incompatible-ms-struct",
"-Wno-incompatible-pointer-types",
"-Wno-incompatible-pointer-types-discards-qualifiers",
"-Wno-incompatible-property-type",
"-Wno-incompatible-sysroot",
"-Wno-incomplete-framework-module-declaration",
"-Wno-incomplete-implementation",
"-Wno-incomplete-module",
"-Wno-incomplete-setjmp-declaration",
"-Wno-incomplete-umbrella",
"-Wno-inconsistent-dllimport",
"-Wno-inconsistent-missing-destructor-override",
"-Wno-inconsistent-missing-override",
"-Wno-increment-bool",
"-Wno-infinite-recursion",
"-Wno-init-self",
"-Wno-initializer-overrides",
"-Wno-injected-class-name",
"-Wno-inline",
"-Wno-inline-asm",
"-Wno-inline-namespace-reopened-noninline",
"-Wno-inline-new-delete",
"-Wno-instantiation-after-specialization",
"-Wno-int-conversion",
"-Wno-int-conversions",
"-Wno-int-in-bool-context",
"-Wno-int-to-pointer-cast",
"-Wno-int-to-void-pointer-cast",
"-Wno-integer-overflow",
"-Wno-interrupt-service-routine",
"-Wno-invalid-command-line-argument",
"-Wno-invalid-constexpr",
"-Wno-invalid-iboutlet",
"-Wno-invalid-initializer-from-system-header",
"-Wno-invalid-ios-deployment-target",
"-Wno-invalid-no-builtin-names",
"-Wno-invalid-noreturn",
"-Wno-invalid-offsetof",
"-Wno-invalid-or-nonexistent-directory",
"-Wno-invalid-partial-specialization",
"-Wno-invalid-pch",
"-Wno-invalid-pp-token",
"-Wno-invalid-source-encoding",
"-Wno-invalid-token-paste",
"-Wno-jump-seh-finally",
"-Wno-keyword-compat",
"-Wno-keyword-macro",
"-Wno-knr-promoted-parameter",
"-Wno-language-extension-token",
"-Wno-large-by-value-copy",
"-Wno-liblto",
"-Wno-linker-warnings",
"-Wno-literal-conversion",
"-Wno-literal-range",
"-Wno-local-type-template-args",
"-Wno-logical-not-parentheses",
"-Wno-logical-op-parentheses",
"-Wno-long-long",
"-Wno-loop-analysis",
"-Wno-macro-redefined",
"-Wno-main",
"-Wno-main-return-type",
"-Wno-malformed-warning-check",
"-Wno-many-braces-around-scalar-init",
"-Wno-max-tokens",
"-Wno-max-unsigned-zero",
"-Wno-memset-transposed-args",
"-Wno-memsize-comparison",
"-Wno-method-signatures",
"-Wno-microsoft",
"-Wno-microsoft-abstract",
"-Wno-microsoft-anon-tag",
"-Wno-microsoft-cast",
"-Wno-microsoft-charize",
"-Wno-microsoft-comment-paste",
"-Wno-microsoft-const-init",
"-Wno-microsoft-cpp-macro",
"-Wno-microsoft-default-arg-redefinition",
"-Wno-microsoft-drectve-section",
"-Wno-microsoft-end-of-file",
"-Wno-microsoft-enum-forward-reference",
"-Wno-microsoft-enum-value",
"-Wno-microsoft-exception-spec",
"-Wno-microsoft-exists",
"-Wno-microsoft-extra-qualification",
"-Wno-microsoft-fixed-enum",
"-Wno-microsoft-flexible-array",
"-Wno-microsoft-goto",
"-Wno-microsoft-inaccessible-base",
"-Wno-microsoft-include",
"-Wno-microsoft-mutable-reference",
"-Wno-microsoft-pure-definition",
"-Wno-microsoft-redeclare-static",
"-Wno-microsoft-sealed",
"-Wno-microsoft-static-assert",
"-Wno-microsoft-template",
"-Wno-microsoft-template-shadow",
"-Wno-microsoft-unqualified-friend",
"-Wno-microsoft-using-decl",
"-Wno-microsoft-void-pseudo-dtor",
"-Wno-misleading-indentation",
"-Wno-mismatched-new-delete",
"-Wno-mismatched-parameter-types",
"-Wno-mismatched-return-types",
"-Wno-mismatched-tags",
"-Wno-missing-braces",
"-Wno-missing-constinit",
"-Wno-missing-declarations",
"-Wno-missing-exception-spec",
"-Wno-missing-field-initializers",
"-Wno-missing-format-attribute",
"-Wno-missing-include-dirs",
"-Wno-missing-method-return-type",
"-Wno-missing-noescape",
"-Wno-missing-noreturn",
"-Wno-missing-prototype-for-cc",
"-Wno-missing-prototypes",
"-Wno-missing-selector-name",
"-Wno-missing-sysroot",
"-Wno-missing-variable-declarations",
"-Wno-misspelled-assumption",
"-Wno-module-build",
"-Wno-module-conflict",
"-Wno-module-file-config-mismatch",
"-Wno-module-file-extension",
"-Wno-module-import",
"-Wno-module-import-in-extern-c",
"-Wno-module-lock",
"-Wno-modules-ambiguous-internal-linkage",
"-Wno-modules-import-nested-redundant",
"-Wno-most",
"-Wno-move",
"-Wno-msvc-include",
"-Wno-msvc-not-found",
"-Wno-multichar",
"-Wno-multiple-move-vbase",
"-Wno-narrowing",
"-Wno-nested-anon-types",
"-Wno-nested-externs",
"-Wno-new-returns-null",
"-Wno-newline-eof",
"-Wno-noderef",
"-Wno-noexcept-type",
"-Wno-non-c-typedef-for-linkage",
"-Wno-non-gcc",
"-Wno-non-literal-null-conversion",
"-Wno-non-modular-include-in-framework-module",
"-Wno-non-modular-include-in-module",
"-Wno-non-pod-varargs",
"-Wno-non-power-of-two-alignment",
"-Wno-non-virtual-dtor",
"-Wno-nonnull",
"-Wno-nonportable-cfstrings",
"-Wno-nonportable-include-path",
"-Wno-nonportable-system-include-path",
"-Wno-nonportable-vector-initialization",
"-Wno-nontrivial-memaccess",
"-Wno-nsconsumed-mismatch",
"-Wno-nsreturns-mismatch",
"-Wno-null-arithmetic",
"-Wno-null-character",
"-Wno-null-conversion",
"-Wno-null-dereference",
"-Wno-null-pointer-arithmetic",
"-Wno-null-pointer-subtraction",
"-Wno-nullability",
"-Wno-nullability-completeness",
"-Wno-nullability-completeness-on-arrays",
"-Wno-nullability-declspec",
"-Wno-nullability-extension",
"-Wno-nullability-inferred-on-nested-type",
"-Wno-nullable-to-nonnull-conversion",
"-Wno-objc-autosynthesis-property-ivar-name-match",
"-Wno-objc-bool-constant-conversion",
"-Wno-objc-boxing",
"-Wno-objc-circular-container",
"-Wno-objc-cocoa-api",
"-Wno-objc-designated-initializers",
"-Wno-objc-dictionary-duplicate-keys",
"-Wno-objc-flexible-array",
"-Wno-objc-forward-class-redefinition",
"-Wno-objc-interface-ivars",
"-Wno-objc-literal-compare",
"-Wno-objc-literal-conversion",
"-Wno-objc-macro-redefinition",
"-Wno-objc-messaging-id",
"-Wno-objc-method-access",
"-Wno-objc-missing-property-synthesis",
"-Wno-objc-missing-super-calls",
"-Wno-objc-multiple-method-names",
"-Wno-objc-noncopy-retain-block-property",
"-Wno-objc-nonunified-exceptions",
"-Wno-objc-property-assign-on-object-type",
"-Wno-objc-property-implementation",
"-Wno-objc-property-implicit-mismatch",
"-Wno-objc-property-matches-cocoa-ownership-rule",
"-Wno-objc-property-no-attribute",
"-Wno-objc-property-synthesis",
"-Wno-objc-protocol-method-implementation",
"-Wno-objc-protocol-property-synthesis",
"-Wno-objc-protocol-qualifiers",
"-Wno-objc-readonly-with-setter-property",
"-Wno-objc-redundant-api-use",
"-Wno-objc-redundant-literal-use",
"-Wno-objc-root-class",
"-Wno-objc-signed-char-bool",
"-Wno-objc-signed-char-bool-implicit-float-conversion",
"-Wno-objc-signed-char-bool-implicit-int-conversion",
"-Wno-objc-string-compare",
"-Wno-objc-string-concatenation",
"-Wno-objc-unsafe-perform-selector",
"-Wno-odr",
"-Wno-old-style-cast",
"-Wno-old-style-definition",
"-Wno-opencl-unsupported-rgba",
"-Wno-openmp",
"-Wno-openmp-51-extensions",
"-Wno-openmp-clauses",
"-Wno-openmp-loop-form",
"-Wno-openmp-mapping",
"-Wno-openmp-target",
"-Wno-option-ignored",
"-Wno-ordered-compare-function-pointers",
"-Wno-out-of-line-declaration",
"-Wno-out-of-scope-function",
"-Wno-over-aligned",
"-Wno-overflow",
"-Wno-overlength-strings",
"-Wno-overloaded-shift-op-parentheses",
"-Wno-overloaded-virtual",
"-Wno-override-init",
"-Wno-override-module",
"-Wno-overriding-method-mismatch",
"-Wno-overriding-t-option",
"-Wno-packed",
"-Wno-padded",
"-Wno-parentheses",
"-Wno-parentheses-equality",
"-Wno-partial-availability",
"-Wno-pass",
"-Wno-pass-analysis",
"-Wno-pass-failed",
"-Wno-pass-missed",
"-Wno-pch-date-time",
"-Wno-pedantic",
"-Wno-pedantic-core-features",
"-Wno-pedantic-macros",
"-Wno-pessimizing-move",
"-Wno-pointer-arith",
"-Wno-pointer-bool-conversion",
"-Wno-pointer-compare",
"-Wno-pointer-integer-compare",
"-Wno-pointer-sign",
"-Wno-pointer-to-enum-cast",
"-Wno-pointer-to-int-cast",
"-Wno-pointer-type-mismatch",
"-Wno-poison-system-directories",
"-Wno-potentially-direct-selector",
"-Wno-potentially-evaluated-expression",
"-Wno-pragma-clang-attribute",
"-Wno-pragma-once-outside-header",
"-Wno-pragma-pack",
"-Wno-pragma-pack-suspicious-include",
"-Wno-pragma-system-header-outside-header",
"-Wno-pragmas",
"-Wno-pre-c++14-compat",
"-Wno-pre-c++14-compat-pedantic",
"-Wno-pre-c++17-compat",
"-Wno-pre-c++17-compat-pedantic",
"-Wno-pre-c++20-compat",
"-Wno-pre-c++20-compat-pedantic",
"-Wno-pre-c++2b-compat",
"-Wno-pre-c++2b-compat-pedantic",
"-Wno-pre-c2x-compat",
"-Wno-pre-c2x-compat-pedantic",
"-Wno-pre-openmp-51-compat",
"-Wno-predefined-identifier-outside-function",
"-Wno-private-extern",
"-Wno-private-header",
"-Wno-private-module",
"-Wno-profile-instr-missing",
"-Wno-profile-instr-out-of-date",
"-Wno-profile-instr-unprofiled",
"-Wno-property-access-dot-syntax",
"-Wno-property-attribute-mismatch",
"-Wno-protocol",
"-Wno-protocol-property-synthesis-ambiguity",
"-Wno-psabi",
"-Wno-qualified-void-return-type",
"-Wno-quoted-include-in-framework-header",
"-Wno-range-loop-analysis",
"-Wno-range-loop-bind-reference",
"-Wno-range-loop-construct",
"-Wno-readonly-iboutlet-property",
"-Wno-receiver-expr",
"-Wno-receiver-forward-class",
"-Wno-redeclared-class-member",
"-Wno-redundant-consteval-if",
"-Wno-redundant-decls",
"-Wno-redundant-move",
"-Wno-redundant-parens",
"-Wno-register",
"-Wno-reinterpret-base-class",
"-Wno-remark-backend-plugin",
"-Wno-reorder",
"-Wno-reorder-ctor",
"-Wno-reorder-init-list",
"-Wno-requires-super-attribute",
"-Wno-reserved-id-macro",
"-Wno-reserved-identifier",
"-Wno-reserved-macro-identifier",
"-Wno-reserved-user-defined-literal",
"-Wno-restrict-expansion",
"-Wno-retained-language-linkage",
"-Wno-return-stack-address",
"-Wno-return-std-move",
"-Wno-return-type",
"-Wno-return-type-c-linkage",
"-Wno-rewrite-not-bool",
"-Wno-round-trip-cc1-args",
"-Wno-rtti",
"-Wno-sanitize-address",
"-Wno-search-path-usage",
"-Wno-section",
"-Wno-selector",
"-Wno-selector-type-mismatch",
"-Wno-self-assign",
"-Wno-self-assign-field",
"-Wno-self-assign-overloaded",
"-Wno-self-move",
"-Wno-semicolon-before-method-body",
"-Wno-sentinel",
"-Wno-sequence-point",
"-Wno-serialized-diagnostics",
"-Wno-shadow",
"-Wno-shadow-all",
"-Wno-shadow-field",
"-Wno-shadow-field-in-constructor",
"-Wno-shadow-field-in-constructor-modified",
"-Wno-shadow-ivar",
"-Wno-shadow-uncaptured-local",
"-Wno-shift-count-negative",
"-Wno-shift-count-overflow",
"-Wno-shift-negative-value",
"-Wno-shift-op-parentheses",
"-Wno-shift-overflow",
"-Wno-shift-sign-overflow",
"-Wno-shorten-64-to-32",
"-Wno-sign-compare",
"-Wno-sign-conversion",
"-Wno-sign-promo",
"-Wno-signed-enum-bitfield",
"-Wno-signed-unsigned-wchar",
"-Wno-sizeof-array-argument",
"-Wno-sizeof-array-decay",
"-Wno-sizeof-array-div",
"-Wno-sizeof-pointer-div",
"-Wno-sizeof-pointer-memaccess",
"-Wno-slash-u-filename",
"-Wno-slh-asm-goto",
"-Wno-sometimes-uninitialized",
"-Wno-source-mgr",
"-Wno-source-uses-openmp",
"-Wno-spir-compat",
"-Wno-stack-exhausted",
"-Wno-stack-protector",
"-Wno-static-float-init",
"-Wno-static-in-inline",
"-Wno-static-inline-explicit-instantiation",
"-Wno-static-local-in-inline",
"-Wno-static-self-init",
"-Wno-stdlibcxx-not-found",
"-Wno-strict-aliasing",
"-Wno-strict-aliasing=0",
"-Wno-strict-aliasing=1",
"-Wno-strict-aliasing=2",
"-Wno-strict-overflow",
"-Wno-strict-overflow=0",
"-Wno-strict-overflow=1",
"-Wno-strict-overflow=2",
"-Wno-strict-overflow=3",
"-Wno-strict-overflow=4",
"-Wno-strict-overflow=5",
"-Wno-strict-potentially-direct-selector",
"-Wno-strict-prototypes",
"-Wno-strict-selector-match",
"-Wno-string-compare",
"-Wno-string-concatenation",
"-Wno-string-conversion",
"-Wno-string-plus-char",
"-Wno-string-plus-int",
"-Wno-strlcpy-strlcat-size",
"-Wno-strncat-size",
"-Wno-suggest-destructor-override",
"-Wno-suggest-override",
"-Wno-super-class-method-mismatch",
"-Wno-suspicious-bzero",
"-Wno-suspicious-memaccess",
"-Wno-swift-name-attribute",
"-Wno-switch",
"-Wno-switch-bool",
"-Wno-switch-default",
"-Wno-switch-enum",
"-Wno-sync-fetch-and-nand-semantics-changed",
"-Wno-synth",
"-Wno-tautological-bitwise-compare",
"-Wno-tautological-compare",
"-Wno-tautological-constant-compare",
"-Wno-tautological-constant-in-range-compare",
"-Wno-tautological-constant-out-of-range-compare",
"-Wno-tautological-objc-bool-compare",
"-Wno-tautological-overlap-compare",
"-Wno-tautological-pointer-compare",
"-Wno-tautological-type-limit-compare",
"-Wno-tautological-undefined-compare",
"-Wno-tautological-unsigned-char-zero-compare",
"-Wno-tautological-unsigned-enum-zero-compare",
"-Wno-tautological-unsigned-zero-compare",
"-Wno-tautological-value-range-compare",
"-Wno-tcb-enforcement",
"-Wno-tentative-definition-incomplete-type",
"-Wno-thread-safety",
"-Wno-thread-safety-analysis",
"-Wno-thread-safety-attributes",
"-Wno-thread-safety-beta",
"-Wno-thread-safety-negative",
"-Wno-thread-safety-precise",
"-Wno-thread-safety-reference",
"-Wno-thread-safety-verbose",
"-Wno-trigraphs",
"-Wno-type-limits",
"-Wno-type-safety",
"-Wno-typedef-redefinition",
"-Wno-typename-missing",
"-Wno-unable-to-open-stats-file",
"-Wno-unavailable-declarations",
"-Wno-undeclared-selector",
"-Wno-undef",
"-Wno-undef-prefix",
"-Wno-undefined-bool-conversion",
"-Wno-undefined-func-template",
"-Wno-undefined-inline",
"-Wno-undefined-internal",
"-Wno-undefined-internal-type",
"-Wno-undefined-reinterpret-cast",
"-Wno-undefined-var-template",
"-Wno-underaligned-exception-object",
"-Wno-unevaluated-expression",
"-Wno-unguarded-availability",
"-Wno-unguarded-availability-new",
"-Wno-unicode",
"-Wno-unicode-homoglyph",
"-Wno-unicode-whitespace",
"-Wno-unicode-zero-width",
"-Wno-uninitialized",
"-Wno-uninitialized-const-reference",
"-Wno-unknown-argument",
"-Wno-unknown-assumption",
"-Wno-unknown-attributes",
"-Wno-unknown-cuda-version",
"-Wno-unknown-escape-sequence",
"-Wno-unknown-pragmas",
"-Wno-unknown-sanitizers",
"-Wno-unknown-warning-option",
"-Wno-unnamed-type-template-args",
"-Wno-unneeded-internal-declaration",
"-Wno-unneeded-member-function",
"-Wno-unreachable-code",
"-Wno-unreachable-code-aggressive",
"-Wno-unreachable-code-break",
"-Wno-unreachable-code-fallthrough",
"-Wno-unreachable-code-loop-increment",
"-Wno-unreachable-code-return",
"-Wno-unsequenced",
"-Wno-unsupported-abs",
"-Wno-unsupported-availability-guard",
"-Wno-unsupported-cb",
"-Wno-unsupported-dll-base-class-template",
"-Wno-unsupported-floating-point-opt",
"-Wno-unsupported-friend",
"-Wno-unsupported-gpopt",
"-Wno-unsupported-nan",
"-Wno-unsupported-target-opt",
"-Wno-unsupported-visibility",
"-Wno-unusable-partial-specialization",
"-Wno-unused",
"-Wno-unused-argument",
"-Wno-unused-but-set-parameter",
"-Wno-unused-but-set-variable",
"-Wno-unused-command-line-argument",
"-Wno-unused-comparison",
"-Wno-unused-const-variable",
"-Wno-unused-exception-parameter",
"-Wno-unused-function",
"-Wno-unused-getter-return-value",
"-Wno-unused-label",
"-Wno-unused-lambda-capture",
"-Wno-unused-local-typedef",
"-Wno-unused-local-typedefs",
"-Wno-unused-macros",
"-Wno-unused-member-function",
"-Wno-unused-parameter",
"-Wno-unused-private-field",
"-Wno-unused-property-ivar",
"-Wno-unused-result",
"-Wno-unused-template",
"-Wno-unused-value",
"-Wno-unused-variable",
"-Wno-unused-volatile-lvalue",
"-Wno-used-but-marked-unused",
"-Wno-user-defined-literals",
"-Wno-user-defined-warnings",
"-Wno-varargs",
"-Wno-variadic-macros",
"-Wno-vec-elem-size",
"-Wno-vector-conversion",
"-Wno-vector-conversions",
"-Wno-vexing-parse",
"-Wno-visibility",
"-Wno-vla",
"-Wno-vla-extension",
"-Wno-void-pointer-to-enum-cast",
"-Wno-void-pointer-to-int-cast",
"-Wno-void-ptr-dereference",
"-Wno-volatile-register-var",
"-Wno-wasm-exception-spec",
"-Wno-weak-template-vtables",
"-Wno-weak-vtables",
"-Wno-writable-strings",
"-Wno-write-strings",
"-Wno-xor-used-as-pow",
"-Wno-zero-as-null-pointer-constant",
"-Wno-zero-length-array",
"-Wnoderef",
"-Wnoexcept-type",
"-Wnon-c-typedef-for-linkage",
"-Wnon-gcc",
"-Wnon-literal-null-conversion",
"-Wnon-modular-include-in-framework-module",
"-Wnon-modular-include-in-module",
"-Wnon-pod-varargs",
"-Wnon-power-of-two-alignment",
"-Wnon-virtual-dtor",
"-Wnonnull",
"-Wnonportable-cfstrings",
"-Wnonportable-include-path",
"-Wnonportable-system-include-path",
"-Wnonportable-vector-initialization",
"-Wnontrivial-memaccess",
"-Wnsconsumed-mismatch",
"-Wnsreturns-mismatch",
"-Wnull-arithmetic",
"-Wnull-character",
"-Wnull-conversion",
"-Wnull-dereference",
"-Wnull-pointer-arithmetic",
"-Wnull-pointer-subtraction",
"-Wnullability",
"-Wnullability-completeness",
"-Wnullability-completeness-on-arrays",
"-Wnullability-declspec",
"-Wnullability-extension",
"-Wnullability-inferred-on-nested-type",
"-Wnullable-to-nonnull-conversion",
"-Wobjc-autosynthesis-property-ivar-name-match",
"-Wobjc-bool-constant-conversion",
"-Wobjc-boxing",
"-Wobjc-circular-container",
"-Wobjc-cocoa-api",
"-Wobjc-designated-initializers",
"-Wobjc-dictionary-duplicate-keys",
"-Wobjc-flexible-array",
"-Wobjc-forward-class-redefinition",
"-Wobjc-interface-ivars",
"-Wobjc-literal-compare",
"-Wobjc-literal-conversion",
"-Wobjc-macro-redefinition",
"-Wobjc-messaging-id",
"-Wobjc-method-access",
"-Wobjc-missing-property-synthesis",
"-Wobjc-missing-super-calls",
"-Wobjc-multiple-method-names",
"-Wobjc-noncopy-retain-block-property",
"-Wobjc-nonunified-exceptions",
"-Wobjc-property-assign-on-object-type",
"-Wobjc-property-implementation",
"-Wobjc-property-implicit-mismatch",
"-Wobjc-property-matches-cocoa-ownership-rule",
"-Wobjc-property-no-attribute",
"-Wobjc-property-synthesis",
"-Wobjc-protocol-method-implementation",
"-Wobjc-protocol-property-synthesis",
"-Wobjc-protocol-qualifiers",
"-Wobjc-readonly-with-setter-property",
"-Wobjc-redundant-api-use",
"-Wobjc-redundant-literal-use",
"-Wobjc-root-class",
"-Wobjc-signed-char-bool",
"-Wobjc-signed-char-bool-implicit-float-conversion",
"-Wobjc-signed-char-bool-implicit-int-conversion",
"-Wobjc-string-compare",
"-Wobjc-string-concatenation",
"-Wobjc-unsafe-perform-selector",
"-Wodr",
"-Wold-style-cast",
"-Wold-style-definition",
"-Wopencl-unsupported-rgba",
"-Wopenmp",
"-Wopenmp-51-extensions",
"-Wopenmp-clauses",
"-Wopenmp-loop-form",
"-Wopenmp-mapping",
"-Wopenmp-target",
"-Woption-ignored",
"-Wordered-compare-function-pointers",
"-Wout-of-line-declaration",
"-Wout-of-scope-function",
"-Wover-aligned",
"-Woverflow",
"-Woverlength-strings",
"-Woverloaded-shift-op-parentheses",
"-Woverloaded-virtual",
"-Woverride-init",
"-Woverride-module",
"-Woverriding-method-mismatch",
"-Woverriding-t-option",
"-Wpacked",
"-Wpadded",
"-Wparentheses",
"-Wparentheses-equality",
"-Wpartial-availability",
"-Wpass",
"-Wpass-analysis",
"-Wpass-failed",
"-Wpass-missed",
"-Wpch-date-time",
"-Wpedantic",
"-Wpedantic-core-features",
"-Wpedantic-macros",
"-Wpessimizing-move",
"-Wpointer-arith",
"-Wpointer-bool-conversion",
"-Wpointer-compare",
"-Wpointer-integer-compare",
"-Wpointer-sign",
"-Wpointer-to-enum-cast",
"-Wpointer-to-int-cast",
"-Wpointer-type-mismatch",
"-Wpoison-system-directories",
"-Wpotentially-direct-selector",
"-Wpotentially-evaluated-expression",
"-Wpragma-clang-attribute",
"-Wpragma-once-outside-header",
"-Wpragma-pack",
"-Wpragma-pack-suspicious-include",
"-Wpragma-system-header-outside-header",
"-Wpragmas",
"-Wpre-c++14-compat",
"-Wpre-c++14-compat-pedantic",
"-Wpre-c++17-compat",
"-Wpre-c++17-compat-pedantic",
"-Wpre-c++20-compat",
"-Wpre-c++20-compat-pedantic",
"-Wpre-c++2b-compat",
"-Wpre-c++2b-compat-pedantic",
"-Wpre-c2x-compat",
"-Wpre-c2x-compat-pedantic",
"-Wpre-openmp-51-compat",
"-Wpredefined-identifier-outside-function",
"-Wprivate-extern",
"-Wprivate-header",
"-Wprivate-module",
"-Wprofile-instr-missing",
"-Wprofile-instr-out-of-date",
"-Wprofile-instr-unprofiled",
"-Wproperty-access-dot-syntax",
"-Wproperty-attribute-mismatch",
"-Wprotocol",
"-Wprotocol-property-synthesis-ambiguity",
"-Wpsabi",
"-Wqualified-void-return-type",
"-Wquoted-include-in-framework-header",
"-Wrange-loop-analysis",
"-Wrange-loop-bind-reference",
"-Wrange-loop-construct",
"-Wreadonly-iboutlet-property",
"-Wreceiver-expr",
"-Wreceiver-forward-class",
"-Wredeclared-class-member",
"-Wredundant-consteval-if",
"-Wredundant-decls",
"-Wredundant-move",
"-Wredundant-parens",
"-Wregister",
"-Wreinterpret-base-class",
"-Wremark-backend-plugin",
"-Wreorder",
"-Wreorder-ctor",
"-Wreorder-init-list",
"-Wrequires-super-attribute",
"-Wreserved-id-macro",
"-Wreserved-identifier",
"-Wreserved-macro-identifier",
"-Wreserved-user-defined-literal",
"-Wrestrict-expansion",
"-Wretained-language-linkage",
"-Wreturn-stack-address",
"-Wreturn-std-move",
"-Wreturn-type",
"-Wreturn-type-c-linkage",
"-Wrewrite-not-bool",
"-Wround-trip-cc1-args",
"-Wrtti",
"-Wsanitize-address",
"-Wsearch-path-usage",
"-Wsection",
"-Wselector",
"-Wselector-type-mismatch",
"-Wself-assign",
"-Wself-assign-field",
"-Wself-assign-overloaded",
"-Wself-move",
"-Wsemicolon-before-method-body",
"-Wsentinel",
"-Wsequence-point",
"-Wserialized-diagnostics",
"-Wshadow",
"-Wshadow-all",
"-Wshadow-field",
"-Wshadow-field-in-constructor",
"-Wshadow-field-in-constructor-modified",
"-Wshadow-ivar",
"-Wshadow-uncaptured-local",
"-Wshift-count-negative",
"-Wshift-count-overflow",
"-Wshift-negative-value",
"-Wshift-op-parentheses",
"-Wshift-overflow",
"-Wshift-sign-overflow",
"-Wshorten-64-to-32",
"-Wsign-compare",
"-Wsign-conversion",
"-Wsign-promo",
"-Wsigned-enum-bitfield",
"-Wsigned-unsigned-wchar",
"-Wsizeof-array-argument",
"-Wsizeof-array-decay",
"-Wsizeof-array-div",
"-Wsizeof-pointer-div",
"-Wsizeof-pointer-memaccess",
"-Wslash-u-filename",
"-Wslh-asm-goto",
"-Wsometimes-uninitialized",
"-Wsource-mgr",
"-Wsource-uses-openmp",
"-Wspir-compat",
"-Wstack-exhausted",
"-Wstack-protector",
"-Wstatic-float-init",
"-Wstatic-in-inline",
"-Wstatic-inline-explicit-instantiation",
"-Wstatic-local-in-inline",
"-Wstatic-self-init",
"-Wstdlibcxx-not-found",
"-Wstrict-aliasing",
"-Wstrict-aliasing=0",
"-Wstrict-aliasing=1",
"-Wstrict-aliasing=2",
"-Wstrict-overflow",
"-Wstrict-overflow=0",
"-Wstrict-overflow=1",
"-Wstrict-overflow=2",
"-Wstrict-overflow=3",
"-Wstrict-overflow=4",
"-Wstrict-overflow=5",
"-Wstrict-potentially-direct-selector",
"-Wstrict-prototypes",
"-Wstrict-selector-match",
"-Wstring-compare",
"-Wstring-concatenation",
"-Wstring-conversion",
"-Wstring-plus-char",
"-Wstring-plus-int",
"-Wstrlcpy-strlcat-size",
"-Wstrncat-size",
"-Wsuggest-destructor-override",
"-Wsuggest-override",
"-Wsuper-class-method-mismatch",
"-Wsuspicious-bzero",
"-Wsuspicious-memaccess",
"-Wswift-name-attribute",
"-Wswitch",
"-Wswitch-bool",
"-Wswitch-default",
"-Wswitch-enum",
"-Wsync-fetch-and-nand-semantics-changed",
"-Wsynth",
"-Wtautological-bitwise-compare",
"-Wtautological-compare",
"-Wtautological-constant-compare",
"-Wtautological-constant-in-range-compare",
"-Wtautological-constant-out-of-range-compare",
"-Wtautological-objc-bool-compare",
"-Wtautological-overlap-compare",
"-Wtautological-pointer-compare",
"-Wtautological-type-limit-compare",
"-Wtautological-undefined-compare",
"-Wtautological-unsigned-char-zero-compare",
"-Wtautological-unsigned-enum-zero-compare",
"-Wtautological-unsigned-zero-compare",
"-Wtautological-value-range-compare",
"-Wtcb-enforcement",
"-Wtentative-definition-incomplete-type",
"-Wthread-safety",
"-Wthread-safety-analysis",
"-Wthread-safety-attributes",
"-Wthread-safety-beta",
"-Wthread-safety-negative",
"-Wthread-safety-precise",
"-Wthread-safety-reference",
"-Wthread-safety-verbose",
"-Wtrigraphs",
"-Wtype-limits",
"-Wtype-safety",
"-Wtypedef-redefinition",
"-Wtypename-missing",
"-Wunable-to-open-stats-file",
"-Wunavailable-declarations",
"-Wundeclared-selector",
"-Wundef",
"-Wundef-prefix",
"-Wundefined-bool-conversion",
"-Wundefined-func-template",
"-Wundefined-inline",
"-Wundefined-internal",
"-Wundefined-internal-type",
"-Wundefined-reinterpret-cast",
"-Wundefined-var-template",
"-Wunderaligned-exception-object",
"-Wunevaluated-expression",
"-Wunguarded-availability",
"-Wunguarded-availability-new",
"-Wunicode",
"-Wunicode-homoglyph",
"-Wunicode-whitespace",
"-Wunicode-zero-width",
"-Wuninitialized",
"-Wuninitialized-const-reference",
"-Wunknown-argument",
"-Wunknown-assumption",
"-Wunknown-attributes",
"-Wunknown-cuda-version",
"-Wunknown-escape-sequence",
"-Wunknown-pragmas",
"-Wunknown-sanitizers",
"-Wunknown-warning-option",
"-Wunnamed-type-template-args",
"-Wunneeded-internal-declaration",
"-Wunneeded-member-function",
"-Wunreachable-code",
"-Wunreachable-code-aggressive",
"-Wunreachable-code-break",
"-Wunreachable-code-fallthrough",
"-Wunreachable-code-loop-increment",
"-Wunreachable-code-return",
"-Wunsequenced",
"-Wunsupported-abs",
"-Wunsupported-availability-guard",
"-Wunsupported-cb",
"-Wunsupported-dll-base-class-template",
"-Wunsupported-floating-point-opt",
"-Wunsupported-friend",
"-Wunsupported-gpopt",
"-Wunsupported-nan",
"-Wunsupported-target-opt",
"-Wunsupported-visibility",
"-Wunusable-partial-specialization",
"-Wunused",
"-Wunused-argument",
"-Wunused-but-set-parameter",
"-Wunused-but-set-variable",
"-Wunused-command-line-argument",
"-Wunused-comparison",
"-Wunused-const-variable",
"-Wunused-exception-parameter",
"-Wunused-function",
"-Wunused-getter-return-value",
"-Wunused-label",
"-Wunused-lambda-capture",
"-Wunused-local-typedef",
"-Wunused-local-typedefs",
"-Wunused-macros",
"-Wunused-member-function",
"-Wunused-parameter",
"-Wunused-private-field",
"-Wunused-property-ivar",
"-Wunused-result",
"-Wunused-template",
"-Wunused-value",
"-Wunused-variable",
"-Wunused-volatile-lvalue",
"-Wused-but-marked-unused",
"-Wuser-defined-literals",
"-Wuser-defined-warnings",
"-Wvarargs",
"-Wvariadic-macros",
"-Wvec-elem-size",
"-Wvector-conversion",
"-Wvector-conversions",
"-Wvexing-parse",
"-Wvisibility",
"-Wvla",
"-Wvla-extension",
"-Wvoid-pointer-to-enum-cast",
"-Wvoid-pointer-to-int-cast",
"-Wvoid-ptr-dereference",
"-Wvolatile-register-var",
"-Wwasm-exception-spec",
"-Wweak-template-vtables",
"-Wweak-vtables",
"-Wwritable-strings",
"-Wwrite-strings",
"-Wxor-used-as-pow",
"-Wzero-as-null-pointer-constant",
"-Wzero-length-array",
};
static const unsigned long NUM_KNOWN_WARNINGS = ABSL_ARRAYSIZE(KNOWN_WARNINGS);
| 27.417253 | 79 | 0.645681 | [
"object",
"vector"
] |
093cf364c575972ebbcd5328b673a8c699b08027 | 387 | cpp | C++ | IcarusDetector/Modules/CPUAffinityTool.cpp | RoboPioneers/ProjectIcarus | 85328c0206d77617fe7fbb81b2ca0cda805de849 | [
"MIT"
] | 1 | 2021-10-05T03:43:57.000Z | 2021-10-05T03:43:57.000Z | IcarusDetector/Modules/CPUAffinityTool.cpp | RoboPioneers/ProjectIcarus | 85328c0206d77617fe7fbb81b2ca0cda805de849 | [
"MIT"
] | null | null | null | IcarusDetector/Modules/CPUAffinityTool.cpp | RoboPioneers/ProjectIcarus | 85328c0206d77617fe7fbb81b2ca0cda805de849 | [
"MIT"
] | null | null | null | #include "CPUAffinityTool.hpp"
#include <pthread.h>
namespace Gaia::Modules
{
int CPUAffinityTool::SetCurrentThreadCPUAffinity(const std::vector<unsigned int>& cpus)
{
cpu_set_t mask;
CPU_ZERO(&mask);
for (const auto index : cpus)
{
CPU_SET(index, &mask);
}
return sched_setaffinity(0, sizeof(mask), &mask);
}
} | 20.368421 | 91 | 0.604651 | [
"vector"
] |
093eccccf46c240276b0e5984e10a3cc4862a862 | 1,477 | cpp | C++ | BinaryGenerator/Main.cpp | NEtuee/AnimationEngine | feb7d974edf9cb19725578cae1bcda35a0edc683 | [
"MIT"
] | null | null | null | BinaryGenerator/Main.cpp | NEtuee/AnimationEngine | feb7d974edf9cb19725578cae1bcda35a0edc683 | [
"MIT"
] | null | null | null | BinaryGenerator/Main.cpp | NEtuee/AnimationEngine | feb7d974edf9cb19725578cae1bcda35a0edc683 | [
"MIT"
] | null | null | null | #include "../VulkanSetup/AnimationLoader.h"
#include "../VulkanSetup/AnimationDataRow.h"
#include "../VulkanSetup/FrameData.h"
#include "../VulkanSetup/XMLLoader.h"
#include "../VulkanSetup/XMLData.h"
#include "../VulkanSetup/StringEx.h"
#include "../VulkanSetup/Serialize.h"
#include "../VulkanSetup/HalfFloat.h"
#include <functional>
#include <iostream>
#include <fstream>
#include <vector>
#include "FBXLoader.h"
#include "../VulkanSetup/BoneStructure.h"
#include "../VulkanSetup/Serialize.h"
#include "../VulkanSetup/TransformStructure.h"
#include "../VulkanSetup/SkeletonLoader.h"
#include "../VulkanSetup/SplineKeyVariable.h"
#include "../VulkanSetup/CatmullRomSpline.h"
#include <filesystem>
int main()
{
while (true)
{
std::string path;
std::cout << "path : ";
std::cin >> path;
if (path.compare("exit") == 0)
break;
for (const auto& file : std::filesystem::directory_iterator(path))
{
if (file.path().extension().compare(".fbx") == 0)
{
AnimationLoader loader;
FBXLoader fbxLoader;
std::string path = file.path().string();
//auto ani = loader.loadAnimation(path);
auto ani = fbxLoader.loadAnimation(path.c_str());
loader.optimization(*ani);
std::ofstream save;
path = path.substr(0, path.size() - 3) + ".dat";
std::cout << path << std::endl;
save.open(path, std::ios::binary);
Serialization serialize;
ani->serialize(&serialize, &save);
save.close();
}
}
}
return 0;
} | 22.378788 | 68 | 0.666215 | [
"vector"
] |
09413f1b4fc3640729eb4c78f9e7fcca7ef34811 | 3,708 | cpp | C++ | libgpopt/src/xforms/CXformIntersectAll2LeftSemiJoin.cpp | khannaekta/gporca | 94e509d0a2456851a2cabf02e933c3523946b87b | [
"ECL-2.0",
"Apache-2.0"
] | 1 | 2019-03-05T10:08:56.000Z | 2019-03-05T10:08:56.000Z | libgpopt/src/xforms/CXformIntersectAll2LeftSemiJoin.cpp | khannaekta/gporca | 94e509d0a2456851a2cabf02e933c3523946b87b | [
"ECL-2.0",
"Apache-2.0"
] | null | null | null | libgpopt/src/xforms/CXformIntersectAll2LeftSemiJoin.cpp | khannaekta/gporca | 94e509d0a2456851a2cabf02e933c3523946b87b | [
"ECL-2.0",
"Apache-2.0"
] | null | null | null | //---------------------------------------------------------------------------
// Greenplum Database
// Copyright (C) 2012 EMC Corp.
//
// @filename:
// CXformIntersectAll2LeftSemiJoin.cpp
//
// @doc:
// Implement the transformation of CLogicalIntersectAll into a left semi join
//---------------------------------------------------------------------------
#include "gpos/base.h"
#include "gpopt/exception.h"
#include "gpopt/base/CUtils.h"
#include "gpopt/base/CColRefComputed.h"
#include "gpopt/operators/ops.h"
#include "gpopt/operators/COperator.h"
#include "gpopt/xforms/CXformIntersectAll2LeftSemiJoin.h"
#include "gpopt/xforms/CXformUtils.h"
#include "gpopt/translate/CTranslatorDXLToExpr.h"
using namespace gpmd;
using namespace gpopt;
//---------------------------------------------------------------------------
// @function:
// CXformIntersectAll2LeftSemiJoin::CXformIntersectAll2LeftSemiJoin
//
// @doc:
// Ctor
//
//---------------------------------------------------------------------------
CXformIntersectAll2LeftSemiJoin::CXformIntersectAll2LeftSemiJoin
(
IMemoryPool *pmp
)
:
CXformExploration
(
// pattern
GPOS_NEW(pmp) CExpression
(
pmp,
GPOS_NEW(pmp) CLogicalIntersectAll(pmp),
GPOS_NEW(pmp) CExpression(pmp, GPOS_NEW(pmp) CPatternLeaf(pmp)), // left relational child
GPOS_NEW(pmp) CExpression(pmp, GPOS_NEW(pmp) CPatternLeaf(pmp)) // right relational child
)
)
{}
//---------------------------------------------------------------------------
// @function:
// CXformIntersectAll2LeftSemiJoin::Transform
//
// @doc:
// Actual transformation that transforms a intersect all into a left semi
// join over a window operation over the inputs
//
//---------------------------------------------------------------------------
void
CXformIntersectAll2LeftSemiJoin::Transform
(
CXformContext *pxfctxt,
CXformResult *pxfres,
CExpression *pexpr
)
const
{
GPOS_ASSERT(NULL != pxfctxt);
GPOS_ASSERT(NULL != pxfres);
GPOS_ASSERT(FPromising(pxfctxt->Pmp(), this, pexpr));
GPOS_ASSERT(FCheckPattern(pexpr));
IMemoryPool *pmp = pxfctxt->Pmp();
// TODO: we currently only handle intersect all operators that
// have two children
GPOS_ASSERT(2 == pexpr->UlArity());
// extract components
CExpression *pexprLeftChild = (*pexpr)[0];
CExpression *pexprRightChild = (*pexpr)[1];
CLogicalIntersectAll *popIntersectAll = CLogicalIntersectAll::PopConvert(pexpr->Pop());
DrgDrgPcr *pdrgpdrgpcrInput = popIntersectAll->PdrgpdrgpcrInput();
CExpression *pexprLeftWindow = CXformUtils::PexprWindowWithRowNumber(pmp, pexprLeftChild, (*pdrgpdrgpcrInput)[0]);
CExpression *pexprRightWindow = CXformUtils::PexprWindowWithRowNumber(pmp, pexprRightChild, (*pdrgpdrgpcrInput)[1]);
DrgDrgPcr *pdrgpdrgpcrInputNew = GPOS_NEW(pmp) DrgDrgPcr(pmp);
DrgPcr *pdrgpcrLeftNew = CUtils::PdrgpcrExactCopy(pmp, (*pdrgpdrgpcrInput)[0]);
pdrgpcrLeftNew->Append(CXformUtils::PcrProjectElement(pexprLeftWindow, 0 /* row_number window function*/));
DrgPcr *pdrgpcrRightNew = CUtils::PdrgpcrExactCopy(pmp, (*pdrgpdrgpcrInput)[1]);
pdrgpcrRightNew->Append(CXformUtils::PcrProjectElement(pexprRightWindow, 0 /* row_number window function*/));
pdrgpdrgpcrInputNew->Append(pdrgpcrLeftNew);
pdrgpdrgpcrInputNew->Append(pdrgpcrRightNew);
CExpression *pexprScCond = CUtils::PexprConjINDFCond(pmp, pdrgpdrgpcrInputNew);
// assemble the new logical operator
CExpression *pexprLSJ = GPOS_NEW(pmp) CExpression
(
pmp,
GPOS_NEW(pmp) CLogicalLeftSemiJoin(pmp),
pexprLeftWindow,
pexprRightWindow,
pexprScCond
);
// clean up
pdrgpdrgpcrInputNew->Release();
pxfres->Add(pexprLSJ);
}
// EOF
| 30.644628 | 117 | 0.650485 | [
"transform"
] |
09451c1afca4963e8e2ac12edfeb23f327dbcf51 | 1,112 | cpp | C++ | algorithms/greedy_algorithm/activity_selection.cpp | wuyongfa-genius/Algorithms_in_C- | 0973fc1e2c01a818056a0f0b3bfac7a62449bc73 | [
"MIT"
] | 1 | 2021-08-17T05:22:09.000Z | 2021-08-17T05:22:09.000Z | algorithms/greedy_algorithm/activity_selection.cpp | wuyongfa-genius/Algorithms_in_C- | 0973fc1e2c01a818056a0f0b3bfac7a62449bc73 | [
"MIT"
] | null | null | null | algorithms/greedy_algorithm/activity_selection.cpp | wuyongfa-genius/Algorithms_in_C- | 0973fc1e2c01a818056a0f0b3bfac7a62449bc73 | [
"MIT"
] | null | null | null | //You are given n activities with their start and finish times. Select the maximum number of
//activities that can be performed by a single person, assuming that a person can only work
//on a single activity at a time.
#include<bits/stdc++.h>
using namespace std;
typedef pair<int, int> Pair;
void activity_selection(const vector<int>&starts, const vector<int>&finishs, vector<Pair>&res){
priority_queue<Pair, vector<Pair>, greater<Pair>>pq;
for(int i=0;i<starts.size();++i){
pq.emplace(finishs[i], starts[i]);
}
int start=pq.top().second, end=pq.top().first;
res.emplace_back(start, end);
pq.pop();
while(!pq.empty()){
Pair p=pq.top();
pq.pop();
if(p.second>=end){
start = p.second;
end = p.first;
res.emplace_back(start, end);
}
}
}
// Driver program
int main()
{
vector<int>s = {1, 3, 0, 5, 8, 5};
vector<int>f = {2, 4, 6, 7, 9, 9};
vector<Pair>res;
activity_selection(s, f, res);
for(auto&a:res){
cout<<'('<<a.first<<','<<a.second<<')'<<"-->";
}
return 0;
} | 28.512821 | 95 | 0.586331 | [
"vector"
] |
09475a3240f89043dcd0d9a83b37a58b1c28b78f | 820 | hpp | C++ | include/mtao/geometry/mesh/write_obj.hpp | mtao/core | 91f9bc6e852417989ed62675e2bb372e6afc7325 | [
"MIT"
] | null | null | null | include/mtao/geometry/mesh/write_obj.hpp | mtao/core | 91f9bc6e852417989ed62675e2bb372e6afc7325 | [
"MIT"
] | 4 | 2020-04-18T16:16:05.000Z | 2020-04-18T16:17:36.000Z | include/mtao/geometry/mesh/write_obj.hpp | mtao/core | 91f9bc6e852417989ed62675e2bb372e6afc7325 | [
"MIT"
] | null | null | null | #ifndef WRITE_OBJ_H
#define WRITE_OBJ_H
#include "mtao/types.hpp"
#include <tuple>
namespace mtao::geometry::mesh {
template <typename T>
void write_obj(const mtao::ColVectors<T,3>& V,const mtao::ColVectors<int,3>& F, const std::string& filename);
/*
template <>
extern void write_obj(const mtao::ColVectors<float,3>& V,const mtao::ColVectors<int,3>& F, const std::string& filename);
template <>
extern void write_obj(const mtao::ColVectors<double,3>& V,const mtao::ColVectors<int,3>& F, const std::string& filename);
*/
void write_objF(const mtao::ColVectors<float,3>& V,const mtao::ColVectors<int,3>& F, const std::string& filename);
void write_objD(const mtao::ColVectors<double,3>& V,const mtao::ColVectors<int,3>& F, const std::string& filename);
}
#endif//READ_OBJ_H
| 32.8 | 125 | 0.70122 | [
"mesh",
"geometry"
] |
094d9864aabbfa24bc8f642e99a35c3b47839fd9 | 3,998 | cpp | C++ | tc 160+/BusinessPlan.cpp | ibudiselic/contest-problem-solutions | 88082981b4d87da843472e3ca9ed5f4c42b3f0aa | [
"BSD-2-Clause"
] | 3 | 2015-05-25T06:24:37.000Z | 2016-09-10T07:58:00.000Z | tc 160+/BusinessPlan.cpp | ibudiselic/contest-problem-solutions | 88082981b4d87da843472e3ca9ed5f4c42b3f0aa | [
"BSD-2-Clause"
] | null | null | null | tc 160+/BusinessPlan.cpp | ibudiselic/contest-problem-solutions | 88082981b4d87da843472e3ca9ed5f4c42b3f0aa | [
"BSD-2-Clause"
] | 5 | 2015-05-25T06:24:40.000Z | 2021-08-19T19:22:29.000Z | #include <algorithm>
#include <cassert>
#include <cstdio>
#include <iostream>
#include <sstream>
#include <string>
#include <vector>
#include <cstring>
using namespace std;
int best[1000001];
class BusinessPlan {
public:
int howLong(vector <int> expense, vector <int> revenue, vector <int> ptime, int C, int D) {
if (C >= D)
return 0;
for (int i=0; i<(int)expense.size(); ++i)
if (expense[i] >= revenue[i]) {
expense.erase(expense.begin() + i);
revenue.erase(revenue.begin() + i);
ptime.erase(ptime.begin() + i);
--i;
}
int n = expense.size();
if (n == 0)
return -1;
best[0] = C;
for (int t=1; t<1000001; ++t) {
best[t] = 0;
for (int j=0; j<n; ++j)
if (ptime[j]<=t && best[t-ptime[j]]>=expense[j])
best[t] = max(best[t], best[t-ptime[j]] + revenue[j]-expense[j]);
if (best[t] >= D)
return t;
}
return -1;
}
// BEGIN CUT HERE
public:
void run_test(int Case) { if ((Case == -1) || (Case == 0)) test_case_0(); if ((Case == -1) || (Case == 1)) test_case_1(); if ((Case == -1) || (Case == 2)) test_case_2(); if ((Case == -1) || (Case == 3)) test_case_3(); if ((Case == -1) || (Case == 4)) test_case_4(); }
private:
template <typename T> string print_array(const vector<T> &V) { ostringstream os; os << "{ "; for (typename vector<T>::const_iterator iter = V.begin(); iter != V.end(); ++iter) os << '\"' << *iter << "\","; os << " }"; return os.str(); }
void verify_case(int Case, const int &Expected, const int &Received) { cerr << "Test Case #" << Case << "..."; if (Expected == Received) cerr << "PASSED" << endl; else { cerr << "FAILED" << endl; cerr << "\tExpected: \"" << Expected << '\"' << endl; cerr << "\tReceived: \"" << Received << '\"' << endl; } }
void test_case_0() { int Arr0[] = {1,4}; vector <int> Arg0(Arr0, Arr0 + (sizeof(Arr0) / sizeof(Arr0[0]))); int Arr1[] = {2,10}; vector <int> Arg1(Arr1, Arr1 + (sizeof(Arr1) / sizeof(Arr1[0]))); int Arr2[] = {1,2}; vector <int> Arg2(Arr2, Arr2 + (sizeof(Arr2) / sizeof(Arr2[0]))); int Arg3 = 1; int Arg4 = 10; int Arg5 = 5; verify_case(0, Arg5, howLong(Arg0, Arg1, Arg2, Arg3, Arg4)); }
void test_case_1() { int Arr0[] = {11}; vector <int> Arg0(Arr0, Arr0 + (sizeof(Arr0) / sizeof(Arr0[0]))); int Arr1[] = {20}; vector <int> Arg1(Arr1, Arr1 + (sizeof(Arr1) / sizeof(Arr1[0]))); int Arr2[] = {10}; vector <int> Arg2(Arr2, Arr2 + (sizeof(Arr2) / sizeof(Arr2[0]))); int Arg3 = 10; int Arg4 = 10; int Arg5 = 0; verify_case(1, Arg5, howLong(Arg0, Arg1, Arg2, Arg3, Arg4)); }
void test_case_2() { int Arr0[] = {11}; vector <int> Arg0(Arr0, Arr0 + (sizeof(Arr0) / sizeof(Arr0[0]))); int Arr1[] = {20}; vector <int> Arg1(Arr1, Arr1 + (sizeof(Arr1) / sizeof(Arr1[0]))); int Arr2[] = {10}; vector <int> Arg2(Arr2, Arr2 + (sizeof(Arr2) / sizeof(Arr2[0]))); int Arg3 = 10; int Arg4 = 11; int Arg5 = -1; verify_case(2, Arg5, howLong(Arg0, Arg1, Arg2, Arg3, Arg4)); }
void test_case_3() { int Arr0[] = {1,1,1}; vector <int> Arg0(Arr0, Arr0 + (sizeof(Arr0) / sizeof(Arr0[0]))); int Arr1[] = {3,4,8}; vector <int> Arg1(Arr1, Arr1 + (sizeof(Arr1) / sizeof(Arr1[0]))); int Arr2[] = {1,2,3}; vector <int> Arg2(Arr2, Arr2 + (sizeof(Arr2) / sizeof(Arr2[0]))); int Arg3 = 1; int Arg4 = 11; int Arg5 = 5; verify_case(3, Arg5, howLong(Arg0, Arg1, Arg2, Arg3, Arg4)); }
void test_case_4() { int Arr0[] = {99999,1,99998,2,99997,3,99996,4,99995,5}; vector <int> Arg0(Arr0, Arr0 + (sizeof(Arr0) / sizeof(Arr0[0]))); int Arr1[] = {100000,100000,100000,100,100000,100000,100000,100000,100000,100000}; vector <int> Arg1(Arr1, Arr1 + (sizeof(Arr1) / sizeof(Arr1[0]))); int Arr2[] = {1,9,1,10,1,9,1,9,1,9}; vector <int> Arg2(Arr2, Arr2 + (sizeof(Arr2) / sizeof(Arr2[0]))); int Arg3 = 2; int Arg4 = 100; int Arg5 = 9; verify_case(4, Arg5, howLong(Arg0, Arg1, Arg2, Arg3, Arg4)); }
// END CUT HERE
};
// BEGIN CUT HERE
int main()
{
BusinessPlan ___test;
___test.run_test(-1);
}
// END CUT HERE
| 54.027027 | 503 | 0.582791 | [
"vector"
] |
095394b5c12a47a74011c927dd45538961c71f18 | 2,260 | cpp | C++ | mak3do/mak3do/scenegraph/src/Node.cpp | moimart/mak3do | e78369de2e5925be3bc4108cb31002a1ec29ef52 | [
"MIT"
] | 4 | 2020-02-22T16:34:27.000Z | 2020-06-02T10:58:16.000Z | mak3do/mak3do/scenegraph/src/Node.cpp | moimart/mak3do | e78369de2e5925be3bc4108cb31002a1ec29ef52 | [
"MIT"
] | null | null | null | mak3do/mak3do/scenegraph/src/Node.cpp | moimart/mak3do | e78369de2e5925be3bc4108cb31002a1ec29ef52 | [
"MIT"
] | null | null | null | #include <mak3do/scenegraph/Node.h>
#include <mak3do/scenegraph/Director.h>
#include <mak3do/scenegraph/ActionRunner.h>
#ifdef M3D_PLAT_APPLE
#include <mak3do/scenegraph/apple/NodeImpl.h>
#elif M3D_PLAT_ANDROID
#include <mak3do/scenegraph/android/NodeImpl.h>
#endif
namespace mak3do {
Node::Node()
{
m_pimpl = std::make_shared<NodeImpl>(this);
}
void Node::add_node(NodePtr node)
{
m_pimpl->addChild(node);
}
NodePtr Node::parent() const
{
return m_pimpl->parent();
}
std::vector<NodePtr> Node::nodes() const
{
return m_pimpl->getChildren();
}
void Node::removeFromParent()
{
m_pimpl->removeFromParent();
}
void Node::position(const Vec3& position)
{
m_pimpl->position(position);
}
Vec3 Node::position() const
{
return m_pimpl->position();
}
void Node::visible(bool visible)
{
m_pimpl->visible(visible);
}
bool Node::visible() const
{
return m_pimpl->visible();
}
void Node::scale(const Vec3& scale)
{
m_pimpl->scale(scale);
}
Vec3 Node::scale() const
{
return m_pimpl->scale();
}
void Node::yaw(float yaw)
{
m_pimpl->yaw(yaw);
}
float Node::yaw() const
{
return m_pimpl->yaw();
}
void Node::pitch(float pitch)
{
m_pimpl->pitch(pitch);
}
float Node::pitch() const
{
return m_pimpl->pitch();
}
void Node::roll(float roll)
{
m_pimpl->roll(roll);
}
float Node::roll() const
{
return m_pimpl->roll();
}
void Node::rotation(const Quaternion& rotation)
{
m_pimpl->rotation(rotation);
}
Quaternion Node::rotation() const
{
return m_pimpl->rotation();
}
void Node::name(const std::string& name)
{
m_pimpl->name(name);
}
std::string Node::name() const
{
return m_pimpl->name();
}
void Node::action(ActionPtr action)
{
Director::get()->action_runner()->add_action(action,
std::dynamic_pointer_cast<Node>(this->shared_from_this()));
}
void Node::stop_all_actions()
{
Director::get()->action_runner()->remove_target(std::dynamic_pointer_cast<Node>(this->shared_from_this()));
}
void Node::geometry(GeometryPtr geometry)
{
m_pimpl->geometry(geometry);
}
GeometryPtr Node::geometry() const
{
return m_pimpl->geometry();
}
void Node::look_at(const Vec3& lookat)
{
m_pimpl->look_at(lookat);
}
}
| 15.694444 | 111 | 0.669469 | [
"geometry",
"vector"
] |
0959476158ff7f6df57e3ea26f960260633b22d2 | 8,174 | cpp | C++ | searchlib/src/vespa/searchlib/attribute/attribute_weighted_set_blueprint.cpp | amahussein/vespa | 29d266ae1e5c95e25002b97822953fdd02b1451e | [
"Apache-2.0"
] | 1 | 2021-01-11T18:37:46.000Z | 2021-01-11T18:37:46.000Z | searchlib/src/vespa/searchlib/attribute/attribute_weighted_set_blueprint.cpp | amahussein/vespa | 29d266ae1e5c95e25002b97822953fdd02b1451e | [
"Apache-2.0"
] | 1 | 2021-03-31T22:24:20.000Z | 2021-03-31T22:24:20.000Z | searchlib/src/vespa/searchlib/attribute/attribute_weighted_set_blueprint.cpp | amahussein/vespa | 29d266ae1e5c95e25002b97822953fdd02b1451e | [
"Apache-2.0"
] | 1 | 2020-09-03T11:39:52.000Z | 2020-09-03T11:39:52.000Z | // Copyright 2017 Yahoo Holdings. Licensed under the terms of the Apache 2.0 license. See LICENSE in the project root.
#include "attribute_weighted_set_blueprint.h"
#include <vespa/searchcommon/attribute/i_search_context.h>
#include <vespa/searchlib/common/bitvector.h>
#include <vespa/searchlib/fef/matchdatalayout.h>
#include <vespa/searchlib/query/query_term_ucs4.h>
#include <vespa/searchlib/queryeval/weighted_set_term_search.h>
#include <vespa/vespalib/objects/visit.h>
#include <vespa/vespalib/util/stringfmt.h>
#include <vespa/vespalib/stllike/hash_map.hpp>
#include <vespa/searchlib/queryeval/filter_wrapper.h>
#include <vespa/searchlib/queryeval/orsearch.h>
namespace search {
namespace {
using attribute::ISearchContext;
using attribute::IAttributeVector;
//-----------------------------------------------------------------------------
class UseAttr
{
private:
const attribute::IAttributeVector &_attr;
protected:
const attribute::IAttributeVector &attribute() const { return _attr; }
public:
UseAttr(const attribute::IAttributeVector & attr)
: _attr(attr) {}
};
//-----------------------------------------------------------------------------
class UseStringEnum : public UseAttr
{
public:
using TokenT = uint32_t;
UseStringEnum(const IAttributeVector & attr)
: UseAttr(attr) {}
auto mapToken(const ISearchContext &context) const {
return attribute().findFoldedEnums(context.queryTerm()->getTerm());
}
TokenT getToken(uint32_t docId) const {
return attribute().getEnum(docId);
}
};
//-----------------------------------------------------------------------------
class UseInteger : public UseAttr
{
public:
using TokenT = uint64_t;
UseInteger(const IAttributeVector & attr) : UseAttr(attr) {}
std::vector<int64_t> mapToken(const ISearchContext &context) const {
std::vector<int64_t> result;
Int64Range range(context.getAsIntegerTerm());
if (range.isPoint()) {
result.push_back(range.lower());
}
return result;
}
TokenT getToken(uint32_t docId) const {
return attribute().getInt(docId);
}
};
//-----------------------------------------------------------------------------
template <typename T>
class AttributeFilter final : public queryeval::SearchIterator
{
private:
using Key = typename T::TokenT;
using Map = vespalib::hash_map<Key, int32_t, vespalib::hash<Key>, std::equal_to<Key>, vespalib::hashtable_base::and_modulator>;
using TFMD = fef::TermFieldMatchData;
TFMD &_tfmd;
T _attr;
Map _map;
int32_t _weight;
public:
AttributeFilter(fef::TermFieldMatchData &tfmd,
const IAttributeVector & attr,
const std::vector<int32_t> & weights,
const std::vector<ISearchContext*> & contexts)
: _tfmd(tfmd), _attr(attr), _map(), _weight(0)
{
for (size_t i = 0; i < contexts.size(); ++i) {
for (int64_t token : _attr.mapToken(*contexts[i])) {
_map[token] = weights[i];
}
}
}
void and_hits_into(BitVector & result,uint32_t begin_id) override {
typename Map::iterator end = _map.end();
result.foreach_truebit([&, end](uint32_t key) { if ( _map.find(_attr.getToken(key)) == end) { result.clearBit(key); }}, begin_id);
}
void doSeek(uint32_t docId) override {
typename Map::const_iterator pos = _map.find(_attr.getToken(docId));
if (pos != _map.end()) {
_weight = pos->second;
setDocId(docId);
}
}
void doUnpack(uint32_t docId) override {
_tfmd.reset(docId);
fef::TermFieldMatchDataPosition pos;
pos.setElementWeight(_weight);
_tfmd.appendPosition(pos);
}
void visitMembers(vespalib::ObjectVisitor &) const override {}
};
//-----------------------------------------------------------------------------
} // namespace search::<unnamed>
AttributeWeightedSetBlueprint::AttributeWeightedSetBlueprint(const queryeval::FieldSpec &field, const IAttributeVector & attr)
: queryeval::ComplexLeafBlueprint(field),
_numDocs(attr.getNumDocs()),
_estHits(0),
_weights(),
_attr(attr),
_contexts()
{
set_allow_termwise_eval(true);
}
AttributeWeightedSetBlueprint::~AttributeWeightedSetBlueprint()
{
while (!_contexts.empty()) {
delete _contexts.back();
_contexts.pop_back();
}
}
void
AttributeWeightedSetBlueprint::addToken(std::unique_ptr<ISearchContext> context, int32_t weight)
{
_estHits = std::min(_estHits + context->approximateHits(), _numDocs);
setEstimate(HitEstimate(_estHits, (_estHits == 0)));
_weights.push_back(weight);
_contexts.push_back(context.get());
context.release();
}
queryeval::SearchIterator::UP
AttributeWeightedSetBlueprint::createLeafSearch(const fef::TermFieldMatchDataArray &tfmda, bool strict) const
{
assert(tfmda.size() == 1);
fef::TermFieldMatchData &tfmd = *tfmda[0];
if (strict) { // use generic weighted set search
fef::MatchDataLayout layout;
auto handle = layout.allocTermField(tfmd.getFieldId());
auto match_data = layout.createMatchData();
auto child_tfmd = match_data->resolveTermField(handle);
std::vector<queryeval::SearchIterator*> children(_contexts.size());
for (size_t i = 0; i < _contexts.size(); ++i) {
// TODO: pass ownership with unique_ptr
children[i] = _contexts[i]->createIterator(child_tfmd, true).release();
}
return queryeval::SearchIterator::UP(queryeval::WeightedSetTermSearch::create(children, tfmd, _weights, std::move(match_data)));
} else { // use attribute filter optimization
bool isSingleValue = !_attr.hasMultiValue();
bool isString = (_attr.isStringType() && _attr.hasEnum());
bool isInteger = _attr.isIntegerType();
assert(isSingleValue);
(void) isSingleValue;
if (isString) {
return std::make_unique<AttributeFilter<UseStringEnum>>(tfmd, _attr, _weights, _contexts);
} else {
assert(isInteger);
(void) isInteger;
return std::make_unique<AttributeFilter<UseInteger>>(tfmd, _attr, _weights, _contexts);
}
}
}
queryeval::SearchIterator::UP
AttributeWeightedSetBlueprint::createFilterSearch(bool strict, FilterConstraint constraint) const
{
(void) constraint;
std::vector<std::unique_ptr<queryeval::SearchIterator>> children;
children.reserve(_contexts.size());
for (auto& context : _contexts) {
auto wrapper = std::make_unique<search::queryeval::FilterWrapper>(1);
wrapper->wrap(context->createIterator(wrapper->tfmda()[0], strict));
children.emplace_back(std::move(wrapper));
}
search::queryeval::UnpackInfo unpack_info;
return search::queryeval::OrSearch::create(std::move(children), strict, unpack_info);
}
void
AttributeWeightedSetBlueprint::fetchPostings(const queryeval::ExecuteInfo &execInfo)
{
if (execInfo.isStrict()) {
for (auto * context : _contexts) {
context->fetchPostings(execInfo);
}
}
}
void
AttributeWeightedSetBlueprint::visitMembers(vespalib::ObjectVisitor &visitor) const
{
ComplexLeafBlueprint::visitMembers(visitor);
visitor.visitString("attribute", _attr.getName());
visitor.openStruct("terms", "TermList");
for (size_t i = 0; i < _contexts.size(); ++i) {
const ISearchContext * context = _contexts[i];
visitor.openStruct(vespalib::make_string("[%zu]", i), "Term");
visitor.visitBool("valid", context->valid());
if (context-> valid()) {
bool isString = (_attr.isStringType() && _attr.hasEnum());
if (isString) {
visitor.visitString("term", context->queryTerm()->getTerm());
} else {
visitor.visitInt("term", context->getAsIntegerTerm().lower());
}
visitor.visitInt("weight", _weights[i]);
}
visitor.closeStruct();
}
visitor.closeStruct();
}
} // namespace search
| 34.489451 | 138 | 0.630169 | [
"vector"
] |
8232c65023a789e7bb1320aa8b9145a10f7f55f6 | 6,556 | cc | C++ | util/util_mkldnn.cc | AINoobs/jitinfer | 00b7081a45b8be99376d7aad1b52e28ed97d649c | [
"Apache-2.0"
] | null | null | null | util/util_mkldnn.cc | AINoobs/jitinfer | 00b7081a45b8be99376d7aad1b52e28ed97d649c | [
"Apache-2.0"
] | null | null | null | util/util_mkldnn.cc | AINoobs/jitinfer | 00b7081a45b8be99376d7aad1b52e28ed97d649c | [
"Apache-2.0"
] | null | null | null | /*******************************************************************************
* Copyright 2018 Tensor Tang. 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 "util_mkldnn.h"
#include "log.h"
namespace jitinfer {
namespace util {
// TODO: get concat pd
std::unique_ptr<mkldnn::eltwise_forward::primitive_desc> get_mkldnn_relu_pd(
const mkldnn::memory::desc md, const mkldnn::engine& eng) {
using namespace mkldnn;
auto relu_desc = eltwise_forward::desc(
prop_kind::forward_inference, algorithm::eltwise_relu, md, 0.f, 0.f);
return std::unique_ptr<eltwise_forward::primitive_desc>(
new eltwise_forward::primitive_desc(relu_desc, eng));
}
std::unique_ptr<mkldnn::convolution_forward::desc> get_conv_desc(
const conv_params& p,
mkldnn::memory::data_type src_dt,
mkldnn::memory::data_type wei_dt,
mkldnn::memory::data_type bia_dt,
mkldnn::memory::data_type dst_dt) {
mkldnn::memory::format src_fmt = mkldnn::memory::format::any;
mkldnn::memory::format wei_fmt = mkldnn::memory::format::any;
mkldnn::memory::format bia_fmt = mkldnn::memory::format::x;
mkldnn::memory::format dst_fmt = mkldnn::memory::format::any;
auto aprop_kind = mkldnn::prop_kind::forward_inference;
auto aalgorithm = mkldnn::algorithm::convolution_direct;
auto pad_kind = mkldnn::padding_kind::zero;
// memory desc
auto c_src_desc =
mkldnn::memory::desc({p.bs, p.ic, p.ih, p.iw}, src_dt, src_fmt);
auto c_weights_desc =
p.gp > 1
? mkldnn::memory::desc(
{p.gp, p.oc / p.gp, p.ic / p.gp, p.kh, p.kw}, wei_dt, wei_fmt)
: mkldnn::memory::desc({p.oc, p.ic, p.kh, p.kw}, wei_dt, wei_fmt);
auto c_bias_desc = bia_dt != mkldnn::memory::data_type::data_undef
? mkldnn::memory::desc({p.oc}, bia_dt, bia_fmt)
: mkldnn::memory::desc({}, bia_dt, bia_fmt);
auto c_dst_desc =
mkldnn::memory::desc({p.bs, p.oc, p.oh, p.ow}, dst_dt, dst_fmt);
std::vector<int> padR = {p.ph, p.pw};
for (int i = 0; i < 2; ++i) {
if ((p.ih - ((p.kh - 1) * (p.dh + 1) + 1) + p.ph + padR[0]) / p.sh + 1 !=
p.oh) {
++padR[0];
}
if ((p.iw - ((p.kw - 1) * (p.dw + 1) + 1) + p.pw + padR[1]) / p.sw + 1 !=
p.ow) {
++padR[1];
}
}
if (bia_dt != mkldnn::memory::data_type::data_undef) {
return std::unique_ptr<mkldnn::convolution_forward::desc>(
new mkldnn::convolution_forward::desc(aprop_kind,
aalgorithm,
c_src_desc,
c_weights_desc,
c_bias_desc,
c_dst_desc,
{p.sh, p.sw},
{p.dh, p.dw},
{p.ph, p.pw},
padR,
pad_kind));
} else {
return std::unique_ptr<mkldnn::convolution_forward::desc>(
new mkldnn::convolution_forward::desc(aprop_kind,
aalgorithm,
c_src_desc,
c_weights_desc,
c_dst_desc,
{p.sh, p.sw},
{p.dh, p.dw},
{p.ph, p.pw},
padR,
pad_kind));
}
}
std::unique_ptr<mkldnn::convolution_forward::primitive_desc> get_conv_pd(
const std::unique_ptr<mkldnn::convolution_forward::desc>& conv_desc,
const mkldnn::engine& eng,
std::vector<float> scales,
mkldnn::round_mode rmode,
bool with_relu) {
// attribute
mkldnn::primitive_attr attr = mkldnn::primitive_attr();
attr.set_int_output_round_mode(rmode);
const int count = scales.size();
const int mask = count > 1 ? 1 << 1 : 0;
check_ge(count, 1);
attr.set_output_scales(mask, scales);
if (with_relu) {
mkldnn::post_ops ops;
const float negative_slope = 0.f;
ops.append_eltwise(
1.0f, mkldnn::algorithm::eltwise_relu, negative_slope, 0.f);
attr.set_post_ops(ops);
}
return std::unique_ptr<mkldnn::convolution_forward::primitive_desc>(
new mkldnn::convolution_forward::primitive_desc(*conv_desc, attr, eng));
}
namespace exchange {
mkldnn::round_mode round_mode(jitinfer::round_mode rmode) {
switch (rmode) {
#define CASE(tp) \
case jitinfer::round_mode::tp: \
return mkldnn::round_mode::round_##tp
CASE(nearest);
CASE(down);
#undef CASE
default:
error_and_exit("Unkown round mode %d", rmode);
}
}
memory::dtype dtype(mkldnn::memory::data_type dt) {
switch (dt) {
#define CASE(tp) \
case mkldnn::memory::data_type::tp: \
return memory::dtype::tp
CASE(f32);
CASE(s32);
CASE(s8);
CASE(u8);
#undef CASE
case mkldnn::memory::data_type::data_undef:
return jitinfer::memory::dtype::undef;
default:
error_and_exit("Unkown type %d", dt);
}
}
mkldnn::memory::data_type dtype(memory::dtype dt) {
switch (dt) {
#define CASE(tp) \
case jitinfer::memory::dtype::tp: \
return mkldnn::memory::data_type::tp
CASE(f32);
CASE(s32);
CASE(s8);
CASE(u8);
#undef CASE
case jitinfer::memory::dtype::undef:
return mkldnn::memory::data_type::data_undef;
default:
error_and_exit("Unkown type %d", dt);
}
}
mkldnn::memory::dims dims(const memory::nchw_dims& nchwdims) {
mkldnn::memory::dims out(nchwdims.size());
for (size_t i = 0; i < out.size(); ++i) {
out[i] = nchwdims[i];
}
return out;
}
}
}
}
| 35.825137 | 80 | 0.548505 | [
"vector"
] |
8235cb649798edce956a8d5352ebd56dfcf57d9f | 5,854 | hpp | C++ | idl_compiler/include/morbid/idl_compiler/generator/struct_generator_generator.hpp | felipealmeida/mORBid | 3ebc133f9dbe8af1c5cfb39349a0fbf5c125229b | [
"BSL-1.0"
] | 2 | 2018-01-31T07:06:23.000Z | 2021-02-18T00:49:05.000Z | idl_compiler/include/morbid/idl_compiler/generator/struct_generator_generator.hpp | felipealmeida/mORBid | 3ebc133f9dbe8af1c5cfb39349a0fbf5c125229b | [
"BSL-1.0"
] | null | null | null | idl_compiler/include/morbid/idl_compiler/generator/struct_generator_generator.hpp | felipealmeida/mORBid | 3ebc133f9dbe8af1c5cfb39349a0fbf5c125229b | [
"BSL-1.0"
] | null | null | null | /* (c) Copyright 2012 Felipe Magno de Almeida
*
* Distributed under the Boost Software License, Version 1.0. (See
* accompanying file LICENSE_1_0.txt or copy at
* http://www.boost.org/LICENSE_1_0.txt)
*/
#ifndef MORBID_IDL_COMPILER_STRUCT_GENERATOR_GENERATOR_HPP
#define MORBID_IDL_COMPILER_STRUCT_GENERATOR_GENERATOR_HPP
#include <morbid/idl_compiler/module.hpp>
#include <morbid/idl_compiler/generator/type_spec.hpp>
#include <morbid/idl_compiler/generator/scoped_name.hpp>
#include <boost/spirit/home/karma.hpp>
#include <string>
#include <ostream>
#include <vector>
namespace morbid { namespace idl_compiler { namespace generator {
namespace karma = boost::spirit::karma;
template <typename OutputIterator, typename Iterator>
struct struct_generator_generator : karma::grammar
<OutputIterator, idl_compiler::struct_def_type(struct_)>
{
struct_generator_generator()
: struct_generator_generator::base_type(start)
{
using phoenix::at_c;
using karma::eol;
using karma::string;
using karma::_1; using karma::_r1;
using karma::_val;
namespace types = idl_parser::types;
floating_point_generator =
(
karma::eps(at_c<0>(_val) == types::floating_point::float_)
<< "::morbid::giop::float_"
)
| (
karma::eps(at_c<0>(_val) == types::floating_point::double_)
<< "::morbid::giop::double_"
)
| (
karma::eps(at_c<0>(_val) == types::floating_point::long_double_)
<< karma::eps(false) //"CORBA::LongDouble"
)
;
integer_generator =
(
karma::eps(at_c<0>(_val) == types::integer::signed_short_int)
<< "::morbid::giop::short_"
)
| (
karma::eps(at_c<0>(_val) == types::integer::signed_long_int)
<< "::morbid::giop::long_"
)
| (
karma::eps(at_c<0>(_val) == types::integer::signed_longlong_int)
<< "::morbid::giop::longlong_"
)
| (
karma::eps(at_c<0>(_val) == types::integer::unsigned_short_int)
<< "::morbid::giop::ushort_"
)
| (
karma::eps(at_c<0>(_val) == types::integer::unsigned_long_int)
<< "::morbid::giop::ulong_"
)
| (
karma::eps(at_c<0>(_val) == types::integer::unsigned_longlong_int)
<< "::morbid::giop::ulonglong_"
)
;
char_generator = karma::string[_1 = "::morbid::giop::octet"];
wchar_generator = karma::string[_1 = "::morbid::giop::wchar_"];
boolean_generator = karma::string[_1 = "::morbid::giop::bool_"];
octet_generator = karma::string[_1 = "::morbid::giop::octet"];
// any_generator = karma::eps;
// object_generator = karma::eps;
// value_base_generator = karma::eps;
// void_generator = karma::eps;
// scoped_name_generator = karma::string[_1 = "scoped_name_generator"];//karma::eps;
// sequence_generator = karma::string[_1 = "sequence_generator"];//karma::eps;
// any = karma::string[_1 = "CORBA::Any"];
// object = karma::string[_1 = "CORBA::Object"];
// value_base = karma::string[_1 = "CORBA::ValueBase"];
member_generator =
(floating_point_generator | integer_generator | char_generator | wchar_generator
| boolean_generator | octet_generator
| any_generator | object_generator | value_base_generator | void_generator
| scoped_name_generator
(
at_c<1>(_r1)[at_c<0>(_val)]
)
| sequence_generator
(
at_c<1>(_r1)[at_c<0>(_val)]
)
) [_1 = phoenix::at_c<0>(at_c<0>(_val))]
;
start =
eol
<< "template <typename Domain, typename Iterator, typename Attr>" << eol
<< "struct _morbid_grammar : ::morbid::giop::grammar<Domain, Iterator, Attr( ::morbid::giop::endian)>" << eol
// << indent << ", " << karma::string[_1 = at_c<0>(_val)] << "(unsigned int)>" << eol
<< '{' << eol
<< indent << "_morbid_grammar() : _morbid_grammar::base_type(start)" << eol
<< indent << '{' << eol
// << indent << indent << "namespace karma = boost::spirit::karma;" << eol
// << indent << indent << "using karma::_r1;" << eol
<< indent << indent << "start = " << eol
<< indent << indent << indent
<< (
((member_generator(_r1) << eol) % (indent << indent << indent << "& "))[_1 = at_c<1>(_val)]
| ("karma::eps" << eol)
) << indent << indent << indent << ";" << eol
<< indent << '}' << eol
<< indent << "::morbid::giop::rule<Domain, Iterator, Attr( ::morbid::giop::endian)> start;" << eol
<< "};" << eol << eol
;
indent = karma::space << karma::space;
}
karma::rule<OutputIterator, idl_parser::types::scoped_name(lookuped_type_wrapper)> scoped_name_generator;
karma::rule<OutputIterator, idl_parser::types::floating_point()> floating_point_generator;
karma::rule<OutputIterator, idl_parser::types::integer()> integer_generator;
karma::rule<OutputIterator, idl_parser::types::char_()> char_generator;
karma::rule<OutputIterator, idl_parser::types::wchar_()> wchar_generator;
karma::rule<OutputIterator, idl_parser::types::boolean()> boolean_generator;
karma::rule<OutputIterator, idl_parser::types::octet()> octet_generator;
karma::rule<OutputIterator, idl_parser::types::any()> any_generator;
karma::rule<OutputIterator, idl_parser::types::object()> object_generator;
karma::rule<OutputIterator, idl_parser::types::value_base()> value_base_generator;
karma::rule<OutputIterator, idl_parser::types::void_()> void_generator;
karma::rule<OutputIterator, idl_parser::types::sequence<Iterator>(lookuped_type_wrapper)> sequence_generator;
karma::rule<OutputIterator, idl_parser::struct_member<Iterator>(struct_)> member_generator;
karma::rule<OutputIterator> indent;
karma::rule<OutputIterator, idl_compiler::struct_def_type(struct_)> start;
};
} } }
#endif
| 38.012987 | 115 | 0.640246 | [
"object",
"vector"
] |
8239ab2f8e41563e7b3647c2dc27f776f9e18e0e | 7,276 | hpp | C++ | src/details/hashmap.hpp | lcTls/levin | 7c3768ba96c752fe30b721fcc3af0f7202d5b6b3 | [
"Apache-2.0"
] | 113 | 2019-07-11T08:31:33.000Z | 2022-01-28T03:31:58.000Z | src/details/hashmap.hpp | msdgwzhy6/levin | 082a21d29ac19acbd16c5874367e77a424b7d255 | [
"Apache-2.0"
] | 1 | 2019-07-25T03:21:13.000Z | 2019-07-25T03:21:13.000Z | src/details/hashmap.hpp | msdgwzhy6/levin | 082a21d29ac19acbd16c5874367e77a424b7d255 | [
"Apache-2.0"
] | 27 | 2019-07-11T09:16:36.000Z | 2021-05-28T03:05:07.000Z | #ifndef LEVIN_DETAILS_HASHMAP_H
#define LEVIN_DETAILS_HASHMAP_H
#include <sstream>
#include <unordered_map>
#include "shared_utils.h"
#include "vector.hpp"
namespace levin {
template<class Key, class Value>
class HashIterator;
// @brief customized hashmap which MUST be inplacement new at allocated address
template <class Key, class Value, class Hash = std::hash<Key> >
class HashMap {
public:
// @brief typedefs
// key: hash buckets idx
// val: [ pair<key, value> ]
typedef CustomVector<CustomVector<std::pair<Key, Value>, uint32_t>, size_t> impl_type;
typedef typename impl_type::value_type bucket_type;
typedef typename bucket_type::value_type value_type;
typedef typename bucket_type::size_type value_size_type;
typedef Key key_type;
typedef size_t size_type;
typedef HashIterator<Key, Value> iterator;
typedef HashIterator<Key, Value> const_iterator;
friend class HashIterator<Key, Value>;
// @breif construct&destruct
HashMap();
explicit HashMap(size_type n);
~HashMap() { /* do NOT delete[] */ }
// @brief debugging
std::string layout() const;
// @brief capacity
bool empty() const { return _size == 0; }
size_type size() const { return _size; }
size_type bucket_size() const { return _bucket_size; }
const impl_type& datas() const { return _datas; }
// @brief element access (no range check)
void swap(HashMap<Key, Value, Hash> &other);
// @brief iterators
bool operator ==(const HashMap<Key, Value, Hash> &other) const;
bool operator !=(const HashMap<Key, Value, Hash> &other) const { return !(*this == other); }
iterator find(const Key& key);
iterator begin();
iterator end();
const_iterator begin() const;
const_iterator end() const;
size_type count(const Key& key);
// @brief Do not inserts a new element when the key does not match the key of any element in the container
// Throws an exception when it does not match
const Value& operator[](const Key& key);
// If key does not match the key of any element in the container, the function throws an out_of_range exception.
const Value& at (const Key& key);
private:
HashMap(const HashMap<Key, Value, Hash>&) = delete;
HashMap(HashMap<Key, Value, Hash>&&) = delete;
HashMap<Key, Value, Hash>& operator =(const HashMap<Key, Value, Hash>&) = delete;
HashMap<Key, Value, Hash>& operator =(HashMap<Key, Value, Hash>&&) = delete;
private:
size_type _size = 0;
size_type _bucket_size = 0;
impl_type _datas;
}; // HashMap
template <class Key, class Value, class Hash>
HashMap<Key, Value, Hash>::HashMap() :
_size(0),
_bucket_size(0) {
}
template <class Key, class Value, class Hash>
HashMap<Key, Value, Hash>::HashMap(const size_type n) :
_size(n),
_bucket_size(getPrime(n)) {
}
template <class Key, class Value, class Hash>
typename HashMap<Key, Value, Hash>::iterator HashMap<Key, Value, Hash>::begin() {
return HashIterator<Key, Value>(0, _datas[0].begin(), this);
}
template <class Key, class Value, class Hash>
typename HashMap<Key, Value, Hash>::const_iterator HashMap<Key, Value, Hash>::begin() const {
return HashIterator<Key, Value>(0, _datas[0].begin(), this);
}
template <class Key, class Value, class Hash>
typename HashMap<Key, Value, Hash>::iterator HashMap<Key, Value, Hash>::end() {
return HashIterator<Key, Value>(-1, _datas[_datas.size()-1].end(), this);
}
template <class Key, class Value, class Hash>
typename HashMap<Key, Value, Hash>::const_iterator HashMap<Key, Value, Hash>::end() const {
return HashIterator<Key, Value>(-1, _datas[_datas.size()-1].end(), this);
}
template <class Key, class Value, class Hash>
typename HashMap<Key, Value, Hash>::iterator HashMap<Key, Value, Hash>::find(const Key& key) {
uint32_t bucket_idx = Hash()(key) % _bucket_size;
auto &bucket = _datas[bucket_idx];
int32_t pos = binary_search(&bucket[0], bucket.size() - 1, key);
if (pos >= 0 && pos < bucket.size() && bucket[pos].first == key) {
return HashIterator<Key, Value>(pos, bucket.begin() + pos, this);
}
return end();
}
template<class Key, class Value, class Hash>
typename HashMap<Key, Value, Hash>::size_type HashMap<Key, Value, Hash>::count(const Key& key) {
return find(key) == end()? 0 : 1;
}
template<class Key, class Value, class Hash>
const Value& HashMap<Key, Value, Hash>::operator[](const Key& key) {
return find(key)->second;
}
template<class Key, class Value, class Hash>
const Value& HashMap<Key, Value, Hash>::at(const Key& key) {
return find(key)->second;
}
template <class Key, class Value, class Hash>
void HashMap<Key, Value, Hash>::swap(HashMap<Key, Value, Hash> &other) {
std::swap(_size, other._size);
std::swap(_bucket_size, other._bucket_size);
std::swap(_datas, other._datas);
}
template <class Key, class Value, class Hash>
bool HashMap<Key, Value, Hash>::operator ==(const HashMap<Key, Value, Hash> &other) const {
if (_size != other._size || _bucket_size != other._bucket_size) {
return false;
}
return _datas == other._datas;
}
template <class Key, class Value, class Hash>
std::string HashMap<Key, Value, Hash>::layout() const {
std::stringstream ss;
ss << "HashMap this=[" << (void*)this << "]" << std::endl
<< "[" << (void*)&_size << "]\t\t_size=" << _size << std::endl
<< "[" << (void*)&_bucket_size << "]\t\t_bucket_size=" << _bucket_size << std::endl
<< container_layout(&_datas);
return ss.str();
}
template <class Key, class Value, class Hash>
inline size_t container_memsize(const HashMap<Key, Value, Hash> *object) {
return (object->datas().empty() ? sizeof(*object) :
(size_t)object->datas().back().cend() - (size_t)object);
}
template<class Key, class Value>
class HashIterator {
public:
HashIterator() {
_pos = -1;
_it = typename HashMap<Key, Value>::bucket_type::iterator();
_hashmap = nullptr;
}
HashIterator(int32_t pos,
typename HashMap<Key, Value>::bucket_type::iterator vit,
const HashMap<Key, Value>* hashmap) :
_pos(pos),
_it(vit),
_hashmap(hashmap) {
}
~HashIterator() {}
const typename HashMap<Key, Value>::value_type& operator*() const {
if (_pos == -1) {
throw std::out_of_range("accessed position out of range");
}
return *_it;
}
const typename HashMap<Key, Value>::value_type* operator->() const {
if (_pos == -1) {
throw std::out_of_range("accessed position out of range");
}
return _it;
}
bool operator==(const HashIterator& hsit) const {
return (_hashmap == hsit._hashmap) && (_it == hsit._it);
}
bool operator!=(const HashIterator& hsit) const {
return !(operator==(hsit));
}
HashIterator<Key, Value>& operator++() {
++_it;
return *this;
}
private:
int32_t _pos;
typename HashMap<Key, Value>::bucket_type::iterator _it;
const HashMap<Key, Value>* _hashmap;
}; // class HashIterator
} // namespace levin
#endif // LEVIN_DETAILS_HASHMAP_H
| 34.483412 | 116 | 0.648296 | [
"object",
"vector"
] |
823f251abb82a0a5c8edcec5d8e7a4ea62a4004b | 33,051 | hpp | C++ | include/dpMM/dirMultiNaiveBayes.hpp | jstraub/dpMM | 538c432d5f98c040d5c1adb072e545e38f97fc69 | [
"MIT-feh"
] | 11 | 2015-04-27T15:14:01.000Z | 2021-11-18T00:19:18.000Z | include/dpMM/dirMultiNaiveBayes.hpp | jstraub/dpMM | 538c432d5f98c040d5c1adb072e545e38f97fc69 | [
"MIT-feh"
] | null | null | null | include/dpMM/dirMultiNaiveBayes.hpp | jstraub/dpMM | 538c432d5f98c040d5c1adb072e545e38f97fc69 | [
"MIT-feh"
] | 6 | 2015-07-02T12:46:20.000Z | 2022-03-30T04:39:30.000Z | /* Copyright (c) 2015, Julian Straub <jstraub@csail.mit.edu>, Randi Cabezas <rcabezas@csail.mit.edu>
* Licensed under the MIT license. See the license file LICENSE.
*/
#pragma once
#include <iostream>
#include <stdint.h>
#include <vector>
#include <Eigen/Dense>
#include <boost/shared_ptr.hpp>
#include <dpMM/dpMM.hpp>
#include <dpMM/cat.hpp>
#include <dpMM/dir.hpp>
#include <dpMM/niw.hpp>
#include <dpMM/sampler.hpp>
#include <dpMM/basemeasure.hpp>
#include <dpMM/niwBaseMeasure.hpp>
#include <dpMM/niwSphere.hpp>
#include <dpMM/dirBaseMeasure.hpp>
#include <mmf/mfBaseMeasure.hpp>
using namespace Eigen;
using std::cout;
using std::endl;
using boost::shared_ptr;
using std::vector;
template<typename T=double>
class DirMultiNaiveBayes : public DpMM<T>{
public:
DirMultiNaiveBayes(std::ifstream &in, boost::mt19937 *rng);
DirMultiNaiveBayes(const Dir<Cat<T>, T>& alpha, const vector<boost::shared_ptr<BaseMeasure<T> > >&thetas);
DirMultiNaiveBayes(const Dir<Cat<T>, T>& alpha, const vector< vector<boost::shared_ptr<BaseMeasure<T> > > >&thetas);
virtual ~DirMultiNaiveBayes();
virtual void loadData(const vector<vector<Matrix<T,Dynamic,Dynamic> > > &x);//does nothing other than load data
virtual void initialize(const vector<vector< Matrix<T,Dynamic,Dynamic> > >&x);
virtual void initializeNoParamSampling(const vector<vector< Matrix<T,Dynamic,Dynamic> > >&x);
virtual void initialize(const vector<vector< Matrix<T,Dynamic,Dynamic> > >&x, VectorXu &z);
virtual void initialize(const boost::shared_ptr<ClGMMData<T> >&cld)
{cout<<"not supported"<<endl; assert(false);};
virtual void sampleLabels();
virtual void MAPLabel();
virtual void sampleParameters();
virtual T logJoint(bool verbose=false);
virtual const VectorXu& labels(){return z_;};
virtual const VectorXu& getLabels(){return z_;};
virtual uint32_t getK() const { return K_;};
virtual uint32_t getM() const { return M_;};
virtual uint32_t getN() const { return Nd_;};
// virtual MatrixXu mostLikelyInds(uint32_t n);
virtual MatrixXu mostLikelyInds(uint32_t n, Matrix<T,Dynamic,Dynamic>& logLikes);
Matrix<T,Dynamic,1> getCounts();
virtual void inferAll(uint32_t nIter, bool verbose=false);
virtual void dump(std::ofstream& fOutMeans, std::ofstream& fOutCovs);
virtual void dump_clean(std::ofstream &out);
virtual vector<boost::shared_ptr<BaseMeasure<T> > > getThetas(uint32_t m) {
return(thetas_[m]);
};
virtual boost::shared_ptr<BaseMeasure<T> > getThetas(uint32_t m, uint32_t k) {
return(thetas_[m][k]);
};
virtual void setTheta(uint32_t m, uint32_t k, boost::shared_ptr<BaseMeasure<T> > newTheta ) {
thetas_[m][k] = newTheta;
};
virtual vector<T> evalLogLik(const vector<Matrix<T,Dynamic,1> > xnew, const vector<uint32_t> clusterInd,
const vector<uint32_t> comp2eval =vector<uint32_t>());
virtual uint32_t sampleLabels(const vector<Matrix<T,Dynamic,1> > xnew,
const vector<uint32_t> comp2eval =vector<uint32_t>());
virtual vector<uint32_t> sampleLabels(const vector<vector<Matrix<T,Dynamic,1> > > xnew,
const vector<uint32_t> comp2eval =vector<uint32_t>());
virtual uint32_t MAPLabels(const vector<Matrix<T,Dynamic,1> > xnew,
const vector<uint32_t> comp2eval =vector<uint32_t>());
virtual vector<uint32_t> MAPLabels(const vector<vector<Matrix<T,Dynamic,1> > > xnew,
const vector<uint32_t> comp2eval =vector<uint32_t>());
virtual void updatePDF();
vector<uint32_t> getLogEvalItersHist() {return logJointIterEval;}
vector<T> getLogJointHist() {return logJointHist;}
protected:
virtual T evalLogLik(const vector<Matrix<T,Dynamic,1> > xnew, const uint32_t clusterInd,
const vector<uint32_t> comp2eval);
virtual uint32_t labels_sample_max(const vector<Matrix<T,Dynamic,1> > xnew,
const vector<uint32_t> comp2eval, const bool return_MAP_labels=false);
uint32_t Nd_;
uint32_t K_; //num cluseters
uint32_t M_; //num data sources
Dir<Cat<T>, T> dir_;
Cat<T> pi_;
#ifdef CUDA
SamplerGpu<T>* sampler_;
#else
Sampler<T>* sampler_;
#endif
virtual void initialize_sampler();
Matrix<T,Dynamic,Dynamic> pdfs_;
// Cat cat_;
vector<vector<boost::shared_ptr<BaseMeasure<T> > > > thetas_; // theta_[M][K]
//suffiecient stats
vector<vector<Matrix<T,Dynamic,Dynamic> > > x_; //x_[M][doc](:,word)
VectorXu z_;
virtual void helper_setDims();
vector<VectorXu> dataDim;
vector<uint32_t> logJointIterEval;
vector<T> logJointHist;
};
// --------------------------------------- impl -------------------------------
template<typename T>
void DirMultiNaiveBayes<T>::initialize_sampler() {
if (sampler_ != NULL) {
delete sampler_;
sampler_ = NULL;
}
//initialize sampler
#ifdef CUDA
sampler_ = new SamplerGpu<T>(uint32_t(Nd_),K_,dir_.pRndGen_);
#else
sampler_ = new Sampler<T>(dir_.pRndGen_);
#endif
}
template<typename T>
DirMultiNaiveBayes<T>::DirMultiNaiveBayes(std::ifstream &in, boost::mt19937 *rng) :
dir_(Matrix<T,2,1>::Ones(),rng), pi_(dir_.sample()),sampler_(NULL)
{
//initialize the class from the file pointer given
in >> M_;
in >> K_;
in >> Nd_;
vector<uint32_t> dim;
vector<baseMeasureType> type;
Matrix<T,Dynamic,1> alpha(K_), pi(K_);
for(uint32_t m = 0; m<M_; ++m){
uint32_t temp;
in >> temp;
dim.push_back(temp);
}
for(uint32_t m = 0; m<M_; ++m){
uint32_t temp;
in >> temp;
type.push_back(baseMeasureType(temp));
}
z_ = VectorXu(Nd_);
for(uint32_t n=0; n<Nd_; ++n)
in >> z_(n);
for(uint32_t k=0; k<K_; ++k)
in >> alpha(k);
for(uint32_t k=0; k<K_; ++k)
in >> pi(k);
pdfs_ = Matrix<T,Dynamic,Dynamic>(Nd_,K_);
//for(uint32_t n=0; n<Nd_*K_; ++n)
// in >> pdfs_(n%Nd_, (n-(n%Nd_))/Nd_);
// //in >> pdfs_((n-(n%Nd_))/Nd_, n%Nd_);
////pdfs_ = pdfs_.transpose();
//get parameters
for(uint32_t m=0; m<M_; ++m) {
baseMeasureType typeIter = baseMeasureType(type[m]);
vector<boost::shared_ptr<BaseMeasure<T> > > thetaM;
if(typeIter==NIW_SAMPLED) {
uint32_t Diter = dim[m];
T nu, kappa;
Matrix<T,Dynamic,Dynamic> scatter(Diter, Diter), sigma(Diter,Diter);
Matrix<T,Dynamic,1> theta(Diter), mu(Diter);
for(uint32_t k=0; k<K_; ++k) {
//get nu and kappa
in>> nu;
in>> kappa;
//get theta
for(uint32_t n=0; n<Diter; ++n)
in >> theta(n);
theta = theta.transpose();
//get scatter
for(uint32_t n=0; n<Diter*Diter; ++n)
in >> scatter((n-(n%Diter))/Diter, n%Diter);
//get mean
for(uint32_t n=0; n<Diter; ++n)
in >> mu(n);
mu = mu.transpose();
//get sigma
for(uint32_t n=0; n<Diter*Diter; ++n)
in >> sigma((n-(n%Diter))/Diter, n%Diter);
//build theta[m][k]
NIW<T> niw(scatter,theta,nu,kappa,rng);
Normal<T> normal(mu,sigma,rng);
boost::shared_ptr<NiwSampled<T> > baseIter( new NiwSampled<T>(niw, normal));
//set
thetaM.push_back(boost::shared_ptr<BaseMeasure<T> >(baseIter));
}
} else if(typeIter==NIW_SPHERE) {
uint32_t Diter = dim[m]-1;
T nu;
T counts;
Matrix<T,Dynamic,Dynamic> scatter(Diter, Diter), sigma(Diter,Diter),delta(Diter,Diter);
Matrix<T,Dynamic,1> mu(Diter+1), mu_prior(Diter), north(Diter+1);
for(uint32_t k=0; k<K_; ++k) {
//get nu
in>> nu;
in>> counts;
//get prior mean
for(uint32_t n=0; n<Diter; ++n)
in>> mu_prior(n);
//get scatter
for(uint32_t n=0; n<Diter*Diter; ++n)
in >> scatter((n-(n%Diter))/Diter, n%Diter);
//get delta
for(uint32_t n=0; n<Diter*Diter; ++n)
in >> delta((n-(n%Diter))/Diter, n%Diter);
//get mean
for(uint32_t n=0; n<(Diter+1); ++n)
in >> mu(n);
mu = mu.transpose();
//get sigma
for(uint32_t n=0; n<Diter*Diter; ++n)
in >> sigma((n-(n%Diter))/Diter, n%Diter);
//get north
for(uint32_t n=0; n<(Diter+1); ++n)
in >> north(n);
north = north.transpose();
//build theta[m][k]
IW<T> iw(delta,nu, scatter, mu_prior, counts, rng);
//IW<T> iw(delta,nu, rng);
NiwSphere<T> niwSp(iw,rng);
niwSp.S_ = Sphere<T>(north);
niwSp.normalS_ = NormalSphere<T>(mu,sigma,rng);
//set
thetaM.push_back(boost::shared_ptr<BaseMeasure<T> >(niwSp.copy()));
//boost::shared_ptr<NiwSphere<T> > baseIter( new NiwSphere<T>(iw,rng));
//thetaM.push_back(boost::shared_ptr<BaseMeasure<T> >(baseIter));
}
} else if(typeIter==DIR_SAMPLED) {
uint32_t Diter = dim[m];
T localCount;
Matrix<T,Dynamic,1> post_alpha(Diter), counts(Diter), pdf(Diter);
for(uint32_t k=0; k<K_; ++k) {
//get dir alpha
for(uint32_t n=0; n<Diter; ++n)
in >> post_alpha(n);
//get dir counts
for(uint32_t n=0; n<Diter; ++n)
in >> counts(n);
//get disc pdf
for(uint32_t n=0; n<Diter; ++n)
in >> pdf(n);
in >> localCount;
//build theta[m][k]
Dir<Cat<T>,T> dirBase(post_alpha,counts, rng);
DirSampled<Cat<T>,T> dirSamp(dirBase);
Cat<T> disc(pdf,rng);
dirSamp.disc_ = disc;
dirSamp.count_ = localCount;
//set
thetaM.push_back(boost::shared_ptr<BaseMeasure<T> >(dirSamp.copy()));
}
} else if(typeIter==MF_T) {
// uint32_t Diter = dim[m];
// T localCount;
Matrix<T,Dynamic,1> post_alpha(6), counts(6), pi_pdf(6);
post_alpha.fill(1);
counts.fill(0);
pi_pdf.fill(0);
Matrix<T,3,3> R;
Dir<Cat<T>, T> alpha(post_alpha,rng);
Cat<T> pi(pi_pdf,rng);
std::vector<shared_ptr<BaseMeasure<T> > > iwTs;
std::vector<NormalSphere<T> > TGs;
uint32_t nIter;
for(uint32_t k=0; k<K_; ++k)
{
in >> nIter;
//get dir alpha
for(uint32_t n=0; n<6; ++n) in >> post_alpha(n);
//get dir counts
for(uint32_t n=0; n<6; ++n) in >> counts(n);
//get pi pdf
for(uint32_t n=0; n<6; ++n) in >> pi_pdf(n);
alpha.alpha_ = post_alpha;
alpha.setCounts(counts);
pi.pdf(pi_pdf);
// get rotation
for(uint32_t n=0; n<9; ++n) in >> R(n/3,n%3);
for(uint32_t j=0; j<6; ++j)
{
// load IW in tangent space
Matrix<T,Dynamic,Dynamic> Delta(2,2);
Matrix<T,Dynamic,Dynamic> Scatter(2,2);
Matrix<T,Dynamic,1> mean(2);
T nu,count;
in >> nu;
for(uint32_t n=0; n<4; ++n) in >> Delta(n/2,n%2);
for(uint32_t n=0; n<4; ++n) in >> Scatter(n/2,n%2);
for(uint32_t n=0; n<2; ++n) in >> mean(n);
in >> count;
IW<T> iw(Delta,nu,Scatter,mean,count,rng);
iwTs.push_back(shared_ptr<IwTangent<T> >(
new IwTangent<T>(iw,rng)));
// load tangent space gaussians
Matrix<T,Dynamic,Dynamic> Sigma(2,2);
Matrix<T,Dynamic,1> mu(3);
for(uint32_t n=0; n<4; ++n) in >> Sigma(n/2,n%2);
for(uint32_t n=0; n<3; ++n) in >> mu(n);
TGs.push_back(NormalSphere<T>(mu,Sigma,rng));
reinterpret_cast<IwTangent<T>* >(
iwTs[j].get())->normalS_=TGs[j];
};
// labels -- not set
uint32_t Nk = 0;
in >> Nk;
VectorXu z(Nk);
for(uint32_t n=0; n<Nk; ++n) in >> z(n);
// build model
DirMM<T> dirMM(alpha,iwTs);
MfPrior<T> mfPrior(dirMM, nIter);
MF<T> mf(R,pi,TGs);
//set
thetaM.push_back(boost::shared_ptr<BaseMeasure<T> >(
new MfBase<T>(mfPrior, mf)));
}
} else {
std::cerr << "[DirMultiNaiveBayes::dump_clean] error saving...returning" << endl;
return;
}
thetas_.push_back(thetaM);
}
dir_ = Dir<Cat<T>, T>(alpha,rng);
pi_ = Cat<T>(pi,rng);
this->initialize_sampler();
//cout << "M:" << M_ << " K: " << K_ << " nd: " << Nd_ << endl;
//for(uint32_t m = 0; m<M_; ++m){
// cout << m << ": d="<< dim[m] << ", type=" << type[m] << endl;
//}
//cout << "z_ " << z_.transpose() << endl;
//cout << "alpha " << alpha.transpose() << endl;
}
template<typename T>
DirMultiNaiveBayes<T>::DirMultiNaiveBayes(const Dir<Cat<T>,T>& alpha,
const vector<boost::shared_ptr<BaseMeasure<T> > >& thetas) :
sampler_(NULL), K_(alpha.K_), dir_(alpha), pi_(dir_.sample()), M_(uint32_t(thetas.size()))
{
for (uint32_t m=0; m<M_; ++m)
{
vector<boost::shared_ptr<BaseMeasure<T> > > temp;
for (uint32_t k=0; k<K_; ++k)
{
temp.push_back(boost::shared_ptr<BaseMeasure<T> >(thetas[m]->copy()));
}
thetas_.push_back(temp);
}
#ifndef NDEBUG
for(uint32_t m=0; m<int(M_); ++m) {
for(int k=0; k<int(K_); ++k) {
thetas_[m][k]->print();
}
}
#endif
};
template<typename T>
DirMultiNaiveBayes<T>::DirMultiNaiveBayes(const Dir<Cat<T>,T>& alpha,
const vector< vector<boost::shared_ptr<BaseMeasure<T> > > >& theta) :
K_(alpha.K_), M_(uint32_t(theta.size())),dir_(alpha),
pi_(dir_.sample()), sampler_(NULL),thetas_(theta)
{ };
template<typename T>
DirMultiNaiveBayes<T>::~DirMultiNaiveBayes()
{
if (sampler_ != NULL) {
delete sampler_;
sampler_ = NULL;
}
};
template <typename T>
Matrix<T,Dynamic,1> DirMultiNaiveBayes<T>::getCounts()
{
return counts<T,uint32_t>(z_,K_);
};
template<typename T>
void DirMultiNaiveBayes<T>::loadData(const vector<vector<Matrix<T,Dynamic,Dynamic> > > &x){
x_ = x;
this->helper_setDims();
}
template<typename T>
void DirMultiNaiveBayes<T>::initializeNoParamSampling(const vector< vector< Matrix<T,Dynamic,Dynamic> > > &x)
{
// randomly init labels from prior
Nd_= uint32_t(x.front().size());
z_ = VectorXu::Zero(Nd_);
//init data and labels from given
pi_.sample(z_);
x_ = x;
pdfs_.setZero(Nd_,K_);
this->initialize_sampler();
this->helper_setDims();
};
template<typename T>
void DirMultiNaiveBayes<T>::initialize(const vector< vector< Matrix<T,Dynamic,Dynamic> > > &x)
{
uint32_t Nd= uint32_t(x.front().size());
// randomly init labels from prior
VectorXu z;
z.setZero(Nd);
Cat<T> pi = dir_.sample();
pi.sample(z);
//delegate the initialization to the main intitialization function
this->initialize(x,z);
};
template<typename T>
void DirMultiNaiveBayes<T>::initialize(const vector< vector< Matrix<T,Dynamic,Dynamic> > > &x, VectorXu &z)
{
Nd_= uint32_t(x.front().size());
//init data and labels from given
x_ = x;
z_ = z;
pi_ = dir_.sample();
pdfs_.setZero(Nd_,K_);
this->initialize_sampler();
this->helper_setDims();
this->sampleParameters();
};
template<typename T>
void DirMultiNaiveBayes<T>::helper_setDims()
{
dataDim.clear();
dataDim.reserve(M_);
for(uint32_t m=0; m<M_; ++m) {
VectorXu temp(x_[m].size());
for(uint32_t t=0; t<x_[m].size(); ++t)
temp(t) = uint32_t(x_[m][t].cols());
dataDim.push_back(temp);
}
}
template<typename T>
void DirMultiNaiveBayes<T>::sampleLabels()
{
// obtain posterior categorical under labels
pi_ = dir_.posterior(z_).sample();
// cout<<pi_.pdf().transpose()<<endl;
this->updatePDF();
// sample z_i
sampler_->sampleDiscPdf(pdfs_,z_);
};
template<typename T>
void DirMultiNaiveBayes<T>::updatePDF() {
// compute categorical distribution over label z_i
// no need to re-compute the array and log every iteration)
VectorXd logPdf_z_value = pi_.pdf().array().log();
#pragma omp parallel for
for(int32_t d=0; d<int32_t(Nd_); ++d)
{
VectorXd logPdf_z = logPdf_z_value;
for(uint32_t m=0; m<uint32_t(M_); ++m)
{
for(uint32_t k=0; k<K_; ++k)
{
//updated to SS
logPdf_z[k] += thetas_[m][k]->logLikelihoodFromSS(x_[m][d]);
}
}
// cout<<endl;
// make pdf sum to 1. and exponentiate
pdfs_.row(d) = (logPdf_z.array()-logSumExp(logPdf_z)).exp().matrix().transpose();
// cout<<pi_.pdf().transpose()<<endl;
// cout<<pdf.transpose()<<" |.|="<<pdf.sum();
// cout<<" z_i="<<z_[d]<<endl;
}
}
template<typename T>
void DirMultiNaiveBayes<T>::MAPLabel()
{
/* it chooses the MAP label rather than sampling */
this->updatePDF();
#pragma omp parallel for
for(int32_t d=0; d<int32_t(Nd_); ++d) {
int r,c;
pdfs_.row(d).maxCoeff(&r, &c);
z_(d) = c;
}
};
template<typename T>
void DirMultiNaiveBayes<T>::sampleParameters()
{
//unpacks the contains here vector<vector<Matrix>> into what the posterior expects Matrix
MatrixXu dim(M_,K_);
for(uint32_t m=0; m<M_; ++m) {
#pragma omp parallel for
for(int32_t k=0; k<int32_t(K_); ++k) {
VectorXu temp = (z_.array()==k).select(dataDim[m],0);
dim(m,k) = temp.sum();
}
}
for(int32_t m=0; m<M_; ++m) {
#ifdef _WINDOWS
//#pragma omp parallel for
for(int32_t k=0; k<int32_t(K_); ++k) {
#else
//#pragma omp parallel for
#pragma omp parallel for schedule(dynamic)
for(int32_t k=0; k<int32_t(K_); ++k) {
#endif
if(dim(m,k)!=0) {
//Matrix<T,Dynamic,1> ssIn = Matrix<T,Dynamic,1>::Zero(x_[m].front().rows());
vector< Matrix<T,Dynamic,1> >dataIn;
dataIn.reserve(dim(m,k));
uint32_t count=0;
for(int32_t d=0; d<Nd_; ++d) {
if(z_[d]==k) {
int add_size =int(x_[m][d].cols());
//ssIn += x_[m][d]; //update iteration SS
dataIn.push_back(x_[m][d]);
count+=add_size;
if(count==dim(m,k))
break; //early out if you found them all
}
}
//update values
//thetas_[m][k]->posteriorFromSS(ssIn);
// if(thetas_[m][k]->getBaseMeasureType() == MF_T)
// {
// cout<<"MF "<<k<<" ---------------- "<<endl;
// }
//always sends zeros and look for zeros
thetas_[m][k]->posteriorFromSS(dataIn,VectorXu::Zero(dim(m,k)),0);
} else {
//Matrix<T,Dynamic,1> ssIn = Matrix<T,Dynamic,1>::Zero(x_[m].front().rows());
//ssIn[0]=1; //set counts to 1 to avoid inf
//the posterior needs to reset
//thetas_[m][k]->posteriorFromSS(ssIn);
//passing in one data point (all zeros, with 1 index value=0 and looking for 1)
vector<Matrix<T,Dynamic,1> >dataIn;
dataIn.push_back(Matrix<T,Dynamic,1>::Zero(x_[m].front().rows(),1));
//the posterior needs to reset
VectorXu zz = VectorXu::Zero(1);
thetas_[m][k]->posteriorFromSS(dataIn,zz,1);
}
}
}
};
template<typename T>
T DirMultiNaiveBayes<T>::logJoint(bool verbose)
{
T logJoint = dir_.logPdf(pi_);
if(verbose)
cout<<"\tlog p(pi)="<< logJoint << endl;
for(int32_t m=0; m<int32_t(M_); ++m) {
T logPriorM = 0;
#pragma omp parallel for reduction(+:logPriorM)
for (int32_t k=0; k<int32_t(K_); ++k) {
logPriorM = logPriorM + thetas_[m][k]->logPdfUnderPrior();
}
logJoint+=logPriorM;
if(verbose)
cout<<"\tlog p(theta_" << m << ")="<< logPriorM << endl;
}
for (int32_t m=0; m<int32_t(M_); ++m) {
T logThetaM=0;
#pragma omp parallel for reduction(+:logThetaM)
for (int32_t d=0; d<int32_t(Nd_); ++d) {
logThetaM = logThetaM + thetas_[m][z_[d]]->logLikelihoodFromSS(x_[m][d]);
}
logJoint += logThetaM;
if(verbose)
cout<<"\tlog p(x|z,theta_" << m << ")=" << logThetaM << endl;
}
if(verbose)
cout<<"log p(pi)*p(theta)*p(x|z,theta)=" << logJoint << endl;
return logJoint;
};
template<typename T>
void DirMultiNaiveBayes<T>::inferAll(uint32_t nIter, bool verbose)
{
if(verbose){
cout<<"[DirMultiNaiveBayes::inferALL] ------ inferingALL (nIter=" << nIter << ") ------"<<endl;
if(Nd_<=100) {
cout <<"initial labels:"<< endl;
cout<<this->labels().transpose()<<endl;
}
}
logJointIterEval.clear(); logJointHist.clear();
if(verbose) {
//all iterations stored
logJointIterEval.reserve(nIter); logJointHist.reserve(nIter);
} else {
//only mod 100 stored
logJointIterEval.reserve(int((nIter/100) + 1)); logJointHist.reserve(int((nIter/100) + 1));
}
for(uint32_t t=0; t<nIter; ++t)
{
this->sampleLabels();
this->sampleParameters();
if(verbose)
{
for(int m=0; m<int(M_); ++m) {
for(int k=0; k<int(K_); ++k) {
thetas_[m][k]->print();
}
}
}
if(verbose || t%int(ceil(nIter/100.))==0)
{
VectorXu Ns = counts<uint32_t,uint32_t>(
this->labels(),K_).transpose();
uint32_t K = K_;
for(uint32_t k = 0; k<K_; ++k)
if (Ns(k) == 0) --K;
cout<<"@i "<<t<<": # "
<<K<<" "<<std::setw(1)<<Ns.transpose() <<endl;
T iterLogJoint = this->logJoint(true) ;
//log iterJoint Prob
logJointIterEval.push_back(t);
logJointHist.push_back(iterLogJoint);
if(Nd_<=10) {
cout << "[" << std::setw(3)<< std::setfill('0')
<< t <<"] label: "
<< this->labels().transpose()
<< " [joint= " << std::setw(6) << iterLogJoint << "]"<< endl;
} else {
cout << "[" << std::setw(3)<< std::setfill('0')
<< t <<"] joint= "
<< std::setw(6) << iterLogJoint << endl;
}
}
// if(verbose)
// {
// VectorXu Ns = counts<uint32_t,uint32_t>(this->labels(),K_).transpose();
// uint32_t K = K_;
// for(uint32_t k = 0; k<K_; ++k)
// if (Ns(k) == 0) --K;
// cout<<"@i "<<t<<": # "<<K<<" "<<std::setw(1) <<Ns.transpose() <<endl;
// }
}
//keeps the MAP label in memory
this->MAPLabel();
this->sampleParameters();
}
template <typename T>
void DirMultiNaiveBayes<T>::dump(std::ofstream& fOutMeans, std::ofstream& fOutCovs)
{
cout << "dumping MultiObs naiveBayes" << endl;
cout << "doc index: " << endl;
cout << this->labels().transpose() << endl;
cout << "printing num components: " << endl;
cout << M_ << endl;
cout << "printing cluster params: " << endl;
cout << K_ << endl;
for(uint32_t m=0; m<M_; ++m) {
cout << "component: " << m << endl;
for(uint32_t k=0; k<K_; ++k) {
cout << "theta: " << k << endl;
thetas_[m][k]->print();
}
}
cout << "printing mixture params: " << endl;
pi_.print();
}
template <typename T>
void DirMultiNaiveBayes<T>::dump_clean(std::ofstream &out){
//clean dump, only data with specific format
//FORMAT:
//M 1x1
//K 1x1
//Nd 1x1
//D[m] 1xM
//Type[m] 1xM
//labels 1xNd
//Dir alpha 1xK
//pi pdf 1xK
//pdf KxNd
// mixture parameters
//params Loop over M then K each contains data type for specific type
//for type 1 (NIWSampled)
//---prior--- (NIW)
//nu 1x1
//kappa 1x1
//theta 1xD
//scatter DxD
//---estimate (normal)
//mu 1xD
//Sigma DxD
//for type 2 (NIWSphereFull)
//----prior--- (IW)
//nu 1x1
//count 1x1
//mean 1x(D-1)
//scatter (D-1)x(D-1)
//Delta (D-1)x(D-1)
//--posterior (NormalSphere)
//mean 1x(D-1)
//Sigma (D-1)x(D-1)
//--sphere--- (Sphere)
//north 1x(D-1)
//for type 3 (DirSampled)
//--posterior (Dir)
//alpha 1xK
//counts 1xK
//--distribution (Cat)
//pdf 1xK
//--counts (scalar)
//counts 1x1
//logJoint history
// Niter 1x1
// iterValue 1xNiter (iteration corresponding to the logValue)
// logJoint 1xNiter (logJoint)
//this fixes issues with eigen matrices printing (eg, 00-0.7 )
int curPres = int(out.precision());
out.precision(10);
IOFormat fullPresPrint(FullPrecision,DontAlignCols);
//prints headers
out << M_ << endl
<< K_ << endl
<< Nd_ << endl;
//print dim
for(uint32_t m=0; m<M_; ++m) {
vector<boost::shared_ptr<BaseMeasure<T> > > theta_base = this->getThetas(m);
uint32_t temp = theta_base.front()->getDim();
out << temp << " ";
//out << x_[m].front().rows() << " ";
}
out << endl;
//print type
for(uint32_t m=0; m<M_; ++m) {
out << thetas_[m].front()->getBaseMeasureType() << " ";
}
out << endl;
//print labels
out << this->labels().transpose() << endl;
//print mixture parameters
out << this->dir_.alpha_.transpose() << endl;
out << this->pi_.pdf_.transpose().format(fullPresPrint) << endl;
//out << this->pdfs_.transpose().format(fullPresPrint) << endl;
//print parameters
for(uint32_t m=0; m<M_; ++m) {
vector<boost::shared_ptr<BaseMeasure<T> > > theta_base = this->getThetas(m);
for(uint32_t k=0; k<K_; ++k) {
baseMeasureType type = theta_base[k]->getBaseMeasureType();
if(type==NIW_SAMPLED) {
boost::shared_ptr<NiwSampled<T> > *theta_iter =
reinterpret_cast<boost::shared_ptr<NiwSampled<T> >* >( &theta_base[k]);
//printing prior
NIW<T> prior = theta_iter->get()->niw0_;
out << prior.nu_ << endl <<
prior.kappa_ << endl <<
prior.theta_.transpose() << endl <<
prior.Delta_.format(fullPresPrint) << endl;
//printing posterior
Normal<T> norm = theta_iter->get()->normal_;
out << norm.mu_.transpose() << endl;
out << norm.Sigma().format(fullPresPrint) << endl;
} else if(type==NIW_SPHERE) {
boost::shared_ptr<NiwSphere<T> > *theta_iter =
reinterpret_cast<boost::shared_ptr<NiwSphere<T> >* >(
&theta_base[k]);
//prior
IW<T> prior = theta_iter->get()->iw0_;
out << prior.nu_ << endl
<< prior.count() << endl
<< prior.mean().transpose() << endl
<< prior.scatter().format(fullPresPrint) << endl
<< prior.Delta_.format(fullPresPrint) << endl;
//posterior
NormalSphere<T> norm = theta_iter->get()->normalS_;
out << norm.getMean().transpose().format(fullPresPrint) << endl;
out << norm.Sigma().format(fullPresPrint) << endl;
//sphere
Sphere<T> sp = theta_iter->get()->S_;
out << sp.north().transpose() << endl;
} else if(type==DIR_SAMPLED) {
boost::shared_ptr<DirSampled<Cat<T>,T> > *theta_iter =
reinterpret_cast<boost::shared_ptr<DirSampled<Cat<T>,T> >* >( &theta_base[k]);
//posterior
Dir<Catd,T> post = theta_iter->get()->dir0_;
out << post.alpha_.transpose() << endl;
out << post.counts().transpose() << endl;
//distribution
Catd dist = theta_iter->get()->disc_;
out << dist.pdf_.transpose() << endl;
//counts
T counts = theta_iter->get()->count_;
out << counts << endl;
} else if(type==MF_T) {
boost::shared_ptr<MfBase<T> > *theta_iter =
reinterpret_cast<boost::shared_ptr<MfBase<T> >* >(
&theta_base[k]);
out<< theta_iter->get()->mf0_.T_<<endl;
//posterior
Dir<Cat<T>, T> post = theta_iter->get()->mf0_.dirMM().Alpha();
out << post.alpha_.transpose() << endl;
out << post.counts().transpose() << endl;
Cat<T> pi = theta_iter->get()->mf0_.dirMM().Pi();
out << pi.pdf().transpose() << endl;
out << theta_iter->get()->mf_.R().format(fullPresPrint)<<endl;
for(uint32_t j=0; j<6; ++j)
{
out<< theta_iter->get()->mf0_.theta(j)->iw0_.nu_ << endl;
out<< theta_iter->get()->mf0_.theta(j)->iw0_.Delta_ << endl;
out<< theta_iter->get()->mf0_.theta(j)->iw0_.scatter() << endl;
out<< theta_iter->get()->mf0_.theta(j)->iw0_.mean() << endl;
out<< theta_iter->get()->mf0_.theta(j)->iw0_.count() << endl;
out<< theta_iter->get()->mf0_.theta(j)->normalS_.Sigma() << endl;
out<< theta_iter->get()->mf0_.theta(j)->normalS_.getMean() << endl;
}
// output the labeling
out<<theta_iter->get()->mf0_.dirMM().labels().size()<<endl;
out<<theta_iter->get()->mf0_.dirMM().labels().transpose()<<endl;
} else {
std::cerr << "[DirMultiNaiveBayes::dump_clean] error saving...returning" << endl;
return;
}
}
}
//print logHistory
out << int(logJointHist.size()) << endl;
for(int i=0; i<logJointIterEval.size(); ++i)
out << logJointIterEval[i] << " ";
out << endl;
for(int i=0; i<logJointHist.size(); ++i)
out << logJointHist[i] << " ";
out << endl;
out.precision(curPres);
}
//template <typename T>
//void DirMultiNaiveBayes<T>::dump_clean(std::ofstream &out){
// streambuf *coutbuf = std::cout.rdbuf(); //save old cout buffer
// cout.rdbuf(out.rdbuf()); //redirect std::cout to fout1 buffer
// this->dump_clean(); //write using cout to the specified buffer
// std::cout.rdbuf(coutbuf); //reset to standard output again
//}
template <typename T>
T DirMultiNaiveBayes<T>::evalLogLik(const vector<Matrix<T,Dynamic,1> > xnew,
const uint32_t clusterInd, const vector<uint32_t> comp2eval)
{
//T logJoint = pi_.pdf_(clusterInd);
T logJoint = 0;
for (int32_t m=0; m<int32_t(comp2eval.size()); ++m)
{
logJoint += thetas_[comp2eval[m]][clusterInd]->logLikelihoodFromSS(xnew[m]);
}
return logJoint;
}
template <typename T>
vector<T> DirMultiNaiveBayes<T>::evalLogLik(const vector<Matrix<T,Dynamic,1> > xnew,
const vector<uint32_t> clusterInd,
const vector<uint32_t> comp2eval) {
vector<uint32_t> comp2evalLocal = comp2eval;
if(comp2evalLocal.empty()) {
for(uint32_t m=0; m<M_; ++m)
comp2evalLocal.push_back(m);
}
vector<T> out;
for(uint32_t k=0; k<uint32_t(clusterInd.size()); ++k) {
out.push_back(this->evalLogLik(xnew,clusterInd[k],comp2evalLocal));
}
return(out);
}
template <typename T>
uint32_t DirMultiNaiveBayes<T>::labels_sample_max(const
vector<Matrix<T,Dynamic,1> > xnew, const vector<uint32_t>
comp2eval, const bool return_MAP_labels)
{
/* xnew in the form x[docs][m][SS] */
VectorXd logPdf_z = pi_.pdf().array().log();
for(int32_t m=0; m<comp2eval.size(); ++m)
{
for(int32_t k=0; k<int32_t(K_); ++k)
{
logPdf_z[k] += thetas_[comp2eval[m]][k]->logLikelihoodFromSS(
xnew[m]);
}
}
// make pdf sum to 1. and exponentiate
Matrix<T,Dynamic,Dynamic> pdfLocal = Matrix<T,Dynamic,Dynamic>(1,K_);
pdfLocal = (logPdf_z.array()-logSumExp(logPdf_z)).exp().matrix().transpose();
VectorXu zout = VectorXu(1);
if(return_MAP_labels) {
// return MAP label
int r,c;
pdfLocal.maxCoeff(&r, &c);
zout(0) = c;
} else {
// sample z_i
sampler_->sampleDiscPdf(pdfLocal,zout);
}
return(zout(0));
};
template <typename T>
uint32_t DirMultiNaiveBayes<T>::sampleLabels(const vector<Matrix<T,Dynamic,1> > xnew,
const vector<uint32_t> comp2eval) {
return(this->labels_sample_max(xnew, comp2eval, false));
}
template <typename T>
vector<uint32_t> DirMultiNaiveBayes<T>::sampleLabels(const vector<vector<Matrix<T,Dynamic,1> > > xnew,
const vector<uint32_t> comp2eval)
{
/* xnew in the form x[doc][m][SS] */
vector<uint32_t> out;
for(uint32_t d=0; d<xnew.size(); ++d) {
out.push_back(this->sampleLabels(xnew[d],comp2eval));
}
return(out);
}
template <typename T>
uint32_t DirMultiNaiveBayes<T>::MAPLabels(const vector<Matrix<T,Dynamic,1> > xnew,
const vector<uint32_t> comp2eval) {
return(this->labels_sample_max(xnew, comp2eval, true));
}
template <typename T>
vector<uint32_t> DirMultiNaiveBayes<T>::MAPLabels(const vector<vector<Matrix<T,Dynamic,1> > > xnew,
const vector<uint32_t> comp2eval) {
/* xnew in the form x[docs][m][SS] */
vector<uint32_t> out;
for(uint32_t d=0; d<xnew.size(); ++d) {
out.push_back(this->MAPLabels(xnew[d],comp2eval));
}
return(out);
}
template<typename T>
MatrixXu DirMultiNaiveBayes<T>::mostLikelyInds(uint32_t n, Matrix<T,Dynamic,Dynamic>& logLikes)
{
MatrixXu inds = MatrixXu::Zero(n,K_);
logLikes = Matrix<T,Dynamic,Dynamic>::Ones(n,K_);
#pragma omp parallel for
for (int32_t k=0; k<K_; ++k)
{
for (uint32_t i=0; i<z_.size(); ++i)
if(z_(i) == k)
{
T logLike = 0.;
// iterate over datasources and sum up their logLikes
for(uint32_t m=0; m<uint32_t(M_); ++m)
{
logLike += thetas_[m][z_[i]]->logLikelihoodFromSS(x_[m][i]);
}
// keep only the top n and sorted
for (uint32_t j=0; j<n; ++j)
if(logLikes(j,k) < logLike)
{
for(uint32_t l=n-1; l>j; --l)
{
logLikes(l,k) = logLikes(l-1,k);
inds(l,k) = inds(l-1,k);
}
logLikes(j,k) = logLike;
inds(j,k) = i;
// cout<<"after update "<<logLike<<endl;
// Matrix<T,Dynamic,Dynamic> out(n,K_*2);
// out<<logLikes.cast<T>(),inds.cast<T>();
// cout<<out<<endl;
break;
}
}
}
cout<<"::mostLikelyInds: logLikes"<<endl;
cout<<logLikes<<endl;
cout<<"::mostLikelyInds: inds"<<endl;
cout<<inds<<endl;
return inds;
};
| 29.457219 | 119 | 0.589725 | [
"vector",
"model"
] |
8249779c091983b98392fdf5dc0e9c1f7398452c | 190,592 | cpp | C++ | src/Scheme.cpp | yanndepps/Extempore | d13723dc8dd49ebac01a7883810d5fed871ee0b0 | [
"Unlicense"
] | 994 | 2015-01-02T17:44:22.000Z | 2022-03-26T17:07:43.000Z | src/Scheme.cpp | yanndepps/Extempore | d13723dc8dd49ebac01a7883810d5fed871ee0b0 | [
"Unlicense"
] | 226 | 2015-01-01T17:44:41.000Z | 2022-03-25T10:23:11.000Z | src/Scheme.cpp | yanndepps/Extempore | d13723dc8dd49ebac01a7883810d5fed871ee0b0 | [
"Unlicense"
] | 134 | 2015-01-06T07:37:08.000Z | 2022-02-13T05:34:04.000Z | /*
* Copyright (c) 2011, Andrew Sorensen
* Original credits + licence for TinyScheme and Mini-Scheme below
*
* All rights reserved.
*
*
* Redistribution and use in source and binary forms, with or without
* modification, are permitted provided that the following conditions are met:
*
* 1. Redistributions of source code must retain the above copyright notice,
* this list of conditions and the following disclaimer.
*
* 2. Redistributions in binary form must reproduce the above copyright notice,
* this list of conditions and the following disclaimer in the documentation
* and/or other materials provided with the distribution.
*
* Neither the name of the authors nor other contributors may be used to endorse
* or promote products derived from this software without specific prior written
* permission.
*
*
* THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS"
* AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE
* IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE
* ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT OWNER OR CONTRIBUTORS BE
* LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR
* CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF
* SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS
* INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN
* CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE)
* ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE
* POSSIBILITY OF SUCH DAMAGE.
*
*/
////////////////////////////////////////////////////////////////////////////////////////////////////////////////
//
// Originally from TinyScheme v1.35 (2005) but subsequently reworked for use in impromptu
// Modified again before initial inclusion in Extempore project January 2011
//
// Original TinyScheme Credits Below:
// Dimitrios Souflis (dsouflis@acm.org)
// Based on MiniScheme (original credits follow)
// (MINISCM) coded by Atsushi Moriwaki (11/5/1989)
// (MINISCM) E-MAIL : moriwaki@kurims.kurims.kyoto-u.ac.jp
// (MINISCM) This version has been modified by R.C. Secrist.
// (MINISCM)
// (MINISCM) Mini-Scheme is now maintained by Akira KIDA.
// (MINISCM)
// (MINISCM) This is a revised and modified version by Akira KIDA.
// (MINISCM) current version is 0.85k4 (15 May 1994)
//
// TinyScheme v.1.35 released under MIT licence. This file also released under MIT licence.
/////////////////////////////////////////////////////////////////////////////////////////////////////////////////
#include <inttypes.h>
#include <iostream>
#include <sstream>
#ifndef _WIN32
#include <execinfo.h>
#endif
#include "pcre.h"
#include "EXTLLVM.h"
#include "BranchPrediction.h"
//#include "EXTMonitor"
//#include "EXTThread"
//#include <iosfwd>
#include <iomanip>
#define _SCHEME_SOURCE
#include "SchemePrivate.h"
#ifndef _WIN32
#include <unistd.h>
#endif
#if USE_DL
# include "dynload.h"
#endif
#if USE_MATH
# include <math.h>
#endif
#include <limits.h>
#include <float.h>
#include <ctype.h>
#include <stddef.h>
#include "UNIV.h"
#include "SchemeProcess.h"
/* Used for documentation purposes, to signal functions in 'interface' */
#define INTERFACE
#define TOK_EOF (-1)
#define TOK_LPAREN 0
#define TOK_RPAREN 1
#define TOK_DOT 2
#define TOK_ATOM 3
#define TOK_QUOTE 4
#define TOK_COMMENT 5
#define TOK_DQUOTE 6
#define TOK_BQUOTE 7
#define TOK_COMMA 8
#define TOK_ATMARK 9
#define TOK_SHARP 10
#define TOK_SHARP_CONST 11
#define TOK_VEC 12
# define BACKQUOTE '`'
/*
* Basic memory allocation units
*/
#define banner "Extempore"
#include <string.h>
#include <stdlib.h>
#ifdef _WIN32
#define atoll _atoi64
#endif
/*
#if USE_STRLWR
static const char *strlwr(char *s) {
const char *p=s;
// while(*s) {
// *s=tolower(*s);
// s++;
// }
return p;
}
#endif
*/
#define strlwr(a) a
#ifndef prompt
# define prompt "> "
#endif
#ifndef InitFile
# define InitFile "init.scm"
#endif
#ifndef FIRST_CELLSEGS
# define FIRST_CELLSEGS 1
#endif
static pointer _Error_1(scheme *sc, const char *s, pointer a, int location, int errnum=0);
//#define TREADMILL_DEBUG 1
//#define TREADMILL_CHECKS
inline void unlink(pointer p)
{
pointer cw = p->_cw;
pointer ccw = p->_ccw;
cw->_ccw = ccw;
ccw->_cw = cw;
return;
}
//int missed_thread_insert = 0;
//int hit_thread_insert = 0;
static long long treadmill_inserts_per_cycle = 0;
static int last_call_to_insert_treadmill = 0;
inline void insert_treadmill(scheme* sc, pointer p)
{
if(p->_colour == sc->dark)
{
return;
}
#ifdef TREADMILL_CHECKS
if(sc->treadmill_scanner_finished == true && sc->treadmill_flip_active == false)
{
std::cout << "ERROR: shouldn't be inserting a free cell now!!!" << p << std::endl;
}
#endif
#ifdef TREADMILL_CHECKS
uintptr_t lowptr = (uintptr_t)((char*)sc->cell_seg[0]);
uintptr_t highptr = (uintptr_t)((char*)sc->cell_seg[0]+(CELL_SEGSIZE * sizeof(struct cell)));
uintptr_t actualptr = (uintptr_t)((char*)p);
if ((actualptr > highptr) || (actualptr < lowptr)) {
printf("Pointer not in Cell range!! %" PRIuPTR " != %" PRIuPTR ":%" PRIuPTR "\n",actualptr,lowptr,highptr);
}
#endif
#ifdef TREADMILL_CHECKS
if(p->_list_colour == 0)
{
std::cout << "ERROR[" << extemp::SchemeProcess::I(sc)->getName() <<"] should not be inserting a free cell on the grey list!!!" << p << std::endl;
printf("last_call_to_insert_treadmill: %d\n",last_call_to_insert_treadmill);
last_call_to_insert_treadmill = 0;
printf("CELL: inserted is 0x%" PRIXPTR " base of memory is 0x%" PRIXPTR ":0x%" PRIXPTR "\n",(uintptr_t)p,(uintptr_t)sc->cell_seg[0],(uintptr_t)((char*)sc->cell_seg[0]+(CELL_SEGSIZE * sizeof(struct cell))));
printf("CELL: inserted is %" PRIuPTR " base of memory is %" PRIuPTR ":%" PRIuPTR "\n",(uintptr_t)p,(uintptr_t)&(sc->cell_seg[0]),(uintptr_t)((char*)sc->cell_seg[0]+(CELL_SEGSIZE * sizeof(struct cell))));
printf("CELL: %" PRIuPTR " of %" PRIuPTR "\n",(actualptr-lowptr),(highptr-lowptr));
printf("left: %d right: %d\n",p->_ccw->_list_colour,p->_cw->_list_colour);
#ifndef _WIN32
void* callstack[128];
int i, frames = backtrace(callstack, 128);
char** strs = backtrace_symbols(callstack, frames);
for (i = 0; i < frames; ++i) {
printf("%s\n", strs[i]);
}
free(strs);
#endif
}
// if black don't insert again
if(p->_list_colour == 3)
{
return;
}
// if grey don't insert again
if(p->_list_colour == 2)
{
return;
}
#endif
extemp::EXTMutex::ScopedLock lock(*sc->mutex);
// we might be locked while the treadmill flip happens
// so when we wake up we should re-check our colour to make
// sure that the flip hasn't already added us to the scanner list
if(p->_colour == sc->dark)
{
#ifdef TREADMILL_CHECKS
//std::cout << "WARNING: inserting during flip ... this should be OK?" << p << std::endl;
#endif
return;
}
pointer at = sc->treadmill_top;
#ifdef TREADMILL_CHECKS
if(p == sc->treadmill_scan)
{
// the only time this should be valid is if sc->treadmill_scan == sc->treadmill_top
if(sc->treadmill_scan == sc->treadmill_top)
{
std::cout << "WARNING MOVING SCAN POINTER: this should be OK because SCAN and TOP are currently equal?" << std::endl;
}else{
std::cout << "WARNING scan should never equal p in insert accept if scan == top scan list colour is: " << sc->treadmill_scan->_list_colour << std::endl;
}
}
#endif
if(p == sc->treadmill_top) {
//std::cout << "WARNING MIGHT BE MOVING TOP POINTER BY MISTAKE" << std::endl;
#ifdef TREADMILL_CHECKS
if(sc->treadmill_top->_ccw->_list_colour == 1)
{
sc->treadmill_top = sc->treadmill_top->_ccw;
at = sc->treadmill_top;
}else{
printf("CELL COUNTER CLOCKWISE OF TOP IS NOT ECRU\n");
}
if(sc->treadmill_bottom == sc->treadmill_top)
std::cout << "VERY VERY BAD - Bottom and Top met in insert_treadmill !!!!!!! inserting(" << p << ")" << std::endl;
#else
sc->treadmill_top = sc->treadmill_top->_ccw;
at = sc->treadmill_top;
#endif
}else if(p == sc->treadmill_bottom) {
//std::cout << "WARNING MIGHT BE MOVING BOTTOM POINTER BY MISTAKE" << std::endl;
#ifdef TREADMILL_CHECKS
if(sc->treadmill_bottom->_cw->_list_colour == 1)
{
if(sc->treadmill_bottom == sc->treadmill_free)
{
sc->treadmill_free = sc->treadmill_bottom->_cw;
}
sc->treadmill_bottom = sc->treadmill_bottom->_cw;
}else{
printf("CELL CLOCKWISE OF BOTTOM IS NOT ECRU\n");
}
#else
if(sc->treadmill_bottom == sc->treadmill_free)
{
sc->treadmill_free = sc->treadmill_bottom->_cw;
}
sc->treadmill_bottom = sc->treadmill_bottom->_cw;
if(sc->treadmill_bottom == sc->treadmill_top) std::cout << "VERY VERY BAD - Bottom and Top met in insert_treadmill !!!!!!!" << std::endl;
#endif
//if(p == at) at = sc->treadmill_bottom;
//sc->treadmill_bottom = sc->treadmill_bottom->_cw;
}else if(p == sc->treadmill_free) {
std::cout << "WARNING MOVING FREE POINTER BY MISTAKE: THIS IS AN ERROR!!!!!!!" << std::endl;
_Error_1(sc, "OUT OF MEMORY ERROR!", sc->NIL, 0, 0);
return;
}
// make this sure this happens after check for p & top as at may have changed.
if(sc->treadmill_scan == at) // this assumes that at is always sc->treadmill_top
{
#ifdef TREADMILL_DEBUG
std::cout << "SETTING TREADMILL_SCAN IN INSERT: " << at << " :: " << sc->treadmill_top << std::endl;
#endif
sc->treadmill_scan = p;
#ifdef TREADMILL_CHECKS
//printf("SCAN == TOP. set SCAN to %p for insert\n",p);
#endif
}
#ifdef TREADMILL_CHECKS
p->_list_colour = 2; //set to grey
#endif
treadmill_inserts_per_cycle++;
unlink(p);
p->_colour = sc->dark;
p->_ccw = at;
p->_cw = at->_cw;
p->_cw->_ccw = p;
at->_cw = p;
//final sanity check
#ifdef TREADMILL_CHECKS
if(p->_ccw == p || p->_cw == p)
{
printf("ERROR P refers to itself after insert\n");
}
if(at->_ccw == at || at->_cw == at)
{
printf("ERROR AT refers to itself after insert\n");
}
#endif
return;
}
#if USE_MATH
static double round_per_R5RS(double x);
#endif
static int is_zero_double(double x);
static num num_zero;
static num num_one;
static inline const num& nvalue(pointer Ptr)
{
return Ptr->_object._number;
}
EXPORT int64_t i64value(pointer p)
{
return ivalue(p);
}
EXPORT int32_t i32value(pointer p)
{
return ivalue(p);
}
EXPORT int16_t i16value(pointer p)
{
return ivalue(p);
}
EXPORT int8_t i8value(pointer p)
{
return ivalue(p);
}
EXPORT bool i1value(scheme* _sc, pointer p)
{
return p == _sc->T;
}
EXPORT double r64value(pointer p)
{
return rvalue(p);
}
EXPORT float r32value(pointer p)
{
return rvalue(p);
}
#define ivalue_unchecked(p) (p)->_object._number.value.ivalue
#define rvalue_unchecked(p) (p)->_object._number.value.rvalue
#define ratvalue_unchecked(p) (p)->_object._number.value.ratvalue
#define set_integer(p) (p)->_object._number.num_type = T_INTEGER;
#define set_real(p) (p)->_object._number.num_type = T_REAL;
#define set_rational(p) (p)->_object._number.num_type = T_RATIONAL;
EXPORT long long charvalue(pointer p)
{
//if(!is_character(p)) _Error_1(sc, "Attempting to return a character from a non-character obj", p, sc->code->_debugger->_size);//[NSException raise:@"IncorrectSchemeOBJ" format:@"Attempting to return a character from a non-character obj"];
return ivalue_unchecked(p);
}
long long charvalue_sc(scheme* sc, pointer p)
{
if(!is_character(p)) _Error_1(sc, "Attempting to return a character from a non-character obj", p, sc->code->_debugger->_size);
return ivalue_unchecked(p);
}
#define is_inport(p) (type(p)==T_PORT && p->_object._port->kind&port_input)
#define is_outport(p) (type(p)==T_PORT && p->_object._port->kind&port_output)
pointer pair_car(pointer p)
{
if (!is_pair(p)) throw ScmRuntimeError("Attempting to access the car of a primitive",p);
return car(p);
}
pointer pair_car_sc(scheme* sc, pointer p)
{
if(!is_pair(p)) _Error_1(sc,"Attempting to access the car of a primitive",0,sc->code->_debugger->_size);
return car(p);
}
pointer pair_cdr(pointer p)
{
if(!is_pair(p)&&!is_continuation(p))
{
throw ScmRuntimeError("Attempting to access the cdr of a primitive",p);
}
return cdr(p);
}
// AS CHANGE TO CHECK VALIDITY OF P
char* symname(pointer p)
{
if(!is_symbol(p)) {
throw ScmRuntimeError("Attempting to return a string from non-symbol obj",p);
//[NSException raise:@"IncorrectSchemeOBJ" format:@"Attempting to return a string from non-symbol obj"];
}
return strvalue(car(p));
}
inline char* symname_sc(scheme* sc,pointer p)
{
if (unlikely(!is_symbol(p))) {
_Error_1(sc, "Attempting to return a string from non-symbol obj", p, sc->code->_debugger->_size);
}
return strvalue(car(p));
}
#if USE_PLIST
inline int hasprop(pointer p) { return (typeflag(p)&T_SYMBOL); }
#define symprop(p) cdr(p)
#endif
//int is_objc(pointer p) { return (type(p) == T_OBJC); }
EXPORT void* cptr_value(pointer p)
{
if(!is_cptr(p)) {
if(is_string(p)) return (void*) strvalue(p);
else throw ScmRuntimeError("Attempting to return a cptr from a non-cptr obj",p);
//[NSException raise:@"IncorrectSchemeOBJ" format:@"Attempting to return a cptr from a non-cptr obj"];
}
return p->_object._cptr;
}
void* cptr_value_sc(scheme* sc, pointer p)
{
if(!is_cptr(p)) {
if(!is_string(p)) {
_Error_1(sc, "Attempting to return a cptr from a non-cptr obj", p, sc->code->_debugger->_size);
}else{
return strvalue(p);
}
}
return p->_object._cptr;
}
inline char *syntaxname(pointer p) { return strvalue(car(p)); }
#define procnum(p) ivalue(p)
//const char *procname(pointer x);
static const char *opcodename(int opcode);
int is_closure(pointer p) { return (type(p)==T_CLOSURE); }
int is_macro(pointer p) { return (type(p)==T_MACRO); }
pointer closure_code(pointer p) { return car(p); }
pointer closure_env(pointer p) { return cdr(p); }
int is_continuation(pointer p) { return (type(p)==T_CONTINUATION); }
#define cont_dump(p) cdr(p)
/* To do: promise should be forced ONCE only */
int is_promise(pointer p) { return (type(p)==T_PROMISE); }
#define setenvironment(p) typeflag(p) = T_ENVIRONMENT
#define is_atom(p) (typeflag(p)&T_ATOM)
#define setatom(p) typeflag(p) |= T_ATOM
#define clratom(p) typeflag(p) &= CLRATOM
#define is_mark(p) (typeflag(p)&MARK)
#define setmark(p) typeflag(p) |= MARK
#define clrmark(p) typeflag(p) &= UNMARK
inline int is_immutable(pointer p) { return (typeflag(p)&T_IMMUTABLE); }
inline void setimmutable(pointer p) { typeflag(p) |= T_IMMUTABLE; }
#define caar(p) car(car(p))
#define cadr(p) car(cdr(p))
#define cdar(p) cdr(car(p))
#define cddr(p) cdr(cdr(p))
#define cadar(p) car(cdr(car(p)))
#define caddr(p) car(cdr(cdr(p)))
#define cadaar(p) car(cdr(car(car(p))))
#define cadddr(p) car(cdr(cdr(cdr(p))))
#define cddddr(p) cdr(cdr(cdr(cdr(p))))
#if USE_CHAR_CLASSIFIERS
static inline int Cisalpha(int c) { return isascii(c) && isalpha(c); }
static inline int Cisdigit(int c) { return isascii(c) && isdigit(c); }
static inline int Cisspace(int c) { return isascii(c) && isspace(c); }
static inline int Cisupper(int c) { return isascii(c) && isupper(c); }
static inline int Cislower(int c) { return isascii(c) && islower(c); }
#endif
#if USE_ASCII_NAMES
static const char *charnames[32]={
"nul",
"soh",
"stx",
"etx",
"eot",
"enq",
"ack",
"bel",
"bs",
"ht",
"lf",
"vt",
"ff",
"cr",
"so",
"si",
"dle",
"dc1",
"dc2",
"dc3",
"dc4",
"nak",
"syn",
"etb",
"can",
"em",
"sub",
"esc",
"fs",
"gs",
"rs",
"us"
};
static int is_ascii_name(const char *name, int *pc) {
int i;
for(i=0; i<32; i++) {
if(strcmp(name,charnames[i])==0) {
*pc=i;
return 1;
}
}
if(strcmp(name,"del")==0) {
*pc=127;
return 1;
}
return 0;
}
#endif
static int file_push(scheme *sc, const char *fname);
static void file_pop(scheme *sc);
static int file_interactive(scheme *sc);
static inline int is_one_of(const char *s, int c);
static int alloc_cellseg(scheme *sc, int n);
static long binary_decode(const char *s);
static inline pointer get_cell(scheme *sc, pointer a, pointer b);
static pointer _get_cell(scheme *sc, pointer a, pointer b);
static void finalize_cell(scheme *sc, pointer a);
EXPORT pointer mk_number(scheme *sc, const num& n);
EXPORT pointer mk_empty_string(scheme *sc, int len, char fill);
EXPORT char *store_string(scheme *sc, int len, const char *str, char fill);
static pointer mk_atom(scheme *sc, char *q);
static pointer mk_sharp_const(scheme *sc, char *name);
EXPORT pointer mk_port(scheme *sc, port *p);
static pointer port_from_filename(scheme *sc, const char *fn, int prop);
static pointer port_from_file(scheme *sc, FILE *, int prop);
static pointer port_from_string(scheme *sc, char *start, char *past_the_end, int prop);
static port *port_rep_from_filename(scheme *sc, const char *fn, int prop);
static port *port_rep_from_file(scheme *sc, FILE *, int prop);
static port *port_rep_from_string(scheme *sc, char *start, char *past_the_end, int prop);
static void port_close(scheme *sc, pointer p, int flag);
//static void mark(pointer a);
static void treadmill_mark_roots(scheme* sc, pointer a, pointer b);
static void* treadmill_scanner(void* obj);
static int basic_inchar(port *pt);
static int inchar(scheme *sc);
static void backchar(scheme *sc, int c);
static char *readstr_upto(scheme *sc, char *delim);
static pointer readstrexp(scheme *sc);
static inline void skipspace(scheme *sc);
static int token(scheme *sc);
static void printslashstring(scheme *sc, char *s, int len);
static void atom2str(scheme *sc, pointer l, int f, char **pp, int *plen);
static void printatom(scheme *sc, pointer l, int f);
static pointer mk_proc(scheme *sc, enum scheme_opcodes op);
//static pointer mk_closure(scheme *sc, pointer c, pointer e);
//pointer mk_continuation(scheme *sc);
/*
static void dump_stack_mark(scheme *);
*/
static pointer dump_stack_copy(scheme *sc);
static pointer opexe_0(scheme *sc, enum scheme_opcodes op);
static pointer opexe_1(scheme *sc, enum scheme_opcodes op);
static pointer opexe_2(scheme *sc, enum scheme_opcodes op);
static pointer opexe_3(scheme *sc, enum scheme_opcodes op);
static pointer opexe_4(scheme *sc, enum scheme_opcodes op);
static pointer opexe_5(scheme *sc, enum scheme_opcodes op);
static pointer opexe_6(scheme *sc, enum scheme_opcodes op);
static void Eval_Cycle(scheme *sc, enum scheme_opcodes op);
static void assign_syntax(scheme *sc, char *name);
static int syntaxnum(pointer p);
static void assign_proc(scheme *sc, enum scheme_opcodes, char *name);
static void treadmill_flip(scheme* sc, pointer a, pointer b);
pointer reverse(scheme *sc, pointer a);
pointer reverse_in_place(scheme *sc, pointer term, pointer list);
pointer append(scheme *sc, pointer a, pointer b);
int eqv(pointer a, pointer b);
int eqv_sc(scheme* sc, pointer a, pointer b);
static inline int64_t num_ivalue(const num& Val) {
if (likely(Val.num_type == T_INTEGER)) {
return Val.value.ivalue;
}
if (likely(Val.num_type == T_REAL)) {
return Val.value.rvalue;
}
return Val.value.ratvalue.n / Val.value.ratvalue.d;
}
static inline double num_rvalue(const num& Val) {
if (likely(Val.num_type == T_INTEGER)) {
return Val.value.ivalue;
}
if (likely(Val.num_type == T_REAL)) {
return Val.value.rvalue;
}
return double(Val.value.ratvalue.n) / Val.value.ratvalue.d;
}
static const num_type MY_ARR[] = { T_INTEGER, T_REAL, T_REAL, T_RATIONAL, T_REAL, T_INTEGER, T_RATIONAL };
static num num_add(const num& a, const num& b)
{
num ret;
ret.num_type = MY_ARR[a.num_type + b.num_type];
if (likely(ret.num_type == T_INTEGER)) {
ret.value.ivalue = a.value.ivalue + b.value.ivalue;
return ret;
}
if (likely(ret.num_type == T_REAL)) {
ret.value.rvalue = num_rvalue(a) + num_rvalue(b);
return ret;
}
if (a.num_type == T_INTEGER) {
ret.value.ratvalue.n = a.value.ivalue * b.value.ratvalue.d + b.value.ratvalue.n;
ret.value.ratvalue.d = b.value.ratvalue.d;
} else if (b.num_type == T_INTEGER) {
ret.value.ratvalue.n = b.value.ivalue * a.value.ratvalue.d + a.value.ratvalue.n;
ret.value.ratvalue.d = a.value.ratvalue.d;
} else {
ret.value.ratvalue.n = a.value.ratvalue.n * b.value.ratvalue.d + b.value.ratvalue.n * a.value.ratvalue.d;
ret.value.ratvalue.d = a.value.ratvalue.d * b.value.ratvalue.d;
}
return ret;
}
static num num_mul(const num& a, const num& b)
{
num ret;
ret.num_type = MY_ARR[a.num_type + b.num_type];
if (likely(ret.num_type == T_INTEGER)) {
ret.value.ivalue = a.value.ivalue * b.value.ivalue;
return ret;
}
if (likely(ret.num_type == T_REAL)) {
ret.value.rvalue = num_rvalue(a) * num_rvalue(b);
return ret;
}
if (a.num_type == T_INTEGER) {
ret.value.ratvalue.n = a.value.ivalue * b.value.ratvalue.n;
ret.value.ratvalue.d = b.value.ratvalue.d;
} else if (b.num_type == T_INTEGER) {
ret.value.ratvalue.n = b.value.ivalue * a.value.ratvalue.n;
ret.value.ratvalue.d = a.value.ratvalue.d;
} else {
ret.value.ratvalue.n = a.value.ratvalue.n * b.value.ratvalue.n;
ret.value.ratvalue.d = a.value.ratvalue.d * b.value.ratvalue.d;
}
return ret;
}
static num num_div(const num& a, const num& b)
{
num ret;
ret.num_type = MY_ARR[a.num_type + b.num_type];
if (likely(ret.num_type == T_INTEGER)) {
if (unlikely(!(a.value.ivalue % b.value.ivalue))) {
ret.value.ivalue = a.value.ivalue / b.value.ivalue;
return ret;
}
ret.num_type = T_RATIONAL;
ret.value.ratvalue.n = a.value.ivalue;
ret.value.ratvalue.d = b.value.ivalue;
return ret;
}
if (likely(ret.num_type == T_REAL)) {
ret.value.rvalue = num_rvalue(a) / num_rvalue(b);
return ret;
}
if (a.num_type == T_INTEGER) {
ret.value.ratvalue.n = a.value.ivalue * b.value.ratvalue.d;
ret.value.ratvalue.d = b.value.ratvalue.n;
} else if (b.num_type == T_INTEGER) {
ret.value.ratvalue.n = a.value.ratvalue.n;
ret.value.ratvalue.d = b.value.ivalue * a.value.ratvalue.d;
} else {
ret.value.ratvalue.n = a.value.ratvalue.n * b.value.ratvalue.d;
ret.value.ratvalue.d = a.value.ratvalue.d * b.value.ratvalue.n;
}
return ret;
}
static num num_bitnot(const num& a)
{
num ret;
ret.num_type = a.num_type;
if (likely(ret.num_type == T_INTEGER)) {
ret.value.ivalue = ~a.value.ivalue;
return ret;
}
ret.num_type = T_INTEGER;
ret.value.ivalue= ~num_ivalue(a);
return ret;
}
#define BBOP(NAME, OP) \
static num num_bit ## NAME(const num& a, const num& b) { \
num ret; \
ret.num_type = MY_ARR[a.num_type + b.num_type]; \
if (likely(ret.num_type == T_INTEGER)) { \
ret.value.ivalue = a.value.ivalue OP b.value.ivalue; \
return ret; \
} \
ret.num_type = T_INTEGER; \
ret.value.ivalue = num_ivalue(a) OP num_ivalue(b); \
return ret; \
}
BBOP(and, &)
BBOP(or, |)
BBOP(eor, ^)
BBOP(lsl, <<)
BBOP(lsr, >>)
static num num_intdiv(const num& a, const num& b)
{
num ret;
ret.num_type = MY_ARR[a.num_type + b.num_type];
if (likely(ret.num_type == T_INTEGER)) {
ret.value.ivalue = a.value.ivalue / b.value.ivalue;
return ret;
}
ret.num_type = T_INTEGER;
ret.value.ivalue = int64_t(num_rvalue(a) / num_rvalue(b));
return ret;
}
static num num_sub(const num& a, const num& b)
{
num ret;
ret.num_type = MY_ARR[a.num_type + b.num_type];
if (likely(ret.num_type == T_INTEGER)) {
ret.value.ivalue = a.value.ivalue - b.value.ivalue;
return ret;
}
if (likely(ret.num_type == T_REAL)) {
ret.value.rvalue = num_rvalue(a) - num_rvalue(b);
return ret;
}
if (a.num_type == T_INTEGER) {
ret.value.ratvalue.n = a.value.ivalue * b.value.ratvalue.d - b.value.ratvalue.n;
ret.value.ratvalue.d = b.value.ratvalue.d;
} else if(b.num_type == T_INTEGER) {
ret.value.ratvalue.n = a.value.ratvalue.n - b.value.ivalue * a.value.ratvalue.d;
ret.value.ratvalue.d = a.value.ratvalue.d;
} else {
ret.value.ratvalue.n = a.value.ratvalue.n * b.value.ratvalue.d - b.value.ratvalue.n * a.value.ratvalue.d;
ret.value.ratvalue.d = a.value.ratvalue.d * b.value.ratvalue.d;
}
return ret;
}
static num num_rem(const num& a, const num& b)
{
num ret;
ret.num_type = T_INTEGER;
auto e1 = num_ivalue(a);
auto e2 = num_ivalue(b);
auto res = e1 % e2;
/* modulo should have same sign as second operand */
if (res > 0) {
if (e1 < 0) {
res -= std::llabs(e2);
}
} else if (res < 0) {
if (e1 > 0) {
res += std::llabs(e2);
}
}
ret.value.ivalue = res;
return ret;
}
static num num_mod(const num& a, const num& b)
{
num ret;
ret.num_type = MY_ARR[a.num_type + b.num_type];
if (likely(ret.num_type == T_INTEGER)) {
auto e1 = num_ivalue(a);
auto e2 = num_ivalue(b);
auto res = e1 % e2;
if (res * e2 < 0) { /* modulo should have same sign as second operand */ // TODO: NOT FOR MODUL
if (res > 0) {
res -= std::llabs(e2);
} else {
res += std::llabs(e2);
}
}
ret.value.ivalue = res;
return ret;
}
if (likely(ret.num_type == T_REAL)) {
ret.value.rvalue = fmod(num_rvalue(a), num_rvalue(b));
return ret;
}
ret = num_div(a, b);
ret.value.ratvalue.n = ret.value.ratvalue.n % ret.value.ratvalue.d;
return num_mul(b, ret);
return ret;
}
static int num_eq(const num& a, const num& b)
{
auto type(MY_ARR[a.num_type + b.num_type]);
if (likely(type == T_INTEGER)) {
return a.value.ivalue == b.value.ivalue;
}
if (likely(type == T_REAL)) {
return num_rvalue(a) == num_rvalue(b);
}
if (b.num_type == T_INTEGER) {
return a.value.ratvalue.d * b.value.ivalue == a.value.ratvalue.n;
}
if (a.num_type == T_INTEGER) {
return b.value.ratvalue.d * a.value.ivalue == b.value.ratvalue.n;
}
return a.value.ratvalue.n == b.value.ratvalue.n && a.value.ratvalue.d == b.value.ratvalue.d;
}
static int num_gt(const num& a, const num& b)
{
if (a.num_type == T_INTEGER && b.num_type == T_INTEGER) {
return a.value.ivalue > b.value.ivalue;
}
return num_rvalue(a) > num_rvalue(b);
}
static int num_le(const num& a, const num& b)
{
return !num_gt(a, b);
}
static int num_lt(const num& a, const num& b)
{
if (a.num_type == T_INTEGER && b.num_type == T_INTEGER) {
return a.value.ivalue < b.value.ivalue;
}
return num_rvalue(a) < num_rvalue(b);
}
static int num_ge(const num& a, const num& b)
{
return !num_lt(a, b);
}
#if USE_MATH
/* Round to nearest. Round to even if midway */
static double round_per_R5RS(double x) {
double fl=floor(x);
double ce=ceil(x);
double dfl=x-fl;
double dce=ce-x;
if(dfl>dce) {
return ce;
} else if(dfl<dce) {
return fl;
} else {
if(fmod(fl,2.0)==0.0) { /* I imagine this holds */
return fl;
} else {
return ce;
}
}
}
#endif
static int is_zero_double(double x) {
return x<DBL_MIN && x>-DBL_MIN;
}
static long binary_decode(const char *s) {
long x=0;
while(*s!=0 && (*s=='1' || *s=='0')) {
x<<=1;
x+=*s-'0';
s++;
}
return x;
}
/* allocate new cell segment */
static int alloc_cellseg(scheme *sc, int n) {
pointer newp;
pointer last;
pointer p;
char *cp;
long i;
int k;
int adj=ADJ;
if(adj<sizeof(struct cell)) {
adj=sizeof(struct cell);
}
//std::cout << "ALLOCATE MEMORY: " << sc->last_cell_seg << std::endl;
//std::cout << "FCELLS: " << sc->fcells << std::endl;
for (k = 0; k < n; k++) {
if (sc->last_cell_seg >= CELL_NSEGMENT - 1)
return k;
cp = (char*) sc->malloc(CELL_SEGSIZE * sizeof(struct cell)+adj);
if (cp == 0)
return k;
i = ++sc->last_cell_seg ;
sc->alloc_seg[i] = cp;
/* adjust in TYPE_BITS-bit boundary */
//if(( *((unsigned*)cp) )%adj!=0) {
// cp=(char*)(adj*((long)cp/adj+1));
//}
/* insert new segment in address order */
newp=(pointer)cp;
// std::cout << "ALLOCATING MEM IN PROCESS: " << extemp::SchemeProcess::I(sc)->getName() << std::endl;
//printf("Alloced Memory[%d]: 0x%" PRIXPTR ":0x%" PRIXPTR " 0x%" PRIXPTR ":0x%" PRIXPTR "\n",i,(uintptr_t)&newp[0],(uintptr_t)&newp[CELL_SEGSIZE],(uintptr_t)cp,(uintptr_t)(cp+(CELL_SEGSIZE * sizeof(struct cell))));
//printf("Alloced Memory[%d]: %" PRIuPTR ":%" PRIuPTR " %" PRIuPTR ":%" PRIuPTR "\n",i,(uintptr_t)&newp[0],(uintptr_t)&newp[CELL_SEGSIZE],(uintptr_t)cp,(uintptr_t)(cp+(CELL_SEGSIZE * sizeof(struct cell))));
sc->cell_seg[i] = newp;
while (i > 0 && sc->cell_seg[i - 1] > sc->cell_seg[i]) {
p = sc->cell_seg[i];
sc->cell_seg[i] = sc->cell_seg[i - 1];
sc->cell_seg[--i] = p;
}
// sc->fcells += CELL_SEGSIZE;
last = newp + CELL_SEGSIZE - 1;
//sc->NIL = newp;
int k=0;
for (p = newp; p <= last; p++, k++) {
typeflag(p) = 0;
p->_colour = !sc->dark; // initially set all cells to light
#ifdef TREADMILL_CHECKS
p->_list_colour = 1; //all ecru
#endif
cdr(p) = 0; //sc->NIL; //(p==last) ? p + 1 : newp;
car(p) = 0; //sc->NIL;
//added to alloc
//p->_colour = (k<100000) ? 0 : 1;
(p)->_cw = (p==last) ? newp : p+1;
(p)->_ccw = (p==newp) ? last : p-1;
}
}
sc->total_memory_allocated = CELL_SEGSIZE;
//added to alloc
sc->starting_cell = newp;
sc->treadmill_free = newp;
sc->treadmill_top = sc->treadmill_free->_ccw;
sc->treadmill_scan = sc->treadmill_top;
//sc->treadmill_scan->_colour = sc->dark;
pointer ttt = sc->treadmill_free;
// sc->fcells = 0;
for(int i=0;i<(CELL_SEGSIZE/2);i++)
{
ttt->_colour = !sc->dark;
#ifdef TREADMILL_CHECKS
ttt->_list_colour = 0;
#endif
// sc->fcells++;
ttt = ttt->_cw;
}
sc->treadmill_bottom = ttt; //sc->treadmill_free + (CELL_SEGSIZE/2);//100000;
//std::cout << sc->fcells << " number of free cells" << std::endl;
#ifdef TREADMILL_CHECKS
//printf("////////////// SANITY CHECK TREADMILL AFTER ALLOCATION /////////////\n");
if(sc->treadmill_bottom->_ccw->_list_colour != 0)
{
printf("_CCW OF BOTTOM SHOULD BE FREE CELL!\n");
}
if(sc->treadmill_top != sc->treadmill_scan)
{
printf("SCAN & TOP SHOULD BE AT THE SAME LOCATION!!\n");
}
if(sc->treadmill_scan->_cw != sc->treadmill_free)
{
printf("FREE SHOULD BE _CW of SCAN\n");
}
if(sc->treadmill_top->_list_colour != sc->treadmill_scan->_list_colour != sc->treadmill_bottom->_list_colour != 1)
{
printf("SCAN & TOP & BOTTOM SHOULD BE ECRU!\n");
}
if(sc->treadmill_free->_list_colour != 0)
{
printf("FREE SHOULD BE WHITE!!\n");
}
//check no gaps between ecru cells
pointer ecru_check = sc->treadmill_bottom;
int ecrus = 0;
while(ecru_check != sc->treadmill_free){
if(ecru_check->_list_colour != 1)
{
printf("Should have complete list of ecrus between BOTTOM and FREE moving clockwise! Catastrophic error in GC\n");
}
ecrus++;
ecru_check = ecru_check->_cw;
}
//check no gaps between free cells
pointer free_check = sc->treadmill_free;
int frees = 0;
while(free_check != sc->treadmill_bottom){
if(free_check->_list_colour != 0)
{
printf("Should have complete list of frees between free and bottom moving clockwise! Catastrophic error in GC\n");
}
frees++;
free_check = free_check->_cw;
}
//if(frees+ecrus != CELL_SEGSIZE)
//{
//printf("FREES(%d) ECRUS(%d) TOTAL(%d) CELLSEG(%lld)\n",frees,ecrus,frees+ecrus,sc->total_memory_allocated);
//}
//printf("------------- FINISHED SANITY CHECK TREADMILL AFTER ALLOCATION ---------------\n");
#endif
char str[256];
// sprintf(str,"Allocated: %d cell segements for a total of %d. Free cells = %lld",n,sc->last_cell_seg,sc->fcells);
//sprintf(str,"Allocated: %d cell segments for a total of %d.",n,sc->last_cell_seg);
//CPPBridge::notification(str);
//std::cout << "Allocated: " << n << " Cell Segments For A Total Of " << sc->last_cell_seg << ", Free Cells = " << sc->fcells << std::endl;
return n;
}
static inline pointer get_cell(scheme* Scheme, pointer A, pointer B)
{
if (unlikely(Scheme->treadmill_free == Scheme->treadmill_bottom)) {
//std::cout << "START FLIP FROM GET_CELL " << Scheme << std::endl;
treadmill_flip(Scheme, A, B);
//std::cout << "FINISHED FLIP FROM GET_CELL " << Scheme << std::endl;
// if(Scheme->fcells<=0) { // if even after flip we have no free cells
// std::cout << "Out of memory!!. Catastrophic error!! free cells: " << Scheme->fcells << std::endl;
// exit(0);
// }
}
auto x(Scheme->treadmill_free);
#ifdef TREADMILL_CHECKS
if (x->_list_colour) {
_Error_1(Scheme, "Cell is not empty. Catastrophic error in GC", Scheme->NIL,0);
//printf("Error: cell is not empty");
}
#endif
finalize_cell(Scheme, x);
typeflag(x) = 0;
car(x) = Scheme->NIL;
cdr(x) = Scheme->NIL;
//////////////// these for debugger //////////////////
x->_debugger = Scheme->NIL; // might not need this?
x->_size = 0; // or this?
///////////////////////////////////////////////////////
Scheme->treadmill_free = Scheme->treadmill_free->_cw;
x->_colour = Scheme->dark;
#ifdef TREADMILL_CHECKS
x->_list_colour = 3; // black
#endif
// --Scheme->fcells;
return x;
}
/* get new cons cell */
pointer _cons(scheme *sc, pointer a, pointer b, int immutable) {
pointer x = get_cell(sc,a, b);
typeflag(x) = T_PAIR;
if(immutable) {
setimmutable(x);
}
////////////// write barrier for treadmill
if(a->_colour != sc->dark)
{
//std::cout << "INSERT FROM CONS: " << a << " " << (int)a->_colour << " != " << sc->dark << std::endl << std::flush;
#ifdef TREADMILL_CHECKS
last_call_to_insert_treadmill = 1;
#endif
insert_treadmill(sc,a);
}
if(b->_colour != sc->dark)
{
#ifdef TREADMILL_CHECKS
last_call_to_insert_treadmill = 2;
#endif
insert_treadmill(sc,b);
}
//////////////////////////////////////////
car(x) = a;
cdr(x) = b;
return (x);
}
/* ========== oblist implementation ========== */
static int hash_fn(const char *key, int table_size);
static pointer oblist_initial_value(scheme *sc)
{
return mk_vector(sc, 65521);
}
/* returns the new symbol */
static pointer oblist_add_by_name(scheme *sc, const char *name)
{
pointer x;
int location;
x = immutable_cons(sc, mk_string(sc, name), sc->NIL);
typeflag(x) = T_SYMBOL;
setimmutable(car(x));
location = hash_fn(name, sc->oblist->_size);
set_vector_elem(sc, sc->oblist, location,
immutable_cons(sc, x, vector_elem(sc->oblist, location)));
return x;
}
static inline pointer oblist_find_by_name(scheme *sc, const char *name)
{
int location;
pointer x;
char *s;
location = hash_fn(name, sc->oblist->_size); //ivalue_unchecked(sc->oblist));
for (x = vector_elem(sc->oblist, location); x != sc->NIL; x = cdr(x)) {
s = symname_sc(sc,car(x));
/* case-insensitive, per R5RS section 2. */
if(strcmp(name, s) == 0) {
return car(x);
}
}
return sc->NIL;
}
static pointer oblist_all_symbols(scheme *sc)
{
int i;
pointer x;
pointer ob_list = sc->NIL;
for (i = 0; i < sc->oblist->_size; i++) {
for (x = vector_elem(sc->oblist, i); x != sc->NIL; x = cdr(x)) {
ob_list = cons(sc, x, ob_list);
}
}
return ob_list;
}
EXPORT pointer mk_port(scheme *sc, port *p) {
pointer x = get_cell(sc, sc->NIL, sc->NIL);
typeflag(x) = T_PORT|T_ATOM;
x->_object._port=p;
return (x);
}
EXPORT pointer mk_foreign_func(scheme *sc, foreign_func f) {
pointer x = get_cell(sc, sc->NIL, sc->NIL);
typeflag(x) = (T_FOREIGN | T_ATOM);
x->_object._ff=f;
return (x);
}
EXPORT pointer mk_cptr(scheme *sc, void* p) {
pointer x = get_cell(sc, sc->NIL, sc->NIL);
typeflag(x) = (T_CPTR | T_ATOM);
x->_object._cptr = p;
return (x);
}
int retained = 0;
EXPORT pointer mk_character(scheme *sc, int c) {
pointer x = get_cell(sc,sc->NIL, sc->NIL);
typeflag(x) = (T_CHARACTER | T_ATOM);
ivalue_unchecked(x)= c;
set_integer(x);
return (x);
}
/* get number atom (integer) */
EXPORT pointer mk_integer(scheme* Scheme, long long Num) {
pointer x = get_cell(Scheme, Scheme->NIL, Scheme->NIL);
//std::cout << "NUM: " << Num << " :: " << sizeof(long) << " :: " << sizeof(int) << std::endl;
typeflag(x) = T_NUMBER | T_ATOM;
ivalue_unchecked(x) = Num;
set_integer(x);
//std::cout << "NUM2: " << ivalue(x) << std::endl;
return x;
}
EXPORT pointer mk_i64(scheme *sc, long long num) {
return mk_integer(sc, num);
}
EXPORT pointer mk_i32(scheme *sc, int num) {
return mk_integer(sc, num);
}
EXPORT pointer mk_i16(scheme *sc, short num) {
return mk_integer(sc, (int)num);
}
EXPORT pointer mk_i8(scheme *sc, char num) {
return mk_integer(sc, num);
}
EXPORT pointer mk_i1(scheme *sc, bool num) {
return mk_integer(sc, num);
}
EXPORT pointer mk_real(scheme *sc, double n) {
pointer x = get_cell(sc, sc->NIL, sc->NIL);
typeflag(x) = (T_NUMBER | T_ATOM);
rvalue_unchecked(x) = n;
set_real(x);
return (x);
}
EXPORT pointer mk_double(scheme* sc, double n) {
return mk_real(sc, n);
}
EXPORT pointer mk_float(scheme* sc, float n) {
return mk_real(sc, (double) n);
}
int64_t gcd(int64_t a, int64_t b)
{
while (b) {
auto r(a % b);
a = b;
b = r;
}
return a;
}
EXPORT pointer mk_rational(scheme *sc, long long n, long long d) {
if(d==0) {
_Error_1(sc,"Cannot make rational with 0 denominator",sc->NIL,sc->code->_size);
return sc->NIL;
}
pointer x = get_cell(sc,sc->NIL, sc->NIL);
if(n==0) { // return integer 0
typeflag(x) = (T_NUMBER | T_ATOM);
ivalue_unchecked(x)=0;
set_integer(x);
}else{
auto _gcd = gcd(n, d);
typeflag(x) = (T_NUMBER | T_ATOM);
//NSLog(@"MKRAT: %d %d",n,d);
ratvalue_unchecked(x).n=n/_gcd;
ratvalue_unchecked(x).d=d/_gcd;
//std::cout << "MK_RATIONAL: " << ratvalue_unchecked(x).n << "/" << ratvalue_unchecked(x).d << std::endl << std::flush;
set_rational(x);
}
return (x);
}
EXPORT pointer mk_number(scheme *sc, const num& n) {
if (likely(n.num_type == T_INTEGER)) {
return mk_integer(sc, n.value.ivalue);
}
if (likely(n.num_type == T_REAL)) {
return mk_real(sc,n.value.rvalue);
}
if (likely(n.num_type == T_RATIONAL)) {
return mk_rational(sc, n.value.ratvalue.n, n.value.ratvalue.d);
}
return sc->NIL;
}
/* allocate name to string area */
EXPORT char* store_string(scheme *sc, int len_str, const char *str, char fill)
{
auto q = reinterpret_cast<char*>(sc->malloc(len_str + 1));
if (unlikely(!q)) {
sc->no_memory = 1;
return sc->strbuff;
}
if (str) {
strcpy(q, str);
} else {
memset(q, fill, len_str);
q[len_str] = '\0';
}
return q;
}
/* get new string */
EXPORT pointer mk_string(scheme *sc, const char *str) {
if(str == 0) str = "";
return mk_counted_string(sc,str,strlen(str));
}
EXPORT pointer mk_counted_string(scheme *sc, const char *str, int len) {
pointer x = get_cell(sc, sc->NIL, sc->NIL);
strvalue(x) = store_string(sc,len,str,0);
typeflag(x) = (T_STRING | T_ATOM);
strlength(x) = len;
return (x);
}
EXPORT pointer mk_empty_string(scheme *sc, int len, char fill) {
pointer x = get_cell(sc, sc->NIL, sc->NIL);
strvalue(x) = store_string(sc,len,0,fill);
typeflag(x) = (T_STRING | T_ATOM);
strlength(x) = len;
return (x);
}
EXPORT pointer mk_vector(scheme *sc, int len) {
pointer x = get_cell(sc, sc->NIL, sc->NIL);
typeflag(x) = (T_VECTOR | T_ATOM);
x->_size = len;
x->_object._cptr = (char*) sc->malloc(len * sizeof(pointer));
sc->allocation_request += len;
//std::cout << "POINTER: " << x << " CPTR: " << x->_object._cptr << std::endl;
//ivalue_unchecked(x)=len;
//set_integer(x);
fill_vector(sc,x,sc->NIL);
return x;
}
EXPORT void fill_vector(scheme* sc, pointer vec, pointer obj) {
int i;
int num = vec->_size;
pointer* cptr = (pointer*) vec->_object._cptr;
////////////// write barrier for treadmill
#ifdef TREADMILL_CHECKS
last_call_to_insert_treadmill = 3;
#endif
insert_treadmill(sc,obj);
//////////////////////////////////////////
for(i=0; i<num; i++) {
cptr[i] = obj;
}
}
/* get new symbol */
EXPORT pointer mk_symbol(scheme *sc, const char *name) {
//
// if(sc->inport != sc->NIL && sc->inport->_object._port->kind&port_string) {
// int position = 0;
// char* ptr = sc->inport->_object._port->rep.string.start;
// for( ; &ptr[position] < &sc->inport->_object._port->rep.string.curr[0]; position++);
// int lgth = strlen(name);
// std::cout << "sym:" << name << " pos:" << (position-lgth) << " lgth:" << lgth << std::endl; //" start:" << &sc->inport->_object._port->rep.string.start[0] << " curr:" << &sc->inport->_object._port->rep.string.curr[0] << std::endl;
// }
//
pointer x;
/* first check oblist */
x = oblist_find_by_name(sc, name);
if (x != sc->NIL) {
return (x);
} else {
x = oblist_add_by_name(sc, name);
return (x);
}
}
//impromtpu's evil gensym for making uninterned symbols
pointer gensym(scheme *sc) {
pointer x;
char name[40];
sc->gensym_cnt++;
if(sc->gensym_cnt>10000000) sc->gensym_cnt = 0;
sprintf(name,"gensym-%ld",sc->gensym_cnt);
//printf("gensym %s\n",name);
x = immutable_cons(sc, mk_string(sc, name), sc->NIL);
typeflag(x) = T_SYMBOL;
setimmutable(car(x));
return (x);
}
/* make symbol or number atom from string */
static pointer mk_atom(scheme *sc, char *q) {
char c, *p;
char *ratn, *ratd; //added by as for rational numbers support
int has_dec_point=0;
int has_rational=0;
int has_fp_exp = 0;
#if USE_COLON_HOOK
if((p=strstr(q,"::"))!=0) {
*p=0;
return cons(sc, sc->COLON_HOOK,
cons(sc,
cons(sc,
sc->QUOTE,
cons(sc, mk_atom(sc,p+2), sc->NIL)),
cons(sc, mk_symbol(sc,strlwr(q)), sc->NIL)));
}
#endif
ratn = q;
p = q;
c = *p++;
if ((c == '+') || (c == '-')) {
c = *p++;
if (c == '.') {
has_dec_point=1;
c = *p++;
}
if (!isdigit(c)) {
return (mk_symbol(sc, strlwr(q)));
}
} else if (c == '.') {
has_dec_point=1;
c = *p++;
if (!isdigit(c)) {
return (mk_symbol(sc, strlwr(q)));
}
}else if (c == 0) {
return sc->NIL;
} else if (!isdigit(c)) {
return (mk_symbol(sc, strlwr(q)));
}
for ( ; (c = *p) != 0; ++p) {
if (!isdigit(c)) {
if(c=='.') {
if(!has_dec_point) {
has_dec_point=1;
continue;
}
}
if(c=='/') {
if(!has_rational) {
has_rational=1;
ratd = p;
ratd++;
continue;
}
}
else if ((c == 'e') || (c == 'E')) {
if(!has_fp_exp) {
has_dec_point = 1; /* decimal point illegal
from now on */
p++;
if ((*p == '-') || (*p == '+') || isdigit(*p)) {
continue;
}
}
}
return (mk_symbol(sc, strlwr(q)));
}
}
if (has_dec_point) {
return mk_real(sc, atof(q));
}
if (has_rational) {
//std::cout << "N: " << atoll(ratn) << " D: " << atoll(ratd) << std::endl;
return mk_rational(sc,atoll(ratn),atoll(ratd));
}
return (mk_integer(sc, atoll(q)));
}
/* make constant */
static pointer mk_sharp_const(scheme *sc, char *name) {
long x;
char tmp[256];
if (!strcmp(name, "t"))
return (sc->T);
else if (!strcmp(name, "f"))
return (sc->F);
else if (*name == 'o') {/* #o (octal) */
sprintf(tmp, "0%s", name+1);
sscanf(tmp, "%lo", &x);
return (mk_integer(sc, x));
} else if (*name == 'd') { /* #d (decimal) */
sscanf(name+1, "%ld", &x);
return (mk_integer(sc, x));
} else if (*name == 'x') { /* #x (hex) */
sprintf(tmp, "0x%s", name+1);
sscanf(tmp, "%lx", &x);
return (mk_integer(sc, x));
} else if (*name == 'b') { /* #b (binary) */
x = binary_decode(name+1);
return (mk_integer(sc, x));
} else if (*name == '\\') { /* #\w (character) */
int c=0;
if(strcmp(name+1,"space")==0) {
c=' ';
} else if(strcmp(name+1,"newline")==0) {
c='\n';
} else if(strcmp(name+1,"return")==0) {
c='\r';
} else if(strcmp(name+1,"tab")==0) {
c='\t';
} else if(name[1]=='x' && name[2]!=0) {
int c1=0;
if(sscanf(name+2,"%x",&c1)==1 && c1<256) {
c=c1;
} else {
return sc->NIL;
}
#if USE_ASCII_NAMES
} else if(is_ascii_name(name+1,&c)) {
/* nothing */
#endif
} else if(name[2]==0) {
c=name[1];
} else {
return sc->NIL;
}
return mk_character(sc,c);
} else
return (sc->NIL);
}
struct dump_stack_frame {
enum scheme_opcodes op;
pointer args;
pointer envir;
pointer code;
};
static void treadmill_mark_roots(scheme* sc, pointer a, pointer b) {
#ifdef TREADMILL_DEBUG
std::cout << "TREADMILL: MARK ROOTS" << std::endl;// top:" << sc->treadmill_top << " scan: " << sc->treadmill_scan << " bottom:" << sc->treadmill_bottom << " scan: " << sc->treadmill_scan << std::endl;
#endif
sc->mutex->lock();
#ifdef TREADMILL_CHECKS
last_call_to_insert_treadmill = 5;
#endif
insert_treadmill(sc, sc->oblist);
insert_treadmill(sc, sc->global_env);
insert_treadmill(sc, sc->args);
insert_treadmill(sc, sc->envir);
insert_treadmill(sc, sc->code);
intptr_t nframes = (intptr_t)sc->dump;
int i;
for(i=0; i<nframes; i++) {
struct dump_stack_frame *frame;
frame = (struct dump_stack_frame *)sc->dump_base + i;
insert_treadmill(sc,frame->args);
insert_treadmill(sc,frame->envir);
insert_treadmill(sc,frame->code);
}
insert_treadmill(sc, sc->tmp_dump);
insert_treadmill(sc, sc->value);
insert_treadmill(sc, sc->inport);
insert_treadmill(sc, sc->save_inport);
insert_treadmill(sc, sc->outport);
insert_treadmill(sc, sc->loadport);
insert_treadmill(sc, sc->T);
insert_treadmill(sc, sc->F);
insert_treadmill(sc, sc->NIL);
insert_treadmill(sc, sc->EOF_OBJ);
insert_treadmill(sc, sc->sink);
insert_treadmill(sc, a);
insert_treadmill(sc, b);
/* mark pointers */
for (auto pointer : sc->imp_env) {
insert_treadmill(sc, pointer);
}
sc->mutex->unlock();
#ifdef TREADMILL_DEBUG
std::cout << "TREADMILL FINISHED MARKING ROOTS" << std::endl;
#endif
return;
}
static void treadmill_flip(scheme* sc,pointer a,pointer b)
{
#ifdef TREADMILL_DEBUG
std::cout << "TREADMILL: FLIP " << pthread_self() << std::endl << std::flush;
#endif
sc->treadmill_flip_active = true;
while(!sc->treadmill_scanner_finished)// sc->treadmill_scan != sc->treadmill_top)
{
#ifdef TREADMILL_DEBUG
std::cout << "TREADMILL: FLIP SPINNING" << std::endl << std::flush;
#endif
#ifdef _WIN32
std::this_thread::sleep_for(std::chrono::microseconds(50));
#else
usleep(50);
#endif
}
#ifdef TREADMILL_DEBUG
std::cout << "TREADMILL: FINISHSED SPINNING - ON WITH THE WORK" << std::endl << std::flush;
#endif
#ifdef TREADMILL_CHECKS
//std::cout << "START FLIP******************************************************************************************* Scheme Instance:" << sc << std::endl << std::flush;
///////////////////////////////////////////////////////////////////////
//////////////////////////////////////////////////////////////////////
// Some very basic sanity checking
//printf("==============FLIP SANITY CHECKS====================\n");
if(sc->treadmill_top != sc->treadmill_scan) {
printf("Top & Scan must match! Catastrophic error in GC\n");
}
if(sc->treadmill_bottom != sc->treadmill_free) {
printf("Bottom & Free must match! Catastrophic error in GC\n");
}
if(sc->treadmill_top->_list_colour != 1 || sc->treadmill_bottom->_list_colour != 1 || sc->treadmill_scan->_list_colour != 1 || sc->treadmill_free->_list_colour != 1)
{
printf("COLOUR MISMATCH TOP(%d) FREE(%d) SCAN(%d) BOTTOM(%d)\n",sc->treadmill_top->_list_colour,sc->treadmill_free->_list_colour,sc->treadmill_scan->_list_colour,sc->treadmill_bottom->_list_colour);
}
if(sc->treadmill_top->_cw->_list_colour != 3 || sc->treadmill_scan->_cw->_list_colour != 3)
{
printf("Top & Scan should have black to clockwise! Catastrophic error in GC\n");
}
if(sc->treadmill_bottom->_ccw->_list_colour != 3 || sc->treadmill_free->_ccw->_list_colour != 3)
{
printf("Bottom & Free should have black to counter clockwise! Catastrophic error in GC\n");
}
//check no gaps between ecru cells
pointer ecru_check = sc->treadmill_top;
long long ecruscells = 0;
while(ecru_check != sc->treadmill_bottom->_ccw){
if(ecru_check->_list_colour != 1)
{
printf("Should have complete list of ecrus between TOP and BOTTOM moving counter clockwise! Catastrophic error in GC\n");
}
ecruscells++;
ecru_check = ecru_check->_ccw;
}
//check no gaps between black cells
long long blacks = 0;
pointer black_check = sc->treadmill_bottom->_ccw;
while(black_check != sc->treadmill_top){
if(black_check->_list_colour != 3)
{
printf("Should have complete list of blacks between BOTTOM and TOP moving counter clockwise! Catastrophic error in GC\n");
}
blacks++;
black_check = black_check->_ccw;
}
//printf("BLACKS(%lld) ECRUS(%lld) TOTAL(%lld) SEGSIZE(%lld)\n",blacks,ecruscells,blacks+ecruscells,sc->total_memory_allocated);
//printf("-----------------DONE FLIP SANITY CHECKS-----------------\n");
/////////////////////////////////////////////////////////////////////
///////////////////////////////////////////////////////////////////////
#endif
// flip dark
sc->dark = !sc->dark;
#ifdef TREADMILL_DEBUG
std::cout << "TREADMILL: FLIPPING DARK BIT TO: " << sc->dark << std::endl << std::flush;
#endif
#ifdef TREADMILL_CHECKS
// Sanity Check for _cw links
pointer ktt = sc->treadmill_top;
long long check = 0;
long long ecrus = 0;
while(true)
{
if(ktt->_list_colour == 0 || ktt->_list_colour == 2)
{
_Error_1(sc,"Shouldn't be any grey or white cells left at this stage! Catastrophic error in GC",sc->NIL,0);
}
if(ktt->_list_colour == 1) ecrus++;
ktt->_colour = !sc->dark;
ktt->_list_colour = 1; // set all cells to ecru
ktt = ktt->_cw;
check++;
if(ktt == sc->treadmill_top) break;
if(check>sc->total_memory_allocated)
{
_Error_1(sc,"Memory Map Has Changed in FLIP _cw. Catastrophic error in GC",sc->NIL,0);
}
}
if(check<sc->total_memory_allocated)
{
printf("CHECK _CW: %lld\n",check);
_Error_1(sc,"LOST Memory _cw. Catastrophic error in GC",sc->NIL,0);
}
// also check that all _ccw links are working
ktt = sc->treadmill_top;
check = 0;
while(true)
{
ktt = ktt->_ccw;
check++;
if(ktt == sc->treadmill_top) break;
if(check>sc->total_memory_allocated)
{
_Error_1(sc,"Memory Map Has Changed in FLIP _ccw. Catastrophic error in GC",sc->NIL,0);
}
}
if(check<sc->total_memory_allocated)
{
printf("CHECK _CCW: %lld\n",check);
_Error_1(sc,"LOST Memory _ccw. Catastrophic error in GC",sc->NIL,0);
}
#endif
sc->treadmill_bottom = sc->treadmill_top->_cw; //->_ccw;
sc->treadmill_top = sc->treadmill_free->_ccw; //t->_ccw; //sc->treadmill_free->_ccw; //tmp->_ccw;// sc->treadmill_scan->_ccw;
sc->treadmill_scan = sc->treadmill_top; //sc->treadmill_free->_ccw;
//sc->treadmill_scan->_colour = sc->dark;
//#ifdef TREADMILL_CHECKS
/////////////////////////////////////////////////////////////
//Sanity checks marking free cell colours
long long free_cells = 0;
pointer t = sc->treadmill_free;
#ifdef TREADMILL_CHECKS
for( ; t != sc->treadmill_bottom ; ++free_cells)
{
t->_list_colour = 0; //set ecrus to frees
t = t->_cw;
}
#endif
#ifdef TREADMILL_CHECKS
if(free_cells != ecrus)
{
printf("FREE CELLS: %lld OLD ECRUS: %lld\n",free_cells,ecrus);
_Error_1(sc, "Old Ecrus should match exactly to new free_cells!", sc->NIL,0);
}
#endif
#ifdef TREADMILL_DEBUG
std::cout << "TREADMILL: # FREE CELLS : " << free_cells << std::endl << std::flush;
#endif
//std::cout << "CELLS IN FREE LIST: " << free_cells << std::endl;
// sc->fcells = free_cells;
//if(sc->fcells < 20000 || (sc->fcells < (sc->allocation_request+20000)))
if(treadmill_inserts_per_cycle > ((sc->total_memory_allocated/2)-20000))
{
// sc->mutex->Lock(); // lock and don't unlock because we're totally broken :(
// std::cout << "TREADMILL: RUNNING OUT OF MEMORY!" << std::endl << std::flush;
// _Error_1(sc, "OUT OF MEMORY ERROR!!", sc->NIL, 0, 0);
// return;
//////////////////////////////////////////
// ADD NEW MEMORY
int adj=ADJ;
if(adj<sizeof(struct cell)) {
adj=sizeof(struct cell);
}
long long alloc_size = (sc->allocation_request>=0) ? sc->allocation_request : 100000;
char* newmem = (char*) sc->malloc(alloc_size * sizeof(struct cell)+adj);
if (newmem == 0) {
std::cout << "NO AVAILABLE MEMORY!" << std::endl;
exit(1);
}
sc->total_memory_allocated += alloc_size;
std::cout << "ALLOCATED NEW MEMORY: new_total(" << sc->total_memory_allocated << ")" << std::endl;
/* adjust in TYPE_BITS-bit boundary */
if(( *((unsigned*)newmem) )%adj!=0) {
newmem=(char*)(adj*((long)newmem/adj+1));
}
pointer first = (pointer) newmem;
pointer last = ((pointer) newmem)+(alloc_size-1);
long long k=0;
for (pointer p = first; k<alloc_size; p++, k++) {
typeflag(p) = 0;
p->_colour = !sc->dark; // initially set all cells to light
#ifdef TREADMILL_CHECKS
p->_list_colour = 0; //all white!
#endif
cdr(p) = 0; //sc->NIL; //(p==last) ? p + 1 : newp;
car(p) = 0; //sc->NIL;
if(p==last) {
sc->treadmill_bottom->_ccw = p;
}
if(p==first) {
sc->treadmill_bottom->_ccw->_cw = p;
}
(p)->_cw = (p==last) ? sc->treadmill_bottom : p+1;
(p)->_ccw = (p==first) ? sc->treadmill_bottom->_ccw : p-1;
}
// sc->fcells+=alloc_size;
}
sc->allocation_request = -1;
//#endif
/////////////////////////////////////////////////////////////////
treadmill_mark_roots(sc,a,b);
#ifdef TREADMILL_CHECKS
///////////////////////////////////////////////////////////////////////
//////////////////////////////////////////////////////////////////////
// Some very basic sanity checking
//printf("==============POST MARK SANITY CHECKS====================\n");
if(sc->treadmill_top->_list_colour != 1 || sc->treadmill_bottom->_list_colour != 1) {
printf("Top & Bottom must both be ecru! TOP(%d) BOTTOM(%d) Catastrophic error in GC\n",sc->treadmill_top->_list_colour,sc->treadmill_bottom->_list_colour);
}
if(sc->treadmill_top->_cw->_list_colour != 2)
{
printf("TOP _CW must be grey! TOP_CW(%d)\n",sc->treadmill_top->_cw->_list_colour);
}
if(sc->treadmill_bottom->_ccw->_list_colour != 0)
{
printf("BOTTOM _CCW must be pure white (free)\n");
}
if(sc->treadmill_free->_list_colour != 0)
{
printf("Free must be on a white cell\n");
}
if(sc->treadmill_scan->_list_colour != 2)
{
printf("Scan must be on a grey cell\n");
}
if(sc->treadmill_free->_ccw != sc->treadmill_scan && sc->treadmill_scan->_cw != sc->treadmill_free)
{
printf("Free and Scan must be next to each other\n");
}
//check no gaps between ecru cells
ecru_check = sc->treadmill_top;
ecrus = 0;
while(ecru_check != sc->treadmill_bottom->_ccw){
if(ecru_check->_list_colour != 1)
{
printf("Should have complete list of ecrus between TOP and BOTTOM moving counter clockwise! Catastrophic error in GC\n");
}
ecrus++;
ecru_check = ecru_check->_ccw;
}
//check no gaps between white cells
long long whites = 0;
pointer white_check = sc->treadmill_free; //sc->treadmill_bottom->_ccw;
pointer white_check_ccw = sc->treadmill_bottom->_ccw;
while(white_check != sc->treadmill_bottom){
if(white_check_ccw == sc->treadmill_free->_ccw)
{
printf("Should have complete list of whites between BOTTOM and FREE moving counter clockwise! (%lld) Catastrophic error in GC\n",whites);
}
if(white_check->_list_colour != 0)
{
printf("Should have complete list of whites between FREE and BOTTOM moving clockwise! (%lld) Catastrophic error in GC\n",whites);
}
whites++;
white_check = white_check->_cw;
white_check_ccw = white_check->_ccw;
}
//check no gaps between grey cells
long long greys = 0;
pointer grey_check = sc->treadmill_scan;
while(grey_check != sc->treadmill_top){
if(grey_check->_list_colour != 2)
{
printf("Should have complete list of whites between BOTTOM and FREE moving counter clockwise! Catastrophic error in GC\n");
}
greys++;
grey_check = grey_check->_ccw;
}
//printf("GREYS(%lld) WHITES(%lld) ECRUS(%lld) TOTAL(%lld) SEGSIZE(%lld)\n",greys,whites,ecrus,greys+whites+ecrus,sc->total_memory_allocated);
//printf("-----------------DONE FLIP SANITY CHECKS-----------------\n");
/////////////////////////////////////////////////////////////////////
///////////////////////////////////////////////////////////////////////
//std::cout << "FINISHED FLIP**********************************************************************************************************************************" << std::endl << std::flush;
#endif
treadmill_inserts_per_cycle=0;
sc->treadmill_flip_active = false;
//Treadmill_Guard.Unlock();
while(sc->treadmill_scanner_finished == true)
{
try{
sc->Treadmill_Guard->signal();
}catch( ... ) {
std::cout << "ERROR: SENDING NOTIFICATION TO SCANNER THREAD" << std::endl << std::flush;
}
#ifdef _WIN32
std::this_thread::sleep_for(std::chrono::microseconds(50));
#else
usleep(50);
#endif
#ifdef TREADMILL_DEBUG
std::cout << "SPINNING FLIP WAITING FOR NOTIFICATION" << std::endl << std::flush;
#endif
}
#ifdef TREADMILL_DEBUG
std::cout << "FINISHED WITH FLIP" << std::endl << std::flush;
#endif
return;
}
static void* treadmill_scanner(void* obj)
{
scheme* sc = (scheme*) obj;
int total_previous_scan = 0;
sc->mutex->lock();
while(true)
{
sc->treadmill_scanner_finished = false;
#ifdef TREADMILL_DEBUG
std::cout << "TREADMILL: START SCAN " << std::endl << std::flush;
#endif
//treadmill_mark_roots(sc);
total_previous_scan = 0;
//mutex.Lock();
while(!sc->treadmill_flip_active || sc->treadmill_scan != sc->treadmill_top) { // untill the flip is activated we need to keep checking for new objects that may be added to the grey list
int count = 0;
unsigned int dark = sc->dark;
while(sc->treadmill_scan != sc->treadmill_top) //scanned_cell != sc->treadmill_top)
{
#ifdef TREADMILL_CHECKS
if(sc->treadmill_scan->_colour != dark) std::cout << "TREADMILL: SCAN OBJ NOT DARKENED!!!" << std::endl << std::flush;
#endif
pointer scan = sc->treadmill_scan;
if(is_vector(scan)) {
int length = scan->_size;
pointer* cptr = (pointer*) scan->_object._cptr;
for(int i=0; i<length; i++) {
pointer p = cptr[i];
if(p->_colour != dark)
{
#ifdef TREADMILL_CHECKS
last_call_to_insert_treadmill = 6;
#endif
insert_treadmill(sc,p);
}
}
}
if(is_continuation(scan))
{
//#ifdef TREADMILL_CHECKS
//std::cout << "Insert Continuation into Treadmill" << std::endl;
//#endif
pointer d = cont_dump(scan);
unsigned int* dump = (unsigned int*) cptr_value_sc(sc,d);
int nframes = dump[0];
dump_stack_frame* frames = (dump_stack_frame*)&dump[1];
// for each frame check the args and code lists
for(int j=0;j<nframes;j++)
{
// envir
pointer env = frames[j].envir;
if(env->_colour != dark)
{
#ifdef TREADMILL_CHECKS
last_call_to_insert_treadmill = 7;
#endif
insert_treadmill(sc, env);
}
// args
pointer args = frames[j].args;
if(args->_colour != dark)
{
#ifdef TREADMILL_CHECKS
last_call_to_insert_treadmill = 8;
#endif
insert_treadmill(sc, args);
}
// copy code
pointer code = frames[j].code;
if(code->_colour != dark)
{
#ifdef TREADMILL_CHECKS
last_call_to_insert_treadmill = 9;
#endif
insert_treadmill(sc, code);
}
}
}
if(!is_atom(scan))
{
pointer a = scan->_object._cons._car;
pointer b = scan->_object._cons._cdr;
if(a->_colour != dark)
{
#ifdef TREADMILL_CHECKS
last_call_to_insert_treadmill = 10;
#endif
insert_treadmill(sc, a);
}
if(b->_colour != dark)
{
#ifdef TREADMILL_CHECKS
last_call_to_insert_treadmill = 11;
#endif
insert_treadmill(sc, b);
}
}
#ifdef TREADMILL_CHECKS
sc->treadmill_scan->_list_colour = 3;
#endif
sc->treadmill_scan = sc->treadmill_scan->_ccw;
total_previous_scan++;
if(!(count & 16383)) { // force a yield every now and then?
sc->mutex->unlock();
sc->mutex->lock();
}
count++;
}
sc->mutex->unlock(); // yeild here to let interpreter add greys to the treadmill!!
#ifdef _WIN32
std::this_thread::sleep_for(std::chrono::microseconds(500));
#else
usleep(500);
#endif
sc->mutex->lock(); // But lock again after sleep!
}
#ifdef _WIN32
#else
sc->Treadmill_Guard->lock();
#endif
#ifdef TREADMILL_DEBUG
std::cout << "TREADMILL: FINISHED SCAN: " << sc->treadmill_flip_active << std::endl << std::flush;
#endif
if(sc->treadmill_scan != sc->treadmill_top)
{
std::cout << "HUGE ERROR: SHOULD NOT FINISH SCANNER UNTIL SCAN == TOP" << std::endl << std::flush;
}
sc->mutex->unlock();
sc->treadmill_scanner_finished = true;
sc->Treadmill_Guard->wait();
#ifdef TREADMILL_DEBUG
std::cout << "WAKING UP SCANNER" << std::endl << std::flush;
#endif
sc->mutex->lock();
#ifdef _WIN32
#else
sc->Treadmill_Guard->unlock();
#endif
if(sc->treadmill_stop) break; // exit treadmill thread
}
return sc;
}
int released = 0;
static void finalize_cell(scheme *sc, pointer a) {
if(is_vector(a)) {
//std::cout << "RELEASE VECTOR: pointer(" << a << ") cptr(" << a->_object._cptr << ")" << std::endl;
sc->free(a->_object._cptr);
a->_object._cptr = 0; //nil;
} else if(is_string(a)) {
sc->free(strvalue(a));
} else if(is_port(a)) {
if(a->_object._port->kind&port_file
&& a->_object._port->rep.stdio.closeit) {
port_close(sc,a,port_input|port_output);
}
sc->free(a->_object._port);
}
}
/* ========== Routines for Reading ========== */
static int file_push(scheme *sc, const char *fname) {
FILE *fin=fopen(fname,"r");
if(fin!=0) {
sc->file_i++;
sc->load_stack[sc->file_i].kind=port_file|port_input;
sc->load_stack[sc->file_i].rep.stdio.file=fin;
sc->load_stack[sc->file_i].rep.stdio.closeit=1;
sc->nesting_stack[sc->file_i]=0;
sc->loadport->_object._port=sc->load_stack+sc->file_i;
}
return fin!=0;
}
static void file_pop(scheme *sc) {
sc->nesting=sc->nesting_stack[sc->file_i];
if(sc->file_i!=0) {
port_close(sc,sc->loadport,port_input);
sc->file_i--;
sc->loadport->_object._port=sc->load_stack+sc->file_i;
if(file_interactive(sc)) {
putstr(sc,prompt);
}
}
}
static int file_interactive(scheme *sc) {
return sc->file_i==0 && sc->load_stack[0].rep.stdio.file==stdin
&& sc->inport->_object._port->kind&port_file;
}
static port *port_rep_from_filename(scheme *sc, const char *fn, int prop) {
FILE *f;
char *rw;
port *pt;
if(prop==(port_input|port_output)) {
rw=(char*)"a+";
} else if(prop==port_output) {
rw=(char*)"w";
} else {
rw=(char*)"r";
}
f=fopen(fn,rw);
if(f==0) {
return 0;
}
pt=port_rep_from_file(sc,f,prop);
pt->rep.stdio.closeit=1;
return pt;
}
static pointer port_from_filename(scheme *sc, const char *fn, int prop) {
port *pt;
pt=port_rep_from_filename(sc,fn,prop);
if(pt==0) {
return sc->NIL;
}
return mk_port(sc,pt);
}
static port *port_rep_from_file(scheme *sc, FILE *f, int prop) {
char *rw;
port *pt;
pt=(port*)sc->malloc(sizeof(port));
if(pt==0) {
return 0;
}
if(prop==(port_input|port_output)) {
rw=(char*)"a+";
} else if(prop==port_output) {
rw=(char*)"w";
} else {
rw=(char*)"r";
}
pt->kind=port_file|prop;
pt->rep.stdio.file=f;
pt->rep.stdio.closeit=0;
return pt;
}
static pointer port_from_file(scheme *sc, FILE *f, int prop) {
port *pt;
pt=port_rep_from_file(sc,f,prop);
if(pt==0) {
return sc->NIL;
}
return mk_port(sc,pt);
}
static port *port_rep_from_string(scheme *sc, char *start, char *past_the_end, int prop) {
port *pt;
pt=(port*)sc->malloc(sizeof(port));
if(pt==0) {
return 0;
}
pt->kind=port_string|prop;
pt->rep.string.start=start;
pt->rep.string.curr=start;
pt->rep.string.past_the_end=past_the_end;
return pt;
}
static pointer port_from_string(scheme *sc, char *start, char *past_the_end, int prop) {
port *pt;
pt=port_rep_from_string(sc,start,past_the_end,prop);
if(pt==0) {
return sc->NIL;
}
return mk_port(sc,pt);
}
#define BLOCK_SIZE 256
static port *port_rep_from_scratch(scheme *sc) {
port *pt;
char *start;
pt=(port*)sc->malloc(sizeof(port));
if(pt==0) {
return 0;
}
start=(char*)sc->malloc(BLOCK_SIZE);
if(start==0) {
return 0;
}
memset(start,' ',BLOCK_SIZE-1);
start[BLOCK_SIZE-1]='\0';
pt->kind=port_string|port_output|port_srfi6;
pt->rep.string.start=start;
pt->rep.string.curr=start;
pt->rep.string.past_the_end=start+BLOCK_SIZE-1;
return pt;
}
static pointer port_from_scratch(scheme *sc) {
port *pt;
pt=port_rep_from_scratch(sc);
if(pt==0) {
return sc->NIL;
}
return mk_port(sc,pt);
}
static void port_close(scheme *sc, pointer p, int flag) {
port *pt=p->_object._port;
pt->kind&=~flag;
if((pt->kind & (port_input|port_output))==0) {
if(pt->kind&port_file) {
fclose(pt->rep.stdio.file);
}
pt->kind=port_free;
}
}
/* get new character from input file */
static int inchar(scheme *sc) {
int c;
port *pt;
again:
pt=sc->inport->_object._port;
c=basic_inchar(pt);
if(c==EOF && sc->inport==sc->loadport && sc->file_i!=0) {
file_pop(sc);
if(sc->nesting!=0) {
return EOF;
}
goto again;
}
return c;
}
static int basic_inchar(port *pt) {
if(pt->kind&port_file) {
return fgetc(pt->rep.stdio.file);
} else {
if(*pt->rep.string.curr==0
|| pt->rep.string.curr==pt->rep.string.past_the_end) {
return EOF;
} else {
return *pt->rep.string.curr++;
}
}
}
/* back character to input buffer */
static inline void backchar(scheme *sc, int c) {
port *pt;
if(c==EOF) return;
pt=sc->inport->_object._port;
if(pt->kind&port_file) {
ungetc(c,pt->rep.stdio.file);
} else {
if(pt->rep.string.curr!=pt->rep.string.start) {
--pt->rep.string.curr;
}
}
}
static int realloc_port_string(scheme *sc, port *p)
{
char *start=p->rep.string.start;
size_t new_size=p->rep.string.past_the_end-start+1+BLOCK_SIZE;
char *str=(char*)sc->malloc(new_size);
if(str) {
memset(str,' ',new_size-1);
str[new_size-1]='\0';
strcpy(str,start);
p->rep.string.start=str;
p->rep.string.past_the_end=str+new_size-1;
p->rep.string.curr-=start-str;
sc->free(start);
return 1;
} else {
return 0;
}
}
void putstr(scheme *sc, const char *s) {
port *pt=sc->outport->_object._port;
if(pt->kind&port_file) {
fputs(s,pt->rep.stdio.file);
} else {
for(;*s;s++) {
if(pt->rep.string.curr!=pt->rep.string.past_the_end) {
*pt->rep.string.curr++=*s;
} else if(pt->kind&port_srfi6&&realloc_port_string(sc,pt)) {
*pt->rep.string.curr++=*s;
}
}
}
}
static void putchars(scheme *sc, const char *s, int len) {
port *pt=sc->outport->_object._port;
if(pt->kind&port_file) {
fwrite(s,1,len,pt->rep.stdio.file);
} else {
for(;len;len--) {
if(pt->rep.string.curr!=pt->rep.string.past_the_end) {
*pt->rep.string.curr++=*s++;
} else if(pt->kind&port_srfi6&&realloc_port_string(sc,pt)) {
*pt->rep.string.curr++=*s++;
}
}
}
}
void putcharacter(scheme *sc, int c) {
port *pt=sc->outport->_object._port;
if(pt->kind&port_file) {
fputc(c,pt->rep.stdio.file);
} else {
if(pt->rep.string.curr!=pt->rep.string.past_the_end) {
*pt->rep.string.curr++=c;
} else if(pt->kind&port_srfi6&&realloc_port_string(sc,pt)) {
*pt->rep.string.curr++=c;
}
}
}
/* read characters up to delimiter, but cater to character constants */
static char *readstr_upto(scheme *sc, char *delim) {
char *p = sc->strbuff;
while (!is_one_of(delim, (*p++ = inchar(sc))));
if(p==sc->strbuff+2 && p[-2]=='\\') {
*p=0;
} else {
backchar(sc,p[-1]);
*--p = '\0';
}
return sc->strbuff;
}
/* read string expression "xxx...xxx" */
static pointer readstrexp(scheme *sc) {
char *p = sc->strbuff;
int c;
int c1=0;
enum { st_ok, st_bsl, st_x1, st_x2} state=st_ok;
for (;;) {
c=inchar(sc);
if(c==EOF || p-sc->strbuff>sizeof(sc->strbuff)-1) {
printf("String exceeded string buffer size or reached EOF\n");
return sc->F;
}
switch(state) {
case st_ok:
switch(c) {
case '\\':
state=st_bsl;
break;
case '"':
*p=0;
return mk_counted_string(sc,sc->strbuff,p-sc->strbuff);
default:
*p++=c;
break;
}
break;
case st_bsl:
switch(c) {
case 'x':
case 'X':
state=st_x1;
c1=0;
break;
case 'n':
*p++='\n';
state=st_ok;
break;
case 't':
*p++='\t';
state=st_ok;
break;
case 'r':
*p++='\r';
state=st_ok;
break;
case '"':
*p++='"';
state=st_ok;
break;
default:
*p++=c;
state=st_ok;
break;
}
break;
case st_x1:
case st_x2:
c=toupper(c);
if(c>='0' && c<='F') {
if(c<='9') {
c1=(c1<<4)+c-'0';
} else {
c1=(c1<<4)+c-'A'+10;
}
if(state==st_x1) {
state=st_x2;
} else {
*p++=c1;
state=st_ok;
}
} else {
printf("Error parsing string state(x1 or x2) at character(%c)\n", c);
return sc->F;
}
break;
}
}
}
/* check c is in chars */
static inline int is_one_of(const char *s, int c) {
if(c==EOF) return 1;
while (*s)
if (*s++ == c)
return (1);
return (0);
}
/* skip white characters && cntrl characters */
static inline void skipspace(scheme *sc) {
int c = inchar(sc);
while (isspace(c) || iscntrl(c))
{
c = inchar(sc);
}
if(c!=EOF) {
backchar(sc,c);
}
}
/* get token */
static int token(scheme *sc) {
int c;
skipspace(sc);
switch (c=inchar(sc)) {
case EOF:
return (TOK_EOF);
case '(':
return (TOK_LPAREN);
case ')':
return (TOK_RPAREN);
case '.':
c=inchar(sc);
if (is_one_of(" \n\t",c)) {
return (TOK_DOT);
} else {
backchar(sc,c);
backchar(sc,'.');
return TOK_ATOM;
}
case '\'':
return (TOK_QUOTE);
case ';':
return (TOK_COMMENT);
case '"':
return (TOK_DQUOTE);
case BACKQUOTE:
return (TOK_BQUOTE);
case ',':
if ((c=inchar(sc)) == '@')
return (TOK_ATMARK);
else {
backchar(sc,c);
return (TOK_COMMA);
}
case '#':
c=inchar(sc);
if (c == '(') {
return (TOK_VEC);
} else if(c == '!') {
return TOK_COMMENT;
} else {
backchar(sc,c);
if(is_one_of((char*)" tfodxb\\",c)) {
return TOK_SHARP_CONST;
} else {
return (TOK_SHARP);
}
}
default:
backchar(sc,c);
return (TOK_ATOM);
}
}
/* ========== Routines for Printing ========== */
#define ok_abbrev(x) (is_pair(x) && cdr(x) == sc->NIL)
static void printslashstring(scheme *sc, char *p, int len) {
int i;
unsigned char *s=(unsigned char*)p;
putcharacter(sc,'"');
for ( i=0; i<len; i++) {
if(*s==0xff || *s=='"' || *s<' ' || *s=='\\') {
putcharacter(sc,'\\');
switch(*s) {
case '"':
putcharacter(sc,'"');
break;
case '\n':
putcharacter(sc,'n');
break;
case '\t':
putcharacter(sc,'t');
break;
case '\r':
putcharacter(sc,'r');
break;
case '\\':
putcharacter(sc,'\\');
break;
default: {
int d=*s/16;
putcharacter(sc,'x');
if(d<10) {
putcharacter(sc,d+'0');
} else {
putcharacter(sc,d-10+'A');
}
d=*s%16;
if(d<10) {
putcharacter(sc,d+'0');
} else {
putcharacter(sc,d-10+'A');
}
}
}
} else {
putcharacter(sc,*s);
}
s++;
}
putcharacter(sc,'"');
}
/* print atoms */
static void printatom(scheme *sc, pointer l, int f) {
char *p;
int len;
atom2str(sc,l,f,&p,&len);
putchars(sc,p,len);
}
/* Uses internal buffer unless string pointer is already available */
static void atom2str(scheme *sc, pointer l, int f, char **pp, int *plen) {
char *p = NULL;
if (l == sc->NIL) {
p = (char*)"()";
} else if (l == sc->T) {
p = (char*)"#t";
} else if (l == sc->F) {
p = (char*)"#f";
} else if (l == sc->EOF_OBJ) {
p = (char*)"#<EOF>";
} else if (is_port(l)) {
p = sc->strbuff;
strcpy(p, "#<PORT>");
} else if (is_number(l)) {
p = sc->strbuff;
if (is_integer(l)) {
sprintf(p, "%" PRId64, ivalue_unchecked(l));
} else if(is_rational(l)) {
sprintf(p, "%" PRId64 "/%" PRId64, ratvalue_unchecked(l).n,ratvalue_unchecked(l).d);
//sprintf(p, "%ld/%ld", l->_object._number.value.ratvalue.n, l->_object._number.value.ratvalue.d);
} else {
//std::stringstream ss;
//ss << std::fixed << std::showpoint << rvalue_unchecked(l);
//p = (char*) ss.str().c_str();
sprintf(p, "%#.20g", rvalue_unchecked(l));
//sprintf(p, "%#.4e", rvalue_unchecked(l));
}
} else if (is_string(l)) {
if (!f) {
p = strvalue(l);
} else { /* Hack, uses the fact that printing is needed */
*pp=sc->strbuff;
*plen=0;
printslashstring(sc, strvalue(l), strlength(l));
return;
}
} else if (is_character(l)) {
int c=charvalue_sc(sc,l);
p = sc->strbuff;
if (!f) {
p[0]=c;
p[1]=0;
} else {
switch(c) {
case ' ':
sprintf(p,"#\\space"); break;
case '\n':
sprintf(p,"#\\newline"); break;
case '\r':
sprintf(p,"#\\return"); break;
case '\t':
sprintf(p,"#\\tab"); break;
default:
#if USE_ASCII_NAMES
if(c==127) {
strcpy(p,"#\\del"); break;
} else if(c<32) {
strcpy(p,"#\\"); strcat(p,charnames[c]); break;
}
#else
if(c<32) {
sprintf(p,"#\\x%x",c); break;
}
#endif
sprintf(p,"#\\%c",c); break;
}
}
} else if (is_symbol(l)) {
p = symname_sc(sc,l);
} else if (is_proc(l)) {
p = sc->strbuff;
sprintf(p, "#<%s PROCEDURE %" PRId64 ">", procname(l),procnum(l));
} else if (is_macro(l)) {
p = (char*)"#<MACRO>";
} else if (is_closure(l)) {
p = (char*)"#<CLOSURE>";
} else if (is_promise(l)) {
p = (char*)"#<PROMISE>";
} else if (is_foreign(l)) {
p = sc->strbuff;
sprintf(p, "#<FOREIGN PROCEDURE %" PRId64 ">", procnum(l));
} else if (is_continuation(l)) {
p = (char*)"#<CONTINUATION>";
} else if (is_cptr(l)) {
p = (char*)"#<CPTR>";
// } else if (is_objc(l)) {
// p = (char*)"#<OBJC>";
} else {
p = (char*)"#<ERROR>";
}
*pp=p;
*plen=strlen(p);
}
/* ========== Routines for Evaluation Cycle ========== */
/* make closure. c is code. e is environment */
pointer mk_closure(scheme *sc, pointer c, pointer e) {
pointer x = get_cell(sc, c, e);
typeflag(x) = T_CLOSURE;
////////////// write barrier for treadmill
#ifdef TREADMILL_CHECKS
last_call_to_insert_treadmill = 12;
#endif
insert_treadmill(sc,c);
#ifdef TREADMILL_CHECKS
last_call_to_insert_treadmill = 13;
#endif
insert_treadmill(sc,e);
//////////////////////////////////////////
car(x) = c;
cdr(x) = e;
return (x);
}
/* make continuation. */
pointer mk_continuation(scheme *sc) {
pointer y = dump_stack_copy(sc);
pointer x = get_cell(sc, y, sc->NIL);
typeflag(x) = T_CONTINUATION;
cont_dump(x) = y;
return (x);
}
static pointer list_star(scheme *sc, pointer d) {
pointer p, q;
if(cdr(d)==sc->NIL) {
return car(d);
}
p=cons(sc,car(d),cdr(d));
q=p;
while(cdr(cdr(p))!=sc->NIL) {
d=cons(sc,car(p),cdr(p));
if(cdr(cdr(p))!=sc->NIL) {
p=cdr(d);
}
}
// NOT SURE ABOUT THIS ONE? DOING Q for good measure
////////////// write barrier for treadmill
#ifdef TREADMILL_CHECKS
last_call_to_insert_treadmill = 14;
#endif
insert_treadmill(sc,car(cdr(p)));
#ifdef TREADMILL_CHECKS
last_call_to_insert_treadmill = 15;
#endif
insert_treadmill(sc,q);
//////////////////////////////////////////
cdr(p)=car(cdr(p));
return q;
}
/* reverse list -- produce new list */
/*static*/ pointer reverse(scheme *sc, pointer a) {
/* a must be checked by gc */
if(a == sc->NIL) return sc->NIL;
pointer p = sc->NIL;
for ( ; is_pair(a); a = cdr(a)) {
p = cons(sc, car(a), p);
}
return (p);
}
/* reverse list --- in-place */
/*static*/ pointer reverse_in_place(scheme *sc, pointer term, pointer list) {
pointer p = list, result = term, q;
while (p != sc->NIL) {
q = cdr(p);
cdr(p) = result;
result = p;
p = q;
}
////////////// write barrier for treadmill
#ifdef TREADMILL_CHECKS
last_call_to_insert_treadmill = 16;
#endif
insert_treadmill(sc,result);
////////////////////////////////////////////
return (result);
}
/* append list -- produce new list */
/*static*/ pointer append(scheme *sc, pointer a, pointer b) {
pointer p = b, q;
if (a != sc->NIL) {
a = reverse(sc, a);
while (a != sc->NIL) {
q = cdr(a);
cdr(a) = p;
p = a;
a = q;
}
}
////////////// write barrier for treadmill
#ifdef TREADMILL_CHECKS
last_call_to_insert_treadmill = 17;
#endif
insert_treadmill(sc,p);
//////////////////////////////////////////
return (p);
}
/* equivalence of atoms */
/*static*/ int eqv(pointer a, pointer b) {
if (is_string(a)) {
if (is_string(b))
return (strvalue(a) == strvalue(b));
else
return (0);
} else if (is_number(a)) {
if (is_number(b))
return num_eq(nvalue(a),nvalue(b));
else
return (0);
} else if (is_character(a)) {
if (is_character(b))
return charvalue(a)==charvalue(b);
else
return (0);
} else if (is_port(a)) {
if (is_port(b))
return a==b;
else
return (0);
} else if (is_proc(a)) {
if (is_proc(b))
return procnum(a)==procnum(b);
else
return (0);
} else {
return (a == b);
}
}
/*static*/ int eqv_sc(scheme* sc, pointer a, pointer b) {
if (is_string(a)) {
if (is_string(b))
return (strvalue(a) == strvalue(b));
else
return (0);
} else if (is_number(a)) {
if (is_number(b))
return num_eq(nvalue(a),nvalue(b));
else
return (0);
} else if (is_character(a)) {
if (is_character(b))
return charvalue_sc(sc,a)==charvalue_sc(sc,b);
else
return (0);
} else if (is_port(a)) {
if (is_port(b))
return a==b;
else
return (0);
} else if (is_proc(a)) {
if (is_proc(b))
return procnum(a)==procnum(b);
else
return (0);
} else if (is_cptr(a)) {
if (is_cptr(b))
return a->_object._cptr==b->_object._cptr;
else
return (0);
// } else if (is_objc(a)) {
// if (is_objc(b))
// return a->_object._cptr==b->_object._cptr;
// else
// return (0);
} else {
return (a == b);
}
}
/* true or false value macro */
/* () is #t in R5RS */
#define is_true(p) ((p) != sc->F)
#define is_false(p) ((p) == sc->F)
/* ========== Environment implementation ========== */
static inline uint64_t str_hash(const char* str)
{
uint64_t result(0);
unsigned char c;
while((c = *(str++))) {
result = result * 33 + c;
}
return result;
}
static inline int hash_fn(const char *key, int table_size)
{
return str_hash(key) % table_size;
}
/*
* In this implementation, each frame of the environment may be
* a hash table: a vector of alists hashed by variable name.
* In practice, we use a vector only for the initial frame;
* subsequent frames are too small and transient for the lookup
* speed to out-weigh the cost of making a new vector.
*/
static void new_frame_in_env(scheme *sc, pointer old_env)
{
pointer new_frame;
/* The interaction-environment has about 300 variables in it. */
if (old_env == sc->NIL) {
new_frame = mk_vector(sc, 65521);
} else {
new_frame = sc->NIL;
}
sc->envir = immutable_cons(sc, new_frame, old_env);
setenvironment(sc->envir);
}
static inline void new_slot_spec_in_env(scheme *sc, pointer env,
pointer variable, pointer value)
{
pointer slot = immutable_cons(sc, variable, value);
if (is_vector(car(env))) {
int location = hash_fn(symname_sc(sc,variable), (car(env))->_size);
set_vector_elem(sc, car(env), location,
immutable_cons(sc, slot, vector_elem(car(env), location)));
} else {
pointer tmp = immutable_cons(sc, slot, car(env));
////////////// write barrier for treadmill
#ifdef TREADMILL_CHECKS
last_call_to_insert_treadmill = 18;
#endif
insert_treadmill(sc,tmp);
//////////////////////////////////////////
car(env) = tmp;
}
}
pointer find_slot_in_env(scheme *sc, pointer env, pointer hdl, int all)
{
for (auto x = env; x != sc->NIL; x = cdr(x)) {
pointer y;
if (is_vector(car(x))) {
auto location = hash_fn(symname_sc(sc, hdl), car(x)->_size);
y = vector_elem(car(x), location);
} else {
y = car(x);
}
for (; y != sc->NIL; y = cdr(y)) {
if (caar(y) == hdl) {
return car(y);
}
}
if (!all) {
return sc->NIL;
}
}
return sc->NIL;
}
inline void new_slot_in_env(scheme *sc, pointer variable, pointer value)
{
new_slot_spec_in_env(sc, sc->envir, variable, value);
}
inline void set_slot_in_env(scheme *sc, pointer slot, pointer value)
{
////////////// write barrier for treadmill
#ifdef TREADMILL_CHECKS
last_call_to_insert_treadmill = 19;
#endif
insert_treadmill(sc,value);
//////////////////////////////////////////
cdr(slot) = value;
}
inline pointer slot_value_in_env(pointer slot)
{
return cdr(slot);
}
/* ========== Evaluation Cycle ========== */
static pointer _Error_1(scheme *sc, const char *s, pointer a, int location, int errnum) {
// closure stack trace
int cnt = 0;
char* fname = (char*) "toplevel";
char* current = 0;
std::stringstream sss;
if(is_symbol(sc->last_symbol_apply)) {
fname = symname_sc(sc,sc->last_symbol_apply);
current = symname_sc(sc,sc->last_symbol_apply);
sss << symname_sc(sc,sc->last_symbol_apply);
}
if(current==0) {
while(!sc->applied_symbol_names.empty() && cnt<10)
{
pointer item = sc->applied_symbol_names.top();
std::stringstream ss;
extemp::UNIV::printSchemeCell(sc, ss, item, true);
std::cout << "stack-catch: " << ss.str() << std::endl;
cnt++;
sc->applied_symbol_names.pop();
}
}
while(!sc->applied_symbol_names.empty() && cnt<10 && current != 0)
{
pointer item = sc->applied_symbol_names.top();
if(is_symbol(item)) {
if(strcmp(current,symname_sc(sc,item)) == 0) {
sc->applied_symbol_names.pop();
continue;
}
sss << " <- " << symname_sc(sc,item);
current = symname_sc(sc,item);
}
cnt++;
sc->applied_symbol_names.pop();
}
//if(cnt>9) sss << " ... " << std::endl;
//else sss << std::endl;
// log message
char msg[256*10];
int position = 0;
if(a!=0) {
position = location; //a->_debugger->_size;
std::stringstream ss;
extemp::UNIV::printSchemeCell(sc, ss, a, true);
//sprintf(msg, "position:(%d) in function \"%s\"\n%s\nwith: %s\nTrace: %s",position,fname,s,ss.str().c_str(),sss.str().c_str());
sprintf(msg, "%s %s\nTrace: %s",s,ss.str().c_str(),sss.str().c_str());
sc->error_position = position;
}else{
position = location; //sc->code->_size;
//sprintf(msg, "position:(%d) in function \"%s\"\n%s\nTrace: %s",position,fname,s,sss.str().c_str());
sprintf(msg, "%s\nTrace: %s",s,sss.str().c_str());
sc->error_position = position;
}
std::cout << msg << std::endl;
//printf(msg);
// CPPBridge::log("");
// CPPBridge::error(msg);
// CPPBridge::log("");
if(is_symbol(sc->last_symbol_apply)) {
memcpy(sc->error_fname,strvalue(car(sc->last_symbol_apply)),strlength(car(sc->last_symbol_apply)));
}
//memset(fname, 0, 256);
// this as error return string - we parse this in the editor so it's format is important!
sprintf(msg,"%s::%d::%s",fname,position,s);
putstr(sc, msg); // this line sends fname to scheme stderr (which is read as a return result by schemeinterface)
#if USE_ERROR_HOOK
pointer x;
pointer hdl=sc->ERROR_HOOK;
x=find_slot_in_env(sc,sc->envir,hdl,1);
if (x != sc->NIL && slot_value_in_env(x) != sc->NIL) {
if(a!=0) {
sc->code = cons(sc, cons(sc, sc->QUOTE, cons(sc,(a), sc->NIL)), sc->NIL);
} else {
sc->code = sc->NIL;
}
sc->code = cons(sc, mk_string(sc, (s)), sc->code);
setimmutable(car(sc->code));
sc->code = cons(sc, slot_value_in_env(x), sc->code);
sc->op = (int)OP_EVAL;
sc->last_symbol_apply = sc->NIL;
sc->call_end_time = ULLONG_MAX;
// empty applied_symbol_names stack is empty
while(!sc->applied_symbol_names.empty())
{
sc->applied_symbol_names.pop();
}
return sc->T;
}
hdl = sc->LIVECODING_ERROR_HOOK;
x=find_slot_in_env(sc,sc->envir,hdl,1);
if (x != sc->NIL && slot_value_in_env(x) != sc->NIL ) {
if(a!=0) {
pointer p1 = mk_integer(sc, errnum);
pointer p2 = cons(sc,p1,sc->NIL);
pointer p3;
{
EnvInjector injector(sc, p2);
p3 = cons(sc, sc->QUOTE, cons(sc, a, sc->NIL)); // need to quote 'a
}
sc->code = cons(sc, p3, p2);
//sc->code = cons(sc, cons(sc, sc->QUOTE, cons(sc,(a), sc->NIL)), sc->NIL);
} else {
//sc->code = sc->NIL;
pointer p1 = mk_integer(sc, errnum);
pointer p2 = cons(sc,p1,sc->NIL);
pointer p3;
{
EnvInjector injector(sc, p2);
p3 = cons(sc, sc->QUOTE, cons(sc, sc->F, sc->NIL));
}
sc->code = cons(sc, p3, p2);
}
sc->code = cons(sc, mk_string(sc, (s)), sc->code);
setimmutable(car(sc->code));
sc->code = cons(sc, slot_value_in_env(x), sc->code);
sc->op = (int)OP_EVAL;
sc->last_symbol_apply = sc->NIL;
sc->call_end_time = ULLONG_MAX;
// empty applied_symbol_names stack is empty
while(!sc->applied_symbol_names.empty())
{
sc->applied_symbol_names.pop();
}
return sc->T;
}
#endif
if(a!=0) {
sc->args = cons(sc, (a), sc->NIL);
} else {
sc->args = sc->NIL;
}
//sc->args = cons(sc, mk_string(sc, (s)), sc->args);
sc->args = cons(sc, mk_string(sc, fname), sc->args);
setimmutable(car(sc->args));
sc->op = (int)OP_ERR0;
// empty applied_symbol_names stack is empty
while(!sc->applied_symbol_names.empty())
{
sc->applied_symbol_names.pop();
}
sc->last_symbol_apply = sc->NIL;
sc->call_end_time = ULLONG_MAX;
return sc->T;
}
#define Error_1(sc,s,a,l) return _Error_1(sc,s,a,l)
#define Error_0(sc,s,l) return _Error_1(sc,s,0,l)
/* Too small to turn into function */
# define BEGIN do {
# define END } while (0)
#define s_goto(sc,a) BEGIN \
sc->op = (int)(a); \
return sc->T; END
#define s_return(sc,a) return _s_return(sc,a)
#ifndef USE_SCHEME_STACK
#define STACK_GROWTH 3
static void s_save(scheme *sc, enum scheme_opcodes op, pointer args, pointer code)
{
sc->applied_symbol_names.push(sc->last_symbol_apply);
// if(is_symbol(sc->last_symbol_apply)) {
// std::cout << "PUSH SYM " << sc->applied_symbol_names.size() << " " << symname(sc->last_symbol_apply) << std::endl;
// }else{
// std::cout << "PUSH SYM " << sc->applied_symbol_names.size() << std::endl;
// }
intptr_t nframes = (intptr_t)sc->dump;
struct dump_stack_frame *next_frame;
/* enough room for the next frame? */
if (nframes >= sc->dump_size) {
sc->dump_size += STACK_GROWTH;
/* alas there is no sc->realloc */
sc->dump_base = realloc(sc->dump_base, sizeof(struct dump_stack_frame) * sc->dump_size);
}
next_frame = (struct dump_stack_frame *)sc->dump_base + nframes;
next_frame->op = op;
next_frame->args = args;
next_frame->envir = sc->envir;
next_frame->code = code;
sc->dump = (pointer)(nframes+1);
}
static pointer _s_return(scheme *sc, pointer a)
{
if(sc->applied_symbol_names.empty()) {
sc->last_symbol_apply = sc->NIL;
}else{
sc->last_symbol_apply = sc->applied_symbol_names.top();
sc->applied_symbol_names.pop();
}
intptr_t nframes = (intptr_t)sc->dump;
struct dump_stack_frame *frame;
sc->value = (a);
if (nframes <= 0) {
return sc->NIL;
}
nframes--;
frame = (struct dump_stack_frame *)sc->dump_base + nframes;
sc->op = frame->op;
sc->args = frame->args;
sc->envir = frame->envir;
sc->code = frame->code;
sc->dump = (pointer)nframes;
return sc->T;
}
static inline void dump_stack_reset(scheme *sc)
{
/* in this implementation, sc->dump is the number of frames on the stack */
sc->dump = (pointer)0;
}
static inline void dump_stack_initialize(scheme *sc)
{
sc->dump_size = 0;
sc->dump_base = NULL;
dump_stack_reset(sc);
}
static void dump_stack_free(scheme *sc)
{
sc->free(sc->dump_base);
sc->dump_base = NULL;
sc->dump = (pointer)0;
sc->dump_size = 0;
}
/*
static inline void dump_stack_mark(scheme *sc)
{
intptr_t nframes = (intptr_t)sc->dump;
int i;
for(i=0; i<nframes; i++) {
struct dump_stack_frame *frame;
frame = (struct dump_stack_frame *)sc->dump_base + i;
mark(frame->args);
mark(frame->envir);
mark(frame->code);
}
}
*/
static pointer list_copy(scheme* Scheme, pointer Args)
{
pointer ret = Scheme->NIL;
for (; Args != Scheme->NIL; Args = cdr(Args)) {
ret = cons(Scheme, car(Args), ret);
}
return reverse_in_place(Scheme, Scheme->NIL, ret);
}
static void dump_stack_continuation_set(scheme* sc, pointer p)
{
unsigned int* olddump = (unsigned int*) cptr_value_sc(sc,p);
ptrdiff_t nframes = olddump[0];
memcpy(sc->dump_base, &olddump[1], nframes * sizeof(struct dump_stack_frame));
sc->dump = pointer(nframes);
dump_stack_frame* frames = (dump_stack_frame*) sc->dump_base;
for (int j=0;j<nframes;j++) {
frames[j].args = list_copy(sc, frames[j].args);
if (is_symbol(frames[j].code)) {
frames[j].code = mk_symbol(sc, symname_sc(sc,frames[j].code));
} else {
frames[j].code = list_copy(sc, frames[j].code);
}
}
}
pointer dump_stack_copy(scheme* sc)
{
intptr_t nframes = (intptr_t)sc->dump;
unsigned int* newdump = (unsigned int*) malloc(4+(nframes*sizeof(struct dump_stack_frame)));
memcpy(&newdump[1],sc->dump_base, nframes*sizeof(struct dump_stack_frame));
newdump[0] = nframes;
pointer new_stack_ptr = mk_cptr(sc, newdump);
EnvInjector injector(sc, new_stack_ptr);
dump_stack_frame* frames = (dump_stack_frame*)&newdump[1];
for (int j=0;j < nframes; j++)
{
frames[j].args = list_copy(sc, frames[j].args);
if (is_symbol(frames[j].code)) {
frames[j].code = mk_symbol(sc, symname_sc(sc,frames[j].code));
} else {
frames[j].code = list_copy(sc, frames[j].code);
}
}
return new_stack_ptr;
}
#else
static inline void dump_stack_reset(scheme *sc)
{
sc->dump = sc->NIL;
}
static inline void dump_stack_initialize(scheme *sc)
{
dump_stack_reset(sc);
}
static void dump_stack_free(scheme *sc)
{
sc->dump = sc->NIL;
}
static pointer _s_return(scheme *sc, pointer a) {
sc->value = (a);
if(sc->dump==sc->NIL) return sc->NIL;
sc->op = ivalue(car(sc->dump));
sc->args = cadr(sc->dump);
sc->envir = caddr(sc->dump);
sc->code = cadddr(sc->dump);
sc->dump = cddddr(sc->dump);
return sc->T;
}
static void s_save(scheme *sc, enum scheme_opcodes op, pointer args, pointer code) {
sc->dump = cons(sc, sc->envir, cons(sc, (code), sc->dump));
sc->dump = cons(sc, (args), sc->dump);
sc->dump = cons(sc, mk_integer(sc, (long)(op)), sc->dump);
}
// NOTE: This is probably really needlessly inefficient
// I'm probably doing to much gc_masking etc. and should
// probably avoid using the list reverse.
//
// Also note that this function uses tmp_dump and tmp_args
// two new pointers added to the scheme data structure and
// marked before each GC. Probably could do without these
// as well :)
//
// All that said, at least continuations now work :)
static pointer dump_stack_copy(scheme* sc, pointer dump) {
sc->tmp_dump = dump;
sc->tmp_dump = reverse(sc,sc->tmp_dump);
sc->tmp_args = sc->NIL;
for( ;sc->tmp_dump != sc->NIL; sc->tmp_dump=cdr(sc->tmp_dump))
{
pointer val = car(sc->tmp_dump);
if(is_pair(val) && !is_environment(val)) {
int lgth = list_length(sc, val);
if(lgth<0) { // pair
sc->tmp_args = cons(sc, cons(sc,car(val),cdr(val)), sc->tmp_args);
}else{ // list
pointer t = sc->NIL;
for(int i=0;i<lgth;i++)
{
t = cons(sc, list_ref(sc,i,val), t);
}
sc->tmp_args = cons(sc, reverse(sc,t), sc->tmp_args);
}
}else{
sc->tmp_args = cons(sc, val, sc->tmp_args);
}
}
return sc->tmp_args;
}
/*
static inline void dump_stack_mark(scheme *sc)
{
mark(sc->dump);
}
*/
#endif
#define s_retbool(tf) s_return(sc,(tf) ? sc->T : sc->F)
static pointer opexe_0(scheme *sc, enum scheme_opcodes op) {
pointer x, y;
switch (op) {
case OP_LOAD: /* load */
if(file_interactive(sc)) {
fprintf(sc->outport->_object._port->rep.stdio.file,
"Loading %s\n", strvalue(car(sc->args)));
}
if (!file_push(sc,strvalue(car(sc->args)))) {
Error_1(sc,"unable to open", car(sc->args), sc->code->_debugger->_size);
}
if(file_interactive(sc)) {
putstr(sc,"\n");
}
sc->nesting=0;
//dump_stack_reset(sc);
sc->envir = sc->global_env;
sc->save_inport=sc->inport;
sc->inport = sc->loadport;
//s_save(sc,OP_T0LVL, sc->NIL, sc->NIL);
//s_save(sc,OP_VALUEPRINT, sc->NIL, sc->NIL);
s_save(sc,OP_T1LVL, sc->NIL, sc->NIL);
if (file_interactive(sc)) {
putstr(sc,prompt);
}
s_goto(sc,OP_READ_INTERNAL);
case OP_T0LVL: /* top level */
if(file_interactive(sc)) {
putstr(sc,"\n");
}
sc->nesting=0;
dump_stack_reset(sc);
sc->envir = sc->global_env;
sc->save_inport=sc->inport;
sc->inport = sc->loadport;
s_save(sc,OP_T0LVL, sc->NIL, sc->NIL);
s_save(sc,OP_VALUEPRINT, sc->NIL, sc->NIL);
s_save(sc,OP_T1LVL, sc->NIL, sc->NIL);
if (file_interactive(sc)) {
putstr(sc,prompt);
}
s_goto(sc,OP_READ_INTERNAL);
case OP_T1LVL: /* top level */
sc->code = sc->value;
sc->inport=sc->save_inport;
s_goto(sc,OP_EVAL);
case OP_READ_INTERNAL: /* internal read */
sc->tok = token(sc);
if(sc->tok==TOK_EOF) {
if(sc->inport==sc->loadport) {
sc->args=sc->NIL;
s_goto(sc,OP_QUIT);
} else {
s_return(sc,sc->EOF_OBJ);
}
}
s_goto(sc,OP_RDSEXPR);
case OP_GENSYM:
s_return(sc, gensym(sc));
case OP_VALUEPRINT: /* print evaluation result */
/* OP_VALUEPRINT is always pushed, because when changing from
non-interactive to interactive mode, it needs to be
already on the stack */
if(sc->tracing) {
putstr(sc,"\nGives: ");
}
if(file_interactive(sc)) {
sc->print_flag = 1;
sc->args = sc->value;
s_goto(sc,OP_P0LIST);
} else {
s_return(sc,sc->value);
}
case OP_EVAL: /* main part of evaluation */
#if USE_TRACING
if(sc->tracing) {
/*s_save(sc,OP_VALUEPRINT,sc->NIL,sc->NIL);*/
s_save(sc,OP_REAL_EVAL,sc->args,sc->code);
sc->args=sc->code;
putstr(sc,"\nEval: ");
s_goto(sc,OP_P0LIST);
}
/* fall through */
case OP_REAL_EVAL:
#endif
if (is_symbol(sc->code)) { /* symbol */
//printf("evaluating symbol: %s\n",symname_sc(sc,sc->code));
x=find_slot_in_env(sc,sc->envir,sc->code,1);
if (x != sc->NIL) {
pointer xx = slot_value_in_env(x);
xx->_debugger = sc->code->_debugger;
s_return(sc,xx);
//s_return(sc,slot_value_in_env(x));
} else {
if(llvm_check_valid_dot_symbol(sc,symname(sc->code))) {
s_return(sc,sc->code);
}else{
Error_1(sc,"eval: unbound variable:", sc->code, sc->code->_debugger->_size);
}
}
} else if (is_pair(sc->code)) {
if (is_syntax(x = car(sc->code))) { /* SYNTAX */
sc->code = cdr(sc->code);
s_goto(sc,syntaxnum(x));
} else {/* first, eval top element and eval arguments */
s_save(sc,OP_E0ARGS, sc->NIL, sc->code);
/* If no macros => s_save(sc,OP_E1ARGS, sc->NIL, cdr(sc->code));*/
car(sc->code)->_debugger = sc->code;
sc->code = car(sc->code);
s_goto(sc,OP_EVAL);
}
} else {
s_return(sc,sc->code);
}
case OP_E0ARGS: /* eval arguments */
if (is_macro(sc->value)) { /* macro expansion */
s_save(sc,OP_DOMACRO, sc->code, sc->NIL);
//pointer swap_debug = sc->code;
sc->args = cons(sc,sc->code, sc->NIL);
sc->code = sc->value;
//sc->code->_debugger = swap_debug;
s_goto(sc,OP_APPLY);
} else {
sc->code = cdr(sc->code);
s_goto(sc,OP_E1ARGS);
}
case OP_E1ARGS: /* eval arguments */
sc->args = cons(sc, sc->value, sc->args);
if (is_pair(sc->code)) { /* continue */
s_save(sc,OP_E1ARGS, sc->args, cdr(sc->code));
car(sc->code)->_debugger = sc->code;
sc->code = car(sc->code);
sc->args = sc->NIL;
s_goto(sc,OP_EVAL);
} else { /* end */
sc->args = reverse_in_place(sc, sc->NIL, sc->args);
sc->code = car(sc->args);
sc->args = cdr(sc->args);
s_goto(sc,OP_APPLY);
}
#if USE_TRACING
case OP_TRACING: {
int tr=sc->tracing;
sc->tracing=ivalue(car(sc->args));
s_return(sc,mk_integer(sc,tr));
}
#endif
case OP_APPLY: /* apply 'code' to 'args' */
#if USE_TRACING
if(sc->tracing) {
s_save(sc,OP_REAL_APPLY,sc->args,sc->code);
sc->print_flag = 1;
/* sc->args=cons(sc,sc->code,sc->args);*/
putstr(sc,"\nApply to: ");
s_goto(sc,OP_P0LIST);
}
/* fall through */
case OP_REAL_APPLY:
#endif
if (is_proc(sc->code)) {
s_goto(sc,procnum(sc->code)); /* PROCEDURE */
} else if (is_foreign(sc->code)) {
x=sc->code->_object._ff(sc,sc->args);
s_return(sc,x);
} else if (is_closure(sc->code) || is_macro(sc->code) || is_promise(sc->code)) { /* CLOSURE */
sc->last_symbol_apply = closure_code(sc->code)->_debugger;
// if(is_symbol(sc->last_symbol_apply)) {
// std::cout << "SYM: " << symname(sc->last_symbol_apply) << std::endl;
// }
/* Should not accept promise */
/* make environment */
new_frame_in_env(sc, closure_env(sc->code));
for (x = car(closure_code(sc->code)), y = sc->args; is_pair(x); x = cdr(x), y = cdr(y))
{
if (y == sc->NIL) {
Error_1(sc,"not enough arguments calling: ",sc->args,sc->code->_debugger->_size);
std::cout << "NOT ENOUGH ARGS" << std::endl;
} else {
new_slot_in_env(sc, car(x), car(y));
}
}
if (x == sc->NIL) {
/*--
* if (y != sc->NIL) {
* Error_0(sc,"too many arguments");
* }
*/
} else if (is_symbol(x)) {
new_slot_in_env(sc, x, y);
} else {
Error_1(sc,"syntax error in closure: not a symbol:", x,sc->code->_debugger->_size);
std::cout << "SYNTAX ERROR" << std::endl;
}
sc->func_called_by_extempore = car(sc->code);
sc->code = cdr(closure_code(sc->code));
sc->args = sc->NIL;
s_goto(sc,OP_BEGIN);
} else if (is_continuation(sc->code)) { /* CONTINUATION */
dump_stack_continuation_set(sc, cont_dump(sc->code));
s_return(sc,sc->args != sc->NIL ? car(sc->args) : sc->NIL);
} else {
if(llvm_check_valid_dot_symbol(sc, symname(sc->code))) {
// all good so far so now we check llvm
pointer ppp = llvm_scheme_env_set(sc, symname(sc->code));
s_return(sc,ppp);
}else{
Error_0(sc,"illegal function",sc->code->_debugger->_size);
}
}
case OP_DOMACRO: /* do macro */
sc->code = sc->value;
//this size stuff here for debugging
sc->code->_size = sc->args->_size;
s_goto(sc,OP_EVAL);
case OP_LAMBDA: /* lambda */
s_return(sc,mk_closure(sc, sc->code, sc->envir));
case OP_MKCLOSURE: /* make-closure */
x=car(sc->args);
if(car(x)==sc->LAMBDA) {
x=cdr(x);
}
if(cdr(sc->args)==sc->NIL) {
y=sc->envir;
} else {
y=cadr(sc->args);
}
s_return(sc,mk_closure(sc, x, y));
case OP_QUOTE: /* quote */
x=car(sc->code);
s_return(sc,car(sc->code));
case OP_DEF0: /* define */
if (is_pair(car(sc->code))) {
//std::stringstream ss;
// imp::SchemeInterface::printSchemeCell(sc, ss, car(sc->code), true);
//std::cout << "new func: " << ss.str() << std::endl;
char* pp;
int ll;
atom2str(sc,caar(sc->code),0,&pp,&ll);
std::string str(pp);
//tinyscheme code
x = caar(sc->code);
sc->code = cons(sc, sc->LAMBDA, cons(sc, cdar(sc->code), cdr(sc->code)));
} else {
x = car(sc->code);
sc->code = cadr(sc->code);
if(is_pair(sc->code)) {
char* pp;
int ll;
atom2str(sc,cadr(sc->code),0,&pp,&ll);
std::string str2(pp);
//std::stringstream ss;
// imp::SchemeInterface::printSchemeCell(sc, ss, cadr(sc->code), true);
std::string str(symname_sc(sc,x));
str = str + " ";
//str = ss.str().insert(1,str);
str = str2.insert(1,str);
// if(strcmp("test",symname_sc(sc,x)) == 0) printf("test = %p,%p",cdr(sc->code),x);
}
}
if(is_pair(sc->code)) {
cdr(sc->code)->_debugger = x;
}
// std::stringstream ss;
// imp::SchemeInterface::printSchemeCell(sc, ss, sc->code);
// //std::cout << "new func: " << ss.str() << std::endl;
// std::string str(symname_sc(sc,x));
// str = str + " ";
// str = ss.str().insert(1,str);
// sc->reverse_symbol_lookup->insert(std::make_pair(cdr(sc->code),x));
// // if(strcmp("test",symname_sc(sc,x)) == 0) printf("test = %p,%p",cdr(sc->code),x);
// }
/////////////////////////////////////////////////////////////////////////////////////////////////////////////
if (!is_symbol(x)) {
Error_1(sc,"variable is not a symbol",x,sc->code->_debugger->_size);
}
s_save(sc,OP_DEF1, sc->NIL, x);
s_goto(sc,OP_EVAL);
case OP_DEF1: /* define */
x=find_slot_in_env(sc,sc->envir,sc->code,0);
if (x != sc->NIL) {
set_slot_in_env(sc, x, sc->value);
} else {
new_slot_in_env(sc, sc->code, sc->value);
}
s_return(sc,sc->code);
case OP_DEFP: /* defined? */
x=sc->envir;
if(cdr(sc->args)!=sc->NIL) {
x=cadr(sc->args);
}
s_retbool(find_slot_in_env(sc,x,car(sc->args),1)!=sc->NIL);
case OP_SET0: /* set! */
s_save(sc,OP_SET1, sc->NIL, car(sc->code));
sc->code = cadr(sc->code);
s_goto(sc,OP_EVAL);
case OP_SET1: /* set! */
y=find_slot_in_env(sc,sc->envir,sc->code,1);
if (y != sc->NIL) {
set_slot_in_env(sc, y, sc->value);
s_return(sc,sc->value);
} else {
Error_1(sc,"set!: unbound variable:", 0, sc->code->_debugger->_size);
}
case OP_BEGIN: /* begin */
if (!is_pair(sc->code)) {
s_return(sc,sc->code);
}
if (cdr(sc->code) != sc->NIL) {
s_save(sc,OP_BEGIN, sc->NIL, cdr(sc->code));
}
sc->code = car(sc->code);
s_goto(sc,OP_EVAL);
case OP_IF0: /* if */
s_save(sc,OP_IF1, sc->NIL, cdr(sc->code));
sc->code = car(sc->code);
s_goto(sc,OP_EVAL);
case OP_IF1: /* if */
if (is_true(sc->value))
sc->code = car(sc->code);
else
sc->code = cadr(sc->code); /* (if #f 1) ==> () because
* car(sc->NIL) = sc->NIL */
s_goto(sc,OP_EVAL);
case OP_LET0: /* let */
sc->args = sc->NIL;
sc->value = sc->code;
sc->code = is_symbol(car(sc->code)) ? cadr(sc->code) : car(sc->code);
s_goto(sc,OP_LET1);
case OP_LET1: /* let (calculate parameters) */
sc->args = cons(sc, sc->value, sc->args);
if (is_pair(sc->code)) { /* continue */
s_save(sc,OP_LET1, sc->args, cdr(sc->code));
//sorensen replaced this:
//sc->code = cadar(sc->code);
// with this:
sc->code = car(sc->code);
if(!is_pair(sc->code))
Error_0(sc,"Scm Error: Poorly formed let!", sc->code->_size);
sc->code = cadr(sc->code);
////////////////////
sc->args = sc->NIL;
s_goto(sc,OP_EVAL);
} else { /* end */
sc->args = reverse_in_place(sc, sc->NIL, sc->args);
sc->code = car(sc->args);
sc->args = cdr(sc->args);
s_goto(sc,OP_LET2);
}
case OP_LET2: /* let */
new_frame_in_env(sc, sc->envir);
for (x = is_symbol(car(sc->code)) ? cadr(sc->code) : car(sc->code), y = sc->args;
y != sc->NIL; x = cdr(x), y = cdr(y)) {
new_slot_in_env(sc, caar(x), car(y));
}
if (is_symbol(car(sc->code))) { /* named let */
if(!is_pair(cadr(sc->code))) {
Error_0(sc,"Scm Error: Poorly formed named let!", sc->code->_size);
}
for (x = cadr(sc->code), sc->args = sc->NIL; x != sc->NIL; x = cdr(x)) {
sc->args = cons(sc, caar(x), sc->args);
}
x = mk_closure(sc, cons(sc, reverse_in_place(sc, sc->NIL, sc->args), cddr(sc->code)), sc->envir);
new_slot_in_env(sc, car(sc->code), x);
sc->code = cddr(sc->code);
sc->args = sc->NIL;
} else {
sc->code = cdr(sc->code);
sc->args = sc->NIL;
}
s_goto(sc,OP_BEGIN);
case OP_LET0AST: /* let* */{
if (car(sc->code) == sc->NIL) {
new_frame_in_env(sc, sc->envir);
sc->code = cdr(sc->code);
s_goto(sc,OP_BEGIN);
}
s_save(sc,OP_LET1AST, cdr(sc->code), car(sc->code));
////////// AS IMP CODE
if(!is_pair(car(sc->code)))
{
Error_0(sc,"Let* cannot be used for a named let!", sc->code->_size);
}
//////////////////////
// std::stringstream sstt;
// imp::SchemeInterface::printSchemeCell(sc, sstt, sc->code);
// std::cout << "::: " << sstt.str() << std::endl;
sc->code = cadaar(sc->code);
s_goto(sc,OP_EVAL);
}
case OP_LET1AST: /* let* (make new frame) */
new_frame_in_env(sc, sc->envir);
s_goto(sc,OP_LET2AST);
case OP_LET2AST: /* let* (calculate parameters) */
new_slot_in_env(sc, caar(sc->code), sc->value);
sc->code = cdr(sc->code);
if (is_pair(sc->code)) { /* continue */
s_save(sc,OP_LET2AST, sc->args, sc->code);
sc->code = cadar(sc->code);
sc->args = sc->NIL;
s_goto(sc,OP_EVAL);
} else { /* end */
sc->code = sc->args;
sc->args = sc->NIL;
s_goto(sc,OP_BEGIN);
}
default:
sprintf(sc->strbuff, "%d: illegal operator", sc->op);
Error_0(sc,sc->strbuff,0);
// ASIMP
std::cout << "ILLEGAL OPERATION " << sc->op << std::endl;
///////////////
}
return sc->T;
}
static pointer opexe_1(scheme *sc, enum scheme_opcodes op) {
pointer x, y;
switch (op) {
case OP_LET0REC: /* letrec */
new_frame_in_env(sc, sc->envir);
sc->args = sc->NIL;
sc->value = sc->code;
sc->code = car(sc->code);
s_goto(sc,OP_LET1REC);
case OP_LET1REC: /* letrec (calculate parameters) */
sc->args = cons(sc, sc->value, sc->args);
if (is_pair(sc->code)) { /* continue */
s_save(sc,OP_LET1REC, sc->args, cdr(sc->code));
sc->code = cadar(sc->code);
sc->args = sc->NIL;
s_goto(sc,OP_EVAL);
} else { /* end */
sc->args = reverse_in_place(sc, sc->NIL, sc->args);
sc->code = car(sc->args);
sc->args = cdr(sc->args);
s_goto(sc,OP_LET2REC);
}
case OP_LET2REC: /* letrec */
for (x = car(sc->code), y = sc->args; y != sc->NIL; x = cdr(x), y = cdr(y)) {
new_slot_in_env(sc, caar(x), car(y));
}
sc->code = cdr(sc->code);
sc->args = sc->NIL;
s_goto(sc,OP_BEGIN);
case OP_COND0: /* cond */
if (!is_pair(sc->code)) {
Error_0(sc,"syntax error in cond",0);
}
s_save(sc,OP_COND1, sc->NIL, sc->code);
sc->code = caar(sc->code);
s_goto(sc,OP_EVAL);
case OP_COND1: /* cond */
if (is_true(sc->value)) {
if ((sc->code = cdar(sc->code)) == sc->NIL) {
s_return(sc,sc->value);
}
if(car(sc->code)==sc->FEED_TO) {
if(!is_pair(cdr(sc->code))) {
Error_0(sc,"syntax error in cond",0);
}
x=cons(sc, sc->QUOTE, cons(sc, sc->value, sc->NIL));
sc->code=cons(sc,cadr(sc->code),cons(sc,x,sc->NIL));
s_goto(sc,OP_EVAL);
}
s_goto(sc,OP_BEGIN);
} else {
if ((sc->code = cdr(sc->code)) == sc->NIL) {
s_return(sc,sc->NIL);
} else {
s_save(sc,OP_COND1, sc->NIL, sc->code);
sc->code = caar(sc->code);
s_goto(sc,OP_EVAL);
}
}
case OP_DELAY: /* delay */
x = mk_closure(sc, cons(sc, sc->NIL, sc->code), sc->envir);
typeflag(x)=T_PROMISE;
s_return(sc,x);
case OP_AND0: /* and */
if (sc->code == sc->NIL) {
s_return(sc,sc->T);
}
s_save(sc,OP_AND1, sc->NIL, cdr(sc->code));
sc->code = car(sc->code);
s_goto(sc,OP_EVAL);
case OP_AND1: /* and */
if (is_false(sc->value)) {
s_return(sc,sc->value);
} else if (sc->code == sc->NIL) {
s_return(sc,sc->value);
} else {
s_save(sc,OP_AND1, sc->NIL, cdr(sc->code));
sc->code = car(sc->code);
s_goto(sc,OP_EVAL);
}
case OP_OR0: /* or */
if (sc->code == sc->NIL) {
s_return(sc,sc->F);
}
s_save(sc,OP_OR1, sc->NIL, cdr(sc->code));
sc->code = car(sc->code);
s_goto(sc,OP_EVAL);
case OP_OR1: /* or */
if (is_true(sc->value)) {
s_return(sc,sc->value);
} else if (sc->code == sc->NIL) {
s_return(sc,sc->value);
} else {
s_save(sc,OP_OR1, sc->NIL, cdr(sc->code));
sc->code = car(sc->code);
s_goto(sc,OP_EVAL);
}
case OP_C0STREAM: /* cons-stream */
s_save(sc,OP_C1STREAM, sc->NIL, cdr(sc->code));
sc->code = car(sc->code);
s_goto(sc,OP_EVAL);
case OP_C1STREAM: /* cons-stream */
sc->args = sc->value; /* save sc->value to register sc->args for gc */
x = mk_closure(sc, cons(sc, sc->NIL, sc->code), sc->envir);
typeflag(x)=T_PROMISE;
s_return(sc,cons(sc, sc->args, x));
case OP_MACRO0: /* macro */
if (is_pair(car(sc->code))) {
x = caar(sc->code);
sc->code = cons(sc, sc->LAMBDA, cons(sc, cdar(sc->code), cdr(sc->code)));
cdr(sc->code)->_debugger = x;
} else {
x = car(sc->code);
sc->code = cadr(sc->code);
sc->code->_debugger = x;
}
if (!is_symbol(x)) {
Error_1(sc,"variable is not a symbol",x,sc->code->_debugger->_size);
}
s_save(sc,OP_MACRO1, sc->NIL, x);
s_goto(sc,OP_EVAL);
case OP_MACRO1: /* macro */
typeflag(sc->value) = T_MACRO;
x = find_slot_in_env(sc, sc->envir, sc->code, 0);
if (x != sc->NIL) {
set_slot_in_env(sc, x, sc->value);
} else {
new_slot_in_env(sc, sc->code, sc->value);
}
s_return(sc,sc->code);
case OP_CASE0: /* case */
s_save(sc,OP_CASE1, sc->NIL, cdr(sc->code));
sc->code = car(sc->code);
s_goto(sc,OP_EVAL);
case OP_CASE1: /* case */
for (x = sc->code; x != sc->NIL; x = cdr(x)) {
if (!is_pair(y = caar(x))) {
if(is_symbol(caar(x)) && (strcmp(symname(caar(x)),"else")==0)) {
// all good we are in else case
}else{
Error_1(sc,"Syntax Error: Case clause must have the form ((<datum1> ...) <exp1> <exp2> ...) not",car(x),sc->code->_debugger->_size);
}
break;
}
for ( ; y != sc->NIL; y = cdr(y)) {
if (eqv_sc(sc ,car(y), sc->value)) {
break;
}
}
if (y != sc->NIL) {
break;
}
}
if (x != sc->NIL) {
if (is_pair(caar(x))) {
sc->code = cdar(x);
s_goto(sc,OP_BEGIN);
} else {/* else */
s_save(sc,OP_CASE2, sc->NIL, cdar(x));
sc->code = caar(x);
s_goto(sc,OP_EVAL);
}
} else {
s_return(sc,sc->NIL);
}
case OP_CASE2: /* case */
if (is_true(sc->value)) {
s_goto(sc,OP_BEGIN);
} else {
s_return(sc,sc->NIL);
}
case OP_PAPPLY: /* apply */
sc->code = car(sc->args);
sc->args = list_star(sc,cdr(sc->args));
if(!is_pair(sc->args) && sc->args != sc->NIL) {
Error_1(sc,"Error: Apply must finish with a string argument! not:",sc->args,sc->code->_debugger->_size);
}
/*sc->args = cadr(sc->args);*/
s_goto(sc,OP_APPLY);
case OP_PEVAL: /* eval */
if(cdr(sc->args)!=sc->NIL) {
sc->envir=cadr(sc->args);
}
sc->code = car(sc->args);
s_goto(sc,OP_EVAL);
case OP_CONTINUATION: /* call-with-current-continuation */
sc->code = car(sc->args);
sc->args = cons(sc, mk_continuation(sc), sc->NIL);
//sc->args = cons(sc, mk_continuation(sc, sc->dump), sc->NIL);
s_goto(sc,OP_APPLY);
default:
sprintf(sc->strbuff, "%d: illegal operator", sc->op);
Error_0(sc,sc->strbuff,0);
// ASIMP
std::cout << "ILLEGAL OPERATION " << sc->op << std::endl;
///////////////
}
return sc->T;
}
static pointer opexe_2(scheme *sc, enum scheme_opcodes op) {
pointer x;
num v;
#if USE_MATH
double dd;
#endif
switch (op) {
#if USE_MATH
case OP_INEX2EX: /* inexact->exact */
x=car(sc->args);
if(is_integer(x)) {
s_return(sc,x);
} else if(modf(rvalue_unchecked(x),&dd)==0.0) {
s_return(sc,mk_integer(sc,ivalue(x)));
} else {
Error_1(sc,"inexact->exact: not integral:",x,sc->code->_debugger->_size);
}
case OP_EXP:
x=car(sc->args);
s_return(sc, mk_real(sc, exp(rvalue(x))));
case OP_LOG:
x=car(sc->args);
s_return(sc, mk_real(sc, log(rvalue(x))));
case OP_SIN:
x=car(sc->args);
s_return(sc, mk_real(sc, sin(rvalue(x))));
case OP_COS:
x=car(sc->args);
s_return(sc, mk_real(sc, cos(rvalue(x))));
case OP_TAN:
x=car(sc->args);
s_return(sc, mk_real(sc, tan(rvalue(x))));
case OP_ASIN:
x=car(sc->args);
s_return(sc, mk_real(sc, asin(rvalue(x))));
case OP_ACOS:
x=car(sc->args);
s_return(sc, mk_real(sc, acos(rvalue(x))));
case OP_ATAN:
x=car(sc->args);
if(cdr(sc->args)==sc->NIL) {
s_return(sc, mk_real(sc, atan(rvalue(x))));
} else {
pointer y=cadr(sc->args);
s_return(sc, mk_real(sc, atan2(rvalue(x),rvalue(y))));
}
case OP_SQRT:
x=car(sc->args);
s_return(sc, mk_real(sc, sqrt(rvalue(x))));
case OP_EXPT:
x=car(sc->args);
if(cdr(sc->args)==sc->NIL) {
Error_0(sc,"expt: needs two arguments",sc->code->_debugger->_size);
} else {
pointer y=cadr(sc->args);
s_return(sc, mk_real(sc, pow(rvalue(x),rvalue(y))));
}
case OP_FLOOR:
x=car(sc->args);
s_return(sc, mk_real(sc, floor(rvalue(x))));
case OP_CEILING:
x=car(sc->args);
s_return(sc, mk_real(sc, ceil(rvalue(x))));
case OP_TRUNCATE : {
double rvalue_of_x ;
x=car(sc->args);
rvalue_of_x = rvalue(x) ;
if (rvalue_of_x > 0) {
s_return(sc, mk_real(sc, floor(rvalue_of_x)));
} else {
s_return(sc, mk_real(sc, ceil(rvalue_of_x)));
}
}
case OP_ROUND:
x=car(sc->args);
s_return(sc, mk_real(sc, round_per_R5RS(rvalue(x))));
#endif
case OP_ADD: /* + */
v = num_zero;
for (x = sc->args; x != sc->NIL; x = cdr(x)) {
v = num_add(v, nvalue(car(x)));
}
s_return(sc, mk_number(sc, v));
case OP_MUL: /* * */
v=num_one;
for (x = sc->args; x != sc->NIL; x = cdr(x)) {
v=num_mul(v,nvalue(car(x)));
}
s_return(sc,mk_number(sc, v));
case OP_SUB: /* - */
if(cdr(sc->args)==sc->NIL) {
x=sc->args;
v=num_zero;
} else {
x = cdr(sc->args);
v = nvalue(car(sc->args));
}
for (; x != sc->NIL; x = cdr(x)) {
v=num_sub(v,nvalue(car(x)));
}
s_return(sc,mk_number(sc, v));
case OP_DIV: /* / */
if(cdr(sc->args)==sc->NIL) {
x=sc->args;
v=num_one;
} else {
x = cdr(sc->args);
v = nvalue(car(sc->args));
}
for (; x != sc->NIL; x = cdr(x)) {
if (!is_zero_double(rvalue(car(x))))
v=num_div(v,nvalue(car(x)));
else {
std::cout << "DIV BY ZERO ERROR" << std::endl;
Error_0(sc,"/: division by zero",sc->code->_debugger->_size);
}
}
s_return(sc,mk_number(sc, v));
case OP_BITNOT: /* ~ */
v=num_bitnot(nvalue(car(sc->args)));
s_return(sc,mk_number(sc, v));
case OP_BITAND: /* & */
v=num_zero;
x = sc->args;
if (x != sc->NIL) {
v = nvalue(car(x));
for (x = cdr(x); x != sc->NIL; x = cdr(x)) {
v=num_bitand(v,nvalue(car(x)));
}
}
s_return(sc,mk_number(sc, v));
case OP_BITOR: /* | */
v=num_zero;
for (x = sc->args; x != sc->NIL; x = cdr(x)) {
v=num_bitor(v,nvalue(car(x)));
}
s_return(sc,mk_number(sc, v));
case OP_BITEOR: /* ^ */
v=num_zero;
for (x = sc->args; x != sc->NIL; x = cdr(x)) {
v=num_biteor(v,nvalue(car(x)));
}
s_return(sc,mk_number(sc, v));
case OP_BITLSL: /* << */
v=num_zero;
x = sc->args;
if (x != sc->NIL) {
v = nvalue(car(x));
for (x = cdr(x); x != sc->NIL; x = cdr(x)) {
v=num_bitlsl(v,nvalue(car(x)));
}
}
s_return(sc,mk_number(sc, v));
case OP_BITLSR: /* >> */
v=num_zero;
x = sc->args;
if (x != sc->NIL) {
v = nvalue(car(x));
for (x = cdr(x); x != sc->NIL; x = cdr(x)) {
v=num_bitlsr(v,nvalue(car(x)));
}
}
s_return(sc,mk_number(sc, v));
case OP_INTDIV: /* quotient */
if(cdr(sc->args)==sc->NIL) {
x=sc->args;
v=num_one;
} else {
x = cdr(sc->args);
v = nvalue(car(sc->args));
}
for (; x != sc->NIL; x = cdr(x)) {
if (ivalue(car(x)) != 0)
v=num_intdiv(v,nvalue(car(x)));
else {
std::cout << "DIV BY ZERO ERROR" << std::endl;
Error_0(sc,"quotient: division by zero",sc->code->_debugger->_size);
}
}
s_return(sc,mk_number(sc, v));
case OP_REM: /* remainder */
v = nvalue(car(sc->args));
if (ivalue(cadr(sc->args)) != 0)
v=num_rem(v,nvalue(cadr(sc->args)));
else {
std::cout << "DIV BY ZERO ERROR" << std::endl;
Error_0(sc,"remainder: division by zero",sc->code->_debugger->_size);
}
s_return(sc,mk_number(sc, v));
case OP_MOD: /* modulo */
v = nvalue(car(sc->args));
//if (ivalue(cadr(sc->args)) != 0)
if (!is_zero_double(rvalue(cadr(sc->args))))
v=num_mod(v,nvalue(cadr(sc->args)));
else {
std::cout << "DIV BY ZERO ERROR" << std::endl;
Error_0(sc,"modulo: division by zero",sc->code->_debugger->_size);
}
s_return(sc,mk_number(sc, v));
case OP_CAR: /* car */
s_return(sc,caar(sc->args));
case OP_CDR: /* cdr */
s_return(sc,cdar(sc->args));
case OP_CONS: /* cons */
cdr(sc->args) = cadr(sc->args);
////////////// write barrier for treadmill
#ifdef TREADMILL_CHECKS
last_call_to_insert_treadmill = 20;
#endif
insert_treadmill(sc,cdr(sc->args));
//////////////////////////////////////////
s_return(sc,sc->args);
case OP_SETCAR: /* set-car! */
if(!is_immutable(car(sc->args))) {
////////////// write barrier for treadmill
#ifdef TREADMILL_CHECKS
last_call_to_insert_treadmill = 21;
#endif
insert_treadmill(sc,cadr(sc->args));
//////////////////////////////////////////
caar(sc->args) = cadr(sc->args);
s_return(sc,car(sc->args));
} else {
Error_0(sc,"set-car!: unable to alter immutable pair",sc->code->_debugger->_size);
}
case OP_SETCDR: /* set-cdr! */
if(!is_immutable(car(sc->args))) {
////////////// write barrier for treadmill
#ifdef TREADMILL_CHECKS
last_call_to_insert_treadmill = 22;
#endif
insert_treadmill(sc,cadr(sc->args));
//////////////////////////////////////////
cdar(sc->args) = cadr(sc->args);
s_return(sc,car(sc->args));
} else {
Error_0(sc,"set-cdr!: unable to alter immutable pair",sc->code->_debugger->_size);
}
case OP_CHAR2INT: { /* char->integer */
char c;
c=(char)ivalue(car(sc->args));
s_return(sc,mk_integer(sc,(unsigned char)c));
}
case OP_INT2CHAR: { /* integer->char */
unsigned char c;
c=(unsigned char)ivalue(car(sc->args));
s_return(sc,mk_character(sc,(char)c));
}
case OP_CHARUPCASE: {
unsigned char c;
c=(unsigned char)ivalue(car(sc->args));
c=toupper(c);
s_return(sc,mk_character(sc,(char)c));
}
case OP_CHARDNCASE: {
unsigned char c;
c=(unsigned char)ivalue(car(sc->args));
c=tolower(c);
s_return(sc,mk_character(sc,(char)c));
}
case OP_STR2SYM: /* string->symbol */
s_return(sc,mk_symbol(sc,strvalue(car(sc->args))));
case OP_STR2ATOM: /* string->atom */ {
char *s=strvalue(car(sc->args));
if(*s=='#') {
s_return(sc, mk_sharp_const(sc, s+1));
} else {
s_return(sc, mk_atom(sc, s));
}
}
case OP_SYM2STR: /* symbol->string */
x=mk_string(sc,symname_sc(sc,car(sc->args)));
setimmutable(x);
s_return(sc,x);
case OP_ATOM2STR: /* atom->string */
x=car(sc->args);
if(is_number(x) || is_character(x) || is_string(x) || is_symbol(x)) {
char *p;
int len;
atom2str(sc,x,0,&p,&len);
s_return(sc,mk_counted_string(sc,p,len));
} else {
Error_1(sc, "atom->string: not an atom:", x, sc->code->_debugger->_size);
}
case OP_MKSTRING: { /* make-string */
int fill=' ';
int len;
len=ivalue(car(sc->args));
if(cdr(sc->args)!=sc->NIL) {
fill=charvalue_sc(sc,cadr(sc->args));
}
s_return(sc,mk_empty_string(sc,len,(char)fill));
}
case OP_STRLEN: /* string-length */
s_return(sc,mk_integer(sc,strlength(car(sc->args))));
case OP_STRREF: { /* string-ref */
char *str;
int index;
str=strvalue(car(sc->args));
index=ivalue(cadr(sc->args));
if(index>=strlength(car(sc->args))) {
Error_1(sc,"string-ref: out of bounds:",cadr(sc->args), sc->code->_debugger->_size);
}
s_return(sc,mk_character(sc,((unsigned char*)str)[index]));
}
case OP_STRSET: { /* string-set! */
char *str;
int index;
int c;
if(is_immutable(car(sc->args))) {
Error_1(sc,"string-set!: unable to alter immutable string:",car(sc->args), sc->code->_debugger->_size);
}
str=strvalue(car(sc->args));
index=ivalue(cadr(sc->args));
if(index>=strlength(car(sc->args))) {
Error_1(sc,"string-set!: out of bounds:",cadr(sc->args), sc->code->_debugger->_size);
}
c=charvalue_sc(sc,caddr(sc->args));
str[index]=(char)c;
s_return(sc,car(sc->args));
}
case OP_STRAPPEND: { /* string-append */
/* in 1.29 string-append was in Scheme in init.scm but was too slow */
int len = 0;
pointer newstr;
char *pos;
/* compute needed length for new string */
for (x = sc->args; x != sc->NIL; x = cdr(x)) {
len += strlength(car(x));
}
newstr = mk_empty_string(sc, len, ' ');
/* store the contents of the argument strings into the new string */
for (pos = strvalue(newstr), x = sc->args; x != sc->NIL;
pos += strlength(car(x)), x = cdr(x)) {
memcpy(pos, strvalue(car(x)), strlength(car(x)));
}
s_return(sc, newstr);
}
case OP_SUBSTR: { /* substring */
char *str;
int index0;
int index1;
int len;
str=strvalue(car(sc->args));
index0=ivalue(cadr(sc->args));
if(index0>strlength(car(sc->args))) {
Error_1(sc,"substring: start out of bounds:",cadr(sc->args), sc->code->_debugger->_size);
}
if(cddr(sc->args)!=sc->NIL) {
index1=ivalue(caddr(sc->args));
if(index1>strlength(car(sc->args)) || index1<index0) {
Error_1(sc,"substring: end out of bounds:",caddr(sc->args),sc->code->_debugger->_size);
}
} else {
index1=strlength(car(sc->args));
}
len=index1-index0;
x=mk_empty_string(sc,len,' ');
memcpy(strvalue(x),str+index0,len);
strvalue(x)[len]=0;
s_return(sc,x);
}
case OP_VECTOR: { /* vector */
int i;
pointer vec;
int len=list_length(sc,sc->args);
if(len<0) {
Error_1(sc,"vector: not a proper list:",sc->args,sc->code->_debugger->_size);
}
vec=mk_vector(sc,len);
for (x = sc->args, i = 0; is_pair(x); x = cdr(x), i++) {
set_vector_elem(sc, vec,i,car(x));
}
s_return(sc,vec);
}
case OP_MKVECTOR: { /* make-vector */
pointer fill=sc->NIL;
int len;
pointer vec;
len=ivalue(car(sc->args));
if(cdr(sc->args)!=sc->NIL) {
fill=cadr(sc->args);
}
vec=mk_vector(sc,len);
if(fill!=sc->NIL) {
fill_vector(sc,vec,fill);
}
s_return(sc,vec);
}
case OP_VECLEN: /* vector-length */
s_return(sc,mk_integer(sc,(car(sc->args))->_size));
//s_return(sc,mk_integer(sc,ivalue(car(sc->args))));
case OP_VECREF: { /* vector-ref */
int index;
index=ivalue(cadr(sc->args));
if(index>=(car(sc->args))->_size) {
Error_1(sc,"vector-ref: out of bounds:",cadr(sc->args),sc->code->_debugger->_size);
}
s_return(sc,vector_elem(car(sc->args),index));
}
case OP_VECSET: { /* vector-set! */
int index;
if(is_immutable(car(sc->args))) {
Error_1(sc,"vector-set!: unable to alter immutable vector:",car(sc->args),sc->code->_debugger->_size);
}
index=ivalue(cadr(sc->args));
if(index>=(car(sc->args))->_size) {
Error_1(sc,"vector-set!: out of bounds:",cadr(sc->args),sc->code->_debugger->_size);
}
set_vector_elem(sc, car(sc->args),index,caddr(sc->args));
s_return(sc,car(sc->args));
}
default:
sprintf(sc->strbuff, "%d: illegal operator", sc->op);
Error_0(sc,sc->strbuff,sc->code->_debugger->_size);
// ASIMP
std::cout << "ILLEGAL OPERATION " << sc->op << std::endl;
///////////////
}
return sc->T;
}
// keys of assoc lst MUST be strings OR symbols
pointer assoc_strcmp(scheme *sc, pointer key, pointer lst, bool all)
{
pointer errVal = (!all) ? sc->F : sc->NIL;
pointer retlist = errVal;
if (likely(is_symbol(key))) {
auto skey = strvalue(car(key));
for (auto x = lst; is_pair(x); x = cdr(x)) {
auto pair = car(x);
if (unlikely(!is_pair(pair))) {
return errVal;
}
auto r1 = car(pair);
if (unlikely(!is_symbol(r1))) {
return errVal;
}
auto lkey = strvalue(car(r1));
if (!strcmp(lkey, skey)) {
if (likely(!all)) {
return pair;
}
retlist = cons(sc, pair, retlist);
}
}
return retlist;
}
if (is_string(key)) {
auto skey = strvalue(key);
for (auto x = lst; is_pair(x); x = cdr(x)) {
auto pair = car(x);
if (unlikely(!is_pair(pair))) {
return errVal;
}
auto lkey = strvalue(car(pair));
if (!strcmp(lkey,skey)) {
if (likely(!all)) {
return pair;
}
retlist = cons(sc, pair, retlist);
}
}
return retlist;
}
// it not neccessarily a problem for the key to be a non-symbol/string
// although it should return false of course
// which it does after falling through to the final return
return retlist;
}
EXPORT pointer list_ref(scheme *sc, const int pos, pointer a) {
pointer x;
for (int i = 0; i <= pos; ++i, a = cdr(a)) {
if (unlikely(!is_pair(a))) {
return sc->NIL;
}
x = car(a);
}
return x;
}
static pointer opexe_3(scheme *sc, enum scheme_opcodes op) {
pointer x;
num v;
int (*comp_func)(const num&, const num&) = 0;
switch (op) {
case OP_NOT: /* not */
s_retbool(is_false(car(sc->args)));
case OP_BOOLP: /* boolean? */
s_retbool(car(sc->args) == sc->F || car(sc->args) == sc->T);
case OP_EOFOBJP: /* boolean? */
s_retbool(car(sc->args) == sc->EOF_OBJ);
case OP_NULLP: /* null? */
s_retbool(car(sc->args) == sc->NIL);
case OP_NUMEQ: /* = */
case OP_LESS: /* < */
case OP_GRE: /* > */
case OP_LEQ: /* <= */
case OP_GEQ: /* >= */
switch(op) {
case OP_NUMEQ: comp_func=num_eq; break;
case OP_LESS: comp_func=num_lt; break;
case OP_GRE: comp_func=num_gt; break;
case OP_LEQ: comp_func=num_le; break;
case OP_GEQ: comp_func=num_ge; break;
}
x=sc->args;
v=nvalue(car(x));
x=cdr(x);
for (; x != sc->NIL; x = cdr(x)) {
if(!comp_func(v,nvalue(car(x)))) {
s_retbool(0);
}
v=nvalue(car(x));
}
s_retbool(1);
case OP_SYMBOLP: /* symbol? */
s_retbool(is_symbol(car(sc->args)));
case OP_NUMBERP: /* number? */
s_retbool(is_number(car(sc->args)));
case OP_STRINGP: /* string? */
s_retbool(is_string(car(sc->args)));
case OP_INTEGERP: /* integer? */
s_retbool(is_integer(car(sc->args)));
case OP_REALP: /* real? */
s_retbool(is_number(car(sc->args))); /* All numbers are real */
case OP_RATIONALP: /* rational? */
s_retbool(is_rational(car(sc->args)));
case OP_CHARP: /* char? */
s_retbool(is_character(car(sc->args)));
#if USE_CHAR_CLASSIFIERS
case OP_CHARAP: /* char-alphabetic? */
s_retbool(Cisalpha(ivalue(car(sc->args))));
case OP_CHARNP: /* char-numeric? */
s_retbool(Cisdigit(ivalue(car(sc->args))));
case OP_CHARWP: /* char-whitespace? */
s_retbool(Cisspace(ivalue(car(sc->args))));
case OP_CHARUP: /* char-upper-case? */
s_retbool(Cisupper(ivalue(car(sc->args))));
case OP_CHARLP: /* char-lower-case? */
s_retbool(Cislower(ivalue(car(sc->args))));
#endif
case OP_PORTP: /* port? */
s_retbool(is_port(car(sc->args)));
case OP_INPORTP: /* input-port? */
s_retbool(is_inport(car(sc->args)));
case OP_OUTPORTP: /* output-port? */
s_retbool(is_outport(car(sc->args)));
case OP_PROCP: /* procedure? */
/*--
* continuation should be procedure by the example
* (call-with-current-continuation procedure?) ==> #t
* in R^3 report sec. 6.9
*/
s_retbool(is_proc(car(sc->args)) || is_closure(car(sc->args))
|| is_continuation(car(sc->args)) || is_foreign(car(sc->args)));
case OP_PAIRP: /* pair? */
s_retbool(is_pair(car(sc->args)));
case OP_LISTP: { /* list? */
pointer slow, fast;
slow = fast = car(sc->args);
while (1) {
if (!is_pair(fast)) s_retbool(fast == sc->NIL);
fast = cdr(fast);
if (!is_pair(fast)) s_retbool(fast == sc->NIL);
fast = cdr(fast);
slow = cdr(slow);
if (fast == slow) {
/* the fast pointer has looped back around and caught up
with the slow pointer, hence the structure is circular,
not of finite length, and therefore not a list */
s_retbool(0);
}
}
}
case OP_ENVP: /* environment? */
s_retbool(is_environment(car(sc->args)));
case OP_VECTORP: /* vector? */
s_retbool(is_vector(car(sc->args)));
case OP_CPTRP: /* cstr? */
s_retbool(is_cptr(car(sc->args)));
// case OP_OBJCP: /* cstr? */
// s_retbool(is_objc(car(sc->args)));
case OP_EQ: /* eq? */
s_retbool(car(sc->args) == cadr(sc->args));
case OP_EQV: /* eqv? */
s_retbool(eqv_sc(sc, car(sc->args), cadr(sc->args)));
default:
sprintf(sc->strbuff, "%d: illegal operator", sc->op);
Error_0(sc,sc->strbuff,sc->code->_debugger->_size);
// ASIMP
std::cout << "ILLEGAL OPERATION " << sc->op << std::endl;
///////////////
}
return sc->T;
}
static pointer opexe_4(scheme *sc, enum scheme_opcodes op) {
pointer x, y;
switch (op) {
case OP_FORCE: /* force */
sc->code = car(sc->args);
if (is_promise(sc->code)) {
/* Should change type to closure here */
s_save(sc, OP_SAVE_FORCED, sc->NIL, sc->code);
sc->args = sc->NIL;
s_goto(sc,OP_APPLY);
} else {
s_return(sc,sc->code);
}
case OP_SAVE_FORCED: /* Save forced value replacing promise */
memcpy(sc->code,sc->value,sizeof(struct cell));
s_return(sc,sc->value);
case OP_WRITE: /* write */
case OP_DISPLAY: /* display */
case OP_WRITE_CHAR: /* write-char */
if(is_pair(cdr(sc->args))) {
if(cadr(sc->args)!=sc->outport) {
x=cons(sc,sc->outport,sc->NIL);
s_save(sc,OP_SET_OUTPORT, x, sc->NIL);
sc->outport=cadr(sc->args);
}
}
sc->args = car(sc->args);
if(op==OP_WRITE) {
sc->print_flag = 1;
} else {
sc->print_flag = 0;
}
s_goto(sc,OP_P0LIST);
case OP_NEWLINE: /* newline */
if(is_pair(sc->args)) {
if(car(sc->args)!=sc->outport) {
x=cons(sc,sc->outport,sc->NIL);
s_save(sc,OP_SET_OUTPORT, x, sc->NIL);
sc->outport=car(sc->args);
}
}
putstr(sc, "\n");
s_return(sc,sc->T);
case OP_ERR0: /* error */
sc->retcode=-1;
if (!is_string(car(sc->args))) {
sc->args=cons(sc,mk_string(sc," -- "),sc->args);
setimmutable(car(sc->args));
}
//putstr(sc, "Error: ");
//putstr(sc, strvalue(car(sc->args)));
sc->args = cdr(sc->args);
s_goto(sc,OP_ERR1);
case OP_ERR1: /* error */
putstr(sc, " ");
if (sc->args != sc->NIL) {
s_save(sc,OP_ERR1, cdr(sc->args), sc->NIL);
sc->args = car(sc->args);
sc->print_flag = 1;
s_goto(sc,OP_P0LIST);
} else {
putstr(sc, "\n");
if(sc->interactive_repl) {
s_goto(sc,OP_T0LVL);
} else {
return sc->NIL;
}
}
case OP_REVERSE: /* reverse */
s_return(sc,reverse(sc, car(sc->args)));
case OP_LIST_STAR: /* list* */
s_return(sc,list_star(sc,sc->args));
case OP_APPEND: /* append */
if(sc->args==sc->NIL) {
s_return(sc,sc->NIL);
}
x=car(sc->args);
if(cdr(sc->args)==sc->NIL) {
s_return(sc,sc->args);
}
for (y = cdr(sc->args); y != sc->NIL; y = cdr(y)) {
x=append(sc,x,car(y));
}
s_return(sc,x);
#if USE_PLIST
case OP_PUT: /* put */
if (!hasprop(car(sc->args)) || !hasprop(cadr(sc->args))) {
Error_0(sc,"illegal use of put",sc->code->_debugger->_size);
}
for (x = symprop(car(sc->args)), y = cadr(sc->args); x != sc->NIL; x = cdr(x)) {
if (caar(x) == y) {
break;
}
}
if (x != sc->NIL)
cdar(x) = caddr(sc->args);
else
symprop(car(sc->args)) = cons(sc, cons(sc, y, caddr(sc->args)),
symprop(car(sc->args)));
s_return(sc,sc->T);
case OP_GET: /* get */
if (!hasprop(car(sc->args)) || !hasprop(cadr(sc->args))) {
Error_0(sc,"illegal use of get",sc->code->_debugger->_size);
}
for (x = symprop(car(sc->args)), y = cadr(sc->args); x != sc->NIL; x = cdr(x)) {
if (caar(x) == y) {
break;
}
}
if (x != sc->NIL) {
s_return(sc,cdar(x));
} else {
s_return(sc,sc->NIL);
}
#endif /* USE_PLIST */
case OP_QUIT: /* quit */
if(is_pair(sc->args)) {
sc->retcode=ivalue(car(sc->args));
}
return (sc->NIL);
case OP_NEWSEGMENT: /* new-segment */
if (!is_pair(sc->args) || !is_number(car(sc->args))) {
Error_0(sc,"new-segment: argument must be a number",0);
}
alloc_cellseg(sc, (int) ivalue(car(sc->args)));
s_return(sc,sc->T);
case OP_OBLIST: /* oblist */
s_return(sc, oblist_all_symbols(sc));
case OP_CURR_INPORT: /* current-input-port */
s_return(sc,sc->inport);
case OP_CURR_OUTPORT: /* current-output-port */
s_return(sc,sc->outport);
case OP_OPEN_INFILE: /* open-input-file */
case OP_OPEN_OUTFILE: /* open-output-file */
case OP_OPEN_INOUTFILE: /* open-input-output-file */ {
int prop=0;
pointer p;
switch(op) {
case OP_OPEN_INFILE: prop=port_input; break;
case OP_OPEN_OUTFILE: prop=port_output; break;
case OP_OPEN_INOUTFILE: prop=port_input|port_output; break;
}
p=port_from_filename(sc,strvalue(car(sc->args)),prop);
if(p==sc->NIL) {
s_return(sc,sc->F);
}
s_return(sc,p);
}
#if USE_STRING_PORTS
case OP_OPEN_INSTRING: /* open-input-string */
case OP_OPEN_INOUTSTRING: /* open-input-output-string */ {
int prop=0;
pointer p;
switch(op) {
case OP_OPEN_INSTRING: prop=port_input; break;
case OP_OPEN_INOUTSTRING: prop=port_input|port_output; break;
}
p=port_from_string(sc, strvalue(car(sc->args)),
strvalue(car(sc->args))+strlength(car(sc->args)), prop);
if(p==sc->NIL) {
s_return(sc,sc->F);
}
s_return(sc,p);
}
case OP_OPEN_OUTSTRING: /* open-output-string */ {
pointer p;
if(car(sc->args)==sc->NIL) {
p=port_from_scratch(sc);
if(p==sc->NIL) {
s_return(sc,sc->F);
}
} else {
p=port_from_string(sc, strvalue(car(sc->args)),
strvalue(car(sc->args))+strlength(car(sc->args)),
port_output);
if(p==sc->NIL) {
s_return(sc,sc->F);
}
}
s_return(sc,p);
}
case OP_GET_OUTSTRING: /* get-output-string */ {
port *p;
if ((p=car(sc->args)->_object._port)->kind&port_string) {
off_t size;
char *str;
size=p->rep.string.curr-p->rep.string.start+1;
if((str=(char*)sc->malloc(size))) {
pointer s;
memcpy(str,p->rep.string.start,size-1);
str[size-1]='\0';
s=mk_string(sc,str);
sc->free(str);
s_return(sc,s);
}
}
s_return(sc,sc->F);
}
#endif
case OP_CLOSE_INPORT: /* close-input-port */
port_close(sc,car(sc->args),port_input);
s_return(sc,sc->T);
case OP_CLOSE_OUTPORT: /* close-output-port */
port_close(sc,car(sc->args),port_output);
s_return(sc,sc->T);
case OP_INT_ENV: /* interaction-environment */
s_return(sc,sc->global_env);
case OP_CURR_ENV: /* current-environment */
s_return(sc,sc->envir);
}
return sc->T;
}
static pointer opexe_5(scheme *sc, enum scheme_opcodes op) {
pointer x;
if(sc->nesting!=0) {
int n=sc->nesting;
sc->nesting=0;
sc->retcode=-1;
Error_1(sc,"unmatched parentheses:",mk_integer(sc,n),0);
}
switch (op) {
/* ========== reading part ========== */
case OP_READ:
if(!is_pair(sc->args)) {
s_goto(sc,OP_READ_INTERNAL);
}
if(!is_inport(car(sc->args))) {
Error_1(sc,"read: not an input port:",car(sc->args),sc->code->_debugger->_size);
}
if(car(sc->args)==sc->inport) {
s_goto(sc,OP_READ_INTERNAL);
}
x=sc->inport;
sc->inport=car(sc->args);
//////////////////////////////////////////////
//IMPROMPTU BUG WHEN CALLING FROM scheme_call
// if sc->inport is not actually an inport
// we don't want to call OP_SET_INPORT after
// doing our read to reset the inport
if(is_inport(x))
{
x=cons(sc,x,sc->NIL);
s_save(sc,OP_SET_INPORT, x, sc->NIL);
}
//////////////////////////////////////////////
s_goto(sc,OP_READ_INTERNAL);
case OP_READ_CHAR: /* read-char */
case OP_PEEK_CHAR: /* peek-char */ {
int c;
if(is_pair(sc->args)) {
if(car(sc->args)!=sc->inport) {
x=sc->inport;
x=cons(sc,x,sc->NIL);
s_save(sc,OP_SET_INPORT, x, sc->NIL);
sc->inport=car(sc->args);
}
}
c=inchar(sc);
if(c==EOF) {
s_return(sc,sc->EOF_OBJ);
}
if(sc->op==OP_PEEK_CHAR) {
backchar(sc,c);
}
s_return(sc,mk_character(sc,c));
}
case OP_CHAR_READY: /* char-ready? */ {
pointer p=sc->inport;
int res;
if(is_pair(sc->args)) {
p=car(sc->args);
}
res=p->_object._port->kind&port_string;
s_retbool(res);
}
case OP_SET_INPORT: /* set-input-port */
sc->inport=car(sc->args);
s_return(sc,sc->value);
case OP_SET_OUTPORT: /* set-output-port */
sc->outport=car(sc->args);
s_return(sc,sc->value);
case OP_RDSEXPR:
switch (sc->tok) {
case TOK_EOF:
if(sc->inport==sc->loadport) {
sc->args=sc->NIL;
s_goto(sc,OP_QUIT);
} else {
s_return(sc,sc->EOF_OBJ);
}
case TOK_COMMENT: {
int c;
while ((c=inchar(sc)) != '\n' && c!=EOF)
;
sc->tok = token(sc);
s_goto(sc,OP_RDSEXPR);
}
case TOK_VEC:
s_save(sc,OP_RDVEC,sc->NIL,sc->NIL);
/* fall through */
case TOK_LPAREN:
sc->tok = token(sc);
if (sc->tok == TOK_RPAREN) {
s_return(sc,sc->NIL);
} else if (sc->tok == TOK_DOT) {
Error_0(sc,"syntax error: illegal dot expression",sc->code->_debugger->_size);
} else {
sc->nesting_stack[sc->file_i]++;
s_save(sc,OP_RDLIST, sc->NIL, sc->NIL);
s_goto(sc,OP_RDSEXPR);
}
case TOK_QUOTE:
s_save(sc,OP_RDQUOTE, sc->NIL, sc->NIL);
sc->tok = token(sc);
s_goto(sc,OP_RDSEXPR);
case TOK_BQUOTE:
sc->tok = token(sc);
if(sc->tok==TOK_VEC) {
s_save(sc,OP_RDQQUOTEVEC, sc->NIL, sc->NIL);
sc->tok=TOK_LPAREN;
s_goto(sc,OP_RDSEXPR);
} else {
s_save(sc,OP_RDQQUOTE, sc->NIL, sc->NIL);
}
s_goto(sc,OP_RDSEXPR);
case TOK_COMMA:
s_save(sc,OP_RDUNQUOTE, sc->NIL, sc->NIL);
sc->tok = token(sc);
s_goto(sc,OP_RDSEXPR);
case TOK_ATMARK:
s_save(sc,OP_RDUQTSP, sc->NIL, sc->NIL);
sc->tok = token(sc);
s_goto(sc,OP_RDSEXPR);
case TOK_ATOM:
s_return(sc,mk_atom(sc, readstr_upto(sc, (char*)"();\t\n\r ")));
case TOK_DQUOTE:
x=readstrexp(sc);
if(x==sc->F) {
Error_0(sc,"Error reading string",sc->args->_size);
}
setimmutable(x);
s_return(sc,x);
case TOK_SHARP: {
pointer f=find_slot_in_env(sc,sc->envir,sc->SHARP_HOOK,1);
if(f==sc->NIL) {
Error_0(sc,"undefined sharp expression",sc->args->_size);
} else {
sc->code=cons(sc,slot_value_in_env(f),sc->NIL);
s_goto(sc,OP_EVAL);
}
}
case TOK_SHARP_CONST:
if ((x = mk_sharp_const(sc, readstr_upto(sc, (char*)"();\t\n\r "))) == sc->NIL) {
Error_0(sc,"undefined sharp expression",sc->args->_size);
} else {
s_return(sc,x);
}
default:
if(sc->tok == 1) {
std::cout << "ILLEGAL RIGHT BRACKET!!!" << std::endl;
std::cout << "Check for unbalanced expression" << std::endl;
Error_0(sc,"Illegal right bracket: unbalanced expr?",sc->args->_size);
}else{
std::cout << "ILLEGAL TOKEN: " << sc->tok << std::endl;
Error_0(sc,"syntax error: illegal token",sc->args->_size);
}
}
break;
case OP_RDLIST: {
sc->args = cons(sc, sc->value, sc->args);
//////////////////////////////////////////
//added for debugger
if(sc->inport != sc->NIL && sc->inport->_object._port->kind&port_string) {
int position = 0;
char* ptr = sc->inport->_object._port->rep.string.start;
for( ; &ptr[position] < &sc->inport->_object._port->rep.string.curr[0]; position++);
//int lgth = strlen(name);
if(is_symbol(sc->value))
{
sc->args->_size = position - car(sc->value)->_object._string._length;
//std::cout << car(sc->value)->_object._string._svalue << " pos: " << sc->args->_size << std::endl;
}
}
// std::stringstream ss;
// imp::SchemeInterface::printSchemeCell(sc, ss, sc->value);
// std::cout << "stuff: " << ss.str() << std::endl;
sc->tok = token(sc);
if (sc->tok == TOK_COMMENT) {
int c;
while ((c=inchar(sc)) != '\n' && c!=EOF)
;
sc->tok = token(sc);
}
if (sc->tok == TOK_RPAREN) {
int c = inchar(sc);
if (c != '\n') backchar(sc,c);
sc->nesting_stack[sc->file_i]--;
s_return(sc,reverse_in_place(sc, sc->NIL, sc->args));
} else if (sc->tok == TOK_DOT) {
s_save(sc,OP_RDDOT, sc->args, sc->NIL);
sc->tok = token(sc);
s_goto(sc,OP_RDSEXPR);
} else {
s_save(sc,OP_RDLIST, sc->args, sc->NIL);;
s_goto(sc,OP_RDSEXPR);
}
}
case OP_RDDOT:
if (token(sc) != TOK_RPAREN) {
Error_0(sc,"syntax error: illegal dot expression",sc->code->_debugger->_size);
} else {
sc->nesting_stack[sc->file_i]--;
s_return(sc,reverse_in_place(sc, sc->value, sc->args));
}
case OP_RDQUOTE:
s_return(sc,cons(sc, sc->QUOTE, cons(sc, sc->value, sc->NIL)));
case OP_RDQQUOTE:
s_return(sc,cons(sc, sc->QQUOTE, cons(sc, sc->value, sc->NIL)));
case OP_RDQQUOTEVEC:
s_return(sc,cons(sc, mk_symbol(sc,"apply"),
cons(sc, mk_symbol(sc,"vector"),
cons(sc,cons(sc, sc->QQUOTE,
cons(sc,sc->value,sc->NIL)),
sc->NIL))));
case OP_RDUNQUOTE:
s_return(sc,cons(sc, sc->UNQUOTE, cons(sc, sc->value, sc->NIL)));
case OP_RDUQTSP:
s_return(sc,cons(sc, sc->UNQUOTESP, cons(sc, sc->value, sc->NIL)));
case OP_RDVEC:
sc->args=sc->value;
s_goto(sc,OP_VECTOR);
/* ========== printing part ========== */
case OP_P0LIST:
if(is_vector(sc->args)) {
putstr(sc,"#(");
sc->args=cons(sc,sc->args,mk_integer(sc,0));
s_goto(sc,OP_PVECFROM);
} else if(is_environment(sc->args)) {
putstr(sc,"#<ENVIRONMENT>");
s_return(sc,sc->T);
} else if (!is_pair(sc->args)) {
printatom(sc, sc->args, sc->print_flag);
s_return(sc,sc->T);
} else if (car(sc->args) == sc->QUOTE && ok_abbrev(cdr(sc->args))) {
putstr(sc, "'");
sc->args = cadr(sc->args);
s_goto(sc,OP_P0LIST);
} else if (car(sc->args) == sc->QQUOTE && ok_abbrev(cdr(sc->args))) {
putstr(sc, "`");
sc->args = cadr(sc->args);
s_goto(sc,OP_P0LIST);
} else if (car(sc->args) == sc->UNQUOTE && ok_abbrev(cdr(sc->args))) {
putstr(sc, ",");
sc->args = cadr(sc->args);
s_goto(sc,OP_P0LIST);
} else if (car(sc->args) == sc->UNQUOTESP && ok_abbrev(cdr(sc->args))) {
putstr(sc, ",@");
sc->args = cadr(sc->args);
s_goto(sc,OP_P0LIST);
} else {
putstr(sc, "(");
s_save(sc,OP_P1LIST, cdr(sc->args), sc->NIL);
sc->args = car(sc->args);
s_goto(sc,OP_P0LIST);
}
case OP_P1LIST:
if (is_pair(sc->args)) {
s_save(sc,OP_P1LIST, cdr(sc->args), sc->NIL);
putstr(sc, " ");
sc->args = car(sc->args);
s_goto(sc,OP_P0LIST);
} else if(is_vector(sc->args)) {
s_save(sc,OP_P1LIST,sc->NIL,sc->NIL);
putstr(sc, " . ");
s_goto(sc,OP_P0LIST);
} else {
if (sc->args != sc->NIL) {
putstr(sc, " . ");
printatom(sc, sc->args, sc->print_flag);
}
putstr(sc, ")");
s_return(sc,sc->T);
}
case OP_PVECFROM: {
int i=ivalue_unchecked(cdr(sc->args));
pointer vec=car(sc->args);
int len=ivalue_unchecked(vec);
if(i==len) {
putstr(sc,")");
s_return(sc,sc->T);
} else {
pointer elem=vector_elem(vec,i);
ivalue_unchecked(cdr(sc->args))=i+1;
s_save(sc,OP_PVECFROM, sc->args, sc->NIL);
sc->args=elem;
putstr(sc," ");
s_goto(sc,OP_P0LIST);
}
}
default:
sprintf(sc->strbuff, "%d: illegal operator", sc->op);
Error_0(sc,sc->strbuff,0);
// ASIMP
std::cout << "ILLEGAL OPERATION " << sc->op << std::endl;
///////////////
}
return sc->T;
}
static pointer opexe_6(scheme *sc, enum scheme_opcodes op) {
pointer x, y;
long v;
switch (op) {
case OP_LIST_LENGTH: /* length */ /* a.k */
v=list_length(sc,car(sc->args));
if(v<0) {
Error_1(sc,"length: not a list:",car(sc->args),sc->args->_size);
}
s_return(sc,mk_integer(sc, v));
case OP_ASSQ: /* assq */ /* a.k */
x = car(sc->args);
for (y = cadr(sc->args); is_pair(y); y = cdr(y)) {
if (!is_pair(car(y))) {
Error_0(sc,"unable to handle non pair element",sc->args->_size);
}
if (x == caar(y))
break;
}
if (is_pair(y)) {
s_return(sc,car(y));
} else {
s_return(sc,sc->F);
}
case OP_GET_CLOSURE: /* get-closure-code */ /* a.k */
sc->args = car(sc->args);
if (sc->args == sc->NIL) {
s_return(sc,sc->F);
} else if (is_closure(sc->args)) {
s_return(sc,cons(sc, sc->LAMBDA, closure_code(sc->value)));
} else if (is_macro(sc->args)) {
s_return(sc,cons(sc, sc->LAMBDA, closure_code(sc->value)));
} else {
s_return(sc,sc->F);
}
case OP_CLOSUREP: /* closure? */
/*
* macro object is also a closure.
* Therefore, (closure? <#MACRO>) ==> #t
*/
s_retbool(is_closure(car(sc->args)));
case OP_MACROP: /* macro? */
s_retbool(is_macro(car(sc->args)));
default:
sprintf(sc->strbuff, "%d: illegal operator", sc->op);
Error_0(sc,sc->strbuff,0);
// ASIMP
std::cout << "ILLEGAL OPERATION " << sc->op << std::endl;
///////////////
}
return sc->T; /* NOTREACHED */
}
typedef pointer (*dispatch_func)(scheme *, enum scheme_opcodes);
typedef int (*test_predicate)(pointer);
static int is_any(pointer p) { return 1;}
static int is_num_integer(pointer p) {
return is_number(p) && ((p)->_object._number.num_type==0);
//return is_number(p) && ((p)->_object._number.is_fixnum);
}
static int is_nonneg(pointer p) {
return is_num_integer(p) && ivalue(p)>=0;
}
/* Correspond carefully with following defines! */
static struct {
test_predicate fct;
const char *kind;
} tests[]={
{0,0}, /* unused */
{is_any, 0},
{is_string, "string"},
{is_symbol, "symbol"},
{is_port, "port"},
{0,"input port"},
{0,"output_port"},
{is_environment, "environment"},
{is_pair, "pair"},
{0, "pair or '()"},
{is_character, "character"},
{is_vector, "vector"},
{is_number, "number"},
{is_num_integer, "integer"},
{is_nonneg, "non-negative integer"},
{is_cptr, "cptr"} //,
// {is_objc, "objc"}
};
#define TST_NONE 0
#define TST_ANY "\001"
#define TST_STRING "\002"
#define TST_SYMBOL "\003"
#define TST_PORT "\004"
#define TST_INPORT "\005"
#define TST_OUTPORT "\006"
#define TST_ENVIRONMENT "\007"
#define TST_PAIR "\010"
#define TST_LIST "\011"
#define TST_CHAR "\012"
#define TST_VECTOR "\013"
#define TST_NUMBER "\014"
#define TST_INTEGER "\015"
#define TST_NATURAL "\016"
#define TST_CPTR "\017"
//#define TST_OBJC "\018"
typedef struct {
dispatch_func func;
char *name;
int min_arity;
int max_arity;
char *arg_tests_encoding;
} op_code_info;
#define INF_ARG 0xffff
static op_code_info dispatch_table[]= {
#define _OP_DEF(A,B,C,D,E,OP) {A,(char*)B,C,D,(char*)E},
#include "OPDefines.h"
{ 0, NULL, 0, 0, NULL }
};
//
// Dodgy Function to return string name for common opcodes
//
//
static const char* opcodename(int opcode)
{
switch(opcode)
{
case 0:
return "load";
case 1:
return "t0lvl";
case 2:
return "t1lvl";
case 3:
return "read_internal";
case 4:
return "gensym";
case 5:
return "valueprint";
case 6:
return "eval";
case 7:
return "e0args";
case 8:
return "e1args";
case 9:
return "apply";
case 10:
return "domacro";
case 11:
return "lambda";
case 12:
return "mkclosure";
case 13:
return "quote";
case 14:
return "def0";
case 15:
return "def1";
case 16:
return "defp";
case 17:
return "begin";
case 18:
return "if0";
case 19:
return "if1";
case 20:
return "set0";
case 21:
return "set1";
case 22:
return "let0";
case 23:
return "let1";
case 24:
return "let2";
case 25:
return "let0ast";
case 26:
return "let1ast";
case 27:
return "let2ast";
case 28:
return "let0rec";
case 29:
return "let1rec";
case 30:
return "let2rec";
case 31:
return "cond0";
case 32:
return "cond1";
case 33:
return "delay";
case 34:
return "and0";
case 35:
return "and1";
case 36:
return "or0";
case 37:
return "or1";
case 38:
return "c0stream";
case 39:
return "c1stream";
case 40:
return "macro0";
case 41:
return "macro1";
case 42:
return "case0";
case 43:
return "case1";
case 44:
return "case2";
case 165:
return "rdsexpr";
case 166:
return "rdlist";
case 167:
return "rddot";
case 168:
return "rdquote";
case 169:
return "rdqquote";
case 170:
return "rdqquotevec";
case 171:
return "rdunquote";
case 172:
return "rduqtsp";
case 173:
return "rdvec";
case 174:
return "p0list";
case 175:
return "p1list";
case 176:
return "pvecfrom";
default:
return dispatch_table[opcode].name;
}
//return dispatch_table[opcode].name;
}
const char *procname(pointer x) {
int n=procnum(x);
const char *name=dispatch_table[n].name;
if(name==0) {
name="ILLEGAL!";
}
return name;
}
/* kernel of this interpreter */
static void Eval_Cycle(scheme *sc, enum scheme_opcodes op) {
int count=0;
int old_op;
sc->op = op;
for (;;) {
if(extemp::UNIV::TIME > sc->call_end_time)
{
std::cout << "TIME:" << extemp::UNIV::TIME << " END:" << sc->call_end_time << std::endl;
char msg[512];
if(is_symbol(sc->last_symbol_apply)) {
sprintf(msg,"\"%s\" Exceeded maximum rumtime. If you need a higher default process execution time use sys:set-default-timeout\n",symname_sc(sc,sc->last_symbol_apply));
}else{
sprintf(msg,"Exceeded maximum rumtime. If you need a higher default process execution time use sys:set-default-timeout\n");
}
sc->call_end_time = ULLONG_MAX;
_Error_1(sc, msg, sc->NIL, sc->code->_debugger->_size);
return;
}
op_code_info *pcd=dispatch_table+sc->op;
if (pcd->name!=0) { /* if built-in function, check arguments */
char msg[512];
int ok=1;
//pointer error = 0;
int n=list_length(sc,sc->args);
/* Check number of arguments */
if(n<pcd->min_arity) {
ok=0;
sprintf(msg,"function(%s): needs%s %d argument(s)",
pcd->name,
pcd->min_arity==pcd->max_arity?"":" at least",
pcd->min_arity);
// ASIMP
std::cout << "PROBLEM HERE A? " << std::endl;
/////////
}
if(ok && n>pcd->max_arity) {
ok=0;
sprintf(msg,"function(%s): needs%s %d argument(s)",
pcd->name,
pcd->min_arity==pcd->max_arity?"":" at most",
pcd->max_arity);
std::cout << "PROBLEM HERE B? " << std::endl;
}
if(ok) {
if(pcd->arg_tests_encoding!=0) {
int i=0;
int j;
const char *t=pcd->arg_tests_encoding;
pointer arglist=sc->args;
do {
pointer arg=car(arglist);
j=(int)t[0];
if(j==TST_INPORT[0]) {
if(!is_inport(arg)) break;
} else if(j==TST_OUTPORT[0]) {
if(!is_outport(arg)) break;
} else if(j==TST_LIST[0]) {
if(arg!=sc->NIL && !is_pair(arg)) break;
} else {
if(!tests[j].fct(arg)) break;
}
if(t[1]!=0) {/* last test is replicated as necessary */
t++;
}
arglist=cdr(arglist);
i++;
} while(i<n);
if(i<n) {
ok=0;
std::stringstream ss;
extemp::UNIV::printSchemeCell(sc, ss, sc->args, true);
snprintf(msg, sizeof(msg), "function(%s): argument %d must be: %s\nargument values: %s",
pcd->name,
i+1,
tests[j].kind,
ss.str().c_str());
/////////
}
}
}
if(!ok) {
//std::cout << "GENERAL EVAL ERROR !!!" << std::endl;
/////////
//if(_Error_1(sc,msg,0)==sc->NIL) {
if(_Error_1(sc,msg,sc->code,sc->code->_debugger->_size)==sc->NIL) {
return;
}
pcd=dispatch_table+sc->op;
}
}
old_op=sc->op;
if (pcd->func(sc, (enum scheme_opcodes)sc->op) == sc->NIL) {
return;
}
if(sc->no_memory) {
std::cout << " NO MEMORY ERROR " << std::endl;
fprintf(stderr,"No memory!\n");
return;
}
count++;
}
}
/* ========== Initialization of internal keywords ========== */
static void assign_syntax(scheme *sc, char *name) {
pointer x;
x = oblist_add_by_name(sc, name);
typeflag(x) |= T_SYNTAX;
}
static void assign_proc(scheme *sc, enum scheme_opcodes op, char *name) {
pointer x, y;
x = mk_symbol(sc, name);
y = mk_proc(sc,op);
new_slot_in_env(sc, x, y);
}
static pointer mk_proc(scheme *sc, enum scheme_opcodes op) {
pointer y;
y = get_cell(sc, sc->NIL, sc->NIL);
typeflag(y) = (T_PROC | T_ATOM);
ivalue_unchecked(y) = (long) op;
set_integer(y);
return y;
}
/* Hard-coded for the given keywords. Remember to rewrite if more are added! */
static int syntaxnum(pointer p) {
const char *s=strvalue(car(p));
switch(strlength(car(p))) {
case 2:
if(s[0]=='i') return OP_IF0; /* if */
else return OP_OR0; /* or */
case 3:
if(s[0]=='a') return OP_AND0; /* and */
else return OP_LET0; /* let */
case 4:
switch(s[3]) {
case 'e': return OP_CASE0; /* case */
case 'd': return OP_COND0; /* cond */
case '*': return OP_LET0AST; /* let* */
default: return OP_SET0; /* set! */
}
case 5:
switch(s[2]) {
case 'g': return OP_BEGIN; /* begin */
case 'l': return OP_DELAY; /* delay */
case 'c': return OP_MACRO0; /* macro */
default: return OP_QUOTE; /* quote */
}
case 6:
switch(s[2]) {
case 'm': return OP_LAMBDA; /* lambda */
case 'f': return OP_DEF0; /* define */
default: return OP_LET0REC; /* letrec */
}
default:
return OP_C0STREAM; /* cons-stream */
}
}
scheme *scheme_init_new() {
scheme *sc=(scheme*)malloc(sizeof(scheme));
//printf("Scheme init new %p \n",sc);
if(!scheme_init(sc)) {
free(sc);
return 0;
} else {
return sc;
}
}
scheme *scheme_init_new_custom_alloc(func_alloc malloc, func_dealloc free) {
scheme *sc=(scheme*)malloc(sizeof(scheme));
//printf("Scheme init new custom %p \n",sc);
if(!scheme_init_custom_alloc(sc,malloc,free)) {
free(sc);
return 0;
} else {
return sc;
}
}
int scheme_init(scheme *sc) {
return scheme_init_custom_alloc(sc,malloc,free);
}
int scheme_init_custom_alloc(scheme *sc, func_alloc malloc, func_dealloc free) {
new (sc) scheme; // initialize properly
int i, n=sizeof(dispatch_table)/sizeof(dispatch_table[0]);
pointer x;
//printf("Scheme init custom alloc %p\n",sc);
num_zero.num_type=T_INTEGER; //is_fixnum=1;
num_zero.value.ivalue=0;
num_one.num_type=T_INTEGER; //is_fixnum=1;
num_one.value.ivalue=1;
#if USE_
sc->vptr=&vtbl;
#endif
sc->gensym_cnt=0;
sc->malloc=malloc;
sc->free=free;
sc->last_cell_seg = -1;
sc->fcells = 0;
sc->allocation_request = -1;
sc->no_memory=0;
sc->dark = 1;
if (alloc_cellseg(sc,FIRST_CELLSEGS) != FIRST_CELLSEGS) {
sc->no_memory=1;
return 0;
}
sc->NIL = get_cell(sc,sc->NIL,sc->NIL);
sc->sink = get_cell(sc,sc->NIL,sc->NIL);
sc->T = get_cell(sc,sc->NIL,sc->NIL);
sc->F = get_cell(sc,sc->NIL,sc->NIL);
sc->EOF_OBJ = get_cell(sc,sc->NIL,sc->NIL);
sc->free_cell = sc->NIL;
sc->inport=sc->NIL;
sc->outport=sc->NIL;
sc->save_inport=sc->NIL;
sc->loadport=sc->NIL;
sc->nesting=0;
sc->interactive_repl=0;
dump_stack_initialize(sc);
sc->code = sc->NIL;
sc->tracing=0;
sc->args = sc->NIL;
sc->value = sc->NIL;
/* init sc->NIL */
typeflag(sc->NIL) = (T_ATOM | MARK);
car(sc->NIL) = cdr(sc->NIL) = sc->NIL;
/* init T */
typeflag(sc->T) = (T_ATOM | MARK);
car(sc->T) = cdr(sc->T) = sc->T;
/* init F */
typeflag(sc->F) = (T_ATOM | MARK);
car(sc->F) = cdr(sc->F) = sc->F;
sc->oblist = oblist_initial_value(sc);
/* init global_env */
new_frame_in_env(sc, sc->NIL);
sc->global_env = sc->envir;
/* init else */
x = mk_symbol(sc,"else");
new_slot_in_env(sc, x, sc->T);
assign_syntax(sc, (char*)"lambda");
assign_syntax(sc, (char*)"quote");
assign_syntax(sc, (char*)"define");
assign_syntax(sc, (char*)"if");
assign_syntax(sc, (char*)"begin");
assign_syntax(sc, (char*)"set!");
assign_syntax(sc, (char*)"let");
assign_syntax(sc, (char*)"let*");
assign_syntax(sc, (char*)"letrec");
assign_syntax(sc, (char*)"cond");
assign_syntax(sc, (char*)"delay");
assign_syntax(sc, (char*)"and");
assign_syntax(sc, (char*)"or");
assign_syntax(sc, (char*)"cons-stream");
assign_syntax(sc, (char*)"macro");
assign_syntax(sc, (char*)"case");
for(i=0; i<n; i++) {
if(dispatch_table[i].name!=0) {
assign_proc(sc, (enum scheme_opcodes)i, (char*)dispatch_table[i].name);
}
}
/* initialization of global pointers to special symbols */
sc->LAMBDA = mk_symbol(sc, "lambda");
sc->QUOTE = mk_symbol(sc, "quote");
sc->QQUOTE = mk_symbol(sc, "quasiquote");
sc->UNQUOTE = mk_symbol(sc, "unquote");
sc->UNQUOTESP = mk_symbol(sc, "unquote-splicing");
sc->FEED_TO = mk_symbol(sc, "=>");
sc->COLON_HOOK = mk_symbol(sc,"*colon-hook*");
sc->LIVECODING_ERROR_HOOK = mk_symbol(sc, "*livecoding-error-hook*");
sc->ERROR_HOOK = mk_symbol(sc, "*error-hook*");
sc->SHARP_HOOK = mk_symbol(sc, "*sharp-hook*");
//sc->imp_env = sc->NIL;
//sc->imp_env.clear();
sc->tmp_dump = sc->NIL;
sc->tmp_args = sc->NIL;
sc->func_called_by_extempore = sc->NIL;
// setup treadmill stuff
sc->mutex = new extemp::EXTMutex("treadmill_mutex");
sc->mutex->init();
sc->Treadmill_Guard = new extemp::EXTMonitor("treadmill_guard");
sc->Treadmill_Guard->init();
sc->treadmill_flip_active = false;
sc->treadmill_scanner_finished = false;
//define keywords
int dispatch_table_length = sizeof(dispatch_table) / sizeof(dispatch_table[0]);
treadmill_mark_roots(sc, sc->NIL, sc->NIL);
///////////////////////////////////////////////////////////////////////
//////////////////////////////////////////////////////////////////////
// Some very basic sanity checking
#ifdef TREADMILL_CHECKS
bool empty_grey_list = false;
printf("==============ALLOC POST MARK SANITY CHECKS====================\n");
if(sc->treadmill_top->_list_colour != 1 || sc->treadmill_bottom->_list_colour != 1) {
printf("Top & Bottom must both be ecru! TOP(%d) BOTTOM(%d) Catastrophic error in GC\n",sc->treadmill_top->_list_colour,sc->treadmill_bottom->_list_colour);
}
if(sc->treadmill_scan->_cw->_list_colour != 3)
{
printf("Should be black cells clockwise of SCAN\n");
}
if(sc->treadmill_top != sc->treadmill_scan)
{
empty_grey_list = true;
if(sc->treadmill_top->_cw->_list_colour != 2)
{
printf("TOP _CW must be grey!\n");
}
if(sc->treadmill_scan->_list_colour != 2)
{
printf("Scan must be on a grey cell\n");
}
}
if(sc->treadmill_bottom->_ccw->_list_colour != 0)
{
printf("BOTTOM _CCW must be pure white (free)\n");
}
if(sc->treadmill_free->_list_colour != 0)
{
printf("Free must be on a white cell\n");
}
//check no gaps between ecru cells
pointer ecru_check = sc->treadmill_top;
long long ecrus = 0;
while(ecru_check != sc->treadmill_bottom->_ccw){
if(ecru_check->_list_colour != 1)
{
printf("Should have complete list of ecrus between TOP and BOTTOM moving counter clockwise! Catastrophic error in GC\n");
}
ecrus++;
ecru_check = ecru_check->_ccw;
}
//check no gaps between white cells
long long whites = 0;
pointer white_check = sc->treadmill_free;
while(white_check != sc->treadmill_bottom){
if(white_check->_list_colour != 0)
{
printf("Should have complete list of whites between BOTTOM and FREE moving counter clockwise! Catastrophic error in GC\n");
}
whites++;
white_check = white_check->_cw;
}
//check no gaps between black cells
long long blacks = 0;
pointer black_check = sc->treadmill_scan->_cw;
while(black_check != sc->treadmill_free){
if(black_check->_list_colour != 3)
{
printf("Should have complete list of blacks between SCAN and FREE moving counter clockwise colour(%d)! Catastrophic error in GC\n",black_check->_list_colour);
}
blacks++;
black_check = black_check->_cw;
}
//check no gaps between grey cells
long long greys = 0;
if(!empty_grey_list) {
pointer grey_check = sc->treadmill_scan;
while(grey_check != sc->treadmill_top){
if(grey_check->_list_colour != 0)
{
printf("Should have complete list of whites between BOTTOM and FREE moving counter clockwise! Catastrophic error in GC\n");
}
greys++;
grey_check = grey_check->_ccw;
}
}
printf("BLACKS(%lld) GREYS(%lld) WHITES(%lld) ECRUS(%lld) TOTAL(%lld) SEGSIZE(%lld)\n",blacks,greys,whites,ecrus,blacks+greys+whites+ecrus,sc->total_memory_allocated);
printf("-----------------DONE ALLOC POST MARK CHECK-----------------\n");
#endif
/////////////////////////////////////////////////////////////////////
///////////////////////////////////////////////////////////////////////
sc->treadmill_stop = false;
sc->treadmill_scan_thread = new extemp::EXTThread(&treadmill_scanner, sc, "treadmill");
sc->treadmill_scan_thread->start();
sc->call_end_time = ULLONG_MAX;
//sc->call_default_time = 158760000ll; // 1 hour
sc->call_default_time = extemp::UNIV::MINUTE() * 5;
sc->last_symbol_apply = sc->NIL;
return !sc->no_memory;
}
void scheme_set_input_port_file(scheme *sc, FILE *fin) {
sc->inport=port_from_file(sc,fin,port_input);
}
void scheme_set_input_port_string(scheme *sc, char *start, char *past_the_end) {
sc->inport=port_from_string(sc,start,past_the_end,port_input);
}
void scheme_set_output_port_file(scheme *sc, FILE *fout) {
sc->outport=port_from_file(sc,fout,port_output);
}
void scheme_set_output_port_string(scheme *sc, char *start, char *past_the_end) {
sc->outport=port_from_string(sc,start,past_the_end,port_output);
}
void scheme_set_external_data(scheme *sc, void *p) {
sc->ext_data=p;
}
void scheme_deinit(scheme *sc) {
int i;
sc->treadmill_stop = true;
sc->Treadmill_Guard->signal();
sc->oblist=sc->NIL;
sc->global_env=sc->NIL;
dump_stack_free(sc);
sc->envir=sc->NIL;
sc->code=sc->NIL;
sc->args=sc->NIL;
sc->value=sc->NIL;
if(is_port(sc->inport)) {
typeflag(sc->inport) = T_ATOM;
}
sc->inport=sc->NIL;
sc->outport=sc->NIL;
if(is_port(sc->save_inport)) {
typeflag(sc->save_inport) = T_ATOM;
}
sc->save_inport=sc->NIL;
if(is_port(sc->loadport)) {
typeflag(sc->loadport) = T_ATOM;
}
sc->loadport=sc->NIL;
// sc->gc_verbose=0;
// sc->gc_on = 0;
for(i=0; i<=sc->last_cell_seg; i++) {
sc->free(sc->alloc_seg[i]);
}
}
void scheme_load_file(scheme *sc, FILE *fin) {
dump_stack_reset(sc);
sc->envir = sc->global_env;
sc->file_i=0;
sc->load_stack[0].kind=port_input|port_file;
sc->load_stack[0].rep.stdio.file=fin;
sc->loadport=mk_port(sc,sc->load_stack);
sc->retcode=0;
if(fin==stdin) {
sc->interactive_repl=1;
}
sc->inport=sc->loadport;
sc->func_called_by_extempore = sc->NIL;
sc->call_end_time = extemp::UNIV::TIME+(uint64_t)(extemp::UNIV::HOUR());
try{
Eval_Cycle(sc, OP_T0LVL);
}catch(ScmRuntimeError err){
_Error_1(sc,err.msg,err.p,0,0);
}
typeflag(sc->loadport)=T_ATOM;
if(sc->retcode==0) {
sc->retcode=sc->nesting!=0;
}
while(!sc->applied_symbol_names.empty())
{
sc->applied_symbol_names.pop();
}
sc->last_symbol_apply = sc->NIL;
sc->error_position = -1;
sc->call_end_time = ULLONG_MAX;
}
void scheme_load_string(scheme *sc, const char *cmd, uint64_t start_time, uint64_t end_time) {
dump_stack_reset(sc);
sc->envir = sc->global_env;
sc->file_i=0;
sc->load_stack[0].kind=port_input|port_string;
sc->load_stack[0].rep.string.start=(char*)cmd; /* This func respects const */
sc->load_stack[0].rep.string.past_the_end=(char*)cmd+strlen(cmd);
sc->load_stack[0].rep.string.curr=(char*)cmd;
sc->loadport=mk_port(sc,sc->load_stack);
sc->retcode=0;
sc->interactive_repl=0;
sc->inport=sc->loadport;
sc->func_called_by_extempore = sc->NIL;
//std::cout << "START: " << start_time << " END: " << end_time << std::endl;
sc->call_start_time = start_time;
sc->call_end_time = end_time;
try{
Eval_Cycle(sc, OP_T0LVL);
}catch(ScmRuntimeError err){
std::cout << "Error: evaluating expr: " << cmd << std::endl;
_Error_1(sc,err.msg,err.p,0,0);
}catch(std::exception& e) {
_Error_1(sc,e.what(),sc->NIL,0,0);
}catch(std::string& e) {
_Error_1(sc,e.c_str(),sc->NIL,0,0);
}
typeflag(sc->loadport)=T_ATOM;
if(sc->retcode==0) {
sc->retcode=sc->nesting!=0;
}
while(!sc->applied_symbol_names.empty())
{
sc->applied_symbol_names.pop();
}
sc->last_symbol_apply = sc->NIL;
sc->error_position = -1;
sc->call_end_time = ULLONG_MAX;
}
void scheme_define(scheme *sc, pointer envir, pointer symbol, pointer value) {
pointer x;
x=find_slot_in_env(sc,envir,symbol,0);
if (x != sc->NIL) {
set_slot_in_env(sc, x, value);
} else {
new_slot_spec_in_env(sc, envir, symbol, value);
}
}
void scheme_apply0(scheme *sc, const char *procname) {
pointer carx=mk_symbol(sc,procname);
pointer cdrx=sc->NIL;
dump_stack_reset(sc);
sc->envir = sc->global_env;
sc->code = cons(sc,carx,cdrx);
sc->interactive_repl=0;
sc->retcode=0;
try{
Eval_Cycle(sc, OP_EVAL);
}catch(ScmRuntimeError err){
_Error_1(sc,err.msg,err.p,0,0);
}
}
void scheme_call_without_stack_reset(scheme *sc, pointer func, pointer args)
{
sc->args = args;
sc->code = func;
sc->func_called_by_extempore = func;
sc->interactive_repl = 0;
sc->retcode = 0;
try{
Eval_Cycle(sc, OP_APPLY);
}catch(ScmRuntimeError err){
_Error_1(sc,err.msg,err.p,0,0);
}
}
void scheme_call(scheme *sc, pointer func, pointer args, uint64_t start_time, uint64_t end_time) {
dump_stack_reset(sc);
sc->envir = sc->global_env;
sc->args = args;
sc->code = func;
sc->call_start_time = start_time;
sc->call_end_time = end_time;
sc->func_called_by_extempore = func;
sc->interactive_repl = 0;
sc->retcode = 0;
try{
Eval_Cycle(sc, OP_APPLY);
}catch(ScmRuntimeError err){
_Error_1(sc,err.msg,err.p,0,0);
}
while(!sc->applied_symbol_names.empty())
{
sc->applied_symbol_names.pop();
}
sc->last_symbol_apply = sc->NIL;
sc->error_position = -1;
sc->call_end_time = ULLONG_MAX;
}
//#endif
EXPORT int is_integer_extern(pointer Ptr)
{
return is_integer(Ptr);
}
| 30.446006 | 251 | 0.52945 | [
"object",
"vector"
] |
824ae4f8b03be47dcfe17ea0b16a198ca41aafff | 975 | cxx | C++ | demo/download_file.cxx | amarps/amaynet | 58d3c3fddfaf410eaf86da5df22773b5cab9c004 | [
"MIT"
] | null | null | null | demo/download_file.cxx | amarps/amaynet | 58d3c3fddfaf410eaf86da5df22773b5cab9c004 | [
"MIT"
] | null | null | null | demo/download_file.cxx | amarps/amaynet | 58d3c3fddfaf410eaf86da5df22773b5cab9c004 | [
"MIT"
] | null | null | null | #include "TCP/TCPClient.hxx"
#include "common.hxx"
#include <iostream>
#include <sstream>
#include <unistd.h>
int main(int argc, char *argv[])
{
if (argc < 2) {
std::cout << "Usage: download_file https://www.google.com" << std::endl;
return 1;
}
AMAYNET::URL_T url(argv[1]);
AMAYNET::TCPClient connector(url.host, url.protocol);
std::stringstream request;
request << "GET " << url.path << " HTTP/1.0\r\n"
<< "Host: " << url.host << ':' << url.protocol << "\r\n"
<< "Connection: close\r\n"
<< "\r\n";
connector.Send(request.str());
std::vector<char> buffer;
while (true) {
if (connector.Ready()) {
auto recv_obj = connector.Recv(2096);
if (recv_obj.size() > 0) {
buffer.insert(buffer.end(), recv_obj.begin(), recv_obj.end());
} else if (recv_obj.empty()) {
break;
}
} else {
break;
}
}
for (const auto &c : buffer)
printf("%c", c);
return 0;
}
| 21.666667 | 76 | 0.555897 | [
"vector"
] |
824de93d44b21d0281b918badc137989798b1433 | 1,355 | cpp | C++ | renderer/examples/gcbTemplate.cpp | chunmingchen/OSUFlow | 6a5bbb15a43b7f66b58e51705b946f728e98961b | [
"mpich2"
] | 7 | 2019-03-03T18:27:13.000Z | 2021-12-12T07:39:07.000Z | renderer/examples/gcbTemplate.cpp | chunmingchen/OSUFlow | 6a5bbb15a43b7f66b58e51705b946f728e98961b | [
"mpich2"
] | null | null | null | renderer/examples/gcbTemplate.cpp | chunmingchen/OSUFlow | 6a5bbb15a43b7f66b58e51705b946f728e98961b | [
"mpich2"
] | 7 | 2015-01-27T04:26:42.000Z | 2020-06-18T21:29:14.000Z | /*
gcbTemplate:
The is a demo to show how to use GCB to quick create an OpenGL program with GLUT.
Creted by
Abon Chaudhuri and Teng-Yok Lee (The Ohio State University)
May, 2010
*/
#include "gcb.h"
void
_DisplayFunc()
{
glClear(GL_COLOR_BUFFER_BIT | GL_DEPTH_BUFFER_BIT);
// render the scene
glutWireCube(1.0);
// NOTE: Call glutSwapBuffers() at the end of your display function
glutSwapBuffers();
}
void
init()
{
LOG(printf("Initialize OpenGL here."));
glEnable(GL_DEPTH_TEST);
}
void
quit()
{
LOG(printf("Clean up here."));
}
int
main(int argn, char* argv[])
{
// when use GCB, it is still needed to initialize GLUT
glutInit(&argn, argv);
glutInitDisplayMode(GLUT_DEPTH | GLUT_DOUBLE | GLUT_RGBA | GLUT_ALPHA | GLUT_STENCIL );
glutCreateWindow("GCB Template");
// specify the callbacks you really need. Except gcbInit() and gcbDisplayFunc(), other callbacks are optional
gcbInit(init, quit);
gcbDisplayFunc(_DisplayFunc);
// enter the GLUT loop
glutMainLoop();
return 0;
}
/*
$Log: gcbTemplate.cpp,v $
Revision 1.3 2010/10/01 20:38:23 leeten
[10/01/2010]
1. Checkin the merged version from r.186.
Revision 1.2 2010/08/15 12:34:31 leeten
[08/14/2010]
1. [ADD] Add the authorship to the beginning of the source codes.
Revision 1.1.1.1 2010/04/12 21:31:38 leeten
[04/12/2010]
1. [1ST] First Time Checkin.
*/
| 17.597403 | 110 | 0.712915 | [
"render"
] |
82504655f759e641ae763b22eaa3a02c22aebfb2 | 64,136 | cc | C++ | content/browser/renderer_host/navigator_unittest.cc | Yannic/chromium | ab32e8aacb08c9fce0dc4bf09eec456ba46e3710 | [
"BSD-3-Clause-No-Nuclear-License-2014",
"BSD-3-Clause"
] | null | null | null | content/browser/renderer_host/navigator_unittest.cc | Yannic/chromium | ab32e8aacb08c9fce0dc4bf09eec456ba46e3710 | [
"BSD-3-Clause-No-Nuclear-License-2014",
"BSD-3-Clause"
] | 1 | 2019-03-13T10:32:53.000Z | 2019-03-13T11:05:30.000Z | content/browser/renderer_host/navigator_unittest.cc | Yannic/chromium | ab32e8aacb08c9fce0dc4bf09eec456ba46e3710 | [
"BSD-3-Clause-No-Nuclear-License-2014",
"BSD-3-Clause"
] | null | null | null | // 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 "content/browser/renderer_host/navigator.h"
#include <stdint.h>
#include "base/cxx17_backports.h"
#include "base/feature_list.h"
#include "base/test/test_simple_task_runner.h"
#include "base/time/time.h"
#include "build/build_config.h"
#include "content/browser/renderer_host/navigation_controller_impl.h"
#include "content/browser/renderer_host/navigation_entry_impl.h"
#include "content/browser/renderer_host/navigation_request.h"
#include "content/browser/renderer_host/navigation_request_info.h"
#include "content/browser/renderer_host/navigator.h"
#include "content/browser/renderer_host/render_frame_host_manager.h"
#include "content/browser/site_instance_impl.h"
#include "content/common/content_navigation_policy.h"
#include "content/common/frame.mojom.h"
#include "content/public/browser/child_process_security_policy.h"
#include "content/public/common/content_features.h"
#include "content/public/common/url_constants.h"
#include "content/public/common/url_utils.h"
#include "content/public/test/back_forward_cache_util.h"
#include "content/public/test/mock_render_process_host.h"
#include "content/public/test/navigation_simulator.h"
#include "content/public/test/test_navigation_throttle_inserter.h"
#include "content/public/test/test_utils.h"
#include "content/test/navigation_simulator_impl.h"
#include "content/test/task_runner_deferring_throttle.h"
#include "content/test/test_navigation_url_loader.h"
#include "content/test/test_render_frame_host.h"
#include "content/test/test_web_contents.h"
#include "net/base/load_flags.h"
#include "net/http/http_response_headers.h"
#include "net/url_request/redirect_info.h"
#include "ui/base/page_transition_types.h"
#include "url/url_constants.h"
namespace content {
namespace {
// Helper function that determines if a test should expect a cross-site
// navigation to trigger a SiteInstance change based on the current process
// model.
bool ExpectSiteInstanceChange(SiteInstanceImpl* site_instance) {
return AreAllSitesIsolatedForTesting() ||
CanCrossSiteNavigationsProactivelySwapBrowsingInstances() ||
!site_instance->IsDefaultSiteInstance();
}
// Same as above but does not return true if back/forward cache is the only
// trigger for SiteInstance change. This function is useful if, e.g. the test
// intends to disable back/forward cache.
bool ExpectSiteInstanceChangeWithoutBackForwardCache(
SiteInstanceImpl* site_instance) {
return AreAllSitesIsolatedForTesting() ||
IsProactivelySwapBrowsingInstanceEnabled() ||
!site_instance->IsDefaultSiteInstance();
}
} // namespace
class NavigatorTest : public RenderViewHostImplTestHarness {
public:
using SiteInstanceDescriptor = RenderFrameHostManager::SiteInstanceDescriptor;
using SiteInstanceRelation = RenderFrameHostManager::SiteInstanceRelation;
void SetUp() override { RenderViewHostImplTestHarness::SetUp(); }
void TearDown() override { RenderViewHostImplTestHarness::TearDown(); }
TestNavigationURLLoader* GetLoaderForNavigationRequest(
NavigationRequest* request) const {
return static_cast<TestNavigationURLLoader*>(request->loader_for_testing());
}
TestRenderFrameHost* GetSpeculativeRenderFrameHost(FrameTreeNode* node) {
return static_cast<TestRenderFrameHost*>(
node->render_manager()->speculative_render_frame_host_.get());
}
scoped_refptr<SiteInstanceImpl> ConvertToSiteInstance(
RenderFrameHostManager* rfhm,
const SiteInstanceDescriptor& descriptor,
SiteInstance* candidate_instance) {
return static_cast<SiteInstanceImpl*>(
rfhm->ConvertToSiteInstance(
descriptor, static_cast<SiteInstanceImpl*>(candidate_instance),
false /* is_speculative */)
.get());
}
SiteInfo CreateExpectedSiteInfo(const GURL& url) {
return SiteInfo::CreateForTesting(IsolationContext(browser_context()), url);
}
};
// Tests a complete browser-initiated navigation starting with a non-live
// renderer.
TEST_F(NavigatorTest, SimpleBrowserInitiatedNavigationFromNonLiveRenderer) {
const GURL kUrl("http://chromium.org/");
EXPECT_FALSE(main_test_rfh()->IsRenderFrameLive());
// Start a browser-initiated navigation.
auto navigation =
NavigationSimulator::CreateBrowserInitiated(kUrl, contents());
auto site_instance_id = main_test_rfh()->GetSiteInstance()->GetId();
FrameTreeNode* node = main_test_rfh()->frame_tree_node();
navigation->Start();
NavigationRequest* request = node->navigation_request();
ASSERT_TRUE(request);
EXPECT_EQ(kUrl, request->common_params().url);
EXPECT_TRUE(request->browser_initiated());
// As there's no live renderer the navigation should not wait for a
// beforeUnload completion callback being invoked by the renderer and
// start right away.
EXPECT_EQ(NavigationRequest::WILL_START_REQUEST, request->state());
ASSERT_TRUE(GetLoaderForNavigationRequest(request));
EXPECT_FALSE(GetSpeculativeRenderFrameHost(node));
navigation->ReadyToCommit();
EXPECT_TRUE(main_test_rfh()->is_loading());
EXPECT_FALSE(node->navigation_request());
// Commit the navigation.
navigation->Commit();
EXPECT_TRUE(main_test_rfh()->IsActive());
EXPECT_EQ(main_test_rfh()->lifecycle_state(),
RenderFrameHostImpl::LifecycleStateImpl::kActive);
if (AreDefaultSiteInstancesEnabled()) {
EXPECT_TRUE(main_test_rfh()->GetSiteInstance()->IsDefaultSiteInstance());
} else {
EXPECT_EQ(CreateExpectedSiteInfo(kUrl),
main_test_rfh()->GetSiteInstance()->GetSiteInfo());
}
EXPECT_EQ(kUrl, contents()->GetLastCommittedURL());
// The main RenderFrameHost should not have been changed, and the renderer
// should have been initialized.
EXPECT_EQ(site_instance_id, main_test_rfh()->GetSiteInstance()->GetId());
EXPECT_TRUE(main_test_rfh()->IsRenderFrameLive());
// After a navigation is finished no speculative RenderFrameHost should
// exist.
EXPECT_FALSE(GetSpeculativeRenderFrameHost(node));
}
// Tests a complete renderer-initiated same-site navigation.
TEST_F(NavigatorTest, SimpleRendererInitiatedSameSiteNavigation) {
const GURL kUrl1("http://www.chromium.org/");
const GURL kUrl2("http://www.chromium.org/Home");
contents()->NavigateAndCommit(kUrl1);
EXPECT_TRUE(main_test_rfh()->IsRenderFrameLive());
static_cast<mojom::FrameHost*>(main_test_rfh())->DidStopLoading();
FrameTreeNode* node = main_test_rfh()->frame_tree_node();
// Start a renderer-initiated non-user-initiated navigation.
EXPECT_FALSE(node->navigation_request());
auto navigation =
NavigationSimulator::CreateRendererInitiated(kUrl2, main_test_rfh());
navigation->SetTransition(ui::PageTransitionFromInt(
ui::PAGE_TRANSITION_LINK | ui::PAGE_TRANSITION_CLIENT_REDIRECT));
navigation->SetHasUserGesture(false);
navigation->Start();
NavigationRequest* request = node->navigation_request();
ASSERT_TRUE(request);
// The navigation is immediately started as there's no need to wait for
// beforeUnload to be executed.
EXPECT_EQ(NavigationRequest::WILL_START_REQUEST, request->state());
EXPECT_FALSE(request->common_params().has_user_gesture);
EXPECT_EQ(kUrl2, request->common_params().url);
EXPECT_FALSE(request->browser_initiated());
if (CanSameSiteMainFrameNavigationsChangeRenderFrameHosts()) {
// If same-site ProactivelySwapBrowsingInstance or main-frame RenderDocument
// is enabled, the RFH should change so we should have a speculative RFH.
EXPECT_TRUE(GetSpeculativeRenderFrameHost(node));
EXPECT_FALSE(GetSpeculativeRenderFrameHost(node)->is_loading());
} else {
EXPECT_FALSE(GetSpeculativeRenderFrameHost(node));
}
EXPECT_FALSE(main_test_rfh()->is_loading());
// Have the current RenderFrameHost commit the navigation
navigation->ReadyToCommit();
if (CanSameSiteMainFrameNavigationsChangeRenderFrameHosts()) {
EXPECT_TRUE(GetSpeculativeRenderFrameHost(node)->is_loading());
} else {
EXPECT_TRUE(main_test_rfh()->is_loading());
}
EXPECT_FALSE(node->navigation_request());
// Commit the navigation.
navigation->Commit();
EXPECT_TRUE(main_test_rfh()->IsActive());
if (AreDefaultSiteInstancesEnabled()) {
EXPECT_TRUE(main_test_rfh()->GetSiteInstance()->IsDefaultSiteInstance());
} else {
EXPECT_EQ(CreateExpectedSiteInfo(kUrl2),
main_test_rfh()->GetSiteInstance()->GetSiteInfo());
}
EXPECT_EQ(kUrl2, contents()->GetLastCommittedURL());
EXPECT_FALSE(GetSpeculativeRenderFrameHost(node));
}
// Tests a complete renderer-initiated navigation that should be
// cross-site but does not result in a SiteInstance swap because its
// renderer-initiated.
TEST_F(NavigatorTest, SimpleRendererInitiatedCrossSiteNavigation) {
const GURL kUrl1("http://www.chromium.org/");
const GURL kUrl2("http://www.google.com");
contents()->NavigateAndCommit(kUrl1);
EXPECT_TRUE(main_test_rfh()->IsRenderFrameLive());
scoped_refptr<SiteInstanceImpl> site_instance_1 =
main_test_rfh()->GetSiteInstance();
bool expect_site_instance_change =
ExpectSiteInstanceChange(site_instance_1.get());
FrameTreeNode* node = main_test_rfh()->frame_tree_node();
// Start a renderer-initiated navigation.
EXPECT_FALSE(node->navigation_request());
auto navigation =
NavigationSimulator::CreateRendererInitiated(kUrl2, main_test_rfh());
navigation->Start();
NavigationRequest* request = node->navigation_request();
ASSERT_TRUE(request);
// The navigation is immediately started as there's no need to wait for
// beforeUnload to be executed.
EXPECT_EQ(NavigationRequest::WILL_START_REQUEST, request->state());
EXPECT_EQ(kUrl2, request->common_params().url);
EXPECT_FALSE(request->browser_initiated());
if (expect_site_instance_change) {
EXPECT_TRUE(GetSpeculativeRenderFrameHost(node));
} else {
EXPECT_FALSE(GetSpeculativeRenderFrameHost(node));
}
// Have the current RenderFrameHost commit the navigation.
navigation->ReadyToCommit();
if (expect_site_instance_change) {
EXPECT_EQ(navigation->GetFinalRenderFrameHost(),
GetSpeculativeRenderFrameHost(node));
}
EXPECT_FALSE(node->navigation_request());
// Commit the navigation.
navigation->Commit();
EXPECT_TRUE(main_test_rfh()->IsActive());
EXPECT_EQ(kUrl2, contents()->GetLastCommittedURL());
EXPECT_FALSE(GetSpeculativeRenderFrameHost(node));
if (expect_site_instance_change) {
EXPECT_NE(site_instance_1->GetId(),
main_test_rfh()->GetSiteInstance()->GetId());
EXPECT_EQ(site_instance_1->IsDefaultSiteInstance(),
main_test_rfh()->GetSiteInstance()->IsDefaultSiteInstance());
} else {
EXPECT_EQ(site_instance_1->GetId(),
main_test_rfh()->GetSiteInstance()->GetId());
}
}
// Tests that when a navigation to about:blank is renderer-aborted,
// after another cross-site navigation has been initiated, that the
// second navigation is undisturbed.
TEST_F(NavigatorTest, RendererAbortedAboutBlankNavigation) {
const GURL kUrl0("http://www.google.com/");
const GURL kUrl1("about:blank");
const GURL kUrl2("http://www.chromium.org/Home");
contents()->NavigateAndCommit(kUrl0);
EXPECT_TRUE(main_test_rfh()->IsRenderFrameLive());
// The test expects cross-site navigations to change SiteInstances, but not
// same-site navigations. Return if SiteInstance change is not possible, and
// disable same-site back/forward cache to ensure SiteInstance won't change
// for same-site navigations.
DisableBackForwardCacheForTesting(
contents(), BackForwardCache::TEST_ASSUMES_NO_RENDER_FRAME_CHANGE);
if (!ExpectSiteInstanceChangeWithoutBackForwardCache(
main_test_rfh()->GetSiteInstance())) {
return;
}
// Start a renderer-initiated navigation to about:blank.
EXPECT_FALSE(main_test_rfh()->is_loading());
auto navigation1 =
NavigationSimulator::CreateRendererInitiated(kUrl1, main_test_rfh());
navigation1->SetTransition(ui::PAGE_TRANSITION_LINK);
navigation1->Start();
navigation1->ReadyToCommit();
// about:blank should load on the main rfhi, not a speculative one,
// and automatically advance to READY_TO_COMMIT since it requires
// no network resources.
FrameTreeNode* node = main_test_rfh()->frame_tree_node();
ASSERT_FALSE(node->navigation_request());
EXPECT_TRUE(main_test_rfh()->is_loading());
EXPECT_FALSE(GetSpeculativeRenderFrameHost(node));
// Start a second, cross-origin navigation.
auto navigation2 =
NavigationSimulator::CreateRendererInitiated(kUrl2, main_test_rfh());
navigation2->SetTransition(ui::PAGE_TRANSITION_LINK);
navigation2->Start();
ASSERT_TRUE(node->navigation_request());
EXPECT_TRUE(GetSpeculativeRenderFrameHost(node));
// Abort the initial navigation.
navigation1->AbortFromRenderer();
// But the speculative rfhi and second navigation request
// should be unaffected.
ASSERT_TRUE(node->navigation_request());
EXPECT_TRUE(GetSpeculativeRenderFrameHost(node));
}
// Tests that when a navigation to about:blank is renderer-aborted,
// after another cross-site navigation has been initiated, that the
// second navigation is undisturbed. In this variation, the second
// navigation is initially same-site, then redirects cross-site,
// and a throttle DEFERs during WillProcessResponse(). The initial
// navigation gets aborted during this defer.
TEST_F(NavigatorTest,
RedirectedRendererAbortedAboutBlankNavigationwithDeferredCommit) {
const GURL kUrl0("http://www.google.com/");
const GURL kUrl0SameSiteVariation("http://www.google.com/home");
const GURL kUrl1("about:blank");
const GURL kUrl2("http://www.chromium.org/Home");
contents()->NavigateAndCommit(kUrl0);
EXPECT_TRUE(main_test_rfh()->IsRenderFrameLive());
// The test expects cross-site navigations to change SiteInstances, but not
// same-site navigations. Return if SiteInstance change is not possible, and
// disable same-site back/forward cache to ensure SiteInstance won't change
// for same-site navigations.
DisableBackForwardCacheForTesting(
contents(), BackForwardCache::TEST_ASSUMES_NO_RENDER_FRAME_CHANGE);
if (!ExpectSiteInstanceChangeWithoutBackForwardCache(
main_test_rfh()->GetSiteInstance())) {
return;
}
// Start a renderer-initiated navigation to about:blank.
EXPECT_FALSE(main_test_rfh()->is_loading());
auto navigation1 =
NavigationSimulator::CreateRendererInitiated(kUrl1, main_test_rfh());
navigation1->SetTransition(ui::PAGE_TRANSITION_LINK);
navigation1->Start();
navigation1->ReadyToCommit();
// about:blank should load on the main rfhi, not a speculative one,
// and automatically advance to READY_TO_COMMIT since it requires
// no network resources.
FrameTreeNode* node = main_test_rfh()->frame_tree_node();
ASSERT_FALSE(node->navigation_request());
EXPECT_TRUE(main_test_rfh()->is_loading());
EXPECT_FALSE(GetSpeculativeRenderFrameHost(node));
// Start a second, same-origin navigation.
auto navigation2 = NavigationSimulator::CreateRendererInitiated(
kUrl0SameSiteVariation, main_test_rfh());
navigation2->SetTransition(ui::PAGE_TRANSITION_LINK);
navigation2->SetAutoAdvance(false);
// Insert a TaskRunnerDeferringThrottle that will defer
// during WillProcessResponse() of navigation2.
auto task_runner = base::MakeRefCounted<base::TestSimpleTaskRunner>();
auto* raw_runner = task_runner.get();
TestNavigationThrottleInserter throttle_inserter(
web_contents(),
base::BindRepeating(&TaskRunnerDeferringThrottle::Create,
std::move(task_runner), false /* defer_start */,
false /* defer-redirect */,
true /* defer_response */));
navigation2->Start();
ASSERT_TRUE(node->navigation_request());
EXPECT_FALSE(GetSpeculativeRenderFrameHost(node));
// Redirect navigation2 cross-site, which, once ReadyCommit()
// is called, will force a speculative RFHI to be created,
// and update the associated site instance type of the
// NavigationRequest for navigation2. This will prevent
// the abort of navigation1 from destroying the speculative
// RFHI that navigation2 depends on.
navigation2->Redirect(kUrl2);
EXPECT_FALSE(GetSpeculativeRenderFrameHost(node));
EXPECT_TRUE(node->navigation_request()->associated_site_instance_type() ==
NavigationRequest::AssociatedSiteInstanceType::CURRENT);
navigation2->ReadyToCommit();
EXPECT_EQ(1u, raw_runner->NumPendingTasks());
EXPECT_TRUE(navigation2->IsDeferred());
EXPECT_TRUE(GetSpeculativeRenderFrameHost(node));
EXPECT_EQ(node->navigation_request()->associated_site_instance_type(),
NavigationRequest::AssociatedSiteInstanceType::SPECULATIVE);
// Abort the initial navigation.
navigation1->AbortFromRenderer();
// The speculative rfhi and second navigation request
// should be unaffected.
ASSERT_TRUE(node->navigation_request());
EXPECT_TRUE(GetSpeculativeRenderFrameHost(node));
}
// Tests that a beforeUnload denial cancels the navigation.
TEST_F(NavigatorTest, BeforeUnloadDenialCancelNavigation) {
const GURL kUrl1("http://www.google.com/");
const GURL kUrl2("http://www.chromium.org/");
contents()->NavigateAndCommit(kUrl1);
// Start a new navigation.
FrameTreeNode* node = main_test_rfh()->frame_tree_node();
auto navigation =
NavigationSimulatorImpl::CreateBrowserInitiated(kUrl2, contents());
navigation->BrowserInitiatedStartAndWaitBeforeUnload();
NavigationRequest* request = node->navigation_request();
ASSERT_TRUE(request);
EXPECT_TRUE(request->browser_initiated());
EXPECT_EQ(NavigationRequest::WAITING_FOR_RENDERER_RESPONSE, request->state());
EXPECT_TRUE(GetSpeculativeRenderFrameHost(node));
RenderFrameDeletedObserver rfh_deleted_observer(
GetSpeculativeRenderFrameHost(node));
// Simulate a beforeUnload denial.
main_test_rfh()->SimulateBeforeUnloadCompleted(false);
EXPECT_FALSE(node->navigation_request());
EXPECT_FALSE(GetSpeculativeRenderFrameHost(node));
EXPECT_TRUE(rfh_deleted_observer.deleted());
}
// Test that a proper NavigationRequest is created at navigation start.
TEST_F(NavigatorTest, BeginNavigation) {
const GURL kUrl1("http://www.google.com/");
const GURL kUrl2("http://www.chromium.org/");
const GURL kUrl3("http://www.gmail.com/");
contents()->NavigateAndCommit(kUrl1);
// Add a subframe.
FrameTreeNode* root_node = contents()->GetFrameTree()->root();
TestRenderFrameHost* subframe_rfh = main_test_rfh()->AppendChild("Child");
ASSERT_TRUE(subframe_rfh);
// Start a navigation at the subframe.
FrameTreeNode* subframe_node = subframe_rfh->frame_tree_node();
auto navigation =
NavigationSimulatorImpl::CreateBrowserInitiated(kUrl2, contents());
NavigationController::LoadURLParams load_url_params(kUrl2);
load_url_params.frame_tree_node_id = subframe_node->frame_tree_node_id();
navigation->SetLoadURLParams(&load_url_params);
navigation->BrowserInitiatedStartAndWaitBeforeUnload();
NavigationRequest* subframe_request = subframe_node->navigation_request();
// We should be waiting for the BeforeUnload event to execute in the subframe.
ASSERT_TRUE(subframe_request);
EXPECT_EQ(NavigationRequest::WAITING_FOR_RENDERER_RESPONSE,
subframe_request->state());
EXPECT_TRUE(subframe_rfh->is_waiting_for_beforeunload_completion());
// Start the navigation, which will internally simulate that the beforeUnload
// completion callback has been invoked.
navigation->Start();
TestNavigationURLLoader* subframe_loader =
GetLoaderForNavigationRequest(subframe_request);
ASSERT_TRUE(subframe_loader);
EXPECT_EQ(NavigationRequest::WILL_START_REQUEST, subframe_request->state());
EXPECT_EQ(kUrl2, subframe_request->common_params().url);
EXPECT_EQ(kUrl2, subframe_loader->request_info()->common_params->url);
EXPECT_TRUE(
net::IsolationInfo::Create(
net::IsolationInfo::RequestType::kSubFrame,
url::Origin::Create(kUrl1), url::Origin::Create(kUrl2),
net::SiteForCookies::FromUrl(kUrl1), std::set<net::SchemefulSite>())
.IsEqualForTesting(subframe_loader->request_info()->isolation_info));
EXPECT_FALSE(subframe_loader->request_info()->is_main_frame);
EXPECT_TRUE(subframe_request->browser_initiated());
EXPECT_FALSE(GetSpeculativeRenderFrameHost(root_node));
// Subframe navigations should never create a speculative RenderFrameHost,
// unless site-per-process or ProcessSharingWithStrictSiteInstances is
// enabled. In that case, as the subframe navigation is to a different site
// and is still ongoing, it should have one.
bool expect_site_instance_change = AreStrictSiteInstancesEnabled();
if (expect_site_instance_change) {
EXPECT_TRUE(GetSpeculativeRenderFrameHost(subframe_node));
} else {
EXPECT_FALSE(GetSpeculativeRenderFrameHost(subframe_node));
}
// Now start a navigation at the root node.
auto navigation2 =
NavigationSimulatorImpl::CreateBrowserInitiated(kUrl3, contents());
navigation2->BrowserInitiatedStartAndWaitBeforeUnload();
NavigationRequest* main_request = root_node->navigation_request();
ASSERT_TRUE(main_request);
EXPECT_EQ(NavigationRequest::WAITING_FOR_RENDERER_RESPONSE,
main_request->state());
// Main frame navigation to a different site should use a speculative
// RenderFrameHost.
EXPECT_TRUE(GetSpeculativeRenderFrameHost(root_node));
// Start the navigation, which will internally simulate that the beforeUnload
// completion callback has been invoked.
navigation2->Start();
TestNavigationURLLoader* main_loader =
GetLoaderForNavigationRequest(main_request);
EXPECT_EQ(kUrl3, main_request->common_params().url);
EXPECT_EQ(kUrl3, main_loader->request_info()->common_params->url);
EXPECT_TRUE(
net::IsolationInfo::Create(
net::IsolationInfo::RequestType::kMainFrame,
url::Origin::Create(kUrl3), url::Origin::Create(kUrl3),
net::SiteForCookies::FromUrl(kUrl3), std::set<net::SchemefulSite>())
.IsEqualForTesting(main_loader->request_info()->isolation_info));
EXPECT_TRUE(main_loader->request_info()->is_main_frame);
EXPECT_TRUE(main_request->browser_initiated());
// BeforeUnloadCompleted callback was invoked by the renderer so the
// navigation should have started.
EXPECT_EQ(NavigationRequest::WILL_START_REQUEST, main_request->state());
EXPECT_TRUE(GetSpeculativeRenderFrameHost(root_node));
// As the main frame hasn't yet committed the subframe still exists. Thus, the
// above situation regarding subframe navigations is valid here.
if (expect_site_instance_change) {
EXPECT_TRUE(GetSpeculativeRenderFrameHost(subframe_node));
} else {
EXPECT_FALSE(GetSpeculativeRenderFrameHost(subframe_node));
}
}
// Tests that committing an HTTP 204 or HTTP 205 response cancels
// the navigation.
TEST_F(NavigatorTest, NoContent) {
const GURL kUrl1("http://www.chromium.org/");
const GURL kUrl2("http://www.google.com/");
// Load a URL.
contents()->NavigateAndCommit(kUrl1);
FrameTreeNode* node = main_test_rfh()->frame_tree_node();
// Navigate to a different site.
EXPECT_FALSE(node->navigation_request());
auto navigation =
NavigationSimulator::CreateBrowserInitiated(kUrl2, contents());
navigation->Start();
NavigationRequest* main_request = node->navigation_request();
ASSERT_TRUE(main_request);
// Navigations to a different site do create a speculative RenderFrameHost.
EXPECT_TRUE(GetSpeculativeRenderFrameHost(node));
// Commit an HTTP 204 response.
auto response = network::mojom::URLResponseHead::New();
const char kNoContentHeaders[] = "HTTP/1.1 204 No Content\0\0";
response->headers = new net::HttpResponseHeaders(
std::string(kNoContentHeaders, base::size(kNoContentHeaders)));
GetLoaderForNavigationRequest(main_request)
->CallOnResponseStarted(std::move(response),
mojo::ScopedDataPipeConsumerHandle());
// There should be no pending nor speculative RenderFrameHost; the navigation
// was aborted.
EXPECT_FALSE(node->navigation_request());
EXPECT_FALSE(GetSpeculativeRenderFrameHost(node));
// Now, repeat the test with 205 Reset Content.
// Navigate to a different site again.
auto navigation2 =
NavigationSimulator::CreateBrowserInitiated(kUrl2, contents());
navigation2->Start();
main_request = node->navigation_request();
ASSERT_TRUE(main_request);
EXPECT_TRUE(GetSpeculativeRenderFrameHost(node));
// Commit an HTTP 205 response.
response = network::mojom::URLResponseHead::New();
const char kResetContentHeaders[] = "HTTP/1.1 205 Reset Content\0\0";
response->headers = new net::HttpResponseHeaders(
std::string(kResetContentHeaders, base::size(kResetContentHeaders)));
GetLoaderForNavigationRequest(main_request)
->CallOnResponseStarted(std::move(response),
mojo::ScopedDataPipeConsumerHandle());
// There should be no pending nor speculative RenderFrameHost; the navigation
// was aborted.
EXPECT_FALSE(node->navigation_request());
EXPECT_FALSE(GetSpeculativeRenderFrameHost(node));
}
// Test that a new RenderFrameHost is created when doing a cross site
// navigation.
TEST_F(NavigatorTest, CrossSiteNavigation) {
const GURL kUrl1("http://www.chromium.org/");
const GURL kUrl2("http://www.google.com/");
contents()->NavigateAndCommit(kUrl1);
RenderFrameHostImpl* initial_rfh = main_test_rfh();
FrameTreeNode* node = main_test_rfh()->frame_tree_node();
// Navigate to a different site.
EXPECT_EQ(main_test_rfh()->navigation_requests().size(), 0u);
auto navigation =
NavigationSimulator::CreateBrowserInitiated(kUrl2, contents());
navigation->Start();
NavigationRequest* main_request = node->navigation_request();
ASSERT_TRUE(main_request);
TestRenderFrameHost* speculative_rfh = GetSpeculativeRenderFrameHost(node);
ASSERT_TRUE(speculative_rfh);
EXPECT_EQ(speculative_rfh, GetSpeculativeRenderFrameHost(node));
navigation->ReadyToCommit();
EXPECT_EQ(speculative_rfh, GetSpeculativeRenderFrameHost(node));
EXPECT_EQ(speculative_rfh->navigation_requests().size(), 1u);
EXPECT_EQ(main_test_rfh()->navigation_requests().size(), 0u);
navigation->Commit();
RenderFrameHostImpl* final_rfh = main_test_rfh();
EXPECT_EQ(speculative_rfh, final_rfh);
EXPECT_NE(initial_rfh, final_rfh);
EXPECT_TRUE(final_rfh->IsRenderFrameLive());
EXPECT_TRUE(final_rfh->render_view_host()->IsRenderViewLive());
EXPECT_FALSE(GetSpeculativeRenderFrameHost(node));
}
// Test that redirects are followed and the speculative RenderFrameHost logic
// behaves as expected.
TEST_F(NavigatorTest, RedirectCrossSite) {
const GURL kUrl1("http://www.chromium.org/");
const GURL kUrl2("http://www.google.com/");
contents()->NavigateAndCommit(kUrl1);
RenderFrameHostImpl* rfh = main_test_rfh();
FrameTreeNode* node = main_test_rfh()->frame_tree_node();
// Navigate to a URL on the same site.
EXPECT_EQ(main_test_rfh()->navigation_requests().size(), 0u);
auto navigation =
NavigationSimulator::CreateBrowserInitiated(kUrl1, contents());
navigation->Start();
NavigationRequest* main_request = node->navigation_request();
ASSERT_TRUE(main_request);
EXPECT_FALSE(GetSpeculativeRenderFrameHost(node));
// It then redirects to another site.
navigation->Redirect(kUrl2);
// The redirect should have been followed.
EXPECT_EQ(1, GetLoaderForNavigationRequest(main_request)->redirect_count());
EXPECT_FALSE(GetSpeculativeRenderFrameHost(node));
navigation->ReadyToCommit();
TestRenderFrameHost* final_speculative_rfh =
GetSpeculativeRenderFrameHost(node);
EXPECT_TRUE(final_speculative_rfh);
EXPECT_EQ(final_speculative_rfh->navigation_requests().size(), 1u);
navigation->Commit();
RenderFrameHostImpl* final_rfh = main_test_rfh();
ASSERT_TRUE(final_rfh);
EXPECT_NE(rfh, final_rfh);
EXPECT_EQ(final_speculative_rfh, final_rfh);
EXPECT_TRUE(final_rfh->IsRenderFrameLive());
EXPECT_TRUE(final_rfh->render_view_host()->IsRenderViewLive());
EXPECT_FALSE(GetSpeculativeRenderFrameHost(node));
}
// Test that a navigation is canceled if another browser-initiated request has
// been issued in the meantime. Also confirms that the speculative
// RenderFrameHost is correctly updated in the process.
TEST_F(NavigatorTest, BrowserInitiatedNavigationCancel) {
const GURL kUrl0("http://www.wikipedia.org/");
const GURL kUrl1("http://www.chromium.org/");
const auto kUrl1SiteInfo = CreateExpectedSiteInfo(kUrl1);
const GURL kUrl2("http://www.google.com/");
const auto kUrl2SiteInfo = CreateExpectedSiteInfo(kUrl2);
// Initialization.
contents()->NavigateAndCommit(kUrl0);
FrameTreeNode* node = main_test_rfh()->frame_tree_node();
// Request navigation to the 1st URL.
EXPECT_FALSE(node->navigation_request());
auto navigation1 =
NavigationSimulator::CreateBrowserInitiated(kUrl1, contents());
navigation1->Start();
NavigationRequest* request1 = node->navigation_request();
ASSERT_TRUE(request1);
EXPECT_EQ(kUrl1, request1->common_params().url);
EXPECT_TRUE(request1->browser_initiated());
base::WeakPtr<TestNavigationURLLoader> loader1 =
GetLoaderForNavigationRequest(request1)->AsWeakPtr();
EXPECT_TRUE(loader1);
// Confirm a speculative RenderFrameHost was created.
TestRenderFrameHost* speculative_rfh = GetSpeculativeRenderFrameHost(node);
ASSERT_TRUE(speculative_rfh);
auto site_instance_id_1 = speculative_rfh->GetSiteInstance()->GetId();
if (AreDefaultSiteInstancesEnabled()) {
EXPECT_TRUE(speculative_rfh->GetSiteInstance()->IsDefaultSiteInstance());
} else {
EXPECT_EQ(kUrl1SiteInfo, speculative_rfh->GetSiteInstance()->GetSiteInfo());
}
// Request navigation to the 2nd URL; the NavigationRequest must have been
// replaced by a new one with a different URL.
auto navigation2 =
NavigationSimulator::CreateBrowserInitiated(kUrl2, contents());
navigation2->Start();
NavigationRequest* request2 = node->navigation_request();
ASSERT_TRUE(request2);
EXPECT_EQ(kUrl2, request2->common_params().url);
EXPECT_TRUE(request2->browser_initiated());
// Confirm that the first loader got destroyed.
EXPECT_FALSE(loader1);
// Confirm that a new speculative RenderFrameHost was created.
speculative_rfh = GetSpeculativeRenderFrameHost(node);
ASSERT_TRUE(speculative_rfh);
auto site_instance_id_2 = speculative_rfh->GetSiteInstance()->GetId();
if (AreDefaultSiteInstancesEnabled()) {
EXPECT_TRUE(speculative_rfh->GetSiteInstance()->IsDefaultSiteInstance());
EXPECT_EQ(site_instance_id_1, site_instance_id_2);
} else {
EXPECT_NE(site_instance_id_1, site_instance_id_2);
}
navigation2->ReadyToCommit();
EXPECT_EQ(speculative_rfh->navigation_requests().size(), 1u);
EXPECT_EQ(main_test_rfh()->navigation_requests().size(), 0u);
// Have the RenderFrameHost commit the navigation.
navigation2->Commit();
// Confirm that the commit corresponds to the new request.
ASSERT_TRUE(main_test_rfh());
if (AreDefaultSiteInstancesEnabled()) {
EXPECT_TRUE(main_test_rfh()->GetSiteInstance()->IsDefaultSiteInstance());
} else {
EXPECT_EQ(kUrl2SiteInfo, main_test_rfh()->GetSiteInstance()->GetSiteInfo());
}
EXPECT_EQ(kUrl2, contents()->GetLastCommittedURL());
// Confirm that the committed RenderFrameHost is the latest speculative one.
EXPECT_EQ(site_instance_id_2, main_test_rfh()->GetSiteInstance()->GetId());
}
// Test that a browser-initiated navigation is canceled if a renderer-initiated
// user-initiated request has been issued in the meantime.
TEST_F(NavigatorTest, RendererUserInitiatedNavigationCancel) {
const GURL kUrl0("http://www.wikipedia.org/");
const GURL kUrl1("http://www.chromium.org/");
const GURL kUrl2("http://www.google.com/");
// Initialization.
contents()->NavigateAndCommit(kUrl0);
FrameTreeNode* node = main_test_rfh()->frame_tree_node();
bool expect_site_instance_change =
ExpectSiteInstanceChange(main_test_rfh()->GetSiteInstance());
// Start a browser-initiated navigation to the 1st URL and invoke its
// beforeUnload completion callback.
EXPECT_FALSE(node->navigation_request());
auto navigation2 =
NavigationSimulator::CreateBrowserInitiated(kUrl1, contents());
navigation2->Start();
NavigationRequest* request1 = node->navigation_request();
ASSERT_TRUE(request1);
EXPECT_EQ(kUrl1, request1->common_params().url);
EXPECT_TRUE(request1->browser_initiated());
base::WeakPtr<TestNavigationURLLoader> loader1 =
GetLoaderForNavigationRequest(request1)->AsWeakPtr();
EXPECT_TRUE(loader1);
// Confirm that a speculative RenderFrameHost was created.
ASSERT_TRUE(GetSpeculativeRenderFrameHost(node));
// Now receive a renderer-initiated user-initiated request. It should replace
// the current NavigationRequest.
auto navigation =
NavigationSimulator::CreateRendererInitiated(kUrl2, main_test_rfh());
navigation->SetTransition(ui::PAGE_TRANSITION_LINK);
navigation->SetHasUserGesture(true);
navigation->Start();
NavigationRequest* request2 = node->navigation_request();
ASSERT_TRUE(request2);
EXPECT_EQ(kUrl2, request2->common_params().url);
EXPECT_FALSE(request2->browser_initiated());
EXPECT_TRUE(request2->common_params().has_user_gesture);
// Confirm that the first loader got destroyed.
EXPECT_FALSE(loader1);
// Confirm that the speculative RenderFrameHost was destroyed in the non
// SitePerProcess case.
if (expect_site_instance_change) {
EXPECT_TRUE(GetSpeculativeRenderFrameHost(node));
} else {
EXPECT_FALSE(GetSpeculativeRenderFrameHost(node));
}
// Commit the navigation.
navigation->Commit();
// Confirm that the commit corresponds to the new request.
ASSERT_TRUE(main_test_rfh());
EXPECT_EQ(kUrl2, contents()->GetLastCommittedURL());
}
// Tests that a renderer-initiated user-initiated navigation is
// canceled if a renderer-initiated non-user-initiated request is issued in the
// meantime.
TEST_F(NavigatorTest,
RendererNonUserInitiatedNavigationCancelsRendererUserInitiated) {
const GURL kUrl0("http://www.wikipedia.org/");
const GURL kUrl1("http://www.chromium.org/");
const GURL kUrl2("http://www.google.com/");
// Initialization.
contents()->NavigateAndCommit(kUrl0);
FrameTreeNode* node = main_test_rfh()->frame_tree_node();
bool expect_site_instance_change =
ExpectSiteInstanceChange(main_test_rfh()->GetSiteInstance());
// Start a renderer-initiated user-initiated navigation to the 1st URL.
EXPECT_FALSE(node->navigation_request());
auto user_initiated_navigation =
NavigationSimulator::CreateRendererInitiated(kUrl1, main_test_rfh());
user_initiated_navigation->SetTransition(ui::PAGE_TRANSITION_LINK);
user_initiated_navigation->SetHasUserGesture(true);
user_initiated_navigation->Start();
NavigationRequest* request1 = node->navigation_request();
ASSERT_TRUE(request1);
EXPECT_EQ(kUrl1, request1->common_params().url);
EXPECT_FALSE(request1->browser_initiated());
EXPECT_TRUE(request1->common_params().has_user_gesture);
if (expect_site_instance_change) {
EXPECT_TRUE(GetSpeculativeRenderFrameHost(node));
} else {
EXPECT_FALSE(GetSpeculativeRenderFrameHost(node));
}
// Now receive a renderer-initiated non-user-initiated request. The previous
// navigation should be replaced.
auto non_user_initiated_navigation =
NavigationSimulator::CreateRendererInitiated(kUrl2, main_test_rfh());
non_user_initiated_navigation->SetTransition(ui::PAGE_TRANSITION_LINK);
non_user_initiated_navigation->SetHasUserGesture(false);
non_user_initiated_navigation->Start();
NavigationRequest* request2 = node->navigation_request();
ASSERT_TRUE(request2);
EXPECT_NE(request1, request2);
EXPECT_EQ(kUrl2, request2->common_params().url);
EXPECT_FALSE(request2->browser_initiated());
EXPECT_FALSE(request2->common_params().has_user_gesture);
if (expect_site_instance_change) {
EXPECT_TRUE(GetSpeculativeRenderFrameHost(node));
} else {
EXPECT_FALSE(GetSpeculativeRenderFrameHost(node));
}
// Commit the navigation.
non_user_initiated_navigation->Commit();
EXPECT_EQ(kUrl2, contents()->GetLastCommittedURL());
}
// PlzNavigate: Test that a browser-initiated navigation is NOT canceled if a
// renderer-initiated non-user-initiated request is issued in the meantime.
TEST_F(NavigatorTest,
RendererNonUserInitiatedNavigationDoesntCancelBrowserInitiated) {
const GURL kUrl0("http://www.wikipedia.org/");
const GURL kUrl1("http://www.chromium.org/");
const GURL kUrl2("http://www.google.com/");
// Initialization.
contents()->NavigateAndCommit(kUrl0);
FrameTreeNode* node = main_test_rfh()->frame_tree_node();
// Start a browser-initiated navigation to the 1st URL.
EXPECT_FALSE(node->navigation_request());
auto navigation =
NavigationSimulator::CreateBrowserInitiated(kUrl1, contents());
navigation->Start();
NavigationRequest* request1 = node->navigation_request();
ASSERT_TRUE(request1);
EXPECT_EQ(kUrl1, request1->common_params().url);
EXPECT_TRUE(request1->browser_initiated());
TestRenderFrameHost* speculative_rfh = GetSpeculativeRenderFrameHost(node);
ASSERT_TRUE(speculative_rfh);
// Now receive a renderer-initiated non-user-initiated request. Nothing should
// change.
main_test_rfh()->SendRendererInitiatedNavigationRequest(
kUrl2, false /* has_user_gesture */);
NavigationRequest* request2 = node->navigation_request();
ASSERT_TRUE(request2);
EXPECT_EQ(request1, request2);
EXPECT_EQ(kUrl1, request2->common_params().url);
EXPECT_TRUE(request2->browser_initiated());
EXPECT_TRUE(speculative_rfh);
navigation->ReadyToCommit();
EXPECT_EQ(speculative_rfh->navigation_requests().size(), 1u);
EXPECT_EQ(main_test_rfh()->navigation_requests().size(), 0u);
navigation->Commit();
EXPECT_EQ(kUrl1, contents()->GetLastCommittedURL());
}
// PlzNavigate: Test that a renderer-initiated non-user-initiated navigation is
// canceled if a another similar request is issued in the meantime.
TEST_F(NavigatorTest,
RendererNonUserInitiatedNavigationCancelSimilarNavigation) {
const GURL kUrl0("http://www.wikipedia.org/");
const GURL kUrl1("http://www.chromium.org/");
const GURL kUrl2("http://www.google.com/");
// Initialization.
contents()->NavigateAndCommit(kUrl0);
FrameTreeNode* node = main_test_rfh()->frame_tree_node();
auto site_instance_id_0 = main_test_rfh()->GetSiteInstance()->GetId();
bool expect_site_instance_change =
ExpectSiteInstanceChange(main_test_rfh()->GetSiteInstance());
// Start a renderer-initiated non-user-initiated navigation to the 1st URL.
EXPECT_FALSE(node->navigation_request());
auto navigation1 =
NavigationSimulator::CreateRendererInitiated(kUrl1, main_test_rfh());
navigation1->SetTransition(ui::PageTransitionFromInt(
ui::PAGE_TRANSITION_LINK | ui::PAGE_TRANSITION_CLIENT_REDIRECT));
navigation1->SetHasUserGesture(false);
navigation1->Start();
NavigationRequest* request1 = node->navigation_request();
ASSERT_TRUE(request1);
EXPECT_EQ(kUrl1, request1->common_params().url);
EXPECT_FALSE(request1->browser_initiated());
EXPECT_FALSE(request1->common_params().has_user_gesture);
if (expect_site_instance_change) {
EXPECT_TRUE(GetSpeculativeRenderFrameHost(node));
} else {
EXPECT_FALSE(GetSpeculativeRenderFrameHost(node));
}
base::WeakPtr<TestNavigationURLLoader> loader1 =
GetLoaderForNavigationRequest(request1)->AsWeakPtr();
EXPECT_TRUE(loader1);
// Now receive a 2nd similar request that should replace the current one.
auto navigation2 =
NavigationSimulator::CreateRendererInitiated(kUrl2, main_test_rfh());
navigation2->SetTransition(ui::PageTransitionFromInt(
ui::PAGE_TRANSITION_LINK | ui::PAGE_TRANSITION_CLIENT_REDIRECT));
navigation2->SetHasUserGesture(false);
navigation2->Start();
NavigationRequest* request2 = node->navigation_request();
EXPECT_EQ(kUrl2, request2->common_params().url);
EXPECT_FALSE(request2->browser_initiated());
EXPECT_FALSE(request2->common_params().has_user_gesture);
if (expect_site_instance_change) {
EXPECT_TRUE(GetSpeculativeRenderFrameHost(node));
} else {
EXPECT_FALSE(GetSpeculativeRenderFrameHost(node));
}
// Confirm that the first loader got destroyed.
EXPECT_FALSE(loader1);
// Commit the navigation.
navigation2->Commit();
EXPECT_EQ(kUrl2, contents()->GetLastCommittedURL());
if (expect_site_instance_change) {
EXPECT_NE(site_instance_id_0, main_test_rfh()->GetSiteInstance()->GetId());
} else {
EXPECT_EQ(site_instance_id_0, main_test_rfh()->GetSiteInstance()->GetId());
}
}
// PlzNavigate: Test that a reload navigation is properly signaled to the
// RenderFrame when the navigation can commit. A speculative RenderFrameHost
// should not be created at any step.
TEST_F(NavigatorTest, Reload) {
const GURL kUrl("http://www.google.com/");
contents()->NavigateAndCommit(kUrl);
FrameTreeNode* node = main_test_rfh()->frame_tree_node();
controller().Reload(ReloadType::NORMAL, false);
auto reload1 =
NavigationSimulator::CreateFromPending(contents()->GetController());
// A NavigationRequest should have been generated.
NavigationRequest* main_request = node->navigation_request();
ASSERT_TRUE(main_request != nullptr);
EXPECT_EQ(blink::mojom::NavigationType::RELOAD,
main_request->common_params().navigation_type);
reload1->ReadyToCommit();
EXPECT_FALSE(GetSpeculativeRenderFrameHost(node));
reload1->Commit();
EXPECT_FALSE(GetSpeculativeRenderFrameHost(node));
// Now do a shift+reload.
controller().Reload(ReloadType::BYPASSING_CACHE, false);
auto reload2 =
NavigationSimulator::CreateFromPending(contents()->GetController());
// A NavigationRequest should have been generated.
main_request = node->navigation_request();
ASSERT_TRUE(main_request != nullptr);
EXPECT_EQ(blink::mojom::NavigationType::RELOAD_BYPASSING_CACHE,
main_request->common_params().navigation_type);
reload2->ReadyToCommit();
EXPECT_FALSE(GetSpeculativeRenderFrameHost(node));
}
// PlzNavigate: Confirm that a speculative RenderFrameHost is used when
// navigating from one site to another.
TEST_F(NavigatorTest, SpeculativeRendererWorksBaseCase) {
// Navigate to an initial site.
const GURL kUrlInit("http://wikipedia.org/");
contents()->NavigateAndCommit(kUrlInit);
FrameTreeNode* node = main_test_rfh()->frame_tree_node();
// Begin navigating to another site.
const GURL kUrl("http://google.com/");
EXPECT_FALSE(node->navigation_request());
auto navigation =
NavigationSimulator::CreateBrowserInitiated(kUrl, contents());
navigation->Start();
TestRenderFrameHost* speculative_rfh = GetSpeculativeRenderFrameHost(node);
auto site_instance_id = speculative_rfh->GetSiteInstance()->GetId();
ASSERT_TRUE(speculative_rfh);
EXPECT_NE(speculative_rfh, main_test_rfh());
if (AreDefaultSiteInstancesEnabled()) {
EXPECT_TRUE(speculative_rfh->GetSiteInstance()->IsDefaultSiteInstance());
} else {
EXPECT_EQ(CreateExpectedSiteInfo(kUrl),
speculative_rfh->GetSiteInstance()->GetSiteInfo());
}
navigation->ReadyToCommit();
EXPECT_EQ(speculative_rfh->navigation_requests().size(), 1u);
// Ask the navigation to commit.
navigation->Commit();
EXPECT_EQ(site_instance_id, main_test_rfh()->GetSiteInstance()->GetId());
EXPECT_FALSE(GetSpeculativeRenderFrameHost(node));
}
// PlzNavigate: Confirm that a speculative RenderFrameHost is thrown away when
// the final URL's site differs from the initial one due to redirects.
TEST_F(NavigatorTest, SpeculativeRendererDiscardedAfterRedirectToAnotherSite) {
// Navigate to an initial site.
const GURL kUrlInit("http://wikipedia.org/");
contents()->NavigateAndCommit(kUrlInit);
FrameTreeNode* node = main_test_rfh()->frame_tree_node();
auto init_site_instance_id = main_test_rfh()->GetSiteInstance()->GetId();
// Begin navigating to another site.
const GURL kUrl("http://google.com/");
EXPECT_FALSE(node->navigation_request());
auto navigation =
NavigationSimulator::CreateBrowserInitiated(kUrl, contents());
navigation->Start();
TestRenderFrameHost* speculative_rfh = GetSpeculativeRenderFrameHost(node);
ASSERT_TRUE(speculative_rfh);
auto site_instance_id = speculative_rfh->GetSiteInstance()->GetId();
RenderFrameDeletedObserver rfh_deleted_observer(speculative_rfh);
EXPECT_NE(init_site_instance_id, site_instance_id);
EXPECT_EQ(init_site_instance_id, main_test_rfh()->GetSiteInstance()->GetId());
EXPECT_NE(speculative_rfh, main_test_rfh());
if (AreDefaultSiteInstancesEnabled()) {
EXPECT_TRUE(speculative_rfh->GetSiteInstance()->IsDefaultSiteInstance());
} else {
EXPECT_EQ(CreateExpectedSiteInfo(kUrl),
speculative_rfh->GetSiteInstance()->GetSiteInfo());
}
// It then redirects to yet another site.
NavigationRequest* main_request = node->navigation_request();
ASSERT_TRUE(main_request);
const GURL kUrlRedirect("https://www.google.com/");
navigation->Redirect(kUrlRedirect);
EXPECT_EQ(init_site_instance_id, main_test_rfh()->GetSiteInstance()->GetId());
// For now, ensure that the speculative RenderFrameHost does not change after
// the redirect.
// TODO(carlosk): once the speculative RenderFrameHost updates with redirects
// this next check will be changed to verify that it actually happens.
EXPECT_EQ(speculative_rfh, GetSpeculativeRenderFrameHost(node));
EXPECT_EQ(site_instance_id, speculative_rfh->GetSiteInstance()->GetId());
EXPECT_FALSE(rfh_deleted_observer.deleted());
// Send the commit to the renderer.
navigation->ReadyToCommit();
// Once commit happens the speculative RenderFrameHost is updated to match the
// known final SiteInstance.
speculative_rfh = GetSpeculativeRenderFrameHost(node);
ASSERT_TRUE(speculative_rfh);
EXPECT_EQ(speculative_rfh->navigation_requests().size(), 1u);
EXPECT_EQ(init_site_instance_id, main_test_rfh()->GetSiteInstance()->GetId());
auto redirect_site_instance_id = speculative_rfh->GetSiteInstance()->GetId();
// Expect the initial and redirect SiteInstances to be different because
// they should be associated with different BrowsingInstances.
EXPECT_NE(init_site_instance_id, redirect_site_instance_id);
if (AreDefaultSiteInstancesEnabled()) {
EXPECT_TRUE(speculative_rfh->GetSiteInstance()->IsDefaultSiteInstance());
EXPECT_EQ(site_instance_id, redirect_site_instance_id);
// Verify the old speculative RenderFrameHost was not deleted because
// the SiteInstance stayed the same.
EXPECT_FALSE(rfh_deleted_observer.deleted());
} else {
EXPECT_EQ(CreateExpectedSiteInfo(kUrlRedirect),
speculative_rfh->GetSiteInstance()->GetSiteInfo());
EXPECT_NE(site_instance_id, redirect_site_instance_id);
// Verify the old speculative RenderFrameHost was deleted because
// the SiteInstance changed.
EXPECT_TRUE(rfh_deleted_observer.deleted());
}
// Invoke DidCommitProvisionalLoad.
navigation->Commit();
// Check that the speculative RenderFrameHost was swapped in.
EXPECT_EQ(redirect_site_instance_id,
main_test_rfh()->GetSiteInstance()->GetId());
EXPECT_FALSE(GetSpeculativeRenderFrameHost(node));
}
// PlzNavigate: Verify that data urls are properly handled.
TEST_F(NavigatorTest, DataUrls) {
const GURL kUrl1("http://wikipedia.org/");
const GURL kUrl2("data:text/html,test");
// Isolate kUrl1 so it can't be mapped into a default SiteInstance along with
// kUrl2. This ensures that the speculative RenderFrameHost will always be
// used because the URLs map to different SiteInstances.
ChildProcessSecurityPolicy::GetInstance()->AddFutureIsolatedOrigins(
{url::Origin::Create(kUrl1)},
ChildProcessSecurityPolicy::IsolatedOriginSource::TEST,
browser_context());
// Navigate to an initial site.
contents()->NavigateAndCommit(kUrl1);
FrameTreeNode* node = main_test_rfh()->frame_tree_node();
EXPECT_FALSE(main_test_rfh()->GetSiteInstance()->IsDefaultSiteInstance());
// Navigate to a data url. The request should have been sent to the IO
// thread and not committed immediately.
auto navigation =
NavigationSimulator::CreateBrowserInitiated(kUrl2, contents());
navigation->Start();
TestRenderFrameHost* speculative_rfh = GetSpeculativeRenderFrameHost(node);
ASSERT_TRUE(speculative_rfh);
EXPECT_FALSE(speculative_rfh->is_loading());
EXPECT_TRUE(node->navigation_request());
navigation->ReadyToCommit();
EXPECT_TRUE(speculative_rfh->is_loading());
EXPECT_FALSE(node->navigation_request());
EXPECT_NE(main_test_rfh(), speculative_rfh);
navigation->Commit();
EXPECT_EQ(main_test_rfh(), speculative_rfh);
// Go back to the initial site.
contents()->NavigateAndCommit(kUrl1);
// Do a renderer-initiated navigation to a data url. The request should be
// sent to the IO thread.
auto navigation_to_data_url =
NavigationSimulator::CreateRendererInitiated(kUrl2, main_test_rfh());
navigation_to_data_url->Start();
EXPECT_FALSE(main_test_rfh()->is_loading());
EXPECT_TRUE(node->navigation_request());
}
// Tests several cases for converting SiteInstanceDescriptors into
// SiteInstances:
// 1) Pointer to the current SiteInstance.
// 2) Pointer to an unrelated SiteInstance.
// 3) Same-site URL, related.
// 4) Cross-site URL, related.
// 5) Same-site URL, unrelated (with and without candidate SiteInstances).
// 6) Cross-site URL, unrelated (with candidate SiteInstance).
TEST_F(NavigatorTest, SiteInstanceDescriptionConversion) {
// Navigate to set a current SiteInstance on the RenderFrameHost.
GURL kUrl1("http://a.com");
// Isolate one of the sites so the both can't be mapped to the default
// site instance.
ChildProcessSecurityPolicy::GetInstance()->AddFutureIsolatedOrigins(
{url::Origin::Create(kUrl1)},
ChildProcessSecurityPolicy::IsolatedOriginSource::TEST,
browser_context());
contents()->NavigateAndCommit(kUrl1);
SiteInstanceImpl* current_instance = main_test_rfh()->GetSiteInstance();
ASSERT_TRUE(current_instance);
// 1) Convert a descriptor pointing to the current instance.
RenderFrameHostManager* rfhm =
main_test_rfh()->frame_tree_node()->render_manager();
{
SiteInstanceDescriptor descriptor(current_instance);
scoped_refptr<SiteInstance> converted_instance =
ConvertToSiteInstance(rfhm, descriptor, nullptr);
EXPECT_EQ(current_instance, converted_instance);
}
// 2) Convert a descriptor pointing an instance unrelated to the current one,
// with a different site.
GURL kUrl2("http://b.com");
scoped_refptr<SiteInstance> unrelated_instance(
SiteInstance::CreateForURL(browser_context(), kUrl2));
EXPECT_FALSE(
current_instance->IsRelatedSiteInstance(unrelated_instance.get()));
{
SiteInstanceDescriptor descriptor(unrelated_instance.get());
scoped_refptr<SiteInstance> converted_instance =
ConvertToSiteInstance(rfhm, descriptor, nullptr);
EXPECT_EQ(unrelated_instance.get(), converted_instance);
}
// 3) Convert a descriptor of a related instance with the same site as the
// current one.
GURL kUrlSameSiteAs1("http://www.a.com/foo");
{
SiteInstanceDescriptor descriptor(
UrlInfo::CreateForTesting(kUrlSameSiteAs1),
SiteInstanceRelation::RELATED);
scoped_refptr<SiteInstance> converted_instance =
ConvertToSiteInstance(rfhm, descriptor, nullptr);
EXPECT_EQ(current_instance, converted_instance);
}
// 4) Convert a descriptor of a related instance with a site different from
// the current one.
GURL kUrlSameSiteAs2("http://www.b.com/foo");
scoped_refptr<SiteInstanceImpl> related_instance;
{
SiteInstanceDescriptor descriptor(
UrlInfo::CreateForTesting(kUrlSameSiteAs2),
SiteInstanceRelation::RELATED);
related_instance = ConvertToSiteInstance(rfhm, descriptor, nullptr);
// If kUrlSameSiteAs2 requires a dedicated process on this platform, this
// should return a new instance, related to the current and set to the new
// site URL.
// Otherwise, this should return the default site instance
EXPECT_TRUE(
current_instance->IsRelatedSiteInstance(related_instance.get()));
EXPECT_NE(current_instance, related_instance.get());
EXPECT_NE(unrelated_instance.get(), related_instance.get());
if (AreDefaultSiteInstancesEnabled()) {
ASSERT_TRUE(related_instance->IsDefaultSiteInstance());
} else {
EXPECT_EQ(SiteInfo::CreateForTesting(
current_instance->GetIsolationContext(), kUrlSameSiteAs2),
related_instance->GetSiteInfo());
}
}
// 5) Convert a descriptor of an unrelated instance with the same site as the
// current one, several times, with and without candidate sites.
{
SiteInstanceDescriptor descriptor(
UrlInfo::CreateForTesting(kUrlSameSiteAs1),
SiteInstanceRelation::UNRELATED);
scoped_refptr<SiteInstanceImpl> converted_instance_1 =
ConvertToSiteInstance(rfhm, descriptor, nullptr);
// Should return a new instance, unrelated to the current one, set to the
// provided site URL.
EXPECT_FALSE(
current_instance->IsRelatedSiteInstance(converted_instance_1.get()));
EXPECT_NE(current_instance, converted_instance_1.get());
EXPECT_NE(unrelated_instance.get(), converted_instance_1.get());
EXPECT_EQ(CreateExpectedSiteInfo(kUrlSameSiteAs1),
converted_instance_1->GetSiteInfo());
// Does the same but this time using unrelated_instance as a candidate,
// which has a different site.
scoped_refptr<SiteInstanceImpl> converted_instance_2 =
ConvertToSiteInstance(rfhm, descriptor, unrelated_instance.get());
// Should return yet another new instance, unrelated to the current one, set
// to the same site URL.
EXPECT_FALSE(
current_instance->IsRelatedSiteInstance(converted_instance_2.get()));
EXPECT_NE(current_instance, converted_instance_2.get());
EXPECT_NE(unrelated_instance.get(), converted_instance_2.get());
EXPECT_NE(converted_instance_1.get(), converted_instance_2.get());
EXPECT_EQ(CreateExpectedSiteInfo(kUrlSameSiteAs1),
converted_instance_1->GetSiteInfo());
// Converts once more but with |converted_instance_1| as a candidate.
scoped_refptr<SiteInstance> converted_instance_3 =
ConvertToSiteInstance(rfhm, descriptor, converted_instance_1.get());
// Should return |converted_instance_1| because its site matches and it is
// unrelated to the current SiteInstance.
EXPECT_EQ(converted_instance_1.get(), converted_instance_3);
}
// 6) Convert a descriptor of an unrelated instance with the same site of
// related_instance and using it as a candidate.
{
SiteInstanceDescriptor descriptor(
UrlInfo::CreateForTesting(kUrlSameSiteAs2),
SiteInstanceRelation::UNRELATED);
scoped_refptr<SiteInstanceImpl> converted_instance_1 =
ConvertToSiteInstance(rfhm, descriptor, related_instance.get());
// Should return a new instance, unrelated to the current, set to the
// provided site URL.
EXPECT_FALSE(
current_instance->IsRelatedSiteInstance(converted_instance_1.get()));
EXPECT_NE(related_instance.get(), converted_instance_1.get());
EXPECT_NE(unrelated_instance.get(), converted_instance_1.get());
if (AreDefaultSiteInstancesEnabled()) {
EXPECT_TRUE(converted_instance_1->IsDefaultSiteInstance());
} else {
EXPECT_EQ(CreateExpectedSiteInfo(kUrlSameSiteAs2),
converted_instance_1->GetSiteInfo());
}
scoped_refptr<SiteInstance> converted_instance_2 =
ConvertToSiteInstance(rfhm, descriptor, unrelated_instance.get());
// Should return |unrelated_instance| because its site matches and it is
// unrelated to the current SiteInstance.
EXPECT_EQ(unrelated_instance.get(), converted_instance_2);
}
}
// A renderer process might try and claim that a cross site navigation was
// within the same document by setting was_within_same_document = true in
// DidCommitProvisionalLoadParams. Such case should be detected on the browser
// side and the renderer process should be killed.
TEST_F(NavigatorTest, CrossSiteClaimWithinPage) {
const GURL kUrl1("http://www.chromium.org/");
const GURL kUrl2("http://www.google.com/");
NavigationSimulator::NavigateAndCommitFromBrowser(contents(), kUrl1);
// Navigate to a different site and claim that the navigation was within same
// page.
int bad_msg_count = process()->bad_msg_count();
auto simulator =
NavigationSimulator::CreateRendererInitiated(kUrl2, main_test_rfh());
simulator->CommitSameDocument();
EXPECT_EQ(process()->bad_msg_count(), bad_msg_count + 1);
}
// Tests that an ongoing NavigationRequest is deleted when a same-site
// user-initiated navigation commits.
TEST_F(NavigatorTest, NavigationRequestDeletedWhenUserInitiatedCommits) {
const GURL kUrl1("http://www.chromium.org/");
const GURL kUrl2("http://www.chromium.org/foo");
const GURL kUrl3("http://www.google.com/");
contents()->NavigateAndCommit(kUrl1);
FrameTreeNode* node = main_test_rfh()->frame_tree_node();
// The test below only makes sense if the same-site navigation below will not
// create a speculative RFH, so we need to ensure that we won't trigger a
// same-site cross-RFH navigation.
// Note: this will not disable RenderDocument.
// TODO(crbug.com/936696): Skip this test when main-frame RenderDocument is
// enabled.
DisableProactiveBrowsingInstanceSwapFor(main_test_rfh());
// Navigate same-site.
auto navigation =
NavigationSimulator::CreateBrowserInitiated(kUrl2, contents());
navigation->ReadyToCommit();
EXPECT_TRUE(main_test_rfh()->is_loading());
EXPECT_FALSE(node->navigation_request());
// Start a new cross-site navigation. The current RFH should still be trying
// to commit the previous navigation, but we create a NavigationRequest in the
// FrameTreeNode.
auto navigation2 =
NavigationSimulator::CreateBrowserInitiated(kUrl3, contents());
navigation2->Start();
EXPECT_TRUE(main_test_rfh()->is_loading());
EXPECT_TRUE(node->navigation_request());
EXPECT_TRUE(GetSpeculativeRenderFrameHost(node));
// The first navigation commits. This should clear up the speculative RFH and
// the ongoing NavigationRequest.
navigation->Commit();
EXPECT_FALSE(node->navigation_request());
EXPECT_FALSE(GetSpeculativeRenderFrameHost(node));
}
// Tests that an ongoing NavigationRequest is deleted when a cross-site
// navigation commits.
TEST_F(NavigatorTest, NavigationRequestDeletedWhenCrossSiteCommits) {
const GURL kUrl1("http://www.chromium.org/");
const GURL kUrl2("http://www.google.com/");
const GURL kUrl3("http://www.google.com/foo");
contents()->NavigateAndCommit(kUrl1);
FrameTreeNode* node = main_test_rfh()->frame_tree_node();
// Navigate cross-site.
auto navigation =
NavigationSimulator::CreateBrowserInitiated(kUrl2, contents());
navigation->ReadyToCommit();
TestRenderFrameHost* speculative_rfh = GetSpeculativeRenderFrameHost(node);
ASSERT_TRUE(speculative_rfh);
EXPECT_TRUE(speculative_rfh->is_loading());
EXPECT_FALSE(node->navigation_request());
// Start a new cross-site navigation to the same-site as the ongoing
// navigation. The speculative RFH should still be live and trying
// to commit the previous navigation, and we create a NavigationRequest in the
// FrameTreeNode.
auto navigation2 =
NavigationSimulator::CreateBrowserInitiated(kUrl3, contents());
navigation2->Start();
TestRenderFrameHost* speculative_rfh_2 = GetSpeculativeRenderFrameHost(node);
ASSERT_TRUE(speculative_rfh_2);
EXPECT_EQ(speculative_rfh_2, speculative_rfh);
EXPECT_TRUE(speculative_rfh->is_loading());
EXPECT_TRUE(node->navigation_request());
// The first navigation commits. This should clear up the speculative RFH and
// the ongoing NavigationRequest.
navigation->Commit();
EXPECT_FALSE(node->navigation_request());
EXPECT_FALSE(GetSpeculativeRenderFrameHost(node));
EXPECT_EQ(speculative_rfh, main_test_rfh());
}
// Permissions Policy: Test that the permissions policy is reset when navigating
// pages within a site.
TEST_F(NavigatorTest, PermissionsPolicySameSiteNavigation) {
const GURL kUrl1("http://www.chromium.org/");
const GURL kUrl2("http://www.chromium.org/Home");
contents()->NavigateAndCommit(kUrl1);
// Check the permissions policy before navigation.
const blink::PermissionsPolicy* original_permissions_policy =
main_test_rfh()->permissions_policy();
ASSERT_TRUE(original_permissions_policy);
// Navigate to the new URL.
contents()->NavigateAndCommit(kUrl2);
// Check the permissions policy after navigation.
const blink::PermissionsPolicy* final_permissions_policy =
main_test_rfh()->permissions_policy();
ASSERT_TRUE(final_permissions_policy);
ASSERT_NE(original_permissions_policy, final_permissions_policy);
}
// Permissions Policy: Test that the permissions policy is not reset when
// navigating within a page.
TEST_F(NavigatorTest, PermissionsPolicyFragmentNavigation) {
const GURL kUrl1("http://www.chromium.org/");
const GURL kUrl2("http://www.chromium.org/#Home");
contents()->NavigateAndCommit(kUrl1);
// Check the permissions policy before navigation.
const blink::PermissionsPolicy* original_permissions_policy =
main_test_rfh()->permissions_policy();
ASSERT_TRUE(original_permissions_policy);
// Navigate to the new URL.
contents()->NavigateAndCommit(kUrl2);
// Check the permissions policy after navigation.
const blink::PermissionsPolicy* final_permissions_policy =
main_test_rfh()->permissions_policy();
ASSERT_EQ(original_permissions_policy, final_permissions_policy);
}
// Permissions Policy: Test that the permissions policy is set correctly when
// inserting a new child frame.
TEST_F(NavigatorTest, PermissionsPolicyNewChild) {
const GURL kUrl1("http://www.chromium.org/");
const GURL kUrl2("http://www.chromium.org/Home");
contents()->NavigateAndCommit(kUrl1);
// Simulate the navigation triggered by inserting a child frame into a page.
TestRenderFrameHost* subframe_rfh =
contents()->GetMainFrame()->AppendChild("child");
NavigationSimulator::NavigateAndCommitFromDocument(kUrl2, subframe_rfh);
const blink::PermissionsPolicy* subframe_permissions_policy =
subframe_rfh->permissions_policy();
ASSERT_TRUE(subframe_permissions_policy);
ASSERT_FALSE(subframe_permissions_policy->GetOriginForTest().opaque());
}
TEST_F(NavigatorTest, TwoNavigationsRacingCommit) {
const GURL kUrl1("http://www.chromium.org/");
const GURL kUrl2("http://www.chromium.org/Home");
EXPECT_EQ(0u, contents()->GetMainFrame()->navigation_requests_.size());
// Have the first navigation reach ReadyToCommit.
auto first_navigation =
NavigationSimulator::CreateBrowserInitiated(kUrl1, contents());
first_navigation->ReadyToCommit();
EXPECT_EQ(1u, contents()->GetMainFrame()->navigation_requests_.size());
// A second navigation starts and reaches ReadyToCommit.
auto second_navigation =
NavigationSimulator::CreateBrowserInitiated(kUrl1, contents());
second_navigation->ReadyToCommit();
EXPECT_EQ(2u, contents()->GetMainFrame()->navigation_requests_.size());
// The first navigation commits.
first_navigation->Commit();
EXPECT_EQ(1u, contents()->GetMainFrame()->navigation_requests_.size());
// The second navigation commits.
second_navigation->Commit();
EXPECT_EQ(0u, contents()->GetMainFrame()->navigation_requests_.size());
}
} // namespace content
| 41.351386 | 80 | 0.759714 | [
"model"
] |
8252a158c6437ce92738518338059c21fdff469c | 2,463 | cpp | C++ | jni/src/core/ImageProc.cpp | yajun0601/DetectionOpenCV | e697b6b8cf16480fd08d3e68c513ece628bd77fc | [
"Apache-2.0"
] | null | null | null | jni/src/core/ImageProc.cpp | yajun0601/DetectionOpenCV | e697b6b8cf16480fd08d3e68c513ece628bd77fc | [
"Apache-2.0"
] | null | null | null | jni/src/core/ImageProc.cpp | yajun0601/DetectionOpenCV | e697b6b8cf16480fd08d3e68c513ece628bd77fc | [
"Apache-2.0"
] | null | null | null | #include <com_example_carplate_CarPlateDetection.h>
#include "plate_locate.h"
#include "plate_judge.h"
#include "chars_segment.h"
#include "chars_identify.h"
#include "plate_detect.h"
#include "chars_recognise.h"
#include "plate_recognize.h"
using namespace easypr;
#include <android/log.h>
#include <string>
#include <jni.h>
#define LOG_TAG "System.out"
#define LOGI(...) __android_log_print(ANDROID_LOG_INFO,LOG_TAG,__VA_ARGS__)
#define LOGD(...) __android_log_print(ANDROID_LOG_DEBUG,LOG_TAG,__VA_ARGS__)
#define LOGE(...) __android_log_print(ANDROID_LOG_ERROR,LOG_TAG,__VA_ARGS__)
JNIEXPORT jstring JNICALL Java_com_example_carplate_CarPlateDetection_stringFromJNI (JNIEnv *env, jclass thiz){
return env->NewStringUTF("\n Hello from JNI ! Compiled with ABI .");
}
char* jstring2str(JNIEnv* env, jstring jstr) {
char* rtn = NULL;
jclass clsstring = env->FindClass("java/lang/String");
jstring strencode = env->NewStringUTF("GB2312");
jmethodID mid = env->GetMethodID(clsstring, "getBytes",
"(Ljava/lang/String;)[B");
jbyteArray barr = (jbyteArray) env->CallObjectMethod(jstr, mid, strencode);
jsize alen = env->GetArrayLength(barr);
jbyte* ba = env->GetByteArrayElements(barr, JNI_FALSE);
if (alen > 0) {
rtn = (char*) malloc(alen + 1);
memcpy(rtn, ba, alen);
rtn[alen] = 0;
}
env->ReleaseByteArrayElements(barr, ba, 0);
return rtn;
}
JNIEXPORT jbyteArray JNICALL Java_com_example_carplate_CarPlateDetection_ImageProc(
JNIEnv *env, jclass obj, jstring imgpath, jstring svmpath,
jstring annpath) {
CPlateRecognize pr;
// const string *img = (*env)->GetStringUTFChars(env, imgpath, 0);
// const string *svm = (*env)->GetStringUTFChars(env, svmpath, 0);
// const string *ann = (*env)->GetStringUTFChars(env, annpath, 0);
char* img = jstring2str(env,imgpath);
char* svm = jstring2str(env,svmpath);
char* ann = jstring2str(env,annpath);
Mat src = imread(img);
pr.LoadSVM(svm);
pr.LoadANN(ann);
pr.setGaussianBlurSize(5);
pr.setMorphSizeWidth(17);
pr.setVerifyMin(3);
pr.setVerifyMax(20);
pr.setLiuDingSize(7);
pr.setColorThreshold(150);
vector < string > plateVec;
int count = pr.plateRecognize(src, plateVec);
string str = "0";
if (count == 0) {
str = plateVec[0];
}
char *result = new char[str.length() + 1];
strcpy(result, str.c_str());
jbyte *by = (jbyte*) result;
jbyteArray jarray = env->NewByteArray(strlen(result));
env->SetByteArrayRegion(jarray, 0, strlen(result), by);
return jarray;
}
| 31.576923 | 112 | 0.729598 | [
"vector"
] |
8256abd1eac13b94951c0c195f6e0a013c8458f8 | 1,541 | cpp | C++ | C3D/C3D-v1.1/src/caffe/layers/black_hole_layer.cpp | Blssel/ClassicalAlgorZoo | b3cd08961d971658cfc9ebd98760c7207f7b322e | [
"MIT"
] | null | null | null | C3D/C3D-v1.1/src/caffe/layers/black_hole_layer.cpp | Blssel/ClassicalAlgorZoo | b3cd08961d971658cfc9ebd98760c7207f7b322e | [
"MIT"
] | null | null | null | C3D/C3D-v1.1/src/caffe/layers/black_hole_layer.cpp | Blssel/ClassicalAlgorZoo | b3cd08961d971658cfc9ebd98760c7207f7b322e | [
"MIT"
] | null | null | null | /*
*
* Copyright (c) 2015, Facebook, Inc. All rights reserved.
*
* Licensed under the Creative Commons Attribution-NonCommercial 3.0
* License (the "License"). You may obtain a copy of the License at
* https://creativecommons.org/licenses/by-nc/3.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 <vector>
#include "caffe/layers/black_hole_layer.hpp"
#include "caffe/util/math_functions.hpp"
namespace caffe {
template <typename Dtype>
void BlackHoleLayer<Dtype>::LayerSetUp(const vector<Blob<Dtype>*>& bottom,
const vector<Blob<Dtype>*>& top) {
vector<int> top_shape(5,1);
top[0]->Reshape(top_shape);
}
template <typename Dtype>
void BlackHoleLayer<Dtype>::Reshape(const vector<Blob<Dtype>*>& bottom,
const vector<Blob<Dtype>*>& top) {
}
template <typename Dtype>
void BlackHoleLayer<Dtype>::Forward_cpu(const vector<Blob<Dtype>*>& bottom,
const vector<Blob<Dtype>*>& top) {
}
template <typename Dtype>
void BlackHoleLayer<Dtype>::Backward_cpu(const vector<Blob<Dtype>*>& top,
const vector<bool>& propagate_down, const vector<Blob<Dtype>*>& bottom) {
}
#ifdef CPU_ONLY
STUB_GPU(BlackHoleLayer);
#endif
INSTANTIATE_CLASS(BlackHoleLayer);
REGISTER_LAYER_CLASS(BlackHole);
} // namespace caffe
| 27.035088 | 79 | 0.731992 | [
"vector"
] |
8257da6348756249ef57c47a4593c94a3886f529 | 8,934 | hpp | C++ | src/maluuba/vptree.hpp | skoomasteve/PhoneticMatching | 441b2cc85e60829029c0af401a10db85fced872e | [
"MIT"
] | 89 | 2019-05-08T04:03:44.000Z | 2022-03-18T18:05:24.000Z | src/maluuba/vptree.hpp | BigHam/PhoneticMatching | e675a516aa557759a6656f6642f518cdce862840 | [
"MIT"
] | 22 | 2019-08-22T13:11:35.000Z | 2021-11-18T15:13:04.000Z | src/maluuba/vptree.hpp | BigHam/PhoneticMatching | e675a516aa557759a6656f6642f518cdce862840 | [
"MIT"
] | 21 | 2019-09-10T01:48:10.000Z | 2021-12-06T09:27:43.000Z | /**
* @file
* Vantage point trees.
*
* @author Tavian Barnes (tavian.barnes@microsoft.com)
*
* Copyright (c) Microsoft Corporation. All rights reserved.
* Licensed under the MIT License.
*/
#ifndef MALUUBA_VPTREE_HPP
#define MALUUBA_VPTREE_HPP
#include "maluuba/metric.hpp"
#include "maluuba/xtd/optional.hpp"
#include <algorithm>
#include <initializer_list>
#include <queue>
namespace maluuba
{
/**
* A vantage point tree.
*
* @tparam T The type of element to store.
* @tparam Metric The metric used to compare elements.
* @author Tavian Barnes (tavian.barnes@microsoft.com)
*/
template <typename T, typename Metric>
class VpTree
{
public:
using value_type = T;
using distance_type = MetricResult<Metric, T>;
private:
struct Node
{
T element;
distance_type radius;
std::size_t left_size;
Node(T element)
: element(std::move(element)), radius{}, left_size{}
{ }
};
using NodeVector = std::vector<Node>;
using NodeIterator = typename NodeVector::const_iterator;
public:
using size_type = typename NodeVector::size_type;
using difference_type = typename NodeVector::difference_type;
using reference = value_type&;
using const_reference = const value_type&;
using pointer = value_type*;
using const_pointer = const value_type*;
VpTree() = default;
explicit VpTree(Metric metric)
: m_metric{std::move(metric)}
{ }
explicit VpTree(std::initializer_list<T> ilist, Metric metric = Metric{})
: m_nodes{ilist.begin(), ilist.end()},
m_metric{std::move(metric)}
{
build_tree();
}
template <typename Iterator>
explicit VpTree(Iterator first, Iterator last, Metric metric = Metric{})
: m_nodes{first, last},
m_metric{std::move(metric)}
{
build_tree();
}
bool
empty() const
{
return m_nodes.empty();
}
size_type
size() const
{
return m_nodes.size();
}
/**
* A near match found in the tree.
*/
class Match
{
public:
Match() = default;
Match(NodeIterator node, distance_type distance)
: m_node{node}, m_distance{distance}
{ }
/**
* @return The found element.
*/
const T&
element() const
{
return m_node->element;
}
/**
* @return The metric distance from the target to this element.
*/
distance_type
distance() const
{
return m_distance;
}
private:
friend bool
operator<(const Match& lhs, const Match& rhs)
{
return lhs.distance() < rhs.distance();
}
NodeIterator m_node;
distance_type m_distance;
};
private:
/**
* An entry in the search stack.
*/
struct StackEntry
{
/** The range to search. */
NodeIterator first, last;
/** Search is necessary iff a <= b + tau. */
distance_type a, b;
StackEntry(NodeIterator first, NodeIterator last, distance_type a, distance_type b)
: first{first}, last{last}, a{a}, b{b}
{ }
};
using SearchStack = std::vector<StackEntry>;
public:
/**
* Find the nearest element in the tree.
*
* @param target The search target.
* @return The closest match to @p target, or @c nullopt if the tree is
* empty.
*/
template <typename U>
xtd::optional<Match>
find_nearest(const U& target) const
{
auto matches = find_k_nearest(target, 1);
if (matches.empty()) {
return xtd::nullopt;
} else {
return matches[0];
}
}
/**
* Find the nearest element in the tree.
*
* @param target The search target.
* @param limit The maximum distance to a match.
* @return The closest match to @p target within @p limit, or @c nullopt if
* no match is found.
*/
template <typename U>
xtd::optional<Match>
find_nearest_within(const U& target, distance_type limit) const
{
auto matches = find_k_nearest_within(target, 1, limit);
if (matches.empty()) {
return xtd::nullopt;
} else {
return matches[0];
}
}
/**
* Find the @p k nearest elements in the tree.
*
* @param target The search target.
* @param k The maximum number of result to return.
* @return The @p k nearest elements in the tree to @p target.
*/
template <typename U>
std::vector<Match>
find_k_nearest(const U& target, size_type k) const
{
std::priority_queue<Match> matches;
distance_type tau{};
SearchStack stack;
stack.emplace_back(m_nodes.begin(), m_nodes.end(), 0, 0);
while (!stack.empty()) {
auto entry = stack.back();
stack.pop_back();
if (entry.first == entry.last || (matches.size() == k && entry.a > entry.b + tau)) {
continue;
}
auto root = entry.first;
auto distance = m_metric(root->element, target);
if (matches.size() < k || distance <= tau) {
if (matches.size() == k) {
matches.pop();
}
matches.push(Match(root, distance));
tau = matches.top().distance();
}
auto left = root + 1;
auto right = entry.last;
if (left == right) {
continue;
}
auto mid = left + root->left_size;
auto radius = root->radius;
if (distance < radius) {
stack.emplace_back(mid, right, radius, distance);
stack.emplace_back(left, mid, distance, radius);
} else {
stack.emplace_back(left, mid, distance, radius);
stack.emplace_back(mid, right, radius, distance);
}
}
auto i = matches.size();
std::vector<Match> result{i};
while (!matches.empty()) {
result[--i] = matches.top();
matches.pop();
}
return result;
}
/**
* Find the @p k nearest elements in the tree.
*
* @param target The search target.
* @param k The maximum number of result to return.
* @param limit The maximum distance to a match.
* @return The @p k nearest elements in the tree to @p target within @p limit.
*/
template <typename U>
std::vector<Match>
find_k_nearest_within(const U& target, size_type k, distance_type limit) const
{
std::priority_queue<Match> matches;
distance_type tau = limit;
SearchStack stack;
stack.emplace_back(m_nodes.begin(), m_nodes.end(), 0, 0);
while (!stack.empty()) {
auto entry = stack.back();
stack.pop_back();
if (entry.first == entry.last || entry.a > entry.b + tau) {
continue;
}
auto root = entry.first;
auto distance = m_metric(root->element, target);
if (distance <= tau) {
if (matches.size() == k) {
matches.pop();
}
matches.push(Match(root, distance));
if (matches.size() == k) {
tau = matches.top().distance();
}
}
auto left = root + 1;
auto right = entry.last;
if (left == right) {
continue;
}
auto mid = left + root->left_size;
auto radius = root->radius;
if (distance < radius) {
stack.emplace_back(mid, right, radius, distance);
stack.emplace_back(left, mid, distance, radius);
} else {
stack.emplace_back(left, mid, distance, radius);
stack.emplace_back(mid, right, radius, distance);
}
}
auto i = matches.size();
std::vector<Match> result{i};
while (!matches.empty()) {
result[--i] = matches.top();
matches.pop();
}
return result;
}
private:
NodeVector m_nodes;
Metric m_metric;
void
build_tree()
{
using iterator = typename NodeVector::iterator;
using SubRange = std::pair<iterator, iterator>;
std::vector<SubRange> stack;
stack.emplace_back(m_nodes.begin(), m_nodes.end());
while (!stack.empty()) {
auto range = stack.back();
stack.pop_back();
if (range.second - range.first <= 1) {
continue;
}
auto root = range.first;
auto begin = root + 1;
auto end = range.second;
auto mid = begin + (end - begin)/2;
auto compare = [=] (const Node& a, const Node& b) {
return m_metric(root->element, a.element) < m_metric(root->element, b.element);
};
std::nth_element(begin, mid, end, compare);
root->radius = m_metric(root->element, mid->element);
root->left_size = mid - begin;
stack.emplace_back(mid, end);
stack.emplace_back(begin, mid);
}
}
};
}
#endif // MALUUBA_VPTREE_HPP
| 24.61157 | 92 | 0.566935 | [
"vector"
] |
8267674abddbff631b575c9bac80ddbd5b937f08 | 3,597 | cpp | C++ | src/racer/iobbpln.cpp | 3dhater/Racer | d7fe4014b1efefe981528547649dc397da7fa780 | [
"Unlicense"
] | null | null | null | src/racer/iobbpln.cpp | 3dhater/Racer | d7fe4014b1efefe981528547649dc397da7fa780 | [
"Unlicense"
] | null | null | null | src/racer/iobbpln.cpp | 3dhater/Racer | d7fe4014b1efefe981528547649dc397da7fa780 | [
"Unlicense"
] | 1 | 2021-01-03T16:16:47.000Z | 2021-01-03T16:16:47.000Z | /*
* D3 - intersection of plane and OBB
* 23-11-01: Created!
* NOTES:
* - Pseudocode from the book Real-Time Rendering (Moller/Haines), pp. 311-312.
* (C) MarketGraph/RvG
*/
#include <d3/d3.h>
#include <qlib/debug.h>
#pragma hdrstop
#include <d3/intersect.h>
DEBUG_ENABLE
// Method #1 is to transform the plane's normal, and then do an AABB-plane
// test instead. Bugs: some offset need to be negated or something. It's
// close, but actually reverses some numbers, so the answers are not yet right.
//#define USE_TRANSFORMED_NORMAL
// Method #2 is to calculate the radius of the OBB and check the OBB's
// center distance to the plane and see if it's greater than this radius.
#define USE_RADIUS
dfloat d3FindOBBPlaneIntersection(const DOBB *obb,const DPlane3 *plane,
DVector3 *point)
// Finds the intersection of an OBB (oriented bounding box) and a plane.
// Returns the penetration depth, or 0 if no penetration is present.
// Returns contact point in 'point'. Addmitedly, the point is very crude
// at this point though and may be of limited use.
// Assumes the plane's normal is normalized (!).
{
//qdbg("d3FindOBBPlaneIntersection()\n");
//plane->DbgPrint("plane");
//obb->DbgPrint("obb");
#ifdef USE_RADIUS
dfloat r,d;
// Calculate the radius of the OBB
r=fabs(obb->extents.x*plane->n.Dot(&obb->axis[0]))+
fabs(obb->extents.y*plane->n.Dot(&obb->axis[1]))+
fabs(obb->extents.z*plane->n.Dot(&obb->axis[2]));
// Now check how far the center is distantiated from the plane
d=fabs(obb->center.Dot(plane->n)+plane->d);
//qdbg("OBB r=%f, distance to plane=%f\n",r,d);
if(d>r)
{
// No intersection
return 0;
} else
{
// Return penetration depth
//qdbg(" pen=%.4f\n",r-d);
return r-d;
}
#endif
#ifdef USE_TRANSFORMED_NORMAL
DVector3 n,vMin,vMax,bMin,bMax;
dfloat pen;
// Transform the plane's normal so that we can simplify the test
// to an AABB-plane intersection.
n.x=plane->n.Dot(&obb->axis[0]);
n.y=plane->n.Dot(&obb->axis[1]);
n.z=plane->n.Dot(&obb->axis[2]);
n.DbgPrint("n'");
// Create min/max vertex of the OBB
bMin.x=obb->center.x-obb->extents.x;
bMin.y=obb->center.y-obb->extents.y;
bMin.z=obb->center.z-obb->extents.z;
bMax.x=obb->center.x+obb->extents.x;
bMax.y=obb->center.y+obb->extents.y;
bMax.z=obb->center.z+obb->extents.z;
// Find the closest and farthest points of the OBB wrt the plane
if(n.x>=0){ vMin.x=bMin.x; vMax.x=bMax.x; }
else { vMin.x=bMax.x; vMax.x=bMin.x; }
if(n.y>=0){ vMin.y=bMin.y; vMax.y=bMax.y; }
else { vMin.y=bMax.y; vMax.y=bMin.y; }
if(n.z>=0){ vMin.z=bMin.z; vMax.z=bMax.z; }
else { vMin.z=bMax.z; vMax.z=bMin.z; }
bMin.DbgPrint("bMin");
bMax.DbgPrint("bMax");
vMin.DbgPrint("vMin");
vMax.DbgPrint("vMax");
qdbg("vMin dot = %f\n",n.Dot(&vMin)+plane->d);
// If the minimum point is in front of the plane, no overlap takes place.
if((n.Dot(&vMin)+plane->d)>0)
return 0;
// If the maximum point is at the back of the plane, the box intersects
// the plane.
pen=n.Dot(&vMax)+plane->d;
qdbg(" pen=%.2f\n",pen);
if(pen>=0)
{
// Overlap; calculate penetration depth
n.Normalize();
pen=n.Dot(&vMax)+plane->d;
qdbg("OBB-Plane; penetration depth=%.2f\n",pen);
return pen;
}
// Otherwise both points are on the same side of the plane and don't
// intersect. Note that you may STILL want to detect this; i.e. a very
// fast traveling suddenly jumping through a plane (of a triangle) and
// suddenly being totally behind the triangle's plane. However, that
// can be tricky.
return 0;
#endif
}
| 30.74359 | 79 | 0.666945 | [
"transform"
] |
82686c76fbe40f5c7961e04f653f41dfe069b5c9 | 1,987 | cpp | C++ | oneflow/core/operator/tick_op.cpp | L-Net-1992/oneflow | 4dc08d65caea36fdd137841ac95551218897e730 | [
"Apache-2.0"
] | 1 | 2022-03-14T11:17:56.000Z | 2022-03-14T11:17:56.000Z | oneflow/core/operator/tick_op.cpp | L-Net-1992/oneflow | 4dc08d65caea36fdd137841ac95551218897e730 | [
"Apache-2.0"
] | null | null | null | oneflow/core/operator/tick_op.cpp | L-Net-1992/oneflow | 4dc08d65caea36fdd137841ac95551218897e730 | [
"Apache-2.0"
] | 1 | 2021-12-15T02:14:49.000Z | 2021-12-15T02:14:49.000Z | /*
Copyright 2020 The OneFlow 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 "oneflow/core/operator/tick_op.h"
#include "oneflow/core/job/sbp_signature_builder.h"
namespace oneflow {
namespace {
Maybe<void> InferBlobDescs(const std::function<BlobDesc*(const std::string&)>& BlobDesc4BnInOp) {
BlobDesc* blob_desc = BlobDesc4BnInOp("out");
blob_desc->mut_shape() = Shape({1});
blob_desc->set_data_type(DataType::kInt8);
return Maybe<void>::Ok();
}
} // namespace
Maybe<void> TickOp::InitFromOpConf() {
CHECK(op_conf().has_tick_conf());
EnrollRepeatedInputBn("tick", false);
EnrollOutputBn("out", false);
return Maybe<void>::Ok();
}
Maybe<void> TickOp::InferLogicalOutBlobDescs(
const std::function<BlobDesc*(const std::string&)>& BlobDesc4BnInOp,
const ParallelDesc& parallel_desc) const {
return InferBlobDescs(BlobDesc4BnInOp);
}
Maybe<void> TickOp::InferOutBlobDescs(
const std::function<BlobDesc*(const std::string&)>& GetBlobDesc4BnInOp,
const ParallelContext* parallel_ctx) const {
return InferBlobDescs(GetBlobDesc4BnInOp);
}
Maybe<void> TickOp::GetSbpSignatures(
const std::function<Maybe<const BlobDesc&>(const std::string&)>& LogicalBlobDesc4Ibn,
SbpSignatureList* sbp_sig_list) const {
return Maybe<void>::Ok();
}
REGISTER_OP_SAME_OUTPUT_BLOB_REGST_NUM(OperatorConf::kTickConf, 2);
REGISTER_OP(OperatorConf::kTickConf, TickOp);
REGISTER_TICK_TOCK_OP(OperatorConf::kTickConf);
} // namespace oneflow
| 32.048387 | 97 | 0.761449 | [
"shape"
] |
826d10c55c189b7e164d772b06ce82b58c6524ed | 8,520 | cpp | C++ | applications/blas/l1_fused_dot.cpp | ExternalRepositories/universal | 3635a092d3cedd05a965f8154f147f450193be6b | [
"MIT"
] | 254 | 2017-05-24T16:51:57.000Z | 2022-03-22T13:07:29.000Z | applications/blas/l1_fused_dot.cpp | jamesquinlan/universal | 3b7e6bf37cbb9123425b634d18af18a409c2eccc | [
"MIT"
] | 101 | 2017-11-09T22:57:24.000Z | 2022-03-17T12:44:59.000Z | applications/blas/l1_fused_dot.cpp | jamesquinlan/universal | 3b7e6bf37cbb9123425b634d18af18a409c2eccc | [
"MIT"
] | 55 | 2017-06-09T10:04:38.000Z | 2022-02-01T16:54:56.000Z | // l1_fused_dot.cpp: example program showing a fused-dot product for error free linear algebra
//
// Copyright (C) 2017-2021 Stillwater Supercomputing, Inc.
//
// This file is part of the universal numbers project, which is released under an MIT Open Source license.
#ifdef _MSC_VER
#pragma warning(disable : 4514) // warning C4514: 'std::complex<float>::complex': unreferenced inline function has been removed
#pragma warning(disable : 4571) // warning C4571: Informational: catch(...) semantics changed since Visual C++ 7.1; structured exceptions (SEH) are no longer caught
#pragma warning(disable : 4625) // warning C4625: 'std::moneypunct<char,true>': copy constructor was implicitly defined as deleted
#pragma warning(disable : 4626) // warning C4626: 'std::codecvt_base': assignment operator was implicitly defined as deleted
#pragma warning(disable : 4710) // warning C4710: 'int swprintf_s(wchar_t *const ,const size_t,const wchar_t *const ,...)': function not inlined
#pragma warning(disable : 4774) // warning C4774: 'sprintf_s' : format string expected in argument 3 is not a string literal
#pragma warning(disable : 4820) // warning C4820: 'std::_Mpunct<_Elem>': '4' bytes padding added after data member 'std::_Mpunct<_Elem>::_Kseparator'
#pragma warning(disable : 5026) // warning C5026 : 'std::_Generic_error_category' : move constructor was implicitly defined as deleted
#pragma warning(disable : 5027) // warning C5027 : 'std::_Generic_error_category' : move assignment operator was implicitly defined as deleted
#pragma warning(disable : 5045) // warning C5045: Compiler will insert Spectre mitigation for memory load if /Qspectre switch specified
#endif
// enable the following define to show the intermediate steps in the fused-dot product
// #define POSIT_VERBOSE_OUTPUT
#define POSIT_TRACE_MUL
#define QUIRE_TRACE_ADD
// configure posit environment using fast posits
#define POSIT_FAST_POSIT_8_0 1
#define POSIT_FAST_POSIT_16_1 1
#define POSIT_FAST_POSIT_32_2 1
#define POSIT_FAST_POSIT_64_3 0 // TODO
// enable posit arithmetic exceptions
#define POSIT_THROW_ARITHMETIC_EXCEPTION 1
#include <universal/number/posit/posit.hpp>
#include <universal/blas/blas.hpp>
template<typename Vector>
void PrintProducts(const Vector& a, const Vector& b) {
constexpr size_t nbits = Vector::value_type::nbits;
constexpr size_t es = Vector::value_type::es;
sw::universal::quire<nbits, es> q(0);
for (size_t i = 0; i < a.size(); ++i) {
q += sw::universal::quire_mul(a[i], b[i]);
std::cout << a[i] << " * " << b[i] << " = " << a[i] * b[i] << std::endl << "quire " << q << std::endl;
}
typename Vector::value_type sum;
sw::universal::convert(q.to_value(), sum); // one and only rounding step of the fused-dot product
std::cout << "fdp result " << sum << std::endl;
}
template<typename ResultScalar, typename RefScalar>
void reportOnCatastrophicCancellation(const std::string& type, const ResultScalar& v, const RefScalar& ref) {
constexpr size_t COLUMN_WIDTH = 15;
std::cout << type << std::setw(COLUMN_WIDTH) << v << (v == ref ? " <----- PASS" : " <----- FAIL") << '\n';
}
int main(int argc, char** argv)
try {
using namespace sw::universal;
if (argc == 1) std::cout << argv[0] << '\n';
// generate an interesting vector x with 0.5 ULP round-off errors in each product
// that the fused-dot product will be able to resolve
// by progressively adding smaller values, a regular dot product loses these bits due to canceleation.
// but a fused dot product leveraging a quire will be able to resolve these.
//float eps = std::numeric_limits<float>::epsilon();
//float epsminus = 1.0f - eps;
//float epsplus = 1.0f + eps;
std::streamsize prec = std::cout.precision();
std::cout << std::setprecision(17);
{
using Scalar = float;
using Vector = sw::universal::blas::vector<Scalar>;
Scalar a1 = 3.2e8, a2 = 1, a3 = -1, a4 = 8e7;
Scalar b1 = 4.0e7, b2 = 1, b3 = -1, b4 = -1.6e8;
Vector a = { a1, a2, a3, a4 };
Vector b = { b1, b2, b3, b4 };
std::cout << "a: " << a << '\n';
std::cout << "b: " << b << '\n';
std::cout << "\n\n";
reportOnCatastrophicCancellation("IEEE float BLAS dot(x,y) : ", dot(a,b), 2);
}
{
using Scalar = double;
using Vector = sw::universal::blas::vector<Scalar>;
Scalar a1 = 3.2e8, a2 = 1, a3 = -1, a4 = 8e7;
Scalar b1 = 4.0e7, b2 = 1, b3 = -1, b4 = -1.6e8;
Vector a = { a1, a2, a3, a4 };
Vector b = { b1, b2, b3, b4 };
reportOnCatastrophicCancellation("IEEE double BLAS dot(x,y) : ", dot(a, b), 2);
}
{
// a little verbose but enabling different precisions to be injected
// float, double, long double
// so that you can convince yourself that this is a property of posits and quires
// and not some input precision shenanigans. The magic is all in the quire
// accumulating UNROUNDED multiplies: that gives you in affect double the
// fraction bits.
using Real = float;
Real a1 = 3.2e8, a2 = 1, a3 = -1, a4 = 8e7;
Real b1 = 4.0e7, b2 = 1, b3 = -1, b4 = -1.6e8;
#ifdef LATER
{
using Scalar = posit<8, 0>;
vector<Scalar> x = { a1, a2, a3, a4 };
vector<Scalar> y = { b1, b2, b3, b4 };
reportOnCatastrophicCancellation("posit< 8,0> fused dot(x,y) : ", fdp(x, y), 2);
}
{
using Scalar = posit<8, 2>;
vector<Scalar> x = { a1, a2, a3, a4 };
vector<Scalar> y = { b1, b2, b3, b4 };
reportOnCatastrophicCancellation("posit< 8,2> fused dot(x,y) : ", fdp(x, y), 2);
}
{
using Scalar = posit<8, 3>;
vector<Scalar> x = { a1, a2, a3, a4 };
vector<Scalar> y = { b1, b2, b3, b4 };
reportOnCatastrophicCancellation("posit< 8,3> fused dot(x,y) : ", fdp(x, y), 2);
}
#endif
{
using Scalar = posit<16, 1>;
std::vector<Scalar> x = { a1, a2, a3, a4 };
std::vector<Scalar> y = { b1, b2, b3, b4 };
reportOnCatastrophicCancellation("posit<16,1> fused dot(x,y) : " , fdp(x, y), 2);
}
{
using Scalar = posit<16, 2>;
std::vector<Scalar> x = { a1, a2, a3, a4 };
std::vector<Scalar> y = { b1, b2, b3, b4 };
reportOnCatastrophicCancellation("posit<16,2> fused dot(x,y) : ", fdp(x, y), 2);
}
{
using Scalar = posit<32, 2>;
std::vector<Scalar> x = { a1, a2, a3, a4 };
std::vector<Scalar> y = { b1, b2, b3, b4 };
reportOnCatastrophicCancellation("posit<32,2> fused dot(x,y) : ", fdp(x, y), 2);
//PrintProducts(x, y);
}
{
using Scalar = posit<64, 1>;
std::vector<Scalar> x = { a1, a2, a3, a4 };
std::vector<Scalar> y = { b1, b2, b3, b4 };
reportOnCatastrophicCancellation("posit<64,1> fused dot(x,y) : ", fdp(x, y), 2);
}
{
using Scalar = posit<64, 0>;
std::vector<Scalar> x = { a1, a2, a3, a4 };
std::vector<Scalar> y = { b1, b2, b3, b4 };
reportOnCatastrophicCancellation("posit<64,0> fused dot(x,y) : ", fdp(x, y), 2);
}
{
using Scalar = posit<32, 1>;
std::vector<Scalar> x = { a1, a2, a3, a4 };
std::vector<Scalar> y = { b1, b2, b3, b4 };
reportOnCatastrophicCancellation("posit<32,1> fused dot(x,y) : ", fdp(x, y), 2);
std::cout << "Reason why posit<32,1> fails\n";
PrintProducts(x, y);
std::cout << "Cannot represent integer value " << a1 << " != " << x[0] << '\n';
// std::cout << "Cannot represent integer value " << b1 << " != " << y[0] << endl;
std::cout << "Product is " << a1*b1 << " but quire_mul approximation yields " << quire_mul(x[0],y[0]) << '\n';
std::cout << "Cannot represent integer value " << a4 << " != " << x[3] << '\n';
std::cout << "Cannot represent integer value " << b4 << " != " << y[3] << '\n';
std::cout << "Product is " << a4*b4 << " but quire_mul approximation yields " << quire_mul(x[3],y[3]) << '\n';
}
std::cout << std::setprecision(prec);
}
return EXIT_SUCCESS;
}
catch (char const* msg) {
std::cerr << "Caught exception: " << msg << std::endl;
return EXIT_FAILURE;
}
catch (const sw::universal::posit_arithmetic_exception& err) {
std::cerr << "Uncaught posit arithmetic exception: " << err.what() << std::endl;
return EXIT_FAILURE;
}
catch (const sw::universal::quire_exception& err) {
std::cerr << "Uncaught quire exception: " << err.what() << std::endl;
return EXIT_FAILURE;
}
catch (const sw::universal::posit_internal_exception& err) {
std::cerr << "Uncaught posit internal exception: " << err.what() << std::endl;
return EXIT_FAILURE;
}
catch (const std::runtime_error& err) {
std::cerr << "Uncaught runtime exception: " << err.what() << std::endl;
return EXIT_FAILURE;
}
catch (...) {
std::cerr << "Caught unknown exception" << std::endl;
return EXIT_FAILURE;
}
| 39.813084 | 164 | 0.646948 | [
"vector"
] |
82736c11588916b6f48b854846d396f9dcfb6f94 | 11,146 | hpp | C++ | VulkanAPI/Project1/VulkanModel.hpp | moothyknight/Vulkan-Compute-Example | 1c8ccba1abd893212148a9f848496dddde90e1ab | [
"MIT"
] | 4 | 2019-06-21T18:46:55.000Z | 2021-12-17T08:26:30.000Z | VulkanAPI/Project1/VulkanModel.hpp | moothyknight/Vulkan-Compute-Example | 1c8ccba1abd893212148a9f848496dddde90e1ab | [
"MIT"
] | null | null | null | VulkanAPI/Project1/VulkanModel.hpp | moothyknight/Vulkan-Compute-Example | 1c8ccba1abd893212148a9f848496dddde90e1ab | [
"MIT"
] | null | null | null | /*
* Vulkan Model loader using ASSIMP
*
* Copyright(C) 2016-2017 by Sascha Willems - www.saschawillems.de
*
* This code is licensed under the MIT license(MIT) (http://opensource.org/licenses/MIT)
*/
#pragma once
#include <stdlib.h>
#include <string>
#include <fstream>
#include <vector>
#include "vulkan/vulkan.h"
#include <assimp/Importer.hpp>
#include <assimp/scene.h>
#include <assimp/postprocess.h>
#include <assimp/cimport.h>
#include <glm/glm.hpp>
#include <glm/gtc/matrix_transform.hpp>
#include <glm/gtc/type_ptr.hpp>
#include "VulkanDevice.hpp"
#include "VulkanBuffer.hpp"
namespace vks
{
/** @brief Vertex layout components */
typedef enum Component {
VERTEX_COMPONENT_POSITION = 0x0,
VERTEX_COMPONENT_NORMAL = 0x1,
VERTEX_COMPONENT_COLOR = 0x2,
VERTEX_COMPONENT_UV = 0x3,
VERTEX_COMPONENT_TANGENT = 0x4,
VERTEX_COMPONENT_BITANGENT = 0x5,
VERTEX_COMPONENT_DUMMY_FLOAT = 0x6,
VERTEX_COMPONENT_DUMMY_VEC4 = 0x7
} Component;
/** @brief Stores vertex layout components for model loading and Vulkan vertex input and atribute bindings */
struct VertexLayout {
public:
/** @brief Components used to generate vertices from */
std::vector<Component> components;
VertexLayout(std::vector<Component> components)
{
this->components = std::move(components);
}
uint32_t stride()
{
uint32_t res = 0;
for (auto& component : components)
{
switch (component)
{
case VERTEX_COMPONENT_UV:
res += 2 * sizeof(float);
break;
case VERTEX_COMPONENT_DUMMY_FLOAT:
res += sizeof(float);
break;
case VERTEX_COMPONENT_DUMMY_VEC4:
res += 4 * sizeof(float);
break;
default:
// All components except the ones listed above are made up of 3 floats
res += 3 * sizeof(float);
}
}
return res;
}
};
/** @brief Used to parametrize model loading */
struct ModelCreateInfo {
glm::vec3 center;
glm::vec3 scale;
glm::vec2 uvscale;
ModelCreateInfo() {};
ModelCreateInfo(glm::vec3 scale, glm::vec2 uvscale, glm::vec3 center)
{
this->center = center;
this->scale = scale;
this->uvscale = uvscale;
}
ModelCreateInfo(float scale, float uvscale, float center)
{
this->center = glm::vec3(center);
this->scale = glm::vec3(scale);
this->uvscale = glm::vec2(uvscale);
}
};
struct Model {
VkDevice device = nullptr;
vks::Buffer vertices;
vks::Buffer indices;
uint32_t indexCount = 0;
uint32_t vertexCount = 0;
/** @brief Stores vertex and index base and counts for each part of a model */
struct ModelPart {
uint32_t vertexBase;
uint32_t vertexCount;
uint32_t indexBase;
uint32_t indexCount;
};
std::vector<ModelPart> parts;
static const int defaultFlags = aiProcess_FlipWindingOrder | aiProcess_Triangulate | aiProcess_PreTransformVertices | aiProcess_CalcTangentSpace | aiProcess_GenSmoothNormals;
struct Dimension
{
glm::vec3 min = glm::vec3(FLT_MAX);
glm::vec3 max = glm::vec3(-FLT_MAX);
glm::vec3 size;
} dim;
/** @brief Release all Vulkan resources of this model */
void destroy()
{
assert(device);
vkDestroyBuffer(device, vertices.buffer, nullptr);
vkFreeMemory(device, vertices.memory, nullptr);
if (indices.buffer != VK_NULL_HANDLE)
{
vkDestroyBuffer(device, indices.buffer, nullptr);
vkFreeMemory(device, indices.memory, nullptr);
}
}
/**
* Loads a 3D model from a file into Vulkan buffers
*
* @param device Pointer to the Vulkan device used to generated the vertex and index buffers on
* @param filename File to load (must be a model format supported by ASSIMP)
* @param layout Vertex layout components (position, normals, tangents, etc.)
* @param createInfo MeshCreateInfo structure for load time settings like scale, center, etc.
* @param copyQueue Queue used for the memory staging copy commands (must support transfer)
* @param (Optional) flags ASSIMP model loading flags
*/
bool loadFromFile(const std::string& filename, vks::VertexLayout layout, vks::ModelCreateInfo *createInfo, vks::VulkanDevice *device, VkQueue copyQueue, const int flags = defaultFlags)
{
this->device = device->logicalDevice;
Assimp::Importer Importer;
const aiScene* pScene;
// Load file
pScene = Importer.ReadFile(filename.c_str(), flags);
if (pScene)
{
parts.clear();
parts.resize(pScene->mNumMeshes);
glm::vec3 scale(1.0f);
glm::vec2 uvscale(1.0f);
glm::vec3 center(0.0f);
if (createInfo)
{
scale = createInfo->scale;
uvscale = createInfo->uvscale;
center = createInfo->center;
}
std::vector<float> vertexBuffer;
std::vector<uint32_t> indexBuffer;
vertexCount = 0;
indexCount = 0;
// Load meshes
for (unsigned int i = 0; i < pScene->mNumMeshes; i++)
{
const aiMesh* paiMesh = pScene->mMeshes[i];
parts[i] = {};
parts[i].vertexBase = vertexCount;
parts[i].indexBase = indexCount;
vertexCount += pScene->mMeshes[i]->mNumVertices;
aiColor3D pColor(0.f, 0.f, 0.f);
pScene->mMaterials[paiMesh->mMaterialIndex]->Get(AI_MATKEY_COLOR_DIFFUSE, pColor);
const aiVector3D Zero3D(0.0f, 0.0f, 0.0f);
for (unsigned int j = 0; j < paiMesh->mNumVertices; j++)
{
const aiVector3D* pPos = &(paiMesh->mVertices[j]);
const aiVector3D* pNormal = &(paiMesh->mNormals[j]);
const aiVector3D* pTexCoord = (paiMesh->HasTextureCoords(0)) ? &(paiMesh->mTextureCoords[0][j]) : &Zero3D;
const aiVector3D* pTangent = (paiMesh->HasTangentsAndBitangents()) ? &(paiMesh->mTangents[j]) : &Zero3D;
const aiVector3D* pBiTangent = (paiMesh->HasTangentsAndBitangents()) ? &(paiMesh->mBitangents[j]) : &Zero3D;
for (auto& component : layout.components)
{
switch (component) {
case VERTEX_COMPONENT_POSITION:
vertexBuffer.push_back(pPos->x * scale.x + center.x);
vertexBuffer.push_back(-pPos->y * scale.y + center.y);
vertexBuffer.push_back(pPos->z * scale.z + center.z);
break;
case VERTEX_COMPONENT_NORMAL:
vertexBuffer.push_back(pNormal->x);
vertexBuffer.push_back(-pNormal->y);
vertexBuffer.push_back(pNormal->z);
break;
case VERTEX_COMPONENT_UV:
vertexBuffer.push_back(pTexCoord->x * uvscale.s);
vertexBuffer.push_back(pTexCoord->y * uvscale.t);
break;
case VERTEX_COMPONENT_COLOR:
vertexBuffer.push_back(pColor.r);
vertexBuffer.push_back(pColor.g);
vertexBuffer.push_back(pColor.b);
break;
case VERTEX_COMPONENT_TANGENT:
vertexBuffer.push_back(pTangent->x);
vertexBuffer.push_back(pTangent->y);
vertexBuffer.push_back(pTangent->z);
break;
case VERTEX_COMPONENT_BITANGENT:
vertexBuffer.push_back(pBiTangent->x);
vertexBuffer.push_back(pBiTangent->y);
vertexBuffer.push_back(pBiTangent->z);
break;
// Dummy components for padding
case VERTEX_COMPONENT_DUMMY_FLOAT:
vertexBuffer.push_back(0.0f);
break;
case VERTEX_COMPONENT_DUMMY_VEC4:
vertexBuffer.push_back(0.0f);
vertexBuffer.push_back(0.0f);
vertexBuffer.push_back(0.0f);
vertexBuffer.push_back(0.0f);
break;
};
}
dim.max.x = fmax(pPos->x, dim.max.x);
dim.max.y = fmax(pPos->y, dim.max.y);
dim.max.z = fmax(pPos->z, dim.max.z);
dim.min.x = fmin(pPos->x, dim.min.x);
dim.min.y = fmin(pPos->y, dim.min.y);
dim.min.z = fmin(pPos->z, dim.min.z);
}
dim.size = dim.max - dim.min;
parts[i].vertexCount = paiMesh->mNumVertices;
uint32_t indexBase = static_cast<uint32_t>(indexBuffer.size());
for (unsigned int j = 0; j < paiMesh->mNumFaces; j++)
{
const aiFace& Face = paiMesh->mFaces[j];
if (Face.mNumIndices != 3)
continue;
indexBuffer.push_back(indexBase + Face.mIndices[0]);
indexBuffer.push_back(indexBase + Face.mIndices[1]);
indexBuffer.push_back(indexBase + Face.mIndices[2]);
parts[i].indexCount += 3;
indexCount += 3;
}
}
uint32_t vBufferSize = static_cast<uint32_t>(vertexBuffer.size()) * sizeof(float);
uint32_t iBufferSize = static_cast<uint32_t>(indexBuffer.size()) * sizeof(uint32_t);
// Use staging buffer to move vertex and index buffer to device local memory
// Create staging buffers
vks::Buffer vertexStaging, indexStaging;
// Vertex buffer
VK_CHECK_RESULT(device->createBuffer(
VK_BUFFER_USAGE_TRANSFER_SRC_BIT,
VK_MEMORY_PROPERTY_HOST_VISIBLE_BIT,
&vertexStaging,
vBufferSize,
vertexBuffer.data()));
// Index buffer
VK_CHECK_RESULT(device->createBuffer(
VK_BUFFER_USAGE_TRANSFER_SRC_BIT,
VK_MEMORY_PROPERTY_HOST_VISIBLE_BIT,
&indexStaging,
iBufferSize,
indexBuffer.data()));
// Create device local target buffers
// Vertex buffer
VK_CHECK_RESULT(device->createBuffer(
VK_BUFFER_USAGE_VERTEX_BUFFER_BIT | VK_BUFFER_USAGE_TRANSFER_DST_BIT,
VK_MEMORY_PROPERTY_DEVICE_LOCAL_BIT,
&vertices,
vBufferSize));
// Index buffer
VK_CHECK_RESULT(device->createBuffer(
VK_BUFFER_USAGE_INDEX_BUFFER_BIT | VK_BUFFER_USAGE_TRANSFER_DST_BIT,
VK_MEMORY_PROPERTY_DEVICE_LOCAL_BIT,
&indices,
iBufferSize));
// Copy from staging buffers
VkCommandBuffer copyCmd = device->createCommandBuffer(VK_COMMAND_BUFFER_LEVEL_PRIMARY, true);
VkBufferCopy copyRegion{};
copyRegion.size = vertices.size;
vkCmdCopyBuffer(copyCmd, vertexStaging.buffer, vertices.buffer, 1, ©Region);
copyRegion.size = indices.size;
vkCmdCopyBuffer(copyCmd, indexStaging.buffer, indices.buffer, 1, ©Region);
device->flushCommandBuffer(copyCmd, copyQueue);
// Destroy staging resources
vkDestroyBuffer(device->logicalDevice, vertexStaging.buffer, nullptr);
vkFreeMemory(device->logicalDevice, vertexStaging.memory, nullptr);
vkDestroyBuffer(device->logicalDevice, indexStaging.buffer, nullptr);
vkFreeMemory(device->logicalDevice, indexStaging.memory, nullptr);
return true;
}
else
{
printf("Error parsing '%s': '%s'\n", filename.c_str(), Importer.GetErrorString());
return false;
}
};
/**
* Loads a 3D model from a file into Vulkan buffers
*
* @param device Pointer to the Vulkan device used to generated the vertex and index buffers on
* @param filename File to load (must be a model format supported by ASSIMP)
* @param layout Vertex layout components (position, normals, tangents, etc.)
* @param scale Load time scene scale
* @param copyQueue Queue used for the memory staging copy commands (must support transfer)
* @param (Optional) flags ASSIMP model loading flags
*/
bool loadFromFile(const std::string& filename, vks::VertexLayout layout, float scale, vks::VulkanDevice *device, VkQueue copyQueue, const int flags = defaultFlags)
{
vks::ModelCreateInfo modelCreateInfo(scale, 1.0f, 0.0f);
return loadFromFile(filename, layout, &modelCreateInfo, device, copyQueue, flags);
}
};
}; | 30.453552 | 186 | 0.684102 | [
"vector",
"model",
"3d"
] |
8279d8710489db0f40d2563d227bf9c2081396e9 | 8,411 | cpp | C++ | Contrib-Intel/RSD-PSME-RMM/common/agent-framework/src/action/task.cpp | opencomputeproject/Rack-Manager | e1a61d3eeeba0ff655fe9c1301e8b510d9b2122a | [
"MIT"
] | 5 | 2019-11-11T07:57:26.000Z | 2022-03-28T08:26:53.000Z | Contrib-Intel/RSD-PSME-RMM/common/agent-framework/src/action/task.cpp | opencomputeproject/Rack-Manager | e1a61d3eeeba0ff655fe9c1301e8b510d9b2122a | [
"MIT"
] | 3 | 2019-09-05T21:47:07.000Z | 2019-09-17T18:10:45.000Z | Contrib-Intel/RSD-PSME-RMM/common/agent-framework/src/action/task.cpp | opencomputeproject/Rack-Manager | e1a61d3eeeba0ff655fe9c1301e8b510d9b2122a | [
"MIT"
] | 11 | 2019-07-20T00:16:32.000Z | 2022-01-11T14:17:48.000Z | /*!
* @copyright
* Copyright (c) 2016-2019 Intel Corporation
*
* @copyright
* 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
*
* @copyright
* http://www.apache.org/licenses/LICENSE-2.0
*
* @copyright
* 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 task.cpp
* @brief Asynchronous task model class
* */
#include "agent-framework/action/task.hpp"
#include <algorithm>
#include <exception>
using namespace agent_framework::action;
using namespace agent_framework::exceptions;
Task::~Task() {}
void Task::operator()() {
try {
prerun();
run();
run_completion_callbacks();
}
catch (const GamiException& e) {
run_exception_callbacks(e);
run_exception_handlers(e);
}
catch (const std::exception& e) {
auto gami_exception = GamiException(ErrorCode::UNKNOWN_ERROR, e.what());
run_exception_callbacks(gami_exception);
run_exception_handlers(gami_exception);
}
catch (...) {
auto unknown_exception = GamiException(ErrorCode::UNKNOWN_ERROR, "An unknown error occurred during task execution.");
run_exception_callbacks(unknown_exception);
run_exception_handlers(unknown_exception);
}
postrun();
}
void Task::run() {
for (const auto& subtask : m_subtasks) {
subtask();
}
}
void Task::prerun() {
for (const auto& prerun_action : m_prerun_actions) {
prerun_action();
}
}
void Task::postrun() {
for (const auto& postrun_action : m_postrun_actions) {
postrun_action();
}
}
Task& Task::add_subtask(const SubtaskType& subtask) {
m_subtasks.push_back(subtask);
return *this;
}
Task& Task::add_subtask(SubtaskType&& subtask) {
m_subtasks.push_back(std::move(subtask));
return *this;
}
Task& Task::move_subtask(std::size_t old_position, std::size_t new_position) {
if (old_position >= m_subtasks.size() || new_position >= m_subtasks.size()) {
throw std::out_of_range("Cannot move subtask: index out of range");
}
const SubtaskType subtask = m_subtasks[old_position];
m_subtasks.erase(m_subtasks.begin() + old_position);
m_subtasks.insert(m_subtasks.begin() + new_position, subtask);
return *this;
}
Task& Task::move_callback(CallbackType callback_type, std::size_t old_position, std::size_t new_position) {
switch (callback_type) {
case CallbackType::Completion:
move_completion_callback(old_position, new_position);
break;
case CallbackType::Exception:
move_exception_callback(old_position, new_position);
break;
default:
break;
}
return *this;
}
Task& Task::move_prerun_action(std::size_t old_position, std::size_t new_position) {
if (old_position >= m_prerun_actions.size() || new_position >= m_prerun_actions.size()) {
throw std::out_of_range("Cannot move prerun action: index out of range");
}
const PrerunActionType prerun_action = m_prerun_actions[old_position];
m_prerun_actions.erase(m_prerun_actions.begin() + old_position);
m_prerun_actions.insert(m_prerun_actions.begin() + new_position, prerun_action);
return *this;
}
Task& Task::move_postrun_action(std::size_t old_position, std::size_t new_position) {
if (old_position >= m_postrun_actions.size() || new_position >= m_postrun_actions.size()) {
throw std::out_of_range("Cannot move postrun action: index out of range");
}
const PostrunActionType postrun_action = m_postrun_actions[old_position];
m_postrun_actions.erase(m_postrun_actions.begin() + old_position);
m_postrun_actions.insert(m_postrun_actions.begin() + new_position, postrun_action);
return *this;
}
Task& Task::remove_subtask(std::size_t position) {
if (position >= m_subtasks.size()) {
throw std::out_of_range("Cannot delete subtask: index out of range");
}
m_subtasks.erase(m_subtasks.begin() + position);
return *this;
}
Task& Task::remove_callback(CallbackType callback_type, std::size_t position) {
switch (callback_type) {
case CallbackType::Completion:
remove_completion_callback(position);
break;
case CallbackType::Exception:
remove_exception_callback(position);
break;
default:
break;
}
return *this;
}
Task& Task::remove_prerun_action(std::size_t position) {
if (position >= m_prerun_actions.size()) {
throw std::out_of_range("Cannot delte prerun action: index out of rande");
}
m_prerun_actions.erase(m_subtasks.begin() + position);
return *this;
}
Task& Task::remove_postrun_action(std::size_t position) {
if (position >= m_postrun_actions.size()) {
throw std::out_of_range("Cannot delete postrun action: index out of range");
}
m_postrun_actions.erase(m_postrun_actions.begin() + position);
return *this;
}
Task& Task::add_exception_handler(const action::Task::ExceptionHandlerFunctionType& exception_handler) {
m_exception_handlers.push_back(exception_handler);
return *this;
}
Task& Task::add_prerun_action(const PrerunActionType& prerun_action) {
m_prerun_actions.push_back(prerun_action);
return *this;
}
Task& Task::add_postrun_action(const PostrunActionType& postrun_action) {
m_postrun_actions.push_back(postrun_action);
return *this;
}
// Protected functions implementation
Task& Task::add_completion_callback(const CallbackFunctionType& callback) {
m_completion_callbacks.push_back(callback);
return *this;
}
Task& Task::add_exception_callback(const ExceptionCallbackFunctionType& callback) {
m_exception_callbacks.push_back(callback);
return *this;
}
void Task::run_completion_callbacks() {
for (const auto& completion_callback : m_completion_callbacks) {
completion_callback();
}
}
void Task::run_exception_callbacks(const GamiException& e) {
for (const auto& exception_callback : m_exception_callbacks) {
exception_callback(e);
}
}
void Task::run_exception_handlers(const GamiException& e) {
for (const auto& exception_handler : m_exception_handlers) {
exception_handler(e);
}
}
Task& Task::move_completion_callback(std::size_t old_position, std::size_t new_position) {
if (old_position >= m_completion_callbacks.size() || new_position >= m_completion_callbacks.size()) {
throw std::out_of_range("Cannot delete callback: index out of range");
}
CallbackFunctionType completion_callback = m_completion_callbacks[old_position];
m_completion_callbacks.erase(m_completion_callbacks.begin() + old_position);
m_completion_callbacks.insert(m_completion_callbacks.begin() + new_position, completion_callback);
return *this;
}
Task& Task::move_exception_callback(std::size_t old_position, std::size_t new_position) {
if (old_position >= m_exception_callbacks.size() || new_position >= m_exception_callbacks.size()) {
throw std::out_of_range("Cannot delete callback: index out of range");
}
ExceptionCallbackFunctionType exception_callback = m_exception_callbacks[old_position];
m_exception_callbacks.erase(m_exception_callbacks.begin() + old_position);
m_exception_callbacks.insert(m_exception_callbacks.begin() + new_position, exception_callback);
return *this;
}
Task& Task::remove_completion_callback(std::size_t position) {
if (position >= m_completion_callbacks.size()) {
throw std::out_of_range("Cannot delete completion callback: index out of range");
}
m_completion_callbacks.erase(m_completion_callbacks.begin() + position);
return *this;
}
Task& Task::remove_exception_callback(std::size_t position) {
if (position >= m_exception_callbacks.size()) {
throw std::out_of_range("Cannot delete exception callback: index out of range");
}
m_exception_callbacks.erase(m_exception_callbacks.begin() + position);
return *this;
}
| 28.036667 | 125 | 0.707169 | [
"model"
] |
827e2b2152ef7cf71cd0be3c047fb9ab4097d9b2 | 2,236 | cpp | C++ | src/objects/primitive3d.cpp | KSaunders98/simpleEngine | d2bb6f77606dba04c4289125ca3799cc725cb60f | [
"MIT"
] | 1 | 2022-02-17T03:25:14.000Z | 2022-02-17T03:25:14.000Z | src/objects/primitive3d.cpp | KSaunders98/simpleEngine | d2bb6f77606dba04c4289125ca3799cc725cb60f | [
"MIT"
] | null | null | null | src/objects/primitive3d.cpp | KSaunders98/simpleEngine | d2bb6f77606dba04c4289125ca3799cc725cb60f | [
"MIT"
] | null | null | null | #include "objects/primitive3d.hpp"
#include "render_base/exception.hpp"
#include "render_base/shader.hpp"
#include "render_base/window.hpp"
using namespace Render3D;
using namespace Math3D;
void Primitive3D::setSize(const Vector4& value) {
size = value;
}
Vector4 Primitive3D::getSize() const {
return size;
}
void Primitive3D::setCFrame(const Matrix4x4& value) {
cframe = value;
}
Matrix4x4 Primitive3D::getCFrame() const {
return cframe;
}
void Primitive3D::setColor(const Color& value) {
color = value;
}
Color Primitive3D::getColor() const {
return color;
}
void Primitive3D::setShader(Shader* const s) {
shader = s;
if (shader != nullptr) {
modelCFrameVariable = shader->getVariable<Matrix4x4>("modelCFrame");
modelRotationVariable = shader->getVariable<Matrix4x4>("modelRotation");
modelSizeVariable = shader->getVariable<Vector4>("modelSize");
modelColorVariable = shader->getVariable<Color>("modelColor");
} else {
modelCFrameVariable = nullptr;
modelRotationVariable = nullptr;
modelSizeVariable = nullptr;
modelColorVariable = nullptr;
}
}
Shader* const Primitive3D::getShader() const {
return shader;
}
Instance* Primitive3D::newInstance(const Matrix4x4& cfr) {
Instance* newInstance = new Instance(cfr);
instances.push_back(newInstance);
return newInstance;
}
void Primitive3D::deleteInstance(Instance*& instance) {
for (unsigned int i = 0; i < instances.size(); ++i) {
if (instances[i] == instance) {
instances.erase(instances.begin() + i);
delete instance;
instance = nullptr;
return;
}
}
throw Exception("Unable to delete instance from object, instance not found");
}
void Primitive3D::clearInstances() {
for (unsigned int i = 0; i < instances.size(); ++i) {
delete instances[i];
}
instances.clear();
}
void Primitive3D::applyVariables(Window& win) {
Matrix4x4 rotation = cframe.rotation();
modelCFrameVariable->setValue(win, cframe);
modelRotationVariable->setValue(win, rotation);
modelSizeVariable->setValue(win, size);
modelColorVariable->setValue(win, color);
}
| 25.123596 | 81 | 0.674419 | [
"object"
] |
828b0351595bd24a23981186c912c0608955e7bc | 1,708 | cpp | C++ | LockBox.cpp | bfridkis/Plane-Crash-Survival-Game-CPP | 417efd13cb01a5a5e64799fa9f00217fbb7c3a3a | [
"MIT"
] | null | null | null | LockBox.cpp | bfridkis/Plane-Crash-Survival-Game-CPP | 417efd13cb01a5a5e64799fa9f00217fbb7c3a3a | [
"MIT"
] | null | null | null | LockBox.cpp | bfridkis/Plane-Crash-Survival-Game-CPP | 417efd13cb01a5a5e64799fa9f00217fbb7c3a3a | [
"MIT"
] | null | null | null | /*************************************************************
** Program name: LockBox.cpp
** Author: Ben Fridkis
** Date: 6/1/2017
** Description: Defintion of LockBox class member functions.
LockBox is a derived class of the parent class
Item.
**************************************************************/
#include "LockBox.hpp"
/****************************************
Constructor
LockBox constructor to establish an
initial starting coordinates for the
LockBox. Passes xCoord and yCoord parameters
to the base class constructor, and
establishes the Item's name and character.
Passes Player object pointer to the base
class constructor for interchange of Items
between the Space and Player and for
related Player updates.
****************************************/
LockBox::LockBox(int xCoord, int yCoord,
Player* player) :
Item(xCoord, yCoord, player)
{
itemName = "LockBox";
itemChar = 'L';
isPerishable = false;
}
/********************************************************
itemInteract
Function to interact with LockBox (a derived Item) when
in a space environment (as opposed to an item carried
by the player).
*********************************************************/
void LockBox::itemInteract()
{
cout << "\nYou Found a LockBox!\n";
if (thePlayer->getHasKey())
{
cout << "o - open, i - ignore: ";
char userSelection =
InputValidation::oOrIInputValidation();
if (userSelection == 'O')
{
cout << "\nIt's the transmitter! Hallelujah!\n";
thePlayer->setHasTransmitted();
}
}
else
{
cout << "But it's locked and too heavy to pickup.\n";
}
}
| 28.949153 | 64 | 0.5363 | [
"object"
] |
828ea0cbacd6ee7fa4959beb991ca15bd169fd76 | 6,449 | hpp | C++ | PlanetaEngine/src/planeta/core/MetaprogrammingUtility.hpp | CdecPGL/PlanetaEngine | b15d5b13c3b2aee886d3f92d13777f1b12860260 | [
"MIT"
] | null | null | null | PlanetaEngine/src/planeta/core/MetaprogrammingUtility.hpp | CdecPGL/PlanetaEngine | b15d5b13c3b2aee886d3f92d13777f1b12860260 | [
"MIT"
] | 15 | 2018-01-14T14:14:47.000Z | 2018-01-14T15:00:15.000Z | PlanetaEngine/src/planeta/core/MetaprogrammingUtility.hpp | CdecPGL/PlanetaEngine | b15d5b13c3b2aee886d3f92d13777f1b12860260 | [
"MIT"
] | null | null | null | #pragma once
#include <string>
#include <functional>
#include <typeinfo>
#include <iostream>
#include <type_traits>
#include "boost/any.hpp"
#include "boost/call_traits.hpp"
namespace plnt {
namespace mp_util{
struct nil {};
/*ペアを作成*/
template<typename First, typename Rest>
struct Cons {
using first = First;
using rest = Rest;
};
/*リストを作成*/
template<typename TFirst, typename ... TRest>
struct List {
using list = Cons<TFirst, List<TRest...>>;
};
template<>
struct List<void> {
using list = nil;
};
/*リストに処理を行う*/
template<typename List,template<typename>typename Proc>
struct ApplyToList {
using list = Cons<typename Proc<typename List::first>::type,typename ApplyToList<typename List::rest,Proc>::list>;
};
template<template<typename>typename Proc>
struct ApplyToList<nil,Proc> {
using list = nil;
};
/*タイプリストを最適な引数リストに変換*/
template<typename List>
struct ConvertParameterList {
private:
template<typename T>
struct BoostCallTraitsParamTypeWrapper { using type = typename boost::call_traits<T>::param_type; };
public:
using param_list = typename ApplyToList<List, BoostCallTraitsParamTypeWrapper>::list;
};
/*関数の型を表す*/
template<typename ... Params>
struct FunctionType {
template<typename Ret>
using func_type = std::function<Ret(Params...)>;
template<typename Ret>
using func_pointer_type = Ret(*)(Params...);
template<class C, typename Ret>
using mfunc_pointer_type = Ret(C::*)(Params...);
template<typename Ret>
static Ret Call(const func_type<Ret>& func, Params... params) {
return func(params...);
}
};
/*引数リストを展開(FuncType<Params...>に展開する)*/
template<typename ParamList, typename ... Params>
struct ExpandParameterList2 {
using type = typename ExpandParameterList2<typename ParamList::rest, typename ParamList::first, Params...>::type;
};
template<typename ... Params>
struct ExpandParameterList2<nil, Params...> {
using type = FunctionType<Params...>;
};
template<typename ParamList>
struct ExpandParameterList {
using type = typename ExpandParameterList2<typename ParamList::rest, typename ParamList::first>::type;
};
//! 引数を文字列化
template<typename FirstParam, typename ... Params>
std::string ConvertParametersToString(FirstParam fparam, Params... params) {
return std::move(std::string(typeid(FirstParam).name()) + " " + boost::lexical_cast<std::string>(fparam) + "," + ConvertParametersToString(params...));
};
template<typename FirstParam>
std::string ConvertParametersToString(FirstParam fparam) {
return std::move(std::string(typeid(FirstParam).name()) + " " + boost::lexical_cast<std::string>(fparam));
};
//! 引数の型を文字列化
template<typename FirstParam, typename ... Params>
std::string ConvertParameterTypesToString() {
return std::move(std::string(std::typeid(FirstParam).name()) + "," + ConvertParameterTypesToString<Params...>());
};
template<typename FirstParam>
std::string ConvertParameterTypesToString() {
return std::move(std::string(std::typeid(FirstParam).name()));
};
//! 全ての要素First,Rest...が単項述語UnaryPredicateを満たしているか
template<template<class> class UnaryPredicate, typename... Args>
struct AllOf : public std::true_type {};
template<template<class> class UnaryPredicate, typename First, typename... Rest>
struct AllOf<UnaryPredicate, First, Rest...> : public std::conditional_t<UnaryPredicate<First>::value, AllOf<UnaryPredicate, Rest...>, std::false_type> {};
/*template<template<class>class UnaryPredicate>
struct AllOf<UnaryPredicate, void> : public std::true_type{};*/
//! いずれかの要素First,Rest...が単項述語UnaryPredicateを満たしているか
template<template<class> class UnaryPredicate, typename... Args>
struct AnyOf : public std::false_type {};
template<template<class> class UnaryPredicate, typename First, typename... Rest>
struct AnyOf<UnaryPredicate, First, Rest...> : public std::conditional_t<UnaryPredicate<First>::value,std::true_type, AnyOf<UnaryPredicate, Rest...>> {};
//! メンバ関数の引数の数を取得する
template<class C, typename Ret, typename... Args>
constexpr int GetFunctionArgCount(Ret(C::*)(Args...)) {
return sizeof...(Args);
}
//! 関数の引数の数を取得する
template<class C, typename Ret, typename... Args>
constexpr int GetFunctionArgCount(Ret(Args...)) {
return sizeof...(Args);
}
//引数リストからメンバ関数を呼び出す関数と、引数リストから関数を呼び出す関数を取得する関数。コンパイルの確認すらしていないので、エラーになる可能性が高い。
/*template<class C, typename Ret, typename... Args, int N, int IDX, typename... FArgs>
Ret CallMemFuncWithParamArray(std::enable_if_t<!N, C*> cptr, Ret(C::*)(Args...) mpfunc, FArgs... fargs) {
return (cptr->*mpfunc)(fargs...);
}
template<class C, typename Ret, typename FirstArg, typename... RestArgs, int N, int IDX, typename... FArgs>
Ret CallMemFuncWithParamArray(std::enable_if_t<N, C*> cptr, Ret(C::*)(Args...) mpfunc, const std::vector<boost::any>& arg_list, FArgs... fargs) {
return CallMemFuncWithParamArray<C, Ret, RestArgs..., N, IDX + 1, FArgs..., FirstArg>(cptr, mpfunc, arg_list, fargs..., boost::any_cast<FirstArg>(arg_list.at(IDX)));
}
template<class C, typename Ret, typename... Args>
Ret CallMemFuncWithParamArray(C* cptr, Ret(C::*mfunc)(Args...), const std::vector<boost::any>& arg_list) {
return CallMemFuncWithParamArray<C, Ret, Args..., sizeof...(Args), 0>(cptr, mfunc, arg_list);
}
template<class C, typename Ret, typename... Args>
std::function<boost::any(void*, const std::vector<boost::any>&)> GetMemFuncCaller(Ret(C::*mpfunc)(Args...)) {
return [](void* cptr, const std::vector<boost::any>& arg_list) {CallMemFuncWithParamArray(reinterpret_cast<C*>(cptr), mpfunc, arg_list); };*/
//入力ストリームに対応しているかどうかを判断するメタ関数
template<typename T, typename U = void>
struct IsIStreamCompatible : public std::false_type {};
template<typename T>
struct IsIStreamCompatible<T, decltype(std::declval<std::istream&>() >> std::declval<T&>(), std::declval<void>())> : public std::true_type {};
template<typename T>
constexpr bool IsIStreamCompatible_v = IsIStreamCompatible<T>::value;
//出力ストリームに対応しているかどうかを判断するメタ関数
template<typename T, typename U = void>
struct IsOStreamCompatible : public std::false_type {};
template<typename T>
struct IsOStreamCompatible<T, decltype(std::declval<std::ostream&>() << std::declval<T&>(), std::declval<void>())> : public std::true_type {};
template<typename T>
constexpr bool IsOStreamCompatible_v = IsOStreamCompatible<T>::value;
}
}
| 40.559748 | 168 | 0.710033 | [
"vector"
] |
829250f3935fb0df95dd791bcd0d54507d41b8d2 | 4,226 | cpp | C++ | 3rdParty/boost/1.61.0/libs/math/reporting/performance/test_gcd.cpp | mikestaub/arangodb | 1bdf414de29b31bcaf80769a095933f66f8256ce | [
"ICU",
"BSL-1.0",
"Zlib",
"Apache-2.0"
] | 5 | 2017-01-19T09:35:40.000Z | 2021-02-26T07:31:38.000Z | libs/math/reporting/performance/test_gcd.cpp | crystax/android-vendor-boost-1-61-0 | a1f467d25d815dc7613fbee06c632cae423f52ca | [
"BSL-1.0"
] | 1 | 2015-11-09T15:38:28.000Z | 2015-11-12T11:14:58.000Z | libs/math/reporting/performance/test_gcd.cpp | crystax/android-vendor-boost-1-61-0 | a1f467d25d815dc7613fbee06c632cae423f52ca | [
"BSL-1.0"
] | 3 | 2015-11-02T09:37:09.000Z | 2017-05-05T06:38:49.000Z | // Copyright Jeremy Murphy 2016.
// Use, modification and distribution are subject to the
// Boost Software License, Version 1.0. (See accompanying file
// LICENSE_1_0.txt or copy at http://www.boost.org/LICENSE_1_0.txt)
#ifdef _MSC_VER
# pragma warning (disable : 4224)
#endif
#include "../../test/table_type.hpp"
#include "table_helper.hpp"
#include "performance.hpp"
#include <boost/math/common_factor_rt.hpp>
#include <boost/math/special_functions/prime.hpp>
#include <boost/multiprecision/cpp_int.hpp>
#include <boost/random.hpp>
#include <boost/array.hpp>
#include <iostream>
#include <algorithm>
#include <numeric>
#include <string>
#include <tuple>
#include <type_traits>
#include <vector>
#include <functional>
using namespace std;
boost::multiprecision::cpp_int total_sum(0);
template <typename Func, class Table>
double exec_timed_test_foo(Func f, const Table& data, double min_elapsed = 0.5)
{
double t = 0;
unsigned repeats = 1;
typename Table::value_type::first_type sum{0};
stopwatch<boost::chrono::high_resolution_clock> w;
do
{
for(unsigned count = 0; count < repeats; ++count)
{
for(typename Table::size_type n = 0; n < data.size(); ++n)
sum += f(data[n].first, data[n].second);
}
t = boost::chrono::duration_cast<boost::chrono::duration<double>>(w.elapsed()).count();
if(t < min_elapsed)
repeats *= 2;
}
while(t < min_elapsed);
total_sum += sum;
return t / repeats;
}
template <typename T>
struct test_function_template
{
vector<pair<T, T> > const & data;
const char* data_name;
test_function_template(vector<pair<T, T> > const &data, const char* name) : data(data), data_name(name) {}
template <typename Function>
void operator()(pair<Function, string> const &f) const
{
auto result = exec_timed_test_foo(f.first, data);
report_execution_time(result,
string("gcd method comparison with ") + compiler_name() + string(" on ") + platform_name(),
string("gcd<") + data_name + string(">"),
string(f.second) + "\n" + boost_name());
}
};
boost::random::mt19937 rng;
boost::random::uniform_int_distribution<> d_0_6(0, 6);
boost::random::uniform_int_distribution<> d_1_20(1, 20);
template <class T>
T get_random_arg()
{
int n_primes = d_0_6(rng);
switch(n_primes)
{
case 0:
// Generate a power of 2:
return static_cast<T>(1u) << d_1_20(rng);
case 1:
// prime number:
return boost::math::prime(d_1_20(rng) + 3);
}
T result = 1;
for(int i = 0; i < n_primes; ++i)
result *= boost::math::prime(d_1_20(rng) + 3) * boost::math::prime(d_1_20(rng) + 3) * boost::math::prime(d_1_20(rng) + 3) * boost::math::prime(d_1_20(rng) + 3) * boost::math::prime(d_1_20(rng) + 3);
return result;
}
template <class T>
void test_type(const char* name)
{
using namespace boost::math::detail;
typedef T int_type;
std::vector<pair<int_type, int_type> > data, data2;
for(unsigned i = 0; i < 1000; ++i)
{
data.push_back(std::make_pair(get_random_arg<T>(), get_random_arg<T>()));
}
// uncomment and change data to data2 below to test one specific value:
//data2.assign(data.size(), data[1]);
//pair<int_type, int_type> test_data{ 1836311903, 2971215073 }; // 46th and 47th Fibonacci numbers. 47th is prime.
typedef pair< function<int_type(int_type, int_type)>, string> f_test;
array<f_test, 2> test_functions{ { { gcd_binary<int_type>, "gcd_binary" } ,{ gcd_euclidean<int_type>, "gcd_euclidean" } } };
for_each(begin(test_functions), end(test_functions), test_function_template<int_type>(data, name));
}
int main()
{
test_type<unsigned short>("unsigned short");
test_type<unsigned>("unsigned");
test_type<unsigned long>("unsigned long");
test_type<unsigned long long>("unsigned long long");
test_type<boost::multiprecision::uint256_t>("boost::multiprecision::uint256_t");
test_type<boost::multiprecision::uint512_t>("boost::multiprecision::uint512_t");
test_type<boost::multiprecision::uint1024_t>("boost::multiprecision::uint1024_t");
}
| 31.774436 | 204 | 0.658779 | [
"vector"
] |
82987041e11f05f9889743e982671b8c78a0e266 | 826 | cpp | C++ | Codeforces/211/C.cpp | Mindjolt2406/Competitive-Programming | d000d98bf7005ee4fb809bcea2f110e4c4793b80 | [
"MIT"
] | 2 | 2018-12-11T14:37:24.000Z | 2022-01-23T18:11:54.000Z | Codeforces/211/C.cpp | Mindjolt2406/Competitive-Programming | d000d98bf7005ee4fb809bcea2f110e4c4793b80 | [
"MIT"
] | null | null | null | Codeforces/211/C.cpp | Mindjolt2406/Competitive-Programming | d000d98bf7005ee4fb809bcea2f110e4c4793b80 | [
"MIT"
] | null | null | null | #include<bits/stdc++.h>
#define mt make_tuple
#define mp make_pair
#define pu push_back
#define INF 1000000001
#define MOD 1000000007
#define ll long long int
#define ld long double
#define vi vector<int>
#define vll vector<long long int>
#define sc(n) scanf("%d",&n);
#define scll(n) scanf("%lld",&n);
#define scld(n) scanf("%Lf",&n);
#define scr(s) {char temp[1000000];scanf("%s",temp);s = temp;}
using namespace std;
int main()
{
string s;
scr(s);
int n = s.size();
int last2 = 0,last1 = 0;
char last = '0';
string k;
for(int i=0;i<n;i++)
{
if(s[i]==last)
{
if(last1==1 && last2==2) continue;
else if(last1==2) continue;
else {k+=s[i];last1++;}
}
else
{
last = s[i];
last2 = last1;
last1 = 1;
k+=s[i];
}
}
cout<<k<<endl;
return 0;
}
| 18.355556 | 62 | 0.57385 | [
"vector"
] |
82a0b7d6b70aaf889b285a9df0228dc4c571f438 | 1,062 | cc | C++ | leetcode/lru-cache.cc | Waywrong/leetcode-solution | 55115aeab4040f5ff84bdce6ffcfe4a98f879616 | [
"MIT"
] | null | null | null | leetcode/lru-cache.cc | Waywrong/leetcode-solution | 55115aeab4040f5ff84bdce6ffcfe4a98f879616 | [
"MIT"
] | null | null | null | leetcode/lru-cache.cc | Waywrong/leetcode-solution | 55115aeab4040f5ff84bdce6ffcfe4a98f879616 | [
"MIT"
] | null | null | null | // LRU Cache
class LRUCache {
public:
LRUCache(int capacity) {
this->capacity = capacity;
}
int get(int key) {
if (map.find(key) == map.end()) return -1;
int val = map[key]->second;
queue.erase(map[key]);
queue.push_front(make_pair(key, val));
map[key] = queue.begin();
return val;
}
void put(int key, int value) {
if (map.find(key) == map.end()) {
if (queue.size() >= capacity) {
int temp = queue.back().first;
queue.pop_back();
map.erase(temp);
}
}
else
queue.erase(map[key]);
queue.push_front(make_pair(key, value));
map[key] = queue.begin();
}
private:
int capacity;
list<pair<int, int>> queue;
unordered_map<int, list<pair<int, int>>::iterator> map;
};
/**
* Your LRUCache object will be instantiated and called as such:
* LRUCache obj = new LRUCache(capacity);
* int param_1 = obj.get(key);
* obj.put(key,value);
*/
| 24.136364 | 64 | 0.52354 | [
"object"
] |
82a1a0380e79eeb226932c3a5b7dcd713c4d2261 | 2,527 | hpp | C++ | MerdogRT/interpreter/include/namespace.hpp | HttoHu/MerdogUWP | 4d823f1c95b655151f8d972018d6caed33e187ee | [
"MIT"
] | 9 | 2018-03-05T15:07:44.000Z | 2019-12-07T10:15:00.000Z | MerdogRT/interpreter/include/namespace.hpp | HttoHu/MerdogUWP | 4d823f1c95b655151f8d972018d6caed33e187ee | [
"MIT"
] | null | null | null | MerdogRT/interpreter/include/namespace.hpp | HttoHu/MerdogUWP | 4d823f1c95b655151f8d972018d6caed33e187ee | [
"MIT"
] | 1 | 2019-11-14T08:09:19.000Z | 2019-11-14T08:09:19.000Z | /*
MIT License
Copyright (c) 2019 HttoHu
Permission is hereby granted, free of charge, to any person obtaining a copy
of this software and associated documentation files (the "Software"), to deal
in the Software without restriction, including without limitation the rights
to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
copies of the Software, and to permit persons to whom the Software is
furnished to do so, subject to the following conditions:
The above copyright notice and this permission notice shall be included in all
copies or substantial portions of the Software.
THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
SOFTWARE.
*/
#pragma once
#include "expr.hpp"
#include "function.hpp"
#define tsymbol_table root_namespace->sl_table
namespace Mer
{
class Structure;
class SymbolTable;
class Namespace
{
public:
Namespace(Namespace* pare);
Namespace(Namespace* pare,
const std::map<std::string,Namespace*>&cs):parent(pare), children(cs) {}
Namespace *parent;
std::map<std::string, std::pair<Structure*, type_code_index>> structures;
std::map<std::string, Namespace*> children;
std::vector<Namespace*> using_namespaces;
SymbolTable* sl_table = nullptr;
void set_new_func(const std::string & name, FunctionBase * func);
void set_new_var(const std::string &name,size_t type, Mem::Object obj);
Mem::Object find_var(const std::string &name);
~Namespace();
};
// 5-3
/*
Task :
1. Namespace 1.0
*/
extern Namespace *root_namespace;
extern Namespace *this_namespace;
/*
* a class which is aimed to change the value of namespace_var,
* the global variable also called namespace var in merdog, is differnt from local var. At the stage of
* syntax analysis, the local var will convert to a postion, however, global var will created in parser
* stage, so global var always be a object, and the Assign classes don't handle such situation.
*/
namespace Parser
{
Mer::Namespace * _find_namespace_driver(Mer::Namespace *current, const std::string &name);
Namespace *find_namespace(const std::string &name);
}
} | 37.161765 | 104 | 0.749901 | [
"object",
"vector"
] |
82a39e55d70fedc9cf5c817900fb29817aa8bb8c | 1,508 | cpp | C++ | src/renderer/sphere.cpp | danbrakeley/stantz | 58b7ff24fab94accd710092893e7b0c4a0d6897f | [
"MIT"
] | null | null | null | src/renderer/sphere.cpp | danbrakeley/stantz | 58b7ff24fab94accd710092893e7b0c4a0d6897f | [
"MIT"
] | null | null | null | src/renderer/sphere.cpp | danbrakeley/stantz | 58b7ff24fab94accd710092893e7b0c4a0d6897f | [
"MIT"
] | null | null | null | #include "pch.h"
#include "sphere.h"
bool Sphere::hit(const Ray& r, float t_min, float t_max, hit_record* p_rec) const {
assert(p_rec != nullptr);
assert(p_mat_ != nullptr);
Vec3 oc = r.origin() - center_;
float a = dot(r.direction(), r.direction());
// the 2 from b was removed because it doesn't impact how we use the discriminant, and cancels in the final quadratic
float b = dot(oc, r.direction());
float c = dot(oc, oc) - radius_ * radius_;
// discriminant determines how many roots:
// < 0 == 0 roots (can't sqrt a negative number)
// = 0 == 1 root (ignore as a possible hit?)
// > 0 == 2 roots
float discriminant = b * b - a * c;
if (discriminant > 0) {
// some 2's are missing because we cancelled them with b's 2
float temp = (-b - sqrt(discriminant)) / a;
if (temp < t_max && temp > t_min) {
p_rec->t = temp;
p_rec->point = r.point(p_rec->t);
// normal is center to point on sphere (aka point of intersection we just calculated)
// and radius is the length of any vector from the center to the surface, so skip a sqrt
p_rec->normal = (p_rec->point - center_) / radius_;
p_rec->p_mat = p_mat_;
return true;
}
// if the above closest root wasn't in the range we want, try again for second root
temp = (-b + sqrt(discriminant)) / a;
if (temp < t_max && temp > t_min) {
p_rec->t = temp;
p_rec->point = r.point(p_rec->t);
p_rec->normal = (p_rec->point - center_) / radius_;
p_rec->p_mat = p_mat_;
return true;
}
}
return false;
}
| 35.069767 | 118 | 0.645889 | [
"vector"
] |
82a6a574cb971b8dc0364bcff56a1a60d6130f10 | 8,382 | cpp | C++ | EmojicodeCompiler/CodeGenerator.cpp | jdiss/emojicode | f39fa328763b9f48a5c18cada709da964371c2a4 | [
"Artistic-2.0"
] | 1 | 2019-06-27T13:58:43.000Z | 2019-06-27T13:58:43.000Z | EmojicodeCompiler/CodeGenerator.cpp | icodeing/emojicode | f39fa328763b9f48a5c18cada709da964371c2a4 | [
"Artistic-2.0"
] | null | null | null | EmojicodeCompiler/CodeGenerator.cpp | icodeing/emojicode | f39fa328763b9f48a5c18cada709da964371c2a4 | [
"Artistic-2.0"
] | null | null | null | //
// CodeGenerator.cpp
// Emojicode
//
// Created by Theo Weidmann on 19/09/16.
// Copyright © 2016 Theo Weidmann. All rights reserved.
//
#include "CodeGenerator.hpp"
#include <cstring>
#include <vector>
#include "FunctionPAG.hpp"
#include "Protocol.hpp"
#include "CallableScoper.hpp"
#include "Class.hpp"
#include "EmojicodeCompiler.hpp"
#include "StringPool.hpp"
#include "ValueType.hpp"
#include "DiscardingFunctionWriter.hpp"
#include "TypeDefinitionFunctional.hpp"
template <typename T>
int writeUsed(const std::vector<T *> &functions, Writer &writer) {
int counter = 0;
for (auto function : functions) {
if (function->used()) {
writer.writeFunction(function);
counter++;
}
}
return counter;
}
template <typename T>
void compileUnused(const std::vector<T *> &functions) {
for (auto function : functions) {
if (!function->used() && !function->isNative()) {
DiscardingFunctionWriter writer = DiscardingFunctionWriter();
generateCodeForFunction(function, writer);
}
}
}
void generateCodeForFunction(Function *function, FunctionWriter &w) {
CallableScoper scoper = CallableScoper();
if (FunctionPAG::hasInstanceScope(function->compilationMode())) {
scoper = CallableScoper(&function->owningType().typeDefinitionFunctional()->instanceScope());
}
FunctionPAG(*function, function->owningType().disableSelfResolving(), w, scoper).compile();
}
void writeProtocolTable(const Type &type, Writer &writer) {
auto typeDefinitionFunctional = type.typeDefinitionFunctional();
writer.writeUInt16(typeDefinitionFunctional->protocols().size());
if (!typeDefinitionFunctional->protocols().empty()) {
auto biggestPlaceholder = writer.writePlaceholder<uint16_t>();
auto smallestPlaceholder = writer.writePlaceholder<uint16_t>();
uint_fast16_t smallestProtocolIndex = UINT_FAST16_MAX;
uint_fast16_t biggestProtocolIndex = 0;
for (const Type &protocol : typeDefinitionFunctional->protocols()) {
writer.writeUInt16(protocol.protocol()->index);
if (protocol.protocol()->index > biggestProtocolIndex) {
biggestProtocolIndex = protocol.protocol()->index;
}
if (protocol.protocol()->index < smallestProtocolIndex) {
smallestProtocolIndex = protocol.protocol()->index;
}
writer.writeUInt16(protocol.protocol()->methodList().size());
for (auto method : protocol.protocol()->methodList()) {
auto layerName = method->protocolBoxingLayerName(protocol.protocol()->name());
Function *clm = typeDefinitionFunctional->lookupMethod(layerName);
if (clm == nullptr) {
clm = typeDefinitionFunctional->lookupMethod(method->name());
}
writer.writeUInt16(clm->vtiForUse());
}
}
biggestPlaceholder.write(biggestProtocolIndex);
smallestPlaceholder.write(smallestProtocolIndex);
}
}
void writeClass(const Type &classType, Writer &writer) {
auto eclass = classType.eclass();
writer.writeEmojicodeChar(eclass->name()[0]);
if (eclass->superclass() != nullptr) {
writer.writeUInt16(eclass->superclass()->index);
}
else {
// If the class does not have a superclass the own index is written.
writer.writeUInt16(eclass->index);
}
writer.writeUInt16(eclass->size());
writer.writeUInt16(eclass->fullMethodCount());
writer.writeByte(eclass->inheritsInitializers() ? 1 : 0);
writer.writeUInt16(eclass->fullInitializerCount());
if (eclass->fullInitializerCount() > 65535) {
throw CompilerError(eclass->position(), "More than 65535 initializers in class.");
}
if (eclass->fullMethodCount() > 65535) {
throw CompilerError(eclass->position(), "More than 65535 methods in class.");
}
writer.writeUInt16(eclass->usedMethodCount());
writer.writeUInt16(eclass->usedInitializerCount());
writeUsed(eclass->methodList(), writer);
writeUsed(eclass->typeMethodList(), writer);
writeUsed(eclass->initializerList(), writer);
writeProtocolTable(classType, writer);
std::vector<ObjectVariableInformation> information;
for (auto variable : eclass->instanceScope().map()) {
variable.second.type().objectVariableRecords(variable.second.id(), information);
}
writer.writeUInt16(information.size());
for (auto info : information) {
writer.writeUInt16(info.index);
writer.writeUInt16(info.conditionIndex);
writer.writeUInt16(static_cast<uint16_t>(info.type));
}
}
void writePackageHeader(Package *pkg, Writer &writer) {
if (pkg->requiresBinary()) {
size_t l = pkg->name().size() + 1;
writer.writeByte(l);
writer.writeBytes(pkg->name().c_str(), l);
writer.writeUInt16(pkg->version().major);
writer.writeUInt16(pkg->version().minor);
}
else {
writer.writeByte(0);
}
writer.writeUInt16(pkg->classes().size());
}
void generateCode(Writer &writer) {
auto &theStringPool = StringPool::theStringPool();
theStringPool.poolString(EmojicodeString());
Function::start->setVtiProvider(&Function::pureFunctionsProvider);
Function::start->vtiForUse();
for (auto vt : ValueType::valueTypes()) { // Must be processed first, different sizes
vt->finalize();
}
for (auto eclass : Class::classes()) { // Can be processed afterwards, all pointers are 1 word
eclass->finalize();
}
while (!Function::compilationQueue.empty()) {
Function *function = Function::compilationQueue.front();
generateCodeForFunction(function, function->writer_);
Function::compilationQueue.pop();
}
if (ValueType::maxBoxIndetifier() > 2147483647) {
throw CompilerError(SourcePosition(0, 0, ""), "More than 2147483647 box identifiers in use.");
}
writer.writeUInt16(Class::classes().size());
writer.writeUInt16(Function::functionCount());
auto pkgCount = Package::packagesInOrder().size();
if (pkgCount > 255) {
throw CompilerError(Package::packagesInOrder().back()->position(), "You exceeded the maximum of 255 packages.");
}
writer.writeByte(pkgCount);
for (auto pkg : Package::packagesInOrder()) {
writePackageHeader(pkg, writer);
for (auto cl : pkg->classes()) {
writeClass(Type(cl, false), writer);
}
auto placeholder = writer.writePlaceholder<uint16_t>();
placeholder.write(writeUsed(pkg->functions(), writer));
}
int smallestBoxIdentifier = UINT16_MAX;
int biggestBoxIdentifier = 0;
int vtWithProtocolsCount = 0;
auto tableSizePlaceholder = writer.writePlaceholder<uint16_t>();
auto smallestPlaceholder = writer.writePlaceholder<uint16_t>();
auto countPlaceholder = writer.writePlaceholder<uint16_t>();
for (auto vt : ValueType::valueTypes()) {
if (!vt->protocols().empty()) {
writer.writeUInt16(vt->boxIdentifier());
writeProtocolTable(Type(vt, false), writer);
if (vt->boxIdentifier() < smallestBoxIdentifier) {
smallestBoxIdentifier = vt->boxIdentifier();
}
if (vt->boxIdentifier() > biggestBoxIdentifier) {
biggestBoxIdentifier = vt->boxIdentifier();
}
vtWithProtocolsCount++;
}
}
countPlaceholder.write(vtWithProtocolsCount);
tableSizePlaceholder.write(vtWithProtocolsCount > 0 ? biggestBoxIdentifier - smallestBoxIdentifier + 1 : 0);
smallestPlaceholder.write(smallestBoxIdentifier);
writer.writeUInt16(theStringPool.strings().size());
for (auto string : theStringPool.strings()) {
writer.writeUInt16(string.size());
for (auto c : string) {
writer.writeEmojicodeChar(c);
}
}
for (auto eclass : Class::classes()) {
compileUnused(eclass->methodList());
compileUnused(eclass->initializerList());
compileUnused(eclass->typeMethodList());
}
for (auto vt : ValueType::valueTypes()) {
compileUnused(vt->methodList());
compileUnused(vt->initializerList());
compileUnused(vt->typeMethodList());
}
}
| 34.780083 | 120 | 0.653663 | [
"vector"
] |
82a7f5014b66b4485b4772ec2031c14ec78e8ada | 3,309 | cc | C++ | src/0332_reconstruct_itinerary/reconstruct_itinerary.cc | youngqqcn/LeetCodeNodes | 62bbd30fbdf1640526d7fc4437cde1b05d67fc8f | [
"MIT"
] | 1 | 2021-05-23T02:15:03.000Z | 2021-05-23T02:15:03.000Z | src/0332_reconstruct_itinerary/reconstruct_itinerary.cc | youngqqcn/LeetCodeNotes | 62bbd30fbdf1640526d7fc4437cde1b05d67fc8f | [
"MIT"
] | null | null | null | src/0332_reconstruct_itinerary/reconstruct_itinerary.cc | youngqqcn/LeetCodeNotes | 62bbd30fbdf1640526d7fc4437cde1b05d67fc8f | [
"MIT"
] | null | null | null | // author: yqq
// date: 2021-07-28 18:35:23
// descriptions: https://leetcode-cn.com/problems/reconstruct-itinerary
#include <bits/stdc++.h>
#include <iostream>
#include <numeric>
#include <vector>
#include <string>
#include <map>
#include <set>
#include <algorithm>
#include <memory>
#include <queue>
#include <stack>
#include <unordered_set>
#include <unordered_map>
#include <string.h>
#include <stdlib.h>
using namespace std;
/*
给你一份航线列表 tickets ,其中 tickets[i] = [fromi, toi] 表示飞机出发和降落的机场地点。请你对该行程进行重新规划排序。
所有这些机票都属于一个从 JFK(肯尼迪国际机场)出发的先生,所以该行程必须从 JFK 开始。如果存在多种有效的行程,请你按字典排序返回最小的行程组合。
例如,行程 ["JFK", "LGA"] 与 ["JFK", "LGB"] 相比就更小,排序更靠前。
假定所有机票至少存在一种合理的行程。且所有的机票 必须都用一次 且 只能用一次。
示例 1:
┌───────┐ ┌───────┐ ┌──────┐
│ MUC ├────►│ LHR ├────►│ SFO │
└───────┘ └───────┘ └──┬───┘
▲ │
│ │
┌───┴───┐ ┌──▼───┐
│ JFK │ │ SJC │
└───────┘ └──────┘
输入:tickets = [["MUC","LHR"],["JFK","MUC"],["SFO","SJC"],["LHR","SFO"]]
输出:["JFK","MUC","LHR","SFO","SJC"]
示例 2:
┌───────┐
│ ├─────────────────────┐
│ SFO │ │
└───────┘◄──────────────────┐ │
▲ │ │
│ │ │
│ │ │
│ │ │
┌──┴────┐ ┌────┴─▼─┐
│ ├──────────────► │
│ JFK │ │ ATL │
└───────┘◄────────── ──┴────────┘
输入:tickets = [["JFK","SFO"],["JFK","ATL"],["SFO","ATL"],["ATL","JFK"],["ATL","SFO"]]
输出:["JFK","ATL","JFK","SFO","ATL","SFO"]
解释:另一种有效的行程是 ["JFK","SFO","ATL","JFK","ATL","SFO"] ,但是它字典排序更大更靠后。
*/
class Solution
{
private:
// unordered_map<出发机场, map<到达机场, 航班次数>> targets
unordered_map<string, map<string, int>> targets;
bool backtracking(int ticketNum, vector<string>& result)
{
if (result.size() == ticketNum + 1) {
return true;
}
for (pair<const string, int>& target : targets[result[result.size() - 1]])
{
if (target.second > 0 ) {
result.push_back(target.first);
target.second--;
if (backtracking(ticketNum, result)) return true;
result.pop_back();
target.second++;
}
}
return false;
}
public:
vector<string> findItinerary(vector<vector<string>>& tickets)
{
targets.clear();
vector<string> result;
for (const vector<string>& vec : tickets) {
targets[vec[0]][vec[1]]++;
}
result.push_back("JFK");
backtracking(tickets.size(), result);
return result;
}
};
void test(vector<vector<string>> targets, vector<string> expected)
{
Solution sol;
auto result = sol.findItinerary(targets);
if(expected.size() != result.size())
{
cout << "FAILED" << endl;
return;
}
if(expected != result)
{
cout << "FAILED" << endl;
return;
}
cout << "PASSED" << endl;
}
int main()
{
test({{"JFK","SFO"},{"JFK","ATL"},{"SFO","ATL"},{"ATL","JFK"},{"ATL","SFO"}}, {"JFK","ATL","JFK","SFO","ATL","SFO"} );
test({{"MUC","LHR"},{"JFK","MUC"},{"SFO","SJC"},{"LHR","SFO"}}, {"JFK","MUC","LHR","SFO","SJC"});
return 0;
}
| 25.068182 | 122 | 0.460864 | [
"vector"
] |
82a987ecd82c6720023fc984088afebcc8725e93 | 1,121 | cpp | C++ | ProblemsSolved/Graphs/ShortestPaths/WormHoles.cpp | searleser97/Algorithms | af791541d416c29867213d705375cbb3361f486c | [
"Apache-2.0"
] | 7 | 2019-06-06T17:54:20.000Z | 2021-03-24T02:31:55.000Z | ProblemsSolved/Graphs/ShortestPaths/WormHoles.cpp | searleser97/Algorithms | af791541d416c29867213d705375cbb3361f486c | [
"Apache-2.0"
] | null | null | null | ProblemsSolved/Graphs/ShortestPaths/WormHoles.cpp | searleser97/Algorithms | af791541d416c29867213d705375cbb3361f486c | [
"Apache-2.0"
] | 1 | 2021-03-24T02:31:57.000Z | 2021-03-24T02:31:57.000Z | #include <bits/stdc++.h>
using namespace std;
typedef int Weight;
int MAXN = 20001, N, INF = 1 << 30, isDirected = true;
vector<vector<int>> ady, weight;
void initVars() {
ady = vector<vector<int>>(MAXN, vector<int>());
weight = vector<vector<int>>(MAXN, vector<int>(MAXN, INF));
}
vector<Weight> bellmanFord(int s) {
vector<Weight> dist(MAXN, INF);
dist[s] = 0;
for (int i = 1; i <= N; i++)
for (int u = 0; u < N; u++)
for (auto &v : ady[u]) {
Weight w = weight[u][v];
if (dist[u] != INF && dist[v] > dist[u] + w) {
if (i == N) return {};
dist[v] = dist[u] + w;
}
}
return dist;
}
void addEdge(int u, int v, Weight w) {
ady[u].push_back(v);
weight[u][v] = w;
if (isDirected) return;
ady[v].push_back(u);
weight[v][u] = w;
}
int main() {
int T;
cin >> T;
while (T--) {
initVars();
int m, x, y, t;
cin >> N >> m;
while (m--) {
cin >> x >> y >> t;
addEdge(x, y, t);
}
if (bellmanFord(0).empty())
cout << "possible" << endl;
else
cout << "not possible" << endl;
}
return 0;
} | 21.150943 | 61 | 0.504014 | [
"vector"
] |
82a9a0d2ea3eb36fadfeb1404e3e431911911aec | 3,921 | cc | C++ | cdn/src/model/DescribeLiveStreamRecordIndexFilesResult.cc | iamzken/aliyun-openapi-cpp-sdk | 3c991c9ca949b6003c8f498ce7a672ea88162bf1 | [
"Apache-2.0"
] | 89 | 2018-02-02T03:54:39.000Z | 2021-12-13T01:32:55.000Z | cdn/src/model/DescribeLiveStreamRecordIndexFilesResult.cc | iamzken/aliyun-openapi-cpp-sdk | 3c991c9ca949b6003c8f498ce7a672ea88162bf1 | [
"Apache-2.0"
] | 89 | 2018-03-14T07:44:54.000Z | 2021-11-26T07:43:25.000Z | cdn/src/model/DescribeLiveStreamRecordIndexFilesResult.cc | aliyun/aliyun-openapi-cpp-sdk | 0cf5861ece17dfb0bb251f13bf3fbdb39c0c6e36 | [
"Apache-2.0"
] | 69 | 2018-01-22T09:45:52.000Z | 2022-03-28T07:58:38.000Z | /*
* Copyright 2009-2017 Alibaba Cloud 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 <alibabacloud/cdn/model/DescribeLiveStreamRecordIndexFilesResult.h>
#include <json/json.h>
using namespace AlibabaCloud::Cdn;
using namespace AlibabaCloud::Cdn::Model;
DescribeLiveStreamRecordIndexFilesResult::DescribeLiveStreamRecordIndexFilesResult() :
ServiceResult()
{}
DescribeLiveStreamRecordIndexFilesResult::DescribeLiveStreamRecordIndexFilesResult(const std::string &payload) :
ServiceResult()
{
parse(payload);
}
DescribeLiveStreamRecordIndexFilesResult::~DescribeLiveStreamRecordIndexFilesResult()
{}
void DescribeLiveStreamRecordIndexFilesResult::parse(const std::string &payload)
{
Json::Reader reader;
Json::Value value;
reader.parse(payload, value);
setRequestId(value["RequestId"].asString());
auto allRecordIndexInfoListNode = value["RecordIndexInfoList"]["RecordIndexInfo"];
for (auto valueRecordIndexInfoListRecordIndexInfo : allRecordIndexInfoListNode)
{
RecordIndexInfo recordIndexInfoListObject;
if(!valueRecordIndexInfoListRecordIndexInfo["RecordId"].isNull())
recordIndexInfoListObject.recordId = valueRecordIndexInfoListRecordIndexInfo["RecordId"].asString();
if(!valueRecordIndexInfoListRecordIndexInfo["RecordUrl"].isNull())
recordIndexInfoListObject.recordUrl = valueRecordIndexInfoListRecordIndexInfo["RecordUrl"].asString();
if(!valueRecordIndexInfoListRecordIndexInfo["DomainName"].isNull())
recordIndexInfoListObject.domainName = valueRecordIndexInfoListRecordIndexInfo["DomainName"].asString();
if(!valueRecordIndexInfoListRecordIndexInfo["AppName"].isNull())
recordIndexInfoListObject.appName = valueRecordIndexInfoListRecordIndexInfo["AppName"].asString();
if(!valueRecordIndexInfoListRecordIndexInfo["StreamName"].isNull())
recordIndexInfoListObject.streamName = valueRecordIndexInfoListRecordIndexInfo["StreamName"].asString();
if(!valueRecordIndexInfoListRecordIndexInfo["OssObject"].isNull())
recordIndexInfoListObject.ossObject = valueRecordIndexInfoListRecordIndexInfo["OssObject"].asString();
if(!valueRecordIndexInfoListRecordIndexInfo["StartTime"].isNull())
recordIndexInfoListObject.startTime = valueRecordIndexInfoListRecordIndexInfo["StartTime"].asString();
if(!valueRecordIndexInfoListRecordIndexInfo["EndTime"].isNull())
recordIndexInfoListObject.endTime = valueRecordIndexInfoListRecordIndexInfo["EndTime"].asString();
if(!valueRecordIndexInfoListRecordIndexInfo["Duration"].isNull())
recordIndexInfoListObject.duration = std::stof(valueRecordIndexInfoListRecordIndexInfo["Duration"].asString());
if(!valueRecordIndexInfoListRecordIndexInfo["Height"].isNull())
recordIndexInfoListObject.height = std::stoi(valueRecordIndexInfoListRecordIndexInfo["Height"].asString());
if(!valueRecordIndexInfoListRecordIndexInfo["Width"].isNull())
recordIndexInfoListObject.width = std::stoi(valueRecordIndexInfoListRecordIndexInfo["Width"].asString());
if(!valueRecordIndexInfoListRecordIndexInfo["CreateTime"].isNull())
recordIndexInfoListObject.createTime = valueRecordIndexInfoListRecordIndexInfo["CreateTime"].asString();
recordIndexInfoList_.push_back(recordIndexInfoListObject);
}
}
std::vector<DescribeLiveStreamRecordIndexFilesResult::RecordIndexInfo> DescribeLiveStreamRecordIndexFilesResult::getRecordIndexInfoList()const
{
return recordIndexInfoList_;
}
| 49.0125 | 142 | 0.816118 | [
"vector",
"model"
] |
82abb329d74afb9adae058cbe0236666ce0c9121 | 2,513 | cc | C++ | gazebo/common/CommonIface_TEST.cc | siconos/gazebo-siconos | 612f6a78184cb95d5e7a6898c42003c4109ae3c6 | [
"ECL-2.0",
"Apache-2.0"
] | 5 | 2017-07-14T19:36:51.000Z | 2020-04-01T06:47:59.000Z | gazebo/common/CommonIface_TEST.cc | siconos/gazebo-siconos | 612f6a78184cb95d5e7a6898c42003c4109ae3c6 | [
"ECL-2.0",
"Apache-2.0"
] | 20 | 2017-07-20T21:04:49.000Z | 2017-10-19T19:32:38.000Z | gazebo/common/CommonIface_TEST.cc | siconos/gazebo-siconos | 612f6a78184cb95d5e7a6898c42003c4109ae3c6 | [
"ECL-2.0",
"Apache-2.0"
] | null | null | null | /*
* Copyright (C) 2012-2016 Open Source Robotics Foundation
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*
*/
#include <stdlib.h>
#include <gtest/gtest.h>
#include <string>
#include <sstream>
#include "gazebo/common/CommonIface.hh"
#include "test/util.hh"
using namespace gazebo;
class CommonIface_TEST : public gazebo::testing::AutoLogFixture { };
/////////////////////////////////////////////////
/// \brief Test CommonIface::GetSHA1
TEST_F(CommonIface_TEST, GetSHA1)
{
// Do not forget to update 'precomputedSHA1' if you modify the SHA1 input.
std::string precomputedSHA1;
std::string computedSHA1;
std::string s;
// Compute the SHA1 of the vector
std::vector<float> v;
for (int i = 0; i < 100; ++i)
v.push_back(i);
computedSHA1 = common::get_sha1<std::vector<float> >(v);
precomputedSHA1 = "913283ec8502ba1423d38a7ea62cb8e492e87b23";
EXPECT_EQ(precomputedSHA1, computedSHA1);
// Compute the SHA1 of a string
s = "Marty McFly: Wait a minute, Doc. Ah... Are you telling me that you"
" built a time machine... out of a DeLorean?\n"
"Dr. Emmett Brown: The way I see it, if you're gonna build a time"
" machine into a car, why not do it with some style?";
computedSHA1 = common::get_sha1<std::string>(s);
precomputedSHA1 = "a370ddc4d61d936b2bb40f98bae061dc15fd8923";
EXPECT_EQ(precomputedSHA1, computedSHA1);
// Compute the SHA1 of an empty string
s = "";
computedSHA1 = common::get_sha1<std::string>(s);
precomputedSHA1 = "da39a3ee5e6b4b0d3255bfef95601890afd80709";
EXPECT_EQ(precomputedSHA1, computedSHA1);
// Compute a bunch of SHA1's to verify consistent length
for (unsigned i = 0; i < 100; ++i)
{
std::stringstream stream;
stream << i << '\n';
std::string sha = common::get_sha1<std::string>(stream.str());
EXPECT_EQ(sha.length(), 40u);
}
}
/////////////////////////////////////////////////
int main(int argc, char **argv)
{
::testing::InitGoogleTest(&argc, argv);
return RUN_ALL_TESTS();
}
| 31.810127 | 76 | 0.679268 | [
"vector"
] |
82acaa55ac591f1af436e42a9f5a329b55b41039 | 5,224 | cpp | C++ | typer.cpp | flyyee/typer | 01c83136afe423c60c71f29105f3ec41cbb8d60b | [
"MIT"
] | null | null | null | typer.cpp | flyyee/typer | 01c83136afe423c60c71f29105f3ec41cbb8d60b | [
"MIT"
] | null | null | null | typer.cpp | flyyee/typer | 01c83136afe423c60c71f29105f3ec41cbb8d60b | [
"MIT"
] | null | null | null | #include "typer.h"
#include <windows.h>
#include <iostream>
using namespace std;
typer::typer() : word("void"),
s_Sleep(10), sver(1), sverinfo("typers version 2: a-z, 0-9, :-./(spacekey)_\nsyntax: typers(' ');\n"),
fctrl(0), fenter(0), falt(0), ftab(0),
f_Sleep(10), fver(2), fverinfo("typerf version 3: ctrl, enter, alt, tab\nsyntax: typerf(" ", c, e);\n") {
}
void typer::s_off() {
unsigned char keys[] = {'0x41', '0x42', '0x43', '0x44', '0x45', '0x46', '0x47', '0x48', '0x49', '0x4a', '0x4b', '0x4c', '0x4d', '0x4e', '0x4f', '0x50', '0x51', '0x52', '0x53',
'0x53', '0x54', '0x55', '0x56', '0x57', '0x58', '0x59', '0x5a', '0xC0', '0xBD', '0xBA', '0xBF', '0xBE', '0x20', '0x31', '0x32', '0x33', '0x34', '0x35', '0x36', '0x37',
'0x38', '0x39', '0x30'
};
for (int x = 0; (x < sizeof(keys)/sizeof(*keys)); x++) {
//cout << x;
keybd_event(keys[x], 0, 0x0002, 0);
}
}
void typer::s_on() { //?
unsigned char keys[] = {'0x41', '0x42', '0x43', '0x44', '0x45', '0x46', '0x47', '0x48', '0x49', '0x4a', '0x4b', '0x4c', '0x4d', '0x4e', '0x4f', '0x50', '0x51', '0x52', '0x53',
'0x53', '0x54', '0x55', '0x56', '0x57', '0x58', '0x59', '0x5a', '0xC0', '0xBD', '0xBA', '0xBF', '0xBE', '0x20', '0x31', '0x32', '0x33', '0x34', '0x35', '0x36', '0x37',
'0x38', '0x39', '0x30'
};
for (int x = 0; (x < sizeof(keys)/sizeof(*keys)); x++) {
//cout << x;
keybd_event(keys[x], 0, 0, 0);
}
}
//capital letters
void typer::s(string ipt) {
char skey;
word = ipt;
for (int n = 0; n < word.size(); ++n) {
skey = word[n];
switch(skey) {
case 'a':
keybd_event(0x41, 0, 0, 0);
break;
case 'b':
keybd_event(0x42, 0, 0, 0);
break;
case 'c':
keybd_event(0x43, 0, 0, 0);
break;
case 'd':
keybd_event(0x44, 0, 0, 0);
break;
case 'e':
keybd_event(0x45, 0, 0, 0);
break;
case 'f':
keybd_event(0x46, 0, 0, 0);
break;
case 'g':
keybd_event(0x47, 0, 0, 0);
break;
case 'h':
keybd_event(0x48, 0, 0, 0);
break;
case 'i':
keybd_event(0x49, 0, 0, 0);
break;
case 'j':
keybd_event(0x4a, 0, 0, 0);
break;
case 'k':
keybd_event(0x4b, 0, 0, 0);
break;
case 'l':
keybd_event(0x4c, 0, 0, 0);
break;
case 'm':
keybd_event(0x4d, 0, 0, 0);
break;
case 'n':
keybd_event(0x4e, 0, 0, 0);
break;
case 'o':
keybd_event(0x4f, 0, 0, 0);
break;
case 'p':
keybd_event(0x50, 0, 0, 0);
break;
case 'q':
keybd_event(0x51, 0, 0, 0);
break;
case 'r':
keybd_event(0x52, 0, 0, 0);
break;
case 's':
keybd_event(0x53, 0, 0, 0);
break;
case 't':
keybd_event(0x54, 0, 0, 0);
break;
case 'u':
keybd_event(0x55, 0, 0, 0);
break;
case 'v':
keybd_event(0x56, 0, 0, 0);
break;
case 'w':
keybd_event(0x57, 0, 0, 0);
break;
case 'x':
keybd_event(0x58, 0, 0, 0);
break;
case 'y':
keybd_event(0x59, 0, 0, 0);
break;
case 'z':
keybd_event(0x5a, 0, 0, 0);
break;
case '~':
keybd_event(0xC0, 0, 0, 0);
break;
case '-':
keybd_event(0xBD, 0, 0, 0);
break;
case ':':
keybd_event(0x10, 0, 0, 0);
keybd_event(0xBA, 0, 0, 0);
keybd_event(0x10, 0, 0x0002, 0);
break;
case '/':
keybd_event(0xBF, 0, 0, 0);
break;
case '.':
keybd_event(0xBE, 0, 0, 0);
break;
case ' ':
keybd_event(0x20, 0, 0, 0);
break;
case '_':
keybd_event(0x10, 0, 0, 0);
keybd_event(0xBD, 0, 0, 0);
keybd_event(0x10, 0, 0x0002, 0);
break;
case '1':
keybd_event(0x31, 0, 0, 0);
break;
case '2':
keybd_event(0x32, 0, 0, 0);
break;
case '3':
keybd_event(0x33, 0, 0, 0);
break;
case '4':
keybd_event(0x34, 0, 0, 0);
break;
case '5':
keybd_event(0x35, 0, 0, 0);
break;
case '6':
keybd_event(0x36, 0, 0, 0);
break;
case '7':
keybd_event(0x37, 0, 0, 0);
break;
case '8':
keybd_event(0x38, 0, 0, 0);
break;
case '9':
keybd_event(0x39, 0, 0, 0);
break;
case '0':
keybd_event(0x30, 0, 0, 0);
break;
}
Sleep(s_Sleep);
}
}
//use if (fctrl) { reverse function } as f_Xname is a bool
//accept long string which parses words eg object.f("alttab"); Sleep(500); object.f("tabalt");
//create bool variable for automatic switch eg bool autooff = 1; object.f("enter"); result is pressing enter then turning it off instead of just continuously pressing enter
void typer::f(string fkey) {
if (fkey == "ctrl") {
if (fctrl == 0) {
keybd_event(0x11, 0, 0, 0);
fctrl = 1;
} else {
keybd_event(0x11, 0, 0x0002, 0);
fctrl = 0;
}
}
if (fkey == "enter") {
if (fenter == 0) {
keybd_event(0x0D, 0, 0, 0);
fenter = 1;
} else {
keybd_event(0x0D, 0, 0x0002, 0);
fenter = 0;
}
}
if (fkey == "alt") {
if (falt == 0) {
keybd_event(0x12, 0, 0, 0);
falt = 1;
} else {
keybd_event(0x12, 0, 0x0002, 0);
falt = 0;
}
}
if (fkey == "tab") {
if (ftab == 0) {
keybd_event(0x09, 0, 0, 0);
ftab = 1;
} else {
keybd_event(0x09, 0, 0x0002, 0);
ftab = 0;
}
}
Sleep(f_Sleep);
}
| 23.013216 | 178 | 0.516462 | [
"object"
] |
82acd3a06c27e81908b424487c70cc794cf47bd0 | 4,587 | cpp | C++ | src/navigator.cpp | ryuichiueda/raspimouse_cartographer_teach_and_replay | 7092584331b73251b78e9b7237107e51d42808c1 | [
"MIT"
] | null | null | null | src/navigator.cpp | ryuichiueda/raspimouse_cartographer_teach_and_replay | 7092584331b73251b78e9b7237107e51d42808c1 | [
"MIT"
] | null | null | null | src/navigator.cpp | ryuichiueda/raspimouse_cartographer_teach_and_replay | 7092584331b73251b78e9b7237107e51d42808c1 | [
"MIT"
] | null | null | null | #include <ros/ros.h>
#include <tf/transform_listener.h>
#include <ros/package.h>
#include <iostream>
#include <fstream>
#include <iomanip>
#include <vector>
#include <string>
#include <visualization_msgs/Marker.h>
#include "raspimouse_ros_2/ButtonValues.h"
#include "raspimouse_ros_2/LedValues.h"
#include <geometry_msgs/PoseWithCovarianceStamped.h>
#include <geometry_msgs/Twist.h>
#include "visualization_msgs/MarkerArray.h"
using namespace ros;
bool load_finished = false;
std::vector<geometry_msgs::Point> trajectory;
visualization_msgs::MarkerArray marker_array;
int step = 0;
double x = 0.0;
double y = 0.0;
double yaw = 0.0;
bool replay_start = false;
bool replay_finished = false;
visualization_msgs::Marker markerBuilder(const geometry_msgs::Point &p, int id)
{
visualization_msgs::Marker m;
m.header.frame_id = "/map";
m.type = 2;
m.id = id;
m.scale.x = 0.05;
m.scale.y = 0.05;
m.scale.z = 0.05;
m.pose.position.x = p.x;
m.pose.position.y = p.y;
m.color.r = 0.0;
m.color.g = 1.0;
m.color.b = 0.0;
m.color.a = 0.5;
return m;
}
geometry_msgs::Twist decision(double distance, double direction)
{
geometry_msgs::Twist tw;
if(direction > 180.0) direction -= 360.0;
if(direction < -180.0) direction += 360.0;
if( (fabs(direction) > 10.0 and distance < 0.1) or fabs(direction) > 30.0 ){
tw.linear.x /= 1.1;
}else{
if(tw.linear.x < 0.05)
tw.linear.x = 0.05;
tw.linear.x *= 2.0;
if(tw.linear.x > 0.4)
tw.linear.x = 0.4;
}
tw.angular.z = 2*direction*3.141592/180;
if(tw.angular.z > 2.0) tw.angular.z = 2.0;
else if(tw.angular.z < -2.0) tw.angular.z = -2.0;
return tw;
}
bool read_trajectory(std::string filename)
{
std::ifstream f(filename);
if(!f)
return false;
double x,y;
while(f >> x >> y){
geometry_msgs::Point p;
p.x = x;
p.y = y;
p.z = 0.0;
trajectory.push_back(p);
}
if(trajectory.size() == 0)
return false;
int n = 0;
for(auto p : trajectory){
ROS_INFO("point %d\t%f\t%f", n++, p.x, p.y);
}
return true;
}
void callbackPose(const geometry_msgs::PoseWithCovarianceStamped::ConstPtr& msg)
{
x = msg->pose.pose.position.x;
y = msg->pose.pose.position.y;
yaw = tf::getYaw(msg->pose.pose.orientation)/3.141592*180;
}
void callbackButtons(const raspimouse_ros_2::ButtonValues::ConstPtr& msg)
{
if (msg->mid){
ROS_INFO("replay start");
replay_start = true;
}
if (msg->rear){
ROS_INFO("replay finished");
replay_finished = true;
}
}
int main(int argc, char **argv)
{
read_trajectory("/tmp/trajectory.tsv");
int marker_id = 0;
for(auto p : trajectory){
marker_array.markers.push_back( markerBuilder(p, marker_id++) );
}
init(argc,argv,"navigator");
NodeHandle n;
Subscriber sub_pose = n.subscribe("/amcl_pose", 1, callbackPose);
Subscriber sub_button = n.subscribe("/buttons", 1, callbackButtons);
Publisher pub_cmd_vel = n.advertise<geometry_msgs::Twist>("/cmd_vel", 1);
Publisher pub_led = n.advertise<raspimouse_ros_2::LedValues>("leds", 5);
Publisher pub_trajectory = n.advertise<visualization_msgs::MarkerArray>("trajectory", 5);
Publisher pub_target = n.advertise<visualization_msgs::Marker>("target_marker", 5);
raspimouse_ros_2::LedValues leds;
leds.left_side = false;
leds.right_side = false;
leds.left_forward = true;
leds.right_forward = false;
Rate r(10);
while(ok()){ //waiting the center button
pub_trajectory.publish(marker_array);
pub_led.publish(leds);
if(replay_start)
break;
spinOnce();
r.sleep();
}
geometry_msgs::Twist tw;
tw.linear.x = 0.0;
tw.angular.z = 0.0;
int step = 0;
int prev_step = trajectory.size() - 1;
marker_array.markers[step].color.r = 1.0;
marker_array.markers[step].color.g = 0.0;
pub_trajectory.publish(marker_array);
while(ok()){
double prev_x = trajectory[prev_step].x;
double prev_y = trajectory[prev_step].y;
double target_x = trajectory[step].x;
double target_y = trajectory[step].y;
double target_r = sqrt((target_x-x)*(target_x-x) + (target_y-y)*(target_y-y));
if(target_r < 0.05){
prev_step = step;
step = (step+1)%trajectory.size();
marker_array.markers[step].color.r = 1.0;
marker_array.markers[step].color.g = 0.0;
marker_array.markers[prev_step].color.r = 0.0;
marker_array.markers[prev_step].color.g = 1.0;
pub_trajectory.publish(marker_array);
continue;
}
double target_direction = atan2(target_y-y, target_x-x)/3.141592*180 - yaw;
geometry_msgs::Twist tw = decision(target_r, target_direction);
pub_cmd_vel.publish(tw);
if(replay_finished)
break;
spinOnce();
r.sleep();
}
return 0;
}
| 22.485294 | 90 | 0.685851 | [
"vector"
] |
82b0890112f949756b1e2fc4abdb70f36264cba1 | 2,395 | cpp | C++ | models/AI-Model-Zoo/caffe-xilinx/src/caffe/layers/cudnn_batch_norm_fixed_layer.cpp | hito0512/Vitis-AI | 996459fb96cb077ed2f7e789d515893b1cccbc95 | [
"Apache-2.0"
] | 848 | 2019-12-03T00:16:17.000Z | 2022-03-31T22:53:17.000Z | models/AI-Model-Zoo/caffe-xilinx/src/caffe/layers/cudnn_batch_norm_fixed_layer.cpp | wangyifan778/Vitis-AI | f61061eef7550d98bf02a171604c9a9f283a7c47 | [
"Apache-2.0"
] | 656 | 2019-12-03T00:48:46.000Z | 2022-03-31T18:41:54.000Z | models/AI-Model-Zoo/caffe-xilinx/src/caffe/layers/cudnn_batch_norm_fixed_layer.cpp | wangyifan778/Vitis-AI | f61061eef7550d98bf02a171604c9a9f283a7c47 | [
"Apache-2.0"
] | 506 | 2019-12-03T00:46:26.000Z | 2022-03-30T10:34:56.000Z | /*
* Copyright 2019 Xilinx Inc.
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
#ifdef USE_CUDNN
#include <vector>
#include "caffe/layers/cudnn_batch_norm_fixed_layer.hpp"
namespace caffe {
template <typename Dtype>
void CuDNNBatchNormFixedLayer<Dtype>::LayerSetUp(
const vector<Blob<Dtype>*>& bottom,
const vector<Blob<Dtype>*>& top) {
// // Set up convolution layer
CuDNNBatchNormLayer<Dtype>::LayerSetUp(bottom, top);
// Set up BatchNorm layer
LayerParameter bn_layer_param(this->layer_param_);
bn_layer_param.set_type("BatchNorm");
internal_bn_layer_ = LayerRegistry<Dtype>::CreateLayer(bn_layer_param);
internal_bn_layer_->SetUp(bottom, top);
internal_bn_layer_->set_piter(this->piter_);
// Set up fixed parameters
FixedParameter fixed_param = this->layer_param_.fixed_param();
enable_fix_ = fixed_param.enable();
fixed_method_ = fixed_param.fixed_method();
bit_width_ = fixed_param.bit_width();
weight_dec_pos_ = 0;
bias_dec_pos_ = 0;
// Set up BatchNorm layer for fixed forward
LayerParameter fixed_forward_bn_layer_param(this->layer_param_);
fixed_forward_bn_layer_param.set_type("BatchNorm");
fixed_forward_bn_layer_param.set_phase(TEST);
fixed_forward_bn_layer_ = LayerRegistry<Dtype>::CreateLayer(fixed_forward_bn_layer_param);
fixed_forward_bn_layer_->SetUp(bottom, top);
// bind blobs_ to internal_bn_layer
for (size_t i = 0; i< internal_bn_layer_->blobs().size(); ++i) {
this->blobs_[i] = internal_bn_layer_->blobs()[i];
}
}
template <typename Dtype>
void CuDNNBatchNormFixedLayer<Dtype>::Reshape(
const vector<Blob<Dtype>*>& bottom,
const vector<Blob<Dtype>*>& top) {
CuDNNBatchNormLayer<Dtype>::Reshape(bottom, top);
internal_bn_layer_->Reshape(bottom, top);
fixed_forward_bn_layer_->Reshape(bottom, top);
}
INSTANTIATE_CLASS(CuDNNBatchNormFixedLayer);
} // namespace caffe
#endif
| 31.103896 | 92 | 0.754489 | [
"vector"
] |
a118eee7421c7cc6c4aaa3fbdee4a41950426469 | 828 | cpp | C++ | sources/Reader.cpp | FORTYSS0/lab-kv-storage-10 | 4d2e7eff44dc54237ad0e6deaa5911d8a00b0c75 | [
"MIT"
] | null | null | null | sources/Reader.cpp | FORTYSS0/lab-kv-storage-10 | 4d2e7eff44dc54237ad0e6deaa5911d8a00b0c75 | [
"MIT"
] | null | null | null | sources/Reader.cpp | FORTYSS0/lab-kv-storage-10 | 4d2e7eff44dc54237ad0e6deaa5911d8a00b0c75 | [
"MIT"
] | null | null | null | // Copyright 2021 by FORTYSS
#include "Reader.hpp"
Reader::Reader(const int& num_workers) : readers(num_workers) {}
void Reader::read(const Field& field_) {
readers.enqueue([&](const Field& field){
++temp_nums_in_column;
db_out->Put(rocksdb::WriteOptions(),
handles_cf_out.front(),
field.key, field.value);
if (nums_in_columns.front() == temp_nums_in_column){
handles_cf_out.erase(handles_cf_out.begin());
nums_in_columns.erase(nums_in_columns.begin());
temp_nums_in_column = 0;
}
}, field_);
}
void Reader::setting(
rocksdb::DB* db_out_,
const std::vector<rocksdb::ColumnFamilyHandle*>& handles_cf_out_,
const std::vector<int>& nums_in_columns_) {
db_out = db_out_;
handles_cf_out = handles_cf_out_;
nums_in_columns = nums_in_columns_;
}
| 31.846154 | 69 | 0.68599 | [
"vector"
] |
a11cee579f244ce7f695206098038d0d24c43e53 | 1,052 | cpp | C++ | BOJ/1260.cpp | ReinforceIII/Algorithm | 355f6e19f8deb6a76f82f5283d7c1987acd699a6 | [
"MIT"
] | null | null | null | BOJ/1260.cpp | ReinforceIII/Algorithm | 355f6e19f8deb6a76f82f5283d7c1987acd699a6 | [
"MIT"
] | null | null | null | BOJ/1260.cpp | ReinforceIII/Algorithm | 355f6e19f8deb6a76f82f5283d7c1987acd699a6 | [
"MIT"
] | null | null | null | /* 1260 DFS와 BFS*/
#include <iostream>
#include <string>
#include <algorithm>
#include <vector>
#include <queue>
#include <cstring>
using namespace std;
vector<int> v[1001];
bool visited[1001];
void dfs(int node) {
visited[node] = true;
cout<<node<<" ";
for(int i=0; i<v[node].size(); i++) {
int next = v[node][i];
if(visited[next] == false) dfs(next);
}
}
void bfs(int node) {
queue<int> q;
visited[node] = true;
q.push(node);
while(!q.empty()) {
int now = q.front(); q.pop();
cout<<now<<" ";
for(int i=0; i<v[now].size(); i++) {
int next = v[now][i];
if(visited[next] == false) {
visited[next] = true;
q.push(next);
}
}
}
}
int main() {
int n,m,start;
cin>>n>>m>>start;
for(int i=0; i<m; i++) {
int from,to;
cin>>from>>to;
v[from].push_back(to);
v[to].push_back(from);
}
for(int i=1; i<=n; i++) {
sort(v[i].begin(),v[i].end());
}
dfs(start);
cout<<"\n";
memset(visited,false,sizeof(visited));
bfs(start);
cout<<"\n";
return 0;
} | 19.127273 | 41 | 0.538023 | [
"vector"
] |
a12ae53f2d2d1281d0d156306d5c654a401203b7 | 12,319 | cpp | C++ | RogueEngine/Source/EditorViewport.cpp | silferysky/RogueArcher | 3c77696260f773a0b7adb88b991e09bb35069901 | [
"FSFAP"
] | 1 | 2019-06-18T20:07:47.000Z | 2019-06-18T20:07:47.000Z | RogueEngine/Source/EditorViewport.cpp | silferysky/RogueArcher | 3c77696260f773a0b7adb88b991e09bb35069901 | [
"FSFAP"
] | null | null | null | RogueEngine/Source/EditorViewport.cpp | silferysky/RogueArcher | 3c77696260f773a0b7adb88b991e09bb35069901 | [
"FSFAP"
] | null | null | null | /* Start Header ************************************************************************/
/*!
\file EditorViewport.cpp
\project Exale
\author Loh Kai Yi,kaiyi.loh,390002918 (100%)
\par kaiyi.loh\@digipen.edu
\date 1 December,2019
\brief This file contains the function definitions for EditorViewport
All content (C) 2019 DigiPen (SINGAPORE) Corporation, all rights
reserved.
Reproduction or disclosure of this file or its contents
without the prior written consent of DigiPen Institute of
Technology is prohibited.
*/
/* End Header **************************************************************************/
#include "Precompiled.h"
#include "EditorViewport.h"
#include "PickingManager.h"
#include "CameraManager.h"
#include "REMath.h"
#include "CollisionManager.h"
namespace Rogue
{
ImGuiEditorViewport::ImGuiEditorViewport() :
m_currentVector{ g_engine.m_coordinator.GetActiveObjects() }, m_CurrentGizmoOperation{ ImGuizmo::TRANSLATE }, m_CurrentGizmoMode{ }
{
}
void ImGuiEditorViewport::Init()
{}
void ImGuiEditorViewport::Update()
{
ImGui::Begin("Viewport");
ImGui::BeginChild("Viewport child");
ImGuiStyle& style = ImGui::GetStyle();
if (ImGui::Button("Play"))
{
//If game is not running, save level, and set it to running
if (!g_engine.m_coordinator.GetGameState())
{
g_engine.SetTimeScale(1.0f);
SceneManager::instance().SaveLevel(SceneManager::instance().getCurrentFileName().c_str());
CameraManager::instance().SetCameraZoom(CameraManager::instance().GetLevelCameraZoom());
CameraManager::instance().SetCameraPos(glm::vec3(PLAYER_STATUS.GetStartingPos().x, PLAYER_STATUS.GetStartingPos().y, CameraManager::instance().GetCameraPos().z));
//SceneManager::instance().SaveAndLoadLevel();
g_engine.m_coordinator.SetGameState(true);
//ShowCursor(false);
}
else //If game is running, just stop and reload old data
{
//Loads last iteration and pauses game
SceneManager::instance().ReloadLevel();
//ShowCursor(true);
}
}
if (ImGui::IsItemHovered())
{
ImGui::BeginTooltip();
ImGui::Text("If game is paused, will save level");
ImGui::EndTooltip();
}
ImGui::SameLine();
if (!g_engine.m_coordinator.GetGameState())
{
ImGui::PushStyleColor(ImGuiCol_Button, { 0.8f,0.0f,0.0f,0.4f });
ImGui::PushStyleColor(ImGuiCol_ButtonHovered, { 0.8f,0.0f,0.0f,1.0f });
ImGui::PushStyleColor(ImGuiCol_ButtonActive, { 0.9f,0.0f,0.0f,1.0f });
}
else if(!g_engine.m_coordinator.GetPauseState())
{
ImGui::PushStyleColor(ImGuiCol_Button, style.Colors[ImGuiCol_Button]);
ImGui::PushStyleColor(ImGuiCol_ButtonHovered, style.Colors[ImGuiCol_ButtonHovered]);
ImGui::PushStyleColor(ImGuiCol_ButtonActive, style.Colors[ImGuiCol_ButtonActive]);
}
else
{
ImGui::PushStyleColor(ImGuiCol_Button, {0.3f, 0.3f, 0.3f, 0.3f});
ImGui::PushStyleColor(ImGuiCol_ButtonHovered, { 0.8f, 0.8f, 0.8f, 0.8f });
ImGui::PushStyleColor(ImGuiCol_ButtonActive, { 0.8f, 0.8f, 0.8f, 0.8f });
}
if (ImGui::Button("Pause"))
{
//Pause/Unpause only if game is running
if (g_engine.m_coordinator.GetGameState())
{
g_engine.m_coordinator.TogglePauseState();
//ShowCursor(true);
}
}
if (ImGui::IsItemHovered())
{
ImGui::BeginTooltip();
ImGui::Text("Toggles Pause");
ImGui::EndTooltip();
}
ImGui::PopStyleColor(3);
ImGui::SameLine();
if (!g_engine.m_coordinator.GetGameState())
{
ImGui::PushStyleColor(ImGuiCol_Button, { 0.8f,0.0f,0.0f,0.4f });
ImGui::PushStyleColor(ImGuiCol_ButtonHovered, { 0.8f,0.0f,0.0f,1.0f });
ImGui::PushStyleColor(ImGuiCol_ButtonActive, { 0.9f,0.0f,0.0f,1.0f });
}
else
{
ImGui::PushStyleColor(ImGuiCol_Button, style.Colors[ImGuiCol_Button]);
ImGui::PushStyleColor(ImGuiCol_ButtonHovered, style.Colors[ImGuiCol_ButtonHovered]);
ImGui::PushStyleColor(ImGuiCol_ButtonActive, style.Colors[ImGuiCol_ButtonActive]);
}
if (ImGui::Button("Stop"))
{
if (g_engine.m_coordinator.GetGameState())
{
//Loads last iteration and pauses game
SceneManager::instance().ReloadLevel();
}
}
ImGui::PopStyleColor(3);
if (ImGui::IsItemHovered())
{
ImGui::BeginTooltip();
ImGui::Text("Stops game and loads last saved state");
ImGui::EndTooltip();
}
ImGui::SameLine();
int m_Frames = (int)g_engine.m_coordinator.GetStepFrames();
ImGui::PushItemWidth(75);
ImGui::SliderInt("Step Count", &m_Frames, 1, 60);
g_engine.m_coordinator.SetStepFrames(m_Frames);
ImGui::SameLine();
if (ImGui::Button("Step"))
{
g_engine.m_coordinator.StepOnce();
}
ImGui::SameLine();
ImGui::PushItemWidth(75);
if (ImGui::Button("Play Without Saving"))
{
if (!g_engine.m_coordinator.GetGameState())
{
CameraManager::instance().SetCameraZoom(CameraManager::instance().GetLevelCameraZoom());
CameraManager::instance().SetCameraPos(glm::vec3(PLAYER_STATUS.GetStartingPos().x, PLAYER_STATUS.GetStartingPos().y, CameraManager::instance().GetCameraPos().z));
g_engine.m_coordinator.SetGameState(true);
//ShowCursor(false);
}
}
if (ImGui::IsItemHovered())
{
ImGui::BeginTooltip();
ImGui::Text("Instantly plays the scene without saving");
ImGui::EndTooltip();
}
if (!g_engine.m_coordinator.GetGameState() || g_engine.m_coordinator.GetPauseState())
{
if (g_engine.GetIsFocused())
{
if (ImGui::IsKeyPressed('Q') && g_engine.GetIsFocused())
{
m_CurrentGizmoOperation = ImGuizmo::TRANSLATE;
}
if (ImGui::IsKeyPressed('W') && g_engine.GetIsFocused())
{
m_CurrentGizmoOperation = ImGuizmo::ROTATE;
}
if (ImGui::IsKeyPressed('E') && g_engine.GetIsFocused())
{
m_CurrentGizmoOperation = ImGuizmo::SCALE;
}
}
}
ImGui::SameLine();
if (ImGui::RadioButton("Translate", m_CurrentGizmoOperation == ImGuizmo::TRANSLATE))
m_CurrentGizmoOperation = ImGuizmo::TRANSLATE;
ImGui::SameLine();
if (ImGui::RadioButton("Rotate", m_CurrentGizmoOperation == ImGuizmo::ROTATE))
m_CurrentGizmoOperation = ImGuizmo::ROTATE;
ImGui::SameLine();
if (ImGui::RadioButton("Scale", m_CurrentGizmoOperation == ImGuizmo::SCALE))
m_CurrentGizmoOperation = ImGuizmo::SCALE;
if (!g_engine.m_coordinator.GetGameState() || g_engine.m_coordinator.GetPauseState())
{
for (auto& i : m_currentVector)
{
HierarchyInfo& objInfo = g_engine.m_coordinator.GetHierarchyInfo(i);
if (objInfo.m_selected == true)
{
const AABB& viewportArea = PickingManager::instance().GetViewPortArea();
TransformComponent& trans = g_engine.m_coordinator.GetComponent<TransformComponent>(i);
Vec2 pos = trans.GetPosition();
if (CollisionManager::instance().DiscretePointVsAABB(pos, viewportArea) /*&& ImGui::IsWindowFocused()*/)
{
ShowGizmo(i);
}
}
}
}
ImVec2 imageSize = ImGui::GetContentRegionAvail();
ImGui::Image((void*)(intptr_t)(g_engine.m_coordinator.GetSystem<GraphicsSystem>()->getFBO()), ImVec2(imageSize.x,imageSize.y ), ImVec2(0, 1), ImVec2(1, 0));
auto drawlist = ImGui::GetWindowDrawList();
ImVec2 TileSize(64.0f, 64.0f);
ImGui::GetWindowContentRegionMin();
//drawlist->AddLine(ImVec2(1000.0f, 1000.0f), ImVec2(100.0f, 100.0f), ImColor(120, 100, 100), 3.0f);
if (ImGui::BeginDragDropTarget())
{
if (const ImGuiPayload * payload = ImGui::AcceptDragDropPayload("Data"))
{
DirectoryInfo payload_n = *(DirectoryInfo*)payload->Data;
size_t levelcheck = payload_n.m_filePath.find_last_of("Level");
std::cout << levelcheck << std::endl;
size_t filetype = payload_n.m_filePath.find_last_of(".");
std::string levelnumber = payload_n.m_filePath.substr(levelcheck - 4, filetype);
std::string level = levelnumber.substr(0, 5);
if (payload_n.m_fileType == "json" && level == ("Level"))
{
SceneManager& sceneManager = SceneManager::instance();
std::cout << "load!" << std::endl;
sceneManager.LoadLevel(levelnumber);
g_engine.m_coordinator.SetGameState(false);
g_engine.m_coordinator.SetPauseState(false);
ImGui::EndDragDropTarget();
}
else if (payload_n.m_fileType == "json")
{
size_t filetype = payload_n.m_fileName.find_last_of(".");
std::string fileNameWithoutType = payload_n.m_fileName.substr(0, filetype);
for (auto& i : SceneManager::instance().GetArchetypeMap())
{
SceneManager::instance().Clone(fileNameWithoutType.c_str());
std::cout << "clone!" << std::endl;
}
}
else
{
ImGui::OpenPopup("File Error");
}
}
}
bool open = true;
if (ImGui::BeginPopupModal("File Error", &open))
{
ImGui::Text("Error!, Please only put in level files or prefabs!");
if (ImGui::Button("Close"))
ImGui::CloseCurrentPopup();
ImGui::EndPopup();
}
ImVec2 mousePos = ImGui::GetMousePos();
int width = g_engine.GetEngineWindowWidth();
int height = g_engine.GetEngineWindowHeight();
// Bring mousePos to the bottom left of the viewport
mousePos.x -= ImGui::GetCursorScreenPos().x;
mousePos.y -= ImGui::GetCursorScreenPos().y;
// Bring mousePos to the top left of the viewport
mousePos.y += imageSize.y;
// Scale viewport coordinates to screen coordinates
mousePos.x = mousePos.x * width / imageSize.x;
mousePos.y = mousePos.y * height / imageSize.y;
PickingManager::instance().SetViewPortCursor(mousePos);
ImGui::EndChild();
ImGui::End();
}
void ImGuiEditorViewport::Shutdown()
{
}
void ImGuiEditorViewport::ShowGizmo(Entity& selectedentity)
{
if (g_engine.m_coordinator.ComponentExists<TransformComponent>(selectedentity))
{
auto& transform = g_engine.m_coordinator.GetComponent<TransformComponent>(selectedentity);
float gizmoMatrix[16]{};
float matrixScale[3]{}, matrixRotate[3]{}, matrixTranslate[3]{};
float buttonOffset = 21.0f;
ImVec2 m_Min = ImGui::GetWindowContentRegionMin();
ImVec2 m_Max = ImGui::GetWindowContentRegionMax();
ImVec2 imageSize = ImGui::GetContentRegionAvail();
ImVec2 mousePos = ImGui::GetMousePos();
m_Min.x += ImGui::GetWindowPos().x;
m_Min.y += ImGui::GetWindowPos().y;
m_Max.x += ImGui::GetWindowPos().x;
m_Max.y += ImGui::GetWindowPos().y;
const AABB& viewportArea = PickingManager::instance().GetViewPortArea();
matrixScale[0] = abs(transform.GetScale().x);
matrixScale[1] = abs(transform.GetScale().y);
matrixScale[2] = 1;
float width = m_Max.x - m_Min.x;
float height = m_Max.y - m_Min.y;
matrixRotate[2] = transform.GetRotation();
matrixTranslate[0] = transform.GetPosition().x;
matrixTranslate[1] = transform.GetPosition().y;
ImGuizmo::RecomposeMatrixFromComponents(matrixTranslate, matrixRotate, matrixScale, gizmoMatrix);
ImGuiIO& io = ImGui::GetIO();
ImVec2 size = ImGui::GetWindowSize();
ImGuizmo::SetRect(m_Min.x, m_Min.y + buttonOffset, imageSize.x, imageSize.y);
//ImGui::GetWindowDrawList()->PushClipRect(m_Min, m_Max, false);
//ImGui::GetWindowDrawList()->PushClipRect(m_Min, m_Max, false);
//ImGuizmo::SetDrawlist();
//if (mousePos.x < m_Min.x)
//{
// return;
//}
ImGuizmo::Manipulate(glm::value_ptr(g_engine.m_coordinator.GetSystem<CameraSystem>()->GetViewMatrix(1.0f)),glm::value_ptr( g_engine.GetProjMat()), m_CurrentGizmoOperation, ImGuizmo::LOCAL, gizmoMatrix, NULL);
ImGuizmo::DecomposeMatrixToComponents(gizmoMatrix, matrixTranslate, matrixRotate, matrixScale);
switch (m_CurrentGizmoOperation)
{
case ImGuizmo::OPERATION::TRANSLATE:
if (ImGuizmo::IsUsing())
{
Vec2 m_Translate{ matrixTranslate[0],matrixTranslate[1] };
g_engine.m_coordinator.GetComponent<TransformComponent>(selectedentity).setPosition(m_Translate);
}
break;
case ImGuizmo::OPERATION::ROTATE:
if (ImGuizmo::IsUsing())
{
g_engine.m_coordinator.GetComponent<TransformComponent>(selectedentity).setRotation(matrixRotate[2]);
}
break;
case ImGuizmo::OPERATION::SCALE:
if (ImGuizmo::IsUsing())
{
Vec2 m_Scale{ matrixScale[0],matrixScale[1] };
g_engine.m_coordinator.GetComponent<TransformComponent>(selectedentity).setScale(m_Scale);
}
break;
default:
break;
}
if (ImGuizmo::IsOver())
ImGuizmo::Enable(true);
else
ImGuizmo::Enable(false);
}
}
} | 33.750685 | 211 | 0.68577 | [
"transform"
] |
a13b0546a1f3eb9cc11f47d4081917964d159907 | 1,747 | hpp | C++ | include/rpc/msgpack/v3/object_fwd.hpp | agrawalamit2005/rpclib | cb84e2c64b6fe1a1ba8c399dad6479ec43382300 | [
"MIT"
] | null | null | null | include/rpc/msgpack/v3/object_fwd.hpp | agrawalamit2005/rpclib | cb84e2c64b6fe1a1ba8c399dad6479ec43382300 | [
"MIT"
] | null | null | null | include/rpc/msgpack/v3/object_fwd.hpp | agrawalamit2005/rpclib | cb84e2c64b6fe1a1ba8c399dad6479ec43382300 | [
"MIT"
] | null | null | null | //
// MessagePack for C++ static resolution routine
//
// Copyright (C) 2008-2018 FURUHASHI Sadayuki and KONDO Takatoshi
//
// Distributed under the Boost Software License, Version 1.0.
// (See accompanying file LICENSE_1_0.txt or copy at
// http://www.boost.org/LICENSE_1_0.txt)
//
#ifndef MSGPACK_V3_OBJECT_FWD_HPP
#define MSGPACK_V3_OBJECT_FWD_HPP
#include "rpc/msgpack/v3/object_fwd_decl.hpp"
#include "rpc/msgpack/object_fwd.hpp"
namespace clmdep_msgpack {
/// @cond
MSGPACK_API_VERSION_NAMESPACE(v3) {
/// @endcond
#if !defined(MSGPACK_USE_CPP03)
namespace adaptor {
// If v2 has as specialization for T, then dispatch v2::adaptor::as<T>.
// So I call v2::has_as<T> meta function intentionally.
template <typename T>
struct as<T, typename std::enable_if<v2::has_as<T>::value>::type> : v2::adaptor::as<T> {
};
} // namespace adaptor
template <typename T>
struct has_as {
private:
template <typename U>
static auto check(U*) ->
typename std::enable_if<
// check v3 specialization
std::is_same<
decltype(adaptor::as<U>()(std::declval<clmdep_msgpack::object>())),
U
>::value
||
// check v2 specialization
v2::has_as<U>::value
||
// check v1 specialization
v1::has_as<U>::value,
std::true_type
>::type;
template <typename...>
static std::false_type check(...);
public:
using type = decltype(check<T>(MSGPACK_NULLPTR));
static constexpr bool value = type::value;
};
#endif // !defined(MSGPACK_USE_CPP03)
/// @cond
} // MSGPACK_API_VERSION_NAMESPACE(v3)
/// @endcond
} // namespace clmdep_msgpack
#endif // MSGPACK_V3_OBJECT_FWD_HPP
| 24.605634 | 88 | 0.646251 | [
"object"
] |
a13cd223d2f57dd47404a4b3157136672f2e5f9b | 3,369 | cpp | C++ | src/ivium.cpp | ahpohl/convpot | f626cdf1a27e416ca2d8c67d63d6456285ce1839 | [
"MIT"
] | 2 | 2017-09-13T12:55:25.000Z | 2021-02-23T15:10:44.000Z | src/ivium.cpp | ahpohl/convpot | f626cdf1a27e416ca2d8c67d63d6456285ce1839 | [
"MIT"
] | 2 | 2017-09-14T01:23:43.000Z | 2017-10-06T18:46:35.000Z | src/ivium.cpp | ahpohl/convpot | f626cdf1a27e416ca2d8c67d63d6456285ce1839 | [
"MIT"
] | null | null | null | #include "util.h"
#include "device.h"
#include <iostream>
#include <fstream>
using namespace std;
// get file type, ivcure, eis, etc.
void Device::iviumParseFileType()
{
string line;
vector<string> tokens;
// check if ivium file, skip first line with binary data
getline( *reader, line );
getline( *reader, line );
if ( line.find("QR=", 0) == string::npos ) {
errorHandler(CodeFileNotValid, file -> name);
}
// default ivcurve, no keywords to check
file -> plot = args.plots[CodeIVCurve];
}
// get start time of data
void Device::iviumParseStartTime()
{
string line;
vector<string> tokens;
stringstream stream;
struct tm tm = {0};
reader -> seekg(0); // rewind
while ( ! reader -> eof() ) {
getline( *reader, line );
// parse date and time string
if ( line.find("starttime", 0) != string::npos ) {
util::tokenize(line, tokens, "=/: ");
tm.tm_mday = util::stringTo<time_t> (tokens.at(2));
tm.tm_mon = util::stringTo<time_t> (tokens.at(1));
tm.tm_year = util::stringTo<time_t> (tokens.at(3));
tm.tm_hour = util::stringTo<time_t> (tokens.at(4));
tm.tm_min = util::stringTo<time_t> (tokens.at(5));
tm.tm_sec = util::stringTo<time_t> (tokens.at(6));
break;
}
}
tm.tm_year -= 1900;
tm.tm_mon -= 1;
tm.tm_isdst = -1; // ignore dst
if (tokens.at(7) == "PM") {
tm.tm_hour += 12;
}
// save creation Date
file -> secs = mktime(&tm);
file -> date = asctime(&tm);
(file -> date).erase((file -> date).find_last_not_of("\n")+1);
}
void Device::iviumReadDataPoints()
{
string line;
vector<string> tokens;
rec_t* record;
size_t row = 0;
reader->seekg(0); // rewind
while ( ! reader->eof() ) {
getline( *reader, line );
// parse columns
if ( line.find("primary_data", 0) != string::npos ) {
for (int i = 0; i < 2; ++i) {
getline( *reader, line );
}
break;
}
}
while ( ! reader->eof() ) {
record = new rec_t({0});
getline( *reader, line );
tokens.clear();
util::tokenize(line, tokens, " ");
// skip empty lines
if (tokens.size() > 0) {
// test time + time offset
record->testTime = util::stringTo<double> (tokens.at(0)) + args.testTimeSum;
// test time + start time
record->secSinceEpoch = util::stringTo<time_t> (tokens.at(0)) + file->secs;
// current
record->current = util::stringTo<double> (tokens.at(1));
// voltage, working electrode
record->voltage = util::stringTo<double> (tokens.at(2));
record->dataPoint = row + args.recordsSum; // data point
record->fileId = file->id; // file id
record->localTime = ctime(&(record->secSinceEpoch)); // local time stamp in ctime format
(record->localTime).erase((record->localTime).find_last_not_of("\n")+1); // chop newline
// get step index
if (record->current > 1e-15) {
// charge
record->stepIndex = 1;
} else if (record->current < -1e-15) {
// discharge
record->stepIndex = -1;
} else {
// rest
record->stepIndex = 0;
}
// save record
recs.push_back(*record);
row++;
}
// free pointer
delete record;
}
// save global data
(file->recs) = row; // number data points in this file
(file->testTime) = (row == 0) ? 0 : recs.back().testTime - args.testTimeSum; // test time in this file
args.recordsSum += row; // total data points
args.testTimeSum += (file->testTime); // total test time
}
| 24.955556 | 103 | 0.61591 | [
"vector"
] |
a13f8ab4deae92b85465507a15c67a7f3f173867 | 26,270 | cpp | C++ | OpenGLFramework/SpaceShooter_LevelsEditor/MyPanel.cpp | PlayeRom/SpaceShooter | c284ca6503800ed1e45fc8ceeaf9d98d38917f30 | [
"MIT"
] | null | null | null | OpenGLFramework/SpaceShooter_LevelsEditor/MyPanel.cpp | PlayeRom/SpaceShooter | c284ca6503800ed1e45fc8ceeaf9d98d38917f30 | [
"MIT"
] | null | null | null | OpenGLFramework/SpaceShooter_LevelsEditor/MyPanel.cpp | PlayeRom/SpaceShooter | c284ca6503800ed1e45fc8ceeaf9d98d38917f30 | [
"MIT"
] | null | null | null | #include "StdAfx.h"
#include "MyFrame.h"
#include "LevelsManager.h"
#include "SelectObjectDlg.h"
#include "MyPanel.h"
//#include <vld.h>
BEGIN_EVENT_TABLE( CMyPanel, wxPanel )
EVT_LISTBOX( ID_EVENT_LISTBOX_LEVELS, CMyPanel::OnListBoxLevels )
EVT_LISTBOX( ID_EVENT_LISTBOX_GROUPS, CMyPanel::OnListBoxGroups )
EVT_CHECKBOX( ID_EVENT_CHECKBOX_ZIGZAGFLIGHT,CMyPanel::OnCheckBoxZigzagFlight )
EVT_CHECKBOX( ID_EVENT_CHECKBOX_SLANTFLIGHT, CMyPanel::OnCheckBoxSlantFlight )
EVT_BUTTON( ID_EVENT_BUTTON_INDEX_OF_BOSS, CMyPanel::OnButtonIndexOfBoss )
EVT_BUTTON( ID_EVENT_BUTTON_MOVEUP, CMyPanel::OnButtonMoveUp )
EVT_BUTTON( ID_EVENT_BUTTON_MOVEDOWN, CMyPanel::OnButtonMoveDown )
EVT_BUTTON( ID_EVENT_BUTTON_GROUP_ADD, CMyPanel::OnButtonGroupAdd )
EVT_BUTTON( ID_EVENT_BUTTON_GROUP_DELETE, CMyPanel::OnButtonGroupDelete )
EVT_BUTTON( ID_EVENT_BUTTON_GROUP_SAVEMOD, CMyPanel::OnButtonGroupSaveMod )
EVT_BUTTON( ID_EVENT_BUTTON_LEVEL_ADD, CMyPanel::OnButtonLevelAdd )
EVT_BUTTON( ID_EVENT_BUTTON_LEVEL_DELETE, CMyPanel::OnButtonLevelDelete )
EVT_BUTTON( ID_EVENT_BUTTON_LEVEL_SAVEMOD, CMyPanel::OnButtonLevelSaveMod )
EVT_BUTTON( ID_EVENT_BUTTON_INDEX_OF_OBJ, CMyPanel::OnButtonIndexOfObject )
END_EVENT_TABLE()
CMyPanel::CMyPanel( wxFrame *frame, const wxPoint& pos, const wxSize& size, long style )
: wxPanel( frame, wxID_ANY, pos, size, style )
{
m_bReady = false;
m_pMyFrame = ( CMyFrame* )frame;
( void )new wxStaticBox( this, wxID_ANY, _T("Loaded levels"), wxPoint( 5, 5 ), wxSize( 120, 500 ) );
m_pListBoxLevels = new wxListBox( this, ID_EVENT_LISTBOX_LEVELS, wxPoint( 15, 25 ), wxSize( 100, 400 ), 0, 0 );
m_pButtonMoveUp = new wxButton( this, ID_EVENT_BUTTON_MOVEUP, _T("Move up"), wxPoint( 15, 435 ), wxSize( 100, 24 ) );
m_pButtonMoveDown = new wxButton( this, ID_EVENT_BUTTON_MOVEDOWN, _T("Move down"), wxPoint( 15, 469 ), wxSize( 100, 24 ) );
wxColour colourReadOnly( 192, 192, 192 );
int iStartPosY = 5; //pozycja Y pierwszych kontrolek
int iOffsetPosY = 25;
int iLabelLength = 150; //dlugosc napisow przed edit boxami
int iLabelPosX = 5 + 130; //pozycja napisow przed edit boxami
int iEditPosX = iLabelPosX + iLabelLength + 5;//210; //pozycja X edit boxow
int iPosY = iStartPosY;
m_pLabelNumberOfLevel = new wxStaticText( this, wxID_ANY, _T("Number of level:"), wxPoint( iLabelPosX, iPosY ), wxSize( iLabelLength, 20 ), wxALIGN_RIGHT );
m_pTextCtrlNumberOfLevel = new wxTextCtrl( this, wxID_ANY, _T("0"), wxPoint( iEditPosX, iPosY ), wxDefaultSize, wxTE_READONLY );
m_pTextCtrlNumberOfLevel->SetBackgroundColour( colourReadOnly );
iPosY += iOffsetPosY;
//m_pLabelIndexOfBoss = new wxStaticText( this, wxID_ANY, _T("Index of boss:"), wxPoint( iLabelPosX, iPosY ), wxSize( iLabelLength, 20 ), wxALIGN_RIGHT );
m_pButtonIndexOfBoss = new wxButton( this, ID_EVENT_BUTTON_INDEX_OF_BOSS, _T("Index of boss:"), wxPoint( iLabelPosX, iPosY ), wxSize( 150, 20 ) );
m_pTextCtrlIndexOfBoss = new wxTextCtrl( this, wxID_ANY, _T("-1"), wxPoint( iEditPosX, iPosY ) );
m_pTextCtrlIndexOfBoss->SetToolTip( _T("When -1 then level without boss") );
//m_pCheckBoxWithBoss = new wxCheckBox( this, wxID_ANY, _T("Level with boss"), wxPoint( iEditPosX, iPosY ) );
iPosY += iOffsetPosY;
m_pLabelMaxObjOnScreen = new wxStaticText( this, wxID_ANY, _T("Max objects on screen:"), wxPoint( iLabelPosX, iPosY ), wxSize( iLabelLength, 20 ), wxALIGN_RIGHT );
m_pTextCtrlMaxObjOnScreen = new wxTextCtrl( this, wxID_ANY, _T("15"), wxPoint( iEditPosX, iPosY ) );
m_pTextCtrlMaxObjOnScreen->SetToolTip( _T("Expect integer between ~15 and ~35") );
iPosY += iOffsetPosY;
m_pLabelFrequencyOfShoot = new wxStaticText( this, wxID_ANY, _T("Frequency of shoot:"), wxPoint( iLabelPosX, iPosY ), wxSize( iLabelLength, 20 ), wxALIGN_RIGHT );
m_pTextCtrlFrequencyOfShoot = new wxTextCtrl( this, wxID_ANY, _T("0"), wxPoint( iEditPosX, iPosY ) );
m_pTextCtrlFrequencyOfShoot->SetToolTip( _T("Expect integer between 1 and 6. They value is smaller then quickly it shoots.") );
iPosY += iOffsetPosY;
m_pLabelChanceOnShot = new wxStaticText( this, wxID_ANY, _T("Chance on give shoot:"), wxPoint( iLabelPosX, iPosY ), wxSize( iLabelLength, 20 ), wxALIGN_RIGHT );
m_pTextCtrlChanceOnShot = new wxTextCtrl( this, wxID_ANY, _T("40"), wxPoint( iEditPosX, iPosY ) );
m_pTextCtrlChanceOnShot->SetToolTip( _T("Expect integer between 0 and 100. Suggested rand between 40% and 85%.") );
///////////////////////////////////
iPosY += ( iOffsetPosY * 5 );
m_pButtonAddLevel = new wxButton( this, ID_EVENT_BUTTON_LEVEL_ADD, _T("Add new level"), wxPoint( iEditPosX, iPosY ), wxSize( 150, 24 ) );
iPosY += iOffsetPosY + 5;
m_pButtonDeleteLevel = new wxButton( this, ID_EVENT_BUTTON_LEVEL_DELETE, _T("Delete selected level"), wxPoint( iEditPosX, iPosY ), wxSize( 150, 24 ) );
iPosY += iOffsetPosY + 5;
m_pButtonSaveModifyLevel = new wxButton( this, ID_EVENT_BUTTON_LEVEL_SAVEMOD, _T("Save modify for level"), wxPoint( iEditPosX, iPosY ), wxSize( 150, 24 ) );
//////////////////////////////////////
/////////////////////////////////////
iPosY = iStartPosY;
int iLabelPosX2 = iLabelPosX + iLabelLength + 100 + 100; //100 - dlugosc exit boxa
iLabelLength = 150;// nowa dlugosc label-a
int iEditPosX2 = iLabelPosX2 + iLabelLength + 5;
( void )new wxStaticBox( this, wxID_ANY, _T("Gropus of objects/ships"), wxPoint( iLabelPosX2 - 10, iPosY ), wxSize( 330, 450 ) );
iPosY += iOffsetPosY;
m_pLabelGroupsNumber = new wxStaticText( this, wxID_ANY, _T("Number of groups:"), wxPoint( iLabelPosX2, iPosY ), wxSize( iLabelLength, 20 ), wxALIGN_RIGHT );
m_pTextCtrlGroupsNumber = new wxTextCtrl( this, wxID_ANY, _T("0"), wxPoint( iEditPosX2, iPosY ), wxDefaultSize, wxTE_READONLY );
m_pTextCtrlGroupsNumber->SetBackgroundColour( colourReadOnly );
iPosY += iOffsetPosY;
m_pListBoxGroups = new wxListBox( this, ID_EVENT_LISTBOX_GROUPS, wxPoint( iEditPosX2, iPosY ), wxSize( 100, 60 ), 0, 0 );
iPosY += ( iOffsetPosY * 3 );
//m_pLabelGroupIndexOfObject = new wxStaticText( this, wxID_ANY, _T("Index of object:"), wxPoint( iLabelPosX2, iPosY ), wxSize( iLabelLength, 20 ), wxALIGN_RIGHT );
m_pButtonIndexOfObject = new wxButton( this, ID_EVENT_BUTTON_INDEX_OF_OBJ, _T("Index of object:"), wxPoint( iLabelPosX2, iPosY ), wxSize( 150, 20 ) );
m_pTextCtrlGroupIndexOfObject = new wxTextCtrl( this, wxID_ANY, _T("0"), wxPoint( iEditPosX2, iPosY ) );
m_pTextCtrlGroupIndexOfObject->SetToolTip( _T("Index of object from ships.dat file") );
iPosY += iOffsetPosY;
m_pLabelGroupNumberOfObjects = new wxStaticText( this, wxID_ANY, _T("Number of objects in group:"), wxPoint( iLabelPosX2, iPosY ), wxSize( iLabelLength, 20 ), wxALIGN_RIGHT );
m_pTextCtrlGroupNumberOfObjects = new wxTextCtrl( this, wxID_ANY, _T("60"), wxPoint( iEditPosX2, iPosY ) );
m_pTextCtrlGroupNumberOfObjects->SetToolTip( _T("Expect integer larger from 0.") );
iPosY += iOffsetPosY;
wxString strTypesOfFormation[] = { _T("1"), _T("2"), _T("3") };
m_pRadioGroupFormation = new wxRadioBox( this, wxID_ANY, _T("Type of formation"), wxPoint( iEditPosX2, iPosY ), wxDefaultSize, WXSIZEOF( strTypesOfFormation ), strTypesOfFormation, 0 );
iPosY += iOffsetPosY * 2;
//to jest "Pos X for rand"
m_pLabelGroupWidthOfFlying = new wxStaticText( this, wxID_ANY, _T("Width of flying the objects:"), wxPoint( iLabelPosX2, iPosY ), wxSize( iLabelLength, 20 ), wxALIGN_RIGHT );
m_pTextCtrlGroupWidthOfFlying = new wxTextCtrl( this, wxID_ANY, _T("242"), wxPoint( iEditPosX2, iPosY ) );
m_pTextCtrlGroupWidthOfFlying->SetToolTip( _T("Expect integer larger from 0. Standard: 242.") );
iPosY += iOffsetPosY;
m_pLabelGroupSpeed = new wxStaticText( this, wxID_ANY, _T("Speed:"), wxPoint( iLabelPosX2, iPosY ), wxSize( iLabelLength, 20 ), wxALIGN_RIGHT );
m_pTextCtrlGroupSpeed = new wxTextCtrl( this, wxID_ANY, _T("120.0"), wxPoint( iEditPosX2, iPosY ) );
m_pTextCtrlGroupSpeed->SetToolTip( _T("Expect float number. Suggested minimum: 120.0") );
iPosY += iOffsetPosY;
m_pCheckGroupZigzagFlight = new wxCheckBox( this, ID_EVENT_CHECKBOX_ZIGZAGFLIGHT, _T("Zigzag flight"), wxPoint( iEditPosX2, iPosY ) );
iPosY += iOffsetPosY;
m_pCheckBoxSlantFlight = new wxCheckBox( this, ID_EVENT_CHECKBOX_SLANTFLIGHT, _T("Slant flight"), wxPoint( iEditPosX2, iPosY ) );
iPosY += iOffsetPosY;
m_pLabelGroupOffsetForSlant = new wxStaticText( this, wxID_ANY, _T("Offset for slant:"), wxPoint( iLabelPosX2, iPosY ), wxSize( iLabelLength, 20 ), wxALIGN_RIGHT );
m_pTextCtrlOffsetForSlant = new wxTextCtrl( this, wxID_ANY, _T("605.0"), wxPoint( iEditPosX2, iPosY ) );
m_pTextCtrlOffsetForSlant->SetToolTip( _T("Expect float number. Standard: 605.0") );
iPosY += iOffsetPosY + 5;
m_pButtonGroupAdd = new wxButton( this, ID_EVENT_BUTTON_GROUP_ADD, _T("Add new group"), wxPoint( iEditPosX2, iPosY ), wxSize( 150, 24 ) );
iPosY += iOffsetPosY + 5;
m_pButtonGroupDelete = new wxButton( this, ID_EVENT_BUTTON_GROUP_DELETE, _T("Delete selected group"), wxPoint( iEditPosX2, iPosY ), wxSize( 150, 24 ) );
iPosY += iOffsetPosY + 5;
m_pButtonGroupSaveModify = new wxButton( this, ID_EVENT_BUTTON_GROUP_SAVEMOD, _T("Save modify for group"), wxPoint( iEditPosX2, iPosY ), wxSize( 150, 24 ) );
m_strFileName = FILE_NAME_LEVEL_EDIT2;
m_pLevelsManager = new CLevelsManager();
//m_pLevelsManager->ConvertStruct();
m_pSelectObjDlg = NULL;
m_bReady = true;
}
void CMyPanel::Initialize()
{
if( !FillLoadedLevelsList() )
m_pMyFrame->OpenFile( true );
SetItemLoadedLevelList( 0 );
}
CMyPanel::~CMyPanel()
{
delete m_pLevelsManager;
}
void CMyPanel::LoadLevels( wxString strFileName )
{
m_strFileName = strFileName;
FillLoadedLevelsList();
SetItemLoadedLevelList( 0 );
}
bool CMyPanel::FillLoadedLevelsList()
{
bool bLoadOK = m_pLevelsManager->LoadLevels( m_strFileName.c_str() );
m_pListBoxLevels->Clear();
for( int i = 0; i < m_pLevelsManager->GetLevelsSize(); ++i ) {
wxString str;
str.Printf( _T("%2d Level"), i );
m_pListBoxLevels->Append( str );
}
return bLoadOK;
}
void CMyPanel::FillGroupsList( int iIndexLevel )
{
ClearAllGroupsControls();
if( iIndexLevel == -1 )
iIndexLevel = m_pListBoxGroups->GetSelection();
if( iIndexLevel == -1 )
return;
wxString str;
for( int i = 0; i < m_pLevelsManager->GetLevel( iIndexLevel ).iNumberGroups; ++i ) {
str.Printf( _T("%2d Group"), i );
m_pListBoxGroups->Append( str );
}
}
void CMyPanel::SetItemLoadedLevelList( int iIndex )
{
if( iIndex < 0 || iIndex >= m_pLevelsManager->GetLevelsSize() )
return;
if( iIndex < static_cast<int>( m_pListBoxLevels->GetCount() ) )
m_pListBoxLevels->SetSelection( iIndex );
FillAllControls( iIndex );
}
void CMyPanel::SetItemGroupList( int iIndexLevel, int iIndexGroup )
{
if( iIndexLevel < 0 || iIndexLevel >= m_pLevelsManager->GetLevelsSize() )
return;
m_pCheckGroupZigzagFlight->Show( true );
m_pCheckBoxSlantFlight->Show( true );
m_pLabelGroupOffsetForSlant->Show( false );
m_pTextCtrlOffsetForSlant->Show( false );
if( iIndexGroup < 0 || iIndexGroup >= m_pLevelsManager->GetLevel( iIndexLevel ).iNumberGroups )
return;
if( iIndexGroup < static_cast<int>( m_pListBoxGroups->GetCount() ) )
m_pListBoxGroups->SetSelection( iIndexGroup );
FillAllControlsForGroup( iIndexLevel, iIndexGroup );
}
void CMyPanel::FillAllControls( int iIndex )
{
wxString str;
//UWAGA numer poziomu obliczamy z indeksu a nie podajemy bezposrednio
//aby zmienic numer poziomu nalezy uzyc kalwiszy MoveUp i MoveDown
//str.Printf( _T("%d"), m_pLevelsManager->GetLevel( iIndex ).iLevel );
str.Printf( _T("%d"), iIndex + 1 );
m_pTextCtrlNumberOfLevel->SetValue( str );
//if( m_pLevelsManager->GetLevel( iIndex ).bWithBoss )
// m_pCheckBoxWithBoss->SetValue( true );
//else
// m_pCheckBoxWithBoss->SetValue( false );
str.Printf( _T("%d"), m_pLevelsManager->GetLevel( iIndex ).iIndexBoss );
m_pTextCtrlIndexOfBoss->SetValue( str );
str.Printf( _T("%d"), m_pLevelsManager->GetLevel( iIndex ).iMaxShipsOnScreen );
m_pTextCtrlMaxObjOnScreen->SetValue( str );
str.Printf( _T("%d"), m_pLevelsManager->GetLevel( iIndex ).iFrequencyShoot );
m_pTextCtrlFrequencyOfShoot->SetValue( str );
str.Printf( _T("%d"), m_pLevelsManager->GetLevel( iIndex ).iPercentChanceToShoot );
m_pTextCtrlChanceOnShot->SetValue( str );
//////////////////////////////////////////////////////
//////////// ustaw emitery ///////////////////////////
str.Printf( _T("%d"), m_pLevelsManager->GetLevel( iIndex ).iNumberGroups );
m_pTextCtrlGroupsNumber->SetValue( str );
FillGroupsList( iIndex );
SetItemGroupList( iIndex, 0 );
}
void CMyPanel::FillAllControlsForGroup( int iIndexLevel, int iIndexGroup )
{
wxString str;
str.Printf( _T("%d"), m_pLevelsManager->GetLevel( iIndexLevel ).iNumberGroups );
m_pTextCtrlGroupsNumber->SetValue( str );
str.Printf( _T("%d"), m_pLevelsManager->GetLevel( iIndexLevel ).psShipsGroups[ iIndexGroup].iIndexShip );
m_pTextCtrlGroupIndexOfObject->SetValue( str );
str.Printf( _T("%d"), m_pLevelsManager->GetLevel( iIndexLevel ).psShipsGroups[ iIndexGroup].iNumberShips );
m_pTextCtrlGroupNumberOfObjects->SetValue( str );
m_pRadioGroupFormation->SetSelection( m_pLevelsManager->GetLevel( iIndexLevel ).psShipsGroups[ iIndexGroup].iFormation - 1 );
str.Printf( _T("%d"), m_pLevelsManager->GetLevel( iIndexLevel ).psShipsGroups[ iIndexGroup].iPosXForRand );
m_pTextCtrlGroupWidthOfFlying->SetValue( str );
str.Printf( _T("%f"), m_pLevelsManager->GetLevel( iIndexLevel ).psShipsGroups[ iIndexGroup].fSpeed );
m_pTextCtrlGroupSpeed->SetValue( str );
if( m_pLevelsManager->GetLevel( iIndexLevel ).psShipsGroups[ iIndexGroup].bCosFly )
m_pCheckGroupZigzagFlight->SetValue( true );
else
m_pCheckGroupZigzagFlight->SetValue( false );
if( m_pLevelsManager->GetLevel( iIndexLevel ).psShipsGroups[ iIndexGroup].bSlantFly )
m_pCheckBoxSlantFlight->SetValue( true );
else
m_pCheckBoxSlantFlight->SetValue( false );
str.Printf( _T("%f"), m_pLevelsManager->GetLevel( iIndexLevel ).psShipsGroups[ iIndexGroup].fOffsetXPosForSlantFly );
m_pTextCtrlOffsetForSlant->SetValue( str );
m_pCheckGroupZigzagFlight->Show( true );
m_pCheckBoxSlantFlight->Show( true );
m_pLabelGroupOffsetForSlant->Show( true );
m_pTextCtrlOffsetForSlant->Show( true );
wxCommandEvent eEvent;
OnCheckBoxZigzagFlight( eEvent );
OnCheckBoxSlantFlight( eEvent );
}
void CMyPanel::ClearAllGroupsControls()
{
m_pListBoxGroups->Clear();
m_pTextCtrlGroupIndexOfObject->SetValue( _T("0") );
m_pTextCtrlGroupNumberOfObjects->SetValue( _T("60") );
m_pRadioGroupFormation->SetSelection( 0 );
m_pTextCtrlGroupWidthOfFlying->SetValue( _T("242") );
m_pTextCtrlGroupSpeed->SetValue( _T("120.0") );
m_pCheckGroupZigzagFlight->SetValue( false );
m_pCheckBoxSlantFlight->SetValue( false );
m_pTextCtrlOffsetForSlant->SetValue( _T("605.0") );
}
void CMyPanel::OnListBoxLevels( wxCommandEvent &eEvent )
{
SetItemLoadedLevelList( eEvent.GetInt() );
}
void CMyPanel::OnListBoxGroups( wxCommandEvent &eEvent )
{
SetItemGroupList( m_pListBoxLevels->GetSelection(), eEvent.GetInt() );
}
void CMyPanel::OnCheckBoxZigzagFlight( wxCommandEvent &WXUNUSED( eEvent ) )
{
if( m_pCheckGroupZigzagFlight->GetValue() ) {
m_pCheckBoxSlantFlight->Show( false );
m_pCheckBoxSlantFlight->SetValue( false );
}
else {
m_pCheckBoxSlantFlight->Show( true );
}
}
void CMyPanel::OnCheckBoxSlantFlight( wxCommandEvent &WXUNUSED( eEvent ) )
{
if( m_pCheckBoxSlantFlight->GetValue() ) {
m_pTextCtrlOffsetForSlant->Show( true );
if(_wtof( m_pTextCtrlOffsetForSlant->GetValue() ) == 0.0f )
m_pTextCtrlOffsetForSlant->SetValue( _T("605.0") );
m_pLabelGroupOffsetForSlant->Show( true );
m_pCheckGroupZigzagFlight->Show( false );
m_pCheckGroupZigzagFlight->SetValue( false );
}
else {
m_pTextCtrlOffsetForSlant->Show( false );
m_pLabelGroupOffsetForSlant->Show( false );
m_pCheckGroupZigzagFlight->Show( true );
}
}
CSelectObjectDlg* CMyPanel::CreateDialog( int iActualIndex, const wxString& strName )
{
m_strArrayChoices.Clear();
for( int i = 0; i < m_pLevelsManager->GetShipsNumber(); ++i ) {
wxString strIndex;
strIndex.Printf( _T("%d. "), i );
m_strArrayChoices.Add( strIndex + wxString( m_pLevelsManager->GetShipName( i ) ) );
}
return new CSelectObjectDlg( iActualIndex, m_strArrayChoices, this, -1, strName, wxPoint( -1, -1 ), wxSize( 240, 110 ), wxCAPTION|wxSYSTEM_MENU );
}
void CMyPanel::OnButtonIndexOfBoss( wxCommandEvent &WXUNUSED( eEvent ) )
{
int iActualIndexOfBoss = _wtoi( m_pTextCtrlIndexOfBoss->GetValue() );
m_pSelectObjDlg = CreateDialog( iActualIndexOfBoss, _T("Select object") );
int iResult = m_pSelectObjDlg->ShowModal();
if( iResult > -1 ) {
wxString value;
value.Printf( _T("%d"), iResult );
m_pTextCtrlIndexOfBoss->SetValue( value );
}
m_pSelectObjDlg->Destroy();
m_strArrayChoices.Clear();
}
void CMyPanel::OnButtonIndexOfObject( wxCommandEvent &WXUNUSED( eEvent ) )
{
int iActualIndexOfObj = _wtoi( m_pTextCtrlGroupIndexOfObject->GetValue() );
m_pSelectObjDlg = CreateDialog( iActualIndexOfObj, _T("Select object") );
int iResult = m_pSelectObjDlg->ShowModal();
if( iResult > -1 ) {
wxString value;
value.Printf( _T("%d"), iResult );
m_pTextCtrlGroupIndexOfObject->SetValue( value );
}
m_pSelectObjDlg->Destroy();
m_strArrayChoices.Clear();
}
void CMyPanel::OnButtonMoveUp( wxCommandEvent &WXUNUSED( eEvent ) )
{
int iIndex = m_pListBoxLevels->GetSelection();
if( m_pLevelsManager->MoveUpIndex( iIndex ) ) {
FillLoadedLevelsList();
SetItemLoadedLevelList( --iIndex );
}
}
void CMyPanel::OnButtonMoveDown( wxCommandEvent &WXUNUSED( eEvent ) )
{
int iIndex = m_pListBoxLevels->GetSelection();
if( m_pLevelsManager->MoveDownIndex( iIndex ) ) {
FillLoadedLevelsList();
SetItemLoadedLevelList( ++iIndex );
}
}
bool CMyPanel::CheckCorrectnessGroupControl()
{
if( !CheckWhetherStringIsInteger( m_pTextCtrlGroupIndexOfObject->GetValue() ) )
return false;
if( !CheckWhetherStringIsInteger( m_pTextCtrlGroupNumberOfObjects->GetValue() ) )
return false;
if( !CheckWhetherStringIsInteger( m_pTextCtrlGroupWidthOfFlying->GetValue() ) )
return false;
if( !CheckWhetherStringIsFloat( m_pTextCtrlGroupSpeed->GetValue() ) )
return false;
if( m_pCheckBoxSlantFlight->GetValue() ) {
if( !CheckWhetherStringIsFloat( m_pTextCtrlOffsetForSlant->GetValue() ) )
return false;
}
if(_wtoi( m_pTextCtrlGroupNumberOfObjects->GetValue() ) <= 0 ) {
wxMessageBox( _T("Value for \"Number of objects in group\" must be larger from 0"), _T("Incorrect data"), wxOK | wxICON_EXCLAMATION );
return false;
}
if(_wtoi( m_pTextCtrlGroupWidthOfFlying->GetValue() ) <= 0 ) {
wxMessageBox( _T("Value for \"Width of flying the objects\" must be larger from 0"), _T("Incorrect data"), wxOK | wxICON_EXCLAMATION );
return false;
}
return true;
}
void CMyPanel::FillStructGroup( SShipsGroups &sGroup )
{
sGroup.iIndexShip = _wtoi( m_pTextCtrlGroupIndexOfObject->GetValue() );
sGroup.iNumberShips = _wtoi( m_pTextCtrlGroupNumberOfObjects->GetValue() );
sGroup.iFormation = m_pRadioGroupFormation->GetSelection() + 1;
sGroup.iPosXForRand = _wtoi( m_pTextCtrlGroupWidthOfFlying->GetValue() );
sGroup.fSpeed = _wtof( m_pTextCtrlGroupSpeed->GetValue() );
sGroup.bCosFly = m_pCheckGroupZigzagFlight->GetValue();
if( sGroup.bCosFly ) {
sGroup.bSlantFly = 0;
sGroup.fOffsetXPosForSlantFly = 0.0f;
}
else {
sGroup.bSlantFly = m_pCheckBoxSlantFlight->GetValue();
if( sGroup.bSlantFly )
sGroup.fOffsetXPosForSlantFly = _wtof( m_pTextCtrlOffsetForSlant->GetValue() );
else
sGroup.fOffsetXPosForSlantFly = 0.0f;
}
}
void CMyPanel::OnButtonGroupAdd( wxCommandEvent &WXUNUSED( eEvent ) )
{
if( wxMessageBox( _T("From current data in controls will be created new group. Do you want to continue?"), _T("Add new group"), wxYES_NO|wxICON_QUESTION ) == wxNO )
return;
if( !CheckCorrectnessGroupControl() )
return;
//wypelnij strukture danymi
SShipsGroups sNewGroup;
FillStructGroup( sNewGroup );
if( m_pLevelsManager->AddNewGroup( m_pListBoxLevels->GetSelection(), sNewGroup ) ) {
int iIndexLevel = m_pListBoxLevels->GetSelection();
int iIndexGroup = m_pLevelsManager->GetLevel( iIndexLevel ).iNumberGroups - 1;
FillGroupsList( iIndexLevel );
SetItemGroupList( iIndexLevel, iIndexGroup );
}
}
void CMyPanel::OnButtonGroupDelete( wxCommandEvent &WXUNUSED( eEvent ) )
{
if( m_pListBoxGroups->GetCount() <= 0 ) {
wxMessageBox( _T("List of groups is empty."), _T("Delete Group"), wxOK | wxICON_INFORMATION );
return;
}
if( wxMessageBox( _T("Do you want to delete selected group?"), _T("Delete group"), wxYES_NO|wxICON_QUESTION ) == wxNO )
return;
if( m_pLevelsManager->DeleteGroup( m_pListBoxLevels->GetSelection(), m_pListBoxGroups->GetSelection() ) ) {
int iIndexLevel = m_pListBoxLevels->GetSelection();
FillGroupsList( iIndexLevel );
SetItemGroupList( iIndexLevel, 0 );
//ustaw ilosc emiterow na zero jezeli jest 0 to przy fill nie sutawia bo nie dojdzie
if( m_pLevelsManager->GetLevel( iIndexLevel ).iNumberGroups == 0 )
m_pTextCtrlGroupsNumber->SetValue( _T("0") );
}
}
void CMyPanel::OnButtonGroupSaveMod( wxCommandEvent &WXUNUSED( eEvent ) )
{
if( m_pListBoxGroups->GetCount() <= 0 ) {
wxMessageBox( _T("List of groups is empty."), _T("Save modify group"), wxOK | wxICON_INFORMATION );
return;
}
if( wxMessageBox( _T("Do you want to save modify of selected group?"), _T("Save modify group"), wxYES_NO|wxICON_QUESTION ) == wxNO )
return;
if( !CheckCorrectnessGroupControl() )
return;
//wypelnij strukture danymi
SShipsGroups sNewGroup;
FillStructGroup( sNewGroup );
m_pLevelsManager->SaveModifyGroup(
m_pListBoxLevels->GetSelection(),
m_pListBoxGroups->GetSelection(),
sNewGroup );
}
bool CMyPanel::CheckCorrectnessLevelControl()
{
if( !CheckWhetherStringIsInteger( m_pTextCtrlMaxObjOnScreen->GetValue() ) )
return false;
if( !CheckWhetherStringIsInteger( m_pTextCtrlFrequencyOfShoot->GetValue() ) )
return false;
if( !CheckWhetherStringIsInteger( m_pTextCtrlChanceOnShot->GetValue() ) )
return false;
if(_wtoi( m_pTextCtrlMaxObjOnScreen->GetValue() ) <= 0 ) {
wxMessageBox( _T("Value for \"Max objects on screen\" must be larger from 0"), _T("Incorrect data"), wxOK | wxICON_EXCLAMATION );
return false;
}
if(_wtoi( m_pTextCtrlFrequencyOfShoot->GetValue() ) < 1 || _wtoi( m_pTextCtrlFrequencyOfShoot->GetValue() ) > 6 ) {
wxMessageBox( _T("Value for \"Frequency of shoot\" must be between 1 and 6"), _T("Incorrect data"), wxOK | wxICON_EXCLAMATION );
return false;
}
return true;
}
void CMyPanel::FillStructLevel( SLevel &sLevel )
{
wxString str;
sLevel.iLevel = m_pListBoxLevels->GetSelection() + 1;
//sLevel.bWithBoss = m_pCheckBoxWithBoss->GetValue();
sLevel.iIndexBoss = _wtoi( m_pTextCtrlIndexOfBoss->GetValue() );
sLevel.iMaxShipsOnScreen = _wtoi( m_pTextCtrlMaxObjOnScreen->GetValue() );
sLevel.iFrequencyShoot = _wtoi( m_pTextCtrlFrequencyOfShoot->GetValue() );
sLevel.iPercentChanceToShoot = _wtoi( m_pTextCtrlChanceOnShot->GetValue() );
}
void CMyPanel::OnButtonLevelAdd( wxCommandEvent &WXUNUSED( eEvent ) )
{
if( wxMessageBox( _T("From current data in controls will be created new level. Do you want to continue?"), _T("Add new level"), wxYES_NO|wxICON_QUESTION ) == wxNO )
return;
if( !CheckCorrectnessLevelControl() )
return;
//wypelnij strukture danymi
SLevel sLevel;
FillStructLevel( sLevel );
sLevel.iNumberGroups = 0;
sLevel.psShipsGroups = NULL;
if( m_pLevelsManager->AddNewLevel( sLevel ) ) {
FillLoadedLevelsList();
SetItemLoadedLevelList( m_pListBoxLevels->GetCount() - 1 );
}
}
void CMyPanel::OnButtonLevelDelete( wxCommandEvent &WXUNUSED( eEvent ) )
{
if( m_pListBoxLevels->GetCount() <= 0 ) {
wxMessageBox( _T("List of levels is empty."), _T("Delete level"), wxOK | wxICON_INFORMATION );
return;
}
if( wxMessageBox( _T("Do you want to delete selected level?"), _T("Delete level"), wxYES_NO|wxICON_QUESTION ) == wxNO )
return;
if( m_pLevelsManager->DeleteLevel( m_pListBoxLevels->GetSelection() ) ) {
FillLoadedLevelsList();
SetItemLoadedLevelList( 0 );
}
}
void CMyPanel::OnButtonLevelSaveMod( wxCommandEvent &WXUNUSED( eEvent ) )
{
if( m_pListBoxLevels->GetCount() <= 0 ) {
wxMessageBox( _T("List of levels is empty."), _T("Save modify level"), wxOK | wxICON_INFORMATION );
return;
}
if( wxMessageBox( _T("Do you want to save modify of selected level?"), _T("Save modify level"), wxYES_NO|wxICON_QUESTION ) == wxNO )
return;
if( !CheckCorrectnessLevelControl() )
return;
SLevel sLevel;
FillStructLevel( sLevel );
int iIndexLevel = m_pListBoxLevels->GetSelection();
if( m_pLevelsManager->SaveModifyLevel( iIndexLevel, sLevel ) ) {
FillLoadedLevelsList();
SetItemLoadedLevelList( iIndexLevel );
}
}
bool CMyPanel::CheckWhetherStringIsFloat( wxString strSrc )
{
for( size_t i = 0; i < strSrc.Length(); ++i ) {
switch( strSrc[ i ] ) {
case '0':
case '1':
case '2':
case '3':
case '4':
case '5':
case '6':
case '7':
case '8':
case '9':
case '.':
case '-':
break;
default:
wxMessageBox( strSrc + _T(" - it is not float number!"), _T("Incorrect data"), wxOK | wxICON_EXCLAMATION );
return false;
}
}
return true;
}
bool CMyPanel::CheckWhetherStringIsInteger( wxString strSrc )
{
for( size_t i = 0; i < strSrc.Length(); ++i ) {
switch( strSrc[ i ] ) {
case '0':
case '1':
case '2':
case '3':
case '4':
case '5':
case '6':
case '7':
case '8':
case '9':
case '-':
break;
default:
wxMessageBox( strSrc + _T(" - it is not integer!"), _T("Incorrect data"), wxOK | wxICON_EXCLAMATION );
return false;
}
}
return true;
} | 40.045732 | 187 | 0.712828 | [
"object"
] |
a142aeb8b8984ff6e1563c4621c972f00b4027de | 4,931 | hxx | C++ | main/drawinglayer/inc/drawinglayer/primitive2d/controlprimitive2d.hxx | Grosskopf/openoffice | 93df6e8a695d5e3eac16f3ad5e9ade1b963ab8d7 | [
"Apache-2.0"
] | 679 | 2015-01-06T06:34:58.000Z | 2022-03-30T01:06:03.000Z | main/drawinglayer/inc/drawinglayer/primitive2d/controlprimitive2d.hxx | Grosskopf/openoffice | 93df6e8a695d5e3eac16f3ad5e9ade1b963ab8d7 | [
"Apache-2.0"
] | 102 | 2017-11-07T08:51:31.000Z | 2022-03-17T12:13:49.000Z | main/drawinglayer/inc/drawinglayer/primitive2d/controlprimitive2d.hxx | 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.
*
*************************************************************/
#ifndef INCLUDED_DRAWINGLAYER_PRIMITIVE2D_CONTROLPRIMITIVE2D_HXX
#define INCLUDED_DRAWINGLAYER_PRIMITIVE2D_CONTROLPRIMITIVE2D_HXX
#include <drawinglayer/drawinglayerdllapi.h>
#include <drawinglayer/primitive2d/baseprimitive2d.hxx>
#include <basegfx/matrix/b2dhommatrix.hxx>
#include <com/sun/star/awt/XControlModel.hpp>
#include <com/sun/star/awt/XControl.hpp>
//////////////////////////////////////////////////////////////////////////////
namespace drawinglayer
{
namespace primitive2d
{
/** ControlPrimitive2D class
Base class for ControlPrimitive handling. It decoposes to a
graphical representation (Bitmap data) of the control. This
representation is limited to a quadratic pixel maximum defined
in the applicatin settings.
*/
class DRAWINGLAYER_DLLPUBLIC ControlPrimitive2D : public BufferedDecompositionPrimitive2D
{
private:
/// object's base data
basegfx::B2DHomMatrix maTransform;
com::sun::star::uno::Reference< com::sun::star::awt::XControlModel > mxControlModel;
/// the created an cached awt::XControl
com::sun::star::uno::Reference< com::sun::star::awt::XControl > mxXControl;
/// the last used scaling, used from getDecomposition for buffering
basegfx::B2DVector maLastViewScaling;
/** used from getXControl() to create a local awt::XControl which is remembered in mxXControl
and from thereon always used and returned by getXControl()
*/
void createXControl();
/// single local decompositions, used from create2DDecomposition()
Primitive2DReference createBitmapDecomposition(const geometry::ViewInformation2D& rViewInformation) const;
Primitive2DReference createPlaceholderDecomposition(const geometry::ViewInformation2D& rViewInformation) const;
protected:
/// local decomposition
virtual Primitive2DSequence create2DDecomposition(const geometry::ViewInformation2D& rViewInformation) const;
public:
/// constructor
ControlPrimitive2D(
const basegfx::B2DHomMatrix& rTransform,
const com::sun::star::uno::Reference< com::sun::star::awt::XControlModel >& rxControlModel);
/** constructor with an additional XControl as parameter to allow to hand it over at incarnation time
if it exists. This will avoid to create a 2nd one on demand in createXControl()
and thus double the XControls.
*/
ControlPrimitive2D(
const basegfx::B2DHomMatrix& rTransform,
const com::sun::star::uno::Reference< com::sun::star::awt::XControlModel >& rxControlModel,
const com::sun::star::uno::Reference< com::sun::star::awt::XControl >& rxXControl);
/// data read access
const basegfx::B2DHomMatrix& getTransform() const { return maTransform; }
const com::sun::star::uno::Reference< com::sun::star::awt::XControlModel >& getControlModel() const { return mxControlModel; }
/** mxControl access. This will on demand create the awt::XControl using createXControl()
if it does not exist. It may already have been created or even handed over at
incarnation
*/
const com::sun::star::uno::Reference< com::sun::star::awt::XControl >& getXControl() const;
/// compare operator
virtual bool operator==(const BasePrimitive2D& rPrimitive) const;
/// get range
virtual basegfx::B2DRange getB2DRange(const geometry::ViewInformation2D& rViewInformation) const;
/// provide unique ID
DeclPrimitrive2DIDBlock()
/// Overload standard getDecomposition call to be view-dependent here
virtual Primitive2DSequence get2DDecomposition(const geometry::ViewInformation2D& rViewInformation) const;
};
} // end of namespace primitive2d
} // end of namespace drawinglayer
//////////////////////////////////////////////////////////////////////////////
#endif // INCLUDED_DRAWINGLAYER_PRIMITIVE2D_CONTROLPRIMITIVE2D_HXX
//////////////////////////////////////////////////////////////////////////////
// eof
| 41.788136 | 129 | 0.681201 | [
"geometry",
"object"
] |
a14514071f93c144c4fea8a1550f1a3bf981d221 | 6,328 | cpp | C++ | src/GameState/GHud.cpp | isabella232/modite-adventure | 66c7779271706ec35e0a2f808afe92d7e15e0f85 | [
"MIT"
] | 5 | 2020-12-02T12:28:14.000Z | 2021-02-16T18:02:09.000Z | src/GameState/GHud.cpp | pedrohyvo/modite-adventure | 8c273803bd60747a169be3ba3f06b3419cc0ebff | [
"MIT"
] | 2 | 2021-01-22T18:51:48.000Z | 2021-01-28T18:43:43.000Z | src/GameState/GHud.cpp | pedrohyvo/modite-adventure | 8c273803bd60747a169be3ba3f06b3419cc0ebff | [
"MIT"
] | 2 | 2021-01-26T23:22:36.000Z | 2021-02-03T10:07:03.000Z | #include <Display.h>
#include <BViewPort.h>
#include "GResources.h"
#include "BResourceManager.h"
#include "GPlayer.h"
#include "GHud.h"
#include "Items.h"
#include "Game.h"
#include "GBossProcess.h"
static const TRect heart(0, 384, 15, 399);
static const TRect magic(16, 384, 31, 399);
static const TRect sword(0, 400, 15, 415);
static const TRect water(32, 384, 47, 399);
static const TRect fire(48, 384, 48 + 15, 399);
static const TRect earth(32, 400, 32 + 15, 415);
static const TRect energy(48, 400, 48 + 15, 415);
static const TRect silver_key(64, 384, 79,399);
static const TRect gold_key(64, 400, 79, 415);
// meter width:
// 26, 70
static const TInt METER_WIDTH = 60;
static const TInt METER_HEIGHT = 12;
static const TInt STAT_WIDTH = 200;
static void render_meter(BViewPort *vp, BBitmap *screen, TUint8 color, TInt x, TInt y, TFloat value, TFloat max) {
TFloat pct = (value / max);
const TInt innerWidth = METER_WIDTH - 2;
TInt w = (TInt)(pct * innerWidth);
if (w < 2) {
w = 2;
}
screen->DrawRect(vp, x, y, x + METER_WIDTH - 1, y + METER_HEIGHT - 1, COLOR_METER_OUTLINE);
screen->DrawFastHLine(vp, x + 1, y + 1, w, color);
screen->FillRect(vp, x + 1, y + 2, x + w, y + METER_HEIGHT - 2, TUint8(color + 1));
// erase the corners
screen->DrawFastHLine(vp, x, y, 2, COLOR_HUD_BG);
screen->DrawFastVLine(vp, x, y, 2, COLOR_HUD_BG);
screen->DrawFastHLine(vp, x + METER_WIDTH - 2, y, 2, COLOR_HUD_BG);
screen->DrawFastVLine(vp, x + METER_WIDTH - 1, y, 2, COLOR_HUD_BG);
screen->DrawFastHLine(vp, x, y + METER_HEIGHT - 1, 2, COLOR_HUD_BG);
screen->DrawFastVLine(vp, x, y + METER_HEIGHT - 2, 2, COLOR_HUD_BG);
screen->DrawFastHLine(vp, x + METER_WIDTH - 2, y + METER_HEIGHT - 1, 2, COLOR_HUD_BG);
screen->DrawFastVLine(vp, x + METER_WIDTH - 1, y + METER_HEIGHT - 2, 2, COLOR_HUD_BG);
// draw the 4 pixels to round off the oval
screen->WritePixel(x + 1, y + 1, COLOR_METER_OUTLINE);
screen->WritePixel(x + METER_WIDTH - 2, y + 1, COLOR_METER_OUTLINE);
screen->WritePixel(x + 1, y + METER_HEIGHT - 2, COLOR_METER_OUTLINE);
screen->WritePixel(x + METER_WIDTH - 2, y + METER_HEIGHT - 2, COLOR_METER_OUTLINE);
}
static TUint32 frame = 0;
static TBool darkHealth = EFalse;
void GHud::SetColors() {
frame = 0;
// printf("GHud::SetColors()\n");
gDisplay.renderBitmap->SetColor(COLOR_HUD_BG, 0, 0, 0);
gDisplay.renderBitmap->SetColor(COLOR_METER_OUTLINE, 64, 64, 64); // outline color for meter
gDisplay.renderBitmap->SetColor(COLOR_HEALTH, 0xf9, 0xa4, 0xa1); // light
gDisplay.renderBitmap->SetColor(COLOR_HEALTH2, 0xff, 0x59, 0x43); // dark
gDisplay.renderBitmap->SetColor(COLOR_MAGIC, 0x63, 0xab, 0xf1); // light
gDisplay.renderBitmap->SetColor(COLOR_MAGIC2, 0x43, 0x7b, 0xf0); // dark
gDisplay.renderBitmap->SetColor(COLOR_EXPERIENCE, 0x6c, 0xd8, 0x20); // light
gDisplay.renderBitmap->SetColor(COLOR_EXPERIENCE2, 0x2d, 0xa1, 0x2f); // dark
}
void GHud::Render() {
BBitmap *b = gResourceManager.GetBitmap(ENVIRONMENT_SLOT),
*screen = gDisplay.renderBitmap;
BViewPort vp;
TRect rect(0, 0, SCREEN_WIDTH - 1, 15);
vp.SetRect(rect);
gDisplay.renderBitmap->FillRect(&vp, vp.mRect, COLOR_HUD_BG);
screen->DrawBitmapTransparent(&vp, b, heart, 8, 0);
TFloat healthPct = (TFloat)GPlayer::mHitPoints / (TFloat)GPlayer::mMaxHitPoints;
frame++;
if (healthPct < .10f && frame % 30 == 0) {
darkHealth = ! darkHealth;
if (darkHealth && gGame->GetState() == GAME_STATE_GAME) {
gSoundPlayer.TriggerSfx(SFX_PLAYER_LOW_HEALTH_WAV, 2);
}
}
if (darkHealth && healthPct > .10f) {
darkHealth = EFalse;
}
if (darkHealth) {
gDisplay.renderBitmap->SetColor(COLOR_HEALTH, 0xf9 - 50, 0xa4 - 50, 0xa1 - 50);
gDisplay.renderBitmap->SetColor(COLOR_HEALTH2, 0xff - 50, 0x59 - 50, 0x43 - 50); // dark
}
else{
gDisplay.renderBitmap->SetColor(COLOR_HEALTH, 0xf9, 0xa4, 0xa1);
gDisplay.renderBitmap->SetColor(COLOR_HEALTH2, 0xff, 0x59, 0x43); // dark
}
render_meter(&vp, screen, COLOR_HEALTH, 26, 2, GPlayer::mHitPoints, GPlayer::mMaxHitPoints);
screen->DrawBitmapTransparent(&vp, b, magic, 91, 0);
render_meter(&vp, screen, COLOR_MAGIC, 105, 2, GPlayer::mManaPotion, GPlayer::mMaxMana);
screen->DrawBitmapTransparent(&vp, b, sword, 168, 0);
render_meter(&vp, screen, COLOR_EXPERIENCE, 169 + 20, 2, GPlayer::mExperience, GPlayer::mNextLevel);
switch (GPlayer::mEquipped.mSpellBookElement) {
case ELEMENT_WATER:
screen->DrawBitmapTransparent(&vp, b, water, 249, 0);
break;
case ELEMENT_FIRE:
screen->DrawBitmapTransparent(&vp, b, energy, 249, 0);
break;
case ELEMENT_ENERGY:
screen->DrawBitmapTransparent(&vp, b, fire, 249, 0);
break;
case ELEMENT_EARTH:
screen->DrawBitmapTransparent(&vp, b, earth, 249, 0);
break;
default:
break;
}
if (GPlayer::mInventoryList.FindItem(ITEM_SILVER_KEY)) {
screen->DrawBitmapTransparent(&vp, b, silver_key, 278, 0);
}
if (GPlayer::mInventoryList.FindItem(ITEM_GOLD_KEY)) {
screen->DrawBitmapTransparent(&vp, b, gold_key, 294, 0);
}
GBossProcess *boss = GPlayer::mActiveBoss;
if (boss) {
TInt h = gViewPort->mRect.Height();
for (TInt i = 1; i <= boss->mHealthBarCount; i++) {
gDisplay.renderBitmap->DrawFastHLine(gViewPort, 21, h - 11, STAT_WIDTH + 1, COLOR_METER_OUTLINE);
gDisplay.renderBitmap->DrawFastVLine(gViewPort, 22 + STAT_WIDTH, h - 15, 5, COLOR_METER_OUTLINE);
gDisplay.renderBitmap->FillRect(gViewPort, 20, h - 16, 21 + STAT_WIDTH, h - 12, COLOR_TEXT);
if (boss->mCurrentHealthBar == i) {
if (boss->mHitPoints > 0) {
gDisplay.renderBitmap->FillRect(gViewPort, 20, h - 16, 21 + boss->mHitPoints * STAT_WIDTH / boss->mMaxHitPoints,
h - 12, COLOR_ENEMY_HEALTH);
}
} else if (boss->mCurrentHealthBar > i) {
gDisplay.renderBitmap->FillRect(gViewPort, 20, h - 16, 21 + STAT_WIDTH, h - 12, COLOR_ENEMY_HEALTH);
}
h -= 7;
}
gDisplay.renderBitmap->DrawStringShadow(gViewPort, boss->mSprite->Name(), gFont8x8, 21, h - 18, COLOR_TEXT,
COLOR_TEXT_SHADOW,
COLOR_TEXT_TRANSPARENT);
}
}
| 36.367816 | 122 | 0.663085 | [
"render"
] |
a154ef7808bfebf861e9ebf27a639c56d838b195 | 5,754 | cpp | C++ | src/GafferScene/OpenGLAttributes.cpp | ddesmond/gaffer | 4f25df88103b7893df75865ea919fb035f92bac0 | [
"BSD-3-Clause"
] | 561 | 2016-10-18T04:30:48.000Z | 2022-03-30T06:52:04.000Z | src/GafferScene/OpenGLAttributes.cpp | ddesmond/gaffer | 4f25df88103b7893df75865ea919fb035f92bac0 | [
"BSD-3-Clause"
] | 1,828 | 2016-10-14T19:01:46.000Z | 2022-03-30T16:07:19.000Z | src/GafferScene/OpenGLAttributes.cpp | ddesmond/gaffer | 4f25df88103b7893df75865ea919fb035f92bac0 | [
"BSD-3-Clause"
] | 120 | 2016-10-18T15:19:13.000Z | 2021-12-20T16:28:23.000Z | //////////////////////////////////////////////////////////////////////////
//
// Copyright (c) 2012, Image Engine Design Inc. All rights reserved.
//
// Redistribution and use in source and binary forms, with or without
// modification, are permitted provided that the following conditions are
// met:
//
// * Redistributions of source code must retain the above
// copyright notice, this list of conditions and the following
// disclaimer.
//
// * Redistributions in binary form must reproduce the above
// copyright notice, this list of conditions and the following
// disclaimer in the documentation and/or other materials provided with
// the distribution.
//
// * Neither the name of John Haddon nor the names of
// any other contributors to this software may be used to endorse or
// promote products derived from this software without specific prior
// written permission.
//
// THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS
// IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO,
// THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR
// PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT OWNER OR
// CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL,
// EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO,
// PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR
// PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF
// LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING
// NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS
// SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
//
//////////////////////////////////////////////////////////////////////////
#include "GafferScene/OpenGLAttributes.h"
#include "Gaffer/NameValuePlug.h"
using namespace Imath;
using namespace Gaffer;
using namespace GafferScene;
GAFFER_NODE_DEFINE_TYPE( OpenGLAttributes );
OpenGLAttributes::OpenGLAttributes( const std::string &name )
: Attributes( name )
{
Gaffer::CompoundDataPlug *attributes = attributesPlug();
// drawing parameters
attributes->addChild( new NameValuePlug( "gl:primitive:solid", new IECore::BoolData( true ), false, "primitiveSolid" ) );
attributes->addChild( new NameValuePlug( "gl:primitive:wireframe", new IECore::BoolData( true ), false, "primitiveWireframe" ) );
attributes->addChild( new NameValuePlug( "gl:primitive:wireframeColor", new IECore::Color4fData( Color4f( 0.25, 0.6, 0.85, 1 ) ), false, "primitiveWireframeColor" ) );
attributes->addChild( new NameValuePlug( "gl:primitive:wireframeWidth", new FloatPlug( "value", Gaffer::Plug::Direction::In, 1.0f, 0.1f, 32.0f ), false, "primitiveWireframeWidth" ) );
attributes->addChild( new NameValuePlug( "gl:primitive:outline", new IECore::BoolData( true ), false, "primitiveOutline" ) );
attributes->addChild( new NameValuePlug( "gl:primitive:outlineColor", new IECore::Color4fData( Color4f( 0.85, 0.75, 0.45, 1 ) ), false, "primitiveOutlineColor" ) );
attributes->addChild( new NameValuePlug( "gl:primitive:outlineWidth", new IECore::FloatData( 1.0f ), false, "primitiveOutlineWidth" ) );
attributes->addChild( new NameValuePlug( "gl:primitive:points", new IECore::BoolData( true ), false, "primitivePoint" ) );
attributes->addChild( new NameValuePlug( "gl:primitive:pointColor", new IECore::Color4fData( Color4f( 0.85, 0.45, 0, 1 ) ), false, "primitivePointColor" ) );
attributes->addChild( new NameValuePlug( "gl:primitive:pointWidth", new IECore::FloatData( 1.0f ), false, "primitivePointWidth" ) );
attributes->addChild( new NameValuePlug( "gl:primitive:bound", new IECore::BoolData( true ), false, "primitiveBound" ) );
attributes->addChild( new NameValuePlug( "gl:primitive:boundColor", new IECore::Color4fData( Color4f( 0.36, 0.8, 0.85, 1 ) ), false, "primitiveBoundColor" ) );
// points primitive parameters
attributes->addChild( new NameValuePlug( "gl:pointsPrimitive:useGLPoints", new IECore::StringData( "forGLPoints" ), false, "pointsPrimitiveUseGLPoints" ) );
attributes->addChild( new NameValuePlug( "gl:pointsPrimitive:glPointWidth", new FloatPlug( "value", Gaffer::Plug::Direction::In, 1.0f, 0.1f, 128.0f ), false, "pointsPrimitiveGLPointWidth" ) );
// curves primitive parameters
attributes->addChild( new NameValuePlug( "gl:curvesPrimitive:useGLLines", new IECore::BoolData( false ), false, "curvesPrimitiveUseGLLines" ) );
attributes->addChild( new NameValuePlug( "gl:curvesPrimitive:glLineWidth", new FloatPlug( "value", Gaffer::Plug::Direction::In, 1.0f, 0.1f, 32.0f ), false, "curvesPrimitiveGLLineWidth" ) );
attributes->addChild( new NameValuePlug( "gl:curvesPrimitive:ignoreBasis", new IECore::BoolData( false ), false, "curvesPrimitiveIgnoreBasis" ) );
// visualisers
attributes->addChild( new Gaffer::NameValuePlug( "gl:visualiser:scale", new FloatPlug( "value", Gaffer::Plug::Direction::In, 1.0f, 0.01f ), false, "visualiserScale" ) );
attributes->addChild( new Gaffer::NameValuePlug( "gl:visualiser:maxTextureResolution", new IntPlug( "value", Gaffer::Plug::Direction::In, 512, 2, 2048 ), false, "visualiserMaxTextureResolution" ) );
attributes->addChild( new Gaffer::NameValuePlug( "gl:visualiser:frustum", new IECore::StringData( "whenSelected" ), false, "visualiserFrustum" ) );
attributes->addChild( new Gaffer::NameValuePlug( "gl:light:drawingMode", new IECore::StringData( "texture" ), false, "lightDrawingMode" ) );
attributes->addChild( new Gaffer::NameValuePlug( "gl:light:frustumScale", new FloatPlug( "value", Gaffer::Plug::Direction::In, 1.0f, 0.01f ), false, "lightFrustumScale" ) );
}
OpenGLAttributes::~OpenGLAttributes()
{
}
| 61.870968 | 199 | 0.719326 | [
"solid"
] |
a157424d9ec033abb4527d215352275fb58ff898 | 7,286 | cpp | C++ | Core/GDCore/IDE/Events/EventsContextAnalyzer.cpp | Oneoeigh/GDevelop | dddad3ff4b305b161ab6d7938e437fdbf9f0fed6 | [
"MIT"
] | 1 | 2018-11-23T11:56:08.000Z | 2018-11-23T11:56:08.000Z | Core/GDCore/IDE/Events/EventsContextAnalyzer.cpp | Oneoeigh/GDevelop | dddad3ff4b305b161ab6d7938e437fdbf9f0fed6 | [
"MIT"
] | null | null | null | Core/GDCore/IDE/Events/EventsContextAnalyzer.cpp | Oneoeigh/GDevelop | dddad3ff4b305b161ab6d7938e437fdbf9f0fed6 | [
"MIT"
] | 1 | 2018-11-23T15:58:40.000Z | 2018-11-23T15:58:40.000Z | /*
* GDevelop Core
* Copyright 2008-2016 Florian Rival (Florian.Rival@gmail.com). All rights
* reserved. This project is released under the MIT License.
*/
#include "GDCore/IDE/Events/EventsContextAnalyzer.h"
#include <map>
#include <memory>
#include <vector>
#include "GDCore/Events/Event.h"
#include "GDCore/Events/EventsList.h"
#include "GDCore/Events/Parsers/ExpressionParser.h"
#include "GDCore/Extensions/Metadata/ExpressionMetadata.h"
#include "GDCore/Extensions/Metadata/InstructionMetadata.h"
#include "GDCore/Extensions/Metadata/MetadataProvider.h"
#include "GDCore/Project/Layout.h"
#include "GDCore/Project/Project.h"
#include "GDCore/String.h"
namespace gd {
class CallbacksForListingObjects : public gd::ParserCallbacks {
public:
CallbacksForListingObjects(const gd::Platform& platform_,
const gd::ObjectsContainer& project_,
const gd::ObjectsContainer& layout_,
EventsContext& context_)
: platform(platform_),
project(project_),
layout(layout_),
context(context_){};
virtual ~CallbacksForListingObjects(){};
virtual void OnConstantToken(gd::String text){};
virtual void OnStaticFunction(gd::String functionName,
const std::vector<gd::Expression>& parameters,
const gd::ExpressionMetadata& expressionInfo) {
for (std::size_t i = 0;
i < parameters.size() && i < expressionInfo.parameters.size();
++i) {
EventsContextAnalyzer::AnalyzeParameter(platform,
project,
layout,
expressionInfo.parameters[i],
parameters[i],
context);
}
};
virtual void OnObjectFunction(gd::String functionName,
const std::vector<gd::Expression>& parameters,
const gd::ExpressionMetadata& expressionInfo) {
for (std::size_t i = 0;
i < parameters.size() && i < expressionInfo.parameters.size();
++i) {
EventsContextAnalyzer::AnalyzeParameter(platform,
project,
layout,
expressionInfo.parameters[i],
parameters[i],
context);
}
};
virtual void OnObjectBehaviorFunction(
gd::String functionName,
const std::vector<gd::Expression>& parameters,
const gd::ExpressionMetadata& expressionInfo) {
for (std::size_t i = 0;
i < parameters.size() && i < expressionInfo.parameters.size();
++i) {
EventsContextAnalyzer::AnalyzeParameter(platform,
project,
layout,
expressionInfo.parameters[i],
parameters[i],
context);
}
};
virtual bool OnSubMathExpression(const gd::Platform& platform,
const gd::ObjectsContainer& project,
const gd::ObjectsContainer& layout,
gd::Expression& expression) {
CallbacksForListingObjects callbacks(platform, project, layout, context);
gd::ExpressionParser parser(expression.GetPlainString());
parser.ParseMathExpression(platform, project, layout, callbacks);
return true;
}
virtual bool OnSubTextExpression(const gd::Platform& platform,
const gd::ObjectsContainer& project,
const gd::ObjectsContainer& layout,
gd::Expression& expression) {
CallbacksForListingObjects callbacks(platform, project, layout, context);
gd::ExpressionParser parser(expression.GetPlainString());
parser.ParseStringExpression(platform, project, layout, callbacks);
return true;
}
private:
const gd::Platform& platform;
const gd::ObjectsContainer& project;
const gd::ObjectsContainer& layout;
EventsContext& context;
};
bool EventsContextAnalyzer::DoVisitInstruction(gd::Instruction& instruction,
bool isCondition) {
const gd::InstructionMetadata& instrInfo =
isCondition ? MetadataProvider::GetConditionMetadata(
platform, instruction.GetType())
: MetadataProvider::GetActionMetadata(platform,
instruction.GetType());
for (int i = 0; i < instruction.GetParametersCount() &&
i < instrInfo.GetParametersCount();
++i) {
AnalyzeParameter(platform,
project,
layout,
instrInfo.GetParameter(i),
instruction.GetParameter(i),
context);
}
return false;
}
void EventsContextAnalyzer::AnalyzeParameter(
const gd::Platform& platform,
const gd::ObjectsContainer& project,
const gd::ObjectsContainer& layout,
const gd::ParameterMetadata& metadata,
const gd::Expression& parameter,
EventsContext& context) {
const auto& value = parameter.GetPlainString();
const auto& type = metadata.GetType();
if (ParameterMetadata::IsObject(type)) {
context.AddObjectName(value);
} else if (ParameterMetadata::IsExpression("number", type)) {
CallbacksForListingObjects callbacks(platform, project, layout, context);
gd::ExpressionParser parser(value);
parser.ParseMathExpression(platform, project, layout, callbacks);
} else if (ParameterMetadata::IsExpression("string", type)) {
CallbacksForListingObjects callbacks(platform, project, layout, context);
gd::ExpressionParser parser(value);
parser.ParseStringExpression(platform, project, layout, callbacks);
}
}
void EventsContext::AddObjectName(const gd::String& objectName) {
for (auto& realObjectName : ExpandObjectsName(objectName)) {
objectNames.insert(realObjectName);
}
objectOrGroupNames.insert(objectName);
}
std::vector<gd::String> EventsContext::ExpandObjectsName(
const gd::String& objectName) {
// Note: this logic is duplicated in EventsCodeGenerator::ExpandObjectsName
std::vector<gd::String> realObjects;
if (project.GetObjectGroups().Has(objectName))
realObjects =
project.GetObjectGroups().Get(objectName).GetAllObjectsNames();
else if (layout.GetObjectGroups().Has(objectName))
realObjects = layout.GetObjectGroups().Get(objectName).GetAllObjectsNames();
else
realObjects.push_back(objectName);
// Ensure that all returned objects actually exists.
for (std::size_t i = 0; i < realObjects.size();) {
if (!layout.HasObjectNamed(realObjects[i]) &&
!project.HasObjectNamed(realObjects[i]))
realObjects.erase(realObjects.begin() + i);
else
++i;
}
return realObjects;
}
} // namespace gd
| 38.550265 | 80 | 0.594702 | [
"vector"
] |
a15da6e6ccc0e20a14e599924f13d1d567dfd1d8 | 952 | cpp | C++ | src/gui/font.cpp | GabrielMajeri/gomoku | 5c56b6ed3bab38d85758c51e962435b3da6ef61f | [
"MIT"
] | 2 | 2019-05-09T05:27:02.000Z | 2019-05-09T12:21:08.000Z | src/gui/font.cpp | GabrielMajeri/gomoku | 5c56b6ed3bab38d85758c51e962435b3da6ef61f | [
"MIT"
] | null | null | null | src/gui/font.cpp | GabrielMajeri/gomoku | 5c56b6ed3bab38d85758c51e962435b3da6ef61f | [
"MIT"
] | null | null | null | #include "font.hpp"
#include "core/error.hpp"
Font::Font(const std::string& path, int pointSize) {
auto* font = TTF_OpenFont(path.c_str(), pointSize);
if (!font) {
throw SDLFontError("Failed to load font");
}
handle.reset(font);
}
template <> void Wrapper<TTF_Font>::Deleter::operator()(TTF_Font* font) {
TTF_CloseFont(font);
}
Surface Font::render(const std::string& text, Color color) const {
auto* surface = TTF_RenderUTF8_Blended(getHandle(), text.c_str(), color);
if (!surface) {
throw SDLFontError("Failed to render text");
}
return Surface(surface);
}
Surface Font::renderWrapped(const std::string& text, Color color,
int width) const {
auto* surface =
TTF_RenderUTF8_Blended_Wrapped(getHandle(), text.c_str(), color, width);
if (!surface) {
throw SDLFontError("Failed to render wrapped text");
}
return Surface(surface);
}
| 25.052632 | 80 | 0.639706 | [
"render"
] |
a15dfafc7ee60d8ced004f358b9a695ef0430ba6 | 3,133 | hpp | C++ | src/share/grabber_client.hpp | jgosmann/Karabiner-Elements | 5db7b8f7d4b5136d6dac0e8876d105eda4708f10 | [
"Unlicense"
] | 39 | 2017-01-13T13:53:45.000Z | 2021-01-29T16:00:05.000Z | src/share/grabber_client.hpp | jgosmann/Karabiner-Elements | 5db7b8f7d4b5136d6dac0e8876d105eda4708f10 | [
"Unlicense"
] | 25 | 2017-01-27T15:52:36.000Z | 2019-04-06T09:09:17.000Z | src/share/grabber_client.hpp | jgosmann/Karabiner-Elements | 5db7b8f7d4b5136d6dac0e8876d105eda4708f10 | [
"Unlicense"
] | 5 | 2017-01-15T19:48:51.000Z | 2017-07-18T13:49:55.000Z | #pragma once
#include "constants.hpp"
#include "filesystem.hpp"
#include "local_datagram_client.hpp"
#include "session.hpp"
#include "types.hpp"
#include <unistd.h>
#include <vector>
class grabber_client final {
public:
grabber_client(const grabber_client&) = delete;
grabber_client(void) {
// Check socket file existance
if (!filesystem::exists(constants::get_grabber_socket_file_path())) {
throw std::runtime_error("grabber socket is not found");
}
// Check socket file permission
if (auto current_console_user_id = session::get_current_console_user_id()) {
if (!filesystem::is_owned(constants::get_grabber_socket_file_path(), *current_console_user_id)) {
throw std::runtime_error("grabber socket is not writable");
}
} else {
throw std::runtime_error("session::get_current_console_user_id error");
}
client_ = std::make_unique<local_datagram_client>(constants::get_grabber_socket_file_path());
}
void connect(krbn::connect_from connect_from) {
krbn::operation_type_connect_struct s;
s.connect_from = connect_from;
s.pid = getpid();
client_->send_to(reinterpret_cast<uint8_t*>(&s), sizeof(s));
}
void system_preferences_values_updated(const system_preferences::values values) {
krbn::operation_type_system_preferences_values_updated_struct s;
s.values = values;
client_->send_to(reinterpret_cast<uint8_t*>(&s), sizeof(s));
}
void clear_simple_modifications(void) {
krbn::operation_type_clear_simple_modifications_struct s;
client_->send_to(reinterpret_cast<uint8_t*>(&s), sizeof(s));
}
void add_simple_modification(krbn::key_code from_key_code, krbn::key_code to_key_code) {
krbn::operation_type_add_simple_modification_struct s;
s.from_key_code = from_key_code;
s.to_key_code = to_key_code;
client_->send_to(reinterpret_cast<uint8_t*>(&s), sizeof(s));
}
void clear_fn_function_keys(void) {
krbn::operation_type_clear_fn_function_keys_struct s;
client_->send_to(reinterpret_cast<uint8_t*>(&s), sizeof(s));
}
void add_fn_function_key(krbn::key_code from_key_code, krbn::key_code to_key_code) {
krbn::operation_type_add_fn_function_key_struct s;
s.from_key_code = from_key_code;
s.to_key_code = to_key_code;
client_->send_to(reinterpret_cast<uint8_t*>(&s), sizeof(s));
}
void clear_devices(void) {
krbn::operation_type_clear_devices_struct s;
client_->send_to(reinterpret_cast<uint8_t*>(&s), sizeof(s));
}
void add_device(const krbn::device_identifiers_struct& device_identifiers_struct,
const krbn::device_configuration_struct& device_configuration_struct) {
krbn::operation_type_add_device_struct s;
s.device_identifiers_struct = device_identifiers_struct;
s.device_configuration_struct = device_configuration_struct;
client_->send_to(reinterpret_cast<uint8_t*>(&s), sizeof(s));
}
void complete_devices(void) {
krbn::operation_type_complete_devices_struct s;
client_->send_to(reinterpret_cast<uint8_t*>(&s), sizeof(s));
}
private:
std::unique_ptr<local_datagram_client> client_;
};
| 34.428571 | 103 | 0.743058 | [
"vector"
] |
a161cfec37c8aabbe37890849901ed62545fc262 | 45,476 | cpp | C++ | xenuser/winagent/XService.cpp | pearsonk/xc-windows | 0ddce48bf8f3bd75048e8249c91e82bb8b064e6d | [
"MIT"
] | 21 | 2015-02-10T13:44:10.000Z | 2021-12-31T20:24:43.000Z | xenuser/winagent/XService.cpp | pearsonk/xc-windows | 0ddce48bf8f3bd75048e8249c91e82bb8b064e6d | [
"MIT"
] | 24 | 2015-01-02T15:56:57.000Z | 2020-09-10T19:37:22.000Z | xenuser/winagent/XService.cpp | pearsonk/xc-windows | 0ddce48bf8f3bd75048e8249c91e82bb8b064e6d | [
"MIT"
] | 21 | 2015-02-03T20:34:19.000Z | 2021-09-19T16:35:42.000Z | /*
* Copyright (c) 2006 XenSource, Inc. All use and distribution of this
* copyrighted material is governed by and subject to terms and
* conditions as licensed by XenSource, Inc. All other rights reserved.
*/
/*
* Copyright (c) 2014 Citrix Systems, Inc.
*
* Permission is hereby granted, free of charge, to any person obtaining a copy
* of this software and associated documentation files (the "Software"), to deal
* in the Software without restriction, 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 <windows.h>
#include <shlobj.h>
#include <process.h>
#include <powrprof.h>
#include "stdafx.h"
#include "XSAccessor.h"
#include "WMIAccessor.h"
#include "XService.h"
#include "vm_stats.h"
#include "NicInfo.h"
#include "xs2.h"
#include "xs_private.h"
#include "verinfo.h"
#include "messages.h"
#include "TSInfo.h"
#include <setupapi.h>
#include <cfgmgr32.h>
#include <initguid.h>
#include <devguid.h>
#include <wintrust.h>
#include <shellapi.h>
//////////////////////////////////////////////////////////////////////////////
//
// WINTRUST_ACTION_GENERIC_VERIFY_V2 Guid (Authenticode)
//----------------------------------------------------------------------------
// Assigned to the pgActionID parameter of WinVerifyTrust to verify the
// authenticity of a file/object using the Microsoft Authenticode
// Policy Provider,
//
// {00AAC56B-CD44-11d0-8CC2-00C04FC295EE}
//
#define WINTRUST_ACTION_GENERIC_VERIFY_V2 \
{ 0xaac56b, \
0xcd44, \
0x11d0, \
{ 0x8c, 0xc2, 0x0, 0xc0, 0x4f, 0xc2, 0x95, 0xee } \
}
#define SIGNER_CITRIX "Citrix Systems, Inc"
#define SIGNER_XENSOURCE "XenSource, Inc"
#ifdef AMD64
#define XENTOOLS_INSTALL_REG_KEY "SOFTWARE\\Wow6432Node\\Citrix\\XenTools"
#else
#define XENTOOLS_INSTALL_REG_KEY "SOFTWARE\\Citrix\\XenTools"
#endif
SERVICE_STATUS ServiceStatus;
SERVICE_STATUS_HANDLE hStatus;
static HANDLE hServiceExitEvent;
static ULONG WindowsVersion;
static BOOL LegacyHal = FALSE;
static HINSTANCE local_hinstance;
#define SIZECHARS(x) (sizeof((x))/sizeof(TCHAR))
// Internal routines
static void ServiceControlHandler(DWORD request);
static void ServiceControlManagerUpdate(DWORD dwExitCode, DWORD dwState);
static void ServiceMain(int argc, char** argv);
static void GetWindowsVersion();
void PrintError(const char *func, DWORD err)
{
LPVOID lpMsgBuf;
FormatMessage(
FORMAT_MESSAGE_ALLOCATE_BUFFER |
FORMAT_MESSAGE_FROM_SYSTEM,
NULL,
err,
MAKELANGID(LANG_NEUTRAL, SUBLANG_DEFAULT),
(LPTSTR) &lpMsgBuf,
0,
NULL);
DBGPRINT(("%s failed: %s (%lx)\n", func, lpMsgBuf, err));
XenstorePrintf("control/error", "%s failed: %s (%x)", func, lpMsgBuf, err);
LocalFree(lpMsgBuf);
}
void PrintError(const char *func)
{
PrintError(func, GetLastError());
}
void PrintUsage()
{
printf("Usage: xenservice [-i|-u|-c|-t]\n");
printf("\t -i: install service\n");
printf("\t -u: uninstall service\n");
}
HMODULE SLC_API;
HMODULE SLWGA_API;
typedef HRESULT (WINAPI *SL_GET_WINDOWS_INFORMATION_DWORD)(
__in PCWSTR pwszValueName,
__out DWORD *pdwValue
);
typedef GUID SLID;
typedef enum _SL_GENUINE_STATE {
SL_GEN_STATE_IS_GENUINE = 0,
SL_GEN_STATE_INVALID_LICENSE = 1,
SL_GEN_STATE_TAMPERED = 2,
SL_GEN_STATE_LAST = 3
} SL_GENUINE_STATE;
typedef HRESULT (WINAPI *SL_IS_GENUINE_LOCAL)(
__in const SLID *pAppId,
__out SL_GENUINE_STATE *pGenuineState,
__inout_opt VOID *pUnused
);
#define WINDOWS_SLID \
{ 0x55c92734, \
0xd682, \
0x4d71, \
{ 0x98, 0x3e, 0xd6, 0xec, 0x3f, 0x16, 0x05, 0x9f } \
}
static VOID
AddLicenseInfoToStore(
VOID
)
{
SLID appId = WINDOWS_SLID;
SL_IS_GENUINE_LOCAL __SLIsGenuineLocal = NULL;
SL_GET_WINDOWS_INFORMATION_DWORD __SLGetWindowsInformationDWORD = NULL;
HRESULT hResult;
SL_GENUINE_STATE genuineState;
DWORD isAllowed = 0;
if (SLWGA_API != NULL) {
__SLIsGenuineLocal =
(SL_IS_GENUINE_LOCAL)GetProcAddress(SLWGA_API, "SLIsGenuineLocal");
if (__SLIsGenuineLocal != NULL) {
if ((hResult = __SLIsGenuineLocal(&appId, &genuineState, NULL)) == S_OK) {
switch (genuineState) {
case SL_GEN_STATE_IS_GENUINE:
XenstorePrintf("attr/os/license", "genuine");
break;
case SL_GEN_STATE_INVALID_LICENSE:
XenstorePrintf("attr/os/license", "invalid");
break;
case SL_GEN_STATE_TAMPERED:
XenstorePrintf("attr/os/license", "tampered");
break;
case SL_GEN_STATE_LAST:
default:
break;
}
} else {
XsLog("SLIsGenuineLocal() failed (%08x)", hResult);
}
} else {
XsLog("SLIsGenuineLocal() not available");
}
}
if (SLC_API != NULL) {
__SLGetWindowsInformationDWORD =
(SL_GET_WINDOWS_INFORMATION_DWORD)GetProcAddress(SLC_API, "SLGetWindowsInformationDWORD");
if (__SLGetWindowsInformationDWORD != NULL) {
if ((hResult =__SLGetWindowsInformationDWORD(L"VirtualXP-licensing-Enabled", &isAllowed)) == S_OK) {
if (isAllowed != 0)
XenstorePrintf("attr/os/virtualxp_enabled", "1");
else
XenstorePrintf("attr/os/virtualxp_enabled", "0");
} else {
XsLog("SLGetWindowsInformationDWORD(VirtualXP-licensing-Enabled) failed (%08x)", hResult);
}
} else {
XsLog("SLGetWindowsInformationDWORD() not available");
}
}
}
/* Add operating system version, service pack, etc. to store. */
static VOID
AddSystemInfoToStore(
WMIAccessor* wmi
)
{
OSVERSIONINFOEX info;
char buf[MAX_PATH];
XenstorePrintf("attr/os/class", "windows NT");
/* Windows version, service pack, build number */
info.dwOSVersionInfoSize = sizeof(info);
if (GetVersionEx((LPOSVERSIONINFO)&info)) {
#define do_field(name, field) \
XenstorePrintf("attr/os/" #name , "%d", info. field)
do_field(major, dwMajorVersion);
do_field(minor, dwMinorVersion);
do_field(build, dwBuildNumber);
do_field(platform, dwPlatformId);
do_field(spmajor, wServicePackMajor);
do_field(spminor, wServicePackMinor);
do_field(suite, wSuiteMask);
do_field(type, wProductType);
#undef do_field
XenstorePrintf("data/os_distro", "windows");
XenstorePrintf("data/os_majorver", "%d", info.dwMajorVersion);
XenstorePrintf("data/os_minorver", "%d", info.dwMinorVersion);
} else {
/* Flag that we couldn't collect this information. */
XenstorePrintf("attr/os/major", "-1");
}
DumpOSData(wmi);
XenstorePrintf("attr/os/boottype", "%d", GetSystemMetrics(SM_CLEANBOOT));
/* HAL version in use */
if (SUCCEEDED(SHGetFolderPath(NULL, CSIDL_SYSTEM, NULL, SHGFP_TYPE_CURRENT, buf))) {
DWORD tmp;
DWORD versize;
LPVOID buffer = NULL;
TCHAR buffer2[128];
LPTSTR halname;
UINT halnamelen;
struct {
WORD language, code_page;
} *trans;
UINT trans_size;
XenstorePrintf("attr/os/system32_dir", "%s", buf);
strcat(buf, "\\hal.dll");
versize = GetFileVersionInfoSize(buf, &tmp);
if (versize == 0) {
XenstorePrintf("attr/os/hal", "<unknown versize=0>");
goto done_hal;
}
buffer = malloc(versize);
if (!buffer) {
XenstorePrintf("attr/os/hal", "<unknown versize=%d>", versize);
goto done_hal;
}
if (GetFileVersionInfo(buf, tmp, versize, buffer) == 0) {
PrintError("GetFileVersioInfo(hal.dll)");
goto done_hal;
}
if (!VerQueryValue(buffer, TEXT("\\VarFileInfo\\Translation"),
(LPVOID *)&trans, &trans_size)) {
PrintError("VerQueryValue(hal.Translation");
goto done_hal;
}
if (trans_size < sizeof(*trans)) {
XenstorePrintf("attr/os/hal", "<no translations>");
goto done_hal;
}
sprintf(buffer2, "\\StringFileInfo\\%04x%04x\\InternalName",
trans->language, trans->code_page);
if (VerQueryValue(buffer, buffer2, (LPVOID *)&halname,
&halnamelen)) {
XenstorePrintf("attr/os/hal", "%s", halname);
if (!lstrcmpi(halname, "hal.dll")) {
LegacyHal = TRUE;
}
} else {
PrintError("VerQueryValue(hal.InternalName)");
}
done_hal:
free(buffer);
}
/* Kernel command line */
HKEY regKey;
DWORD res;
res = RegOpenKey(HKEY_LOCAL_MACHINE,
"SYSTEM\\CurrentControlSet\\Control",
®Key);
if (res != ERROR_SUCCESS) {
PrintError("RegOpenKey(\"HKLM\\SYSTEM\\CurrentControlSet\\Control\")");
} else {
DWORD keyType;
DWORD tmp;
tmp = sizeof(buf);
res = RegQueryValueEx(regKey, "SystemStartOptions",
NULL, &keyType, (LPBYTE)buf, &tmp);
if (res != ERROR_SUCCESS) {
PrintError("RegQueryValue(SystemStartOptions)");
} else if (keyType != REG_SZ) {
XenstorePrintf("attr/os/boot_options", "<not string>");
} else {
XenstorePrintf("attr/os/boot_options", buf);
}
RegCloseKey(regKey);
regKey = NULL;
}
AddHotFixInfoToStore(wmi);
AddLicenseInfoToStore();
}
struct watch_event {
HANDLE event;
struct xs2_watch *watch;
};
static void
ReleaseWatch(struct watch_event *we)
{
if (we == NULL)
return;
if (we->event != INVALID_HANDLE_VALUE)
CloseHandle(we->event);
if (we->watch)
XenstoreUnwatch(we->watch);
free(we);
}
static struct watch_event *
EstablishWatch(const char *path)
{
struct watch_event *we;
DWORD err;
we = (struct watch_event *)malloc(sizeof(*we));
if (!we) {
SetLastError(ERROR_NOT_ENOUGH_MEMORY);
return NULL;
}
memset(we, 0, sizeof(*we));
we->watch = NULL;
we->event = CreateEvent(NULL, FALSE, FALSE, NULL);
if (we->event != INVALID_HANDLE_VALUE)
we->watch = XenstoreWatch(path, we->event);
if (we->watch == NULL) {
err = GetLastError();
ReleaseWatch(we);
SetLastError(err);
return NULL;
}
return we;
}
struct watch_feature {
struct watch_event *watch;
const char *feature_flag;
const char *name;
void (*handler)(void *);
void *ctx;
};
#define MAX_FEATURES 10
struct watch_feature_set {
struct watch_feature features[MAX_FEATURES];
unsigned nr_features;
};
static void
AddFeature(struct watch_feature_set *wfs, const char *path,
const char *flag, const char *name,
void (*handler)(void *), void *ctx)
{
unsigned n;
if (wfs->nr_features == MAX_FEATURES) {
PrintError("Too many features!", ERROR_INVALID_FUNCTION);
return;
}
n = wfs->nr_features;
wfs->features[n].watch = EstablishWatch(path);
if (wfs->features[n].watch == NULL) {
PrintError("EstablishWatch() for AddFeature()");
return;
}
wfs->features[n].feature_flag = flag;
wfs->features[n].handler = handler;
wfs->features[n].ctx = ctx;
wfs->features[n].name = name;
wfs->nr_features++;
}
static void
AdvertiseFeatures(struct watch_feature_set *wfs)
{
unsigned x;
for (x = 0; x < wfs->nr_features; x++) {
if (wfs->features[x].feature_flag != NULL)
XenstorePrintf(wfs->features[x].feature_flag, "1");
}
}
VOID
RegisterPVAddOns(
WMIAccessor* wmi
)
{
HKEY hRegKey;
HANDLE h = INVALID_HANDLE_VALUE;
DWORD dwVersion;
DWORD cbData;
// If we get here, the drivers are installed.
XenstorePrintf ("attr/PVAddons/Installed", "1");
// Put the major, minor, and build version numbers in the store.
LONG lRet = 0;
lRet = RegOpenKeyEx(HKEY_LOCAL_MACHINE,
XENTOOLS_INSTALL_REG_KEY,
0,
KEY_READ,
&hRegKey);
if (lRet == ERROR_SUCCESS)
{
cbData = sizeof(dwVersion);
#define DO_VERSION(type) \
lRet = RegQueryValueEx ( \
hRegKey, \
#type "Version", \
NULL, \
NULL, \
(PBYTE)&dwVersion, \
&cbData); \
if (lRet == ERROR_SUCCESS) \
XenstorePrintf ("attr/PVAddons/" #type "Version", "%d", \
dwVersion); \
else \
DBGPRINT (("Failed to get version " #type));
DO_VERSION(Major);
DO_VERSION(Minor);
DO_VERSION(Micro);
DO_VERSION(Build);
#undef DO_VERSION
RegCloseKey(hRegKey);
}
AddSystemInfoToStore(wmi);
}
void ServiceUninstall()
{
SC_HANDLE hSvc;
SC_HANDLE hMgr;
hMgr = OpenSCManager(NULL, NULL, SC_MANAGER_ALL_ACCESS);
if ( hMgr )
{
hSvc = OpenService(hMgr, SVC_NAME, SERVICE_ALL_ACCESS);
if (hSvc)
{
// try to stop the service
if ( ControlService( hSvc, SERVICE_CONTROL_STOP, &ServiceStatus ) )
{
printf("Stopping %s.", SVC_DISPLAYNAME);
Sleep( 1000 );
while ( QueryServiceStatus( hSvc, &ServiceStatus ) )
{
if ( ServiceStatus.dwCurrentState == SERVICE_STOP_PENDING )
{
printf(".");
Sleep( 1000 );
}
else
break;
}
if ( ServiceStatus.dwCurrentState == SERVICE_STOPPED )
printf("\n%s stopped.\n", SVC_DISPLAYNAME );
else
printf("\n%s failed to stop.\n", SVC_DISPLAYNAME );
}
// now remove the service
if ( DeleteService(hSvc) )
printf("%s uninstalled.\n", SVC_DISPLAYNAME );
else
printf("Unable to uninstall - %d\n", GetLastError());
CloseServiceHandle(hSvc);
/* Tell dom0 that we're no longer installed. This is a bit
of a hack. */
InitXSAccessor();
XenstorePrintf("attr/PVAddons/Installed", "0");
XenstorePrintf("attr/PVAddons/MajorVersion", "0");
XenstorePrintf("attr/PVAddons/MinorVersion", "0");
XenstorePrintf("attr/PVAddons/BuildVersion", "0");
/* Crank the update number so xapi notices it. */
char *v;
XenstoreRead("data/update_cnt", &v);
if (v) {
int cnt = atoi(v);
XenstorePrintf("data/update_cnt", "%d", cnt + 1);
xs2_free(v);
}
}
else
printf("Unable to open service - %d\n", GetLastError());
CloseServiceHandle(hMgr);
}
else
printf("Unable to open scm - %d\n", GetLastError());
}
int __stdcall
WinMain(HINSTANCE hInstance, HINSTANCE ignore,
LPSTR lpCmdLine, int nCmdShow)
{
local_hinstance = hInstance;
if (strlen(lpCmdLine) == 0) {
SERVICE_TABLE_ENTRY ServiceTable[2];
ServiceTable[0].lpServiceName = SVC_NAME;
ServiceTable[0].lpServiceProc = (LPSERVICE_MAIN_FUNCTION)ServiceMain;
ServiceTable[1].lpServiceName = NULL;
ServiceTable[1].lpServiceProc = NULL;
DBGPRINT(("XenSvc: starting ctrl dispatcher "));
// Start the control dispatcher thread for our service
if (!StartServiceCtrlDispatcher(ServiceTable))
{
if (GetLastError() == ERROR_FAILED_SERVICE_CONTROLLER_CONNECT)
{
DBGPRINT(("XenSvc: unable to start ctrl dispatcher - %d", GetLastError()));
}
}
else
{
// We get here when the service is shut down.
}
} else if (!strcmp(lpCmdLine, "-u") || !strcmp(lpCmdLine, "\"-u\"")) {
ServiceUninstall();
} else {
PrintUsage();
}
return 0;
}
static void AcquireSystemPrivilege(LPCTSTR name)
{
HANDLE token;
TOKEN_PRIVILEGES tkp;
DWORD err;
LookupPrivilegeValue(NULL, name, &tkp.Privileges[0].Luid);
tkp.PrivilegeCount = 1;
tkp.Privileges[0].Attributes = SE_PRIVILEGE_ENABLED;
if (!OpenProcessToken(GetCurrentProcess(),
TOKEN_ADJUST_PRIVILEGES|TOKEN_QUERY,
&token)) {
DBGPRINT(("Failed to open local token.\n"));
} else {
AdjustTokenPrivileges(token, FALSE, &tkp,
NULL, 0, NULL);
err = GetLastError();
if (err != ERROR_SUCCESS) {
PrintError("AdjustTokenPrivileges", err);
}
}
}
static void AcquireSystemShutdownPrivilege(void)
{
AcquireSystemPrivilege(SE_SHUTDOWN_NAME);
}
enum XShutdownType {
XShutdownPoweroff,
XShutdownReboot,
XShutdownSuspend,
XShutdownS3
};
static void maybeReboot(void *ctx)
{
char *shutdown_type;
unsigned int len;
BOOL res;
enum XShutdownType type;
int cntr = 0;
HANDLE eventLog;
if (XenstoreRead("control/shutdown", &shutdown_type) < 0)
return;
DBGPRINT(("Shutdown type %s\n", shutdown_type));
if (strcmp(shutdown_type, "poweroff") == 0 ||
strcmp(shutdown_type, "halt") == 0) {
type = XShutdownPoweroff;
} else if (strcmp(shutdown_type, "reboot") == 0) {
type = XShutdownReboot;
} else if (strcmp(shutdown_type, "hibernate") == 0) {
type = XShutdownSuspend;
} else if (strcmp(shutdown_type, "s3") == 0) {
type = XShutdownS3;
} else {
DBGPRINT(("Bad shutdown type %s\n", shutdown_type));
goto out;
}
/* We try to shutdown even if this fails, since it might work
and it can't do any harm. */
AcquireSystemShutdownPrivilege();
eventLog = RegisterEventSource(NULL, "xensvc");
if (eventLog) {
DWORD eventId;
switch (type) {
case XShutdownPoweroff:
eventId = EVENT_XENUSER_POWEROFF;
break;
case XShutdownReboot:
eventId = EVENT_XENUSER_REBOOT;
break;
case XShutdownSuspend:
eventId = EVENT_XENUSER_HIBERNATE;
break;
case XShutdownS3:
eventId = EVENT_XENUSER_S3;
break;
}
ReportEvent(eventLog, EVENTLOG_SUCCESS, 0, eventId, NULL, 0, 0,
NULL, NULL);
DeregisterEventSource(eventLog);
}
/* do the shutdown */
switch (type) {
case XShutdownPoweroff:
case XShutdownReboot:
if (WindowsVersion == 0x500)
{
/* Windows 2000 InitiateSystemShutdownEx is funny in
various ways (e.g. sometimes fails to power off after
shutdown, especially if the local terminal is locked,
not doing anything if there's nobody logged on, etc.).
ExitWindowsEx seems to be more reliable, so use it
instead. */
/* XXX I don't really understand why
InitiateSystemShutdownEx behaves so badly. */
/* If this is a legacy hal then use EWX_SHUTDOWN when shutting
down instead of EWX_POWEROFF. */
#pragma warning (disable : 28159)
res = ExitWindowsEx((type == XShutdownReboot ?
EWX_REBOOT :
(LegacyHal ?
EWX_SHUTDOWN :
EWX_POWEROFF))|
EWX_FORCE,
SHTDN_REASON_MAJOR_OTHER|
SHTDN_REASON_MINOR_ENVIRONMENT |
SHTDN_REASON_FLAG_PLANNED);
#pragma warning (default: 28159)
if (!res)
PrintError("ExitWindowsEx");
else
XenstoreRemove("control/shutdown");
} else {
#pragma warning (disable : 28159)
res = InitiateSystemShutdownEx(
NULL,
NULL,
0,
TRUE,
type == XShutdownReboot,
SHTDN_REASON_MAJOR_OTHER |
SHTDN_REASON_MINOR_ENVIRONMENT |
SHTDN_REASON_FLAG_PLANNED);
#pragma warning (default: 28159)
if (!res) {
PrintError("InitiateSystemShutdownEx");
} else {
XenstoreRemove("control/shutdown");
}
}
break;
case XShutdownSuspend:
XenstorePrintf ("control/hibernation-state", "started");
/* Even if we think hibernation is disabled, try it anyway.
It's not like it can do any harm. */
res = SetSystemPowerState(FALSE, FALSE);
XenstoreRemove ("control/shutdown");
if (!res) {
/* Tell the tools that we've failed. */
PrintError("SetSystemPowerState");
XenstorePrintf ("control/hibernation-state", "failed");
}
break;
case XShutdownS3:
XenstorePrintf ("control/s3-state", "started");
res = SetSuspendState(FALSE, TRUE, FALSE);
XenstoreRemove ("control/shutdown");
if (!res) {
PrintError("SetSuspendState");
XenstorePrintf ("control/s3-state", "failed");
}
break;
}
out:
xs2_free(shutdown_type);
}
static
void
GetWindowsVersion()
{
OSVERSIONINFO info;
info.dwOSVersionInfoSize = sizeof(info);
WindowsVersion = 0;
if (GetVersionEx(&info)) {
if (((info.dwMajorVersion & ~0xff) == 0)
&& ((info.dwMinorVersion & ~0xff) == 0))
{
WindowsVersion = (info.dwMajorVersion << 8) |
info.dwMinorVersion;
}
}
}
static TCHAR *
FetchRexecBinary(void)
{
TCHAR *res;
TCHAR tempbuf[MAX_PATH];
HANDLE h;
ssize_t chunk_len;
char *chunk;
ssize_t off_in_chunk;
DWORD bytes_this_time;
if (!GetTempPath(sizeof(tempbuf) / sizeof(tempbuf[0]), tempbuf)) {
PrintError(("GetTempPath()"));
return NULL;
}
res = (TCHAR *)malloc(sizeof(TCHAR) * MAX_PATH);
if (!res) {
DBGPRINT(("No memory for temporary path"));
return NULL;
}
if (!GetTempFileName(tempbuf, "xenservice", 0, res)) {
PrintError("GetTempFileName()");
free(res);
return NULL;
}
h = CreateFile(res,
GENERIC_WRITE,
0,
NULL,
CREATE_ALWAYS,
FILE_ATTRIBUTE_NORMAL|FILE_ATTRIBUTE_TEMPORARY,
NULL);
if (h == INVALID_HANDLE_VALUE) {
PrintError("openning temporary file");
DeleteFile(res);
free(res);
return NULL;
}
/* Read the file in */
while (1) {
chunk_len = XenstoreRead("control/rexec_chunk", &chunk);
if (chunk_len < 0) {
if (GetLastError() == ERROR_FILE_NOT_FOUND) {
/* Wait for dom0 to give us the next chunk. Rather
icky; the right answer would be to use a watch, but
it's hardly worth it for this little thing. */
Sleep(1);
continue;
} else {
PrintError("read rexec chunk");
goto err;
}
}
XenstoreRemove("control/rexec_chunk");
if (chunk_len == 0) {
xs2_free(chunk);
break;
}
off_in_chunk = 0;
while (off_in_chunk < chunk_len) {
if (!WriteFile(h,
chunk + off_in_chunk,
(ULONG)(chunk_len - off_in_chunk),
&bytes_this_time,
NULL)) {
PrintError(("WriteFile()"));
goto err;
}
off_in_chunk += bytes_this_time;
}
xs2_free(chunk);
}
CloseHandle(h);
return res;
err:
CloseHandle(h);
DeleteFile(res);
free(res);
return NULL;
}
static BOOL
VerifyRexec(
PCTSTR path
)
{
DWORD Err;
WINTRUST_FILE_INFO FileData;
WCHAR FileName[MAX_PATH];
WINTRUST_DATA WinTrustData;
GUID WVTPolicyGUID = WINTRUST_ACTION_GENERIC_VERIFY_V2;
BOOL valid = FALSE;
PCRYPT_PROVIDER_DATA CryptProviderData;
PCRYPT_PROVIDER_SGNR CryptProviderSgnr;
PCRYPT_PROVIDER_CERT CryptProviderCert;
TCHAR Buffer[32];
if (mbstowcs(FileName, path, MAX_PATH) == -1) {
goto clean;
}
memset(&FileData, 0, sizeof(FileData));
FileData.cbStruct = sizeof(WINTRUST_FILE_INFO);
FileData.pcwszFilePath = FileName;
FileData.hFile = NULL;
FileData.pgKnownSubject = NULL;
memset(&WinTrustData, 0, sizeof(WinTrustData));
WinTrustData.cbStruct = sizeof(WinTrustData);
WinTrustData.pPolicyCallbackData = NULL;
WinTrustData.pSIPClientData = NULL;
WinTrustData.dwUIChoice = WTD_UI_NONE;
WinTrustData.fdwRevocationChecks = WTD_REVOKE_NONE;
WinTrustData.dwUnionChoice = WTD_CHOICE_FILE;
WinTrustData.dwStateAction = WTD_STATEACTION_VERIFY;
WinTrustData.hWVTStateData = NULL;
WinTrustData.pwszURLReference = NULL;
WinTrustData.dwProvFlags = WTD_SAFER_FLAG;
WinTrustData.dwUIContext = 0;
WinTrustData.pFile = &FileData;
Err = WinVerifyTrust(NULL,
&WVTPolicyGUID,
&WinTrustData);
if (Err != ERROR_SUCCESS) {
PrintError("WinVerifyTrust()", Err);
goto clean;
}
CryptProviderData = WTHelperProvDataFromStateData(WinTrustData.hWVTStateData);
if (!CryptProviderData) {
goto clean;
}
CryptProviderSgnr = WTHelperGetProvSignerFromChain(CryptProviderData,
0, //index
FALSE,
0);
if (!CryptProviderSgnr) {
goto clean;
}
CryptProviderCert = WTHelperGetProvCertFromChain(CryptProviderSgnr,
0); //index
if (!CryptProviderCert) {
goto clean;
}
if (CertGetNameString(CryptProviderCert->pCert,
CERT_NAME_SIMPLE_DISPLAY_TYPE,
0,
NULL,
Buffer,
sizeof(Buffer)/sizeof(TCHAR))) {
if (!lstrcmp(Buffer, SIGNER_CITRIX) ||
!lstrcmp(Buffer, SIGNER_XENSOURCE)) {
valid = TRUE;
} else {
//
// The package is properly signed, just not by Citrix or XenSource and therefore
// we don't trust it enough to run it.
//
DBGPRINT(("VerifyRexec() failed: not signed by trusted signer\n"));
XenstorePrintf("control/error", "VerifyRexec() failed: not signed by trusted signer");
}
}
clean:
if (WinTrustData.hWVTStateData != NULL) {
WinTrustData.dwStateAction = WTD_STATEACTION_CLOSE;
WinVerifyTrust(NULL,
&WVTPolicyGUID,
&WinTrustData);
}
return valid;
}
static void
processRexec(void *ctx)
{
char *cmd = NULL;
PROCESS_INFORMATION processInfo = {0};
STARTUPINFO startInfo = {0};
BOOL success;
DWORD code;
TCHAR *path = NULL;
if (XenstoreRead("control/rexec_cmdline", &cmd) < 0)
goto clean;
DBGPRINT(("rexec %s\n", cmd));
XenstoreRemove("control/rexec_cmdline");
//
// Download the binary over xenstore
//
path = FetchRexecBinary();
if (!path) {
XenstorePrintf("control/rexec_res", "-3");
goto clean;
}
//
// Verify that the binary is digitally signed
//
if (!VerifyRexec(path)) {
XenstorePrintf("control/rexec_res", "-4");
goto clean;
}
//
// Execute the binary
//
success = CreateProcessA(path, /* name */
cmd, /* command line */
NULL, /* process security attributes */
NULL, /* thread security attributes */
FALSE, /* Inherit handles ? */
0, /* Creation flags */
NULL, /* environment */
NULL, /* initial working directory */
&startInfo, /* startup info */
&processInfo); /* Process information */
if (!success) {
PrintError("CreateProcess()");
XenstorePrintf("control/rexec_res", "-1");
goto clean;
}
CloseHandle(processInfo.hThread);
WaitForSingleObject(processInfo.hProcess, INFINITE);
success = GetExitCodeProcess(processInfo.hProcess, &code);
if (!success) {
PrintError("GetExitCodeProcess()");
CloseHandle(processInfo.hProcess);
XenstorePrintf("control/rexec_res", "-2");
goto clean;
}
CloseHandle(processInfo.hProcess);
XenstorePrintf("control/rexec_res", "%d", code);
clean:
if (cmd != NULL) {
xs2_free(cmd);
}
if (path != NULL) {
DeleteFile(path);
free(path);
}
return;
}
static void
processRsend(void *ctx)
{
PTSTR path = NULL;
PTSTR data = NULL;
TCHAR expandedPath[MAX_PATH];
DWORD err;
int write_off;
DWORD bytes_written;
HANDLE h = INVALID_HANDLE_VALUE;
ssize_t data_len;
if (XenstoreRead("control/rsend_path", &path) < 0)
goto clean;
//
// Expand out any environment variables that are in the path
//
err = ExpandEnvironmentStrings(path, expandedPath, SIZECHARS(expandedPath));
if ((err == 0) ||
(err >= SIZECHARS(expandedPath))) {
if (err >= SIZECHARS(expandedPath))
SetLastError(ERROR_BUFFER_OVERFLOW);
PrintError("ExpandEnvironmentStrings() for processRsend");
XenstorePrintf("control/rsend_res", "-3");
goto clean;
}
data_len = XenstoreRead("control/rsend_data", &data);
if (data_len < 0) {
PrintError("XenstoreRead(control/rsend_data)");
goto clean;
}
XenstoreRemove("control/rsend_data");
XenstoreRemove("control/rsend_path");
h = CreateFile(expandedPath, GENERIC_WRITE, 0, NULL, CREATE_ALWAYS,
FILE_ATTRIBUTE_NORMAL|FILE_FLAG_SEQUENTIAL_SCAN,
NULL);
if (h == INVALID_HANDLE_VALUE) {
PrintError("CreateFile() for processRsend");
XenstorePrintf("control/rsend_res", "-1");
goto clean;
}
write_off = 0;
while (write_off < data_len) {
if (!WriteFile(h, data + write_off, (DWORD)(data_len - write_off),
&bytes_written, NULL)) {
PrintError("WriteFile() for processRsend");
XenstorePrintf("control/rsend_res", "-2");
goto clean;
}
write_off += bytes_written;
}
XenstorePrintf("control/rsend_res", "0");
clean:
if (h != INVALID_HANDLE_VALUE) {
CloseHandle(h);
}
if (path != NULL) {
xs2_free(path);
}
if (data != NULL) {
xs2_free(data);
}
}
/* We need to resync the clock when we recover from suspend/resume. */
static void
finishSuspend(void)
{
FILETIME now = {0};
SYSTEMTIME sys_time;
SYSTEMTIME current_time;
DBGPRINT(("Coming back from suspend.\n"));
GetXenTime(&now);
XsLog("Xen time is %I64x", now);
if (!FileTimeToSystemTime(&now, &sys_time)) {
PrintError("FileTimeToSystemTime()");
DBGPRINT(("FileTimeToSystemTime(%x.%x)\n",
now.dwLowDateTime, now.dwHighDateTime));
} else {
XsLog("Set time to %d.%d.%d %d:%d:%d.%d",
sys_time.wYear, sys_time.wMonth, sys_time.wDay,
sys_time.wHour, sys_time.wMinute, sys_time.wSecond,
sys_time.wMilliseconds);
GetLocalTime(¤t_time);
XsLog("Time is now %d.%d.%d %d:%d:%d.%d",
current_time.wYear, current_time.wMonth, current_time.wDay,
current_time.wHour, current_time.wMinute, current_time.wSecond,
current_time.wMilliseconds);
if (!SetLocalTime(&sys_time))
PrintError("SetSystemTime()");
}
}
static void
refreshStoreData(WMIAccessor *wmi, NicInfo *nicInfo,
TSInfo *tsInfo, struct watch_feature_set *wfs)
{
PCHAR buffer = NULL;
static int64_t last_meminfo_free;
static int cntr;
unsigned need_kick;
need_kick = 0;
if (XenstoreRead("attr/PVAddons/Installed",
&buffer) < 0) {
if (GetLastError() == ERROR_NO_SYSTEM_RESOURCES)
return;
XsLogMsg("register ourself in the store");
RegisterPVAddOns(wmi);
nicInfo->Refresh();
UpdateProcessListInStore(wmi);
AdvertiseFeatures(wfs);
need_kick = 1;
} else {
xs2_free(buffer);
}
if (XenstoreRead("data/meminfo_free", &buffer) < 0) {
cntr = 0;
last_meminfo_free = 0;
} else {
xs2_free(buffer);
}
if (XenstoreRead("data/ts", &buffer) < 0) {
cntr = 0;
} else {
xs2_free(buffer);
}
/* XXX HACK: Restrict ourselves to only doing this once every two
* minutes or so (we get called about every 4.5 seconds). */
if (cntr++ % 26 == 0) {
VMData data;
BOOLEAN enabled;
XsLogMsg("Get memory data");
memset(&data, 0, sizeof(VMData));
GetWMIData(wmi, data);
if (data.meminfo_free - last_meminfo_free > 1024 ||
data.meminfo_free - last_meminfo_free < -1024) {
XsLogMsg("update memory data in store");
XenstoreDoDump(&data);
need_kick = 1;
last_meminfo_free = data.meminfo_free;
}
XsLogMsg("Refresh terminal services status");
tsInfo->Refresh();
XsLogMsg("Get volume mapping data");
DoVolumeDump();
}
if (need_kick)
XenstoreKickXapi();
}
static void
ProcessTsControl(void *ctx)
{
TSInfo *tsInfo = (TSInfo *)ctx;
tsInfo->ProcessControl();
}
static void
processPing(void *ctx)
{
XenstoreRemove("control/ping");
}
static void
processDumpLog(void *ctx)
{
char *val;
int do_it;
do_it = 0;
if (XenstoreRead("control/dumplog", &val) >= 0) {
xs2_free(val);
do_it = 1;
} else if (GetLastError() != ERROR_FILE_NOT_FOUND)
do_it = 1;
if (do_it) {
XsDumpLogThisThread();
XenstoreRemove("control/dumplog");
}
}
//
// Main loop
//
void Run()
{
VMData data;
bool exit=false;
PCHAR pPVAddonsInstalled = NULL;
PCHAR buffer = NULL;
STARTUPINFO startInfo;
PROCESS_INFORMATION processInfo;
HANDLE suspendEvent;
struct WMIAccessor *wmi;
MSG msg;
int cntr = 0;
NicInfo *nicInfo;
TSInfo *tsInfo;
struct watch_feature_set features;
BOOL snap = FALSE;
HKEY hKey = NULL;
XsLogMsg("Guest agent main loop starting");
memset(&features, 0, sizeof(features));
GetWindowsVersion();
// Load Software Licensing API
SLC_API = LoadLibrary("Slc");
SLWGA_API = LoadLibrary("Slwga");
//
// Refresh WMI ADAP classes
//
ZeroMemory (&startInfo, sizeof (startInfo));
ZeroMemory (&processInfo, sizeof (processInfo));
startInfo.cb = sizeof (startInfo);
if (!CreateProcessA(
NULL,
"\"wmiadap\" /f",
NULL,
NULL,
FALSE,
0,
NULL,
NULL,
&startInfo,
&processInfo
))
{
DBGPRINT (("XenSvc: Unable to refresh WMI ADAP: %d\n", GetLastError()));
}
else
{
WaitForSingleObject (processInfo.hProcess, 5000);
CloseHandle (processInfo.hProcess);
CloseHandle (processInfo.hThread);
}
//
// Enable disk counters forcibly so that we can retrieve disk performance
// using IOCTL_DISK_PERFORMANCE
//
if (!CreateProcessA(
NULL,
"\"diskperf\" -y",
NULL,
NULL,
FALSE,
0,
NULL,
NULL,
&startInfo,
&processInfo
))
{
DBGPRINT (("XenSvc: Cannot enable disk perf counters: %d\n", GetLastError()));
}
else
{
WaitForSingleObject (processInfo.hProcess, 5000);
CloseHandle (processInfo.hProcess);
CloseHandle (processInfo.hThread);
}
AddFeature(&features, "control/shutdown", "control/feature-shutdown",
"shutdown", maybeReboot, NULL);
AddFeature(&features, "control/rexec_cmdline", "control/feature-rexec",
"rexec", processRexec, NULL);
AddFeature(&features, "control/ping", NULL, "ping", processPing, NULL);
AddFeature(&features, "control/dumplog", NULL, "dumplog", processDumpLog, NULL);
/* Disabled for now, until we figure out exactly what we're going
to use this for. */
#if 0
AddFeature(&features, "control/resend_path", "control/feature-rsend",
"rsend", processRsend, NULL);
#endif
suspendEvent = CreateEvent(NULL, FALSE, FALSE, NULL);
if (!suspendEvent) {
PrintError("CreateEvent() suspendEvent");
} else {
if (ListenSuspend(suspendEvent) < 0) {
PrintError("ListenSuspend()");
CloseHandle(suspendEvent);
suspendEvent = NULL;
}
}
StartClipboardSync();
wmi = ConnectToWMI();
UpdateProcessListInStore(wmi);
nicInfo = new NicInfo();
nicInfo->Prime();
tsInfo = new TSInfo();
AddFeature(&features,
"control/ts",
"control/feature-ts",
"ts",
ProcessTsControl,
tsInfo);
XenstoreRemove("attr/PVAddons/Installed");
refreshStoreData(wmi, nicInfo, tsInfo, &features);
while (1)
{
DWORD status;
int nr_handles = 2;
HANDLE handles[3 + MAX_FEATURES];
unsigned x;
handles[0] = hServiceExitEvent;
handles[1] = nicInfo->NicChangeEvent;
if (suspendEvent)
handles[nr_handles++] = suspendEvent;
for (x = 0; x < features.nr_features; x++)
handles[nr_handles++] = features.features[x].watch->event;
XsLogMsg("win agent going to sleep");
status = WaitForMultipleObjects(nr_handles, handles, FALSE, 4500);
XsLogMsg("win agent woke up for %d", status);
if (status == WAIT_TIMEOUT)
{
refreshStoreData(wmi, nicInfo, tsInfo, &features);
if (++cntr % 12 == 0) {
/* Only do this once a minute or so, because it
doesn't really need to be up to date. */
UpdateProcessListInStore(wmi);
}
}
/* WAIT_OBJECT_0 happens to be 0, so the compiler gets shirty
about status >= WAIT_OBJECT_0 (since status is unsigned).
This is more obviously correct than the compiler-friendly
version, though, so just disable the warning. */
#pragma warning (disable: 4296)
else if (status >= WAIT_OBJECT_0 &&
status < WAIT_OBJECT_0 + nr_handles)
#pragma warning (default: 4296)
{
HANDLE event = handles[status - WAIT_OBJECT_0];
if (event == hServiceExitEvent)
{
XsLogMsg("service exit event");
break;
}
else if (event == nicInfo->NicChangeEvent)
{
XsLogMsg("NICs changed");
nicInfo->Refresh();
XenstoreKickXapi();
XsLogMsg("Handled NIC change");
nicInfo->Prime();
}
else if (event == suspendEvent)
{
XsLogMsg("Suspend event");
finishSuspend();
refreshStoreData(wmi, nicInfo, tsInfo, &features);
XsLogMsg("Handled suspend event");
}
else
{
for (x = 0; x < features.nr_features; x++) {
if (features.features[x].watch->event == event) {
XsLogMsg("fire feature %s", features.features[x].name);
features.features[x].handler(features.features[x].ctx);
XsLogMsg("fired feature %s",
features.features[x].name);
}
}
}
}
else
{
PrintError("WaitForMultipleObjects()");
break;
}
}
XsLogMsg("Guest agent finishing");
ReleaseWMIAccessor(wmi);
FinishClipboardSync();
delete tsInfo;
delete nicInfo;
ServiceControlManagerUpdate(0, SERVICE_STOPPED);
if (SLC_API != NULL)
FreeLibrary(SLC_API);
if (SLWGA_API != NULL)
FreeLibrary(SLWGA_API);
XsLogMsg("Guest agent finished");
}
// Service initialization
bool ServiceInit()
{
ServiceStatus.dwServiceType = SERVICE_WIN32;
ServiceStatus.dwCurrentState = SERVICE_START_PENDING;
ServiceStatus.dwControlsAccepted = SERVICE_ACCEPT_STOP | SERVICE_ACCEPT_SHUTDOWN;
ServiceStatus.dwWin32ExitCode = 0;
ServiceStatus.dwServiceSpecificExitCode = 0;
ServiceStatus.dwCheckPoint = 0;
ServiceStatus.dwWaitHint = 0;
hStatus = RegisterServiceCtrlHandler(
"XenService",
(LPHANDLER_FUNCTION)ServiceControlHandler);
if (hStatus == (SERVICE_STATUS_HANDLE)0)
{
// Registering Control Handler failed
DBGPRINT(("XenSvc: Registering service control handler failed - %d\n", GetLastError()));
return false;
}
ServiceStatus.dwCurrentState = SERVICE_RUNNING;
SetServiceStatus (hStatus, &ServiceStatus);
return true;
}
void ServiceMain(int argc, char** argv)
{
// Perform common initialization
hServiceExitEvent = CreateEvent(NULL, false, false, NULL);
if (hServiceExitEvent == NULL)
{
DBGPRINT(("XenSvc: Unable to create the event obj - %d\n", GetLastError()));
return;
}
if (!ServiceInit())
{
DBGPRINT(("XenSvc: Unable to init xenservice\n"));
return;
}
XsInitPerThreadLogging();
InitXSAccessor();
XsLog("Guest agent service starting");
__try
{
Run();
}
__except(XsDumpLogThisThread(), EXCEPTION_CONTINUE_SEARCH)
{
}
XsLog("Guest agent service stopped");
ShutdownXSAccessor();
return;
}
void ServiceControlManagerUpdate(DWORD dwExitCode, DWORD dwState)
{
ServiceStatus.dwWin32ExitCode = dwExitCode;
ServiceStatus.dwCurrentState = dwState;
SetServiceStatus (hStatus, &ServiceStatus);
}
// Service control handler function
void ServiceControlHandler(DWORD request)
{
switch(request)
{
case SERVICE_CONTROL_STOP:
DBGPRINT(("XenSvc: xenservice stopped.\n"));
ServiceControlManagerUpdate(0, SERVICE_STOP_PENDING);
SetEvent(hServiceExitEvent);
return;
case SERVICE_CONTROL_SHUTDOWN:
DBGPRINT(("XenSvc: xenservice shutdown.\n"));
ServiceControlManagerUpdate(0, SERVICE_STOP_PENDING);
SetEvent(hServiceExitEvent);
return;
default:
DBGPRINT(("XenSvc: unknown request."));
break;
}
return;
}
| 29.339355 | 112 | 0.566057 | [
"object"
] |
a168a2539cf6099ee1a2df82960974d9f5246e75 | 1,520 | cpp | C++ | eip/src/v2/model/ListBandwidthsResponse.cpp | yangzhaofeng/huaweicloud-sdk-cpp-v3 | 4f3caac5ba9a9b75b4e5fd61683d1c4d57ec1c23 | [
"Apache-2.0"
] | 5 | 2021-03-03T08:23:43.000Z | 2022-02-16T02:16:39.000Z | eip/src/v2/model/ListBandwidthsResponse.cpp | yangzhaofeng/huaweicloud-sdk-cpp-v3 | 4f3caac5ba9a9b75b4e5fd61683d1c4d57ec1c23 | [
"Apache-2.0"
] | null | null | null | eip/src/v2/model/ListBandwidthsResponse.cpp | yangzhaofeng/huaweicloud-sdk-cpp-v3 | 4f3caac5ba9a9b75b4e5fd61683d1c4d57ec1c23 | [
"Apache-2.0"
] | 7 | 2021-02-26T13:53:35.000Z | 2022-03-18T02:36:43.000Z |
#include "huaweicloud/eip/v2/model/ListBandwidthsResponse.h"
namespace HuaweiCloud {
namespace Sdk {
namespace Eip {
namespace V2 {
namespace Model {
ListBandwidthsResponse::ListBandwidthsResponse()
{
bandwidthsIsSet_ = false;
}
ListBandwidthsResponse::~ListBandwidthsResponse() = default;
void ListBandwidthsResponse::validate()
{
}
web::json::value ListBandwidthsResponse::toJson() const
{
web::json::value val = web::json::value::object();
if(bandwidthsIsSet_) {
val[utility::conversions::to_string_t("bandwidths")] = ModelBase::toJson(bandwidths_);
}
return val;
}
bool ListBandwidthsResponse::fromJson(const web::json::value& val)
{
bool ok = true;
if(val.has_field(utility::conversions::to_string_t("bandwidths"))) {
const web::json::value& fieldValue = val.at(utility::conversions::to_string_t("bandwidths"));
if(!fieldValue.is_null())
{
std::vector<BandwidthResp> refVal;
ok &= ModelBase::fromJson(fieldValue, refVal);
setBandwidths(refVal);
}
}
return ok;
}
std::vector<BandwidthResp>& ListBandwidthsResponse::getBandwidths()
{
return bandwidths_;
}
void ListBandwidthsResponse::setBandwidths(const std::vector<BandwidthResp>& value)
{
bandwidths_ = value;
bandwidthsIsSet_ = true;
}
bool ListBandwidthsResponse::bandwidthsIsSet() const
{
return bandwidthsIsSet_;
}
void ListBandwidthsResponse::unsetbandwidths()
{
bandwidthsIsSet_ = false;
}
}
}
}
}
}
| 18.765432 | 101 | 0.691447 | [
"object",
"vector",
"model"
] |
a16cb52b2326590a784bfd9286fd4372a178725a | 23,672 | cpp | C++ | ddbp-sycl/main.cpp | BeauJoh/HeCBench | 594b845171d686dc951971ce36ed59cf114dd2b4 | [
"BSD-3-Clause"
] | 58 | 2020-08-06T18:53:44.000Z | 2021-10-01T07:59:46.000Z | ddbp-sycl/main.cpp | BeauJoh/HeCBench | 594b845171d686dc951971ce36ed59cf114dd2b4 | [
"BSD-3-Clause"
] | 2 | 2020-12-04T12:35:02.000Z | 2021-03-04T22:49:25.000Z | ddbp-sycl/main.cpp | BeauJoh/HeCBench | 594b845171d686dc951971ce36ed59cf114dd2b4 | [
"BSD-3-Clause"
] | 13 | 2020-08-19T13:44:18.000Z | 2021-09-08T04:25:34.000Z | /*
This function reconstruct the 3D volume from projections, based on
the Distance-Driven principle. It works by calculating the overlap
in X and Y axis of the volume and the detector boundaries.
The geometry is for DBT with half cone-beam. All parameters are set
in "ParameterSettings" code.
Reference:
- Branchless Distance Driven Projection and Backprojection,
Samit Basu and Bruno De Man (2006)
- GPU Acceleration of Branchless Distance Driven Projection and
Backprojection, Liu et al (2016)
- GPU-Based Branchless Distance-Driven Projection and Backprojection,
Liu et al (2017)
- A GPU Implementation of Distance-Driven Computed Tomography,
Ryan D. Wagner (2017)
---------------------------------------------------------------------
Copyright (C) <2019> <Rodrigo de Barros Vimieiro>
This program is free software: you can redistribute it and/or modify
it under the terms of the GNU General Public License as published by
the Free Software Foundation, either version 3 of the License, or
(at your option) any later version.
This program is distributed in the hope that it will be useful,
but WITHOUT ANY WARRANTY; without even the implied warranty of
MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
GNU General Public License 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/>.
Original author: Rodrigo de Barros Vimieiro
*/
#include <stdio.h>
#include <stdlib.h>
#include <math.h>
#include "common.h"
// thread block size
#define BLOCK_SIZE 256
// integration direction
#define integrateXcoord 1
#define integrateYcoord 0
void pad_projections_kernel(
nd_item<3> &item,
double* d_img,
const int nDetXMap,
const int nDetYMap,
const int nElem,
const int np)
{
const int gid = item.get_global_id(2);
if (gid < nElem)
d_img[(np*nDetYMap *nDetXMap) + (gid*nDetYMap)] = 0;
}
void map_boudaries_kernel(
nd_item<3> &item,
double* d_pBound,
const int nElem,
const double valueLeftBound,
const double sizeElem,
const double offset)
{
const int gid = item.get_global_id(2);
if (gid < nElem)
d_pBound[gid] = (gid - valueLeftBound) * sizeElem + offset;
}
void rot_detector_kernel(
nd_item<3> &item,
double* __restrict d_pRdetY,
double* __restrict d_pRdetZ,
const double* __restrict d_pYcoord,
const double* __restrict d_pZcoord,
const double yOffset,
const double zOffset,
const double phi,
const int nElem)
{
const int gid = item.get_global_id(2);
if (gid < nElem) {
// cos and sin are in measured in radians.
d_pRdetY[gid] = ((d_pYcoord[gid] - yOffset) * sycl::cos(phi) -
(d_pZcoord[gid] - zOffset) * sycl::sin(phi)) + yOffset;
d_pRdetZ[gid] = ((d_pYcoord[gid] - yOffset) * sycl::sin(phi) +
(d_pZcoord[gid] - zOffset) * sycl::cos(phi)) + zOffset;
}
}
void mapDet2Slice_kernel(
nd_item<3> &item,
double* __restrict const pXmapp,
double* __restrict const pYmapp,
double tubeX,
double tubeY,
double tubeZ,
const double* __restrict const pXcoord,
const double* __restrict const pYcoord,
const double* __restrict const pZcoord,
const double* __restrict const pZSlicecoord,
const int nDetXMap,
const int nDetYMap,
const int nz)
{
const int px = item.get_global_id(2);
const int py = item.get_global_id(1);
if (px < nDetYMap && py < nDetXMap) {
const int pos = py * nDetYMap + px;
pXmapp[pos] = ((pXcoord[py] - tubeX)*(pZSlicecoord[nz] - pZcoord[px]) -
(pXcoord[py] * tubeZ) + (pXcoord[py] * pZcoord[px])) / (-tubeZ + pZcoord[px]);
if (py == 0)
pYmapp[px] = ((pYcoord[px] - tubeY)*(pZSlicecoord[nz] - pZcoord[px]) -
(pYcoord[px] * tubeZ) + (pYcoord[px] * pZcoord[px])) / (-tubeZ + pZcoord[px]);
}
}
void img_integration_kernel(
nd_item<3> &item,
double* d_img,
const int nPixX,
const int nPixY,
const bool direction,
const int offsetX,
const int offsetY,
const int nSlices)
{
/*
Integration of 2D slices over the whole volume
(S.1.Integration. - Liu et al(2017))
Perform an inclusive scan
*/
const int tx = item.get_global_id(2);
const int ty = item.get_global_id(1);
const int px = tx + offsetX;
const int py = ty + offsetY;
const int pz = item.get_global_id(0);
if (px >= nPixY || py >= nPixX || pz >= nSlices) return;
if (direction == integrateXcoord) {
for (int s = 1; s <= item.get_local_range(1); s *= 2) {
int spot = ty - s;
double val = 0;
if (spot >= 0) {
val = d_img[(pz*nPixY*nPixX) + (offsetY + spot) * nPixY + px];
}
if (spot >= 0) {
d_img[(pz*nPixY*nPixX) + (py * nPixY) + px] += val;
}
}
}
else
{
for (int s = 1; s <= item.get_local_range(2); s *= 2) {
int spot = tx - s;
double val = 0;
if (spot >= 0) {
val = d_img[(pz*nPixY*nPixX) + py * nPixY + spot + offsetX];
}
if (spot >= 0) {
d_img[(pz*nPixY*nPixX) + (py * nPixY) + px] += val;
}
}
}
}
void bilinear_interpolation_kernel(
nd_item<3> &item,
double* __restrict d_sliceI,
const double* __restrict d_pProj,
const double* __restrict d_pObjX,
const double* __restrict d_pObjY,
const double* __restrict d_pDetmX,
const double* __restrict d_pDetmY,
const int nPixXMap,
const int nPixYMap,
const int nDetXMap,
const int nDetYMap,
const int nDetX,
const int nDetY,
const int np)
{
const int px = item.get_global_id(2);
const int py = item.get_global_id(1);
// Make sure we don't try and access memory outside the detector
// by having any threads mapped there return early
if (px >= nPixYMap || py >= nPixXMap) return;
// S.2. Interpolation - Liu et al (2017)
// Adjust the mapped coordinates to cross the range of (0-nDetX).*duMap
// Divide by pixelSize to get a unitary pixel size
const double xNormData = nDetX - d_pObjX[py] / d_pDetmX[0];
const int xData = sycl::floor(xNormData);
const double alpha = xNormData - xData;
// Adjust the mapped coordinates to cross the range of (0-nDetY).*dyMap
// Divide by pixelSize to get a unitary pixel size
const double yNormData = (d_pObjY[px] / d_pDetmX[0]) - (d_pDetmY[0] / d_pDetmX[0]);
const int yData = sycl::floor(yNormData);
const double beta = yNormData - yData;
double d00, d01, d10, d11;
if (((xNormData) >= 0) && ((xNormData) <= nDetX) && ((yNormData) >= 0) && ((yNormData) <= nDetY))
d00 = d_pProj[(np*nDetYMap*nDetXMap) + (xData*nDetYMap + yData)];
else
d00 = 0.0;
if (((xData + 1) > 0) && ((xData + 1) <= nDetX) && ((yNormData) >= 0) && ((yNormData) <= nDetY))
d10 = d_pProj[(np*nDetYMap*nDetXMap) + ((xData + 1)*nDetYMap + yData)];
else
d10 = 0.0;
if (((xNormData) >= 0) && ((xNormData) <= nDetX) && ((yData + 1) > 0) && ((yData + 1) <= nDetY))
d01 = d_pProj[(np*nDetYMap*nDetXMap) + (xData*nDetYMap + yData + 1)];
else
d01 = 0.0;
if (((xData + 1) > 0) && ((xData + 1) <= nDetX) && ((yData + 1) > 0) && ((yData + 1) <= nDetY))
d11 = d_pProj[(np*nDetYMap*nDetXMap) + ((xData + 1)*nDetYMap + yData + 1)];
else
d11 = 0.0;
double result_temp1 = alpha * d10 + (-d00 * alpha + d00);
double result_temp2 = alpha * d11 + (-d01 * alpha + d01);
d_sliceI[py * nPixYMap + px] = beta * result_temp2 + (-result_temp1 * beta + result_temp1);
}
void differentiation_kernel(
nd_item<3> &item,
double* __restrict d_pVolume,
const double* __restrict d_sliceI,
double tubeX,
double rtubeY,
double rtubeZ,
const double* __restrict const d_pObjX,
const double* __restrict const d_pObjY,
const double* __restrict const d_pObjZ,
const int nPixX,
const int nPixY,
const int nPixXMap,
const int nPixYMap,
const double du,
const double dv,
const double dx,
const double dy,
const double dz,
const int nz)
{
const int px = item.get_global_id(2);
const int py = item.get_global_id(1);
/*
S.3. Differentiation - Eq. 24 - Liu et al (2017)
Detector integral projection
___________
|_A_|_B_|___|
|_C_|_D_|___|
|___|___|___|
(px,py)
________________
|_A_|__B__|_____|
|_C_|(0,0)|(0,1)|
|___|(1,0)|(1,1)|
Threads are lauched from D up to nPixX (py) and nPixY (px)
i.e., they are running on the detector image. Thread (0,0) is on D.
Coordinates on intergal projection:
A = py * nPixYMap + px
B = ((py+1) * nPixYMap) + px
C = py * nPixYMap + px + 1
D = ((py+1) * nPixYMap) + px + 1
*/
if (px < nPixY && py < nPixX) {
const int pos = (nPixX*nPixY*nz) + (py * nPixY) + px;
int coordA = py * nPixYMap + px;
int coordB = ((py + 1) * nPixYMap) + px;
int coordC = coordA + 1;
int coordD = coordB + 1;
// x - ray angle in X coord
double gamma = sycl::atan((d_pObjX[py] + (dx / 2.0) - tubeX) / (rtubeZ - d_pObjZ[nz]));
// x - ray angle in Y coord
double alpha = sycl::atan((d_pObjY[px] + (dy / 2.0) - rtubeY) / (rtubeZ - d_pObjZ[nz]));
double dA, dB, dC, dD;
dA = d_sliceI[coordA];
dB = d_sliceI[coordB];
dC = d_sliceI[coordC];
dD = d_sliceI[coordD];
// Treat border of interpolated integral detector
if (dC == 0 && dD == 0) {
dC = dA;
dD = dB;
}
// S.3.Differentiation - Eq. 24 - Liu et al(2017)
d_pVolume[pos] += ((dD - dC - dB + dA)*(du*dv*dz /
(sycl::cos(alpha)*sycl::cos(gamma)*dx*dy)));
}
}
void division_kernel(
nd_item<3> &item,
double* d_img,
const int nPixX,
const int nPixY,
const int nSlices,
const int nProj)
{
const int px = item.get_global_id(2);
const int py = item.get_global_id(1);
const int pz = item.get_global_id(0);
if (px < nPixY && py < nPixX && pz < nSlices) {
const int pos = (nPixX*nPixY*pz) + (py * nPixY) + px;
d_img[pos] /= (double) nProj;
}
}
// Branchless distance-driven backprojection
void backprojectionDDb(
double* const h_pVolume,
const double* const h_pProj,
const double* const h_pTubeAngle,
const double* const h_pDetAngle,
const int idXProj,
const int nProj,
const int nPixX,
const int nPixY,
const int nSlices,
const int nDetX,
const int nDetY,
const double dx,
const double dy,
const double dz,
const double du,
const double dv,
const double DSD,
const double DDR,
const double DAG)
{
// Number of mapped detectors
const int nDetXMap = nDetX + 1;
const int nDetYMap = nDetY + 1;
// Number of mapped pixels
const int nPixXMap = nPixX + 1;
const int nPixYMap = nPixY + 1;
#ifdef USE_GPU
gpu_selector dev_sel;
#else
cpu_selector dev_sel;
#endif
queue q(dev_sel);
buffer<double, 1> d_pProj (nDetXMap*nDetYMap*nProj);
buffer<double, 1> d_sliceI (nPixXMap*nPixYMap);
buffer<double, 1> d_pVolume (h_pVolume, nPixX*nPixY*nSlices);
// Will reuse grid configurations
range<3> gws (1,1,1);
range<3> lws (1,1,1);
const int maxThreadsPerBlock = BLOCK_SIZE;
// Copy projection data padding with zeros for image integation
// Initialize first column and row with zeros
const double* h_pProj_tmp;
lws[2] = maxThreadsPerBlock;
gws[2] = (nDetXMap / maxThreadsPerBlock + 1) * maxThreadsPerBlock;
for (int np = 0; np < nProj; np++) {
// Pad on X coord direction
q.submit([&] (handler &cgh) {
auto proj = d_pProj.get_access<sycl_write>(cgh);
cgh.parallel_for<class pad>(nd_range<3>(gws, lws), [=] (nd_item<3> item) {
pad_projections_kernel (item, proj.get_pointer(),
nDetXMap, nDetYMap, nDetXMap, np);
});
});
// Pad on Y coord direction
q.submit([&] (handler &cgh) {
auto acc = d_pProj.get_access<sycl_write>(cgh, nPixY, (nDetXMap*nDetYMap*np) + 1);
cgh.fill(acc, 0.0);
});
}
// Copy projections data from host to device
for (int np = 0; np < nProj; np++)
for (int c = 0; c < nDetX; c++) {
h_pProj_tmp = h_pProj + (c * nDetY) + (nDetX*nDetY*np);
q.submit([&] (handler &cgh) {
auto acc = d_pProj.get_access<sycl_write>(cgh, nDetY,
(c + 1) * nDetYMap + 1 + nDetXMap*nDetYMap*np);
cgh.copy(h_pProj_tmp, acc);
});
}
// device memory for projections coordinates
buffer<double, 1> d_pDetX ( nDetXMap );
buffer<double, 1> d_pDetY ( nDetYMap );
buffer<double, 1> d_pDetZ ( nDetYMap );
buffer<double, 1> d_pObjX ( nPixXMap );
buffer<double, 1> d_pObjY ( nPixYMap );
buffer<double, 1> d_pObjZ ( nSlices );
// device memory for mapped coordinates
buffer<double, 1> d_pDetmY ( nDetYMap );
buffer<double, 1> d_pDetmX ( nDetYMap * nDetXMap );
// device memory for rotated detector coords
buffer<double, 1> d_pRdetY ( nDetYMap );
buffer<double, 1> d_pRdetZ ( nDetYMap );
// Generate detector and object boudaries
lws[2] = maxThreadsPerBlock;
gws[2] = (nDetX / maxThreadsPerBlock + 1) * maxThreadsPerBlock;
q.submit([&] (handler &cgh) {
auto detX = d_pDetX.get_access<sycl_write>(cgh);
cgh.parallel_for<class map_detX>(nd_range<3>(gws, lws), [=] (nd_item<3> item) {
map_boudaries_kernel(item, detX.get_pointer(), nDetXMap, (double)nDetX, -du, 0.0);
});
});
gws[2] = (nDetY / maxThreadsPerBlock + 1) * maxThreadsPerBlock;
q.submit([&] (handler &cgh) {
auto detY = d_pDetY.get_access<sycl_write>(cgh);
cgh.parallel_for<class map_detY>(nd_range<3>(gws, lws), [=] (nd_item<3> item) {
map_boudaries_kernel(item, detY.get_pointer(), nDetYMap, nDetY / 2.0, dv, 0.0);
});
});
gws[2] = (nPixX / maxThreadsPerBlock + 1) * maxThreadsPerBlock;
q.submit([&] (handler &cgh) {
auto objX = d_pObjX.get_access<sycl_write>(cgh);
cgh.parallel_for<class map_pixX>(nd_range<3>(gws, lws), [=] (nd_item<3> item) {
map_boudaries_kernel(item, objX.get_pointer(), nPixXMap, (double)nPixX, -dx, 0.0);
});
});
gws[2] = (nPixY / maxThreadsPerBlock + 1) * maxThreadsPerBlock;
q.submit([&] (handler &cgh) {
auto objY = d_pObjY.get_access<sycl_write>(cgh);
cgh.parallel_for<class map_pixY>(nd_range<3>(gws, lws), [=] (nd_item<3> item) {
map_boudaries_kernel(item, objY.get_pointer(), nPixYMap, nPixY / 2.0, dy, 0.0);
});
});
gws[2] = (nSlices / maxThreadsPerBlock + 1) * maxThreadsPerBlock;
q.submit([&] (handler &cgh) {
auto objZ = d_pObjZ.get_access<sycl_write>(cgh);
cgh.parallel_for<class map_pixZ>(nd_range<3>(gws, lws), [=] (nd_item<3> item) {
map_boudaries_kernel(item, objZ.get_pointer(), nSlices, 0.0, dz, DAG + (dz / 2.0));
});
});
// Initiate variables value with 0
q.submit([&] (handler &cgh) {
auto acc = d_pDetZ.get_access<sycl_discard_write>(cgh);
cgh.fill(acc, 0.0);
});
q.submit([&] (handler &cgh) {
auto acc = d_pVolume.get_access<sycl_discard_write>(cgh);
cgh.fill(acc, 0.0);
});
// X - ray tube initial position
double tubeX = 0;
double tubeY = 0;
double tubeZ = DSD;
// Iso - center position
double isoY = 0;
double isoZ = DDR;
// Integration of 2D projection over the whole projections
// (S.1.Integration. - Liu et al(2017))
// Naive integration o the X coord
lws[2] = 8;
lws[1] = 4;
lws[0] = 8;
gws[2] = 8 * (int)ceilf((float)nDetYMap / (8 - 1));
gws[1] = 4;
gws[0] = 8 * (int)ceilf((float)nProj / 8);
int Xk = (int)ceilf((float)nDetXMap / (8 - 1));
for (int k = 0; k < Xk; k++) {
q.submit([&] (handler &cgh) {
auto proj = d_pProj.get_access<sycl_read_write>(cgh);
cgh.parallel_for<class img_integralX>(nd_range<3>(gws, lws), [=] (nd_item<3> item) {
img_integration_kernel(item, proj.get_pointer(),
nDetXMap, nDetYMap, integrateXcoord, 0, k * 9, nProj);
});
});
}
// Naive integration o the Y coord
lws[2] = 4;
lws[1] = 8;
lws[0] = 8;
gws[2] = 4;
gws[1] = 8 * (int)ceilf((float)nDetXMap / (8 - 1));
gws[0] = 8 * (int)ceilf((float)nProj / 8);
int Yk = (int)ceilf((float)nDetYMap / (8 - 1));
for (int k = 0; k < Yk; k++) {
q.submit([&] (handler &cgh) {
auto proj = d_pProj.get_access<sycl_read_write>(cgh);
cgh.parallel_for<class img_integralY>(nd_range<3>(gws, lws), [=] (nd_item<3> item) {
img_integration_kernel(item, proj.get_pointer(),
nDetXMap, nDetYMap, integrateYcoord, k * 9, 0, nProj);
});
});
}
// loop over all projections ?
int projIni, projEnd, nProj2Run;
if (idXProj == -1) {
projIni = 0;
projEnd = nProj;
nProj2Run = nProj;
}
else {
projIni = idXProj;
projEnd = idXProj + 1;
nProj2Run = 1;
}
// For each projection
for (int p = projIni; p < projEnd; p++) {
// Get specif tube angle for the projection
double theta = h_pTubeAngle[p] * M_PI / 180.0;
// Get specif detector angle for the projection
double phi = h_pDetAngle[p] * M_PI / 180.0;
//printf("Tube angle:%f Det angle:%f\n", theta, phi);
// Tube rotation
double rtubeY = ((tubeY - isoY)*cos(theta) - (tubeZ - isoZ)*sin(theta)) + isoY;
double rtubeZ = ((tubeY - isoY)*sin(theta) + (tubeZ - isoZ)*cos(theta)) + isoZ;
//printf("R tube Y:%f R tube Z:%f\n", rtubeY, rtubeZ);
// Detector rotation
lws[2] = maxThreadsPerBlock;
lws[1] = 1;
lws[0] = 1;
gws[2] = (nDetYMap / maxThreadsPerBlock + 1) * maxThreadsPerBlock;
gws[1] = 1;
gws[0] = 1;
q.submit([&] (handler &cgh) {
auto RdetY = d_pRdetY.get_access<sycl_discard_write>(cgh);
auto RdetZ = d_pRdetZ.get_access<sycl_discard_write>(cgh);
auto DetY = d_pDetY.get_access<sycl_read>(cgh);
auto DetZ = d_pDetZ.get_access<sycl_read>(cgh);
cgh.parallel_for<class rot_det>(nd_range<3>(gws, lws), [=] (nd_item<3> item) {
rot_detector_kernel(item, RdetY.get_pointer(), RdetZ.get_pointer(),
DetY.get_pointer(), DetZ.get_pointer(),
isoY, isoZ, phi, nDetYMap);
});
});
lws[2] = 16;
lws[1] = 16;
lws[0] = 1;
// For each slice
for (int nz = 0; nz < nSlices; nz++) {
// Map detector onto XY plane(Inside proj loop in case detector rotates)
gws[2] = (nDetYMap / 16 + 1) * 16;
gws[1] = (nDetXMap / 16 + 1) * 16;
gws[0] = 1;
q.submit([&] (handler &cgh) {
auto DetmX = d_pDetmX.get_access<sycl_discard_write>(cgh);
auto DetmY = d_pDetmY.get_access<sycl_discard_write>(cgh);
auto DetX = d_pDetX.get_access<sycl_read>(cgh);
auto RdetY = d_pRdetY.get_access<sycl_read>(cgh);
auto RdetZ = d_pRdetZ.get_access<sycl_read>(cgh);
auto ObjZ = d_pObjZ.get_access<sycl_read>(cgh);
cgh.parallel_for<class mapDet2Slice>(nd_range<3>(gws, lws), [=] (nd_item<3> item) {
mapDet2Slice_kernel (
item,
DetmX.get_pointer(), DetmY.get_pointer(), tubeX, rtubeY, rtubeZ,
DetX.get_pointer(), RdetY.get_pointer(), RdetZ.get_pointer(),
ObjZ.get_pointer(), nDetXMap, nDetYMap, nz);
});
});
// S.2. Interpolation - Liu et al (2017)
gws[2] = (nPixYMap / 16 + 1) * 16;
gws[1] = (nPixXMap / 16 + 1) * 16;
q.submit([&] (handler &cgh) {
auto sliceI = d_sliceI.get_access<sycl_discard_write>(cgh);
auto Proj = d_pProj.get_access<sycl_read>(cgh);
auto ObjX = d_pObjX.get_access<sycl_read>(cgh);
auto ObjY = d_pObjY.get_access<sycl_read>(cgh);
auto DetmX = d_pDetmX.get_access<sycl_read>(cgh);
auto DetmY = d_pDetmY.get_access<sycl_read>(cgh);
cgh.parallel_for<class bilinear_interp>(nd_range<3>(gws, lws), [=] (nd_item<3> item) {
bilinear_interpolation_kernel (item,
sliceI.get_pointer(), Proj.get_pointer(),
ObjX.get_pointer(), ObjY.get_pointer(),
DetmX.get_pointer() + nDetYMap * (nDetXMap-2), DetmY.get_pointer(),
nPixXMap, nPixYMap, nDetXMap, nDetYMap, nDetX, nDetY, p);
});
});
// S.3. Differentiation - Eq. 24 - Liu et al (2017)
gws[2] = (nPixY / 16 + 1) * 16;
gws[1] = (nPixX / 16 + 1) * 16;
q.submit([&] (handler &cgh) {
auto volume = d_pVolume.get_access<sycl_read_write>(cgh);
auto sliceI = d_sliceI.get_access<sycl_read>(cgh);
auto ObjX = d_pObjX.get_access<sycl_read>(cgh);
auto ObjY = d_pObjY.get_access<sycl_read>(cgh);
auto ObjZ = d_pObjZ.get_access<sycl_read>(cgh);
cgh.parallel_for<class diff>(nd_range<3>(gws, lws), [=] (nd_item<3> item) {
differentiation_kernel (
item, volume.get_pointer(), sliceI.get_pointer(),
tubeX, rtubeY, rtubeZ,
ObjX.get_pointer(), ObjY.get_pointer(), ObjZ.get_pointer(),
nPixX, nPixY, nPixXMap, nPixYMap, du, dv, dx, dy, dz, nz);
});
});
} // Loop end slices
} // Loop end Projections
// Normalize volume dividing by the number of projections
lws[2] = 8;
lws[1] = 8;
lws[0] = 4;
gws[2] = (nPixY / 8 + 1) * 8;
gws[1] = (nPixX / 8 + 1) * 8;
gws[0] = (nSlices / 4 + 1) * 4;
q.submit([&] (handler &cgh) {
auto volume = d_pVolume.get_access<sycl_read_write>(cgh);
cgh.parallel_for<class div>(nd_range<3>(gws, lws), [=] (nd_item<3> item) {
division_kernel (item, volume.get_pointer(),
nPixX, nPixY, nSlices, nProj2Run);
});
});
}
int main()
{
// image voxel density
const int nPixX = 1996; // number of voxels
const int nPixY = 2457; // number of voxels
const int nSlices = 78;
// detector panel pixel density
const int nDetX = 1664; // number of pixels
const int nDetY = 2048; // number of pixels
const int nProj = 15; // number of projections
const int idXProj = -1; // loop over all projections
const double dx = 0.112; // single voxel size (mm)
const double dy = 0.112;
const double dz = 1.0;
const double du = 0.14; // single detector size (mm)
const double dv = 0.14;
const double DSD = 700; // distance from source to detector (mm)
const double DDR = 0.0; // distance from detector to pivot (mm)
const double DAG = 25.0; // distance of air gap (mm)
const size_t pixVol = nPixX * nPixY * nSlices;
const size_t detVol = nDetX * nDetY * nProj;
double *h_pVolume = (double*) malloc (pixVol * sizeof(double));
double *h_pProj = (double*) malloc (detVol * sizeof(double));
double *h_pTubeAngle = (double*) malloc (nProj * sizeof(double));
double *h_pDetAngle = (double*) malloc (nProj * sizeof(double));
// tube angles in degrees
for (int i = 0; i < nProj; i++)
h_pTubeAngle[i] = -7.5 + i * 15.0/nProj;
// detector angles in degrees
for (int i = 0; i < nProj; i++)
h_pDetAngle[i] = -2.1 + i * 4.2/nProj;
// random values
srand(123);
for (size_t i = 0; i < pixVol; i++)
h_pVolume[i] = (double)rand() / (double)RAND_MAX;
for (size_t i = 0; i < detVol; i++)
h_pProj[i] = (double)rand() / (double)RAND_MAX;
backprojectionDDb(
h_pVolume,
h_pProj,
h_pTubeAngle,
h_pDetAngle,
idXProj,
nProj,
nPixX, nPixY,
nSlices,
nDetX, nDetY,
dx, dy, dz,
du, dv,
DSD, DDR, DAG);
double checkSum = 0;
for (size_t i = 0; i < pixVol; i++)
checkSum += h_pVolume[i];
printf("checksum = %lf\n", checkSum);
free(h_pVolume);
free(h_pTubeAngle);
free(h_pDetAngle);
free(h_pProj);
return 0;
}
| 30.117048 | 100 | 0.611651 | [
"geometry",
"object",
"3d"
] |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.